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"
64 #include "BufferView.h"
65 #include "converter.h"
68 #include "funcrequest.h"
70 #include "LaTeXFeatures.h"
75 #include "frontends/lyx_gui.h"
76 #include "frontends/Alert.h"
77 #include "frontends/Dialogs.h"
78 #include "frontends/font_metrics.h"
79 #include "frontends/LyXView.h"
80 #include "frontends/Painter.h"
82 #include "support/LAssert.h"
83 #include "support/filetools.h"
84 #include "support/lyxalgo.h" // lyx::count
85 #include "support/lyxlib.h" // float_equal
86 #include "support/path.h"
87 #include "support/tostr.h"
88 #include "support/systemcall.h"
89 #include "support/os.h"
91 #include <boost/weak_ptr.hpp>
92 #include <boost/bind.hpp>
93 #include <boost/signals/trackable.hpp>
94 #include "support/BoostFormat.h"
96 #include <algorithm> // For the std::max
98 extern string system_tempdir;
100 extern bool pdf_mode;
108 ///////////////////////////////////////////////////////////////////////////
109 int const VersionNumber = 1;
110 ///////////////////////////////////////////////////////////////////////////
112 // This function is a utility function
113 // ... that should be with ChangeExtension ...
115 string const RemoveExtension(string const & filename)
117 return ChangeExtension(filename, string());
121 string const uniqueID()
123 static unsigned int seed = 1000;
124 return "graph" + tostr(++seed);
128 string findTargetFormat(string const & suffix)
131 // Are we creating a PDF or a PS file?
132 // (Should actually mean, are we using latex or 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 : Inset(ig, same_id),
199 graphic_label(uniqueID()),
200 cache_(new Cache(*this))
202 setParams(ig.params(), filepath);
206 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
208 return new InsetGraphics(*this, buffer.filePath(), same_id);
212 InsetGraphics::~InsetGraphics()
214 InsetGraphicsMailer mailer(*this);
219 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
221 dispatch_result result = UNDISPATCHED;
223 switch (cmd.action) {
224 case LFUN_INSET_MODIFY: {
225 InsetGraphicsParams p;
226 InsetGraphicsMailer::string2params(cmd.argument, p);
227 if (p.filename.empty())
230 string const filepath = cmd.view()->buffer()->filePath();
231 setParams(p, filepath);
232 cmd.view()->updateInset(this);
237 case LFUN_INSET_DIALOG_UPDATE: {
238 InsetGraphicsMailer mailer(*this);
239 mailer.updateDialog(cmd.view());
243 case LFUN_MOUSE_RELEASE:
244 edit(cmd.view(), cmd.x, cmd.y, cmd.button());
256 string const InsetGraphics::statusMessage() const
258 using namespace grfx;
260 switch (cache_->loader.status()) {
262 return _("Not shown.");
264 return _("Loading...");
266 return _("Converting to loadable format...");
268 return _("Loaded into memory. Must now generate pixmap.");
270 return _("Scaling etc...");
272 return _("Ready to display");
274 return _("No file found!");
275 case ErrorConverting:
276 return _("Error converting to loadable format");
278 return _("Error loading file into memory");
279 case ErrorGeneratingPixmap:
280 return _("Error generating the pixmap");
282 return _("No image");
288 bool InsetGraphics::imageIsDrawable() const
290 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
293 return cache_->loader.image()->isDrawable();
297 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
299 cache_->old_ascent = 50;
300 if (imageIsDrawable())
301 cache_->old_ascent = cache_->loader.image()->getHeight();
302 return cache_->old_ascent;
306 int InsetGraphics::descent(BufferView *, LyXFont const &) const
312 int InsetGraphics::width(BufferView *, LyXFont const & font) const
314 if (imageIsDrawable())
315 return cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
319 LyXFont msgFont(font);
320 msgFont.setFamily(LyXFont::SANS_FAMILY);
322 string const justname = OnlyFilename (params().filename);
323 if (!justname.empty()) {
324 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
325 font_width = font_metrics::width(justname, msgFont);
328 string const msg = statusMessage();
330 msgFont.setSize(LyXFont::SIZE_TINY);
331 int const msg_width = font_metrics::width(msg, msgFont);
332 font_width = std::max(font_width, msg_width);
335 return std::max(50, font_width + 15);
339 BufferView * InsetGraphics::view() const
341 return cache_->view.lock().get();
345 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
346 int baseline, float & x) const
348 // MakeAbsPath returns params().filename unchanged if it absolute
350 string const file_with_path =
351 MakeAbsPath(params().filename, bv->buffer()->filePath());
353 // A 'paste' operation creates a new inset with the correct filepath,
354 // but then the 'old' inset stored in the 'copy' operation is actually
355 // added to the buffer.
356 // Thus, we should ensure that the filepath is correct.
357 if (file_with_path != cache_->loader.filename())
358 cache_->update(file_with_path);
360 cache_->view = bv->owner()->view();
361 int oasc = cache_->old_ascent;
363 int ldescent = descent(bv, font);
364 int lascent = ascent(bv, font);
365 int lwidth = width(bv, font);
367 // we may have changed while someone other was drawing us so better
368 // to not draw anything as we surely call to redraw ourself soon.
369 // This is not a nice thing to do and should be fixed properly somehow.
370 // But I still don't know the best way to go. So let's do this like this
371 // for now (Jug 20020311)
375 // Make sure now that x is updated upon exit from this routine
379 grfx::Params const & gparams = params().as_grfxParams();
381 if (gparams.display != grfx::NoDisplay &&
382 cache_->loader.status() == grfx::WaitingToLoad)
383 cache_->loader.startLoading();
385 if (!cache_->loader.monitoring())
386 cache_->loader.startMonitoring();
388 // This will draw the graphics. If the graphics has not been loaded yet,
389 // we draw just a rectangle.
390 Painter & paint = bv->painter();
392 if (imageIsDrawable()) {
393 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
394 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
395 *cache_->loader.image());
399 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
400 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
402 // Print the file name.
403 LyXFont msgFont(font);
404 msgFont.setFamily(LyXFont::SANS_FAMILY);
405 string const justname = OnlyFilename (params().filename);
406 if (!justname.empty()) {
407 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
408 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
409 baseline - font_metrics::maxAscent(msgFont) - 4,
413 // Print the message.
414 string const msg = statusMessage();
416 msgFont.setSize(LyXFont::SIZE_TINY);
417 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
423 void InsetGraphics::edit(BufferView * bv, int, int, mouse_button::state)
425 InsetGraphicsMailer mailer(*this);
426 mailer.showDialog(bv);
430 void InsetGraphics::edit(BufferView * bv, bool)
432 edit(bv, 0, 0, mouse_button::none);
436 Inset::EDITABLE InsetGraphics::editable() const
442 void InsetGraphics::write(Buffer const *, ostream & os) const
449 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
451 string const token = lex.getString();
453 if (token == "Graphics")
454 readInsetGraphics(lex);
456 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
458 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
462 void InsetGraphics::readInsetGraphics(LyXLex & lex)
464 bool finished = false;
466 while (lex.isOK() && !finished) {
469 string const token = lex.getString();
470 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
475 } else if (token == "\\end_inset") {
477 } else if (token == "FormatVersion") {
479 int version = lex.getInteger();
480 if (version > VersionNumber)
482 << "This document was created with a newer Graphics widget"
483 ", You should use a newer version of LyX to read this"
486 // TODO: Possibly open up a dialog?
489 if (! params_.Read(lex, token))
490 lyxerr << "Unknown token, " << token << ", skipping."
497 string const InsetGraphics::createLatexOptions() const
499 // Calculate the options part of the command, we must do it to a string
500 // stream since we might have a trailing comma that we would like to remove
501 // before writing it to the output stream.
502 ostringstream options;
503 if (!params().bb.empty())
504 options << " bb=" << rtrim(params().bb) << ",\n";
506 options << " draft,\n";
508 options << " clip,\n";
509 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
510 if (!lyx::float_equal(params().scale, 100.0, 0.05))
511 options << " scale=" << params().scale / 100.0
514 if (!params().width.zero())
515 options << " width=" << params().width.asLatexString() << ",\n";
516 if (!params().height.zero())
517 options << " height=" << params().height.asLatexString() << ",\n";
518 if (params().keepAspectRatio)
519 options << " keepaspectratio,\n";
522 // Make sure rotation angle is not very close to zero;
523 // a float can be effectively zero but not exactly zero.
524 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
525 options << " angle=" << params().rotateAngle << ",\n";
526 if (!params().rotateOrigin.empty()) {
527 options << " origin=" << params().rotateOrigin[0];
528 if (contains(params().rotateOrigin,"Top"))
530 else if (contains(params().rotateOrigin,"Bottom"))
532 else if (contains(params().rotateOrigin,"Baseline"))
538 if (!params().special.empty())
539 options << params().special << ",\n";
541 string opts = STRCONV(options.str());
543 return opts.substr(0, opts.size() - 2);
547 string const InsetGraphics::prepareFile(Buffer const * buf) const
549 // LaTeX can cope if the graphics file doesn't exist, so just return the
551 string const orig_file = params().filename;
552 string orig_file_with_path =
553 MakeAbsPath(orig_file, buf->filePath());
554 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
555 << orig_file << "\n\twith path: "
556 << orig_file_with_path << endl;
558 if (!IsFileReadable(orig_file_with_path))
561 bool const zipped = zippedFile(orig_file_with_path);
563 // If the file is compressed and we have specified that it
564 // should not be uncompressed, then just return its name and
565 // let LaTeX do the rest!
566 if (zipped && params().noUnzip) {
567 lyxerr[Debug::GRAPHICS]
568 << "\tpass zipped file to LaTeX but with full path.\n";
569 // LaTeX needs an absolue path, otherwise the
570 // coresponding *.eps.bb file isn't found
571 return orig_file_with_path;
574 // Ascertain whether the file has changed.
575 unsigned long const new_checksum = cache_->loader.checksum();
576 bool const file_has_changed = cache_->checksum != new_checksum;
577 if (file_has_changed)
578 cache_->checksum = new_checksum;
580 // temp_file will contain the file for LaTeX to act on if, for example,
581 // we move it to a temp dir or uncompress it.
582 string temp_file = orig_file;
585 // Uncompress the file if necessary.
586 // If it has been uncompressed in a previous call to
587 // prepareFile, do nothing.
588 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
589 lyxerr[Debug::GRAPHICS]
590 << "\ttemp_file: " << temp_file << endl;
591 if (file_has_changed || !IsFileReadable(temp_file)) {
592 bool const success = lyx::copy(orig_file_with_path,
594 lyxerr[Debug::GRAPHICS]
595 << "\tCopying zipped file from "
596 << orig_file_with_path << " to " << temp_file
597 << (success ? " succeeded\n" : " failed\n");
599 lyxerr[Debug::GRAPHICS]
600 << "\tzipped file " << temp_file
601 << " exists! Maybe no tempdir ...\n";
602 orig_file_with_path = unzipFile(temp_file);
603 lyxerr[Debug::GRAPHICS]
604 << "\tunzipped to " << orig_file_with_path << endl;
607 string const from = getExtFromContents(orig_file_with_path);
608 string const to = findTargetFormat(from);
609 lyxerr[Debug::GRAPHICS]
610 << "\t we have: from " << from << " to " << to << '\n';
612 if (from == to && !lyxrc.use_tempdir) {
613 // No conversion is needed. LaTeX can handle the
614 // graphic file as is.
615 // This is true even if the orig_file is compressed.
616 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
617 return RemoveExtension(orig_file_with_path);
618 return orig_file_with_path;
621 // We're going to be running the exported buffer through the LaTeX
622 // compiler, so must ensure that LaTeX can cope with the graphics
625 // Perform all these manipulations on a temporary file if possible.
626 // If we are not using a temp dir, then temp_file contains the
628 // to allow files with the same name in different dirs
629 // we manipulate the original file "any.dir/file.ext"
630 // to "any_dir_file.ext"! changing the dots in the
631 // dirname is important for the use of ChangeExtension
632 lyxerr[Debug::GRAPHICS]
633 << "\tthe orig file is: " << orig_file_with_path << endl;
635 if (lyxrc.use_tempdir) {
636 string const ext_tmp = GetExtension(orig_file_with_path);
639 ChangeExtension(orig_file_with_path, string()), "/", "_");
640 // without dots and again with ext
641 temp_file = ChangeExtension(
642 subst(temp_file, ".", "_"), ext_tmp);
643 // now we have any_dir_file.ext
644 temp_file = MakeAbsPath(temp_file, buf->tmppath);
645 lyxerr[Debug::GRAPHICS]
646 << "\tchanged to: " << temp_file << endl;
648 // if the file doen't exists, copy it into the tempdir
649 if (file_has_changed || !IsFileReadable(temp_file)) {
650 bool const success = lyx::copy(orig_file_with_path, temp_file);
651 lyxerr[Debug::GRAPHICS]
652 << "\tcopying from " << orig_file_with_path << " to "
654 << (success ? " succeeded\n" : " failed\n");
657 boost::format fmt(_("Could not copy the file\n%1$s\ninto the temporary directory."));
658 fmt % orig_file_with_path;
659 string str = fmt.str();
661 string str = _("Could not copy the file\n");
662 str += orig_file_with_path;
663 str += _("\ninto the temporary directory.");
665 Alert::error(_("Graphics display failed"), str);
671 // No conversion is needed. LaTeX can handle the
672 // graphic file as is.
673 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
674 return RemoveExtension(temp_file);
679 string const outfile_base = RemoveExtension(temp_file);
680 lyxerr[Debug::GRAPHICS]
681 << "\tThe original file is " << orig_file << "\n"
682 << "\tA copy has been made and convert is to be called with:\n"
683 << "\tfile to convert = " << temp_file << '\n'
684 << "\toutfile_base = " << outfile_base << '\n'
685 << "\t from " << from << " to " << to << '\n';
687 // if no special converter defined, than we take the default one
688 // from ImageMagic: convert from:inname.from to:outname.to
689 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
690 string const command =
691 LibFileSearch("scripts", "convertDefault.sh") +
692 ' ' + from + ':' + temp_file + ' ' +
693 to + ':' + outfile_base + '.' + to;
694 lyxerr[Debug::GRAPHICS]
695 << "No converter defined! I use convertDefault.sh:\n\t"
698 one.startscript(Systemcall::Wait, command);
699 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
701 boost::format fmt(_("No information for converting %1$s format files to %1$s.\n"
702 "Try defining a convertor in the preferences."));
704 string str = fmt.str();
706 string str = _("No information for converting ");
707 str += from + _(" format files to ") + to;
708 str += _(".\nTry defining a convertor in the preferences.");
710 Alert::error(_("Could not convert image"), str);
714 return RemoveExtension(temp_file);
718 int InsetGraphics::latex(Buffer const * buf, ostream & os,
719 bool /*fragile*/, bool/*fs*/) const
721 // If there is no file specified or not existing,
722 // just output a message about it in the latex output.
723 lyxerr[Debug::GRAPHICS]
724 << "insetgraphics::latex: Filename = "
725 << params().filename << endl;
727 // A missing (e)ps-extension is no problem for LaTeX, so
728 // we have to test three different cases
729 string const file_ = MakeAbsPath(params().filename, buf->filePath());
730 bool const file_exists =
732 (IsFileReadable(file_) || // original
733 IsFileReadable(file_ + ".eps") || // original.eps
734 IsFileReadable(file_ + ".ps")); // original.ps
735 string const message = file_exists ?
736 string() : string("bb = 0 0 200 100, draft, type=eps");
737 // if !message.empty() than there was no existing file
738 // "filename(.(e)ps)" found. In this case LaTeX
739 // draws only a rectangle with the above bb and the
740 // not found filename in it.
741 lyxerr[Debug::GRAPHICS]
742 << "\tMessage = \"" << message << '\"' << endl;
744 // These variables collect all the latex code that should be before and
745 // after the actual includegraphics command.
748 // Do we want subcaptions?
749 if (params().subcaption) {
750 before += "\\subfigure[" + params().subcaptionText + "]{";
753 // We never use the starred form, we use the "clip" option instead.
754 before += "\\includegraphics";
756 // Write the options if there are any.
757 string const opts = createLatexOptions();
758 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
760 if (!opts.empty() && !message.empty())
761 before += ("[%\n" + opts + ',' + message + ']');
762 else if (!opts.empty() || !message.empty())
763 before += ("[%\n" + opts + message + ']');
765 lyxerr[Debug::GRAPHICS]
766 << "\tBefore = " << before
767 << "\n\tafter = " << after << endl;
770 // "nice" means that the buffer is exported to LaTeX format but not
771 // run through the LaTeX compiler.
773 os << before <<'{' << params().filename << '}' << after;
777 // Make the filename relative to the lyx file
778 // and remove the extension so the LaTeX will use whatever is
779 // appropriate (when there are several versions in different formats)
780 string const latex_str = message.empty() ?
781 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
782 (before + '{' + params().filename + " not found!}" + after);
785 // Return how many newlines we issued.
786 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
790 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
792 // No graphics in ascii output. Possible to use gifscii to convert
793 // images to ascii approximation.
794 // 1. Convert file to ascii using gifscii
795 // 2. Read ascii output file and add it to the output stream.
796 // at least we send the filename
797 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
802 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
804 // No graphics in LinuxDoc output. Should check how/what to add.
809 // For explanation on inserting graphics into DocBook checkout:
810 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
811 // See also the docbook guide at http://www.docbook.org/
812 int InsetGraphics::docbook(Buffer const *, ostream & os,
813 bool /*mixcont*/) const
815 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
816 // need to switch to MediaObject. However, for now this is sufficient and
818 os << "<graphic fileref=\"&" << graphic_label << ";\">";
823 void InsetGraphics::validate(LaTeXFeatures & features) const
825 // If we have no image, we should not require anything.
826 if (params().filename.empty())
829 features.includeFile(graphic_label, RemoveExtension(params().filename));
831 features.require("graphicx");
833 if (params().subcaption)
834 features.require("subfigure");
838 void InsetGraphics::statusChanged()
840 if (!cache_->view.expired())
841 cache_->view.lock()->updateInset(this);
845 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
846 string const & filepath)
848 // If nothing is changed, just return and say so.
849 if (params() == p && !p.filename.empty())
852 // Copy the new parameters.
855 // Update the inset with the new parameters.
856 cache_->update(MakeAbsPath(params().filename, filepath));
858 // We have changed data, report it.
863 InsetGraphicsParams const & InsetGraphics::params() const
869 string const InsetGraphicsMailer::name_("graphics");
871 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
876 string const InsetGraphicsMailer::inset2string() const
878 return params2string(inset_.params());
882 void InsetGraphicsMailer::string2params(string const & in,
883 InsetGraphicsParams & params)
885 params = InsetGraphicsParams();
890 istringstream data(STRCONV(in));
896 string const token = lex.getString();
903 inset.readInsetGraphics(lex);
904 params = inset.params();
910 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
913 data << name_ << ' ';
915 data << "\\end_inset\n";
916 return STRCONV(data.str());