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 * Keep a tab on the image file, if it changes, update the lyx view.
22 * The image choosing dialog could show thumbnails of the image formats
23 it knows of, thus selection based on the image instead of based on
25 * Add support for the 'picins' package.
26 * Add support for the 'picinpar' package.
27 * Improve support for 'subfigure' - Allow to set the various options
33 * Current version is 1 (inset file format version), when changing it
34 * it should be changed in the Write() function when writing in one place
35 * and when reading one should change the version check and the error message.
36 * The filename is kept in the lyx file in a relative way, so as to allow
37 * moving the document file and its images with no problem.
41 * Postscript output means EPS figures.
43 * PDF output is best done with PDF figures if it's a direct conversion
44 * or PNG figures otherwise.
57 #pragma implementation
60 #include "insets/insetgraphics.h"
61 #include "insets/insetgraphicsParams.h"
63 #include "graphics/GraphicsLoader.h"
64 #include "graphics/GraphicsImage.h"
65 #include "graphics/GraphicsParams.h"
69 #include "BufferView.h"
70 #include "converter.h"
71 #include "frontends/Painter.h"
73 #include "frontends/font_metrics.h"
76 #include "LaTeXFeatures.h"
79 #include "frontends/Alert.h"
80 #include "frontends/Dialogs.h"
81 #include "frontends/LyXView.h"
83 #include "frontends/controllers/helper_funcs.h" // getVectorFromString
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/systemcall.h"
91 #include "support/os.h"
93 #include <boost/weak_ptr.hpp>
94 #include <boost/bind.hpp>
95 #include <boost/signals/trackable.hpp>
97 #include <algorithm> // For the std::max
99 extern string system_tempdir;
104 ///////////////////////////////////////////////////////////////////////////
105 int const VersionNumber = 1;
106 ///////////////////////////////////////////////////////////////////////////
110 // This function is a utility function
111 // ... that should be with ChangeExtension ...
113 string const RemoveExtension(string const & filename)
115 return ChangeExtension(filename, string());
123 string const uniqueID()
125 static unsigned int seed = 1000;
128 ost << "graph" << ++seed;
130 // Needed if we use lyxstring.
131 return ost.str().c_str();
137 struct InsetGraphics::Cache : boost::signals::trackable
140 Cache(InsetGraphics &);
142 void update(string const & file_with_path);
149 unsigned long checksum;
151 boost::weak_ptr<BufferView> view;
155 InsetGraphics & parent_;
159 InsetGraphics::Cache::Cache(InsetGraphics & p)
160 : old_ascent(0), checksum(0), parent_(p)
162 loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
166 void InsetGraphics::Cache::update(string const & file_with_path)
168 lyx::Assert(!file_with_path.empty());
170 string const path = OnlyPath(file_with_path);
171 loader.reset(file_with_path, parent_.params().as_grfxParams(path));
175 InsetGraphics::InsetGraphics()
176 : graphic_label(uniqueID()),
177 cache_(new Cache(*this))
181 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
182 string const & filepath,
184 : Inset(ig, same_id),
185 graphic_label(uniqueID()),
186 cache_(new Cache(*this))
188 setParams(ig.params(), filepath);
192 InsetGraphics::~InsetGraphics()
194 // Emits the hide signal to the dialog connected (if any)
199 string const InsetGraphics::statusMessage() const
203 switch (cache_->loader.status()) {
204 case grfx::WaitingToLoad:
205 msg = _("Waiting for draw request to start loading...");
208 msg = _("Loading...");
210 case grfx::Converting:
211 msg = _("Converting to loadable format...");
214 msg = _("Loaded into memory. Must now generate pixmap.");
216 case grfx::ScalingEtc:
217 msg = _("Scaling etc...");
220 msg = _("Ready to display");
222 case grfx::ErrorNoFile:
223 msg = _("No file found!");
225 case grfx::ErrorConverting:
226 msg = _("Error converting to loadable format");
228 case grfx::ErrorLoading:
229 msg = _("Error loading file into memory");
231 case grfx::ErrorGeneratingPixmap:
232 msg = _("Error generating the pixmap");
234 case grfx::ErrorUnknown:
243 bool InsetGraphics::imageIsDrawable() const
245 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
248 return cache_->loader.image()->isDrawable();
252 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
254 cache_->old_ascent = 50;
255 if (imageIsDrawable())
256 cache_->old_ascent = cache_->loader.image()->getHeight();
257 return cache_->old_ascent;
261 int InsetGraphics::descent(BufferView *, LyXFont const &) const
267 int InsetGraphics::width(BufferView *, LyXFont const & font) const
269 if (imageIsDrawable())
270 return cache_->loader.image()->getWidth();
274 LyXFont msgFont(font);
275 msgFont.setFamily(LyXFont::SANS_FAMILY);
277 string const justname = OnlyFilename (params().filename);
278 if (!justname.empty()) {
279 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
280 font_width = font_metrics::width(justname, msgFont);
283 string const msg = statusMessage();
285 msgFont.setSize(LyXFont::SIZE_TINY);
286 int const msg_width = font_metrics::width(msg, msgFont);
287 font_width = std::max(font_width, msg_width);
290 return std::max(50, font_width + 15);
295 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
296 int baseline, float & x, bool) const
298 // MakeAbsPath returns params().filename unchanged if it absolute
300 string const file_with_path =
301 MakeAbsPath(params().filename, bv->buffer()->filePath());
303 // A 'paste' operation creates a new inset with the correct filepath,
304 // but then the 'old' inset stored in the 'copy' operation is actually
305 // added to the buffer.
306 // Thus, we should ensure that the filepath is correct.
307 if (file_with_path != cache_->loader.filename())
308 cache_->update(file_with_path);
310 cache_->view = bv->owner()->view();
311 int oasc = cache_->old_ascent;
313 int ldescent = descent(bv, font);
314 int lascent = ascent(bv, font);
315 int lwidth = width(bv, font);
317 // we may have changed while someone other was drawing us so better
318 // to not draw anything as we surely call to redraw ourself soon.
319 // This is not a nice thing to do and should be fixed properly somehow.
320 // But I still don't know the best way to go. So let's do this like this
321 // for now (Jug 20020311)
322 if (lascent != oasc) {
326 // Make sure now that x is updated upon exit from this routine
330 if (cache_->loader.status() == grfx::WaitingToLoad)
331 cache_->loader.startLoading(*this, *bv);
333 if (!cache_->loader.monitoring())
334 cache_->loader.startMonitoring();
336 // This will draw the graphics. If the graphics has not been loaded yet,
337 // we draw just a rectangle.
338 Painter & paint = bv->painter();
340 if (imageIsDrawable()) {
341 paint.image(old_x + 2, baseline - lascent,
342 lwidth - 4, lascent + ldescent,
343 *cache_->loader.image());
347 paint.rectangle(old_x + 2, baseline - lascent,
351 // Print the file name.
352 LyXFont msgFont(font);
353 msgFont.setFamily(LyXFont::SANS_FAMILY);
354 string const justname = OnlyFilename (params().filename);
355 if (!justname.empty()) {
356 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
357 paint.text(old_x + 8,
358 baseline - font_metrics::maxAscent(msgFont) - 4,
362 // Print the message.
363 string const msg = statusMessage();
365 msgFont.setSize(LyXFont::SIZE_TINY);
366 paint.text(old_x + 8, baseline - 4, msg, msgFont);
370 // the status message may mean we changed size, so indicate
371 // we need a row redraw
373 if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
374 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
378 // Reset the cache, ready for the next draw request
380 cached_status_ = grfx::ErrorUnknown;
381 cached_image_.reset();
382 cache_filled_ = false;
387 void InsetGraphics::edit(BufferView *bv, int, int, mouse_button::state)
389 bv->owner()->getDialogs().showGraphics(this);
393 void InsetGraphics::edit(BufferView * bv, bool)
395 edit(bv, 0, 0, mouse_button::none);
399 Inset::EDITABLE InsetGraphics::editable() const
405 void InsetGraphics::write(Buffer const *, ostream & os) const
412 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
414 string const token = lex.getString();
416 if (token == "Graphics")
417 readInsetGraphics(lex);
419 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
421 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
425 void InsetGraphics::readInsetGraphics(LyXLex & lex)
427 bool finished = false;
429 while (lex.isOK() && !finished) {
432 string const token = lex.getString();
433 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
438 } else if (token == "\\end_inset") {
440 } else if (token == "FormatVersion") {
442 int version = lex.getInteger();
443 if (version > VersionNumber)
445 << "This document was created with a newer Graphics widget"
446 ", You should use a newer version of LyX to read this"
449 // TODO: Possibly open up a dialog?
452 if (! params_.Read(lex, token))
453 lyxerr << "Unknown token, " << token << ", skipping."
460 string const InsetGraphics::createLatexOptions() const
462 // Calculate the options part of the command, we must do it to a string
463 // stream since we might have a trailing comma that we would like to remove
464 // before writing it to the output stream.
465 ostringstream options;
466 if (!params().bb.empty())
467 options << " bb=" << rtrim(params().bb) << ",\n";
469 options << " draft,\n";
471 options << " clip,\n";
473 if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
474 if (!lyx::float_equal(params().scale, 100.0, 0.05))
475 options << " scale=" << params().scale / 100.0
478 if (!params().width.zero())
479 options << " width=" << params().width.asLatexString() << ",\n";
480 if (!params().height.zero())
481 options << " height=" << params().height.asLatexString() << ",\n";
482 if (params().keepAspectRatio)
483 options << " keepaspectratio,\n";
486 // Make sure rotation angle is not very close to zero;
487 // a float can be effectively zero but not exactly zero.
488 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
489 options << " angle=" << params().rotateAngle << ",\n";
490 if (!params().rotateOrigin.empty()) {
491 options << " origin=" << params().rotateOrigin[0];
492 if (contains(params().rotateOrigin,"Top"))
494 else if (contains(params().rotateOrigin,"Bottom"))
496 else if (contains(params().rotateOrigin,"Baseline"))
502 if (!params().special.empty())
503 options << params().special << ",\n";
505 string opts = options.str().c_str();
506 return opts.substr(0,opts.size()-2); // delete last ",\n"
510 string findTargetFormat(string const & suffix)
512 // lyxrc.pdf_mode means:
513 // Are we creating a PDF or a PS file?
514 // (Should actually mean, are we using latex or pdflatex).
515 if (lyxrc.pdf_mode) {
516 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
517 if (contains(suffix, "ps") || suffix == "pdf")
519 else if (suffix == "jpg") // pdflatex can use jpeg
522 return "png"; // and also png
524 // If it's postscript, we always do eps.
525 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
526 if (suffix != "ps") // any other than ps
527 return "eps"; // is changed to eps
529 return suffix; // let ps untouched
535 string const InsetGraphics::prepareFile(Buffer const *buf) const
537 // LaTeX can cope if the graphics file doesn't exist, so just return the
539 string const orig_file = params().filename;
540 string orig_file_with_path =
541 MakeAbsPath(orig_file, buf->filePath());
542 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
543 << orig_file << "\n\twith path: "
544 << orig_file_with_path << endl;
546 if (!IsFileReadable(orig_file_with_path))
549 bool const zipped = zippedFile(orig_file_with_path);
551 // If the file is compressed and we have specified that it
552 // should not be uncompressed, then just return its name and
553 // let LaTeX do the rest!
554 if (zipped && params().noUnzip) {
555 lyxerr[Debug::GRAPHICS]
556 << "\tpass zipped file to LaTeX but with full path.\n";
557 // LaTeX needs an absolue path, otherwise the
558 // coresponding *.eps.bb file isn't found
559 return orig_file_with_path;
562 // Ascertain whether the file has changed.
563 unsigned long const new_checksum = cache_->loader.checksum();
564 bool const file_has_changed = cache_->checksum != new_checksum;
565 if (file_has_changed)
566 cache_->checksum = new_checksum;
568 // temp_file will contain the file for LaTeX to act on if, for example,
569 // we move it to a temp dir or uncompress it.
570 string temp_file(orig_file);
573 // Uncompress the file if necessary.
574 // If it has been uncompressed in a previous call to
575 // prepareFile, do nothing.
576 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
577 lyxerr[Debug::GRAPHICS]
578 << "\ttemp_file: " << temp_file << endl;
579 if (file_has_changed || !IsFileReadable(temp_file)) {
580 bool const success = lyx::copy(orig_file_with_path,
582 lyxerr[Debug::GRAPHICS]
583 << "\tCopying zipped file from "
584 << orig_file_with_path << " to " << temp_file
585 << (success ? " succeeded\n" : " failed\n");
587 lyxerr[Debug::GRAPHICS]
588 << "\tzipped file " << temp_file
589 << " exists! Maybe no tempdir ...\n";
590 orig_file_with_path = unzipFile(temp_file);
591 lyxerr[Debug::GRAPHICS]
592 << "\tunzipped to " << orig_file_with_path << endl;
595 string const from = getExtFromContents(orig_file_with_path);
596 string const to = findTargetFormat(from);
597 lyxerr[Debug::GRAPHICS]
598 << "\t we have: from " << from << " to " << to << '\n';
600 if (from == to && !lyxrc.use_tempdir)
601 // No conversion is needed. LaTeX can handle the
602 // graphic file as is.
603 // This is true even if the orig_file is compressed.
604 return RemoveExtension(orig_file_with_path);
606 // We're going to be running the exported buffer through the LaTeX
607 // compiler, so must ensure that LaTeX can cope with the graphics
610 // Perform all these manipulations on a temporary file if possible.
611 // If we are not using a temp dir, then temp_file contains the
613 // to allow files with the same name in different dirs
614 // we manipulate the original file "any.dir/file.ext"
615 // to "any_dir_file.ext"! changing the dots in the
616 // dirname is important for the use of ChangeExtension
617 lyxerr[Debug::GRAPHICS]
618 << "\tthe orig file is: " << orig_file_with_path << endl;
620 if (lyxrc.use_tempdir) {
621 string const ext_tmp = GetExtension(orig_file_with_path);
624 ChangeExtension(orig_file_with_path, string()), "/", "_");
625 // without dots and again with ext
626 temp_file = ChangeExtension(
627 subst(temp_file, ".", "_"), ext_tmp);
628 // now we have any_dir_file.ext
629 temp_file = MakeAbsPath(temp_file, buf->tmppath);
630 lyxerr[Debug::GRAPHICS]
631 << "\tchanged to: " << temp_file << endl;
633 // if the file doen't exists, copy it into the tempdir
634 if (file_has_changed || !IsFileReadable(temp_file)) {
635 bool const success = lyx::copy(orig_file_with_path, temp_file);
636 lyxerr[Debug::GRAPHICS]
637 << "\tcopying from " << orig_file_with_path << " to "
639 << (success ? " succeeded\n" : " failed\n");
641 Alert::alert(_("Cannot copy file"), orig_file_with_path,
648 // No conversion is needed. LaTeX can handle the
649 // graphic file as is.
650 return RemoveExtension(temp_file);
653 string const outfile_base = RemoveExtension(temp_file);
654 lyxerr[Debug::GRAPHICS]
655 << "\tThe original file is " << orig_file << "\n"
656 << "\tA copy has been made and convert is to be called with:\n"
657 << "\tfile to convert = " << temp_file << '\n'
658 << "\toutfile_base = " << outfile_base << '\n'
659 << "\t from " << from << " to " << to << '\n';
661 // if no special converter defined, than we take the default one
662 // from ImageMagic: convert from:inname.from to:outname.to
663 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
664 string const command =
665 LibFileSearch("scripts", "convertDefault.sh") +
666 ' ' + from + ':' + temp_file + ' ' +
667 to + ':' + outfile_base + '.' + to;
668 lyxerr[Debug::GRAPHICS]
669 << "No converter defined! I use convertDefault.sh:\n\t"
672 one.startscript(Systemcall::Wait, command);
673 if (!IsFileReadable(ChangeExtension(outfile_base, to)))
674 Alert::alert(_("Cannot convert Image (not existing file?)"),
675 _("No information for converting from ")
676 + from + _(" to ") + to);
679 return RemoveExtension(temp_file);
683 int InsetGraphics::latex(Buffer const *buf, ostream & os,
684 bool /*fragile*/, bool/*fs*/) const
686 // If there is no file specified or not existing,
687 // just output a message about it in the latex output.
688 lyxerr[Debug::GRAPHICS]
689 << "insetgraphics::latex: Filename = "
690 << params().filename << endl;
692 // A missing (e)ps-extension is no problem for LaTeX, so
693 // we have to test three different cases
694 string const file_(MakeAbsPath(params().filename, buf->filePath()));
695 bool const file_exists =
697 (IsFileReadable(file_) || // original
698 IsFileReadable(file_ + ".eps") || // original.eps
699 IsFileReadable(file_ + ".ps")); // original.ps
700 string const message = file_exists ?
701 string() : string("bb = 0 0 200 100, draft, type=eps");
702 // if !message.empty() than there was no existing file
703 // "filename(.(e)ps)" found. In this case LaTeX
704 // draws only a rectangle with the above bb and the
705 // not found filename in it.
706 lyxerr[Debug::GRAPHICS]
707 << "\tMessage = \"" << message << '\"' << endl;
709 // These variables collect all the latex code that should be before and
710 // after the actual includegraphics command.
713 // Do we want subcaptions?
714 if (params().subcaption) {
715 before += "\\subfigure[" + params().subcaptionText + "]{";
718 // We never use the starred form, we use the "clip" option instead.
719 before += "\\includegraphics";
721 // Write the options if there are any.
722 string const opts = createLatexOptions();
723 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
725 if (!opts.empty() && !message.empty())
726 before += ("[%\n" + opts + ',' + message + ']');
727 else if (!opts.empty() || !message.empty())
728 before += ("[%\n" + opts + message + ']');
730 lyxerr[Debug::GRAPHICS]
731 << "\tBefore = " << before
732 << "\n\tafter = " << after << endl;
735 // "nice" means that the buffer is exported to LaTeX format but not
736 // run through the LaTeX compiler.
738 os << before <<'{' << params().filename << '}' << after;
742 // Make the filename relative to the lyx file
743 // and remove the extension so the LaTeX will use whatever is
744 // appropriate (when there are several versions in different formats)
745 string const latex_str = message.empty() ?
746 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
747 (before + '{' + params().filename + " not found!}" + after);
750 // Return how many newlines we issued.
752 int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
758 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
760 // No graphics in ascii output. Possible to use gifscii to convert
761 // images to ascii approximation.
762 // 1. Convert file to ascii using gifscii
763 // 2. Read ascii output file and add it to the output stream.
764 // at least we send the filename
765 os << '<' << _("Graphic file:") << params().filename << ">\n";
770 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
772 // No graphics in LinuxDoc output. Should check how/what to add.
777 // For explanation on inserting graphics into DocBook checkout:
778 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
779 // See also the docbook guide at http://www.docbook.org/
780 int InsetGraphics::docbook(Buffer const *, ostream & os,
781 bool /*mixcont*/) const
783 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
784 // need to switch to MediaObject. However, for now this is sufficient and
786 os << "<graphic fileref=\"&" << graphic_label << ";\">";
791 void InsetGraphics::validate(LaTeXFeatures & features) const
793 // If we have no image, we should not require anything.
794 if (params().filename.empty())
797 features.includeFile(graphic_label, RemoveExtension(params().filename));
799 features.require("graphicx");
801 if (params().subcaption)
802 features.require("subfigure");
806 void InsetGraphics::statusChanged()
808 if (cache_->view.get())
809 cache_->view.get()->updateInset(this, false);
813 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
814 string const & filepath)
816 // If nothing is changed, just return and say so.
817 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
838 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
840 return new InsetGraphics(*this, buffer.filePath(), same_id);