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 Inset * InsetGraphics::clone(Buffer const & buffer) const
207 return new InsetGraphics(*this, buffer.filePath());
211 InsetGraphics::~InsetGraphics()
213 InsetGraphicsMailer mailer(*this);
218 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
220 switch (cmd.action) {
221 case LFUN_INSET_MODIFY: {
222 InsetGraphicsParams p;
223 InsetGraphicsMailer::string2params(cmd.argument, p);
224 if (!p.filename.empty()) {
225 string const filepath = cmd.view()->buffer()->filePath();
226 setParams(p, filepath);
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::dimension(BufferView *, LyXFont const & font,
289 Dimension & dim) const
291 cache_->old_ascent = 50;
292 if (imageIsDrawable())
293 cache_->old_ascent = cache_->loader.image()->getHeight();
294 dim.asc = cache_->old_ascent;
296 if (imageIsDrawable())
297 dim.wid = cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
301 LyXFont msgFont(font);
302 msgFont.setFamily(LyXFont::SANS_FAMILY);
304 string const justname = OnlyFilename(params().filename);
305 if (!justname.empty()) {
306 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
307 font_width = font_metrics::width(justname, msgFont);
310 string const msg = statusMessage();
312 msgFont.setSize(LyXFont::SIZE_TINY);
313 font_width = std::max(font_width, font_metrics::width(msg, msgFont));
316 dim.wid = std::max(50, font_width + 15);
321 BufferView * InsetGraphics::view() const
323 return cache_->view.lock().get();
327 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
328 int baseline, float & x) const
330 // MakeAbsPath returns params().filename unchanged if it absolute
332 string const file_with_path =
333 MakeAbsPath(params().filename, bv->buffer()->filePath());
335 // A 'paste' operation creates a new inset with the correct filepath,
336 // but then the 'old' inset stored in the 'copy' operation is actually
337 // added to the buffer.
338 // Thus, we should ensure that the filepath is correct.
339 if (file_with_path != cache_->loader.filename())
340 cache_->update(file_with_path);
342 cache_->view = bv->owner()->view();
343 int oasc = cache_->old_ascent;
345 int ldescent = descent(bv, font);
346 int lascent = ascent(bv, font);
347 int lwidth = width(bv, font);
349 // we may have changed while someone other was drawing us so better
350 // to not draw anything as we surely call to redraw ourself soon.
351 // This is not a nice thing to do and should be fixed properly somehow.
352 // But I still don't know the best way to go. So let's do this like this
353 // for now (Jug 20020311)
357 // Make sure now that x is updated upon exit from this routine
361 grfx::Params const & gparams = params().as_grfxParams();
363 if (gparams.display != grfx::NoDisplay &&
364 cache_->loader.status() == grfx::WaitingToLoad)
365 cache_->loader.startLoading();
367 if (!cache_->loader.monitoring())
368 cache_->loader.startMonitoring();
370 // This will draw the graphics. If the graphics has not been loaded yet,
371 // we draw just a rectangle.
372 Painter & paint = bv->painter();
374 if (imageIsDrawable()) {
375 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
376 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
377 *cache_->loader.image());
381 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
382 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
384 // Print the file name.
385 LyXFont msgFont(font);
386 msgFont.setFamily(LyXFont::SANS_FAMILY);
387 string const justname = OnlyFilename (params().filename);
388 if (!justname.empty()) {
389 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
390 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
391 baseline - font_metrics::maxAscent(msgFont) - 4,
395 // Print the message.
396 string const msg = statusMessage();
398 msgFont.setSize(LyXFont::SIZE_TINY);
399 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
405 Inset::EDITABLE InsetGraphics::editable() const
411 void InsetGraphics::write(Buffer const *, ostream & os) const
418 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
420 string const token = lex.getString();
422 if (token == "Graphics")
423 readInsetGraphics(lex);
425 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
427 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
431 void InsetGraphics::readInsetGraphics(LyXLex & lex)
433 bool finished = false;
435 while (lex.isOK() && !finished) {
438 string const token = lex.getString();
439 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
444 } else if (token == "\\end_inset") {
446 } else if (token == "FormatVersion") {
448 int version = lex.getInteger();
449 if (version > VersionNumber)
451 << "This document was created with a newer Graphics widget"
452 ", You should use a newer version of LyX to read this"
455 // TODO: Possibly open up a dialog?
458 if (! params_.Read(lex, token))
459 lyxerr << "Unknown token, " << token << ", skipping."
466 string const InsetGraphics::createLatexOptions() const
468 // Calculate the options part of the command, we must do it to a string
469 // stream since we might have a trailing comma that we would like to remove
470 // before writing it to the output stream.
471 ostringstream options;
472 if (!params().bb.empty())
473 options << " bb=" << rtrim(params().bb) << ",\n";
475 options << " draft,\n";
477 options << " clip,\n";
478 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
479 if (!lyx::float_equal(params().scale, 100.0, 0.05))
480 options << " scale=" << params().scale / 100.0
483 if (!params().width.zero())
484 options << " width=" << params().width.asLatexString() << ",\n";
485 if (!params().height.zero())
486 options << " height=" << params().height.asLatexString() << ",\n";
487 if (params().keepAspectRatio)
488 options << " keepaspectratio,\n";
491 // Make sure rotation angle is not very close to zero;
492 // a float can be effectively zero but not exactly zero.
493 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
494 options << " angle=" << params().rotateAngle << ",\n";
495 if (!params().rotateOrigin.empty()) {
496 options << " origin=" << params().rotateOrigin[0];
497 if (contains(params().rotateOrigin,"Top"))
499 else if (contains(params().rotateOrigin,"Bottom"))
501 else if (contains(params().rotateOrigin,"Baseline"))
507 if (!params().special.empty())
508 options << params().special << ",\n";
510 string opts = STRCONV(options.str());
512 return opts.substr(0, opts.size() - 2);
516 string const InsetGraphics::prepareFile(Buffer const * buf,
517 LatexRunParams const & runparams) const
519 // LaTeX can cope if the graphics file doesn't exist, so just return the
521 string const orig_file = params().filename;
522 string orig_file_with_path =
523 MakeAbsPath(orig_file, buf->filePath());
524 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
525 << orig_file << "\n\twith path: "
526 << orig_file_with_path << endl;
528 if (!IsFileReadable(orig_file_with_path))
531 bool const zipped = zippedFile(orig_file_with_path);
533 // If the file is compressed and we have specified that it
534 // should not be uncompressed, then just return its name and
535 // let LaTeX do the rest!
536 if (zipped && params().noUnzip) {
537 lyxerr[Debug::GRAPHICS]
538 << "\tpass zipped file to LaTeX but with full path.\n";
539 // LaTeX needs an absolue path, otherwise the
540 // coresponding *.eps.bb file isn't found
541 return orig_file_with_path;
544 // Ascertain whether the file has changed.
545 unsigned long const new_checksum = cache_->loader.checksum();
546 bool const file_has_changed = cache_->checksum != new_checksum;
547 if (file_has_changed)
548 cache_->checksum = new_checksum;
550 // temp_file will contain the file for LaTeX to act on if, for example,
551 // we move it to a temp dir or uncompress it.
552 string temp_file = orig_file;
555 // Uncompress the file if necessary.
556 // If it has been uncompressed in a previous call to
557 // prepareFile, do nothing.
558 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
559 lyxerr[Debug::GRAPHICS]
560 << "\ttemp_file: " << temp_file << endl;
561 if (file_has_changed || !IsFileReadable(temp_file)) {
562 bool const success = lyx::copy(orig_file_with_path,
564 lyxerr[Debug::GRAPHICS]
565 << "\tCopying zipped file from "
566 << orig_file_with_path << " to " << temp_file
567 << (success ? " succeeded\n" : " failed\n");
569 lyxerr[Debug::GRAPHICS]
570 << "\tzipped file " << temp_file
571 << " exists! Maybe no tempdir ...\n";
572 orig_file_with_path = unzipFile(temp_file);
573 lyxerr[Debug::GRAPHICS]
574 << "\tunzipped to " << orig_file_with_path << endl;
577 string const from = getExtFromContents(orig_file_with_path);
578 string const to = findTargetFormat(from, runparams);
579 lyxerr[Debug::GRAPHICS]
580 << "\t we have: from " << from << " to " << to << '\n';
582 if (from == to && !lyxrc.use_tempdir) {
583 // No conversion is needed. LaTeX can handle the
584 // graphic file as is.
585 // This is true even if the orig_file is compressed.
586 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
587 return RemoveExtension(orig_file_with_path);
588 return orig_file_with_path;
591 // We're going to be running the exported buffer through the LaTeX
592 // compiler, so must ensure that LaTeX can cope with the graphics
595 // Perform all these manipulations on a temporary file if possible.
596 // If we are not using a temp dir, then temp_file contains the
598 // to allow files with the same name in different dirs
599 // we manipulate the original file "any.dir/file.ext"
600 // to "any_dir_file.ext"! changing the dots in the
601 // dirname is important for the use of ChangeExtension
602 lyxerr[Debug::GRAPHICS]
603 << "\tthe orig file is: " << orig_file_with_path << endl;
605 if (lyxrc.use_tempdir) {
606 string const ext_tmp = GetExtension(orig_file_with_path);
609 ChangeExtension(orig_file_with_path, string()), "/", "_");
610 // without dots and again with ext
611 temp_file = ChangeExtension(
612 subst(temp_file, ".", "_"), ext_tmp);
613 // now we have any_dir_file.ext
614 temp_file = MakeAbsPath(temp_file, buf->tmppath);
615 lyxerr[Debug::GRAPHICS]
616 << "\tchanged to: " << temp_file << endl;
618 // if the file doen't exists, copy it into the tempdir
619 if (file_has_changed || !IsFileReadable(temp_file)) {
620 bool const success = lyx::copy(orig_file_with_path, temp_file);
621 lyxerr[Debug::GRAPHICS]
622 << "\tcopying from " << orig_file_with_path << " to "
624 << (success ? " succeeded\n" : " failed\n");
626 string str = bformat(_("Could not copy the file\n%1$s\n"
627 "into the temporary directory."), orig_file_with_path);
628 Alert::error(_("Graphics display failed"), str);
634 // No conversion is needed. LaTeX can handle the
635 // graphic file as is.
636 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
637 return RemoveExtension(temp_file);
642 string const outfile_base = RemoveExtension(temp_file);
643 lyxerr[Debug::GRAPHICS]
644 << "\tThe original file is " << orig_file << "\n"
645 << "\tA copy has been made and convert is to be called with:\n"
646 << "\tfile to convert = " << temp_file << '\n'
647 << "\toutfile_base = " << outfile_base << '\n'
648 << "\t from " << from << " to " << to << '\n';
650 // if no special converter defined, than we take the default one
651 // from ImageMagic: convert from:inname.from to:outname.to
652 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
653 string const command =
654 LibFileSearch("scripts", "convertDefault.sh") +
655 ' ' + from + ':' + temp_file + ' ' +
656 to + ':' + outfile_base + '.' + to;
657 lyxerr[Debug::GRAPHICS]
658 << "No converter defined! I use convertDefault.sh:\n\t"
661 one.startscript(Systemcall::Wait, command);
662 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
663 string str = bformat(_("No information for converting %1$s "
664 "format files to %2$s.\n"
665 "Try defining a convertor in the preferences."), from, to);
666 Alert::error(_("Could not convert image"), str);
670 return RemoveExtension(temp_file);
674 int InsetGraphics::latex(Buffer const * buf, ostream & os,
675 LatexRunParams const & runparams) const
677 // If there is no file specified or not existing,
678 // just output a message about it in the latex output.
679 lyxerr[Debug::GRAPHICS]
680 << "insetgraphics::latex: Filename = "
681 << params().filename << endl;
683 // A missing (e)ps-extension is no problem for LaTeX, so
684 // we have to test three different cases
685 string const file_ = MakeAbsPath(params().filename, buf->filePath());
686 bool const file_exists =
688 (IsFileReadable(file_) || // original
689 IsFileReadable(file_ + ".eps") || // original.eps
690 IsFileReadable(file_ + ".ps")); // original.ps
691 string const message = file_exists ?
692 string() : string("bb = 0 0 200 100, draft, type=eps");
693 // if !message.empty() than there was no existing file
694 // "filename(.(e)ps)" found. In this case LaTeX
695 // draws only a rectangle with the above bb and the
696 // not found filename in it.
697 lyxerr[Debug::GRAPHICS]
698 << "\tMessage = \"" << message << '\"' << endl;
700 // These variables collect all the latex code that should be before and
701 // after the actual includegraphics command.
704 // Do we want subcaptions?
705 if (params().subcaption) {
706 before += "\\subfigure[" + params().subcaptionText + "]{";
709 // We never use the starred form, we use the "clip" option instead.
710 before += "\\includegraphics";
712 // Write the options if there are any.
713 string const opts = createLatexOptions();
714 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
716 if (!opts.empty() && !message.empty())
717 before += ("[%\n" + opts + ',' + message + ']');
718 else if (!opts.empty() || !message.empty())
719 before += ("[%\n" + opts + message + ']');
721 lyxerr[Debug::GRAPHICS]
722 << "\tBefore = " << before
723 << "\n\tafter = " << after << endl;
726 // "nice" means that the buffer is exported to LaTeX format but not
727 // run through the LaTeX compiler.
728 if (runparams.nice) {
729 os << before <<'{' << params().filename << '}' << after;
733 // Make the filename relative to the lyx file
734 // and remove the extension so the LaTeX will use whatever is
735 // appropriate (when there are several versions in different formats)
736 string const latex_str = message.empty() ?
737 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
738 (before + '{' + params().filename + " not found!}" + after);
741 // Return how many newlines we issued.
742 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
746 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
748 // No graphics in ascii output. Possible to use gifscii to convert
749 // images to ascii approximation.
750 // 1. Convert file to ascii using gifscii
751 // 2. Read ascii output file and add it to the output stream.
752 // at least we send the filename
753 os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
758 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
760 // No graphics in LinuxDoc output. Should check how/what to add.
765 // For explanation on inserting graphics into DocBook checkout:
766 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
767 // See also the docbook guide at http://www.docbook.org/
768 int InsetGraphics::docbook(Buffer const *, ostream & os,
769 bool /*mixcont*/) const
771 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
772 // need to switch to MediaObject. However, for now this is sufficient and
774 os << "<graphic fileref=\"&" << graphic_label << ";\">";
779 void InsetGraphics::validate(LaTeXFeatures & features) const
781 // If we have no image, we should not require anything.
782 if (params().filename.empty())
785 features.includeFile(graphic_label, RemoveExtension(params().filename));
787 features.require("graphicx");
789 if (params().subcaption)
790 features.require("subfigure");
794 void InsetGraphics::statusChanged()
796 if (!cache_->view.expired())
797 cache_->view.lock()->updateInset(this);
801 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
802 string const & filepath)
804 // If nothing is changed, just return and say so.
805 if (params() == p && !p.filename.empty())
808 // Copy the new parameters.
811 // Update the inset with the new parameters.
812 cache_->update(MakeAbsPath(params().filename, filepath));
814 // We have changed data, report it.
819 InsetGraphicsParams const & InsetGraphics::params() const
825 string const InsetGraphicsMailer::name_("graphics");
827 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
832 string const InsetGraphicsMailer::inset2string() const
834 return params2string(inset_.params());
838 void InsetGraphicsMailer::string2params(string const & in,
839 InsetGraphicsParams & params)
841 params = InsetGraphicsParams();
846 istringstream data(STRCONV(in));
852 string const token = lex.getString();
859 inset.readInsetGraphics(lex);
860 params = inset.params();
866 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
869 data << name_ << ' ';
871 data << "\\end_inset\n";
872 return STRCONV(data.str());