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.
56 #include "insets/insetgraphics.h"
57 #include "insets/insetgraphicsParams.h"
59 #include "graphics/GraphicsLoader.h"
60 #include "graphics/GraphicsImage.h"
61 #include "graphics/GraphicsParams.h"
65 #include "BufferView.h"
66 #include "converter.h"
69 #include "funcrequest.h"
71 #include "LaTeXFeatures.h"
75 #include "frontends/Alert.h"
76 #include "frontends/Dialogs.h"
77 #include "frontends/font_metrics.h"
78 #include "frontends/LyXView.h"
79 #include "frontends/Painter.h"
81 #include "support/LAssert.h"
82 #include "support/filetools.h"
83 #include "support/lyxalgo.h" // lyx::count
84 #include "support/lyxlib.h" // float_equal
85 #include "support/path.h"
86 #include "support/systemcall.h"
87 #include "support/os.h"
89 #include <boost/weak_ptr.hpp>
90 #include <boost/bind.hpp>
91 #include <boost/signals/trackable.hpp>
92 #include "BoostFormat.h"
94 #include <algorithm> // For the std::max
96 extern string system_tempdir;
104 ///////////////////////////////////////////////////////////////////////////
105 int const VersionNumber = 1;
106 ///////////////////////////////////////////////////////////////////////////
108 // This function is a utility function
109 // ... that should be with ChangeExtension ...
111 string const RemoveExtension(string const & filename)
113 return ChangeExtension(filename, string());
117 string const uniqueID()
119 static unsigned int seed = 1000;
122 ost << "graph" << ++seed;
124 // Needed if we use lyxstring.
125 return STRCONV(ost.str());
129 string findTargetFormat(string const & suffix)
131 // lyxrc.pdf_mode means:
132 // Are we creating a PDF or a PS file?
133 // (Should actually mean, are we using latex or pdflatex).
134 if (lyxrc.pdf_mode) {
135 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
136 if (contains(suffix, "ps") || suffix == "pdf")
138 if (suffix == "jpg") // pdflatex can use jpeg
140 return "png"; // and also png
142 // If it's postscript, we always do eps.
143 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
144 if (suffix != "ps") // any other than ps
145 return "eps"; // is changed to eps
146 return suffix; // let ps untouched
152 struct InsetGraphics::Cache : boost::signals::trackable
155 Cache(InsetGraphics &);
157 void update(string const & file_with_path);
164 unsigned long checksum;
166 boost::weak_ptr<BufferView> view;
170 InsetGraphics & parent_;
174 InsetGraphics::Cache::Cache(InsetGraphics & p)
175 : old_ascent(0), checksum(0), parent_(p)
177 loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
181 void InsetGraphics::Cache::update(string const & file_with_path)
183 lyx::Assert(!file_with_path.empty());
185 string const path = OnlyPath(file_with_path);
186 loader.reset(file_with_path, parent_.params().as_grfxParams(path));
190 InsetGraphics::InsetGraphics()
191 : graphic_label(uniqueID()),
192 cache_(new Cache(*this))
196 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
197 string const & filepath,
199 : Inset(ig, same_id),
200 graphic_label(uniqueID()),
201 cache_(new Cache(*this))
203 setParams(ig.params(), filepath);
207 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
209 return new InsetGraphics(*this, buffer.filePath(), same_id);
213 InsetGraphics::~InsetGraphics()
215 InsetGraphicsMailer mailer(*this);
220 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
222 dispatch_result result = UNDISPATCHED;
224 switch (cmd.action) {
225 case LFUN_INSET_MODIFY: {
226 InsetGraphicsParams p;
227 InsetGraphicsMailer::string2params(cmd.argument, p);
228 if (p.filename.empty())
231 string const filepath = cmd.view()->buffer()->filePath();
232 setParams(p, filepath);
233 cmd.view()->updateInset(this);
238 case LFUN_INSET_DIALOG_UPDATE: {
239 InsetGraphicsMailer mailer(*this);
240 mailer.updateDialog(cmd.view());
244 case LFUN_MOUSE_RELEASE:
245 edit(cmd.view(), cmd.x, cmd.y, cmd.button());
257 string const InsetGraphics::statusMessage() const
259 using namespace grfx;
261 switch (cache_->loader.status()) {
263 return _("Not shown.");
265 return _("Loading...");
267 return _("Converting to loadable format...");
269 return _("Loaded into memory. Must now generate pixmap.");
271 return _("Scaling etc...");
273 return _("Ready to display");
275 return _("No file found!");
276 case ErrorConverting:
277 return _("Error converting to loadable format");
279 return _("Error loading file into memory");
280 case ErrorGeneratingPixmap:
281 return _("Error generating the pixmap");
283 return _("No image");
289 bool InsetGraphics::imageIsDrawable() const
291 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
294 return cache_->loader.image()->isDrawable();
298 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
300 cache_->old_ascent = 50;
301 if (imageIsDrawable())
302 cache_->old_ascent = cache_->loader.image()->getHeight();
303 return cache_->old_ascent;
307 int InsetGraphics::descent(BufferView *, LyXFont const &) const
313 int InsetGraphics::width(BufferView *, LyXFont const & font) const
315 if (imageIsDrawable())
316 return cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
320 LyXFont msgFont(font);
321 msgFont.setFamily(LyXFont::SANS_FAMILY);
323 string const justname = OnlyFilename (params().filename);
324 if (!justname.empty()) {
325 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
326 font_width = font_metrics::width(justname, msgFont);
329 string const msg = statusMessage();
331 msgFont.setSize(LyXFont::SIZE_TINY);
332 int const msg_width = font_metrics::width(msg, msgFont);
333 font_width = std::max(font_width, msg_width);
336 return std::max(50, font_width + 15);
340 BufferView * InsetGraphics::view() const
342 return cache_->view.lock().get();
346 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
347 int baseline, float & x) const
349 // MakeAbsPath returns params().filename unchanged if it absolute
351 string const file_with_path =
352 MakeAbsPath(params().filename, bv->buffer()->filePath());
354 // A 'paste' operation creates a new inset with the correct filepath,
355 // but then the 'old' inset stored in the 'copy' operation is actually
356 // added to the buffer.
357 // Thus, we should ensure that the filepath is correct.
358 if (file_with_path != cache_->loader.filename())
359 cache_->update(file_with_path);
361 cache_->view = bv->owner()->view();
362 int oasc = cache_->old_ascent;
364 int ldescent = descent(bv, font);
365 int lascent = ascent(bv, font);
366 int lwidth = width(bv, font);
368 // we may have changed while someone other was drawing us so better
369 // to not draw anything as we surely call to redraw ourself soon.
370 // This is not a nice thing to do and should be fixed properly somehow.
371 // But I still don't know the best way to go. So let's do this like this
372 // for now (Jug 20020311)
376 // Make sure now that x is updated upon exit from this routine
380 grfx::Params const & gparams = params().as_grfxParams();
382 if (gparams.display != grfx::NoDisplay &&
383 cache_->loader.status() == grfx::WaitingToLoad)
384 cache_->loader.startLoading();
386 if (!cache_->loader.monitoring())
387 cache_->loader.startMonitoring();
389 // This will draw the graphics. If the graphics has not been loaded yet,
390 // we draw just a rectangle.
391 Painter & paint = bv->painter();
393 if (imageIsDrawable()) {
394 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
395 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
396 *cache_->loader.image());
400 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
401 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
403 // Print the file name.
404 LyXFont msgFont(font);
405 msgFont.setFamily(LyXFont::SANS_FAMILY);
406 string const justname = OnlyFilename (params().filename);
407 if (!justname.empty()) {
408 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
409 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
410 baseline - font_metrics::maxAscent(msgFont) - 4,
414 // Print the message.
415 string const msg = statusMessage();
417 msgFont.setSize(LyXFont::SIZE_TINY);
418 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
424 void InsetGraphics::edit(BufferView * bv, int, int, mouse_button::state)
426 InsetGraphicsMailer mailer(*this);
427 mailer.showDialog(bv);
431 void InsetGraphics::edit(BufferView * bv, bool)
433 edit(bv, 0, 0, mouse_button::none);
437 Inset::EDITABLE InsetGraphics::editable() const
443 void InsetGraphics::write(Buffer const *, ostream & os) const
450 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
452 string const token = lex.getString();
454 if (token == "Graphics")
455 readInsetGraphics(lex);
457 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
459 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
463 void InsetGraphics::readInsetGraphics(LyXLex & lex)
465 bool finished = false;
467 while (lex.isOK() && !finished) {
470 string const token = lex.getString();
471 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
476 } else if (token == "\\end_inset") {
478 } else if (token == "FormatVersion") {
480 int version = lex.getInteger();
481 if (version > VersionNumber)
483 << "This document was created with a newer Graphics widget"
484 ", You should use a newer version of LyX to read this"
487 // TODO: Possibly open up a dialog?
490 if (! params_.Read(lex, token))
491 lyxerr << "Unknown token, " << token << ", skipping."
498 string const InsetGraphics::createLatexOptions() const
500 // Calculate the options part of the command, we must do it to a string
501 // stream since we might have a trailing comma that we would like to remove
502 // before writing it to the output stream.
503 ostringstream options;
504 if (!params().bb.empty())
505 options << " bb=" << rtrim(params().bb) << ",\n";
507 options << " draft,\n";
509 options << " clip,\n";
510 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
511 if (!lyx::float_equal(params().scale, 100.0, 0.05))
512 options << " scale=" << params().scale / 100.0
515 if (!params().width.zero())
516 options << " width=" << params().width.asLatexString() << ",\n";
517 if (!params().height.zero())
518 options << " height=" << params().height.asLatexString() << ",\n";
519 if (params().keepAspectRatio)
520 options << " keepaspectratio,\n";
523 // Make sure rotation angle is not very close to zero;
524 // a float can be effectively zero but not exactly zero.
525 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
526 options << " angle=" << params().rotateAngle << ",\n";
527 if (!params().rotateOrigin.empty()) {
528 options << " origin=" << params().rotateOrigin[0];
529 if (contains(params().rotateOrigin,"Top"))
531 else if (contains(params().rotateOrigin,"Bottom"))
533 else if (contains(params().rotateOrigin,"Baseline"))
539 if (!params().special.empty())
540 options << params().special << ",\n";
542 string opts = STRCONV(options.str());
544 return opts.substr(0, opts.size() - 2);
548 string const InsetGraphics::prepareFile(Buffer const * buf) const
550 // LaTeX can cope if the graphics file doesn't exist, so just return the
552 string const orig_file = params().filename;
553 string orig_file_with_path =
554 MakeAbsPath(orig_file, buf->filePath());
555 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
556 << orig_file << "\n\twith path: "
557 << orig_file_with_path << endl;
559 if (!IsFileReadable(orig_file_with_path))
562 bool const zipped = zippedFile(orig_file_with_path);
564 // If the file is compressed and we have specified that it
565 // should not be uncompressed, then just return its name and
566 // let LaTeX do the rest!
567 if (zipped && params().noUnzip) {
568 lyxerr[Debug::GRAPHICS]
569 << "\tpass zipped file to LaTeX but with full path.\n";
570 // LaTeX needs an absolue path, otherwise the
571 // coresponding *.eps.bb file isn't found
572 return orig_file_with_path;
575 // Ascertain whether the file has changed.
576 unsigned long const new_checksum = cache_->loader.checksum();
577 bool const file_has_changed = cache_->checksum != new_checksum;
578 if (file_has_changed)
579 cache_->checksum = new_checksum;
581 // temp_file will contain the file for LaTeX to act on if, for example,
582 // we move it to a temp dir or uncompress it.
583 string temp_file = orig_file;
586 // Uncompress the file if necessary.
587 // If it has been uncompressed in a previous call to
588 // prepareFile, do nothing.
589 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
590 lyxerr[Debug::GRAPHICS]
591 << "\ttemp_file: " << temp_file << endl;
592 if (file_has_changed || !IsFileReadable(temp_file)) {
593 bool const success = lyx::copy(orig_file_with_path,
595 lyxerr[Debug::GRAPHICS]
596 << "\tCopying zipped file from "
597 << orig_file_with_path << " to " << temp_file
598 << (success ? " succeeded\n" : " failed\n");
600 lyxerr[Debug::GRAPHICS]
601 << "\tzipped file " << temp_file
602 << " exists! Maybe no tempdir ...\n";
603 orig_file_with_path = unzipFile(temp_file);
604 lyxerr[Debug::GRAPHICS]
605 << "\tunzipped to " << orig_file_with_path << endl;
608 string const from = getExtFromContents(orig_file_with_path);
609 string const to = findTargetFormat(from);
610 lyxerr[Debug::GRAPHICS]
611 << "\t we have: from " << from << " to " << to << '\n';
613 if (from == to && !lyxrc.use_tempdir) {
614 // No conversion is needed. LaTeX can handle the
615 // graphic file as is.
616 // This is true even if the orig_file is compressed.
617 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
618 return RemoveExtension(orig_file_with_path);
619 return orig_file_with_path;
622 // We're going to be running the exported buffer through the LaTeX
623 // compiler, so must ensure that LaTeX can cope with the graphics
626 // Perform all these manipulations on a temporary file if possible.
627 // If we are not using a temp dir, then temp_file contains the
629 // to allow files with the same name in different dirs
630 // we manipulate the original file "any.dir/file.ext"
631 // to "any_dir_file.ext"! changing the dots in the
632 // dirname is important for the use of ChangeExtension
633 lyxerr[Debug::GRAPHICS]
634 << "\tthe orig file is: " << orig_file_with_path << endl;
636 if (lyxrc.use_tempdir) {
637 string const ext_tmp = GetExtension(orig_file_with_path);
640 ChangeExtension(orig_file_with_path, string()), "/", "_");
641 // without dots and again with ext
642 temp_file = ChangeExtension(
643 subst(temp_file, ".", "_"), ext_tmp);
644 // now we have any_dir_file.ext
645 temp_file = MakeAbsPath(temp_file, buf->tmppath);
646 lyxerr[Debug::GRAPHICS]
647 << "\tchanged to: " << temp_file << endl;
649 // if the file doen't exists, copy it into the tempdir
650 if (file_has_changed || !IsFileReadable(temp_file)) {
651 bool const success = lyx::copy(orig_file_with_path, temp_file);
652 lyxerr[Debug::GRAPHICS]
653 << "\tcopying from " << orig_file_with_path << " to "
655 << (success ? " succeeded\n" : " failed\n");
657 Alert::alert(_("Cannot copy file"), orig_file_with_path,
664 // No conversion is needed. LaTeX can handle the
665 // graphic file as is.
666 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
667 return RemoveExtension(temp_file);
672 string const outfile_base = RemoveExtension(temp_file);
673 lyxerr[Debug::GRAPHICS]
674 << "\tThe original file is " << orig_file << "\n"
675 << "\tA copy has been made and convert is to be called with:\n"
676 << "\tfile to convert = " << temp_file << '\n'
677 << "\toutfile_base = " << outfile_base << '\n'
678 << "\t from " << from << " to " << to << '\n';
680 // if no special converter defined, than we take the default one
681 // from ImageMagic: convert from:inname.from to:outname.to
682 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
683 string const command =
684 LibFileSearch("scripts", "convertDefault.sh") +
685 ' ' + from + ':' + temp_file + ' ' +
686 to + ':' + outfile_base + '.' + to;
687 lyxerr[Debug::GRAPHICS]
688 << "No converter defined! I use convertDefault.sh:\n\t"
691 one.startscript(Systemcall::Wait, command);
692 if (!IsFileReadable(ChangeExtension(outfile_base, to)))
694 Alert::alert(_("Cannot convert Image (not existing file?)"),
695 boost::io::str(boost::format(_("No information for converting from %1$s to %2$s"))
698 Alert::alert(_("Cannot convert Image (not existing file?)"),
699 _("No information for converting from ") + from + " to " + to);
703 return RemoveExtension(temp_file);
707 int InsetGraphics::latex(Buffer const * buf, ostream & os,
708 bool /*fragile*/, bool/*fs*/) const
710 // If there is no file specified or not existing,
711 // just output a message about it in the latex output.
712 lyxerr[Debug::GRAPHICS]
713 << "insetgraphics::latex: Filename = "
714 << params().filename << endl;
716 // A missing (e)ps-extension is no problem for LaTeX, so
717 // we have to test three different cases
718 string const file_ = MakeAbsPath(params().filename, buf->filePath());
719 bool const file_exists =
721 (IsFileReadable(file_) || // original
722 IsFileReadable(file_ + ".eps") || // original.eps
723 IsFileReadable(file_ + ".ps")); // original.ps
724 string const message = file_exists ?
725 string() : string("bb = 0 0 200 100, draft, type=eps");
726 // if !message.empty() than there was no existing file
727 // "filename(.(e)ps)" found. In this case LaTeX
728 // draws only a rectangle with the above bb and the
729 // not found filename in it.
730 lyxerr[Debug::GRAPHICS]
731 << "\tMessage = \"" << message << '\"' << endl;
733 // These variables collect all the latex code that should be before and
734 // after the actual includegraphics command.
737 // Do we want subcaptions?
738 if (params().subcaption) {
739 before += "\\subfigure[" + params().subcaptionText + "]{";
742 // We never use the starred form, we use the "clip" option instead.
743 before += "\\includegraphics";
745 // Write the options if there are any.
746 string const opts = createLatexOptions();
747 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
749 if (!opts.empty() && !message.empty())
750 before += ("[%\n" + opts + ',' + message + ']');
751 else if (!opts.empty() || !message.empty())
752 before += ("[%\n" + opts + message + ']');
754 lyxerr[Debug::GRAPHICS]
755 << "\tBefore = " << before
756 << "\n\tafter = " << after << endl;
759 // "nice" means that the buffer is exported to LaTeX format but not
760 // run through the LaTeX compiler.
762 os << before <<'{' << params().filename << '}' << after;
766 // Make the filename relative to the lyx file
767 // and remove the extension so the LaTeX will use whatever is
768 // appropriate (when there are several versions in different formats)
769 string const latex_str = message.empty() ?
770 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
771 (before + '{' + params().filename + " not found!}" + after);
774 // Return how many newlines we issued.
775 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
779 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
781 // No graphics in ascii output. Possible to use gifscii to convert
782 // images to ascii approximation.
783 // 1. Convert file to ascii using gifscii
784 // 2. Read ascii output file and add it to the output stream.
785 // at least we send the filename
788 << boost::format(_("Graphics file: %1$s")) % params().filename
792 << _("Graphics file: ") << params().filename
799 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
801 // No graphics in LinuxDoc output. Should check how/what to add.
806 // For explanation on inserting graphics into DocBook checkout:
807 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
808 // See also the docbook guide at http://www.docbook.org/
809 int InsetGraphics::docbook(Buffer const *, ostream & os,
810 bool /*mixcont*/) const
812 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
813 // need to switch to MediaObject. However, for now this is sufficient and
815 os << "<graphic fileref=\"&" << graphic_label << ";\">";
820 void InsetGraphics::validate(LaTeXFeatures & features) const
822 // If we have no image, we should not require anything.
823 if (params().filename.empty())
826 features.includeFile(graphic_label, RemoveExtension(params().filename));
828 features.require("graphicx");
830 if (params().subcaption)
831 features.require("subfigure");
835 void InsetGraphics::statusChanged()
837 if (!cache_->view.expired())
838 cache_->view.lock()->updateInset(this);
842 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
843 string const & filepath)
845 // If nothing is changed, just return and say so.
846 if (params() == p && !p.filename.empty())
849 // Copy the new parameters.
852 // Update the inset with the new parameters.
853 cache_->update(MakeAbsPath(params().filename, filepath));
855 // We have changed data, report it.
860 InsetGraphicsParams const & InsetGraphics::params() const
866 string const InsetGraphicsMailer::name_("graphics");
868 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
873 string const InsetGraphicsMailer::inset2string() const
875 return params2string(inset_.params());
879 void InsetGraphicsMailer::string2params(string const & in,
880 InsetGraphicsParams & params)
882 params = InsetGraphicsParams();
884 istringstream data(in);
890 string const token = lex.getString();
897 inset.readInsetGraphics(lex);
898 params = inset.params();
904 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
907 data << name_ << ' ';
909 data << "\\end_inset\n";