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"
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 : 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 switch (cmd.action) {
222 case LFUN_INSET_MODIFY: {
223 InsetGraphicsParams p;
224 InsetGraphicsMailer::string2params(cmd.argument, p);
225 if (!p.filename.empty()) {
226 string const filepath = cmd.view()->buffer()->filePath();
227 setParams(p, filepath);
228 cmd.view()->updateInset(this);
233 case LFUN_INSET_DIALOG_UPDATE:
234 InsetGraphicsMailer(*this).updateDialog(cmd.view());
237 case LFUN_INSET_EDIT:
238 case LFUN_MOUSE_RELEASE:
239 InsetGraphicsMailer(*this).showDialog(cmd.view());
243 return Inset::localDispatch(cmd);
248 string const InsetGraphics::statusMessage() const
250 using namespace grfx;
252 switch (cache_->loader.status()) {
254 return _("Not shown.");
256 return _("Loading...");
258 return _("Converting to loadable format...");
260 return _("Loaded into memory. Must now generate pixmap.");
262 return _("Scaling etc...");
264 return _("Ready to display");
266 return _("No file found!");
267 case ErrorConverting:
268 return _("Error converting to loadable format");
270 return _("Error loading file into memory");
271 case ErrorGeneratingPixmap:
272 return _("Error generating the pixmap");
274 return _("No image");
280 bool InsetGraphics::imageIsDrawable() const
282 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
285 return cache_->loader.image()->isDrawable();
289 void InsetGraphics::dimension(BufferView *, LyXFont const & font,
290 Dimension & dim) const
292 cache_->old_ascent = 50;
293 if (imageIsDrawable())
294 cache_->old_ascent = cache_->loader.image()->getHeight();
295 dim.a = cache_->old_ascent;
297 if (imageIsDrawable())
298 dim.w = cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
302 LyXFont msgFont(font);
303 msgFont.setFamily(LyXFont::SANS_FAMILY);
305 string const justname = OnlyFilename(params().filename);
306 if (!justname.empty()) {
307 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
308 font_width = font_metrics::width(justname, msgFont);
311 string const msg = statusMessage();
313 msgFont.setSize(LyXFont::SIZE_TINY);
314 font_width = std::max(font_width, font_metrics::width(msg, msgFont));
317 dim.w = std::max(50, font_width + 15);
322 BufferView * InsetGraphics::view() const
324 return cache_->view.lock().get();
328 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
329 int baseline, float & x) const
331 // MakeAbsPath returns params().filename unchanged if it absolute
333 string const file_with_path =
334 MakeAbsPath(params().filename, bv->buffer()->filePath());
336 // A 'paste' operation creates a new inset with the correct filepath,
337 // but then the 'old' inset stored in the 'copy' operation is actually
338 // added to the buffer.
339 // Thus, we should ensure that the filepath is correct.
340 if (file_with_path != cache_->loader.filename())
341 cache_->update(file_with_path);
343 cache_->view = bv->owner()->view();
344 int oasc = cache_->old_ascent;
346 int ldescent = descent(bv, font);
347 int lascent = ascent(bv, font);
348 int lwidth = width(bv, font);
350 // we may have changed while someone other was drawing us so better
351 // to not draw anything as we surely call to redraw ourself soon.
352 // This is not a nice thing to do and should be fixed properly somehow.
353 // But I still don't know the best way to go. So let's do this like this
354 // for now (Jug 20020311)
358 // Make sure now that x is updated upon exit from this routine
362 grfx::Params const & gparams = params().as_grfxParams();
364 if (gparams.display != grfx::NoDisplay &&
365 cache_->loader.status() == grfx::WaitingToLoad)
366 cache_->loader.startLoading();
368 if (!cache_->loader.monitoring())
369 cache_->loader.startMonitoring();
371 // This will draw the graphics. If the graphics has not been loaded yet,
372 // we draw just a rectangle.
373 Painter & paint = bv->painter();
375 if (imageIsDrawable()) {
376 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
377 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
378 *cache_->loader.image());
382 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
383 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
385 // Print the file name.
386 LyXFont msgFont(font);
387 msgFont.setFamily(LyXFont::SANS_FAMILY);
388 string const justname = OnlyFilename (params().filename);
389 if (!justname.empty()) {
390 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
391 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
392 baseline - font_metrics::maxAscent(msgFont) - 4,
396 // Print the message.
397 string const msg = statusMessage();
399 msgFont.setSize(LyXFont::SIZE_TINY);
400 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
406 Inset::EDITABLE InsetGraphics::editable() const
412 void InsetGraphics::write(Buffer const *, ostream & os) const
419 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
421 string const token = lex.getString();
423 if (token == "Graphics")
424 readInsetGraphics(lex);
426 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
428 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
432 void InsetGraphics::readInsetGraphics(LyXLex & lex)
434 bool finished = false;
436 while (lex.isOK() && !finished) {
439 string const token = lex.getString();
440 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
445 } else if (token == "\\end_inset") {
447 } else if (token == "FormatVersion") {
449 int version = lex.getInteger();
450 if (version > VersionNumber)
452 << "This document was created with a newer Graphics widget"
453 ", You should use a newer version of LyX to read this"
456 // TODO: Possibly open up a dialog?
459 if (! params_.Read(lex, token))
460 lyxerr << "Unknown token, " << token << ", skipping."
467 string const InsetGraphics::createLatexOptions() const
469 // Calculate the options part of the command, we must do it to a string
470 // stream since we might have a trailing comma that we would like to remove
471 // before writing it to the output stream.
472 ostringstream options;
473 if (!params().bb.empty())
474 options << " bb=" << rtrim(params().bb) << ",\n";
476 options << " draft,\n";
478 options << " clip,\n";
479 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
480 if (!lyx::float_equal(params().scale, 100.0, 0.05))
481 options << " scale=" << params().scale / 100.0
484 if (!params().width.zero())
485 options << " width=" << params().width.asLatexString() << ",\n";
486 if (!params().height.zero())
487 options << " height=" << params().height.asLatexString() << ",\n";
488 if (params().keepAspectRatio)
489 options << " keepaspectratio,\n";
492 // Make sure rotation angle is not very close to zero;
493 // a float can be effectively zero but not exactly zero.
494 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
495 options << " angle=" << params().rotateAngle << ",\n";
496 if (!params().rotateOrigin.empty()) {
497 options << " origin=" << params().rotateOrigin[0];
498 if (contains(params().rotateOrigin,"Top"))
500 else if (contains(params().rotateOrigin,"Bottom"))
502 else if (contains(params().rotateOrigin,"Baseline"))
508 if (!params().special.empty())
509 options << params().special << ",\n";
511 string opts = STRCONV(options.str());
513 return opts.substr(0, opts.size() - 2);
517 string const InsetGraphics::prepareFile(Buffer const * buf,
518 LatexRunParams const & runparams) const
520 // LaTeX can cope if the graphics file doesn't exist, so just return the
522 string const orig_file = params().filename;
523 string orig_file_with_path =
524 MakeAbsPath(orig_file, buf->filePath());
525 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
526 << orig_file << "\n\twith path: "
527 << orig_file_with_path << endl;
529 if (!IsFileReadable(orig_file_with_path))
532 bool const zipped = zippedFile(orig_file_with_path);
534 // If the file is compressed and we have specified that it
535 // should not be uncompressed, then just return its name and
536 // let LaTeX do the rest!
537 if (zipped && params().noUnzip) {
538 lyxerr[Debug::GRAPHICS]
539 << "\tpass zipped file to LaTeX but with full path.\n";
540 // LaTeX needs an absolue path, otherwise the
541 // coresponding *.eps.bb file isn't found
542 return orig_file_with_path;
545 // Ascertain whether the file has changed.
546 unsigned long const new_checksum = cache_->loader.checksum();
547 bool const file_has_changed = cache_->checksum != new_checksum;
548 if (file_has_changed)
549 cache_->checksum = new_checksum;
551 // temp_file will contain the file for LaTeX to act on if, for example,
552 // we move it to a temp dir or uncompress it.
553 string temp_file = orig_file;
556 // Uncompress the file if necessary.
557 // If it has been uncompressed in a previous call to
558 // prepareFile, do nothing.
559 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
560 lyxerr[Debug::GRAPHICS]
561 << "\ttemp_file: " << temp_file << endl;
562 if (file_has_changed || !IsFileReadable(temp_file)) {
563 bool const success = lyx::copy(orig_file_with_path,
565 lyxerr[Debug::GRAPHICS]
566 << "\tCopying zipped file from "
567 << orig_file_with_path << " to " << temp_file
568 << (success ? " succeeded\n" : " failed\n");
570 lyxerr[Debug::GRAPHICS]
571 << "\tzipped file " << temp_file
572 << " exists! Maybe no tempdir ...\n";
573 orig_file_with_path = unzipFile(temp_file);
574 lyxerr[Debug::GRAPHICS]
575 << "\tunzipped to " << orig_file_with_path << endl;
578 string const from = getExtFromContents(orig_file_with_path);
579 string const to = findTargetFormat(from, runparams);
580 lyxerr[Debug::GRAPHICS]
581 << "\t we have: from " << from << " to " << to << '\n';
583 if (from == to && !lyxrc.use_tempdir) {
584 // No conversion is needed. LaTeX can handle the
585 // graphic file as is.
586 // This is true even if the orig_file is compressed.
587 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
588 return RemoveExtension(orig_file_with_path);
589 return orig_file_with_path;
592 // We're going to be running the exported buffer through the LaTeX
593 // compiler, so must ensure that LaTeX can cope with the graphics
596 // Perform all these manipulations on a temporary file if possible.
597 // If we are not using a temp dir, then temp_file contains the
599 // to allow files with the same name in different dirs
600 // we manipulate the original file "any.dir/file.ext"
601 // to "any_dir_file.ext"! changing the dots in the
602 // dirname is important for the use of ChangeExtension
603 lyxerr[Debug::GRAPHICS]
604 << "\tthe orig file is: " << orig_file_with_path << endl;
606 if (lyxrc.use_tempdir) {
607 string const ext_tmp = GetExtension(orig_file_with_path);
610 ChangeExtension(orig_file_with_path, string()), "/", "_");
611 // without dots and again with ext
612 temp_file = ChangeExtension(
613 subst(temp_file, ".", "_"), ext_tmp);
614 // now we have any_dir_file.ext
615 temp_file = MakeAbsPath(temp_file, buf->tmppath);
616 lyxerr[Debug::GRAPHICS]
617 << "\tchanged to: " << temp_file << endl;
619 // if the file doen't exists, copy it into the tempdir
620 if (file_has_changed || !IsFileReadable(temp_file)) {
621 bool const success = lyx::copy(orig_file_with_path, temp_file);
622 lyxerr[Debug::GRAPHICS]
623 << "\tcopying from " << orig_file_with_path << " to "
625 << (success ? " succeeded\n" : " failed\n");
627 string str = bformat(_("Could not copy the file\n%1$s\n"
628 "into the temporary directory."), orig_file_with_path);
629 Alert::error(_("Graphics display failed"), str);
635 // No conversion is needed. LaTeX can handle the
636 // graphic file as is.
637 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
638 return RemoveExtension(temp_file);
643 string const outfile_base = RemoveExtension(temp_file);
644 lyxerr[Debug::GRAPHICS]
645 << "\tThe original file is " << orig_file << "\n"
646 << "\tA copy has been made and convert is to be called with:\n"
647 << "\tfile to convert = " << temp_file << '\n'
648 << "\toutfile_base = " << outfile_base << '\n'
649 << "\t from " << from << " to " << to << '\n';
651 // if no special converter defined, than we take the default one
652 // from ImageMagic: convert from:inname.from to:outname.to
653 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
654 string const command =
655 LibFileSearch("scripts", "convertDefault.sh") +
656 ' ' + from + ':' + temp_file + ' ' +
657 to + ':' + outfile_base + '.' + to;
658 lyxerr[Debug::GRAPHICS]
659 << "No converter defined! I use convertDefault.sh:\n\t"
662 one.startscript(Systemcall::Wait, command);
663 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
664 string str = bformat(_("No information for converting %1$s "
665 "format files to %1$s.\n"
666 "Try defining a convertor in the preferences."), from, to);
667 Alert::error(_("Could not convert image"), str);
671 return RemoveExtension(temp_file);
675 int InsetGraphics::latex(Buffer const * buf, ostream & os, LatexRunParams const & runparams,
676 bool /*fragile*/, bool/*fs*/) const
678 // If there is no file specified or not existing,
679 // just output a message about it in the latex output.
680 lyxerr[Debug::GRAPHICS]
681 << "insetgraphics::latex: Filename = "
682 << params().filename << endl;
684 // A missing (e)ps-extension is no problem for LaTeX, so
685 // we have to test three different cases
686 string const file_ = MakeAbsPath(params().filename, buf->filePath());
687 bool const file_exists =
689 (IsFileReadable(file_) || // original
690 IsFileReadable(file_ + ".eps") || // original.eps
691 IsFileReadable(file_ + ".ps")); // original.ps
692 string const message = file_exists ?
693 string() : string("bb = 0 0 200 100, draft, type=eps");
694 // if !message.empty() than there was no existing file
695 // "filename(.(e)ps)" found. In this case LaTeX
696 // draws only a rectangle with the above bb and the
697 // not found filename in it.
698 lyxerr[Debug::GRAPHICS]
699 << "\tMessage = \"" << message << '\"' << endl;
701 // These variables collect all the latex code that should be before and
702 // after the actual includegraphics command.
705 // Do we want subcaptions?
706 if (params().subcaption) {
707 before += "\\subfigure[" + params().subcaptionText + "]{";
710 // We never use the starred form, we use the "clip" option instead.
711 before += "\\includegraphics";
713 // Write the options if there are any.
714 string const opts = createLatexOptions();
715 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
717 if (!opts.empty() && !message.empty())
718 before += ("[%\n" + opts + ',' + message + ']');
719 else if (!opts.empty() || !message.empty())
720 before += ("[%\n" + opts + message + ']');
722 lyxerr[Debug::GRAPHICS]
723 << "\tBefore = " << before
724 << "\n\tafter = " << after << endl;
727 // "nice" means that the buffer is exported to LaTeX format but not
728 // run through the LaTeX compiler.
730 os << before <<'{' << params().filename << '}' << after;
734 // Make the filename relative to the lyx file
735 // and remove the extension so the LaTeX will use whatever is
736 // appropriate (when there are several versions in different formats)
737 string const latex_str = message.empty() ?
738 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
739 (before + '{' + params().filename + " not found!}" + after);
742 // Return how many newlines we issued.
743 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
747 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
749 // No graphics in ascii output. Possible to use gifscii to convert
750 // images to ascii approximation.
751 // 1. Convert file to ascii using gifscii
752 // 2. Read ascii output file and add it to the output stream.
753 // at least we send the filename
754 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
759 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
761 // No graphics in LinuxDoc output. Should check how/what to add.
766 // For explanation on inserting graphics into DocBook checkout:
767 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
768 // See also the docbook guide at http://www.docbook.org/
769 int InsetGraphics::docbook(Buffer const *, ostream & os,
770 bool /*mixcont*/) const
772 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
773 // need to switch to MediaObject. However, for now this is sufficient and
775 os << "<graphic fileref=\"&" << graphic_label << ";\">";
780 void InsetGraphics::validate(LaTeXFeatures & features) const
782 // If we have no image, we should not require anything.
783 if (params().filename.empty())
786 features.includeFile(graphic_label, RemoveExtension(params().filename));
788 features.require("graphicx");
790 if (params().subcaption)
791 features.require("subfigure");
795 void InsetGraphics::statusChanged()
797 if (!cache_->view.expired())
798 cache_->view.lock()->updateInset(this);
802 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
803 string const & filepath)
805 // If nothing is changed, just return and say so.
806 if (params() == p && !p.filename.empty())
809 // Copy the new parameters.
812 // Update the inset with the new parameters.
813 cache_->update(MakeAbsPath(params().filename, filepath));
815 // We have changed data, report it.
820 InsetGraphicsParams const & InsetGraphics::params() const
826 string const InsetGraphicsMailer::name_("graphics");
828 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
833 string const InsetGraphicsMailer::inset2string() const
835 return params2string(inset_.params());
839 void InsetGraphicsMailer::string2params(string const & in,
840 InsetGraphicsParams & params)
842 params = InsetGraphicsParams();
847 istringstream data(STRCONV(in));
853 string const token = lex.getString();
860 inset.readInsetGraphics(lex);
861 params = inset.params();
867 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
870 data << name_ << ' ';
872 data << "\\end_inset\n";
873 return STRCONV(data.str());