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"
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/path.h"
89 #include "support/systemcall.h"
90 #include "support/os.h"
92 #include <boost/weak_ptr.hpp>
93 #include <boost/bind.hpp>
94 #include <boost/signals/trackable.hpp>
96 #include <algorithm> // For the std::max
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;
150 boost::weak_ptr<BufferView> view;
154 InsetGraphics & parent_;
158 InsetGraphics::Cache::Cache(InsetGraphics & p)
159 : old_ascent(0), checksum(0), parent_(p)
161 loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
165 void InsetGraphics::Cache::update(string const & file_with_path)
167 lyx::Assert(!file_with_path.empty());
169 string const path = OnlyPath(file_with_path);
170 loader.reset(file_with_path, parent_.params().as_grfxParams(path));
174 InsetGraphics::InsetGraphics()
175 : graphic_label(uniqueID()),
176 cache_(new Cache(*this))
180 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
181 string const & filepath,
183 : Inset(ig, same_id),
184 graphic_label(uniqueID()),
185 cache_(new Cache(*this))
187 setParams(ig.params(), filepath);
191 InsetGraphics::~InsetGraphics()
193 // Emits the hide signal to the dialog connected (if any)
198 string const InsetGraphics::statusMessage() const
202 switch (cache_->loader.status()) {
203 case grfx::WaitingToLoad:
204 msg = _("Waiting for draw request to start loading...");
207 msg = _("Loading...");
209 case grfx::Converting:
210 msg = _("Converting to loadable format...");
213 msg = _("Loaded into memory. Must now generate pixmap.");
215 case grfx::ScalingEtc:
216 msg = _("Scaling etc...");
219 msg = _("Ready to display");
221 case grfx::ErrorNoFile:
222 msg = _("No file found!");
224 case grfx::ErrorConverting:
225 msg = _("Error converting to loadable format");
227 case grfx::ErrorLoading:
228 msg = _("Error loading file into memory");
230 case grfx::ErrorGeneratingPixmap:
231 msg = _("Error generating the pixmap");
233 case grfx::ErrorUnknown:
242 bool InsetGraphics::imageIsDrawable() const
244 if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
247 return cache_->loader.image()->isDrawable();
251 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
253 cache_->old_ascent = 50;
254 if (imageIsDrawable())
255 cache_->old_ascent = cache_->loader.image()->getHeight();
256 return cache_->old_ascent;
260 int InsetGraphics::descent(BufferView *, LyXFont const &) const
266 int InsetGraphics::width(BufferView *, LyXFont const & font) const
268 if (imageIsDrawable())
269 return cache_->loader.image()->getWidth();
273 LyXFont msgFont(font);
274 msgFont.setFamily(LyXFont::SANS_FAMILY);
276 string const justname = OnlyFilename (params().filename);
277 if (!justname.empty()) {
278 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
279 font_width = font_metrics::width(justname, msgFont);
282 string const msg = statusMessage();
284 msgFont.setSize(LyXFont::SIZE_TINY);
285 int const msg_width = font_metrics::width(msg, msgFont);
286 font_width = std::max(font_width, msg_width);
289 return std::max(50, font_width + 15);
294 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
295 int baseline, float & x, bool) const
297 cache_->view = bv->owner()->view();
298 int oasc = cache_->old_ascent;
300 int ldescent = descent(bv, font);
301 int lascent = ascent(bv, font);
302 int lwidth = width(bv, font);
304 // we may have changed while someone other was drawing us so better
305 // to not draw anything as we surely call to redraw ourself soon.
306 // This is not a nice thing to do and should be fixed properly somehow.
307 // But I still don't know the best way to go. So let's do this like this
308 // for now (Jug 20020311)
309 if (lascent != oasc) {
313 // Make sure now that x is updated upon exit from this routine
317 if (cache_->loader.status() == grfx::WaitingToLoad)
318 cache_->loader.startLoading(*this, *bv);
320 if (!cache_->loader.monitoring())
321 cache_->loader.startMonitoring();
323 // This will draw the graphics. If the graphics has not been loaded yet,
324 // we draw just a rectangle.
325 Painter & paint = bv->painter();
327 if (imageIsDrawable()) {
328 paint.image(old_x + 2, baseline - lascent,
329 lwidth - 4, lascent + ldescent,
330 *cache_->loader.image());
334 paint.rectangle(old_x + 2, baseline - lascent,
338 // Print the file name.
339 LyXFont msgFont(font);
340 msgFont.setFamily(LyXFont::SANS_FAMILY);
341 string const justname = OnlyFilename (params().filename);
342 if (!justname.empty()) {
343 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
344 paint.text(old_x + 8,
345 baseline - font_metrics::maxAscent(msgFont) - 4,
349 // Print the message.
350 string const msg = statusMessage();
352 msgFont.setSize(LyXFont::SIZE_TINY);
353 paint.text(old_x + 8, baseline - 4, msg, msgFont);
357 // the status message may mean we changed size, so indicate
358 // we need a row redraw
360 if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
361 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
365 // Reset the cache, ready for the next draw request
367 cached_status_ = grfx::ErrorUnknown;
368 cached_image_.reset();
369 cache_filled_ = false;
374 void InsetGraphics::edit(BufferView *bv, int, int, mouse_button::state)
376 bv->owner()->getDialogs().showGraphics(this);
380 void InsetGraphics::edit(BufferView * bv, bool)
382 edit(bv, 0, 0, mouse_button::none);
386 Inset::EDITABLE InsetGraphics::editable() const
392 void InsetGraphics::write(Buffer const *, ostream & os) const
399 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
401 string const token = lex.getString();
403 if (token == "Graphics")
404 readInsetGraphics(lex);
406 lyxerr[Debug::GRAPHICS] << "Not a Graphics 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."
447 string const InsetGraphics::createLatexOptions() const
449 // Calculate the options part of the command, we must do it to a string
450 // stream since we might have a trailing comma that we would like to remove
451 // before writing it to the output stream.
452 ostringstream options;
453 if (!params().bb.empty())
454 options << " bb=" << rtrim(params().bb) << ",\n";
456 options << " draft,\n";
458 options << " clip,\n";
460 if (params().scale) {
461 if (params().scale != 100)
462 options << " scale=" << params().scale / 100.0 << ",\n";
464 if (!params().width.zero())
465 options << " width=" << params().width.asLatexString() << ",\n";
466 if (!params().height.zero())
467 options << " height=" << params().height.asLatexString() << ",\n";
468 if (params().keepAspectRatio)
469 options << " keepaspectratio,\n";
472 // Make sure rotation angle is not very close to zero;
473 // a float can be effectively zero but not exactly zero.
474 if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
475 options << " angle=" << params().rotateAngle << ",\n";
476 if (!params().rotateOrigin.empty()) {
477 options << " origin=" << params().rotateOrigin[0];
478 if (contains(params().rotateOrigin,"Top"))
480 else if (contains(params().rotateOrigin,"Bottom"))
482 else if (contains(params().rotateOrigin,"Baseline"))
488 if (!params().special.empty())
489 options << params().special << ",\n";
491 string opts = options.str().c_str();
492 return opts.substr(0,opts.size()-2); // delete last ",\n"
496 string findTargetFormat(string const & suffix)
498 // lyxrc.pdf_mode means:
499 // Are we creating a PDF or a PS file?
500 // (Should actually mean, are we using latex or pdflatex).
501 if (lyxrc.pdf_mode) {
502 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
503 if (contains(suffix, "ps") || suffix == "pdf")
505 else if (suffix == "jpg") // pdflatex can use jpeg
508 return "png"; // and also png
510 // If it's postscript, we always do eps.
511 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
512 if (suffix != "ps") // any other than ps
513 return "eps"; // is changed to eps
515 return suffix; // let ps untouched
521 string const InsetGraphics::prepareFile(Buffer const *buf) const
523 // LaTeX can cope if the graphics file doesn't exist, so just return the
525 string const orig_file = params().filename;
526 string orig_file_with_path =
527 MakeAbsPath(orig_file, buf->filePath());
528 lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
529 << orig_file << "\n\twith path: "
530 << orig_file_with_path << endl;
532 if (!IsFileReadable(orig_file_with_path))
535 bool const zipped = zippedFile(orig_file_with_path);
537 // If the file is compressed and we have specified that it
538 // should not be uncompressed, then just return its name and
539 // let LaTeX do the rest!
540 if (zipped && params().noUnzip) {
541 lyxerr[Debug::GRAPHICS]
542 << "\tpass zipped file to LaTeX but with full path.\n";
543 // LaTeX needs an absolue path, otherwise the
544 // coresponding *.eps.bb file isn't found
545 return orig_file_with_path;
548 // Ascertain whether the file has changed.
549 unsigned long const new_checksum = cache_->loader.checksum();
550 bool const file_has_changed = cache_->checksum != new_checksum;
551 if (file_has_changed)
552 cache_->checksum = new_checksum;
554 // temp_file will contain the file for LaTeX to act on if, for example,
555 // we move it to a temp dir or uncompress it.
556 string temp_file(orig_file);
559 // Uncompress the file if necessary.
560 // If it has been uncompressed in a previous call to
561 // prepareFile, do nothing.
562 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
563 lyxerr[Debug::GRAPHICS]
564 << "\ttemp_file: " << temp_file << endl;
565 if (file_has_changed || !IsFileReadable(temp_file)) {
566 bool const success = lyx::copy(orig_file_with_path,
568 lyxerr[Debug::GRAPHICS]
569 << "\tCopying zipped file from "
570 << orig_file_with_path << " to " << temp_file
571 << (success ? " succeeded\n" : " failed\n");
573 lyxerr[Debug::GRAPHICS]
574 << "\tzipped file " << temp_file
575 << " exists! Maybe no tempdir ...\n";
576 orig_file_with_path = unzipFile(temp_file);
577 lyxerr[Debug::GRAPHICS]
578 << "\tunzipped to " << orig_file_with_path << endl;
581 string const from = getExtFromContents(orig_file_with_path);
582 string const to = findTargetFormat(from);
583 lyxerr[Debug::GRAPHICS]
584 << "\t we have: from " << from << " to " << to << '\n';
586 if (from == to && !lyxrc.use_tempdir)
587 // No conversion is needed. LaTeX can handle the
588 // graphic file as is.
589 // This is true even if the orig_file is compressed.
590 return RemoveExtension(orig_file_with_path);
592 // We're going to be running the exported buffer through the LaTeX
593 // compiler, so must ensure that LaTeX can cope with the graphics
596 // Perform all these manipulations on a temporary file if possible.
597 // If we are not using a temp dir, then temp_file contains the
599 // to allow files with the same name in different dirs
600 // we manipulate the original file "any.dir/file.ext"
601 // to "any_dir_file.ext"! changing the dots in the
602 // dirname is important for the use of ChangeExtension
603 lyxerr[Debug::GRAPHICS]
604 << "\tthe orig file is: " << orig_file_with_path << endl;
606 if (lyxrc.use_tempdir) {
607 string const ext_tmp = GetExtension(orig_file_with_path);
610 ChangeExtension(orig_file_with_path, string()), "/", "_");
611 // without dots and again with ext
612 temp_file = ChangeExtension(
613 subst(temp_file, ".", "_"), ext_tmp);
614 // now we have any_dir_file.ext
615 temp_file = MakeAbsPath(temp_file, buf->tmppath);
616 lyxerr[Debug::GRAPHICS]
617 << "\tchanged to: " << temp_file << endl;
619 // if the file doen't exists, copy it into the tempdir
620 if (file_has_changed || !IsFileReadable(temp_file)) {
621 bool const success = lyx::copy(orig_file_with_path, temp_file);
622 lyxerr[Debug::GRAPHICS]
623 << "\tcopying from " << orig_file_with_path << " to "
625 << (success ? " succeeded\n" : " failed\n");
627 Alert::alert(_("Cannot copy file"), orig_file_with_path,
634 // No conversion is needed. LaTeX can handle the
635 // graphic file as is.
636 return RemoveExtension(temp_file);
639 string const outfile_base = RemoveExtension(temp_file);
640 lyxerr[Debug::GRAPHICS]
641 << "\tThe original file is " << orig_file << "\n"
642 << "\tA copy has been made and convert is to be called with:\n"
643 << "\tfile to convert = " << temp_file << '\n'
644 << "\toutfile_base = " << outfile_base << '\n'
645 << "\t from " << from << " to " << to << '\n';
647 // if no special converter defined, than we take the default one
648 // from ImageMagic: convert from:inname.from to:outname.to
649 if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
650 string const command =
651 LibFileSearch("scripts", "convertDefault.sh") +
652 ' ' + from + ':' + temp_file + ' ' +
653 to + ':' + outfile_base + '.' + to;
654 lyxerr[Debug::GRAPHICS]
655 << "No converter defined! I use convertDefault.sh:\n\t"
658 one.startscript(Systemcall::Wait, command);
659 if (!IsFileReadable(ChangeExtension(outfile_base, to)))
660 Alert::alert(_("Cannot convert Image (not existing file?)"),
661 _("No information for converting from ")
662 + from + _(" to ") + to);
665 return RemoveExtension(temp_file);
669 int InsetGraphics::latex(Buffer const *buf, ostream & os,
670 bool /*fragile*/, bool/*fs*/) const
672 // If there is no file specified or not existing,
673 // just output a message about it in the latex output.
674 lyxerr[Debug::GRAPHICS]
675 << "insetgraphics::latex: Filename = "
676 << params().filename << endl;
678 // A missing (e)ps-extension is no problem for LaTeX, so
679 // we have to test three different cases
680 string const file_(MakeAbsPath(params().filename, buf->filePath()));
681 bool const file_exists =
683 (IsFileReadable(file_) || // original
684 IsFileReadable(file_ + ".eps") || // original.eps
685 IsFileReadable(file_ + ".ps")); // original.ps
686 string const message = file_exists ?
687 string() : string("bb = 0 0 200 100, draft, type=eps]");
688 // if !message.empty() than there was no existing file
689 // "filename(.(e)ps)" found. In this case LaTeX
690 // draws only a rectangle with the above bb and the
691 // not found filename in it.
692 lyxerr[Debug::GRAPHICS]
693 << "\tMessage = \"" << message << '\"' << endl;
695 // These variables collect all the latex code that should be before and
696 // after the actual includegraphics command.
699 // Do we want subcaptions?
700 if (params().subcaption) {
701 before += "\\subfigure[" + params().subcaptionText + "]{";
704 // We never use the starred form, we use the "clip" option instead.
705 before += "\\includegraphics";
707 // Write the options if there are any.
708 string const opts = createLatexOptions();
709 lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
711 if (!opts.empty() && !message.empty())
712 before += ("[%\n" + opts + ',' + message);
713 else if (!message.empty())
714 before += ("[%\n" + message);
715 else if (!opts.empty())
716 before += ("[%\n" + opts + ']');
718 lyxerr[Debug::GRAPHICS]
719 << "\tBefore = " << before
720 << "\n\tafter = " << after << endl;
723 // "nice" means that the buffer is exported to LaTeX format but not
724 // run through the LaTeX compiler.
726 os << before <<'{' << params().filename << '}' << after;
730 // Make the filename relative to the lyx file
731 // and remove the extension so the LaTeX will use whatever is
732 // appropriate (when there are several versions in different formats)
733 string const latex_str = message.empty() ?
734 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
735 (before + '{' + params().filename + " not found!}" + after);
738 // Return how many newlines we issued.
740 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 << '<' << _("Graphic file:") << 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.get())
797 cache_->view.get()->updateInset(this, false);
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()) {
809 // Copy the new parameters.
812 // Update the inset with the new parameters.
813 cache_->update(MakeAbsPath(params().filename, filepath));
815 // We have changed data, report it.
820 InsetGraphicsParams const & InsetGraphics::params() const
826 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
828 return new InsetGraphics(*this, buffer.filePath(), same_id);