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"
87 #include "BufferView.h"
88 #include "converter.h"
91 #include "font.h" // For the lyxfont class.
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 unique_id()
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(unique_id()),
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),
157 graphic_label(unique_id()),
158 cached_status_(grfx::ErrorUnknown), cache_filled_(false), old_asc(0)
160 setParams(ig.params(), filepath);
164 InsetGraphics::~InsetGraphics()
166 cached_image_.reset(0);
167 grfx::GCache & gc = grfx::GCache::get();
170 // Emits the hide signal to the dialog connected (if any)
175 string const InsetGraphics::statusMessage() const
179 switch (cached_status_) {
180 case grfx::WaitingToLoad:
181 msg = _("Waiting for draw request to start loading...");
184 msg = _("Loading...");
186 case grfx::Converting:
187 msg = _("Converting to loadable format...");
189 case grfx::ScalingEtc:
190 msg = _("Loaded. Scaling etc...");
192 case grfx::ErrorNoFile:
193 msg = _("No file found!");
195 case grfx::ErrorLoading:
196 msg = _("Error loading file into memory");
198 case grfx::ErrorConverting:
199 msg = _("Error converting to loadable format");
201 case grfx::ErrorScalingEtc:
202 msg = _("Error scaling etc");
204 case grfx::ErrorUnknown:
208 msg = _("Loaded but not displaying");
216 void InsetGraphics::setCache() const
221 grfx::GCache & gc = grfx::GCache::get();
222 cached_status_ = gc.status(*this);
223 cached_image_ = gc.image(*this);
227 bool InsetGraphics::drawImage() const
230 Pixmap const pixmap =
231 (cached_status_ == grfx::Loaded && cached_image_.get() != 0) ?
232 cached_image_->getPixmap() : 0;
238 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
242 old_asc = cached_image_->getHeight();
247 int InsetGraphics::descent(BufferView *, LyXFont const &) const
253 int InsetGraphics::width(BufferView *, LyXFont const & font) const
256 return cached_image_->getWidth();
260 LyXFont msgFont(font);
261 msgFont.setFamily(LyXFont::SANS_FAMILY);
263 string const justname = OnlyFilename (params().filename);
264 if (!justname.empty()) {
265 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
266 font_width = lyxfont::width(justname, msgFont);
269 string const msg = statusMessage();
271 msgFont.setSize(LyXFont::SIZE_TINY);
272 int const msg_width = lyxfont::width(msg, msgFont);
273 font_width = std::max(font_width, msg_width);
276 return std::max(50, font_width + 15);
281 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
282 int baseline, float & x, bool) const
285 grfx::ImageStatus old_status_ = cached_status_;
287 int ldescent = descent(bv, font);
288 int lascent = ascent(bv, font);
289 int lwidth = width(bv, font);
291 // we may have changed while someone other was drawing us so better
292 // to not draw anything as we surely call to redraw ourself soon.
293 // This is not a nice thing to do and should be fixed properly somehow.
294 // But I still don't know the best way to go. So let's do this like this
295 // for now (Jug 20020311)
296 if (lascent != oasc) {
300 // Make sure now that x is updated upon exit from this routine
304 // Initiate the loading of the graphics file
305 if (cached_status_ == grfx::WaitingToLoad) {
306 grfx::GCache & gc = grfx::GCache::get();
307 gc.startLoading(*this);
310 // This will draw the graphics. If the graphics has not been loaded yet,
311 // we draw just a rectangle.
312 Painter & paint = bv->painter();
315 paint.image(old_x + 2, baseline - lascent,
316 lwidth - 4, lascent + ldescent,
317 *cached_image_.get());
321 paint.rectangle(old_x + 2, baseline - lascent,
325 // Print the file name.
326 LyXFont msgFont(font);
327 msgFont.setFamily(LyXFont::SANS_FAMILY);
328 string const justname = OnlyFilename (params().filename);
329 if (!justname.empty()) {
330 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
331 paint.text(old_x + 8,
332 baseline - lyxfont::maxAscent(msgFont) - 4,
336 // Print the message.
337 string const msg = statusMessage();
339 msgFont.setSize(LyXFont::SIZE_TINY);
340 paint.text(old_x + 8, baseline - 4, msg, msgFont);
344 // the status message may mean we changed size, so indicate
345 // we need a row redraw
346 if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
347 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
350 // Reset the cache, ready for the next draw request
351 cached_status_ = grfx::ErrorUnknown;
352 cached_image_.reset(0);
353 cache_filled_ = false;
357 // Update the inset after parameters changed (read from file or changed in
358 // dialog. The grfx::GCache makes the decisions about whether or not to draw
359 // (interogates lyxrc, ascertains whether file exists etc)
360 void InsetGraphics::updateInset(string const & filepath) const
362 grfx::GCache & gc = grfx::GCache::get();
363 gc.update(*this, filepath);
367 void InsetGraphics::edit(BufferView *bv, int, int, unsigned int)
369 bv->owner()->getDialogs()->showGraphics(this);
373 void InsetGraphics::edit(BufferView * bv, bool)
379 Inset::EDITABLE InsetGraphics::editable() const
385 void InsetGraphics::write(Buffer const *, ostream & os) const
387 os << "Graphics FormatVersion " << VersionNumber << '\n';
392 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
394 string const token = lex.getString();
396 if (token == "Graphics")
397 readInsetGraphics(lex);
398 else if (token == "Figure") // Compatibility reading of FigInset figures.
401 lyxerr[Debug::GRAPHICS] << "Not a Graphics or Figure inset!\n";
403 updateInset(buf->filePath());
407 void InsetGraphics::readInsetGraphics(LyXLex & lex)
409 bool finished = false;
411 while (lex.isOK() && !finished) {
414 string const token = lex.getString();
415 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
420 } else if (token == "\\end_inset") {
422 } else if (token == "FormatVersion") {
424 int version = lex.getInteger();
425 if (version > VersionNumber)
427 << "This document was created with a newer Graphics widget"
428 ", You should use a newer version of LyX to read this"
431 // TODO: Possibly open up a dialog?
434 if (! params_.Read(lex, token))
435 lyxerr << "Unknown token, " << token << ", skipping."
441 // FormatVersion < 1.0 (LyX < 1.2)
442 void InsetGraphics::readFigInset(LyXLex & lex)
444 std::vector<string> const oldUnits =
445 getVectorFromString("pt,cm,in,p%,c%");
446 bool finished = false;
447 // set the display default
448 if (lyxrc.display_graphics == "mono")
449 params_.display = InsetGraphicsParams::MONOCHROME;
450 else if (lyxrc.display_graphics == "gray")
451 params_.display = InsetGraphicsParams::GRAYSCALE;
452 else if (lyxrc.display_graphics == "color")
453 params_.display = InsetGraphicsParams::COLOR;
455 params_.display = InsetGraphicsParams::NONE;
456 while (lex.isOK() && !finished) {
459 string const token = lex.getString();
460 lyxerr[Debug::GRAPHICS] << "Token: " << token << endl;
464 else if (token == "\\end_inset") {
466 } else if (token == "file") {
468 params_.filename = lex.getString();
470 } else if (token == "extra") {
472 // kept for backwards compability. Delete in 0.13.x
473 } else if (token == "subcaption") {
475 params_.subcaptionText = lex.getString();
476 } else if (token == "label") {
478 // kept for backwards compability. Delete in 0.13.x
479 } else if (token == "angle") {
481 params_.rotate = true;
482 params_.rotateAngle = lex.getFloat();
484 } else if (token == "size") {
486 params_.lyxwidth = LyXLength(lex.getString()+"pt");
488 params_.lyxheight = LyXLength(lex.getString()+"pt");
489 params_.lyxsize_type = InsetGraphicsParams::WH;
490 } else if (token == "flags") {
492 switch (lex.getInteger()) {
493 case 1: params_.display = InsetGraphicsParams::MONOCHROME;
495 case 2: params_.display = InsetGraphicsParams::GRAYSCALE;
497 case 3: params_.display = InsetGraphicsParams::COLOR;
500 } else if (token == "subfigure") {
501 params_.subcaption = true;
502 } else if (token == "width") {
504 int i = lex.getInteger();
507 params_.scale = lex.getInteger();
508 params_.size_type = InsetGraphicsParams::SCALE;
510 params_.width = LyXLength(lex.getString()+oldUnits[i]);
511 params_.size_type = InsetGraphicsParams::WH;
515 } else if (token == "height") {
517 int i = lex.getInteger();
519 params_.height = LyXLength(lex.getString()+oldUnits[i]);
520 params_.size_type = InsetGraphicsParams::WH;
527 string const InsetGraphics::createLatexOptions() const
529 // Calculate the options part of the command, we must do it to a string
530 // stream since we might have a trailing comma that we would like to remove
531 // before writing it to the output stream.
532 ostringstream options;
533 if (!params().bb.empty())
534 options << " bb=" << strip(params().bb) << ",\n";
536 options << " draft,\n";
538 options << " clip,\n";
539 if (params().size_type == InsetGraphicsParams::WH) {
540 if (!params().width.zero())
541 options << " width=" << params().width.asLatexString() << ",\n";
542 if (!params().height.zero())
543 options << " height=" << params().height.asLatexString() << ",\n";
544 } else if (params().size_type == InsetGraphicsParams::SCALE) {
545 if (params().scale > 0)
546 options << " scale=" << double(params().scale)/100.0 << ",\n";
548 if (params().keepAspectRatio)
549 options << " keepaspectratio,\n";
550 // Make sure it's not very close to zero, a float can be effectively
551 // zero but not exactly zero.
552 if (!lyx::float_equal(params().rotateAngle, 0, 0.001) && params().rotate) {
553 options << " angle=" << params().rotateAngle << ",\n";
554 if (!params().rotateOrigin.empty()) {
555 options << " origin=" << params().rotateOrigin[0];
556 if (contains(params().rotateOrigin,"Top"))
558 else if (contains(params().rotateOrigin,"Bottom"))
560 else if (contains(params().rotateOrigin,"Baseline"))
565 if (!params().special.empty())
566 options << params().special << ",\n";
567 string opts = options.str().c_str();
568 return opts.substr(0,opts.size()-2); // delete last ",\n"
572 string findTargetFormat(string const & suffix)
574 // lyxrc.pdf_mode means:
575 // Are we creating a PDF or a PS file?
576 // (Should actually mean, are we using latex or pdflatex).
577 lyxerr[Debug::GRAPHICS] << "findTargetFormat: lyxrc.pdf_mode = "
578 << lyxrc.pdf_mode << std::endl;
579 if (lyxrc.pdf_mode) {
580 if (contains(suffix,"ps") || suffix == "pdf")
582 else if (suffix == "jpg")
587 // If it's postscript, we always do eps.
588 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
598 string const InsetGraphics::prepareFile(Buffer const *buf) const
600 // LaTeX can cope if the graphics file doesn't exist, so just return the
602 string const orig_file = params().filename;
603 string const orig_file_with_path =
604 MakeAbsPath(orig_file, buf->filePath());
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);
612 if (zipped && params().noUnzip) {
616 // "nice" means that the buffer is exported to LaTeX format but not
617 // run through the LaTeX compiler.
619 // No conversion of the graphics file is needed.
620 // Return the original filename without any extension.
622 return RemoveExtension(orig_file);
624 // We're going to be running the exported buffer through the LaTeX
625 // compiler, so must ensure that LaTeX can cope with the graphics
628 // Perform all these manipulations on a temporary file if possible.
629 // If we are not using a temp dir, then temp_file contains the
631 string temp_file = MakeAbsPath(OnlyFilename(orig_file), buf->tmppath);
633 lyxerr[Debug::GRAPHICS]
634 << "InsetGraphics::prepareFile. The temp file is: "
635 << temp_file << endl;
637 // If we are using a temp dir, then copy the file into it.
638 if (lyxrc.use_tempdir && !IsFileReadable(temp_file)) {
639 bool const success = lyx::copy(orig_file_with_path, temp_file);
640 lyxerr[Debug::GRAPHICS]
641 << "InsetGraphics::prepareFile. Copying from "
642 << orig_file << " to " << temp_file
643 << (success ? " succeeded\n" : " failed\n");
645 Alert::alert(_("Cannot copy file"), orig_file,
651 // Uncompress the file if necessary. If it has been uncompressed in
652 // a previous call to prepareFile, do nothing.
654 // What we want to end up with:
655 string const temp_file_unzipped =
656 ChangeExtension(temp_file, string());
658 if (!IsFileReadable(temp_file_unzipped)) {
659 // unzipFile generates a random filename, so move this
660 // file where we want it to go.
661 string const tmp = unzipFile(temp_file);
662 lyx::copy(tmp, temp_file_unzipped);
665 lyxerr[Debug::GRAPHICS]
666 << "InsetGraphics::prepareFile. Unzipped to "
667 << temp_file_unzipped << endl;
670 // We have an uncompressed file where we expect it,
671 // so rename temp_file and continue.
672 temp_file = temp_file_unzipped;
675 // Ascertain the graphics format that LaTeX requires.
676 string const from = getExtFromContents(temp_file);
677 string const to = findTargetFormat(from);
679 // No conversion is needed. LaTeX can handle the graphics file as it is.
680 // This is true even if the orig_file is compressed.
685 string const outfile_base = RemoveExtension(temp_file);
687 lyxerr[Debug::GRAPHICS]
688 << "InsetGraphics::prepareFile. The original file is "
689 << orig_file << ".\n"
690 << "A copy has been made and convert is to be called with:\n"
691 << "\tfile to convert = " << temp_file << '\n'
692 << "\toutfile_base = " << outfile_base << '\n'
693 << "\t from " << from << " to " << to << '\n';
695 converters.convert(buf, temp_file, outfile_base, from, to);
696 return RemoveExtension(temp_file);
700 int InsetGraphics::latex(Buffer const *buf, ostream & os,
701 bool /*fragile*/, bool/*fs*/) const
703 // If there is no file specified or not existing,
704 // just output a message about it in the latex output.
705 lyxerr[Debug::GRAPHICS]
706 << "insetgraphics::latex: Filename = "
707 << params().filename << endl;
709 // A missing (e)ps-extension is no problem for LaTeX, so
710 // we have to test three different cases
711 string const file_(MakeAbsPath(params().filename, buf->filePath()));
712 bool const file_exists =
714 (IsFileReadable(file_) || // original
715 IsFileReadable(file_ + ".eps") || // original.eps
716 IsFileReadable(file_ + ".ps")); // original.ps
717 string const message = file_exists ?
718 string() : string("bb = 0 0 200 100, draft, type=eps]");
719 // if !message.empty() than there was no existing file
720 // "filename(.(e)ps)" found. In this case LaTeX
721 // draws only a rectangle with the above bb and the
722 // not found filename in it.
723 lyxerr[Debug::GRAPHICS]
724 << "InsetGraphics::latex. Message = \"" << message << '\"' << endl;
726 // These variables collect all the latex code that should be before and
727 // after the actual includegraphics command.
730 // Do we want subcaptions?
731 if (params().subcaption) {
732 before += "\\subfigure[" + params().subcaptionText + "]{";
735 // We never use the starred form, we use the "clip" option instead.
736 before += "\\includegraphics";
738 // Write the options if there are any.
739 string const opts = createLatexOptions();
740 lyxerr[Debug::GRAPHICS]
741 << "InsetGraphics::latex. Opts = " << opts << endl;
743 if (!opts.empty() && !message.empty())
744 before += ("[" + opts + ',' + message);
745 else if (!message.empty())
746 before += ('[' + message);
747 else if (!opts.empty())
748 before += ("[" + opts + ']');
750 lyxerr[Debug::GRAPHICS]
751 << "InsetGraphics::latex. Before = " << before
752 << "\nafter = " << after << endl;
754 // Make the filename relative to the lyx file
755 // and remove the extension so the LaTeX will use whatever is
756 // appropriate (when there are several versions in different formats)
757 string const latex_str = message.empty() ?
758 (before + '{' + prepareFile(buf) + '}' + after) :
759 (before + '{' + params().filename + " not found!}" + after);
762 // Return how many newlines we issued.
764 int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
770 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
772 // No graphics in ascii output. Possible to use gifscii to convert
773 // images to ascii approximation.
774 // 1. Convert file to ascii using gifscii
775 // 2. Read ascii output file and add it to the output stream.
776 // at least we send the filename
777 os << '<' << _("Graphic file:") << params().filename << ">\n";
782 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
784 // No graphics in LinuxDoc output. Should check how/what to add.
789 // For explanation on inserting graphics into DocBook checkout:
790 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
791 // See also the docbook guide at http://www.docbook.org/
792 int InsetGraphics::docbook(Buffer const *, ostream & os) const
794 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
795 // need to switch to MediaObject. However, for now this is sufficient and
797 os << "<graphic fileref=\"&" << graphic_label << ";\">";
802 void InsetGraphics::validate(LaTeXFeatures & features) const
804 // If we have no image, we should not require anything.
805 if (params().filename.empty())
808 features.includeFile(graphic_label, RemoveExtension(params_.filename));
810 features.require("graphicx");
812 if (params().subcaption)
813 features.require("subfigure");
817 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
818 string const & filepath)
820 // If nothing is changed, just return and say so.
821 if (params() == p && !p.filename.empty()) {
825 // Copy the new parameters.
828 // Update the inset with the new parameters.
829 updateInset(filepath);
831 // We have changed data, report it.
836 InsetGraphicsParams const & InsetGraphics::params() const
842 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
844 return new InsetGraphics(*this, buffer.filePath(), same_id);