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"
77 #include "frontends/lyx_gui.h"
78 #include "frontends/Alert.h"
79 #include "frontends/Dialogs.h"
80 #include "frontends/font_metrics.h"
81 #include "frontends/LyXView.h"
82 #include "frontends/Painter.h"
84 #include "support/LAssert.h"
85 #include "support/filetools.h"
86 #include "support/lyxalgo.h" // lyx::count
87 #include "support/lyxlib.h" // float_equal
88 #include "support/path.h"
89 #include "support/tostr.h"
90 #include "support/systemcall.h"
91 #include "support/os.h"
92 #include "support/lstrings.h"
94 #include <boost/weak_ptr.hpp>
95 #include <boost/bind.hpp>
96 #include <boost/signals/trackable.hpp>
98 #include <algorithm> // For the std::max
100 extern string system_tempdir;
102 extern bool pdf_mode;
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)
133 // Are we creating a PDF or a PS file?
134 // (Should actually mean, are we using latex or pdflatex).
136 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
137 if (contains(suffix, "ps") || suffix == "pdf")
139 if (suffix == "jpg") // pdflatex can use jpeg
141 return "png"; // and also png
143 // If it's postscript, we always do eps.
144 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
145 if (suffix != "ps") // any other than ps
146 return "eps"; // is changed to eps
147 return suffix; // let ps untouched
153 struct InsetGraphics::Cache : boost::signals::trackable
156 Cache(InsetGraphics &);
158 void update(string const & file_with_path);
165 unsigned long checksum;
167 boost::weak_ptr<BufferView> view;
171 InsetGraphics & parent_;
175 InsetGraphics::Cache::Cache(InsetGraphics & p)
176 : old_ascent(0), checksum(0), parent_(p)
178 loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
182 void InsetGraphics::Cache::update(string const & file_with_path)
184 lyx::Assert(!file_with_path.empty());
186 string const path = OnlyPath(file_with_path);
187 loader.reset(file_with_path, parent_.params().as_grfxParams(path));
191 InsetGraphics::InsetGraphics()
192 : graphic_label(uniqueID()),
193 cache_(new Cache(*this))
197 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
198 string const & filepath,
200 : Inset(ig, same_id),
201 graphic_label(uniqueID()),
202 cache_(new Cache(*this))
204 setParams(ig.params(), filepath);
208 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
210 return new InsetGraphics(*this, buffer.filePath(), same_id);
214 InsetGraphics::~InsetGraphics()
216 InsetGraphicsMailer mailer(*this);
221 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
223 switch (cmd.action) {
224 case LFUN_INSET_MODIFY: {
225 InsetGraphicsParams p;
226 InsetGraphicsMailer::string2params(cmd.argument, p);
227 if (!p.filename.empty()) {
228 string const filepath = cmd.view()->buffer()->filePath();
229 setParams(p, filepath);
230 cmd.view()->updateInset(this);
235 case LFUN_INSET_DIALOG_UPDATE:
236 InsetGraphicsMailer(*this).updateDialog(cmd.view());
239 case LFUN_INSET_EDIT:
240 case LFUN_MOUSE_RELEASE:
241 InsetGraphicsMailer(*this).showDialog(cmd.view());
245 return Inset::localDispatch(cmd);
250 string const InsetGraphics::statusMessage() const
252 using namespace grfx;
254 switch (cache_->loader.status()) {
256 return _("Not shown.");
258 return _("Loading...");
260 return _("Converting to loadable format...");
262 return _("Loaded into memory. Must now generate pixmap.");
264 return _("Scaling etc...");
266 return _("Ready to display");
268 return _("No file found!");
269 case ErrorConverting:
270 return _("Error converting to loadable format");
272 return _("Error loading file into memory");
273 case ErrorGeneratingPixmap:
274 return _("Error generating the pixmap");
276 return _("No image");
282 bool InsetGraphics::imageIsDrawable() const
284 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
287 return cache_->loader.image()->isDrawable();
291 void InsetGraphics::dimension(BufferView *, LyXFont const & font,
292 Dimension & dim) const
294 cache_->old_ascent = 50;
295 if (imageIsDrawable())
296 cache_->old_ascent = cache_->loader.image()->getHeight();
297 dim.a = cache_->old_ascent;
299 if (imageIsDrawable())
300 dim.w = cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
304 LyXFont msgFont(font);
305 msgFont.setFamily(LyXFont::SANS_FAMILY);
307 string const justname = OnlyFilename(params().filename);
308 if (!justname.empty()) {
309 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
310 font_width = font_metrics::width(justname, msgFont);
313 string const msg = statusMessage();
315 msgFont.setSize(LyXFont::SIZE_TINY);
316 font_width = std::max(font_width, font_metrics::width(msg, msgFont));
319 dim.w = std::max(50, font_width + 15);
324 BufferView * InsetGraphics::view() const
326 return cache_->view.lock().get();
330 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
331 int baseline, float & x) const
333 // MakeAbsPath returns params().filename unchanged if it absolute
335 string const file_with_path =
336 MakeAbsPath(params().filename, bv->buffer()->filePath());
338 // A 'paste' operation creates a new inset with the correct filepath,
339 // but then the 'old' inset stored in the 'copy' operation is actually
340 // added to the buffer.
341 // Thus, we should ensure that the filepath is correct.
342 if (file_with_path != cache_->loader.filename())
343 cache_->update(file_with_path);
345 cache_->view = bv->owner()->view();
346 int oasc = cache_->old_ascent;
348 int ldescent = descent(bv, font);
349 int lascent = ascent(bv, font);
350 int lwidth = width(bv, font);
352 // we may have changed while someone other was drawing us so better
353 // to not draw anything as we surely call to redraw ourself soon.
354 // This is not a nice thing to do and should be fixed properly somehow.
355 // But I still don't know the best way to go. So let's do this like this
356 // for now (Jug 20020311)
360 // Make sure now that x is updated upon exit from this routine
364 grfx::Params const & gparams = params().as_grfxParams();
366 if (gparams.display != grfx::NoDisplay &&
367 cache_->loader.status() == grfx::WaitingToLoad)
368 cache_->loader.startLoading();
370 if (!cache_->loader.monitoring())
371 cache_->loader.startMonitoring();
373 // This will draw the graphics. If the graphics has not been loaded yet,
374 // we draw just a rectangle.
375 Painter & paint = bv->painter();
377 if (imageIsDrawable()) {
378 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
379 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
380 *cache_->loader.image());
384 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
385 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
387 // Print the file name.
388 LyXFont msgFont(font);
389 msgFont.setFamily(LyXFont::SANS_FAMILY);
390 string const justname = OnlyFilename (params().filename);
391 if (!justname.empty()) {
392 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
393 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
394 baseline - font_metrics::maxAscent(msgFont) - 4,
398 // Print the message.
399 string const msg = statusMessage();
401 msgFont.setSize(LyXFont::SIZE_TINY);
402 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
408 Inset::EDITABLE InsetGraphics::editable() const
414 void InsetGraphics::write(Buffer const *, ostream & os) const
421 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
423 string const token = lex.getString();
425 if (token == "Graphics")
426 readInsetGraphics(lex);
428 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
430 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
434 void InsetGraphics::readInsetGraphics(LyXLex & lex)
436 bool finished = false;
438 while (lex.isOK() && !finished) {
441 string const token = lex.getString();
442 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
447 } else if (token == "\\end_inset") {
449 } else if (token == "FormatVersion") {
451 int version = lex.getInteger();
452 if (version > VersionNumber)
454 << "This document was created with a newer Graphics widget"
455 ", You should use a newer version of LyX to read this"
458 // TODO: Possibly open up a dialog?
461 if (! params_.Read(lex, token))
462 lyxerr << "Unknown token, " << token << ", skipping."
469 string const InsetGraphics::createLatexOptions() const
471 // Calculate the options part of the command, we must do it to a string
472 // stream since we might have a trailing comma that we would like to remove
473 // before writing it to the output stream.
474 ostringstream options;
475 if (!params().bb.empty())
476 options << " bb=" << rtrim(params().bb) << ",\n";
478 options << " draft,\n";
480 options << " clip,\n";
481 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
482 if (!lyx::float_equal(params().scale, 100.0, 0.05))
483 options << " scale=" << params().scale / 100.0
486 if (!params().width.zero())
487 options << " width=" << params().width.asLatexString() << ",\n";
488 if (!params().height.zero())
489 options << " height=" << params().height.asLatexString() << ",\n";
490 if (params().keepAspectRatio)
491 options << " keepaspectratio,\n";
494 // Make sure rotation angle is not very close to zero;
495 // a float can be effectively zero but not exactly zero.
496 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
497 options << " angle=" << params().rotateAngle << ",\n";
498 if (!params().rotateOrigin.empty()) {
499 options << " origin=" << params().rotateOrigin[0];
500 if (contains(params().rotateOrigin,"Top"))
502 else if (contains(params().rotateOrigin,"Bottom"))
504 else if (contains(params().rotateOrigin,"Baseline"))
510 if (!params().special.empty())
511 options << params().special << ",\n";
513 string opts = STRCONV(options.str());
515 return opts.substr(0, opts.size() - 2);
519 string const InsetGraphics::prepareFile(Buffer const * buf) const
521 // LaTeX can cope if the graphics file doesn't exist, so just return the
523 string const orig_file = params().filename;
524 string orig_file_with_path =
525 MakeAbsPath(orig_file, buf->filePath());
526 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
527 << orig_file << "\n\twith path: "
528 << orig_file_with_path << endl;
530 if (!IsFileReadable(orig_file_with_path))
533 bool const zipped = zippedFile(orig_file_with_path);
535 // If the file is compressed and we have specified that it
536 // should not be uncompressed, then just return its name and
537 // let LaTeX do the rest!
538 if (zipped && params().noUnzip) {
539 lyxerr[Debug::GRAPHICS]
540 << "\tpass zipped file to LaTeX but with full path.\n";
541 // LaTeX needs an absolue path, otherwise the
542 // coresponding *.eps.bb file isn't found
543 return orig_file_with_path;
546 // Ascertain whether the file has changed.
547 unsigned long const new_checksum = cache_->loader.checksum();
548 bool const file_has_changed = cache_->checksum != new_checksum;
549 if (file_has_changed)
550 cache_->checksum = new_checksum;
552 // temp_file will contain the file for LaTeX to act on if, for example,
553 // we move it to a temp dir or uncompress it.
554 string temp_file = orig_file;
557 // Uncompress the file if necessary.
558 // If it has been uncompressed in a previous call to
559 // prepareFile, do nothing.
560 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
561 lyxerr[Debug::GRAPHICS]
562 << "\ttemp_file: " << temp_file << endl;
563 if (file_has_changed || !IsFileReadable(temp_file)) {
564 bool const success = lyx::copy(orig_file_with_path,
566 lyxerr[Debug::GRAPHICS]
567 << "\tCopying zipped file from "
568 << orig_file_with_path << " to " << temp_file
569 << (success ? " succeeded\n" : " failed\n");
571 lyxerr[Debug::GRAPHICS]
572 << "\tzipped file " << temp_file
573 << " exists! Maybe no tempdir ...\n";
574 orig_file_with_path = unzipFile(temp_file);
575 lyxerr[Debug::GRAPHICS]
576 << "\tunzipped to " << orig_file_with_path << endl;
579 string const from = getExtFromContents(orig_file_with_path);
580 string const to = findTargetFormat(from);
581 lyxerr[Debug::GRAPHICS]
582 << "\t we have: from " << from << " to " << to << '\n';
584 if (from == to && !lyxrc.use_tempdir) {
585 // No conversion is needed. LaTeX can handle the
586 // graphic file as is.
587 // This is true even if the orig_file is compressed.
588 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
589 return RemoveExtension(orig_file_with_path);
590 return orig_file_with_path;
593 // We're going to be running the exported buffer through the LaTeX
594 // compiler, so must ensure that LaTeX can cope with the graphics
597 // Perform all these manipulations on a temporary file if possible.
598 // If we are not using a temp dir, then temp_file contains the
600 // to allow files with the same name in different dirs
601 // we manipulate the original file "any.dir/file.ext"
602 // to "any_dir_file.ext"! changing the dots in the
603 // dirname is important for the use of ChangeExtension
604 lyxerr[Debug::GRAPHICS]
605 << "\tthe orig file is: " << orig_file_with_path << endl;
607 if (lyxrc.use_tempdir) {
608 string const ext_tmp = GetExtension(orig_file_with_path);
611 ChangeExtension(orig_file_with_path, string()), "/", "_");
612 // without dots and again with ext
613 temp_file = ChangeExtension(
614 subst(temp_file, ".", "_"), ext_tmp);
615 // now we have any_dir_file.ext
616 temp_file = MakeAbsPath(temp_file, buf->tmppath);
617 lyxerr[Debug::GRAPHICS]
618 << "\tchanged to: " << temp_file << endl;
620 // if the file doen't exists, copy it into the tempdir
621 if (file_has_changed || !IsFileReadable(temp_file)) {
622 bool const success = lyx::copy(orig_file_with_path, temp_file);
623 lyxerr[Debug::GRAPHICS]
624 << "\tcopying from " << orig_file_with_path << " to "
626 << (success ? " succeeded\n" : " failed\n");
628 string str = bformat(_("Could not copy the file\n%1$s\n"
629 "into the temporary directory."), orig_file_with_path);
630 Alert::error(_("Graphics display failed"), str);
636 // No conversion is needed. LaTeX can handle the
637 // graphic file as is.
638 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
639 return RemoveExtension(temp_file);
644 string const outfile_base = RemoveExtension(temp_file);
645 lyxerr[Debug::GRAPHICS]
646 << "\tThe original file is " << orig_file << "\n"
647 << "\tA copy has been made and convert is to be called with:\n"
648 << "\tfile to convert = " << temp_file << '\n'
649 << "\toutfile_base = " << outfile_base << '\n'
650 << "\t from " << from << " to " << to << '\n';
652 // if no special converter defined, than we take the default one
653 // from ImageMagic: convert from:inname.from to:outname.to
654 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
655 string const command =
656 LibFileSearch("scripts", "convertDefault.sh") +
657 ' ' + from + ':' + temp_file + ' ' +
658 to + ':' + outfile_base + '.' + to;
659 lyxerr[Debug::GRAPHICS]
660 << "No converter defined! I use convertDefault.sh:\n\t"
663 one.startscript(Systemcall::Wait, command);
664 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
665 string str = bformat(_("No information for converting %1$s "
666 "format files to %1$s.\n"
667 "Try defining a convertor in the preferences."), from, to);
668 Alert::error(_("Could not convert image"), str);
672 return RemoveExtension(temp_file);
676 int InsetGraphics::latex(Buffer const * buf, ostream & os,
677 bool /*fragile*/, bool/*fs*/) const
679 // If there is no file specified or not existing,
680 // just output a message about it in the latex output.
681 lyxerr[Debug::GRAPHICS]
682 << "insetgraphics::latex: Filename = "
683 << params().filename << endl;
685 // A missing (e)ps-extension is no problem for LaTeX, so
686 // we have to test three different cases
687 string const file_ = MakeAbsPath(params().filename, buf->filePath());
688 bool const file_exists =
690 (IsFileReadable(file_) || // original
691 IsFileReadable(file_ + ".eps") || // original.eps
692 IsFileReadable(file_ + ".ps")); // original.ps
693 string const message = file_exists ?
694 string() : string("bb = 0 0 200 100, draft, type=eps");
695 // if !message.empty() than there was no existing file
696 // "filename(.(e)ps)" found. In this case LaTeX
697 // draws only a rectangle with the above bb and the
698 // not found filename in it.
699 lyxerr[Debug::GRAPHICS]
700 << "\tMessage = \"" << message << '\"' << endl;
702 // These variables collect all the latex code that should be before and
703 // after the actual includegraphics command.
706 // Do we want subcaptions?
707 if (params().subcaption) {
708 before += "\\subfigure[" + params().subcaptionText + "]{";
711 // We never use the starred form, we use the "clip" option instead.
712 before += "\\includegraphics";
714 // Write the options if there are any.
715 string const opts = createLatexOptions();
716 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
718 if (!opts.empty() && !message.empty())
719 before += ("[%\n" + opts + ',' + message + ']');
720 else if (!opts.empty() || !message.empty())
721 before += ("[%\n" + opts + message + ']');
723 lyxerr[Debug::GRAPHICS]
724 << "\tBefore = " << before
725 << "\n\tafter = " << after << endl;
728 // "nice" means that the buffer is exported to LaTeX format but not
729 // run through the LaTeX compiler.
731 os << before <<'{' << params().filename << '}' << after;
735 // Make the filename relative to the lyx file
736 // and remove the extension so the LaTeX will use whatever is
737 // appropriate (when there are several versions in different formats)
738 string const latex_str = message.empty() ?
739 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
740 (before + '{' + params().filename + " not found!}" + after);
743 // Return how many newlines we issued.
744 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
748 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
750 // No graphics in ascii output. Possible to use gifscii to convert
751 // images to ascii approximation.
752 // 1. Convert file to ascii using gifscii
753 // 2. Read ascii output file and add it to the output stream.
754 // at least we send the filename
755 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
760 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
762 // No graphics in LinuxDoc output. Should check how/what to add.
767 // For explanation on inserting graphics into DocBook checkout:
768 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
769 // See also the docbook guide at http://www.docbook.org/
770 int InsetGraphics::docbook(Buffer const *, ostream & os,
771 bool /*mixcont*/) const
773 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
774 // need to switch to MediaObject. However, for now this is sufficient and
776 os << "<graphic fileref=\"&" << graphic_label << ";\">";
781 void InsetGraphics::validate(LaTeXFeatures & features) const
783 // If we have no image, we should not require anything.
784 if (params().filename.empty())
787 features.includeFile(graphic_label, RemoveExtension(params().filename));
789 features.require("graphicx");
791 if (params().subcaption)
792 features.require("subfigure");
796 void InsetGraphics::statusChanged()
798 if (!cache_->view.expired())
799 cache_->view.lock()->updateInset(this);
803 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
804 string const & filepath)
806 // If nothing is changed, just return and say so.
807 if (params() == p && !p.filename.empty())
810 // Copy the new parameters.
813 // Update the inset with the new parameters.
814 cache_->update(MakeAbsPath(params().filename, filepath));
816 // We have changed data, report it.
821 InsetGraphicsParams const & InsetGraphics::params() const
827 string const InsetGraphicsMailer::name_("graphics");
829 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
834 string const InsetGraphicsMailer::inset2string() const
836 return params2string(inset_.params());
840 void InsetGraphicsMailer::string2params(string const & in,
841 InsetGraphicsParams & params)
843 params = InsetGraphicsParams();
848 istringstream data(STRCONV(in));
854 string const token = lex.getString();
861 inset.readInsetGraphics(lex);
862 params = inset.params();
868 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
871 data << name_ << ' ';
873 data << "\\end_inset\n";
874 return STRCONV(data.str());