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"
74 #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/systemcall.h"
88 #include "support/os.h"
90 #include <boost/weak_ptr.hpp>
91 #include <boost/bind.hpp>
92 #include <boost/signals/trackable.hpp>
93 #include "support/BoostFormat.h"
95 #include <algorithm> // For the std::max
97 extern string system_tempdir;
107 ///////////////////////////////////////////////////////////////////////////
108 int const VersionNumber = 1;
109 ///////////////////////////////////////////////////////////////////////////
111 // This function is a utility function
112 // ... that should be with ChangeExtension ...
114 string const RemoveExtension(string const & filename)
116 return ChangeExtension(filename, string());
120 string const uniqueID()
122 static unsigned int seed = 1000;
125 ost << "graph" << ++seed;
127 // Needed if we use lyxstring.
128 return STRCONV(ost.str());
132 string findTargetFormat(string const & suffix)
135 // Are we creating a PDF or a PS file?
136 // (Should actually mean, are we using latex or pdflatex).
138 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
139 if (contains(suffix, "ps") || suffix == "pdf")
141 if (suffix == "jpg") // pdflatex can use jpeg
143 return "png"; // and also png
145 // If it's postscript, we always do eps.
146 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
147 if (suffix != "ps") // any other than ps
148 return "eps"; // is changed to eps
149 return suffix; // let ps untouched
155 struct InsetGraphics::Cache : boost::signals::trackable
158 Cache(InsetGraphics &);
160 void update(string const & file_with_path);
167 unsigned long checksum;
169 boost::weak_ptr<BufferView> view;
173 InsetGraphics & parent_;
177 InsetGraphics::Cache::Cache(InsetGraphics & p)
178 : old_ascent(0), checksum(0), parent_(p)
180 loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
184 void InsetGraphics::Cache::update(string const & file_with_path)
186 lyx::Assert(!file_with_path.empty());
188 string const path = OnlyPath(file_with_path);
189 loader.reset(file_with_path, parent_.params().as_grfxParams(path));
193 InsetGraphics::InsetGraphics()
194 : graphic_label(uniqueID()),
195 cache_(new Cache(*this))
199 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
200 string const & filepath,
202 : Inset(ig, same_id),
203 graphic_label(uniqueID()),
204 cache_(new Cache(*this))
206 setParams(ig.params(), filepath);
210 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
212 return new InsetGraphics(*this, buffer.filePath(), same_id);
216 InsetGraphics::~InsetGraphics()
218 InsetGraphicsMailer mailer(*this);
223 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
225 dispatch_result result = UNDISPATCHED;
227 switch (cmd.action) {
228 case LFUN_INSET_MODIFY: {
229 InsetGraphicsParams p;
230 InsetGraphicsMailer::string2params(cmd.argument, p);
231 if (p.filename.empty())
234 string const filepath = cmd.view()->buffer()->filePath();
235 setParams(p, filepath);
236 cmd.view()->updateInset(this);
241 case LFUN_INSET_DIALOG_UPDATE: {
242 InsetGraphicsMailer mailer(*this);
243 mailer.updateDialog(cmd.view());
247 case LFUN_MOUSE_RELEASE:
248 edit(cmd.view(), cmd.x, cmd.y, cmd.button());
260 string const InsetGraphics::statusMessage() const
262 using namespace grfx;
264 switch (cache_->loader.status()) {
266 return _("Not shown.");
268 return _("Loading...");
270 return _("Converting to loadable format...");
272 return _("Loaded into memory. Must now generate pixmap.");
274 return _("Scaling etc...");
276 return _("Ready to display");
278 return _("No file found!");
279 case ErrorConverting:
280 return _("Error converting to loadable format");
282 return _("Error loading file into memory");
283 case ErrorGeneratingPixmap:
284 return _("Error generating the pixmap");
286 return _("No image");
292 bool InsetGraphics::imageIsDrawable() const
294 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
297 return cache_->loader.image()->isDrawable();
301 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
303 cache_->old_ascent = 50;
304 if (imageIsDrawable())
305 cache_->old_ascent = cache_->loader.image()->getHeight();
306 return cache_->old_ascent;
310 int InsetGraphics::descent(BufferView *, LyXFont const &) const
316 int InsetGraphics::width(BufferView *, LyXFont const & font) const
318 if (imageIsDrawable())
319 return cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
323 LyXFont msgFont(font);
324 msgFont.setFamily(LyXFont::SANS_FAMILY);
326 string const justname = OnlyFilename (params().filename);
327 if (!justname.empty()) {
328 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
329 font_width = font_metrics::width(justname, msgFont);
332 string const msg = statusMessage();
334 msgFont.setSize(LyXFont::SIZE_TINY);
335 int const msg_width = font_metrics::width(msg, msgFont);
336 font_width = std::max(font_width, msg_width);
339 return std::max(50, font_width + 15);
343 BufferView * InsetGraphics::view() const
345 return cache_->view.lock().get();
349 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
350 int baseline, float & x) const
352 // MakeAbsPath returns params().filename unchanged if it absolute
354 string const file_with_path =
355 MakeAbsPath(params().filename, bv->buffer()->filePath());
357 // A 'paste' operation creates a new inset with the correct filepath,
358 // but then the 'old' inset stored in the 'copy' operation is actually
359 // added to the buffer.
360 // Thus, we should ensure that the filepath is correct.
361 if (file_with_path != cache_->loader.filename())
362 cache_->update(file_with_path);
364 cache_->view = bv->owner()->view();
365 int oasc = cache_->old_ascent;
367 int ldescent = descent(bv, font);
368 int lascent = ascent(bv, font);
369 int lwidth = width(bv, font);
371 // we may have changed while someone other was drawing us so better
372 // to not draw anything as we surely call to redraw ourself soon.
373 // This is not a nice thing to do and should be fixed properly somehow.
374 // But I still don't know the best way to go. So let's do this like this
375 // for now (Jug 20020311)
379 // Make sure now that x is updated upon exit from this routine
383 grfx::Params const & gparams = params().as_grfxParams();
385 if (gparams.display != grfx::NoDisplay &&
386 cache_->loader.status() == grfx::WaitingToLoad)
387 cache_->loader.startLoading();
389 if (!cache_->loader.monitoring())
390 cache_->loader.startMonitoring();
392 // This will draw the graphics. If the graphics has not been loaded yet,
393 // we draw just a rectangle.
394 Painter & paint = bv->painter();
396 if (imageIsDrawable()) {
397 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
398 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
399 *cache_->loader.image());
403 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
404 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
406 // Print the file name.
407 LyXFont msgFont(font);
408 msgFont.setFamily(LyXFont::SANS_FAMILY);
409 string const justname = OnlyFilename (params().filename);
410 if (!justname.empty()) {
411 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
412 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
413 baseline - font_metrics::maxAscent(msgFont) - 4,
417 // Print the message.
418 string const msg = statusMessage();
420 msgFont.setSize(LyXFont::SIZE_TINY);
421 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
427 void InsetGraphics::edit(BufferView * bv, int, int, mouse_button::state)
429 InsetGraphicsMailer mailer(*this);
430 mailer.showDialog(bv);
434 void InsetGraphics::edit(BufferView * bv, bool)
436 edit(bv, 0, 0, mouse_button::none);
440 Inset::EDITABLE InsetGraphics::editable() const
446 void InsetGraphics::write(Buffer const *, ostream & os) const
453 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
455 string const token = lex.getString();
457 if (token == "Graphics")
458 readInsetGraphics(lex);
460 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
462 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
466 void InsetGraphics::readInsetGraphics(LyXLex & lex)
468 bool finished = false;
470 while (lex.isOK() && !finished) {
473 string const token = lex.getString();
474 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
479 } else if (token == "\\end_inset") {
481 } else if (token == "FormatVersion") {
483 int version = lex.getInteger();
484 if (version > VersionNumber)
486 << "This document was created with a newer Graphics widget"
487 ", You should use a newer version of LyX to read this"
490 // TODO: Possibly open up a dialog?
493 if (! params_.Read(lex, token))
494 lyxerr << "Unknown token, " << token << ", skipping."
501 string const InsetGraphics::createLatexOptions() const
503 // Calculate the options part of the command, we must do it to a string
504 // stream since we might have a trailing comma that we would like to remove
505 // before writing it to the output stream.
506 ostringstream options;
507 if (!params().bb.empty())
508 options << " bb=" << rtrim(params().bb) << ",\n";
510 options << " draft,\n";
512 options << " clip,\n";
513 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
514 if (!lyx::float_equal(params().scale, 100.0, 0.05))
515 options << " scale=" << params().scale / 100.0
518 if (!params().width.zero())
519 options << " width=" << params().width.asLatexString() << ",\n";
520 if (!params().height.zero())
521 options << " height=" << params().height.asLatexString() << ",\n";
522 if (params().keepAspectRatio)
523 options << " keepaspectratio,\n";
526 // Make sure rotation angle is not very close to zero;
527 // a float can be effectively zero but not exactly zero.
528 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
529 options << " angle=" << params().rotateAngle << ",\n";
530 if (!params().rotateOrigin.empty()) {
531 options << " origin=" << params().rotateOrigin[0];
532 if (contains(params().rotateOrigin,"Top"))
534 else if (contains(params().rotateOrigin,"Bottom"))
536 else if (contains(params().rotateOrigin,"Baseline"))
542 if (!params().special.empty())
543 options << params().special << ",\n";
545 string opts = STRCONV(options.str());
547 return opts.substr(0, opts.size() - 2);
551 string const InsetGraphics::prepareFile(Buffer const * buf) const
553 // LaTeX can cope if the graphics file doesn't exist, so just return the
555 string const orig_file = params().filename;
556 string orig_file_with_path =
557 MakeAbsPath(orig_file, buf->filePath());
558 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
559 << orig_file << "\n\twith path: "
560 << orig_file_with_path << endl;
562 if (!IsFileReadable(orig_file_with_path))
565 bool const zipped = zippedFile(orig_file_with_path);
567 // If the file is compressed and we have specified that it
568 // should not be uncompressed, then just return its name and
569 // let LaTeX do the rest!
570 if (zipped && params().noUnzip) {
571 lyxerr[Debug::GRAPHICS]
572 << "\tpass zipped file to LaTeX but with full path.\n";
573 // LaTeX needs an absolue path, otherwise the
574 // coresponding *.eps.bb file isn't found
575 return orig_file_with_path;
578 // Ascertain whether the file has changed.
579 unsigned long const new_checksum = cache_->loader.checksum();
580 bool const file_has_changed = cache_->checksum != new_checksum;
581 if (file_has_changed)
582 cache_->checksum = new_checksum;
584 // temp_file will contain the file for LaTeX to act on if, for example,
585 // we move it to a temp dir or uncompress it.
586 string temp_file = orig_file;
589 // Uncompress the file if necessary.
590 // If it has been uncompressed in a previous call to
591 // prepareFile, do nothing.
592 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
593 lyxerr[Debug::GRAPHICS]
594 << "\ttemp_file: " << temp_file << endl;
595 if (file_has_changed || !IsFileReadable(temp_file)) {
596 bool const success = lyx::copy(orig_file_with_path,
598 lyxerr[Debug::GRAPHICS]
599 << "\tCopying zipped file from "
600 << orig_file_with_path << " to " << temp_file
601 << (success ? " succeeded\n" : " failed\n");
603 lyxerr[Debug::GRAPHICS]
604 << "\tzipped file " << temp_file
605 << " exists! Maybe no tempdir ...\n";
606 orig_file_with_path = unzipFile(temp_file);
607 lyxerr[Debug::GRAPHICS]
608 << "\tunzipped to " << orig_file_with_path << endl;
611 string const from = getExtFromContents(orig_file_with_path);
612 string const to = findTargetFormat(from);
613 lyxerr[Debug::GRAPHICS]
614 << "\t we have: from " << from << " to " << to << '\n';
616 if (from == to && !lyxrc.use_tempdir) {
617 // No conversion is needed. LaTeX can handle the
618 // graphic file as is.
619 // This is true even if the orig_file is compressed.
620 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
621 return RemoveExtension(orig_file_with_path);
622 return orig_file_with_path;
625 // We're going to be running the exported buffer through the LaTeX
626 // compiler, so must ensure that LaTeX can cope with the graphics
629 // Perform all these manipulations on a temporary file if possible.
630 // If we are not using a temp dir, then temp_file contains the
632 // to allow files with the same name in different dirs
633 // we manipulate the original file "any.dir/file.ext"
634 // to "any_dir_file.ext"! changing the dots in the
635 // dirname is important for the use of ChangeExtension
636 lyxerr[Debug::GRAPHICS]
637 << "\tthe orig file is: " << orig_file_with_path << endl;
639 if (lyxrc.use_tempdir) {
640 string const ext_tmp = GetExtension(orig_file_with_path);
643 ChangeExtension(orig_file_with_path, string()), "/", "_");
644 // without dots and again with ext
645 temp_file = ChangeExtension(
646 subst(temp_file, ".", "_"), ext_tmp);
647 // now we have any_dir_file.ext
648 temp_file = MakeAbsPath(temp_file, buf->tmppath);
649 lyxerr[Debug::GRAPHICS]
650 << "\tchanged to: " << temp_file << endl;
652 // if the file doen't exists, copy it into the tempdir
653 if (file_has_changed || !IsFileReadable(temp_file)) {
654 bool const success = lyx::copy(orig_file_with_path, temp_file);
655 lyxerr[Debug::GRAPHICS]
656 << "\tcopying from " << orig_file_with_path << " to "
658 << (success ? " succeeded\n" : " failed\n");
661 boost::format fmt(_("Could not copy the file\n%1$s\ninto the temporary directory."));
662 fmt % orig_file_with_path;
663 string str = fmt.str();
665 string str = _("Could not copy the file\n");
666 str += orig_file_with_path;
667 str += _("\ninto the temporary directory.");
669 Alert::error(_("Graphics display failed"), str);
675 // No conversion is needed. LaTeX can handle the
676 // graphic file as is.
677 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
678 return RemoveExtension(temp_file);
683 string const outfile_base = RemoveExtension(temp_file);
684 lyxerr[Debug::GRAPHICS]
685 << "\tThe original file is " << orig_file << "\n"
686 << "\tA copy has been made and convert is to be called with:\n"
687 << "\tfile to convert = " << temp_file << '\n'
688 << "\toutfile_base = " << outfile_base << '\n'
689 << "\t from " << from << " to " << to << '\n';
691 // if no special converter defined, than we take the default one
692 // from ImageMagic: convert from:inname.from to:outname.to
693 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
694 string const command =
695 LibFileSearch("scripts", "convertDefault.sh") +
696 ' ' + from + ':' + temp_file + ' ' +
697 to + ':' + outfile_base + '.' + to;
698 lyxerr[Debug::GRAPHICS]
699 << "No converter defined! I use convertDefault.sh:\n\t"
702 one.startscript(Systemcall::Wait, command);
703 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
705 boost::format fmt(_("No information for converting %1$s format files to %1$s.\n"
706 "Try defining a convertor in the preferences."));
708 string str = fmt.str();
710 string str = _("No information for converting ");
711 str += from + _(" format files to ") + to;
712 str += _(".\nTry defining a convertor in the preferences.");
714 Alert::error(_("Could not convert image"), str);
718 return RemoveExtension(temp_file);
722 int InsetGraphics::latex(Buffer const * buf, ostream & os,
723 bool /*fragile*/, bool/*fs*/) const
725 // If there is no file specified or not existing,
726 // just output a message about it in the latex output.
727 lyxerr[Debug::GRAPHICS]
728 << "insetgraphics::latex: Filename = "
729 << params().filename << endl;
731 // A missing (e)ps-extension is no problem for LaTeX, so
732 // we have to test three different cases
733 string const file_ = MakeAbsPath(params().filename, buf->filePath());
734 bool const file_exists =
736 (IsFileReadable(file_) || // original
737 IsFileReadable(file_ + ".eps") || // original.eps
738 IsFileReadable(file_ + ".ps")); // original.ps
739 string const message = file_exists ?
740 string() : string("bb = 0 0 200 100, draft, type=eps");
741 // if !message.empty() than there was no existing file
742 // "filename(.(e)ps)" found. In this case LaTeX
743 // draws only a rectangle with the above bb and the
744 // not found filename in it.
745 lyxerr[Debug::GRAPHICS]
746 << "\tMessage = \"" << message << '\"' << endl;
748 // These variables collect all the latex code that should be before and
749 // after the actual includegraphics command.
752 // Do we want subcaptions?
753 if (params().subcaption) {
754 before += "\\subfigure[" + params().subcaptionText + "]{";
757 // We never use the starred form, we use the "clip" option instead.
758 before += "\\includegraphics";
760 // Write the options if there are any.
761 string const opts = createLatexOptions();
762 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
764 if (!opts.empty() && !message.empty())
765 before += ("[%\n" + opts + ',' + message + ']');
766 else if (!opts.empty() || !message.empty())
767 before += ("[%\n" + opts + message + ']');
769 lyxerr[Debug::GRAPHICS]
770 << "\tBefore = " << before
771 << "\n\tafter = " << after << endl;
774 // "nice" means that the buffer is exported to LaTeX format but not
775 // run through the LaTeX compiler.
777 os << before <<'{' << params().filename << '}' << after;
781 // Make the filename relative to the lyx file
782 // and remove the extension so the LaTeX will use whatever is
783 // appropriate (when there are several versions in different formats)
784 string const latex_str = message.empty() ?
785 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
786 (before + '{' + params().filename + " not found!}" + after);
789 // Return how many newlines we issued.
790 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
794 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
796 // No graphics in ascii output. Possible to use gifscii to convert
797 // images to ascii approximation.
798 // 1. Convert file to ascii using gifscii
799 // 2. Read ascii output file and add it to the output stream.
800 // at least we send the filename
803 << boost::format(_("Graphics file: %1$s")) % params().filename
807 << _("Graphics file: ") << params().filename
814 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
816 // No graphics in LinuxDoc output. Should check how/what to add.
821 // For explanation on inserting graphics into DocBook checkout:
822 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
823 // See also the docbook guide at http://www.docbook.org/
824 int InsetGraphics::docbook(Buffer const *, ostream & os,
825 bool /*mixcont*/) const
827 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
828 // need to switch to MediaObject. However, for now this is sufficient and
830 os << "<graphic fileref=\"&" << graphic_label << ";\">";
835 void InsetGraphics::validate(LaTeXFeatures & features) const
837 // If we have no image, we should not require anything.
838 if (params().filename.empty())
841 features.includeFile(graphic_label, RemoveExtension(params().filename));
843 features.require("graphicx");
845 if (params().subcaption)
846 features.require("subfigure");
850 void InsetGraphics::statusChanged()
852 if (!cache_->view.expired())
853 cache_->view.lock()->updateInset(this);
857 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
858 string const & filepath)
860 // If nothing is changed, just return and say so.
861 if (params() == p && !p.filename.empty())
864 // Copy the new parameters.
867 // Update the inset with the new parameters.
868 cache_->update(MakeAbsPath(params().filename, filepath));
870 // We have changed data, report it.
875 InsetGraphicsParams const & InsetGraphics::params() const
881 string const InsetGraphicsMailer::name_("graphics");
883 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
888 string const InsetGraphicsMailer::inset2string() const
890 return params2string(inset_.params());
894 void InsetGraphicsMailer::string2params(string const & in,
895 InsetGraphicsParams & params)
897 params = InsetGraphicsParams();
902 istringstream data(in);
908 string const token = lex.getString();
915 inset.readInsetGraphics(lex);
916 params = inset.params();
922 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
925 data << name_ << ' ';
927 data << "\\end_inset\n";