1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995-2001 the LyX Team.
8 * This file Copyright 2000 Baruch Even.
9 * ====================================================== */
13 * Switch to convert the images in the background, this requires work on
14 the converter, the systemcontroller and the graphics cache.
17 * Pop up a dialog if the widget version is higher than what we accept.
18 * Provide sed/awk/C code to downgrade from InsetGraphics to FigInset(?)
25 * If the image is from the clipart, and the document is moved to another
26 directory, the user is screwed. Need a way to handle it.
27 This amounts to a problem of when to use relative or absolute file paths
28 We should probably use what the user asks to use... but when he chooses
29 by the file dialog we normally get an absolute path and this may not be
31 * Bug in FileDlg class (src/filedlg.[hC]) when selecting a file and then
32 pressing ok, it counts as if no real selection done. Apparently
33 when choosing a file it doesn't update the select file input line.
35 * If we are trying to create a file in a read-only directory and there
36 are graphics that need converting, the converting will fail because
37 it is done in-place, into the same directory as the original image.
38 This needs to be fixed in the src/converter.C file
39 [ This is presumed to be fixed, needs testing.]
41 * We do not dither or resize the image in a WYSIWYM way, we load it at
42 its original size and color, resizing is done in the final output,
43 but not in the LyX window.
45 TODO Before initial production release:
46 * Replace insetfig everywhere
47 * Search for comments of the form
48 // INSET_GRAPHICS: remove this when InsetFig is thrown.
49 And act upon them. Make sure not to remove InsetFig code for the
50 1.2.0 release, only afterwards, after deployment shows InsetGraphics
53 TODO Extended features:
55 * Advanced Latex tab folder.
56 * Add support for more features so that it will be better than insetfig.
57 * Keep aspect ratio radio button
58 * Support for complete control over the latex parameters for TeXperts
59 * What advanced features the users want to do?
60 Implement them in a non latex dependent way, but a logical way.
61 LyX should translate it to latex or any other fitting format.
62 * Add a way to roll the image file into the file format.
63 * When loading, if the image is not found in the expected place, try
64 to find it in the clipart, or in the same directory with the image.
65 * Keep a tab on the image file, if it changes, update the lyx view.
66 * The image choosing dialog could show thumbnails of the image formats
67 it knows of, thus selection based on the image instead of based on
69 * Add support for the 'picins' package.
70 * Add support for the 'picinpar' package.
71 * Improve support for 'subfigure' - Allow to set the various options
73 * Add resizing by percentage of image size (50%, 150%) - usefull for two
74 images of different size to be resized where they both should have
75 the same scale compared to each other.
81 * This is currently a moving target, I'm trying stuff and learning what
82 * is needed and how to accomplish it, since there is no predefined goal or
83 * way to go I invent it as I go.
85 * My current intention is for seperation from LaTeX, the basic needs are
86 * resizing and rotating, displaying on screen in various depths and printing
87 * conversion of depths (independent of the display depth). For this I'll
88 * provide a simple interface.
90 * The medium level includes clipping of the image, but in a limited way.
92 * For the LaTeX gurus I'll provide a complete control over the output, but
93 * this is latex dependent and guru dependent so I'd rather avoid doing this
94 * for the normal user. This stuff includes clipping, special image size
95 * specifications (\textwidth\minus 2in) which I see no way to generalize
96 * to non-latex specific way.
99 * 'graphicx' for the graphics inclusion.
100 * 'subfigure' for the subfigures.
104 * Current version is 1 (inset file format version), when changing it
105 * it should be changed in the Write() function when writing in one place
106 * and when reading one should change the version check and the error message.
108 * The filename is kept in the lyx file in a relative way, so as to allow
109 * moving the document file and its images with no problem.
112 * Postscript output means EPS figures.
114 * PDF output is best done with PDF figures if it's a direct conversion
115 * or PNG figures otherwise.
127 #pragma implementation
130 #include "insets/insetgraphics.h"
131 #include "insets/insetgraphicsParams.h"
132 #include "graphics/GraphicsCache.h"
133 #include "graphics/GraphicsCacheItem.h"
135 #include "frontends/Dialogs.h"
138 #include "BufferView.h"
139 #include "converter.h"
140 #include "frontends/support/LyXImage.h"
142 #include "lyx_gui_misc.h"
143 #include "support/FileInfo.h"
144 #include "support/filetools.h"
145 #include "support/lyxlib.h"
148 #include "font.h" // For the lyxfont class.
149 #include <algorithm> // For the std::max
150 #include "support/lyxmanip.h"
154 extern string system_tempdir;
160 // This function is a utility function
162 string const RemoveExtension(string const & filename)
164 return ChangeExtension(filename, string());
168 // Initialize only those variables that do not have a constructor.
169 InsetGraphics::InsetGraphics()
170 : cacheHandle(0), imageLoaded(false)
174 InsetGraphics::InsetGraphics(InsetGraphics const & ig, bool same_id)
175 : Inset(), SigC::Object()
176 , cacheHandle(ig.cacheHandle)
177 , imageLoaded(ig.imageLoaded)
179 setParams(ig.getParams());
185 InsetGraphics::~InsetGraphics()
187 // Emits the hide signal to the dialog connected (if any)
193 InsetGraphics::statusMessage() const
197 if (cacheHandle.get()) {
198 switch (cacheHandle->getImageStatus()) {
199 case GraphicsCacheItem::UnknownError:
200 msg = _("Unknown Error");
203 case GraphicsCacheItem::Loading:
204 msg = _("Loading...");
207 case GraphicsCacheItem::ErrorReading:
208 msg = _("Error reading");
211 case GraphicsCacheItem::ErrorConverting:
212 msg = _("Error converting");
215 case GraphicsCacheItem::Loaded:
216 // No message to write.
225 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
227 LyXImage * pixmap = 0;
228 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
229 return pixmap->getHeight();
235 int InsetGraphics::descent(BufferView *, LyXFont const &) const
237 // this is not true if viewport is used and clip is not.
242 int InsetGraphics::width(BufferView *, LyXFont const & font) const
244 LyXImage * pixmap = 0;
246 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
247 return pixmap->getWidth();
249 string const msg = statusMessage();
253 font_width = lyxfont::width(msg, font);
255 return std::max(50, font_width + 15);
260 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
261 int baseline, float & x, bool) const
263 Painter & paint = bv->painter();
265 int ldescent = descent(bv, font);
266 int lascent = ascent(bv, font);
267 int lwidth = width(bv, font);
269 // Make sure x is updated upon exit from this routine
273 // This will draw the graphics. If the graphics has not been loaded yet,
274 // we draw just a rectangle.
277 paint.image(old_x + 2, baseline - lascent,
278 lwidth - 4, lascent + ldescent,
279 cacheHandle->getImage());
282 // Get the image status, default to unknown error.
283 GraphicsCacheItem::ImageStatus status = GraphicsCacheItem::UnknownError;
284 if (cacheHandle.get())
285 status = cacheHandle->getImageStatus();
287 // Check if the image is now ready.
288 if (status == GraphicsCacheItem::Loaded) {
291 // Tell BufferView we need to be updated!
292 bv->text->status(bv, LyXText::CHANGED_IN_DRAW);
297 paint.rectangle(old_x + 2, baseline - lascent,
301 string const msg = statusMessage();
303 // Print the message.
304 LyXFont msgFont(font);
305 msgFont.setFamily(LyXFont::SANS_FAMILY);
306 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
307 string const justname = OnlyFilename (params.filename);
308 paint.text(old_x + 8,
309 baseline - lyxfont::maxAscent(msgFont) - 4,
312 msgFont.setSize(LyXFont::SIZE_TINY);
313 paint.text(old_x + 8, baseline - 4, msg, msgFont);
319 void InsetGraphics::edit(BufferView *bv, int, int, unsigned int)
321 bv->owner()->getDialogs()->showGraphics(this);
325 void InsetGraphics::edit(BufferView * bv, bool)
331 Inset::EDITABLE InsetGraphics::editable() const
337 void InsetGraphics::write(Buffer const * buf, ostream & os) const
339 os << "Graphics FormatVersion 1\n";
341 params.Write(buf, os);
345 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
347 string const token = lex.GetString();
349 if (token == "Graphics")
350 readInsetGraphics(buf, lex);
351 else if (token == "Figure") // Compatibility reading of FigInset figures.
352 readFigInset(buf, lex);
354 lyxerr[Debug::INFO] << "Not a Graphics or Figure inset!\n";
359 void InsetGraphics::readInsetGraphics(Buffer const * buf, LyXLex & lex)
361 bool finished = false;
363 while (lex.IsOK() && !finished) {
366 string const token = lex.GetString();
367 lyxerr[Debug::INFO] << "Token: '" << token << '\''
372 } else if (token == "\\end_inset") {
374 } else if (token == "FormatVersion") {
376 int version = lex.GetInteger();
379 << "This document was created with a newer Graphics widget"
380 ", You should use a newer version of LyX to read this"
383 // TODO: Possibly open up a dialog?
386 if (! params.Read(buf, lex, token))
387 lyxerr << "Unknown token, " << token << ", skipping."
394 void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
396 bool finished = false;
398 while (lex.IsOK() && !finished) {
401 string const token = lex.GetString();
402 lyxerr[Debug::INFO] << "Token: " << token << endl;
406 else if (token == "\\end_inset") {
408 } else if (token == "file") {
410 string const name = lex.GetString();
411 string const path = OnlyPath(buf->fileName());
412 params.filename = MakeAbsPath(name, path);
414 } else if (token == "extra") {
416 // kept for backwards compability. Delete in 0.13.x
417 } else if (token == "subcaption") {
419 params.subcaptionText = lex.GetString();
420 } else if (token == "label") {
422 // kept for backwards compability. Delete in 0.13.x
423 } else if (token == "angle") {
425 params.rotateAngle = lex.GetFloat();
426 } else if (token == "size") {
427 // Size of image on screen is ignored in InsetGraphics, just eat
433 } else if (token == "flags") {
434 InsetGraphicsParams::DisplayType tmp = InsetGraphicsParams::COLOR;
436 switch (lex.GetInteger()) {
437 case 1: tmp = InsetGraphicsParams::MONOCHROME; break;
438 case 2: tmp = InsetGraphicsParams::GRAYSCALE; break;
440 params.display = tmp;
441 } else if (token == "subfigure") {
442 params.subcaption = true;
443 } else if (token == "width") {
445 params.widthResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
447 params.widthSize = lex.GetFloat();
448 } else if (token == "height") {
450 params.heightResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
452 params.heightSize = lex.GetFloat();
460 void formatResize(ostream & os, string const & key,
461 InsetGraphicsParams::Resize resizeType, double size)
463 switch (resizeType) {
464 case InsetGraphicsParams::DEFAULT_SIZE:
467 case InsetGraphicsParams::CM:
468 os << key << '=' << size << "cm,";
471 case InsetGraphicsParams::INCH:
472 os << key << '=' << size << "in,";
475 case InsetGraphicsParams::PERCENT_PAGE:
476 os << key << '=' << size / 100 << "\\text" << key << ',';
479 case InsetGraphicsParams::PERCENT_COLUMN:
480 os << key << '=' << size / 100 << "\\column" << key << ',';
490 InsetGraphics::createLatexOptions() const
492 // Calculate the options part of the command, we must do it to a string
493 // stream since we might have a trailing comma that we would like to remove
494 // before writing it to the output stream.
495 ostringstream options;
497 formatResize(options, "width", params.widthResize, params.widthSize);
498 formatResize(options, "height", params.heightResize, params.heightSize);
500 // Make sure it's not very close to zero, a float can be effectively
501 // zero but not exactly zero.
502 if (lyx::float_equal(params.rotateAngle, 0, 0.001)) {
504 << params.rotateAngle << ',';
507 string opts = options.str().c_str();
508 opts = strip(opts, ',');
515 string decideOutputImageFormat(string const & in_fmt)
517 // lyxrc.pdf_mode means:
518 // Are we creating a PDF or a PS file?
519 // (Should actually mean, are we using latex or pdflatex).
521 if (lyxrc.pdf_mode) {
522 if (in_fmt == "eps" || in_fmt == "epsi" || in_fmt == "pdf")
524 else if (in_fmt == "jpg" || in_fmt == "jpeg")
530 // If it's postscript, we always do eps.
531 if (in_fmt == "eps" || in_fmt == "epsi")
532 return in_fmt; // eps & epsi are both eps, but different extension.
539 InsetGraphics::prepareFile(Buffer const *buf) const
542 // do_convert = Do we need to convert the file?
543 // nice = Do we create a nice version?
544 // This is used when exporting the latex file only.
548 // return original filename
551 // convert_place = temp directory
552 // return new filename in temp directory
554 // convert_place = original file directory
555 // return original filename without the extension
558 // Get the extension (format) of the original file.
559 string const extension = GetExtension(params.filename);
561 // Are we creating a PDF or a PS file?
562 // (Should actually mean, are we usind latex or pdflatex).
563 string const image_target = decideOutputImageFormat(extension);
565 if (extension == image_target)
566 return params.filename;
569 if (!buf->niceFile) {
570 string const temp = AddName(buf->tmppath, params.filename);
571 outfile = RemoveExtension(temp);
573 //lyxerr << "buf::tmppath = " << buf->tmppath << "\n";
574 //lyxerr << "filename = " << params.filename << "\n";
575 //lyxerr << "temp = " << temp << "\n";
576 //lyxerr << "outfile = " << outfile << endl;
578 string const path = OnlyPath(buf->fileName());
579 string const relname = MakeRelPath(params.filename, path);
580 outfile = RemoveExtension(relname);
583 converters.Convert(buf, params.filename, outfile, extension, image_target);
589 int InsetGraphics::latex(Buffer const *buf, ostream & os,
590 bool /*fragile*/, bool/*fs*/) const
592 // MISSING: We have to decide how to do the order of the options
593 // that is dependent of order, like width, height, angle. Should
594 // we rotate before scale? Should we let the user decide?
595 // bool rot_before_scale; ?
597 // (BE) As a first step we should do a scale before rotate since this is
598 // more like the natural thought of how to do it.
599 // (BE) I believe that a priority list presented to the user with
600 // a default order would be the best, though it would be better to
601 // hide such a thing in an "Advanced options" dialog.
602 // (BE) This should go an advanced LaTeX options dialog.
604 // If there is no file specified, just output a message about it in
606 if (params.filename.empty()) {
607 os << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
608 << _("empty figure path")
611 return 1; // One end of line marker added to the stream.
614 // Keep count of newlines that we issued.
617 // This variables collect all the latex code that should be before and
618 // after the actual includegraphics command.
622 // Do we want subcaptions?
623 if (params.subcaption) {
624 before += "\\subfigure[" + params.subcaptionText + "]{";
628 // We never use the starred form, we use the "clip" option instead.
629 os << before << "\\includegraphics";
631 // Write the options if there are any.
632 string const opts = createLatexOptions();
634 os << '[' << opts << ']';
637 // Make the filename relative to the lyx file
638 // and remove the extension so the LaTeX will use whatever is
639 // appropriate (when there are several versions in different formats)
640 string const filename = prepareFile(buf);
642 os << '{' << filename << '}' << after;
644 // Return how many newlines we issued.
649 int InsetGraphics::ascii(Buffer const *, ostream &, int) const
651 // No graphics in ascii output. Possible to use gifscii to convert
652 // images to ascii approximation.
654 // 1. Convert file to ascii using gifscii
655 // 2. Read ascii output file and add it to the output stream.
661 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
663 // No graphics in LinuxDoc output. Should check how/what to add.
668 // For explanation on inserting graphics into DocBook checkout:
669 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
670 // See also the docbook guide at http://www.docbook.org/
671 int InsetGraphics::docBook(Buffer const * buf, ostream & os) const
673 // Change the path to be relative to the main file.
674 string const buffer_dir = OnlyPath(buf->fileName());
675 string const filename = RemoveExtension(
676 MakeRelPath(params.filename, buffer_dir));
678 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
679 // need to switch to MediaObject. However, for now this is sufficient and
681 os << "<graphic fileref=\"" << filename << "\"></graphic>";
686 void InsetGraphics::validate(LaTeXFeatures & features) const
688 // If we have no image, we should not require anything.
689 if (params.filename.empty())
692 features.graphicx = true;
694 if (params.subcaption)
695 features.subfigure = true;
699 // Update the inset after parameters changed (read from file or changed in
701 void InsetGraphics::updateInset() const
703 GraphicsCache & gc = GraphicsCache::getInstance();
704 boost::shared_ptr<GraphicsCacheItem> temp(0);
706 // We do it this way so that in the face of some error, we will still
707 // be in a valid state.
708 if (!params.filename.empty()) {
709 temp = gc.addFile(params.filename);
712 // Mark the image as unloaded so that it gets updated.
719 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
721 // If nothing is changed, just return and say so.
725 // Copy the new parameters.
728 // Update the inset with the new parameters.
731 // We have changed data, report it.
736 InsetGraphicsParams InsetGraphics::getParams() const
742 Inset * InsetGraphics::clone(Buffer const &, bool same_id) const
744 return new InsetGraphics(*this, same_id);