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 graphic_label(uniqueID()),
199 cache_(new Cache(*this))
201 setParams(ig.params(), filepath);
205 // InsetGraphics::InsetGraphics(InsetGraphics const & ig,
206 // string const & filepath,
208 // : Inset(ig, same_id),
209 // graphic_label(uniqueID()),
210 // cache_(new Cache(*this))
212 // setParams(ig.params(), filepath);
216 Inset * InsetGraphics::clone(Buffer const & buffer) const
218 return new InsetGraphics(*this, buffer.filePath());
222 // Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
224 // return new InsetGraphics(*this, buffer.filePath(), same_id);
228 InsetGraphics::~InsetGraphics()
230 InsetGraphicsMailer mailer(*this);
235 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
237 switch (cmd.action) {
238 case LFUN_INSET_MODIFY: {
239 InsetGraphicsParams p;
240 InsetGraphicsMailer::string2params(cmd.argument, p);
241 if (!p.filename.empty()) {
242 string const filepath = cmd.view()->buffer()->filePath();
243 setParams(p, filepath);
244 cmd.view()->updateInset(this);
249 case LFUN_INSET_DIALOG_UPDATE:
250 InsetGraphicsMailer(*this).updateDialog(cmd.view());
253 case LFUN_INSET_EDIT:
254 case LFUN_MOUSE_RELEASE:
255 InsetGraphicsMailer(*this).showDialog(cmd.view());
259 return Inset::localDispatch(cmd);
264 string const InsetGraphics::statusMessage() const
266 using namespace grfx;
268 switch (cache_->loader.status()) {
270 return _("Not shown.");
272 return _("Loading...");
274 return _("Converting to loadable format...");
276 return _("Loaded into memory. Must now generate pixmap.");
278 return _("Scaling etc...");
280 return _("Ready to display");
282 return _("No file found!");
283 case ErrorConverting:
284 return _("Error converting to loadable format");
286 return _("Error loading file into memory");
287 case ErrorGeneratingPixmap:
288 return _("Error generating the pixmap");
290 return _("No image");
296 bool InsetGraphics::imageIsDrawable() const
298 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
301 return cache_->loader.image()->isDrawable();
305 void InsetGraphics::dimension(BufferView *, LyXFont const & font,
306 Dimension & dim) const
308 cache_->old_ascent = 50;
309 if (imageIsDrawable())
310 cache_->old_ascent = cache_->loader.image()->getHeight();
311 dim.asc = cache_->old_ascent;
313 if (imageIsDrawable())
314 dim.wid = cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
318 LyXFont msgFont(font);
319 msgFont.setFamily(LyXFont::SANS_FAMILY);
321 string const justname = OnlyFilename(params().filename);
322 if (!justname.empty()) {
323 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
324 font_width = font_metrics::width(justname, msgFont);
327 string const msg = statusMessage();
329 msgFont.setSize(LyXFont::SIZE_TINY);
330 font_width = std::max(font_width, font_metrics::width(msg, msgFont));
333 dim.wid = std::max(50, font_width + 15);
338 BufferView * InsetGraphics::view() const
340 return cache_->view.lock().get();
344 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
345 int baseline, float & x) const
347 // MakeAbsPath returns params().filename unchanged if it absolute
349 string const file_with_path =
350 MakeAbsPath(params().filename, bv->buffer()->filePath());
352 // A 'paste' operation creates a new inset with the correct filepath,
353 // but then the 'old' inset stored in the 'copy' operation is actually
354 // added to the buffer.
355 // Thus, we should ensure that the filepath is correct.
356 if (file_with_path != cache_->loader.filename())
357 cache_->update(file_with_path);
359 cache_->view = bv->owner()->view();
360 int oasc = cache_->old_ascent;
362 int ldescent = descent(bv, font);
363 int lascent = ascent(bv, font);
364 int lwidth = width(bv, font);
366 // we may have changed while someone other was drawing us so better
367 // to not draw anything as we surely call to redraw ourself soon.
368 // This is not a nice thing to do and should be fixed properly somehow.
369 // But I still don't know the best way to go. So let's do this like this
370 // for now (Jug 20020311)
374 // Make sure now that x is updated upon exit from this routine
378 grfx::Params const & gparams = params().as_grfxParams();
380 if (gparams.display != grfx::NoDisplay &&
381 cache_->loader.status() == grfx::WaitingToLoad)
382 cache_->loader.startLoading();
384 if (!cache_->loader.monitoring())
385 cache_->loader.startMonitoring();
387 // This will draw the graphics. If the graphics has not been loaded yet,
388 // we draw just a rectangle.
389 Painter & paint = bv->painter();
391 if (imageIsDrawable()) {
392 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
393 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
394 *cache_->loader.image());
398 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
399 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
401 // Print the file name.
402 LyXFont msgFont(font);
403 msgFont.setFamily(LyXFont::SANS_FAMILY);
404 string const justname = OnlyFilename (params().filename);
405 if (!justname.empty()) {
406 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
407 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
408 baseline - font_metrics::maxAscent(msgFont) - 4,
412 // Print the message.
413 string const msg = statusMessage();
415 msgFont.setSize(LyXFont::SIZE_TINY);
416 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
422 Inset::EDITABLE InsetGraphics::editable() const
428 void InsetGraphics::write(Buffer const *, ostream & os) const
435 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
437 string const token = lex.getString();
439 if (token == "Graphics")
440 readInsetGraphics(lex);
442 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
444 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
448 void InsetGraphics::readInsetGraphics(LyXLex & lex)
450 bool finished = false;
452 while (lex.isOK() && !finished) {
455 string const token = lex.getString();
456 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
461 } else if (token == "\\end_inset") {
463 } else if (token == "FormatVersion") {
465 int version = lex.getInteger();
466 if (version > VersionNumber)
468 << "This document was created with a newer Graphics widget"
469 ", You should use a newer version of LyX to read this"
472 // TODO: Possibly open up a dialog?
475 if (! params_.Read(lex, token))
476 lyxerr << "Unknown token, " << token << ", skipping."
483 string const InsetGraphics::createLatexOptions() const
485 // Calculate the options part of the command, we must do it to a string
486 // stream since we might have a trailing comma that we would like to remove
487 // before writing it to the output stream.
488 ostringstream options;
489 if (!params().bb.empty())
490 options << " bb=" << rtrim(params().bb) << ",\n";
492 options << " draft,\n";
494 options << " clip,\n";
495 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
496 if (!lyx::float_equal(params().scale, 100.0, 0.05))
497 options << " scale=" << params().scale / 100.0
500 if (!params().width.zero())
501 options << " width=" << params().width.asLatexString() << ",\n";
502 if (!params().height.zero())
503 options << " height=" << params().height.asLatexString() << ",\n";
504 if (params().keepAspectRatio)
505 options << " keepaspectratio,\n";
508 // Make sure rotation angle is not very close to zero;
509 // a float can be effectively zero but not exactly zero.
510 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
511 options << " angle=" << params().rotateAngle << ",\n";
512 if (!params().rotateOrigin.empty()) {
513 options << " origin=" << params().rotateOrigin[0];
514 if (contains(params().rotateOrigin,"Top"))
516 else if (contains(params().rotateOrigin,"Bottom"))
518 else if (contains(params().rotateOrigin,"Baseline"))
524 if (!params().special.empty())
525 options << params().special << ",\n";
527 string opts = STRCONV(options.str());
529 return opts.substr(0, opts.size() - 2);
533 string const InsetGraphics::prepareFile(Buffer const * buf,
534 LatexRunParams const & runparams) const
536 // LaTeX can cope if the graphics file doesn't exist, so just return the
538 string const orig_file = params().filename;
539 string orig_file_with_path =
540 MakeAbsPath(orig_file, buf->filePath());
541 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
542 << orig_file << "\n\twith path: "
543 << orig_file_with_path << endl;
545 if (!IsFileReadable(orig_file_with_path))
548 bool const zipped = zippedFile(orig_file_with_path);
550 // If the file is compressed and we have specified that it
551 // should not be uncompressed, then just return its name and
552 // let LaTeX do the rest!
553 if (zipped && params().noUnzip) {
554 lyxerr[Debug::GRAPHICS]
555 << "\tpass zipped file to LaTeX but with full path.\n";
556 // LaTeX needs an absolue path, otherwise the
557 // coresponding *.eps.bb file isn't found
558 return orig_file_with_path;
561 // Ascertain whether the file has changed.
562 unsigned long const new_checksum = cache_->loader.checksum();
563 bool const file_has_changed = cache_->checksum != new_checksum;
564 if (file_has_changed)
565 cache_->checksum = new_checksum;
567 // temp_file will contain the file for LaTeX to act on if, for example,
568 // we move it to a temp dir or uncompress it.
569 string temp_file = orig_file;
572 // Uncompress the file if necessary.
573 // If it has been uncompressed in a previous call to
574 // prepareFile, do nothing.
575 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
576 lyxerr[Debug::GRAPHICS]
577 << "\ttemp_file: " << temp_file << endl;
578 if (file_has_changed || !IsFileReadable(temp_file)) {
579 bool const success = lyx::copy(orig_file_with_path,
581 lyxerr[Debug::GRAPHICS]
582 << "\tCopying zipped file from "
583 << orig_file_with_path << " to " << temp_file
584 << (success ? " succeeded\n" : " failed\n");
586 lyxerr[Debug::GRAPHICS]
587 << "\tzipped file " << temp_file
588 << " exists! Maybe no tempdir ...\n";
589 orig_file_with_path = unzipFile(temp_file);
590 lyxerr[Debug::GRAPHICS]
591 << "\tunzipped to " << orig_file_with_path << endl;
594 string const from = getExtFromContents(orig_file_with_path);
595 string const to = findTargetFormat(from, runparams);
596 lyxerr[Debug::GRAPHICS]
597 << "\t we have: from " << from << " to " << to << '\n';
599 if (from == to && !lyxrc.use_tempdir) {
600 // No conversion is needed. LaTeX can handle the
601 // graphic file as is.
602 // This is true even if the orig_file is compressed.
603 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
604 return RemoveExtension(orig_file_with_path);
605 return orig_file_with_path;
608 // We're going to be running the exported buffer through the LaTeX
609 // compiler, so must ensure that LaTeX can cope with the graphics
612 // Perform all these manipulations on a temporary file if possible.
613 // If we are not using a temp dir, then temp_file contains the
615 // to allow files with the same name in different dirs
616 // we manipulate the original file "any.dir/file.ext"
617 // to "any_dir_file.ext"! changing the dots in the
618 // dirname is important for the use of ChangeExtension
619 lyxerr[Debug::GRAPHICS]
620 << "\tthe orig file is: " << orig_file_with_path << endl;
622 if (lyxrc.use_tempdir) {
623 string const ext_tmp = GetExtension(orig_file_with_path);
626 ChangeExtension(orig_file_with_path, string()), "/", "_");
627 // without dots and again with ext
628 temp_file = ChangeExtension(
629 subst(temp_file, ".", "_"), ext_tmp);
630 // now we have any_dir_file.ext
631 temp_file = MakeAbsPath(temp_file, buf->tmppath);
632 lyxerr[Debug::GRAPHICS]
633 << "\tchanged to: " << temp_file << endl;
635 // if the file doen't exists, copy it into the tempdir
636 if (file_has_changed || !IsFileReadable(temp_file)) {
637 bool const success = lyx::copy(orig_file_with_path, temp_file);
638 lyxerr[Debug::GRAPHICS]
639 << "\tcopying from " << orig_file_with_path << " to "
641 << (success ? " succeeded\n" : " failed\n");
643 string str = bformat(_("Could not copy the file\n%1$s\n"
644 "into the temporary directory."), orig_file_with_path);
645 Alert::error(_("Graphics display failed"), str);
651 // No conversion is needed. LaTeX can handle the
652 // graphic file as is.
653 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
654 return RemoveExtension(temp_file);
659 string const outfile_base = RemoveExtension(temp_file);
660 lyxerr[Debug::GRAPHICS]
661 << "\tThe original file is " << orig_file << "\n"
662 << "\tA copy has been made and convert is to be called with:\n"
663 << "\tfile to convert = " << temp_file << '\n'
664 << "\toutfile_base = " << outfile_base << '\n'
665 << "\t from " << from << " to " << to << '\n';
667 // if no special converter defined, than we take the default one
668 // from ImageMagic: convert from:inname.from to:outname.to
669 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
670 string const command =
671 LibFileSearch("scripts", "convertDefault.sh") +
672 ' ' + from + ':' + temp_file + ' ' +
673 to + ':' + outfile_base + '.' + to;
674 lyxerr[Debug::GRAPHICS]
675 << "No converter defined! I use convertDefault.sh:\n\t"
678 one.startscript(Systemcall::Wait, command);
679 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
680 string str = bformat(_("No information for converting %1$s "
681 "format files to %1$s.\n"
682 "Try defining a convertor in the preferences."), from, to);
683 Alert::error(_("Could not convert image"), str);
687 return RemoveExtension(temp_file);
691 int InsetGraphics::latex(Buffer const * buf, ostream & os,
692 LatexRunParams const & runparams) const
694 // If there is no file specified or not existing,
695 // just output a message about it in the latex output.
696 lyxerr[Debug::GRAPHICS]
697 << "insetgraphics::latex: Filename = "
698 << params().filename << endl;
700 // A missing (e)ps-extension is no problem for LaTeX, so
701 // we have to test three different cases
702 string const file_ = MakeAbsPath(params().filename, buf->filePath());
703 bool const file_exists =
705 (IsFileReadable(file_) || // original
706 IsFileReadable(file_ + ".eps") || // original.eps
707 IsFileReadable(file_ + ".ps")); // original.ps
708 string const message = file_exists ?
709 string() : string("bb = 0 0 200 100, draft, type=eps");
710 // if !message.empty() than there was no existing file
711 // "filename(.(e)ps)" found. In this case LaTeX
712 // draws only a rectangle with the above bb and the
713 // not found filename in it.
714 lyxerr[Debug::GRAPHICS]
715 << "\tMessage = \"" << message << '\"' << endl;
717 // These variables collect all the latex code that should be before and
718 // after the actual includegraphics command.
721 // Do we want subcaptions?
722 if (params().subcaption) {
723 before += "\\subfigure[" + params().subcaptionText + "]{";
726 // We never use the starred form, we use the "clip" option instead.
727 before += "\\includegraphics";
729 // Write the options if there are any.
730 string const opts = createLatexOptions();
731 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
733 if (!opts.empty() && !message.empty())
734 before += ("[%\n" + opts + ',' + message + ']');
735 else if (!opts.empty() || !message.empty())
736 before += ("[%\n" + opts + message + ']');
738 lyxerr[Debug::GRAPHICS]
739 << "\tBefore = " << before
740 << "\n\tafter = " << after << endl;
743 // "nice" means that the buffer is exported to LaTeX format but not
744 // run through the LaTeX compiler.
745 if (runparams.nice) {
746 os << before <<'{' << params().filename << '}' << after;
750 // Make the filename relative to the lyx file
751 // and remove the extension so the LaTeX will use whatever is
752 // appropriate (when there are several versions in different formats)
753 string const latex_str = message.empty() ?
754 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
755 (before + '{' + params().filename + " not found!}" + after);
758 // Return how many newlines we issued.
759 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
763 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
765 // No graphics in ascii output. Possible to use gifscii to convert
766 // images to ascii approximation.
767 // 1. Convert file to ascii using gifscii
768 // 2. Read ascii output file and add it to the output stream.
769 // at least we send the filename
770 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
775 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
777 // No graphics in LinuxDoc output. Should check how/what to add.
782 // For explanation on inserting graphics into DocBook checkout:
783 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
784 // See also the docbook guide at http://www.docbook.org/
785 int InsetGraphics::docbook(Buffer const *, ostream & os,
786 bool /*mixcont*/) const
788 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
789 // need to switch to MediaObject. However, for now this is sufficient and
791 os << "<graphic fileref=\"&" << graphic_label << ";\">";
796 void InsetGraphics::validate(LaTeXFeatures & features) const
798 // If we have no image, we should not require anything.
799 if (params().filename.empty())
802 features.includeFile(graphic_label, RemoveExtension(params().filename));
804 features.require("graphicx");
806 if (params().subcaption)
807 features.require("subfigure");
811 void InsetGraphics::statusChanged()
813 if (!cache_->view.expired())
814 cache_->view.lock()->updateInset(this);
818 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
819 string const & filepath)
821 // If nothing is changed, just return and say so.
822 if (params() == p && !p.filename.empty())
825 // Copy the new parameters.
828 // Update the inset with the new parameters.
829 cache_->update(MakeAbsPath(params().filename, filepath));
831 // We have changed data, report it.
836 InsetGraphicsParams const & InsetGraphics::params() const
842 string const InsetGraphicsMailer::name_("graphics");
844 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
849 string const InsetGraphicsMailer::inset2string() const
851 return params2string(inset_.params());
855 void InsetGraphicsMailer::string2params(string const & in,
856 InsetGraphicsParams & params)
858 params = InsetGraphicsParams();
863 istringstream data(STRCONV(in));
869 string const token = lex.getString();
876 inset.readInsetGraphics(lex);
877 params = inset.params();
883 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
886 data << name_ << ' ';
888 data << "\\end_inset\n";
889 return STRCONV(data.str());