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
21 [Note that browseRelFile in helper_funcs.* provides a file name
22 which is relative if it is at reference path (here puffer path)
23 level or below, and an absolute path if the file name is not a
24 `natural' relative file name. In any case,
25 MakeAbsPath(filename, buf->filePath())
26 is guaranteed to provide the correct absolute path. This is what is
27 done know for include insets. Feel free to ask me -- JMarc
30 * If we are trying to create a file in a read-only directory and there
31 are graphics that need converting, the converting will fail because
32 it is done in-place, into the same directory as the original image.
33 This needs to be fixed in the src/converter.C file
34 [ This is presumed to be fixed, needs testing.]
36 * We do not dither or resize the image in a WYSIWYM way, we load it at
37 its original size and color, resizing is done in the final output,
38 but not in the LyX window.
40 TODO Before initial production release:
41 * Replace insetfig everywhere
42 * Search for comments of the form
43 // INSET_GRAPHICS: remove this when InsetFig is thrown.
44 And act upon them. Make sure not to remove InsetFig code for the
45 1.2.0 release, only afterwards, after deployment shows InsetGraphics
47 * What advanced features the users want to do?
48 Implement them in a non latex dependent way, but a logical way.
49 LyX should translate it to latex or any other fitting format.
50 * Add a way to roll the image file into the file format.
51 * When loading, if the image is not found in the expected place, try
52 to find it in the clipart, or in the same directory with the image.
53 * Keep a tab on the image file, if it changes, update the lyx view.
54 * The image choosing dialog could show thumbnails of the image formats
55 it knows of, thus selection based on the image instead of based on
57 * Add support for the 'picins' package.
58 * Add support for the 'picinpar' package.
59 * Improve support for 'subfigure' - Allow to set the various options
65 * Current version is 1 (inset file format version), when changing it
66 * it should be changed in the Write() function when writing in one place
67 * and when reading one should change the version check and the error message.
68 * The filename is kept in the lyx file in a relative way, so as to allow
69 * moving the document file and its images with no problem.
73 * Postscript output means EPS figures.
75 * PDF output is best done with PDF figures if it's a direct conversion
76 * or PNG figures otherwise.
89 #pragma implementation
92 #include "insets/insetgraphics.h"
93 #include "insets/insetgraphicsParams.h"
95 #include "graphics/GraphicsCache.h"
96 #include "graphics/GraphicsImage.h"
101 #include "BufferView.h"
102 #include "converter.h"
105 #include "font.h" // For the lyxfont class.
108 #include "LaTeXFeatures.h"
110 #include "frontends/Dialogs.h"
111 #include "frontends/controllers/helper_funcs.h" // getVectorFromString
113 #include "support/LAssert.h"
114 #include "support/filetools.h"
115 #include "support/lyxalgo.h" // lyx::count
117 #include <algorithm> // For the std::max
119 extern string system_tempdir;
124 ///////////////////////////////////////////////////////////////////////////
125 int const VersionNumber = 1;
126 ///////////////////////////////////////////////////////////////////////////
130 // This function is a utility function
131 // ... that should be with ChangeExtension ...
133 string const RemoveExtension(string const & filename)
135 return ChangeExtension(filename, string());
143 string const unique_id()
145 static unsigned int seed = 1000;
148 ost << "graph" << ++seed;
150 // Needed if we use lyxstring.
151 return ost.str().c_str();
157 InsetGraphics::InsetGraphics()
158 : graphic_label(unique_id()),
159 cached_status_(grfx::ErrorUnknown), cache_filled_(false), old_asc(0)
164 InsetGraphics::InsetGraphics(InsetGraphics const & ig, bool same_id)
165 : Inset(ig, same_id),
167 graphic_label(unique_id()),
168 cached_status_(grfx::ErrorUnknown), cache_filled_(false), old_asc(0)
170 setParams(ig.params());
176 InsetGraphics::~InsetGraphics()
178 cached_image_.reset(0);
179 grfx::GCache & gc = grfx::GCache::get();
182 // Emits the hide signal to the dialog connected (if any)
187 string const InsetGraphics::statusMessage() const
191 switch (cached_status_) {
192 case grfx::WaitingToLoad:
193 msg = _("Waiting for draw request to start loading...");
196 msg = _("Loading...");
198 case grfx::Converting:
199 msg = _("Converting to loadable format...");
201 case grfx::ScalingEtc:
202 msg = _("Loaded. Scaling etc...");
204 case grfx::ErrorNoFile:
205 msg = _("No file found!");
207 case grfx::ErrorLoading:
208 msg = _("Error loading file into memory");
210 case grfx::ErrorConverting:
211 msg = _("Error converting to loadable format");
213 case grfx::ErrorScalingEtc:
214 msg = _("Error scaling etc");
216 case grfx::ErrorUnknown:
217 msg = _("No image associated with this inset is in the cache!");
220 msg = _("Loaded but not displaying");
228 void InsetGraphics::setCache() const
233 grfx::GCache & gc = grfx::GCache::get();
234 cached_status_ = gc.status(*this);
235 cached_image_ = gc.image(*this);
239 bool InsetGraphics::drawImage() const
242 Pixmap const pixmap =
243 (cached_status_ == grfx::Loaded && cached_image_.get() != 0) ?
244 cached_image_->getPixmap() : 0;
250 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
254 old_asc = cached_image_->getHeight();
259 int InsetGraphics::descent(BufferView *, LyXFont const &) const
265 int InsetGraphics::width(BufferView *, LyXFont const & font) const
268 return cached_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 = lyxfont::width(justname, msgFont);
281 string const msg = statusMessage();
283 msgFont.setSize(LyXFont::SIZE_TINY);
284 int const msg_width = lyxfont::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
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) {
308 // lyxerr << "IG(" << this << "): " << x << endl;
312 // Make sure now that x is updated upon exit from this routine
316 // Initiate the loading of the graphics file
317 if (cached_status_ == grfx::WaitingToLoad) {
318 grfx::GCache & gc = grfx::GCache::get();
319 gc.startLoading(*this);
322 // This will draw the graphics. If the graphics has not been loaded yet,
323 // we draw just a rectangle.
324 Painter & paint = bv->painter();
327 // lyxerr << "IG(" << this << "): " << old_x << endl;
328 paint.image(old_x + 2, baseline - lascent,
329 lwidth - 4, lascent + ldescent,
330 *cached_image_.get());
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 - lyxfont::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 // Reset the cache, ready for the next draw request
358 cached_status_ = grfx::ErrorUnknown;
359 cached_image_.reset(0);
360 cache_filled_ = false;
364 // Update the inset after parameters changed (read from file or changed in
365 // dialog. The grfx::GCache makes the decisions about whether or not to draw
366 // (interogates lyxrc, ascertains whether file exists etc)
367 void InsetGraphics::updateInset() const
369 grfx::GCache & gc = grfx::GCache::get();
374 void InsetGraphics::edit(BufferView *bv, int, int, unsigned int)
376 bv->owner()->getDialogs()->showGraphics(this);
380 void InsetGraphics::edit(BufferView * bv, bool)
386 Inset::EDITABLE InsetGraphics::editable() const
392 void InsetGraphics::write(Buffer const * buf, ostream & os) const
394 os << "Graphics FormatVersion " << VersionNumber << '\n';
395 params().Write(buf, os);
399 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
401 string const token = lex.getString();
403 if (token == "Graphics")
404 readInsetGraphics(buf, lex);
405 else if (token == "Figure") // Compatibility reading of FigInset figures.
406 readFigInset(buf, lex);
408 lyxerr[Debug::GRAPHICS] << "Not a Graphics or Figure inset!\n";
413 void InsetGraphics::readInsetGraphics(Buffer const * buf, LyXLex & lex)
415 bool finished = false;
417 while (lex.isOK() && !finished) {
420 string const token = lex.getString();
421 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
426 } else if (token == "\\end_inset") {
428 } else if (token == "FormatVersion") {
430 int version = lex.getInteger();
431 if (version > VersionNumber)
433 << "This document was created with a newer Graphics widget"
434 ", You should use a newer version of LyX to read this"
437 // TODO: Possibly open up a dialog?
440 if (! params_.Read(buf, lex, token))
441 lyxerr << "Unknown token, " << token << ", skipping."
447 // FormatVersion < 1.0 (LyX < 1.2)
448 void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
450 std::vector<string> const oldUnits =
451 getVectorFromString("pt,cm,in,p%,c%");
452 bool finished = false;
453 // set the display default
454 if (lyxrc.display_graphics == "mono")
455 params_.display = InsetGraphicsParams::MONOCHROME;
456 else if (lyxrc.display_graphics == "gray")
457 params_.display = InsetGraphicsParams::GRAYSCALE;
458 else if (lyxrc.display_graphics == "color")
459 params_.display = InsetGraphicsParams::COLOR;
461 params_.display = InsetGraphicsParams::NONE;
462 while (lex.isOK() && !finished) {
465 string const token = lex.getString();
466 lyxerr[Debug::GRAPHICS] << "Token: " << token << endl;
470 else if (token == "\\end_inset") {
472 } else if (token == "file") {
474 string const name = lex.getString();
475 string const path = buf->filePath();
476 params_.filename = MakeAbsPath(name, path);
478 } else if (token == "extra") {
480 // kept for backwards compability. Delete in 0.13.x
481 } else if (token == "subcaption") {
483 params_.subcaptionText = lex.getString();
484 params_.subcaption = true;
485 } else if (token == "label") {
487 // kept for backwards compability. Delete in 0.13.x
488 } else if (token == "angle") {
490 params_.rotate = true;
491 params_.rotateAngle = lex.getFloat();
492 } else if (token == "size") {
494 params_.lyxwidth = LyXLength(lex.getString()+"pt");
496 params_.lyxheight = LyXLength(lex.getString()+"pt");
497 } else if (token == "flags") {
499 switch (lex.getInteger()) {
500 case 1: params_.display = InsetGraphicsParams::MONOCHROME;
502 case 2: params_.display = InsetGraphicsParams::GRAYSCALE;
504 case 3: params_.display = InsetGraphicsParams::COLOR;
507 } else if (token == "subfigure") {
508 params_.subcaption = true;
509 } else if (token == "width") {
511 int i = lex.getInteger();
514 params_.scale = lex.getInteger();
515 params_.size_type = InsetGraphicsParams::SCALE;
517 params_.width = LyXLength(lex.getString()+oldUnits[i]);
518 params_.size_type = InsetGraphicsParams::WH;
522 } else if (token == "height") {
524 int i = lex.getInteger();
526 params_.height = LyXLength(lex.getString()+oldUnits[i]);
527 params_.size_type = InsetGraphicsParams::WH;
534 string const InsetGraphics::createLatexOptions() const
536 // Calculate the options part of the command, we must do it to a string
537 // stream since we might have a trailing comma that we would like to remove
538 // before writing it to the output stream.
539 ostringstream options;
540 if (!params().bb.empty())
541 options << " bb=" << strip(params().bb) << ",\n";
543 options << " draft,\n";
545 options << " clip,\n";
546 if (params().size_type == InsetGraphicsParams::WH) {
547 if (!params().width.zero())
548 options << " width=" << params().width.asLatexString() << ",\n";
549 if (!params().height.zero())
550 options << " height=" << params().height.asLatexString() << ",\n";
551 } else if (params().size_type == InsetGraphicsParams::SCALE) {
552 if (params().scale > 0)
553 options << " scale=" << double(params().scale)/100.0 << ",\n";
555 if (params().keepAspectRatio)
556 options << " keepaspectratio,\n";
557 // Make sure it's not very close to zero, a float can be effectively
558 // zero but not exactly zero.
559 if (!lyx::float_equal(params().rotateAngle, 0, 0.001) && params().rotate) {
560 options << " angle=" << params().rotateAngle << ",\n";
561 if (!params().rotateOrigin.empty()) {
562 options << " origin=" << params().rotateOrigin[0];
563 if (contains(params().rotateOrigin,"Top"))
565 else if (contains(params().rotateOrigin,"Bottom"))
567 else if (contains(params().rotateOrigin,"Baseline"))
572 if (!params().special.empty())
573 options << params().special << ",\n";
574 string opts = options.str().c_str();
575 return opts.substr(0,opts.size()-2); // delete last ",\n"
579 string findTargetFormat(string const & suffix)
581 // lyxrc.pdf_mode means:
582 // Are we creating a PDF or a PS file?
583 // (Should actually mean, are we using latex or pdflatex).
584 lyxerr[Debug::GRAPHICS] << "decideOutput: lyxrc.pdf_mode = "
585 << lyxrc.pdf_mode << std::endl;
586 if (lyxrc.pdf_mode) {
587 if (contains(suffix,"ps") || suffix == "pdf")
589 else if (suffix == "jpg")
594 // If it's postscript, we always do eps.
595 lyxerr[Debug::GRAPHICS] << "decideOutput: we have PostScript mode\n";
605 string const InsetGraphics::prepareFile(Buffer const *buf) const
607 // do_convert = Do we need to convert the file?
608 // nice = Do we create a nice version?
609 // This is used when exporting the latex file only.
611 // return original filename
613 // convert_place = temp directory
614 // return new filename in temp directory
616 // convert_place = original file directory
617 // return original filename without the extension
619 // if it's a zipped one, than let LaTeX do the rest!!!
620 string filename_ = params().filename;
621 bool const zipped = zippedFile(filename_);
623 if ((zipped && params().noUnzip) || buf->niceFile) {
624 lyxerr[Debug::GRAPHICS] << "don't unzip file or export latex"
625 << filename_ << endl;
630 filename_ = unzipFile(filename_);
632 string const from = getExtFromContents(filename_);
633 string const to = findTargetFormat(from);
636 // No conversion needed!
640 string const temp = AddName(buf->tmppath, filename_);
641 string const outfile_base = RemoveExtension(temp);
643 lyxerr[Debug::GRAPHICS] << "tempname = " << temp << "\n";
644 lyxerr[Debug::GRAPHICS] << "buf::tmppath = " << buf->tmppath << "\n";
645 lyxerr[Debug::GRAPHICS] << "filename_ = " << filename_ << "\n";
646 lyxerr[Debug::GRAPHICS] << "outfile_base = " << outfile_base << endl;
648 converters.convert(buf, filename_, outfile_base, from, to);
653 int InsetGraphics::latex(Buffer const *buf, ostream & os,
654 bool /*fragile*/, bool/*fs*/) const
656 // If there is no file specified, just output a message about it in
658 if (params().filename.empty()) {
659 os << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
660 << _("empty figure path") << "}\n";
661 return 1; // One end of line marker added to the stream.
663 // These variables collect all the latex code that should be before and
664 // after the actual includegraphics command.
667 // Do we want subcaptions?
668 if (params().subcaption) {
669 before += "\\subfigure[" + params().subcaptionText + "]{";
672 // We never use the starred form, we use the "clip" option instead.
673 before += "\\includegraphics";
674 // Write the options if there are any.
675 string const opts = createLatexOptions();
677 before += ("[%\n" + opts +']');
679 // Make the filename relative to the lyx file
680 // and remove the extension so the LaTeX will use whatever is
681 // appropriate (when there are several versions in different formats)
682 string const latex_str = before + '{' + prepareFile(buf) + '}' + after;
685 // Return how many newlines we issued.
687 int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
689 // lyxerr << "includegraphics: " << newlines << " lines of text"
695 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
697 // No graphics in ascii output. Possible to use gifscii to convert
698 // images to ascii approximation.
699 // 1. Convert file to ascii using gifscii
700 // 2. Read ascii output file and add it to the output stream.
701 // at least we send the filename
702 os << '<' << _("Graphicfile:") << params().filename << ">\n";
707 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
709 // No graphics in LinuxDoc output. Should check how/what to add.
714 // For explanation on inserting graphics into DocBook checkout:
715 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
716 // See also the docbook guide at http://www.docbook.org/
717 int InsetGraphics::docbook(Buffer const *, ostream & os) const
719 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
720 // need to switch to MediaObject. However, for now this is sufficient and
722 os << "<graphic fileref=\"&" << graphic_label << ";\">";
727 void InsetGraphics::validate(LaTeXFeatures & features) const
729 // If we have no image, we should not require anything.
730 if (params().filename.empty())
733 features.includeFile(graphic_label, RemoveExtension(params_.filename));
735 features.require("graphicx");
737 if (params().subcaption)
738 features.require("subfigure");
742 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
744 // If nothing is changed, just return and say so.
745 if (params() == p && !p.filename.empty()) {
749 // Copy the new parameters.
752 // Update the inset with the new parameters.
755 // We have changed data, report it.
760 InsetGraphicsParams const & InsetGraphics::params() const
766 Inset * InsetGraphics::clone(Buffer const &, bool same_id) const
768 return new InsetGraphics(*this, same_id);