2 * \file insetgraphics.C
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
15 * What advanced features the users want to do?
16 Implement them in a non latex dependent way, but a logical way.
17 LyX should translate it to latex or any other fitting format.
18 * Add a way to roll the image file into the file format.
19 * When loading, if the image is not found in the expected place, try
20 to find it in the clipart, or in the same directory with the image.
21 * The image choosing dialog could show thumbnails of the image formats
22 it knows of, thus selection based on the image instead of based on
24 * Add support for the 'picins' package.
25 * Add support for the 'picinpar' package.
26 * Improve support for 'subfigure' - Allow to set the various options
32 * The filename is kept in the lyx file in a relative way, so as to allow
33 * moving the document file and its images with no problem.
37 * Postscript output means EPS figures.
39 * PDF output is best done with PDF figures if it's a direct conversion
40 * or PNG figures otherwise.
52 #include "insets/insetgraphics.h"
53 #include "insets/render_graphic.h"
56 #include "BufferView.h"
57 #include "converter.h"
60 #include "dispatchresult.h"
62 #include "funcrequest.h"
64 #include "LaTeXFeatures.h"
67 #include "metricsinfo.h"
68 #include "outputparams.h"
70 #include "frontends/Alert.h"
71 #include "frontends/LyXView.h"
73 #include "support/filetools.h"
74 #include "support/lyxalgo.h" // lyx::count
75 #include "support/lyxlib.h" // float_equal
76 #include "support/os.h"
77 #include "support/systemcall.h"
78 #include "support/tostr.h"
79 #include "support/std_sstream.h"
81 #include <boost/bind.hpp>
82 #include <boost/tuple/tuple.hpp>
84 namespace support = lyx::support;
85 using lyx::support::AbsolutePath;
86 using lyx::support::bformat;
87 using lyx::support::ChangeExtension;
88 using lyx::support::contains;
89 using lyx::support::FileName;
90 using lyx::support::float_equal;
91 using lyx::support::GetExtension;
92 using lyx::support::getExtFromContents;
93 using lyx::support::IsFileReadable;
94 using lyx::support::LibFileSearch;
95 using lyx::support::rtrim;
96 using lyx::support::subst;
97 using lyx::support::Systemcall;
98 using lyx::support::unzipFile;
99 using lyx::support::unzippedFileName;
101 namespace os = lyx::support::os;
106 using std::istringstream;
108 using std::ostringstream;
113 ///////////////////////////////////////////////////////////////////////////
114 int const VersionNumber = 1;
115 ///////////////////////////////////////////////////////////////////////////
117 // This function is a utility function
118 // ... that should be with ChangeExtension ...
120 string const RemoveExtension(string const & filename)
122 return ChangeExtension(filename, string());
126 string const uniqueID()
128 static unsigned int seed = 1000;
129 return "graph" + tostr(++seed);
133 string findTargetFormat(string const & suffix, OutputParams const & runparams)
135 // Are we using latex or pdflatex).
136 if (runparams.flavor == OutputParams::PDFLATEX) {
137 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
138 if (contains(suffix, "ps") || suffix == "pdf")
140 if (suffix == "jpg") // pdflatex can use jpeg
142 return "png"; // and also png
144 // If it's postscript, we always do eps.
145 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
146 if (suffix != "ps") // any other than ps
147 return "eps"; // is changed to eps
148 return suffix; // let ps untouched
154 InsetGraphics::InsetGraphics()
155 : graphic_label(uniqueID()),
156 graphic_(new RenderGraphic(this))
160 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
162 boost::signals::trackable(),
163 graphic_label(uniqueID()),
164 graphic_(new RenderGraphic(*ig.graphic_, this))
166 setParams(ig.params());
170 auto_ptr<InsetBase> InsetGraphics::clone() const
172 return auto_ptr<InsetBase>(new InsetGraphics(*this));
176 InsetGraphics::~InsetGraphics()
178 InsetGraphicsMailer(*this).hideDialog();
182 void InsetGraphics::priv_dispatch(LCursor & cur, FuncRequest & cmd)
184 switch (cmd.action) {
185 case LFUN_GRAPHICS_EDIT: {
186 Buffer const & buffer = *cur.bv().buffer();
187 InsetGraphicsParams p;
188 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
189 editGraphics(p, buffer);
193 case LFUN_INSET_MODIFY: {
194 Buffer const & buffer = cur.buffer();
195 InsetGraphicsParams p;
196 InsetGraphicsMailer::string2params(cmd.argument, buffer, p);
197 if (!p.filename.empty()) {
204 case LFUN_INSET_DIALOG_UPDATE:
205 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
208 case LFUN_MOUSE_RELEASE:
209 InsetGraphicsMailer(*this).showDialog(&cur.bv());
213 InsetOld::priv_dispatch(cur, cmd);
219 void InsetGraphics::edit(LCursor & cur, bool)
221 InsetGraphicsMailer(*this).showDialog(&cur.bv());
225 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
227 graphic_->metrics(mi, dim);
232 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
234 setPosCache(pi, x, y);
235 graphic_->draw(pi, x, y);
239 InsetOld::EDITABLE InsetGraphics::editable() const
245 void InsetGraphics::write(Buffer const & buf, ostream & os) const
248 params().Write(os, buf.filePath());
252 void InsetGraphics::read(Buffer const & buf, LyXLex & lex)
254 string const token = lex.getString();
256 if (token == "Graphics")
257 readInsetGraphics(lex, buf.filePath());
259 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!" << endl;
261 graphic_->update(params().as_grfxParams());
265 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
267 bool finished = false;
269 while (lex.isOK() && !finished) {
272 string const token = lex.getString();
273 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
278 } else if (token == "\\end_inset") {
281 if (!params_.Read(lex, token, bufpath))
282 lyxerr << "Unknown token, " << token << ", skipping."
289 string const InsetGraphics::createLatexOptions() const
291 // Calculate the options part of the command, we must do it to a string
292 // stream since we might have a trailing comma that we would like to remove
293 // before writing it to the output stream.
294 ostringstream options;
295 if (!params().bb.empty())
296 options << " bb=" << rtrim(params().bb) << ",\n";
298 options << " draft,\n";
300 options << " clip,\n";
301 if (!float_equal(params().scale, 0.0, 0.05)) {
302 if (!float_equal(params().scale, 100.0, 0.05))
303 options << " scale=" << params().scale / 100.0
306 if (!params().width.zero())
307 options << " width=" << params().width.asLatexString() << ",\n";
308 if (!params().height.zero())
309 options << " height=" << params().height.asLatexString() << ",\n";
310 if (params().keepAspectRatio)
311 options << " keepaspectratio,\n";
314 // Make sure rotation angle is not very close to zero;
315 // a float can be effectively zero but not exactly zero.
316 if (!float_equal(params().rotateAngle, 0, 0.001)) {
317 options << " angle=" << params().rotateAngle << ",\n";
318 if (!params().rotateOrigin.empty()) {
319 options << " origin=" << params().rotateOrigin[0];
320 if (contains(params().rotateOrigin,"Top"))
322 else if (contains(params().rotateOrigin,"Bottom"))
324 else if (contains(params().rotateOrigin,"Baseline"))
330 if (!params().special.empty())
331 options << params().special << ",\n";
333 string opts = options.str();
335 return opts.substr(0, opts.size() - 2);
349 std::pair<CopyStatus, string> const
350 copyToDirIfNeeded(string const & file_in, string const & dir)
352 using support::rtrim;
354 BOOST_ASSERT(AbsolutePath(file_in));
356 string const only_path = support::OnlyPath(file_in);
357 if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
358 return std::make_pair(IDENTICAL_PATHS, file_in);
361 if (support::zippedFile(file_in)) {
362 string const ext = GetExtension(file_in);
363 string const unzipped = support::unzippedFileName(file_in);
364 mangled = FileName(unzipped).mangledFilename();
365 mangled += "." + ext;
367 mangled = FileName(file_in).mangledFilename();
369 string const file_out = support::MakeAbsPath(mangled, dir);
371 unsigned long const checksum_in = support::sum(file_in);
372 unsigned long const checksum_out = support::sum(file_out);
374 if (checksum_in == checksum_out)
376 return std::make_pair(IDENTICAL_CONTENTS, file_out);
378 bool const success = support::copy(file_in, file_out);
380 lyxerr[Debug::GRAPHICS]
381 << support::bformat(_("Could not copy the file\n%1$s\n"
382 "into the temporary directory."),
387 CopyStatus status = success ? SUCCESS : FAILURE;
388 return std::make_pair(status, file_out);
392 string const stripExtensionIfPossible(string const & file, string const & to)
394 // No conversion is needed. LaTeX can handle the graphic file as is.
395 // This is true even if the orig_file is compressed.
396 if (formats.getFormat(to)->extension() == GetExtension(file))
397 return RemoveExtension(file);
404 string const InsetGraphics::prepareFile(Buffer const & buf,
405 OutputParams const & runparams) const
407 string orig_file = params().filename.absFilename();
408 string const rel_file = params().filename.relFilename(buf.filePath());
410 // LaTeX can cope if the graphics file doesn't exist, so just return the
412 if (!IsFileReadable(orig_file)) {
413 lyxerr[Debug::GRAPHICS]
414 << "InsetGraphics::prepareFile\n"
415 << "No file '" << orig_file << "' can be found!" << endl;
419 // If the file is compressed and we have specified that it
420 // should not be uncompressed, then just return its name and
421 // let LaTeX do the rest!
422 bool const zipped = params().filename.isZipped();
424 if (zipped && params().noUnzip) {
425 lyxerr[Debug::GRAPHICS]
426 << "\tpass zipped file to LaTeX but with full path.\n";
427 // LaTeX needs an absolute path, otherwise the
428 // coresponding *.eps.bb file isn't found
432 // temp_file will contain the file for LaTeX to act on if, for example,
433 // we move it to a temp dir or uncompress it.
434 string temp_file = orig_file;
436 // We place all temporary files in the master buffer's temp dir.
437 // This is possible because we use mangled file names.
438 // This is necessary for DVI export.
439 string const temp_path = buf.getMasterBuffer()->temppath();
443 boost::tie(status, temp_file) =
444 copyToDirIfNeeded(orig_file, temp_path);
446 if (status == FAILURE)
449 orig_file = unzippedFileName(temp_file);
450 if (!IsFileReadable(orig_file)) {
451 unzipFile(temp_file);
452 lyxerr[Debug::GRAPHICS]
453 << "\tunzipped to " << orig_file << endl;
457 string const from = getExtFromContents(orig_file);
458 string const to = findTargetFormat(from, runparams);
459 lyxerr[Debug::GRAPHICS]
460 << "\t we have: from " << from << " to " << to << '\n';
462 // We're going to be running the exported buffer through the LaTeX
463 // compiler, so must ensure that LaTeX can cope with the graphics
466 lyxerr[Debug::GRAPHICS]
467 << "\tthe orig file is: " << orig_file << endl;
469 bool conversion_needed = true;
471 boost::tie(status, temp_file) =
472 copyToDirIfNeeded(orig_file, temp_path);
474 if (status == FAILURE)
476 else if (status == IDENTICAL_CONTENTS)
477 conversion_needed = false;
480 return stripExtensionIfPossible(temp_file, to);
482 string const to_file_base = RemoveExtension(temp_file);
483 string const to_file = ChangeExtension(to_file_base, to);
485 // Do we need to perform the conversion?
486 // Yes if to_file does not exist or if temp_file is newer than to_file
487 if (!conversion_needed ||
488 support::compare_timestamps(temp_file, to_file) < 0) {
489 lyxerr[Debug::GRAPHICS]
490 << bformat(_("No conversion of %1$s is needed after all"),
496 lyxerr[Debug::GRAPHICS]
497 << "\tThe original file is " << orig_file << "\n"
498 << "\tA copy has been made and convert is to be called with:\n"
499 << "\tfile to convert = " << temp_file << '\n'
500 << "\tto_file_base = " << to_file_base << '\n'
501 << "\t from " << from << " to " << to << '\n';
503 // if no special converter defined, then we take the default one
504 // from ImageMagic: convert from:inname.from to:outname.to
505 if (!converters.convert(&buf, temp_file, to_file_base, from, to)) {
506 string const command =
507 "sh " + LibFileSearch("scripts", "convertDefault.sh") +
508 ' ' + from + ':' + temp_file + ' ' +
509 to + ':' + to_file_base + '.' + to;
510 lyxerr[Debug::GRAPHICS]
511 << "No converter defined! I use convertDefault.sh:\n\t"
514 one.startscript(Systemcall::Wait, command);
515 if (!IsFileReadable(ChangeExtension(to_file_base, to))) {
516 string str = bformat(_("No information for converting %1$s "
517 "format files to %2$s.\n"
518 "Try defining a convertor in the preferences."), from, to);
519 Alert::error(_("Could not convert image"), str);
527 int InsetGraphics::latex(Buffer const & buf, ostream & os,
528 OutputParams const & runparams) const
530 // The master buffer. This is useful when there are multiple levels
532 Buffer const * m_buffer = buf.getMasterBuffer();
534 // If there is no file specified or not existing,
535 // just output a message about it in the latex output.
536 lyxerr[Debug::GRAPHICS]
537 << "insetgraphics::latex: Filename = "
538 << params().filename.absFilename() << endl;
540 string const relative_file =
541 params().filename.relFilename(buf.filePath());
543 // A missing (e)ps-extension is no problem for LaTeX, so
544 // we have to test three different cases
546 #warning uh, but can our cache handle it ? no.
548 string const file_ = params().filename.absFilename();
549 bool const file_exists =
551 (IsFileReadable(file_) || // original
552 IsFileReadable(file_ + ".eps") || // original.eps
553 IsFileReadable(file_ + ".ps")); // original.ps
554 string const message = file_exists ?
555 string() : string("bb = 0 0 200 100, draft, type=eps");
556 // if !message.empty() than there was no existing file
557 // "filename(.(e)ps)" found. In this case LaTeX
558 // draws only a rectangle with the above bb and the
559 // not found filename in it.
560 lyxerr[Debug::GRAPHICS]
561 << "\tMessage = \"" << message << '\"' << endl;
563 // These variables collect all the latex code that should be before and
564 // after the actual includegraphics command.
567 // Do we want subcaptions?
568 if (params().subcaption) {
569 before += "\\subfigure[" + params().subcaptionText + "]{";
572 // We never use the starred form, we use the "clip" option instead.
573 before += "\\includegraphics";
575 // Write the options if there are any.
576 string const opts = createLatexOptions();
577 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
579 if (!opts.empty() && !message.empty())
580 before += ("[%\n" + opts + ',' + message + ']');
581 else if (!opts.empty() || !message.empty())
582 before += ("[%\n" + opts + message + ']');
584 lyxerr[Debug::GRAPHICS]
585 << "\tBefore = " << before
586 << "\n\tafter = " << after << endl;
589 string latex_str = before + '{';
590 // "nice" means that the buffer is exported to LaTeX format but not
591 // run through the LaTeX compiler.
592 if (runparams.nice) {
593 // a relative filename should be relative to the master
595 string basename = params().filename.outputFilename(m_buffer->filePath());
596 // Remove the extension so the LaTeX will use whatever
597 // is appropriate (when there are several versions in
598 // different formats)
599 if (!(IsFileReadable(file_ + ".eps") || IsFileReadable(file_ + ".ps")))
600 basename = RemoveExtension(basename);
601 // This works only if the filename contains no dots besides
602 // the just removed one. We can fool here by replacing all
603 // dots with a macro whose definition is just a dot ;-)
604 latex_str += subst(basename, ".", "\\lyxdot ");
605 } else if (file_exists) {
606 // Make the filename relative to the lyx file
607 // and remove the extension so the LaTeX will use whatever
608 // is appropriate (when there are several versions in
609 // different formats)
610 latex_str += os::external_path(prepareFile(buf, runparams));
612 latex_str += relative_file + " not found!";
614 latex_str += '}' + after;
617 lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
618 << latex_str << endl;
619 // Return how many newlines we issued.
620 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
624 int InsetGraphics::plaintext(Buffer const &, ostream & os,
625 OutputParams const &) const
627 // No graphics in ascii output. Possible to use gifscii to convert
628 // images to ascii approximation.
629 // 1. Convert file to ascii using gifscii
630 // 2. Read ascii output file and add it to the output stream.
631 // at least we send the filename
632 os << '<' << bformat(_("Graphics file: %1$s"),
633 params().filename.absFilename()) << ">\n";
638 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
639 OutputParams const & runparams) const
641 string const file_name = runparams.nice ?
642 params().filename.relFilename(buf.filePath()):
643 params().filename.absFilename();
645 os << "<eps file=\"" << file_name << "\">\n";
646 os << "<img src=\"" << file_name << "\">";
651 // For explanation on inserting graphics into DocBook checkout:
652 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
653 // See also the docbook guide at http://www.docbook.org/
654 int InsetGraphics::docbook(Buffer const &, ostream & os,
655 OutputParams const &) const
657 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
658 // need to switch to MediaObject. However, for now this is sufficient and
660 os << "<graphic fileref=\"&" << graphic_label << ";\">";
665 void InsetGraphics::validate(LaTeXFeatures & features) const
667 // If we have no image, we should not require anything.
668 if (params().filename.empty())
671 features.includeFile(graphic_label,
672 RemoveExtension(params().filename.absFilename()));
674 features.require("graphicx");
676 if (features.nice()) {
677 Buffer const * m_buffer = features.buffer().getMasterBuffer();
679 params().filename.outputFilename(m_buffer->filePath());
680 string const file_ = params().filename.absFilename();
681 if (!(IsFileReadable(file_ + ".eps") || IsFileReadable(file_ + ".ps")))
682 basename = RemoveExtension(basename);
683 if (contains(basename, "."))
684 features.require("lyxdot");
687 if (params().subcaption)
688 features.require("subfigure");
692 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
694 // If nothing is changed, just return and say so.
695 if (params() == p && !p.filename.empty())
698 // Copy the new parameters.
701 // Update the display using the new parameters.
702 graphic_->update(params().as_grfxParams());
704 // We have changed data, report it.
709 InsetGraphicsParams const & InsetGraphics::params() const
715 void InsetGraphics::editGraphics(InsetGraphicsParams const & p, Buffer const & buffer) const
717 string const file_with_path = p.filename.absFilename();
718 formats.edit(buffer, file_with_path, getExtFromContents(file_with_path));
722 string const InsetGraphicsMailer::name_("graphics");
724 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
729 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
731 return params2string(inset_.params(), buffer);
735 void InsetGraphicsMailer::string2params(string const & in,
736 Buffer const & buffer,
737 InsetGraphicsParams & params)
739 params = InsetGraphicsParams();
743 istringstream data(in);
749 if (!lex || name != name_)
750 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
753 inset.readInsetGraphics(lex, buffer.filePath());
754 params = inset.params();
759 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
760 Buffer const & buffer)
763 data << name_ << ' ';
764 params.Write(data, buffer.filePath());
765 data << "\\end_inset\n";