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"
79 #include "frontends/Dialogs.h"
80 #include "frontends/Alert.h"
81 #include "frontends/controllers/helper_funcs.h" // getVectorFromString
83 #include "support/LAssert.h"
84 #include "support/filetools.h"
85 #include "support/lyxalgo.h" // lyx::count
86 #include "support/path.h"
87 #include "support/systemcall.h"
88 #include "support/os.h"
90 #include <boost/bind.hpp>
91 #include <boost/signals/trackable.hpp>
93 #include <algorithm> // For the std::max
96 extern BufferView * current_view;
98 extern string system_tempdir;
103 ///////////////////////////////////////////////////////////////////////////
104 int const VersionNumber = 1;
105 ///////////////////////////////////////////////////////////////////////////
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());
122 string const uniqueID()
124 static unsigned int seed = 1000;
127 ost << "graph" << ++seed;
129 // Needed if we use lyxstring.
130 return ost.str().c_str();
136 struct InsetGraphics::Cache : boost::signals::trackable
139 Cache(InsetGraphics &);
141 void update(string const & file_with_path);
148 unsigned long checksum;
152 InsetGraphics & parent_;
156 InsetGraphics::Cache::Cache(InsetGraphics & p)
157 : old_ascent(0), checksum(0), parent_(p)
159 loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
163 void InsetGraphics::Cache::update(string const & file_with_path)
165 lyx::Assert(!file_with_path.empty());
167 string const path = OnlyPath(file_with_path);
168 loader.reset(file_with_path, parent_.params().as_grfxParams(path));
172 InsetGraphics::InsetGraphics()
173 : graphic_label(uniqueID()),
174 cache_(new Cache(*this))
178 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
179 string const & filepath,
181 : Inset(ig, same_id),
182 graphic_label(uniqueID()),
183 cache_(new Cache(*this))
185 setParams(ig.params(), filepath);
189 InsetGraphics::~InsetGraphics()
191 // Emits the hide signal to the dialog connected (if any)
196 string const InsetGraphics::statusMessage() const
200 switch (cache_->loader.status()) {
201 case grfx::WaitingToLoad:
202 msg = _("Waiting for draw request to start loading...");
205 msg = _("Loading...");
207 case grfx::Converting:
208 msg = _("Converting to loadable format...");
211 msg = _("Loaded into memory. Must now generate pixmap.");
213 case grfx::ScalingEtc:
214 msg = _("Scaling etc...");
217 msg = _("Ready to display");
219 case grfx::ErrorNoFile:
220 msg = _("No file found!");
222 case grfx::ErrorConverting:
223 msg = _("Error converting to loadable format");
225 case grfx::ErrorLoading:
226 msg = _("Error loading file into memory");
228 case grfx::ErrorGeneratingPixmap:
229 msg = _("Error generating the pixmap");
231 case grfx::ErrorUnknown:
240 bool InsetGraphics::imageIsDrawable() const
242 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
245 return cache_->loader.image()->isDrawable();
249 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
251 cache_->old_ascent = 50;
252 if (imageIsDrawable())
253 cache_->old_ascent = cache_->loader.image()->getHeight();
254 return cache_->old_ascent;
258 int InsetGraphics::descent(BufferView *, LyXFont const &) const
264 int InsetGraphics::width(BufferView *, LyXFont const & font) const
266 if (imageIsDrawable())
267 return cache_->loader.image()->getWidth();
271 LyXFont msgFont(font);
272 msgFont.setFamily(LyXFont::SANS_FAMILY);
274 string const justname = OnlyFilename (params().filename);
275 if (!justname.empty()) {
276 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
277 font_width = font_metrics::width(justname, msgFont);
280 string const msg = statusMessage();
282 msgFont.setSize(LyXFont::SIZE_TINY);
283 int const msg_width = font_metrics::width(msg, msgFont);
284 font_width = std::max(font_width, msg_width);
287 return std::max(50, font_width + 15);
292 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
293 int baseline, float & x, bool) const
295 int oasc = cache_->old_ascent;
297 int ldescent = descent(bv, font);
298 int lascent = ascent(bv, font);
299 int lwidth = width(bv, font);
301 // we may have changed while someone other was drawing us so better
302 // to not draw anything as we surely call to redraw ourself soon.
303 // This is not a nice thing to do and should be fixed properly somehow.
304 // But I still don't know the best way to go. So let's do this like this
305 // for now (Jug 20020311)
306 if (lascent != oasc) {
310 // Make sure now that x is updated upon exit from this routine
314 if (cache_->loader.status() == grfx::WaitingToLoad)
315 cache_->loader.startLoading(*this, *bv);
317 if (!cache_->loader.monitoring())
318 cache_->loader.startMonitoring();
320 // This will draw the graphics. If the graphics has not been loaded yet,
321 // we draw just a rectangle.
322 Painter & paint = bv->painter();
324 if (imageIsDrawable()) {
325 paint.image(old_x + 2, baseline - lascent,
326 lwidth - 4, lascent + ldescent,
327 *cache_->loader.image());
331 paint.rectangle(old_x + 2, baseline - lascent,
335 // Print the file name.
336 LyXFont msgFont(font);
337 msgFont.setFamily(LyXFont::SANS_FAMILY);
338 string const justname = OnlyFilename (params().filename);
339 if (!justname.empty()) {
340 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
341 paint.text(old_x + 8,
342 baseline - font_metrics::maxAscent(msgFont) - 4,
346 // Print the message.
347 string const msg = statusMessage();
349 msgFont.setSize(LyXFont::SIZE_TINY);
350 paint.text(old_x + 8, baseline - 4, msg, msgFont);
354 // the status message may mean we changed size, so indicate
355 // we need a row redraw
357 if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
358 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
362 // Reset the cache, ready for the next draw request
364 cached_status_ = grfx::ErrorUnknown;
365 cached_image_.reset();
366 cache_filled_ = false;
371 void InsetGraphics::edit(BufferView *bv, int, int, mouse_button::state)
373 bv->owner()->getDialogs()->showGraphics(this);
377 void InsetGraphics::edit(BufferView * bv, bool)
379 edit(bv, 0, 0, mouse_button::none);
383 Inset::EDITABLE InsetGraphics::editable() const
389 void InsetGraphics::write(Buffer const *, ostream & os) const
391 os << "Graphics FormatVersion " << VersionNumber << '\n';
396 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
398 string const token = lex.getString();
400 if (token == "Graphics")
401 readInsetGraphics(lex);
402 else if (token == "Figure") // Compatibility reading of FigInset figures.
405 lyxerr[Debug::GRAPHICS] << "Not a Graphics or Figure inset!\n";
407 cache_->update(MakeAbsPath(params().filename, buf->filePath()));
411 void InsetGraphics::readInsetGraphics(LyXLex & lex)
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))
439 lyxerr << "Unknown token, " << token << ", skipping."
445 // FormatVersion < 1.0 (LyX < 1.2)
446 void InsetGraphics::readFigInset(LyXLex & lex)
448 std::vector<string> const oldUnits =
449 getVectorFromString("pt,cm,in,p%,c%");
450 bool finished = false;
451 // set the display default
452 if (lyxrc.display_graphics == "mono")
453 params_.display = InsetGraphicsParams::MONOCHROME;
454 else if (lyxrc.display_graphics == "gray")
455 params_.display = InsetGraphicsParams::GRAYSCALE;
456 else if (lyxrc.display_graphics == "color")
457 params_.display = InsetGraphicsParams::COLOR;
459 params_.display = InsetGraphicsParams::NONE;
460 while (lex.isOK() && !finished) {
463 string const token = lex.getString();
464 lyxerr[Debug::GRAPHICS] << "Token: " << token << endl;
468 else if (token == "\\end_inset") {
470 } else if (token == "file") {
472 params_.filename = lex.getString();
474 } else if (token == "extra") {
476 // kept for backwards compability. Delete in 0.13.x
477 } else if (token == "subcaption") {
479 params_.subcaptionText = lex.getString();
480 } else if (token == "label") {
482 // kept for backwards compability. Delete in 0.13.x
483 } else if (token == "angle") {
485 params_.rotate = true;
486 params_.rotateAngle = lex.getFloat();
488 } else if (token == "size") {
490 params_.lyxwidth = LyXLength(lex.getString()+"pt");
492 params_.lyxheight = LyXLength(lex.getString()+"pt");
493 params_.lyxsize_type = InsetGraphicsParams::WH;
494 } else if (token == "flags") {
496 switch (lex.getInteger()) {
497 case 1: params_.display = InsetGraphicsParams::MONOCHROME;
499 case 2: params_.display = InsetGraphicsParams::GRAYSCALE;
501 case 3: params_.display = InsetGraphicsParams::COLOR;
504 } else if (token == "subfigure") {
505 params_.subcaption = true;
506 } else if (token == "width") {
508 int i = lex.getInteger();
511 params_.scale = lex.getInteger();
512 params_.size_type = InsetGraphicsParams::SCALE;
514 params_.width = LyXLength(lex.getString()+oldUnits[i]);
515 params_.size_type = InsetGraphicsParams::WH;
519 } else if (token == "height") {
521 int i = lex.getInteger();
523 params_.height = LyXLength(lex.getString()+oldUnits[i]);
524 params_.size_type = InsetGraphicsParams::WH;
531 string const InsetGraphics::createLatexOptions() const
533 // Calculate the options part of the command, we must do it to a string
534 // stream since we might have a trailing comma that we would like to remove
535 // before writing it to the output stream.
536 ostringstream options;
537 if (!params().bb.empty())
538 options << " bb=" << strip(params().bb) << ",\n";
540 options << " draft,\n";
542 options << " clip,\n";
543 if (params().size_type == InsetGraphicsParams::WH) {
544 if (!params().width.zero())
545 options << " width=" << params().width.asLatexString() << ",\n";
546 if (!params().height.zero())
547 options << " height=" << params().height.asLatexString() << ",\n";
548 } else if (params().size_type == InsetGraphicsParams::SCALE) {
549 if (params().scale > 0)
550 options << " scale=" << double(params().scale)/100.0 << ",\n";
552 if (params().keepAspectRatio)
553 options << " keepaspectratio,\n";
554 // Make sure it's not very close to zero, a float can be effectively
555 // zero but not exactly zero.
556 if (!lyx::float_equal(params().rotateAngle, 0, 0.001) && params().rotate) {
557 options << " angle=" << params().rotateAngle << ",\n";
558 if (!params().rotateOrigin.empty()) {
559 options << " origin=" << params().rotateOrigin[0];
560 if (contains(params().rotateOrigin,"Top"))
562 else if (contains(params().rotateOrigin,"Bottom"))
564 else if (contains(params().rotateOrigin,"Baseline"))
569 if (!params().special.empty())
570 options << params().special << ",\n";
571 string opts = options.str().c_str();
572 return opts.substr(0,opts.size()-2); // delete last ",\n"
576 string findTargetFormat(string const & suffix)
578 // lyxrc.pdf_mode means:
579 // Are we creating a PDF or a PS file?
580 // (Should actually mean, are we using latex or pdflatex).
581 if (lyxrc.pdf_mode) {
582 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
583 if (contains(suffix,"ps") || suffix == "pdf")
585 else if (suffix == "jpg") // pdflatex can use jpeg
588 return "png"; // and also png
590 // If it's postscript, we always do eps.
591 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
592 if (suffix != "ps") // any other than ps
593 return "eps"; // is changed to eps
595 return suffix; // let ps untouched
601 string const InsetGraphics::prepareFile(Buffer const *buf) const
603 // LaTeX can cope if the graphics file doesn't exist, so just return the
605 string const orig_file = params().filename;
606 string orig_file_with_path =
607 MakeAbsPath(orig_file, buf->filePath());
608 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
609 << orig_file << "\n\twith path: "
610 << orig_file_with_path << endl;
612 if (!IsFileReadable(orig_file_with_path))
615 bool const zipped = zippedFile(orig_file_with_path);
617 // If the file is compressed and we have specified that it
618 // should not be uncompressed, then just return its name and
619 // let LaTeX do the rest!
620 if (zipped && params().noUnzip) {
621 lyxerr[Debug::GRAPHICS]
622 << "\tpass zipped file to LaTeX but with full path.\n";
623 // LaTeX needs an absolue path, otherwise the
624 // coresponding *.eps.bb file isn't found
625 return orig_file_with_path;
628 // Ascertain whether the file has changed.
629 unsigned long const new_checksum = cache_->loader.checksum();
630 bool const file_has_changed = cache_->checksum != new_checksum;
631 if (file_has_changed)
632 cache_->checksum = new_checksum;
634 // temp_file will contain the file for LaTeX to act on if, for example,
635 // we move it to a temp dir or uncompress it.
636 string temp_file(orig_file);
639 // Uncompress the file if necessary.
640 // If it has been uncompressed in a previous call to
641 // prepareFile, do nothing.
642 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
643 lyxerr[Debug::GRAPHICS]
644 << "\ttemp_file: " << temp_file << endl;
645 if (file_has_changed || !IsFileReadable(temp_file)) {
646 bool const success = lyx::copy(orig_file_with_path,
648 lyxerr[Debug::GRAPHICS]
649 << "\tCopying zipped file from "
650 << orig_file_with_path << " to " << temp_file
651 << (success ? " succeeded\n" : " failed\n");
653 lyxerr[Debug::GRAPHICS]
654 << "\tzipped file " << temp_file
655 << " exists! Maybe no tempdir ...\n";
656 orig_file_with_path = unzipFile(temp_file);
657 lyxerr[Debug::GRAPHICS]
658 << "\tunzipped to " << orig_file_with_path << endl;
661 string const from = getExtFromContents(orig_file_with_path);
662 string const to = findTargetFormat(from);
663 lyxerr[Debug::GRAPHICS]
664 << "\t we have: from " << from << " to " << to << '\n';
666 if (from == to && !lyxrc.use_tempdir)
667 // No conversion is needed. LaTeX can handle the
668 // graphic file as is.
669 // This is true even if the orig_file is compressed.
670 return RemoveExtension(orig_file_with_path);
672 // We're going to be running the exported buffer through the LaTeX
673 // compiler, so must ensure that LaTeX can cope with the graphics
676 // Perform all these manipulations on a temporary file if possible.
677 // If we are not using a temp dir, then temp_file contains the
679 // to allow files with the same name in different dirs
680 // we manipulate the original file "any.dir/file.ext"
681 // to "any_dir_file.ext"! changing the dots in the
682 // dirname is important for the use of ChangeExtension
683 lyxerr[Debug::GRAPHICS]
684 << "\tthe orig file is: " << orig_file_with_path << endl;
686 if (lyxrc.use_tempdir) {
687 string const ext_tmp = GetExtension(orig_file_with_path);
690 ChangeExtension(orig_file_with_path, string()), "/", "_");
691 // without dots and again with ext
692 temp_file = ChangeExtension(
693 subst(temp_file, ".", "_"), ext_tmp);
694 // now we have any_dir_file.ext
695 temp_file = MakeAbsPath(temp_file, buf->tmppath);
696 lyxerr[Debug::GRAPHICS]
697 << "\tchanged to: " << temp_file << endl;
699 // if the file doen't exists, copy it into the tempdir
700 if (file_has_changed || !IsFileReadable(temp_file)) {
701 bool const success = lyx::copy(orig_file_with_path, temp_file);
702 lyxerr[Debug::GRAPHICS]
703 << "\tcopying from " << orig_file_with_path << " to "
705 << (success ? " succeeded\n" : " failed\n");
707 Alert::alert(_("Cannot copy file"), orig_file_with_path,
714 // No conversion is needed. LaTeX can handle the
715 // graphic file as is.
716 return RemoveExtension(temp_file);
719 string const outfile_base = RemoveExtension(temp_file);
720 lyxerr[Debug::GRAPHICS]
721 << "\tThe original file is " << orig_file << "\n"
722 << "\tA copy has been made and convert is to be called with:\n"
723 << "\tfile to convert = " << temp_file << '\n'
724 << "\toutfile_base = " << outfile_base << '\n'
725 << "\t from " << from << " to " << to << '\n';
727 // if no special converter defined, than we take the default one
728 // from ImageMagic: convert from:inname.from to:outname.to
729 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
730 string const command =
732 from + ':' + temp_file + ' ' +
733 to + ':' + outfile_base + '.' + to;
734 lyxerr[Debug::GRAPHICS]
735 << "No converter defined! I use convert from ImageMagic:\n\t"
738 one.startscript(Systemcall::Wait, command);
739 if (!IsFileReadable(ChangeExtension(outfile_base, to)))
740 Alert::alert(_("Cannot convert Image (not existing file?)"),
741 _("No information for converting from ")
742 + from + _(" to ") + to);
745 return RemoveExtension(temp_file);
749 int InsetGraphics::latex(Buffer const *buf, ostream & os,
750 bool /*fragile*/, bool/*fs*/) const
752 // If there is no file specified or not existing,
753 // just output a message about it in the latex output.
754 lyxerr[Debug::GRAPHICS]
755 << "insetgraphics::latex: Filename = "
756 << params().filename << endl;
758 // A missing (e)ps-extension is no problem for LaTeX, so
759 // we have to test three different cases
760 string const file_(MakeAbsPath(params().filename, buf->filePath()));
761 bool const file_exists =
763 (IsFileReadable(file_) || // original
764 IsFileReadable(file_ + ".eps") || // original.eps
765 IsFileReadable(file_ + ".ps")); // original.ps
766 string const message = file_exists ?
767 string() : string("bb = 0 0 200 100, draft, type=eps]");
768 // if !message.empty() than there was no existing file
769 // "filename(.(e)ps)" found. In this case LaTeX
770 // draws only a rectangle with the above bb and the
771 // not found filename in it.
772 lyxerr[Debug::GRAPHICS]
773 << "\tMessage = \"" << message << '\"' << endl;
775 // These variables collect all the latex code that should be before and
776 // after the actual includegraphics command.
779 // Do we want subcaptions?
780 if (params().subcaption) {
781 before += "\\subfigure[" + params().subcaptionText + "]{";
784 // We never use the starred form, we use the "clip" option instead.
785 before += "\\includegraphics";
787 // Write the options if there are any.
788 string const opts = createLatexOptions();
789 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
791 if (!opts.empty() && !message.empty())
792 before += ("[%\n" + opts + ',' + message);
793 else if (!message.empty())
794 before += ("[%\n" + message);
795 else if (!opts.empty())
796 before += ("[%\n" + opts + ']');
798 lyxerr[Debug::GRAPHICS]
799 << "\tBefore = " << before
800 << "\n\tafter = " << after << endl;
803 // "nice" means that the buffer is exported to LaTeX format but not
804 // run through the LaTeX compiler.
806 os << before <<'{' << params().filename << '}' << after;
810 // Make the filename relative to the lyx file
811 // and remove the extension so the LaTeX will use whatever is
812 // appropriate (when there are several versions in different formats)
813 string const latex_str = message.empty() ?
814 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
815 (before + '{' + params().filename + " not found!}" + after);
818 // Return how many newlines we issued.
820 int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
826 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
828 // No graphics in ascii output. Possible to use gifscii to convert
829 // images to ascii approximation.
830 // 1. Convert file to ascii using gifscii
831 // 2. Read ascii output file and add it to the output stream.
832 // at least we send the filename
833 os << '<' << _("Graphic file:") << params().filename << ">\n";
838 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
840 // No graphics in LinuxDoc output. Should check how/what to add.
845 // For explanation on inserting graphics into DocBook checkout:
846 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
847 // See also the docbook guide at http://www.docbook.org/
848 int InsetGraphics::docbook(Buffer const *, ostream & os,
849 bool /*mixcont*/) const
851 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
852 // need to switch to MediaObject. However, for now this is sufficient and
854 os << "<graphic fileref=\"&" << graphic_label << ";\">";
859 void InsetGraphics::validate(LaTeXFeatures & features) const
861 // If we have no image, we should not require anything.
862 if (params().filename.empty())
865 features.includeFile(graphic_label, RemoveExtension(params().filename));
867 features.require("graphicx");
869 if (params().subcaption)
870 features.require("subfigure");
874 void InsetGraphics::statusChanged()
876 current_view->updateInset(this, false);
880 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
881 string const & filepath)
883 // If nothing is changed, just return and say so.
884 if (params() == p && !p.filename.empty()) {
888 // Copy the new parameters.
891 // Update the inset with the new parameters.
892 cache_->update(MakeAbsPath(params().filename, filepath));
894 // We have changed data, report it.
899 InsetGraphicsParams const & InsetGraphics::params() const
905 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
907 return new InsetGraphics(*this, buffer.filePath(), same_id);