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 * If the image is from the clipart, and the document is moved to another
16 directory, the user is screwed. Need a way to handle it.
17 This amounts to a problem of when to use relative or absolute file paths
18 We should probably use what the user asks to use... but when he chooses
19 by the file dialog we normally get an absolute path and this may not be
22 Note that browseRelFile in helper_funcs.* provides a file name
23 which is relative if it is at reference path (here puffer path)
24 level or below, and an absolute path if the file name is not a
25 `natural' relative file name. In any case,
26 MakeAbsPath(filename, buf->filePath())
27 is guaranteed to provide the correct absolute path. This is what is
28 done know for include insets. Feel free to ask me -- JMarc
31 TODO Before initial production release:
33 * What advanced features the users want to do?
34 Implement them in a non latex dependent way, but a logical way.
35 LyX should translate it to latex or any other fitting format.
36 * Add a way to roll the image file into the file format.
37 * When loading, if the image is not found in the expected place, try
38 to find it in the clipart, or in the same directory with the image.
39 * Keep a tab on the image file, if it changes, update the lyx view.
40 * The image choosing dialog could show thumbnails of the image formats
41 it knows of, thus selection based on the image instead of based on
43 * Add support for the 'picins' package.
44 * Add support for the 'picinpar' package.
45 * Improve support for 'subfigure' - Allow to set the various options
51 * Current version is 1 (inset file format version), when changing it
52 * it should be changed in the Write() function when writing in one place
53 * and when reading one should change the version check and the error message.
54 * The filename is kept in the lyx file in a relative way, so as to allow
55 * moving the document file and its images with no problem.
59 * Postscript output means EPS figures.
61 * PDF output is best done with PDF figures if it's a direct conversion
62 * or PNG figures otherwise.
75 #pragma implementation
78 #include "insets/insetgraphics.h"
79 #include "insets/insetgraphicsParams.h"
81 #include "graphics/GraphicsCache.h"
82 #include "graphics/GraphicsImage.h"
84 #include "frontends/LyXView.h"
87 #include "BufferView.h"
88 #include "converter.h"
89 #include "frontends/Painter.h"
91 #include "frontends/font_metrics.h"
94 #include "LaTeXFeatures.h"
96 #include "frontends/Dialogs.h"
97 #include "frontends/Alert.h"
98 #include "frontends/controllers/helper_funcs.h" // getVectorFromString
100 #include "support/LAssert.h"
101 #include "support/filetools.h"
102 #include "support/lyxalgo.h" // lyx::count
103 #include "support/path.h"
105 #include <algorithm> // For the std::max
107 extern string system_tempdir;
112 ///////////////////////////////////////////////////////////////////////////
113 int const VersionNumber = 1;
114 ///////////////////////////////////////////////////////////////////////////
118 // This function is a utility function
119 // ... that should be with ChangeExtension ...
121 string const RemoveExtension(string const & filename)
123 return ChangeExtension(filename, string());
131 string const uniqueID()
133 static unsigned int seed = 1000;
136 ost << "graph" << ++seed;
138 // Needed if we use lyxstring.
139 return ost.str().c_str();
145 InsetGraphics::InsetGraphics()
146 : graphic_label(uniqueID()),
147 cached_status_(grfx::ErrorUnknown), cache_filled_(false), old_asc(0)
152 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
153 string const & filepath,
155 : Inset(ig, same_id),
156 graphic_label(uniqueID()),
157 cached_status_(grfx::ErrorUnknown), cache_filled_(false), old_asc(0)
159 setParams(ig.params(), filepath);
163 InsetGraphics::~InsetGraphics()
165 cached_image_.reset();
166 grfx::GCache & gc = grfx::GCache::get();
169 // Emits the hide signal to the dialog connected (if any)
174 string const InsetGraphics::statusMessage() const
178 switch (cached_status_) {
179 case grfx::WaitingToLoad:
180 msg = _("Waiting for draw request to start loading...");
183 msg = _("Loading...");
185 case grfx::Converting:
186 msg = _("Converting to loadable format...");
188 case grfx::ScalingEtc:
189 msg = _("Loaded. Scaling etc...");
191 case grfx::ErrorNoFile:
192 msg = _("No file found!");
194 case grfx::ErrorLoading:
195 msg = _("Error loading file into memory");
197 case grfx::ErrorConverting:
198 msg = _("Error converting to loadable format");
200 case grfx::ErrorScalingEtc:
201 msg = _("Error scaling etc");
203 case grfx::ErrorUnknown:
207 msg = _("Loaded but not displaying");
215 void InsetGraphics::setCache() const
220 grfx::GCache & gc = grfx::GCache::get();
221 cached_status_ = gc.status(*this);
222 cached_image_ = gc.image(*this);
226 bool InsetGraphics::drawImage() const
229 Pixmap const pixmap =
230 (cached_status_ == grfx::Loaded && cached_image_.get() != 0) ?
231 cached_image_->getPixmap() : 0;
237 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
241 old_asc = cached_image_->getHeight();
246 int InsetGraphics::descent(BufferView *, LyXFont const &) const
252 int InsetGraphics::width(BufferView *, LyXFont const & font) const
255 return cached_image_->getWidth();
259 LyXFont msgFont(font);
260 msgFont.setFamily(LyXFont::SANS_FAMILY);
262 string const justname = OnlyFilename (params().filename);
263 if (!justname.empty()) {
264 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
265 font_width = font_metrics::width(justname, msgFont);
268 string const msg = statusMessage();
270 msgFont.setSize(LyXFont::SIZE_TINY);
271 int const msg_width = font_metrics::width(msg, msgFont);
272 font_width = std::max(font_width, msg_width);
275 return std::max(50, font_width + 15);
280 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
281 int baseline, float & x, bool) const
284 grfx::ImageStatus old_status_ = cached_status_;
286 int ldescent = descent(bv, font);
287 int lascent = ascent(bv, font);
288 int lwidth = width(bv, font);
290 // we may have changed while someone other was drawing us so better
291 // to not draw anything as we surely call to redraw ourself soon.
292 // This is not a nice thing to do and should be fixed properly somehow.
293 // But I still don't know the best way to go. So let's do this like this
294 // for now (Jug 20020311)
295 if (lascent != oasc) {
299 // Make sure now that x is updated upon exit from this routine
303 // Initiate the loading of the graphics file
304 if (cached_status_ == grfx::WaitingToLoad) {
305 grfx::GCache & gc = grfx::GCache::get();
306 gc.startLoading(*this);
309 // This will draw the graphics. If the graphics has not been loaded yet,
310 // we draw just a rectangle.
311 Painter & paint = bv->painter();
314 paint.image(old_x + 2, baseline - lascent,
315 lwidth - 4, lascent + ldescent,
316 *cached_image_.get());
320 paint.rectangle(old_x + 2, baseline - lascent,
324 // Print the file name.
325 LyXFont msgFont(font);
326 msgFont.setFamily(LyXFont::SANS_FAMILY);
327 string const justname = OnlyFilename (params().filename);
328 if (!justname.empty()) {
329 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
330 paint.text(old_x + 8,
331 baseline - font_metrics::maxAscent(msgFont) - 4,
335 // Print the message.
336 string const msg = statusMessage();
338 msgFont.setSize(LyXFont::SIZE_TINY);
339 paint.text(old_x + 8, baseline - 4, msg, msgFont);
343 // the status message may mean we changed size, so indicate
344 // we need a row redraw
345 if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
346 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
349 // Reset the cache, ready for the next draw request
350 cached_status_ = grfx::ErrorUnknown;
351 cached_image_.reset();
352 cache_filled_ = false;
356 // Update the inset after parameters changed (read from file or changed in
357 // dialog. The grfx::GCache makes the decisions about whether or not to draw
358 // (interogates lyxrc, ascertains whether file exists etc)
359 void InsetGraphics::updateInset(string const & filepath) const
361 grfx::GCache & gc = grfx::GCache::get();
362 gc.update(*this, filepath);
366 void InsetGraphics::edit(BufferView *bv, int, int, mouse_button::state)
368 bv->owner()->getDialogs()->showGraphics(this);
372 void InsetGraphics::edit(BufferView * bv, bool)
374 edit(bv, 0, 0, mouse_button::none);
378 Inset::EDITABLE InsetGraphics::editable() const
384 void InsetGraphics::write(Buffer const *, ostream & os) const
386 os << "Graphics FormatVersion " << VersionNumber << '\n';
391 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
393 string const token = lex.getString();
395 if (token == "Graphics")
396 readInsetGraphics(lex);
397 else if (token == "Figure") // Compatibility reading of FigInset figures.
400 lyxerr[Debug::GRAPHICS] << "Not a Graphics or Figure inset!\n";
402 updateInset(buf->filePath());
406 void InsetGraphics::readInsetGraphics(LyXLex & lex)
408 bool finished = false;
410 while (lex.isOK() && !finished) {
413 string const token = lex.getString();
414 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
419 } else if (token == "\\end_inset") {
421 } else if (token == "FormatVersion") {
423 int version = lex.getInteger();
424 if (version > VersionNumber)
426 << "This document was created with a newer Graphics widget"
427 ", You should use a newer version of LyX to read this"
430 // TODO: Possibly open up a dialog?
433 if (! params_.Read(lex, token))
434 lyxerr << "Unknown token, " << token << ", skipping."
440 // FormatVersion < 1.0 (LyX < 1.2)
441 void InsetGraphics::readFigInset(LyXLex & lex)
443 std::vector<string> const oldUnits =
444 getVectorFromString("pt,cm,in,p%,c%");
445 bool finished = false;
446 // set the display default
447 if (lyxrc.display_graphics == "mono")
448 params_.display = InsetGraphicsParams::MONOCHROME;
449 else if (lyxrc.display_graphics == "gray")
450 params_.display = InsetGraphicsParams::GRAYSCALE;
451 else if (lyxrc.display_graphics == "color")
452 params_.display = InsetGraphicsParams::COLOR;
454 params_.display = InsetGraphicsParams::NONE;
455 while (lex.isOK() && !finished) {
458 string const token = lex.getString();
459 lyxerr[Debug::GRAPHICS] << "Token: " << token << endl;
463 else if (token == "\\end_inset") {
465 } else if (token == "file") {
467 params_.filename = lex.getString();
469 } else if (token == "extra") {
471 // kept for backwards compability. Delete in 0.13.x
472 } else if (token == "subcaption") {
474 params_.subcaptionText = lex.getString();
475 } else if (token == "label") {
477 // kept for backwards compability. Delete in 0.13.x
478 } else if (token == "angle") {
480 params_.rotate = true;
481 params_.rotateAngle = lex.getFloat();
483 } else if (token == "size") {
485 params_.lyxwidth = LyXLength(lex.getString()+"pt");
487 params_.lyxheight = LyXLength(lex.getString()+"pt");
488 params_.lyxsize_type = InsetGraphicsParams::WH;
489 } else if (token == "flags") {
491 switch (lex.getInteger()) {
492 case 1: params_.display = InsetGraphicsParams::MONOCHROME;
494 case 2: params_.display = InsetGraphicsParams::GRAYSCALE;
496 case 3: params_.display = InsetGraphicsParams::COLOR;
499 } else if (token == "subfigure") {
500 params_.subcaption = true;
501 } else if (token == "width") {
503 int i = lex.getInteger();
506 params_.scale = lex.getInteger();
507 params_.size_type = InsetGraphicsParams::SCALE;
509 params_.width = LyXLength(lex.getString()+oldUnits[i]);
510 params_.size_type = InsetGraphicsParams::WH;
514 } else if (token == "height") {
516 int i = lex.getInteger();
518 params_.height = LyXLength(lex.getString()+oldUnits[i]);
519 params_.size_type = InsetGraphicsParams::WH;
526 string const InsetGraphics::createLatexOptions() const
528 // Calculate the options part of the command, we must do it to a string
529 // stream since we might have a trailing comma that we would like to remove
530 // before writing it to the output stream.
531 ostringstream options;
532 if (!params().bb.empty())
533 options << " bb=" << strip(params().bb) << ",\n";
535 options << " draft,\n";
537 options << " clip,\n";
538 if (params().size_type == InsetGraphicsParams::WH) {
539 if (!params().width.zero())
540 options << " width=" << params().width.asLatexString() << ",\n";
541 if (!params().height.zero())
542 options << " height=" << params().height.asLatexString() << ",\n";
543 } else if (params().size_type == InsetGraphicsParams::SCALE) {
544 if (params().scale > 0)
545 options << " scale=" << double(params().scale)/100.0 << ",\n";
547 if (params().keepAspectRatio)
548 options << " keepaspectratio,\n";
549 // Make sure it's not very close to zero, a float can be effectively
550 // zero but not exactly zero.
551 if (!lyx::float_equal(params().rotateAngle, 0, 0.001) && params().rotate) {
552 options << " angle=" << params().rotateAngle << ",\n";
553 if (!params().rotateOrigin.empty()) {
554 options << " origin=" << params().rotateOrigin[0];
555 if (contains(params().rotateOrigin,"Top"))
557 else if (contains(params().rotateOrigin,"Bottom"))
559 else if (contains(params().rotateOrigin,"Baseline"))
564 if (!params().special.empty())
565 options << params().special << ",\n";
566 string opts = options.str().c_str();
567 return opts.substr(0,opts.size()-2); // delete last ",\n"
571 string findTargetFormat(string const & suffix)
573 // lyxrc.pdf_mode means:
574 // Are we creating a PDF or a PS file?
575 // (Should actually mean, are we using latex or pdflatex).
576 if (lyxrc.pdf_mode) {
577 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
578 if (contains(suffix,"ps") || suffix == "pdf")
580 else if (suffix == "jpg") // pdflatex can use jpeg
583 return "png"; // and also png
585 // If it's postscript, we always do eps.
586 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
587 if (suffix != "ps") // any other than ps
588 return "eps"; // is changed to eps
590 return suffix; // let ps untouched
596 string const InsetGraphics::prepareFile(Buffer const *buf) const
598 // LaTeX can cope if the graphics file doesn't exist, so just return the
600 string const orig_file = params().filename;
601 string const orig_file_with_path =
602 MakeAbsPath(orig_file, buf->filePath());
603 lyxerr[Debug::GRAPHICS] << "prepareFile: " << orig_file << endl
604 << " with path: " << orig_file_with_path << endl;
606 if (!IsFileReadable(orig_file_with_path))
609 // If the file is compressed and we have specified that it should not be
610 // uncompressed, then just return its name and let LaTeX do the rest!
611 bool const zipped = zippedFile(orig_file_with_path);
613 lyxerr[Debug::GRAPHICS] << "it's a zipped file\n";
614 if (zipped && params().noUnzip) {
615 lyxerr[Debug::GRAPHICS] << "pass file unzipped to LaTeX\n";
619 // "nice" means that the buffer is exported to LaTeX format but not
620 // run through the LaTeX compiler.
622 // No conversion of the graphics file is needed.
623 // Return the original filename without any extension.
625 return RemoveExtension(orig_file);
627 // We're going to be running the exported buffer through the LaTeX
628 // compiler, so must ensure that LaTeX can cope with the graphics
631 // Perform all these manipulations on a temporary file if possible.
632 // If we are not using a temp dir, then temp_file contains the
634 // to allow files with the same name in different dirs
635 // we manipulate the original file "any.dir/file.ext"
636 // to "any_dir_file.ext"! changing the dots in the
637 // dirname is important for the use of ChangeExtension
638 string temp_file(orig_file);
639 if (lyxrc.use_tempdir) {
640 string const ext_tmp = GetExtension(orig_file);
643 ChangeExtension(temp_file, string()), "/", "_");
644 // without . and again with ext
645 temp_file = ChangeExtension(
646 subst(temp_file, ".", "_"), ext_tmp);
647 // now we have any_dir_file.ext
648 temp_file = MakeAbsPath(temp_file, buf->tmppath);
650 lyxerr[Debug::GRAPHICS]
651 << "InsetGraphics::prepareFile. The temp file is: "
652 << temp_file << endl;
654 // If we are using a temp dir, then copy the file into it.
655 if (lyxrc.use_tempdir && !IsFileReadable(temp_file)) {
656 bool const success = lyx::copy(orig_file_with_path, temp_file);
657 lyxerr[Debug::GRAPHICS]
658 << "InsetGraphics::prepareFile. Copying from "
659 << orig_file << " to " << temp_file
660 << (success ? " succeeded\n" : " failed\n");
662 Alert::alert(_("Cannot copy file"), orig_file,
668 // Uncompress the file if necessary. If it has been uncompressed in
669 // a previous call to prepareFile, do nothing.
671 // What we want to end up with:
672 string const temp_file_unzipped =
673 ChangeExtension(temp_file, string());
675 if (!IsFileReadable(temp_file_unzipped)) {
676 // unzipFile generates a random filename, so move this
677 // file where we want it to go.
678 string const tmp = unzipFile(temp_file);
679 lyx::copy(tmp, temp_file_unzipped);
682 lyxerr[Debug::GRAPHICS]
683 << "InsetGraphics::prepareFile. Unzipped to "
684 << temp_file_unzipped << endl;
687 // We have an uncompressed file where we expect it,
688 // so rename temp_file and continue.
689 temp_file = temp_file_unzipped;
692 // Ascertain the graphics format that LaTeX requires.
693 // Make again an absolute path, maybe that we have no
694 // tempdir. Than temp_file=orig_file
695 string const from = lyxrc.use_tempdir ?
696 getExtFromContents(temp_file) :
697 getExtFromContents(MakeAbsPath(temp_file, buf->filePath()));
698 string const to = findTargetFormat(from);
700 // No conversion is needed. LaTeX can handle the graphics file as it is.
701 // This is true even if the orig_file is compressed.
706 string const outfile_base = RemoveExtension(temp_file);
708 lyxerr[Debug::GRAPHICS]
709 << "InsetGraphics::prepareFile. The original file is "
711 << "A copy has been made and convert is to be called with:\n"
712 << "\tfile to convert = " << temp_file << '\n'
713 << "\toutfile_base = " << outfile_base << '\n'
714 << "\t from " << from << " to " << to << '\n';
716 converters.convert(buf, temp_file, outfile_base, from, to);
717 return RemoveExtension(temp_file);
721 int InsetGraphics::latex(Buffer const *buf, ostream & os,
722 bool /*fragile*/, bool/*fs*/) const
724 // If there is no file specified or not existing,
725 // just output a message about it in the latex output.
726 lyxerr[Debug::GRAPHICS]
727 << "insetgraphics::latex: Filename = "
728 << params().filename << endl;
730 // A missing (e)ps-extension is no problem for LaTeX, so
731 // we have to test three different cases
732 string const file_(MakeAbsPath(params().filename, buf->filePath()));
733 bool const file_exists =
735 (IsFileReadable(file_) || // original
736 IsFileReadable(file_ + ".eps") || // original.eps
737 IsFileReadable(file_ + ".ps")); // original.ps
738 string const message = file_exists ?
739 string() : string("bb = 0 0 200 100, draft, type=eps]");
740 // if !message.empty() than there was no existing file
741 // "filename(.(e)ps)" found. In this case LaTeX
742 // draws only a rectangle with the above bb and the
743 // not found filename in it.
744 lyxerr[Debug::GRAPHICS]
745 << "InsetGraphics::latex. Message = \"" << message << '\"' << endl;
747 // These variables collect all the latex code that should be before and
748 // after the actual includegraphics command.
751 // Do we want subcaptions?
752 if (params().subcaption) {
753 before += "\\subfigure[" + params().subcaptionText + "]{";
756 // We never use the starred form, we use the "clip" option instead.
757 before += "\\includegraphics";
759 // Write the options if there are any.
760 string const opts = createLatexOptions();
761 lyxerr[Debug::GRAPHICS]
762 << "InsetGraphics::latex. Opts = " << opts << endl;
764 if (!opts.empty() && !message.empty())
765 before += ("[" + opts + ',' + message);
766 else if (!message.empty())
767 before += ('[' + message);
768 else if (!opts.empty())
769 before += ("[" + opts + ']');
771 lyxerr[Debug::GRAPHICS]
772 << "InsetGraphics::latex. Before = " << before
773 << "\nafter = " << after << endl;
775 // Make the filename relative to the lyx file
776 // and remove the extension so the LaTeX will use whatever is
777 // appropriate (when there are several versions in different formats)
778 string const latex_str = message.empty() ?
779 (before + '{' + prepareFile(buf) + '}' + after) :
780 (before + '{' + params().filename + " not found!}" + after);
783 // Return how many newlines we issued.
785 int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
791 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
793 // No graphics in ascii output. Possible to use gifscii to convert
794 // images to ascii approximation.
795 // 1. Convert file to ascii using gifscii
796 // 2. Read ascii output file and add it to the output stream.
797 // at least we send the filename
798 os << '<' << _("Graphic file:") << params().filename << ">\n";
803 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
805 // No graphics in LinuxDoc output. Should check how/what to add.
810 // For explanation on inserting graphics into DocBook checkout:
811 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
812 // See also the docbook guide at http://www.docbook.org/
813 int InsetGraphics::docbook(Buffer const *, ostream & os, bool mixcont) const
815 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
816 // need to switch to MediaObject. However, for now this is sufficient and
818 os << "<graphic fileref=\"&" << graphic_label << ";\">";
823 void InsetGraphics::validate(LaTeXFeatures & features) const
825 // If we have no image, we should not require anything.
826 if (params().filename.empty())
829 features.includeFile(graphic_label, RemoveExtension(params().filename));
831 features.require("graphicx");
833 if (params().subcaption)
834 features.require("subfigure");
838 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
839 string const & filepath)
841 // If nothing is changed, just return and say so.
842 if (params() == p && !p.filename.empty()) {
846 // Copy the new parameters.
849 // Update the inset with the new parameters.
850 updateInset(filepath);
852 // We have changed data, report it.
857 InsetGraphicsParams const & InsetGraphics::params() const
863 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
865 return new InsetGraphics(*this, buffer.filePath(), same_id);