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"
76 #include "metricsinfo.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());
189 InsetGraphics::InsetGraphics()
190 : graphic_label(uniqueID()),
191 cache_(new Cache(*this))
195 #warning I have zero idea about the trackable()
196 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
198 boost::signals::trackable(ig),
199 graphic_label(uniqueID()),
200 cache_(new Cache(*this))
202 setParams(ig.params());
206 Inset * InsetGraphics::clone() const
208 return new InsetGraphics(*this);
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()) {
227 cmd.view()->updateInset(this);
232 case LFUN_INSET_DIALOG_UPDATE:
233 InsetGraphicsMailer(*this).updateDialog(cmd.view());
236 case LFUN_INSET_EDIT:
237 case LFUN_MOUSE_RELEASE:
238 InsetGraphicsMailer(*this).showDialog(cmd.view());
242 return Inset::localDispatch(cmd);
247 string const InsetGraphics::statusMessage() const
249 using namespace grfx;
251 switch (cache_->loader.status()) {
253 return _("Not shown.");
255 return _("Loading...");
257 return _("Converting to loadable format...");
259 return _("Loaded into memory. Must now generate pixmap.");
261 return _("Scaling etc...");
263 return _("Ready to display");
265 return _("No file found!");
266 case ErrorConverting:
267 return _("Error converting to loadable format");
269 return _("Error loading file into memory");
270 case ErrorGeneratingPixmap:
271 return _("Error generating the pixmap");
273 return _("No image");
279 bool InsetGraphics::imageIsDrawable() const
281 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
284 return cache_->loader.image()->isDrawable();
288 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
290 cache_->old_ascent = 50;
291 if (imageIsDrawable())
292 cache_->old_ascent = cache_->loader.image()->getHeight();
293 dim.asc = cache_->old_ascent;
295 if (imageIsDrawable())
296 dim.wid = cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
300 LyXFont msgFont(mi.base.font);
301 msgFont.setFamily(LyXFont::SANS_FAMILY);
303 string const justname = OnlyFilename(params().filename);
304 if (!justname.empty()) {
305 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
306 font_width = font_metrics::width(justname, msgFont);
309 string const msg = statusMessage();
311 msgFont.setSize(LyXFont::SIZE_TINY);
312 font_width = std::max(font_width, font_metrics::width(msg, msgFont));
315 dim.wid = std::max(50, font_width + 15);
321 BufferView * InsetGraphics::view() const
323 return cache_->view.lock().get();
327 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
329 BufferView * bv = pi.base.bv;
330 cache_->view = bv->owner()->view();
331 int oasc = cache_->old_ascent;
333 // we may have changed while someone other was drawing us so better
334 // to not draw anything as we surely call to redraw ourself soon.
335 // This is not a nice thing to do and should be fixed properly somehow.
336 // But I still don't know the best way to go. So let's do this like this
337 // for now (Jug 20020311)
338 if (dim_.asc != oasc)
341 // Make sure now that x is updated upon exit from this routine
342 grfx::Params const & gparams = params().as_grfxParams();
344 if (gparams.display != grfx::NoDisplay &&
345 cache_->loader.status() == grfx::WaitingToLoad)
346 cache_->loader.startLoading();
348 if (!cache_->loader.monitoring())
349 cache_->loader.startMonitoring();
351 // This will draw the graphics. If the graphics has not been loaded yet,
352 // we draw just a rectangle.
354 if (imageIsDrawable()) {
355 pi.pain.image(x + TEXT_TO_INSET_OFFSET, y - dim_.asc,
356 dim_.wid - 2 * TEXT_TO_INSET_OFFSET, dim_.asc + dim_.des,
357 *cache_->loader.image());
361 pi.pain.rectangle(x + TEXT_TO_INSET_OFFSET, y - dim_.asc,
362 dim_.wid - 2 * TEXT_TO_INSET_OFFSET, dim_.asc + dim_.des);
364 // Print the file name.
365 LyXFont msgFont = pi.base.font;
366 msgFont.setFamily(LyXFont::SANS_FAMILY);
367 string const justname = OnlyFilename (params().filename);
368 if (!justname.empty()) {
369 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
370 pi.pain.text(x + TEXT_TO_INSET_OFFSET + 6,
371 y - font_metrics::maxAscent(msgFont) - 4,
375 // Print the message.
376 string const msg = statusMessage();
378 msgFont.setSize(LyXFont::SIZE_TINY);
379 pi.pain.text(x + TEXT_TO_INSET_OFFSET + 6, y - 4, msg, msgFont);
385 Inset::EDITABLE InsetGraphics::editable() const
391 void InsetGraphics::write(Buffer const * buf, ostream & os) const
394 params().Write(os, buf->filePath());
398 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
400 string const token = lex.getString();
402 if (token == "Graphics")
403 readInsetGraphics(lex, buf->filePath());
405 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
407 cache_->update(params().filename);
411 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
413 bool finished = false;
415 while (lex.isOK() && !finished) {
418 string const token = lex.getString();
419 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
424 } else if (token == "\\end_inset") {
426 } else if (token == "FormatVersion") {
428 int version = lex.getInteger();
429 if (version > VersionNumber)
431 << "This document was created with a newer Graphics widget"
432 ", You should use a newer version of LyX to read this"
435 // TODO: Possibly open up a dialog?
438 if (!params_.Read(lex, token, bufpath))
439 lyxerr << "Unknown token, " << token << ", skipping."
446 string const InsetGraphics::createLatexOptions() const
448 // Calculate the options part of the command, we must do it to a string
449 // stream since we might have a trailing comma that we would like to remove
450 // before writing it to the output stream.
451 ostringstream options;
452 if (!params().bb.empty())
453 options << " bb=" << rtrim(params().bb) << ",\n";
455 options << " draft,\n";
457 options << " clip,\n";
458 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
459 if (!lyx::float_equal(params().scale, 100.0, 0.05))
460 options << " scale=" << params().scale / 100.0
463 if (!params().width.zero())
464 options << " width=" << params().width.asLatexString() << ",\n";
465 if (!params().height.zero())
466 options << " height=" << params().height.asLatexString() << ",\n";
467 if (params().keepAspectRatio)
468 options << " keepaspectratio,\n";
471 // Make sure rotation angle is not very close to zero;
472 // a float can be effectively zero but not exactly zero.
473 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
474 options << " angle=" << params().rotateAngle << ",\n";
475 if (!params().rotateOrigin.empty()) {
476 options << " origin=" << params().rotateOrigin[0];
477 if (contains(params().rotateOrigin,"Top"))
479 else if (contains(params().rotateOrigin,"Bottom"))
481 else if (contains(params().rotateOrigin,"Baseline"))
487 if (!params().special.empty())
488 options << params().special << ",\n";
490 string opts = STRCONV(options.str());
492 return opts.substr(0, opts.size() - 2);
496 string const InsetGraphics::prepareFile(Buffer const * buf,
497 LatexRunParams const & runparams) const
499 // LaTeX can cope if the graphics file doesn't exist, so just return the
501 string orig_file = params().filename;
502 string const rel_file = MakeRelPath(orig_file, buf->filePath());
504 if (!IsFileReadable(rel_file))
507 bool const zipped = zippedFile(orig_file);
509 // If the file is compressed and we have specified that it
510 // should not be uncompressed, then just return its name and
511 // let LaTeX do the rest!
512 if (zipped && params().noUnzip) {
513 lyxerr[Debug::GRAPHICS]
514 << "\tpass zipped file to LaTeX but with full path.\n";
515 // LaTeX needs an absolute path, otherwise the
516 // coresponding *.eps.bb file isn't found
520 // Ascertain whether the file has changed.
521 unsigned long const new_checksum = cache_->loader.checksum();
522 bool const file_has_changed = cache_->checksum != new_checksum;
523 if (file_has_changed)
524 cache_->checksum = new_checksum;
526 // temp_file will contain the file for LaTeX to act on if, for example,
527 // we move it to a temp dir or uncompress it.
528 string temp_file = orig_file;
531 // Uncompress the file if necessary.
532 // If it has been uncompressed in a previous call to
533 // prepareFile, do nothing.
534 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
535 lyxerr[Debug::GRAPHICS]
536 << "\ttemp_file: " << temp_file << endl;
537 if (file_has_changed || !IsFileReadable(temp_file)) {
538 bool const success = lyx::copy(orig_file, temp_file);
539 lyxerr[Debug::GRAPHICS]
540 << "\tCopying zipped file from "
541 << orig_file << " to " << temp_file
542 << (success ? " succeeded\n" : " failed\n");
544 lyxerr[Debug::GRAPHICS]
545 << "\tzipped file " << temp_file
546 << " exists! Maybe no tempdir ...\n";
547 orig_file = unzipFile(temp_file);
548 lyxerr[Debug::GRAPHICS]
549 << "\tunzipped to " << orig_file << endl;
552 string const from = getExtFromContents(orig_file);
553 string const to = findTargetFormat(from, runparams);
554 lyxerr[Debug::GRAPHICS]
555 << "\t we have: from " << from << " to " << to << '\n';
557 if (from == to && !lyxrc.use_tempdir) {
558 // No conversion is needed. LaTeX can handle the
559 // graphic file as is.
560 // This is true even if the orig_file is compressed.
561 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
562 return RemoveExtension(orig_file);
566 // We're going to be running the exported buffer through the LaTeX
567 // compiler, so must ensure that LaTeX can cope with the graphics
570 // Perform all these manipulations on a temporary file if possible.
571 // If we are not using a temp dir, then temp_file contains the
573 // to allow files with the same name in different dirs
574 // we manipulate the original file "any.dir/file.ext"
575 // to "any_dir_file.ext"! changing the dots in the
576 // dirname is important for the use of ChangeExtension
577 lyxerr[Debug::GRAPHICS]
578 << "\tthe orig file is: " << orig_file << endl;
580 if (lyxrc.use_tempdir) {
581 string const ext_tmp = GetExtension(orig_file);
584 ChangeExtension(orig_file, string()), "/", "_");
585 // without dots and again with ext
586 temp_file = ChangeExtension(
587 subst(temp_file, ".", "_"), ext_tmp);
588 // now we have any_dir_file.ext
589 temp_file = MakeAbsPath(temp_file, buf->tmppath);
590 lyxerr[Debug::GRAPHICS]
591 << "\tchanged to: " << temp_file << endl;
593 // if the file doen't exists, copy it into the tempdir
594 if (file_has_changed || !IsFileReadable(temp_file)) {
595 bool const success = lyx::copy(orig_file, temp_file);
596 lyxerr[Debug::GRAPHICS]
597 << "\tcopying from " << orig_file << " to "
599 << (success ? " succeeded\n" : " failed\n");
601 string str = bformat(_("Could not copy the file\n%1$s\n"
602 "into the temporary directory."), orig_file);
603 Alert::error(_("Graphics display failed"), str);
609 // No conversion is needed. LaTeX can handle the
610 // graphic file as is.
611 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
612 return RemoveExtension(temp_file);
617 string const outfile_base = RemoveExtension(temp_file);
618 lyxerr[Debug::GRAPHICS]
619 << "\tThe original file is " << orig_file << "\n"
620 << "\tA copy has been made and convert is to be called with:\n"
621 << "\tfile to convert = " << temp_file << '\n'
622 << "\toutfile_base = " << outfile_base << '\n'
623 << "\t from " << from << " to " << to << '\n';
625 // if no special converter defined, than we take the default one
626 // from ImageMagic: convert from:inname.from to:outname.to
627 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
628 string const command =
629 LibFileSearch("scripts", "convertDefault.sh") +
630 ' ' + from + ':' + temp_file + ' ' +
631 to + ':' + outfile_base + '.' + to;
632 lyxerr[Debug::GRAPHICS]
633 << "No converter defined! I use convertDefault.sh:\n\t"
636 one.startscript(Systemcall::Wait, command);
637 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
638 string str = bformat(_("No information for converting %1$s "
639 "format files to %2$s.\n"
640 "Try defining a convertor in the preferences."), from, to);
641 Alert::error(_("Could not convert image"), str);
645 return RemoveExtension(temp_file);
649 int InsetGraphics::latex(Buffer const * buf, ostream & os,
650 LatexRunParams const & runparams) const
652 // If there is no file specified or not existing,
653 // just output a message about it in the latex output.
654 lyxerr[Debug::GRAPHICS]
655 << "insetgraphics::latex: Filename = "
656 << params().filename << endl;
658 string const relative_file = MakeRelPath(params().filename, buf->filePath());
660 // A missing (e)ps-extension is no problem for LaTeX, so
661 // we have to test three different cases
662 #warning uh, but can our cache handle it ? no.
663 string const file_ = params().filename;
664 bool const file_exists =
666 (IsFileReadable(file_) || // original
667 IsFileReadable(file_ + ".eps") || // original.eps
668 IsFileReadable(file_ + ".ps")); // original.ps
669 string const message = file_exists ?
670 string() : string("bb = 0 0 200 100, draft, type=eps");
671 // if !message.empty() than there was no existing file
672 // "filename(.(e)ps)" found. In this case LaTeX
673 // draws only a rectangle with the above bb and the
674 // not found filename in it.
675 lyxerr[Debug::GRAPHICS]
676 << "\tMessage = \"" << message << '\"' << endl;
678 // These variables collect all the latex code that should be before and
679 // after the actual includegraphics command.
682 // Do we want subcaptions?
683 if (params().subcaption) {
684 before += "\\subfigure[" + params().subcaptionText + "]{";
687 // We never use the starred form, we use the "clip" option instead.
688 before += "\\includegraphics";
690 // Write the options if there are any.
691 string const opts = createLatexOptions();
692 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
694 if (!opts.empty() && !message.empty())
695 before += ("[%\n" + opts + ',' + message + ']');
696 else if (!opts.empty() || !message.empty())
697 before += ("[%\n" + opts + message + ']');
699 lyxerr[Debug::GRAPHICS]
700 << "\tBefore = " << before
701 << "\n\tafter = " << after << endl;
704 // "nice" means that the buffer is exported to LaTeX format but not
705 // run through the LaTeX compiler.
706 if (runparams.nice) {
707 os << before <<'{' << relative_file << '}' << after;
711 // Make the filename relative to the lyx file
712 // and remove the extension so the LaTeX will use whatever is
713 // appropriate (when there are several versions in different formats)
714 string const latex_str = message.empty() ?
715 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
716 (before + '{' + relative_file + " not found!}" + after);
719 // Return how many newlines we issued.
720 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
724 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
726 // No graphics in ascii output. Possible to use gifscii to convert
727 // images to ascii approximation.
728 // 1. Convert file to ascii using gifscii
729 // 2. Read ascii output file and add it to the output stream.
730 // at least we send the filename
731 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
736 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
738 // No graphics in LinuxDoc output. Should check how/what to add.
743 // For explanation on inserting graphics into DocBook checkout:
744 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
745 // See also the docbook guide at http://www.docbook.org/
746 int InsetGraphics::docbook(Buffer const *, ostream & os,
747 bool /*mixcont*/) const
749 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
750 // need to switch to MediaObject. However, for now this is sufficient and
752 os << "<graphic fileref=\"&" << graphic_label << ";\">";
757 void InsetGraphics::validate(LaTeXFeatures & features) const
759 // If we have no image, we should not require anything.
760 if (params().filename.empty())
763 features.includeFile(graphic_label, RemoveExtension(params().filename));
765 features.require("graphicx");
767 if (params().subcaption)
768 features.require("subfigure");
772 void InsetGraphics::statusChanged()
774 if (!cache_->view.expired())
775 cache_->view.lock()->updateInset(this);
779 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
781 // If nothing is changed, just return and say so.
782 if (params() == p && !p.filename.empty())
785 // Copy the new parameters.
788 // Update the inset with the new parameters.
789 cache_->update(params().filename);
791 // We have changed data, report it.
796 InsetGraphicsParams const & InsetGraphics::params() const
802 string const InsetGraphicsMailer::name_("graphics");
804 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
809 string const InsetGraphicsMailer::inset2string() const
811 return params2string(inset_.params());
815 void InsetGraphicsMailer::string2params(string const & in,
816 InsetGraphicsParams & params)
818 params = InsetGraphicsParams();
823 istringstream data(STRCONV(in));
829 string const token = lex.getString();
836 #warning FIXME not setting bufpath is dubious
837 inset.readInsetGraphics(lex, string());
838 params = inset.params();
844 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
847 data << name_ << ' ';
848 #warning FIXME not setting bufpath is dubious
849 params.Write(data, string());
850 data << "\\end_inset\n";
851 return STRCONV(data.str());