1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995-2002 the LyX Team.
9 * \author Herbert Voss <voss@lyx.org>
10 * ====================================================== */
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"
67 #include "frontends/LyXView.h"
70 #include "BufferView.h"
71 #include "converter.h"
72 #include "frontends/Painter.h"
74 #include "frontends/font_metrics.h"
77 #include "LaTeXFeatures.h"
80 #include "frontends/Dialogs.h"
81 #include "frontends/Alert.h"
82 #include "frontends/controllers/helper_funcs.h" // getVectorFromString
84 #include "support/LAssert.h"
85 #include "support/filetools.h"
86 #include "support/lyxalgo.h" // lyx::count
87 #include "support/path.h"
88 #include "support/systemcall.h"
89 #include "support/os.h"
91 #include <boost/bind.hpp>
92 #include <boost/signals/trackable.hpp>
94 #include <algorithm> // For the std::max
97 extern BufferView * current_view;
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;
153 InsetGraphics & parent_;
157 InsetGraphics::Cache::Cache(InsetGraphics & p)
158 : old_ascent(0), checksum(0), parent_(p)
160 loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
164 void InsetGraphics::Cache::update(string const & file_with_path)
166 lyx::Assert(!file_with_path.empty());
168 string const path = OnlyPath(file_with_path);
169 loader.reset(file_with_path, parent_.params().as_grfxParams(path));
173 InsetGraphics::InsetGraphics()
174 : graphic_label(uniqueID()),
175 cache_(new Cache(*this))
179 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
180 string const & filepath,
182 : Inset(ig, same_id),
183 graphic_label(uniqueID()),
184 cache_(new Cache(*this))
186 setParams(ig.params(), filepath);
190 InsetGraphics::~InsetGraphics()
192 // Emits the hide signal to the dialog connected (if any)
197 string const InsetGraphics::statusMessage() const
201 switch (cache_->loader.status()) {
202 case grfx::WaitingToLoad:
203 msg = _("Waiting for draw request to start loading...");
206 msg = _("Loading...");
208 case grfx::Converting:
209 msg = _("Converting to loadable format...");
212 msg = _("Loaded into memory. Must now generate pixmap.");
214 case grfx::ScalingEtc:
215 msg = _("Scaling etc...");
218 msg = _("Ready to display");
220 case grfx::ErrorNoFile:
221 msg = _("No file found!");
223 case grfx::ErrorConverting:
224 msg = _("Error converting to loadable format");
226 case grfx::ErrorLoading:
227 msg = _("Error loading file into memory");
229 case grfx::ErrorGeneratingPixmap:
230 msg = _("Error generating the pixmap");
232 case grfx::ErrorUnknown:
241 bool InsetGraphics::imageIsDrawable() const
243 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
246 return cache_->loader.image()->isDrawable();
250 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
252 cache_->old_ascent = 50;
253 if (imageIsDrawable())
254 cache_->old_ascent = cache_->loader.image()->getHeight();
255 return cache_->old_ascent;
259 int InsetGraphics::descent(BufferView *, LyXFont const &) const
265 int InsetGraphics::width(BufferView *, LyXFont const & font) const
267 if (imageIsDrawable())
268 return cache_->loader.image()->getWidth();
272 LyXFont msgFont(font);
273 msgFont.setFamily(LyXFont::SANS_FAMILY);
275 string const justname = OnlyFilename (params().filename);
276 if (!justname.empty()) {
277 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
278 font_width = font_metrics::width(justname, msgFont);
281 string const msg = statusMessage();
283 msgFont.setSize(LyXFont::SIZE_TINY);
284 int const msg_width = font_metrics::width(msg, msgFont);
285 font_width = std::max(font_width, msg_width);
288 return std::max(50, font_width + 15);
293 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
294 int baseline, float & x, bool) const
296 int oasc = cache_->old_ascent;
298 int ldescent = descent(bv, font);
299 int lascent = ascent(bv, font);
300 int lwidth = width(bv, font);
302 // we may have changed while someone other was drawing us so better
303 // to not draw anything as we surely call to redraw ourself soon.
304 // This is not a nice thing to do and should be fixed properly somehow.
305 // But I still don't know the best way to go. So let's do this like this
306 // for now (Jug 20020311)
307 if (lascent != oasc) {
311 // Make sure now that x is updated upon exit from this routine
315 if (cache_->loader.status() == grfx::WaitingToLoad)
316 cache_->loader.startLoading(*this, *bv);
318 if (!cache_->loader.monitoring())
319 cache_->loader.startMonitoring();
321 // This will draw the graphics. If the graphics has not been loaded yet,
322 // we draw just a rectangle.
323 Painter & paint = bv->painter();
325 if (imageIsDrawable()) {
326 paint.image(old_x + 2, baseline - lascent,
327 lwidth - 4, lascent + ldescent,
328 *cache_->loader.image());
332 paint.rectangle(old_x + 2, baseline - lascent,
336 // Print the file name.
337 LyXFont msgFont(font);
338 msgFont.setFamily(LyXFont::SANS_FAMILY);
339 string const justname = OnlyFilename (params().filename);
340 if (!justname.empty()) {
341 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
342 paint.text(old_x + 8,
343 baseline - font_metrics::maxAscent(msgFont) - 4,
347 // Print the message.
348 string const msg = statusMessage();
350 msgFont.setSize(LyXFont::SIZE_TINY);
351 paint.text(old_x + 8, baseline - 4, msg, msgFont);
355 // the status message may mean we changed size, so indicate
356 // we need a row redraw
358 if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
359 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
363 // Reset the cache, ready for the next draw request
365 cached_status_ = grfx::ErrorUnknown;
366 cached_image_.reset();
367 cache_filled_ = false;
372 void InsetGraphics::edit(BufferView *bv, int, int, mouse_button::state)
374 bv->owner()->getDialogs()->showGraphics(this);
378 void InsetGraphics::edit(BufferView * bv, bool)
380 edit(bv, 0, 0, mouse_button::none);
384 Inset::EDITABLE InsetGraphics::editable() const
390 void InsetGraphics::write(Buffer const *, ostream & os) const
392 os << "Graphics FormatVersion " << VersionNumber << '\n';
397 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
399 string const token = lex.getString();
401 if (token == "Graphics")
402 readInsetGraphics(lex);
403 else if (token == "Figure") // Compatibility reading of FigInset figures.
406 lyxerr[Debug::GRAPHICS] << "Not a Graphics or Figure inset!\n";
408 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
412 void InsetGraphics::readInsetGraphics(LyXLex & lex)
414 bool finished = false;
416 while (lex.isOK() && !finished) {
419 string const token = lex.getString();
420 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
425 } else if (token == "\\end_inset") {
427 } else if (token == "FormatVersion") {
429 int version = lex.getInteger();
430 if (version > VersionNumber)
432 << "This document was created with a newer Graphics widget"
433 ", You should use a newer version of LyX to read this"
436 // TODO: Possibly open up a dialog?
439 if (! params_.Read(lex, token))
440 lyxerr << "Unknown token, " << token << ", skipping."
446 // FormatVersion < 1.0 (LyX < 1.2)
447 void InsetGraphics::readFigInset(LyXLex & lex)
449 std::vector<string> const oldUnits =
450 getVectorFromString("pt,cm,in,p%,c%");
451 bool finished = false;
452 // set the display default
453 if (lyxrc.display_graphics == "mono")
454 params_.display = InsetGraphicsParams::MONOCHROME;
455 else if (lyxrc.display_graphics == "gray")
456 params_.display = InsetGraphicsParams::GRAYSCALE;
457 else if (lyxrc.display_graphics == "color")
458 params_.display = InsetGraphicsParams::COLOR;
460 params_.display = InsetGraphicsParams::NONE;
461 while (lex.isOK() && !finished) {
464 string const token = lex.getString();
465 lyxerr[Debug::GRAPHICS] << "Token: " << token << endl;
469 else if (token == "\\end_inset") {
471 } else if (token == "file") {
473 params_.filename = lex.getString();
475 } else if (token == "extra") {
477 // kept for backwards compability. Delete in 0.13.x
478 } else if (token == "subcaption") {
480 params_.subcaptionText = lex.getString();
481 } else if (token == "label") {
483 // kept for backwards compability. Delete in 0.13.x
484 } else if (token == "angle") {
486 params_.rotate = true;
487 params_.rotateAngle = lex.getFloat();
489 } else if (token == "size") {
491 params_.lyxwidth = LyXLength(lex.getString()+"pt");
493 params_.lyxheight = LyXLength(lex.getString()+"pt");
494 params_.lyxsize_type = InsetGraphicsParams::WH;
495 } else if (token == "flags") {
497 switch (lex.getInteger()) {
498 case 1: params_.display = InsetGraphicsParams::MONOCHROME;
500 case 2: params_.display = InsetGraphicsParams::GRAYSCALE;
502 case 3: params_.display = InsetGraphicsParams::COLOR;
505 } else if (token == "subfigure") {
506 params_.subcaption = true;
507 } else if (token == "width") {
509 int i = lex.getInteger();
512 params_.scale = lex.getInteger();
513 params_.size_type = InsetGraphicsParams::SCALE;
515 params_.width = LyXLength(lex.getString()+oldUnits[i]);
516 params_.size_type = InsetGraphicsParams::WH;
520 } else if (token == "height") {
522 int i = lex.getInteger();
524 params_.height = LyXLength(lex.getString()+oldUnits[i]);
525 params_.size_type = InsetGraphicsParams::WH;
532 string const InsetGraphics::createLatexOptions() const
534 // Calculate the options part of the command, we must do it to a string
535 // stream since we might have a trailing comma that we would like to remove
536 // before writing it to the output stream.
537 ostringstream options;
538 if (!params().bb.empty())
539 options << " bb=" << strip(params().bb) << ",\n";
541 options << " draft,\n";
543 options << " clip,\n";
544 if (params().size_type == InsetGraphicsParams::WH) {
545 if (!params().width.zero())
546 options << " width=" << params().width.asLatexString() << ",\n";
547 if (!params().height.zero())
548 options << " height=" << params().height.asLatexString() << ",\n";
549 } else if (params().size_type == InsetGraphicsParams::SCALE) {
550 if (params().scale > 0)
551 options << " scale=" << double(params().scale)/100.0 << ",\n";
553 if (params().keepAspectRatio)
554 options << " keepaspectratio,\n";
555 // Make sure it's not very close to zero, a float can be effectively
556 // zero but not exactly zero.
557 if (!lyx::float_equal(params().rotateAngle, 0, 0.001) && params().rotate) {
558 options << " angle=" << params().rotateAngle << ",\n";
559 if (!params().rotateOrigin.empty()) {
560 options << " origin=" << params().rotateOrigin[0];
561 if (contains(params().rotateOrigin,"Top"))
563 else if (contains(params().rotateOrigin,"Bottom"))
565 else if (contains(params().rotateOrigin,"Baseline"))
570 if (!params().special.empty())
571 options << params().special << ",\n";
572 string opts = options.str().c_str();
573 return opts.substr(0,opts.size()-2); // delete last ",\n"
577 string findTargetFormat(string const & suffix)
579 // lyxrc.pdf_mode means:
580 // Are we creating a PDF or a PS file?
581 // (Should actually mean, are we using latex or pdflatex).
582 if (lyxrc.pdf_mode) {
583 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
584 if (contains(suffix,"ps") || suffix == "pdf")
586 else if (suffix == "jpg") // pdflatex can use jpeg
589 return "png"; // and also png
591 // If it's postscript, we always do eps.
592 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
593 if (suffix != "ps") // any other than ps
594 return "eps"; // is changed to eps
596 return suffix; // let ps untouched
602 string const InsetGraphics::prepareFile(Buffer const *buf) const
604 // LaTeX can cope if the graphics file doesn't exist, so just return the
606 string const orig_file = params().filename;
607 string orig_file_with_path =
608 MakeAbsPath(orig_file, buf->filePath());
609 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
610 << orig_file << "\n\twith path: "
611 << orig_file_with_path << endl;
613 if (!IsFileReadable(orig_file_with_path))
616 bool const zipped = zippedFile(orig_file_with_path);
618 // If the file is compressed and we have specified that it
619 // should not be uncompressed, then just return its name and
620 // let LaTeX do the rest!
621 if (zipped && params().noUnzip) {
622 lyxerr[Debug::GRAPHICS]
623 << "\tpass zipped file to LaTeX but with full path.\n";
624 // LaTeX needs an absolue path, otherwise the
625 // coresponding *.eps.bb file isn't found
626 return orig_file_with_path;
629 // Ascertain whether the file has changed.
630 unsigned long const new_checksum = cache_->loader.checksum();
631 bool const file_has_changed = cache_->checksum != new_checksum;
632 if (file_has_changed)
633 cache_->checksum = new_checksum;
635 // temp_file will contain the file for LaTeX to act on if, for example,
636 // we move it to a temp dir or uncompress it.
637 string temp_file(orig_file);
640 // Uncompress the file if necessary.
641 // If it has been uncompressed in a previous call to
642 // prepareFile, do nothing.
643 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
644 lyxerr[Debug::GRAPHICS]
645 << "\ttemp_file: " << temp_file << endl;
646 if (file_has_changed || !IsFileReadable(temp_file)) {
647 bool const success = lyx::copy(orig_file_with_path,
649 lyxerr[Debug::GRAPHICS]
650 << "\tCopying zipped file from "
651 << orig_file_with_path << " to " << temp_file
652 << (success ? " succeeded\n" : " failed\n");
654 lyxerr[Debug::GRAPHICS]
655 << "\tzipped file " << temp_file
656 << " exists! Maybe no tempdir ...\n";
657 orig_file_with_path = unzipFile(temp_file);
658 lyxerr[Debug::GRAPHICS]
659 << "\tunzipped to " << orig_file_with_path << endl;
662 string const from = getExtFromContents(orig_file_with_path);
663 string const to = findTargetFormat(from);
664 lyxerr[Debug::GRAPHICS]
665 << "\t we have: from " << from << " to " << to << '\n';
667 if (from == to && !lyxrc.use_tempdir)
668 // No conversion is needed. LaTeX can handle the
669 // graphic file as is.
670 // This is true even if the orig_file is compressed.
671 return RemoveExtension(orig_file_with_path);
673 // We're going to be running the exported buffer through the LaTeX
674 // compiler, so must ensure that LaTeX can cope with the graphics
677 // Perform all these manipulations on a temporary file if possible.
678 // If we are not using a temp dir, then temp_file contains the
680 // to allow files with the same name in different dirs
681 // we manipulate the original file "any.dir/file.ext"
682 // to "any_dir_file.ext"! changing the dots in the
683 // dirname is important for the use of ChangeExtension
684 lyxerr[Debug::GRAPHICS]
685 << "\tthe orig file is: " << orig_file_with_path << endl;
687 if (lyxrc.use_tempdir) {
688 string const ext_tmp = GetExtension(orig_file_with_path);
691 ChangeExtension(orig_file_with_path, string()), "/", "_");
692 // without dots and again with ext
693 temp_file = ChangeExtension(
694 subst(temp_file, ".", "_"), ext_tmp);
695 // now we have any_dir_file.ext
696 temp_file = MakeAbsPath(temp_file, buf->tmppath);
697 lyxerr[Debug::GRAPHICS]
698 << "\tchanged to: " << temp_file << endl;
700 // if the file doen't exists, copy it into the tempdir
701 if (file_has_changed || !IsFileReadable(temp_file)) {
702 bool const success = lyx::copy(orig_file_with_path, temp_file);
703 lyxerr[Debug::GRAPHICS]
704 << "\tcopying from " << orig_file_with_path << " to "
706 << (success ? " succeeded\n" : " failed\n");
708 Alert::alert(_("Cannot copy file"), orig_file_with_path,
715 // No conversion is needed. LaTeX can handle the
716 // graphic file as is.
717 return RemoveExtension(temp_file);
720 string const outfile_base = RemoveExtension(temp_file);
721 lyxerr[Debug::GRAPHICS]
722 << "\tThe original file is " << orig_file << "\n"
723 << "\tA copy has been made and convert is to be called with:\n"
724 << "\tfile to convert = " << temp_file << '\n'
725 << "\toutfile_base = " << outfile_base << '\n'
726 << "\t from " << from << " to " << to << '\n';
728 // if no special converter defined, than we take the default one
729 // from ImageMagic: convert from:inname.from to:outname.to
730 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
731 string const command =
733 from + ':' + temp_file + ' ' +
734 to + ':' + outfile_base + '.' + to;
735 lyxerr[Debug::GRAPHICS]
736 << "No converter defined! I use convert from ImageMagic:\n\t"
739 one.startscript(Systemcall::Wait, command);
740 if (!IsFileReadable(ChangeExtension(outfile_base, to)))
741 Alert::alert(_("Cannot convert Image (not existing file?)"),
742 _("No information for converting from ")
743 + from + _(" to ") + to);
746 return RemoveExtension(temp_file);
750 int InsetGraphics::latex(Buffer const *buf, ostream & os,
751 bool /*fragile*/, bool/*fs*/) const
753 // If there is no file specified or not existing,
754 // just output a message about it in the latex output.
755 lyxerr[Debug::GRAPHICS]
756 << "insetgraphics::latex: Filename = "
757 << params().filename << endl;
759 // A missing (e)ps-extension is no problem for LaTeX, so
760 // we have to test three different cases
761 string const file_(MakeAbsPath(params().filename, buf->filePath()));
762 bool const file_exists =
764 (IsFileReadable(file_) || // original
765 IsFileReadable(file_ + ".eps") || // original.eps
766 IsFileReadable(file_ + ".ps")); // original.ps
767 string const message = file_exists ?
768 string() : string("bb = 0 0 200 100, draft, type=eps]");
769 // if !message.empty() than there was no existing file
770 // "filename(.(e)ps)" found. In this case LaTeX
771 // draws only a rectangle with the above bb and the
772 // not found filename in it.
773 lyxerr[Debug::GRAPHICS]
774 << "\tMessage = \"" << message << '\"' << endl;
776 // These variables collect all the latex code that should be before and
777 // after the actual includegraphics command.
780 // Do we want subcaptions?
781 if (params().subcaption) {
782 before += "\\subfigure[" + params().subcaptionText + "]{";
785 // We never use the starred form, we use the "clip" option instead.
786 before += "\\includegraphics";
788 // Write the options if there are any.
789 string const opts = createLatexOptions();
790 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
792 if (!opts.empty() && !message.empty())
793 before += ("[%\n" + opts + ',' + message);
794 else if (!message.empty())
795 before += ("[%\n" + message);
796 else if (!opts.empty())
797 before += ("[%\n" + opts + ']');
799 lyxerr[Debug::GRAPHICS]
800 << "\tBefore = " << before
801 << "\n\tafter = " << after << endl;
804 // "nice" means that the buffer is exported to LaTeX format but not
805 // run through the LaTeX compiler.
807 os << before <<'{' << params().filename << '}' << after;
811 // Make the filename relative to the lyx file
812 // and remove the extension so the LaTeX will use whatever is
813 // appropriate (when there are several versions in different formats)
814 string const latex_str = message.empty() ?
815 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
816 (before + '{' + params().filename + " not found!}" + after);
819 // Return how many newlines we issued.
821 int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
827 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
829 // No graphics in ascii output. Possible to use gifscii to convert
830 // images to ascii approximation.
831 // 1. Convert file to ascii using gifscii
832 // 2. Read ascii output file and add it to the output stream.
833 // at least we send the filename
834 os << '<' << _("Graphic file:") << params().filename << ">\n";
839 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
841 // No graphics in LinuxDoc output. Should check how/what to add.
846 // For explanation on inserting graphics into DocBook checkout:
847 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
848 // See also the docbook guide at http://www.docbook.org/
849 int InsetGraphics::docbook(Buffer const *, ostream & os,
850 bool /*mixcont*/) const
852 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
853 // need to switch to MediaObject. However, for now this is sufficient and
855 os << "<graphic fileref=\"&" << graphic_label << ";\">";
860 void InsetGraphics::validate(LaTeXFeatures & features) const
862 // If we have no image, we should not require anything.
863 if (params().filename.empty())
866 features.includeFile(graphic_label, RemoveExtension(params().filename));
868 features.require("graphicx");
870 if (params().subcaption)
871 features.require("subfigure");
875 void InsetGraphics::statusChanged()
877 current_view->updateInset(this, false);
881 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
882 string const & filepath)
884 // If nothing is changed, just return and say so.
885 if (params() == p && !p.filename.empty()) {
889 // Copy the new parameters.
892 // Update the inset with the new parameters.
893 cache_->update(MakeAbsPath(params().filename, filepath));
895 // We have changed data, report it.
900 InsetGraphicsParams const & InsetGraphics::params() const
906 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
908 return new InsetGraphics(*this, buffer.filePath(), same_id);