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"
68 #include "frontends/Painter.h"
70 #include "frontends/font_metrics.h"
73 #include "LaTeXFeatures.h"
76 #include "frontends/Alert.h"
77 #include "frontends/Dialogs.h"
78 #include "frontends/LyXView.h"
80 #include "frontends/controllers/helper_funcs.h" // getVectorFromString
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 "BoostFormat.h"
95 #include <algorithm> // For the std::max
97 extern string system_tempdir;
105 ///////////////////////////////////////////////////////////////////////////
106 int const VersionNumber = 1;
107 ///////////////////////////////////////////////////////////////////////////
109 // This function is a utility function
110 // ... that should be with ChangeExtension ...
112 string const RemoveExtension(string const & filename)
114 return ChangeExtension(filename, string());
118 string const uniqueID()
120 static unsigned int seed = 1000;
123 ost << "graph" << ++seed;
125 // Needed if we use lyxstring.
126 return STRCONV(ost.str());
130 string findTargetFormat(string const & suffix)
132 // lyxrc.pdf_mode means:
133 // Are we creating a PDF or a PS file?
134 // (Should actually mean, are we using latex or pdflatex).
135 if (lyxrc.pdf_mode) {
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 // Emits the hide signal to the dialog connected (if any)
221 string const InsetGraphics::statusMessage() const
223 using namespace grfx;
225 switch (cache_->loader.status()) {
227 return _("Not shown.");
229 return _("Loading...");
231 return _("Converting to loadable format...");
233 return _("Loaded into memory. Must now generate pixmap.");
235 return _("Scaling etc...");
237 return _("Ready to display");
239 return _("No file found!");
240 case ErrorConverting:
241 return _("Error converting to loadable format");
243 return _("Error loading file into memory");
244 case ErrorGeneratingPixmap:
245 return _("Error generating the pixmap");
247 return _("No image");
253 bool InsetGraphics::imageIsDrawable() const
255 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
258 return cache_->loader.image()->isDrawable();
262 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
264 cache_->old_ascent = 50;
265 if (imageIsDrawable())
266 cache_->old_ascent = cache_->loader.image()->getHeight();
267 return cache_->old_ascent;
271 int InsetGraphics::descent(BufferView *, LyXFont const &) const
277 int InsetGraphics::width(BufferView *, LyXFont const & font) const
279 if (imageIsDrawable())
280 return cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
284 LyXFont msgFont(font);
285 msgFont.setFamily(LyXFont::SANS_FAMILY);
287 string const justname = OnlyFilename (params().filename);
288 if (!justname.empty()) {
289 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
290 font_width = font_metrics::width(justname, msgFont);
293 string const msg = statusMessage();
295 msgFont.setSize(LyXFont::SIZE_TINY);
296 int const msg_width = font_metrics::width(msg, msgFont);
297 font_width = std::max(font_width, msg_width);
300 return std::max(50, font_width + 15);
304 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
305 int baseline, float & x, bool) const
307 // MakeAbsPath returns params().filename unchanged if it absolute
309 string const file_with_path =
310 MakeAbsPath(params().filename, bv->buffer()->filePath());
312 // A 'paste' operation creates a new inset with the correct filepath,
313 // but then the 'old' inset stored in the 'copy' operation is actually
314 // added to the buffer.
315 // Thus, we should ensure that the filepath is correct.
316 if (file_with_path != cache_->loader.filename())
317 cache_->update(file_with_path);
319 cache_->view = bv->owner()->view();
320 int oasc = cache_->old_ascent;
322 int ldescent = descent(bv, font);
323 int lascent = ascent(bv, font);
324 int lwidth = width(bv, font);
326 // we may have changed while someone other was drawing us so better
327 // to not draw anything as we surely call to redraw ourself soon.
328 // This is not a nice thing to do and should be fixed properly somehow.
329 // But I still don't know the best way to go. So let's do this like this
330 // for now (Jug 20020311)
334 // Make sure now that x is updated upon exit from this routine
338 grfx::Params const & gparams = params().as_grfxParams();
340 if (gparams.display != grfx::NoDisplay &&
341 cache_->loader.status() == grfx::WaitingToLoad)
342 cache_->loader.startLoading();
344 if (!cache_->loader.monitoring())
345 cache_->loader.startMonitoring();
347 // This will draw the graphics. If the graphics has not been loaded yet,
348 // we draw just a rectangle.
349 Painter & paint = bv->painter();
351 if (imageIsDrawable()) {
352 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
353 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
354 *cache_->loader.image());
358 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
359 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
361 // Print the file name.
362 LyXFont msgFont(font);
363 msgFont.setFamily(LyXFont::SANS_FAMILY);
364 string const justname = OnlyFilename (params().filename);
365 if (!justname.empty()) {
366 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
367 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
368 baseline - font_metrics::maxAscent(msgFont) - 4,
372 // Print the message.
373 string const msg = statusMessage();
375 msgFont.setSize(LyXFont::SIZE_TINY);
376 paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
380 // the status message may mean we changed size, so indicate
381 // we need a row redraw
383 if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
384 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
388 // Reset the cache, ready for the next draw request
390 cached_status_ = grfx::ErrorUnknown;
391 cached_image_.reset();
392 cache_filled_ = false;
397 void InsetGraphics::edit(BufferView *bv, int, int, mouse_button::state)
399 bv->owner()->getDialogs().showGraphics(this);
403 void InsetGraphics::edit(BufferView * bv, bool)
405 edit(bv, 0, 0, mouse_button::none);
409 Inset::EDITABLE InsetGraphics::editable() const
415 void InsetGraphics::write(Buffer const *, ostream & os) const
422 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
424 string const token = lex.getString();
426 if (token == "Graphics")
427 readInsetGraphics(lex);
429 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
431 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
435 void InsetGraphics::readInsetGraphics(LyXLex & lex)
437 bool finished = false;
439 while (lex.isOK() && !finished) {
442 string const token = lex.getString();
443 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
448 } else if (token == "\\end_inset") {
450 } else if (token == "FormatVersion") {
452 int version = lex.getInteger();
453 if (version > VersionNumber)
455 << "This document was created with a newer Graphics widget"
456 ", You should use a newer version of LyX to read this"
459 // TODO: Possibly open up a dialog?
462 if (! params_.Read(lex, token))
463 lyxerr << "Unknown token, " << token << ", skipping."
470 string const InsetGraphics::createLatexOptions() const
472 // Calculate the options part of the command, we must do it to a string
473 // stream since we might have a trailing comma that we would like to remove
474 // before writing it to the output stream.
475 ostringstream options;
476 if (!params().bb.empty())
477 options << " bb=" << rtrim(params().bb) << ",\n";
479 options << " draft,\n";
481 options << " clip,\n";
482 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
483 if (!lyx::float_equal(params().scale, 100.0, 0.05))
484 options << " scale=" << params().scale / 100.0
487 if (!params().width.zero())
488 options << " width=" << params().width.asLatexString() << ",\n";
489 if (!params().height.zero())
490 options << " height=" << params().height.asLatexString() << ",\n";
491 if (params().keepAspectRatio)
492 options << " keepaspectratio,\n";
495 // Make sure rotation angle is not very close to zero;
496 // a float can be effectively zero but not exactly zero.
497 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
498 options << " angle=" << params().rotateAngle << ",\n";
499 if (!params().rotateOrigin.empty()) {
500 options << " origin=" << params().rotateOrigin[0];
501 if (contains(params().rotateOrigin,"Top"))
503 else if (contains(params().rotateOrigin,"Bottom"))
505 else if (contains(params().rotateOrigin,"Baseline"))
511 if (!params().special.empty())
512 options << params().special << ",\n";
514 string opts = STRCONV(options.str());
516 return opts.substr(0, opts.size() - 2);
520 string const InsetGraphics::prepareFile(Buffer const * buf) const
522 // LaTeX can cope if the graphics file doesn't exist, so just return the
524 string const orig_file = params().filename;
525 string orig_file_with_path =
526 MakeAbsPath(orig_file, buf->filePath());
527 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
528 << orig_file << "\n\twith path: "
529 << orig_file_with_path << endl;
531 if (!IsFileReadable(orig_file_with_path))
534 bool const zipped = zippedFile(orig_file_with_path);
536 // If the file is compressed and we have specified that it
537 // should not be uncompressed, then just return its name and
538 // let LaTeX do the rest!
539 if (zipped && params().noUnzip) {
540 lyxerr[Debug::GRAPHICS]
541 << "\tpass zipped file to LaTeX but with full path.\n";
542 // LaTeX needs an absolue path, otherwise the
543 // coresponding *.eps.bb file isn't found
544 return orig_file_with_path;
547 // Ascertain whether the file has changed.
548 unsigned long const new_checksum = cache_->loader.checksum();
549 bool const file_has_changed = cache_->checksum != new_checksum;
550 if (file_has_changed)
551 cache_->checksum = new_checksum;
553 // temp_file will contain the file for LaTeX to act on if, for example,
554 // we move it to a temp dir or uncompress it.
555 string temp_file = orig_file;
558 // Uncompress the file if necessary.
559 // If it has been uncompressed in a previous call to
560 // prepareFile, do nothing.
561 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
562 lyxerr[Debug::GRAPHICS]
563 << "\ttemp_file: " << temp_file << endl;
564 if (file_has_changed || !IsFileReadable(temp_file)) {
565 bool const success = lyx::copy(orig_file_with_path,
567 lyxerr[Debug::GRAPHICS]
568 << "\tCopying zipped file from "
569 << orig_file_with_path << " to " << temp_file
570 << (success ? " succeeded\n" : " failed\n");
572 lyxerr[Debug::GRAPHICS]
573 << "\tzipped file " << temp_file
574 << " exists! Maybe no tempdir ...\n";
575 orig_file_with_path = unzipFile(temp_file);
576 lyxerr[Debug::GRAPHICS]
577 << "\tunzipped to " << orig_file_with_path << endl;
580 string const from = getExtFromContents(orig_file_with_path);
581 string const to = findTargetFormat(from);
582 lyxerr[Debug::GRAPHICS]
583 << "\t we have: from " << from << " to " << to << '\n';
585 if (from == to && !lyxrc.use_tempdir) {
586 // No conversion is needed. LaTeX can handle the
587 // graphic file as is.
588 // This is true even if the orig_file is compressed.
589 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
590 return RemoveExtension(orig_file_with_path);
591 return orig_file_with_path;
594 // We're going to be running the exported buffer through the LaTeX
595 // compiler, so must ensure that LaTeX can cope with the graphics
598 // Perform all these manipulations on a temporary file if possible.
599 // If we are not using a temp dir, then temp_file contains the
601 // to allow files with the same name in different dirs
602 // we manipulate the original file "any.dir/file.ext"
603 // to "any_dir_file.ext"! changing the dots in the
604 // dirname is important for the use of ChangeExtension
605 lyxerr[Debug::GRAPHICS]
606 << "\tthe orig file is: " << orig_file_with_path << endl;
608 if (lyxrc.use_tempdir) {
609 string const ext_tmp = GetExtension(orig_file_with_path);
612 ChangeExtension(orig_file_with_path, string()), "/", "_");
613 // without dots and again with ext
614 temp_file = ChangeExtension(
615 subst(temp_file, ".", "_"), ext_tmp);
616 // now we have any_dir_file.ext
617 temp_file = MakeAbsPath(temp_file, buf->tmppath);
618 lyxerr[Debug::GRAPHICS]
619 << "\tchanged to: " << temp_file << endl;
621 // if the file doen't exists, copy it into the tempdir
622 if (file_has_changed || !IsFileReadable(temp_file)) {
623 bool const success = lyx::copy(orig_file_with_path, temp_file);
624 lyxerr[Debug::GRAPHICS]
625 << "\tcopying from " << orig_file_with_path << " to "
627 << (success ? " succeeded\n" : " failed\n");
629 Alert::alert(_("Cannot copy file"), orig_file_with_path,
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)))
666 Alert::alert(_("Cannot convert Image (not existing file?)"),
667 boost::io::str(boost::format(_("No information for converting from %1$s to %2$s"))
670 Alert::alert(_("Cannot convert Image (not existing file?)"),
671 _("No information for converting from ") + from + " to " + to);
675 return RemoveExtension(temp_file);
679 int InsetGraphics::latex(Buffer const * buf, ostream & os,
680 bool /*fragile*/, bool/*fs*/) const
682 // If there is no file specified or not existing,
683 // just output a message about it in the latex output.
684 lyxerr[Debug::GRAPHICS]
685 << "insetgraphics::latex: Filename = "
686 << params().filename << endl;
688 // A missing (e)ps-extension is no problem for LaTeX, so
689 // we have to test three different cases
690 string const file_ = MakeAbsPath(params().filename, buf->filePath());
691 bool const file_exists =
693 (IsFileReadable(file_) || // original
694 IsFileReadable(file_ + ".eps") || // original.eps
695 IsFileReadable(file_ + ".ps")); // original.ps
696 string const message = file_exists ?
697 string() : string("bb = 0 0 200 100, draft, type=eps");
698 // if !message.empty() than there was no existing file
699 // "filename(.(e)ps)" found. In this case LaTeX
700 // draws only a rectangle with the above bb and the
701 // not found filename in it.
702 lyxerr[Debug::GRAPHICS]
703 << "\tMessage = \"" << message << '\"' << endl;
705 // These variables collect all the latex code that should be before and
706 // after the actual includegraphics command.
709 // Do we want subcaptions?
710 if (params().subcaption) {
711 before += "\\subfigure[" + params().subcaptionText + "]{";
714 // We never use the starred form, we use the "clip" option instead.
715 before += "\\includegraphics";
717 // Write the options if there are any.
718 string const opts = createLatexOptions();
719 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
721 if (!opts.empty() && !message.empty())
722 before += ("[%\n" + opts + ',' + message + ']');
723 else if (!opts.empty() || !message.empty())
724 before += ("[%\n" + opts + message + ']');
726 lyxerr[Debug::GRAPHICS]
727 << "\tBefore = " << before
728 << "\n\tafter = " << after << endl;
731 // "nice" means that the buffer is exported to LaTeX format but not
732 // run through the LaTeX compiler.
734 os << before <<'{' << params().filename << '}' << after;
738 // Make the filename relative to the lyx file
739 // and remove the extension so the LaTeX will use whatever is
740 // appropriate (when there are several versions in different formats)
741 string const latex_str = message.empty() ?
742 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
743 (before + '{' + params().filename + " not found!}" + after);
746 // Return how many newlines we issued.
747 return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
751 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
753 // No graphics in ascii output. Possible to use gifscii to convert
754 // images to ascii approximation.
755 // 1. Convert file to ascii using gifscii
756 // 2. Read ascii output file and add it to the output stream.
757 // at least we send the filename
760 << boost::format(_("Graphics file: %1$s")) % params().filename
764 << _("Graphics file: ") << params().filename
771 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
773 // No graphics in LinuxDoc output. Should check how/what to add.
778 // For explanation on inserting graphics into DocBook checkout:
779 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
780 // See also the docbook guide at http://www.docbook.org/
781 int InsetGraphics::docbook(Buffer const *, ostream & os,
782 bool /*mixcont*/) const
784 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
785 // need to switch to MediaObject. However, for now this is sufficient and
787 os << "<graphic fileref=\"&" << graphic_label << ";\">";
792 void InsetGraphics::validate(LaTeXFeatures & features) const
794 // If we have no image, we should not require anything.
795 if (params().filename.empty())
798 features.includeFile(graphic_label, RemoveExtension(params().filename));
800 features.require("graphicx");
802 if (params().subcaption)
803 features.require("subfigure");
807 void InsetGraphics::statusChanged()
809 if (!cache_->view.expired())
810 cache_->view.lock()->updateInset(this, false);
814 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
815 string const & filepath)
817 // If nothing is changed, just return and say so.
818 if (params() == p && !p.filename.empty())
821 // Copy the new parameters.
824 // Update the inset with the new parameters.
825 cache_->update(MakeAbsPath(params().filename, filepath));
827 // We have changed data, report it.
832 InsetGraphicsParams const & InsetGraphics::params() const