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 * Current version is 1 (inset file format version), when changing it
33 * it should be changed in the Write() function when writing in one place
34 * and when reading one should change the version check and the error message.
35 * The filename is kept in the lyx file in a relative way, so as to allow
36 * moving the document file and its images with no problem.
40 * Postscript output means EPS figures.
42 * PDF output is best done with PDF figures if it's a direct conversion
43 * or PNG figures otherwise.
55 #include "insets/insetgraphics.h"
56 #include "insets/insetgraphicsParams.h"
58 #include "graphics/GraphicsLoader.h"
59 #include "graphics/GraphicsImage.h"
60 #include "graphics/GraphicsParams.h"
63 #include "dimension.h"
65 #include "BufferView.h"
66 #include "converter.h"
69 #include "funcrequest.h"
71 #include "LaTeXFeatures.h"
72 #include "latexrunparams.h"
76 #include "metricsinfo.h"
78 #include "frontends/lyx_gui.h"
79 #include "frontends/Alert.h"
80 #include "frontends/Dialogs.h"
81 #include "frontends/font_metrics.h"
82 #include "frontends/LyXView.h"
83 #include "frontends/Painter.h"
85 #include "support/LAssert.h"
86 #include "support/filetools.h"
87 #include "support/lyxalgo.h" // lyx::count
88 #include "support/lyxlib.h" // float_equal
89 #include "support/path.h"
90 #include "support/tostr.h"
91 #include "support/systemcall.h"
92 #include "support/os.h"
93 #include "support/lstrings.h"
95 #include <boost/weak_ptr.hpp>
96 #include <boost/bind.hpp>
97 #include <boost/signals/trackable.hpp>
99 #include <algorithm> // For the std::max
101 extern string system_tempdir;
110 ///////////////////////////////////////////////////////////////////////////
111 int const VersionNumber = 1;
112 ///////////////////////////////////////////////////////////////////////////
114 // This function is a utility function
115 // ... that should be with ChangeExtension ...
117 string const RemoveExtension(string const & filename)
119 return ChangeExtension(filename, string());
123 string const uniqueID()
125 static unsigned int seed = 1000;
126 return "graph" + tostr(++seed);
130 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
132 // Are we using latex or pdflatex).
133 if (runparams.flavor == LatexRunParams::PDFLATEX) {
134 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
135 if (contains(suffix, "ps") || suffix == "pdf")
137 if (suffix == "jpg") // pdflatex can use jpeg
139 return "png"; // and also png
141 // If it's postscript, we always do eps.
142 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
143 if (suffix != "ps") // any other than ps
144 return "eps"; // is changed to eps
145 return suffix; // let ps untouched
151 struct InsetGraphics::Cache : boost::signals::trackable
154 Cache(InsetGraphics &);
156 void update(string const & file_with_path);
163 unsigned long checksum;
165 boost::weak_ptr<BufferView> view;
169 InsetGraphics & parent_;
173 InsetGraphics::Cache::Cache(InsetGraphics & p)
174 : old_ascent(0), checksum(0), parent_(p)
176 loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
180 void InsetGraphics::Cache::update(string const & file_with_path)
182 lyx::Assert(!file_with_path.empty());
184 string const path = OnlyPath(file_with_path);
185 loader.reset(file_with_path, parent_.params().as_grfxParams(path));
189 InsetGraphics::InsetGraphics()
190 : graphic_label(uniqueID()),
191 cache_(new Cache(*this))
195 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
196 string const & filepath)
198 graphic_label(uniqueID()),
199 cache_(new Cache(*this))
201 setParams(ig.params(), filepath);
205 Inset * InsetGraphics::clone(Buffer const & buffer) const
207 return new InsetGraphics(*this, buffer.filePath());
211 InsetGraphics::~InsetGraphics()
213 InsetGraphicsMailer mailer(*this);
218 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
220 switch (cmd.action) {
221 case LFUN_INSET_MODIFY: {
222 InsetGraphicsParams p;
223 InsetGraphicsMailer::string2params(cmd.argument, p);
224 if (!p.filename.empty()) {
225 string const filepath = cmd.view()->buffer()->filePath();
226 setParams(p, filepath);
227 cmd.view()->updateInset(this);
232 case LFUN_INSET_DIALOG_UPDATE:
233 InsetGraphicsMailer(*this).updateDialog(cmd.view());
236 case LFUN_INSET_EDIT:
237 case LFUN_MOUSE_RELEASE:
238 InsetGraphicsMailer(*this).showDialog(cmd.view());
242 return Inset::localDispatch(cmd);
247 string const InsetGraphics::statusMessage() const
249 using namespace grfx;
251 switch (cache_->loader.status()) {
253 return _("Not shown.");
255 return _("Loading...");
257 return _("Converting to loadable format...");
259 return _("Loaded into memory. Must now generate pixmap.");
261 return _("Scaling etc...");
263 return _("Ready to display");
265 return _("No file found!");
266 case ErrorConverting:
267 return _("Error converting to loadable format");
269 return _("Error loading file into memory");
270 case ErrorGeneratingPixmap:
271 return _("Error generating the pixmap");
273 return _("No image");
279 bool InsetGraphics::imageIsDrawable() const
281 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
284 return cache_->loader.image()->isDrawable();
288 void InsetGraphics::dimension(BufferView *, LyXFont const & font,
289 Dimension & dim) const
291 cache_->old_ascent = 50;
292 if (imageIsDrawable())
293 cache_->old_ascent = cache_->loader.image()->getHeight();
294 dim.asc = cache_->old_ascent;
296 if (imageIsDrawable())
297 dim.wid = cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
301 LyXFont msgFont(font);
302 msgFont.setFamily(LyXFont::SANS_FAMILY);
304 string const justname = OnlyFilename(params().filename);
305 if (!justname.empty()) {
306 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
307 font_width = font_metrics::width(justname, msgFont);
310 string const msg = statusMessage();
312 msgFont.setSize(LyXFont::SIZE_TINY);
313 font_width = std::max(font_width, font_metrics::width(msg, msgFont));
316 dim.wid = std::max(50, font_width + 15);
321 BufferView * InsetGraphics::view() const
323 return cache_->view.lock().get();
327 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
329 BufferView * bv = pi.base.bv;
330 // MakeAbsPath returns params().filename unchanged if it absolute
332 string const file_with_path =
333 MakeAbsPath(params().filename, bv->buffer()->filePath());
335 // A 'paste' operation creates a new inset with the correct filepath,
336 // but then the 'old' inset stored in the 'copy' operation is actually
337 // added to the buffer.
338 // Thus, we should ensure that the filepath is correct.
339 if (file_with_path != cache_->loader.filename())
340 cache_->update(file_with_path);
342 cache_->view = bv->owner()->view();
343 int oasc = cache_->old_ascent;
346 dimension(bv, pi.base.font, dim);
348 // we may have changed while someone other was drawing us so better
349 // to not draw anything as we surely call to redraw ourself soon.
350 // This is not a nice thing to do and should be fixed properly somehow.
351 // But I still don't know the best way to go. So let's do this like this
352 // for now (Jug 20020311)
356 // Make sure now that x is updated upon exit from this routine
357 grfx::Params const & gparams = params().as_grfxParams();
359 if (gparams.display != grfx::NoDisplay &&
360 cache_->loader.status() == grfx::WaitingToLoad)
361 cache_->loader.startLoading();
363 if (!cache_->loader.monitoring())
364 cache_->loader.startMonitoring();
366 // This will draw the graphics. If the graphics has not been loaded yet,
367 // we draw just a rectangle.
369 if (imageIsDrawable()) {
370 pi.pain.image(x + TEXT_TO_INSET_OFFSET, y - dim.asc,
371 dim.wid - 2 * TEXT_TO_INSET_OFFSET, dim.asc + dim.des,
372 *cache_->loader.image());
376 pi.pain.rectangle(x + TEXT_TO_INSET_OFFSET, y - dim.asc,
377 dim.wid - 2 * TEXT_TO_INSET_OFFSET, dim.asc + dim.des);
379 // Print the file name.
380 LyXFont msgFont = pi.base.font;
381 msgFont.setFamily(LyXFont::SANS_FAMILY);
382 string const justname = OnlyFilename (params().filename);
383 if (!justname.empty()) {
384 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
385 pi.pain.text(x + TEXT_TO_INSET_OFFSET + 6,
386 y - font_metrics::maxAscent(msgFont) - 4,
390 // Print the message.
391 string const msg = statusMessage();
393 msgFont.setSize(LyXFont::SIZE_TINY);
394 pi.pain.text(x + TEXT_TO_INSET_OFFSET + 6, y - 4, msg, msgFont);
400 Inset::EDITABLE InsetGraphics::editable() const
406 void InsetGraphics::write(Buffer const *, ostream & os) const
413 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
415 string const token = lex.getString();
417 if (token == "Graphics")
418 readInsetGraphics(lex);
420 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
422 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
426 void InsetGraphics::readInsetGraphics(LyXLex & lex)
428 bool finished = false;
430 while (lex.isOK() && !finished) {
433 string const token = lex.getString();
434 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
439 } else if (token == "\\end_inset") {
441 } else if (token == "FormatVersion") {
443 int version = lex.getInteger();
444 if (version > VersionNumber)
446 << "This document was created with a newer Graphics widget"
447 ", You should use a newer version of LyX to read this"
450 // TODO: Possibly open up a dialog?
453 if (! params_.Read(lex, token))
454 lyxerr << "Unknown token, " << token << ", skipping."
461 string const InsetGraphics::createLatexOptions() const
463 // Calculate the options part of the command, we must do it to a string
464 // stream since we might have a trailing comma that we would like to remove
465 // before writing it to the output stream.
466 ostringstream options;
467 if (!params().bb.empty())
468 options << " bb=" << rtrim(params().bb) << ",\n";
470 options << " draft,\n";
472 options << " clip,\n";
473 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
474 if (!lyx::float_equal(params().scale, 100.0, 0.05))
475 options << " scale=" << params().scale / 100.0
478 if (!params().width.zero())
479 options << " width=" << params().width.asLatexString() << ",\n";
480 if (!params().height.zero())
481 options << " height=" << params().height.asLatexString() << ",\n";
482 if (params().keepAspectRatio)
483 options << " keepaspectratio,\n";
486 // Make sure rotation angle is not very close to zero;
487 // a float can be effectively zero but not exactly zero.
488 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
489 options << " angle=" << params().rotateAngle << ",\n";
490 if (!params().rotateOrigin.empty()) {
491 options << " origin=" << params().rotateOrigin[0];
492 if (contains(params().rotateOrigin,"Top"))
494 else if (contains(params().rotateOrigin,"Bottom"))
496 else if (contains(params().rotateOrigin,"Baseline"))
502 if (!params().special.empty())
503 options << params().special << ",\n";
505 string opts = STRCONV(options.str());
507 return opts.substr(0, opts.size() - 2);
511 string const InsetGraphics::prepareFile(Buffer const * buf,
512 LatexRunParams const & runparams) const
514 // LaTeX can cope if the graphics file doesn't exist, so just return the
516 string const orig_file = params().filename;
517 string orig_file_with_path =
518 MakeAbsPath(orig_file, buf->filePath());
519 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
520 << orig_file << "\n\twith path: "
521 << orig_file_with_path << endl;
523 if (!IsFileReadable(orig_file_with_path))
526 bool const zipped = zippedFile(orig_file_with_path);
528 // If the file is compressed and we have specified that it
529 // should not be uncompressed, then just return its name and
530 // let LaTeX do the rest!
531 if (zipped && params().noUnzip) {
532 lyxerr[Debug::GRAPHICS]
533 << "\tpass zipped file to LaTeX but with full path.\n";
534 // LaTeX needs an absolue path, otherwise the
535 // coresponding *.eps.bb file isn't found
536 return orig_file_with_path;
539 // Ascertain whether the file has changed.
540 unsigned long const new_checksum = cache_->loader.checksum();
541 bool const file_has_changed = cache_->checksum != new_checksum;
542 if (file_has_changed)
543 cache_->checksum = new_checksum;
545 // temp_file will contain the file for LaTeX to act on if, for example,
546 // we move it to a temp dir or uncompress it.
547 string temp_file = orig_file;
550 // Uncompress the file if necessary.
551 // If it has been uncompressed in a previous call to
552 // prepareFile, do nothing.
553 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
554 lyxerr[Debug::GRAPHICS]
555 << "\ttemp_file: " << temp_file << endl;
556 if (file_has_changed || !IsFileReadable(temp_file)) {
557 bool const success = lyx::copy(orig_file_with_path,
559 lyxerr[Debug::GRAPHICS]
560 << "\tCopying zipped file from "
561 << orig_file_with_path << " to " << temp_file
562 << (success ? " succeeded\n" : " failed\n");
564 lyxerr[Debug::GRAPHICS]
565 << "\tzipped file " << temp_file
566 << " exists! Maybe no tempdir ...\n";
567 orig_file_with_path = unzipFile(temp_file);
568 lyxerr[Debug::GRAPHICS]
569 << "\tunzipped to " << orig_file_with_path << endl;
572 string const from = getExtFromContents(orig_file_with_path);
573 string const to = findTargetFormat(from, runparams);
574 lyxerr[Debug::GRAPHICS]
575 << "\t we have: from " << from << " to " << to << '\n';
577 if (from == to && !lyxrc.use_tempdir) {
578 // No conversion is needed. LaTeX can handle the
579 // graphic file as is.
580 // This is true even if the orig_file is compressed.
581 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
582 return RemoveExtension(orig_file_with_path);
583 return orig_file_with_path;
586 // We're going to be running the exported buffer through the LaTeX
587 // compiler, so must ensure that LaTeX can cope with the graphics
590 // Perform all these manipulations on a temporary file if possible.
591 // If we are not using a temp dir, then temp_file contains the
593 // to allow files with the same name in different dirs
594 // we manipulate the original file "any.dir/file.ext"
595 // to "any_dir_file.ext"! changing the dots in the
596 // dirname is important for the use of ChangeExtension
597 lyxerr[Debug::GRAPHICS]
598 << "\tthe orig file is: " << orig_file_with_path << endl;
600 if (lyxrc.use_tempdir) {
601 string const ext_tmp = GetExtension(orig_file_with_path);
604 ChangeExtension(orig_file_with_path, string()), "/", "_");
605 // without dots and again with ext
606 temp_file = ChangeExtension(
607 subst(temp_file, ".", "_"), ext_tmp);
608 // now we have any_dir_file.ext
609 temp_file = MakeAbsPath(temp_file, buf->tmppath);
610 lyxerr[Debug::GRAPHICS]
611 << "\tchanged to: " << temp_file << endl;
613 // if the file doen't exists, copy it into the tempdir
614 if (file_has_changed || !IsFileReadable(temp_file)) {
615 bool const success = lyx::copy(orig_file_with_path, temp_file);
616 lyxerr[Debug::GRAPHICS]
617 << "\tcopying from " << orig_file_with_path << " to "
619 << (success ? " succeeded\n" : " failed\n");
621 string str = bformat(_("Could not copy the file\n%1$s\n"
622 "into the temporary directory."), orig_file_with_path);
623 Alert::error(_("Graphics display failed"), str);
629 // No conversion is needed. LaTeX can handle the
630 // graphic file as is.
631 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
632 return RemoveExtension(temp_file);
637 string const outfile_base = RemoveExtension(temp_file);
638 lyxerr[Debug::GRAPHICS]
639 << "\tThe original file is " << orig_file << "\n"
640 << "\tA copy has been made and convert is to be called with:\n"
641 << "\tfile to convert = " << temp_file << '\n'
642 << "\toutfile_base = " << outfile_base << '\n'
643 << "\t from " << from << " to " << to << '\n';
645 // if no special converter defined, than we take the default one
646 // from ImageMagic: convert from:inname.from to:outname.to
647 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
648 string const command =
649 LibFileSearch("scripts", "convertDefault.sh") +
650 ' ' + from + ':' + temp_file + ' ' +
651 to + ':' + outfile_base + '.' + to;
652 lyxerr[Debug::GRAPHICS]
653 << "No converter defined! I use convertDefault.sh:\n\t"
656 one.startscript(Systemcall::Wait, command);
657 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
658 string str = bformat(_("No information for converting %1$s "
659 "format files to %2$s.\n"
660 "Try defining a convertor in the preferences."), from, to);
661 Alert::error(_("Could not convert image"), str);
665 return RemoveExtension(temp_file);
669 int InsetGraphics::latex(Buffer const * buf, ostream & os,
670 LatexRunParams const & runparams) const
672 // If there is no file specified or not existing,
673 // just output a message about it in the latex output.
674 lyxerr[Debug::GRAPHICS]
675 << "insetgraphics::latex: Filename = "
676 << params().filename << endl;
678 // A missing (e)ps-extension is no problem for LaTeX, so
679 // we have to test three different cases
680 string const file_ = MakeAbsPath(params().filename, buf->filePath());
681 bool const file_exists =
683 (IsFileReadable(file_) || // original
684 IsFileReadable(file_ + ".eps") || // original.eps
685 IsFileReadable(file_ + ".ps")); // original.ps
686 string const message = file_exists ?
687 string() : string("bb = 0 0 200 100, draft, type=eps");
688 // if !message.empty() than there was no existing file
689 // "filename(.(e)ps)" found. In this case LaTeX
690 // draws only a rectangle with the above bb and the
691 // not found filename in it.
692 lyxerr[Debug::GRAPHICS]
693 << "\tMessage = \"" << message << '\"' << endl;
695 // These variables collect all the latex code that should be before and
696 // after the actual includegraphics command.
699 // Do we want subcaptions?
700 if (params().subcaption) {
701 before += "\\subfigure[" + params().subcaptionText + "]{";
704 // We never use the starred form, we use the "clip" option instead.
705 before += "\\includegraphics";
707 // Write the options if there are any.
708 string const opts = createLatexOptions();
709 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
711 if (!opts.empty() && !message.empty())
712 before += ("[%\n" + opts + ',' + message + ']');
713 else if (!opts.empty() || !message.empty())
714 before += ("[%\n" + opts + message + ']');
716 lyxerr[Debug::GRAPHICS]
717 << "\tBefore = " << before
718 << "\n\tafter = " << after << endl;
721 // "nice" means that the buffer is exported to LaTeX format but not
722 // run through the LaTeX compiler.
723 if (runparams.nice) {
724 os << before <<'{' << params().filename << '}' << after;
728 // Make the filename relative to the lyx file
729 // and remove the extension so the LaTeX will use whatever is
730 // appropriate (when there are several versions in different formats)
731 string const latex_str = message.empty() ?
732 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
733 (before + '{' + params().filename + " not found!}" + after);
736 // Return how many newlines we issued.
737 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
741 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
743 // No graphics in ascii output. Possible to use gifscii to convert
744 // images to ascii approximation.
745 // 1. Convert file to ascii using gifscii
746 // 2. Read ascii output file and add it to the output stream.
747 // at least we send the filename
748 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
753 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
755 // No graphics in LinuxDoc output. Should check how/what to add.
760 // For explanation on inserting graphics into DocBook checkout:
761 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
762 // See also the docbook guide at http://www.docbook.org/
763 int InsetGraphics::docbook(Buffer const *, ostream & os,
764 bool /*mixcont*/) const
766 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
767 // need to switch to MediaObject. However, for now this is sufficient and
769 os << "<graphic fileref=\"&" << graphic_label << ";\">";
774 void InsetGraphics::validate(LaTeXFeatures & features) const
776 // If we have no image, we should not require anything.
777 if (params().filename.empty())
780 features.includeFile(graphic_label, RemoveExtension(params().filename));
782 features.require("graphicx");
784 if (params().subcaption)
785 features.require("subfigure");
789 void InsetGraphics::statusChanged()
791 if (!cache_->view.expired())
792 cache_->view.lock()->updateInset(this);
796 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
797 string const & filepath)
799 // If nothing is changed, just return and say so.
800 if (params() == p && !p.filename.empty())
803 // Copy the new parameters.
806 // Update the inset with the new parameters.
807 cache_->update(MakeAbsPath(params().filename, filepath));
809 // We have changed data, report it.
814 InsetGraphicsParams const & InsetGraphics::params() const
820 string const InsetGraphicsMailer::name_("graphics");
822 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
827 string const InsetGraphicsMailer::inset2string() const
829 return params2string(inset_.params());
833 void InsetGraphicsMailer::string2params(string const & in,
834 InsetGraphicsParams & params)
836 params = InsetGraphicsParams();
841 istringstream data(STRCONV(in));
847 string const token = lex.getString();
854 inset.readInsetGraphics(lex);
855 params = inset.params();
861 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
864 data << name_ << ' ';
866 data << "\\end_inset\n";
867 return STRCONV(data.str());