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 * ====================================================== */
12 How to use it for now:
13 * The lyxfunc 'graphics-insert' will insert this inset into the document.
18 * Switch to convert the images in the background, this requires work on
19 the converter, the systemcontroller and the graphics cache.
22 * Pop up a dialog if the widget version is higher than what we accept.
23 * Prepare code to read FigInset insets to upgrade upwards
24 * Provide sed/awk/C code to downgrade from InsetGraphics to FigInset(?)
31 * If the image is from the clipart, and the document is moved to another
32 directory, the user is screwed. Need a way to handle it.
33 This amounts to a problem of when to use relative or absolute file paths
34 We should probably use what the user asks to use... but when he chooses
35 by the file dialog we normally get an absolute path and this may not be
37 * Bug in FileDlg class (src/filedlg.[hC]) when selecting a file and then
38 pressing ok, it counts as if no real selection done. Apparently
39 when choosing a file it doesn't update the select file input line.
41 * If we are trying to create a file in a read-only directory and there
42 are graphics that need converting, the converting will fail because
43 it is done in-place, into the same directory as the original image.
44 This needs to be fixed in the src/converter.C file
45 [ This is presumed to be fixed, needs testing.]
47 * We do not dither or resize the image in a WYSIWYM way, we load it at
48 its original size and color, resizing is done in the final output,
49 but not in the LyX window.
51 TODO Before initial production release:
52 * Replace insetfig everywhere
53 * Read it's file format
54 * Get created by all commands used to create figinset currently.
55 * Search for comments of the form
56 // INSET_GRAPHICS: remove this when InsetFig is thrown.
59 TODO Extended features:
61 * Advanced Latex tab folder.
62 * Add support for more features so that it will be better than insetfig.
63 * Keep aspect ratio radio button
64 * Support for complete control over the latex parameters for TeXperts
65 * What advanced features the users want to do?
66 Implement them in a non latex dependent way, but a logical way.
67 LyX should translate it to latex or any other fitting format.
68 * Add a way to roll the image file into the file format.
69 * When loading, if the image is not found in the expected place, try
70 to find it in the clipart, or in the same directory with the image.
71 * Keep a tab on the image file, if it changes, update the lyx view.
72 * The image choosing dialog could show thumbnails of the image formats
73 it knows of, thus selection based on the image instead of based on
75 * Add support for the 'picins' package.
76 * Add support for the 'picinpar' package.
77 * Improve support for 'subfigure' - Allow to set the various options
84 * This is currently a moving target, I'm trying stuff and learning what
85 * is needed and how to accomplish it, since there is no predefined goal or
86 * way to go I invent it as I go.
88 * My current intention is for seperation from LaTeX, the basic needs are
89 * resizing and rotating, displaying on screen in various depths and printing
90 * conversion of depths (independent of the display depth). For this I'll
91 * provide a simple interface.
93 * The medium level includes clipping of the image, but in a limited way.
95 * For the LaTeX gurus I'll provide a complete control over the output, but
96 * this is latex dependent and guru dependent so I'd rather avoid doing this
97 * for the normal user. This stuff includes clipping, special image size
98 * specifications (\textwidth\minus 2in) which I see no way to generalize
99 * to non-latex specific way.
102 * 'graphicx' for the graphics inclusion.
103 * 'subfigure' for the subfigures.
107 * Current version is 1 (inset file format version), when changing it
108 * it should be changed in the Write() function when writing in one place
109 * and when reading one should change the version check and the error message.
111 * The filename is kept in the lyx file in a relative way, so as to allow
112 * moving the document file and its images with no problem.
116 * Apparently the PNG output is preferred over PDF images when doing PDF
117 * documents (i.e. prefer imagemagick eps2png over eps2pdf)
123 #pragma implementation
126 #include "insets/insetgraphics.h"
127 #include "insets/insetgraphicsParams.h"
128 #include "graphics/GraphicsCache.h"
129 #include "graphics/GraphicsCacheItem.h"
131 #include "frontends/Dialogs.h"
134 #include "BufferView.h"
135 #include "converter.h"
136 #include "frontends/support/LyXImage.h"
138 #include "lyx_gui_misc.h"
139 #include "support/FileInfo.h"
140 #include "support/filetools.h"
141 #include "support/lyxlib.h"
144 #include "font.h" // For the lyxfont class.
145 #include <algorithm> // For the std::max
146 #include "support/lyxmanip.h"
150 extern string system_tempdir;
155 // This function is a utility function
157 string const RemoveExtension(string const & filename)
159 return ChangeExtension(filename, string());
163 // Initialize only those variables that do not have a constructor.
164 InsetGraphics::InsetGraphics()
165 : cacheHandle(0), imageLoaded(false)
169 InsetGraphics::InsetGraphics(InsetGraphics const & ig, bool same_id)
170 : Inset(), SigC::Object()
171 , cacheHandle(ig.cacheHandle)
172 , imageLoaded(ig.imageLoaded)
174 setParams(ig.getParams());
180 InsetGraphics::~InsetGraphics()
182 // Emits the hide signal to the dialog connected (if any)
188 InsetGraphics::statusMessage() const
192 if (cacheHandle.get()) {
193 switch (cacheHandle->getImageStatus()) {
194 case GraphicsCacheItem::UnknownError:
195 msg = _("Unknown Error");
198 case GraphicsCacheItem::Loading:
199 msg = _("Loading...");
202 case GraphicsCacheItem::ErrorReading:
203 msg = _("Error reading");
206 case GraphicsCacheItem::ErrorConverting:
207 msg = _("Error converting");
210 case GraphicsCacheItem::Loaded:
211 // No message to write.
220 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
222 LyXImage * pixmap = 0;
223 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
224 return pixmap->getHeight();
230 int InsetGraphics::descent(BufferView *, LyXFont const &) const
232 // this is not true if viewport is used and clip is not.
237 int InsetGraphics::width(BufferView *, LyXFont const & font) const
239 LyXImage * pixmap = 0;
241 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
242 return pixmap->getWidth();
244 string const msg = statusMessage();
248 font_width = lyxfont::width(msg, font);
250 return std::max(50, font_width + 15);
255 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
256 int baseline, float & x, bool) const
258 Painter & paint = bv->painter();
260 int ldescent = descent(bv, font);
261 int lascent = ascent(bv, font);
262 int lwidth = width(bv, font);
264 // Make sure x is updated upon exit from this routine
268 // This will draw the graphics. If the graphics has not been loaded yet,
269 // we draw just a rectangle.
272 paint.image(old_x + 2, baseline - lascent,
273 lwidth - 4, lascent + ldescent,
274 cacheHandle->getImage());
277 // Get the image status, default to unknown error.
278 GraphicsCacheItem::ImageStatus status = GraphicsCacheItem::UnknownError;
279 if (cacheHandle.get())
280 status = cacheHandle->getImageStatus();
282 // Check if the image is now ready.
283 if (status == GraphicsCacheItem::Loaded) {
286 // Tell BufferView we need to be updated!
287 bv->text->status(bv, LyXText::CHANGED_IN_DRAW);
292 paint.rectangle(old_x + 2, baseline - lascent,
296 string const msg = statusMessage();
298 // Print the message.
299 LyXFont msgFont(font);
300 msgFont.setFamily(LyXFont::SANS_FAMILY);
301 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
302 string const justname = OnlyFilename (params.filename);
303 paint.text(old_x + 8,
304 baseline - lyxfont::maxAscent(msgFont) - 4,
307 msgFont.setSize(LyXFont::SIZE_TINY);
308 paint.text(old_x + 8, baseline - 4, msg, msgFont);
314 void InsetGraphics::edit(BufferView *bv, int, int, unsigned int)
316 bv->owner()->getDialogs()->showGraphics(this);
320 void InsetGraphics::edit(BufferView * bv, bool)
326 Inset::EDITABLE InsetGraphics::editable() const
332 void InsetGraphics::write(Buffer const * buf, ostream & os) const
334 os << "GRAPHICS FormatVersion 1\n";
336 params.Write(buf, os);
340 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
342 string const token = lex.GetString();
344 if (token == "GRAPHICS")
345 readInsetGraphics(buf, lex);
346 else if (token == "Figure") // Compatibility reading of FigInset figures.
347 readFigInset(buf, lex);
349 lyxerr[Debug::INFO] << "Not a GRAPHICS or Figure inset!\n";
354 void InsetGraphics::readInsetGraphics(Buffer const * buf, LyXLex & lex)
356 bool finished = false;
358 while (lex.IsOK() && !finished) {
361 string const token = lex.GetString();
362 lyxerr[Debug::INFO] << "Token: '" << token << '\''
367 } else if (token == "\\end_inset") {
369 } else if (token == "FormatVersion") {
371 int version = lex.GetInteger();
374 << "This document was created with a newer Graphics widget"
375 ", You should use a newer version of LyX to read this"
378 // TODO: Possibly open up a dialog?
381 if (! params.Read(buf, lex, token))
382 lyxerr << "Unknown token, " << token << ", skipping."
389 void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
391 bool finished = false;
393 while (lex.IsOK() && !finished) {
396 string const token = lex.GetString();
397 lyxerr[Debug::INFO] << "Token: " << token << endl;
401 else if (token == "\\end_inset") {
403 } else if (token == "file") {
405 string const name = lex.GetString();
406 string const path = OnlyPath(buf->fileName());
407 params.filename = MakeAbsPath(name, path);
409 } else if (token == "extra") {
411 // kept for backwards compability. Delete in 0.13.x
412 } else if (token == "subcaption") {
414 params.subcaptionText = lex.GetString();
415 } else if (token == "label") {
417 // kept for backwards compability. Delete in 0.13.x
418 } else if (token == "angle") {
420 params.rotateAngle = lex.GetFloat();
421 } else if (token == "size") {
422 // Size of image on screen is ignored in InsetGraphics, just eat
428 } else if (token == "flags") {
429 InsetGraphicsParams::DisplayType tmp = InsetGraphicsParams::COLOR;
431 switch (lex.GetInteger()) {
432 case 1: tmp = InsetGraphicsParams::MONOCHROME; break;
433 case 2: tmp = InsetGraphicsParams::GRAYSCALE; break;
435 params.display = tmp;
436 } else if (token == "subfigure") {
437 params.subcaption = true;
438 } else if (token == "width") {
440 params.widthResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
442 params.widthSize = lex.GetFloat();
443 } else if (token == "height") {
445 params.heightResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
447 params.heightSize = lex.GetFloat();
455 void formatResize(ostream & os, string const & key,
456 InsetGraphicsParams::Resize resizeType, double size)
458 switch (resizeType) {
459 case InsetGraphicsParams::DEFAULT_SIZE:
462 case InsetGraphicsParams::CM:
463 os << key << '=' << size << "cm,";
466 case InsetGraphicsParams::INCH:
467 os << key << '=' << size << "in,";
470 case InsetGraphicsParams::PERCENT_PAGE:
471 os << key << '=' << size / 100 << "\\text" << key << ',';
474 case InsetGraphicsParams::PERCENT_COLUMN:
475 os << key << '=' << size / 100 << "\\column" << key << ',';
485 InsetGraphics::createLatexOptions() const
487 // Calculate the options part of the command, we must do it to a string
488 // stream since we might have a trailing comma that we would like to remove
489 // before writing it to the output stream.
490 ostringstream options;
492 formatResize(options, "width", params.widthResize, params.widthSize);
493 formatResize(options, "height", params.heightResize, params.heightSize);
495 // Make sure it's not very close to zero, a float can be effectively
496 // zero but not exactly zero.
497 if (lyx::float_equal(params.rotateAngle, 0, 0.001)) {
499 << params.rotateAngle << ',';
502 string opts = options.str().c_str();
503 opts = strip(opts, ',');
510 InsetGraphics::prepareFile(Buffer const *buf) const
513 // do_convert = Do we need to convert the file?
514 // nice = Do we create a nice version?
515 // This is used when exporting the latex file only.
519 // return original filename
522 // convert_place = temp directory
523 // return new filename in temp directory
525 // convert_place = original file directory
526 // return original filename without the extension
529 // Get the extension (format) of the original file.
530 string const extension = GetExtension(params.filename);
532 // Are we creating a PDF or a PS file?
533 // (Should actually mean, are we usind latex or pdflatex).
534 string const image_target = (lyxrc.pdf_mode ? "png" : "eps");
536 if (extension == image_target)
537 return params.filename;
540 if (!buf->niceFile) {
541 string const temp = AddName(buf->tmppath, params.filename);
542 outfile = RemoveExtension(temp);
544 //lyxerr << "buf::tmppath = " << buf->tmppath << "\n";
545 //lyxerr << "filename = " << params.filename << "\n";
546 //lyxerr << "temp = " << temp << "\n";
547 //lyxerr << "outfile = " << outfile << endl;
549 string const path = OnlyPath(buf->fileName());
550 string const relname = MakeRelPath(params.filename, path);
551 outfile = RemoveExtension(relname);
554 converters.Convert(buf, params.filename, outfile, extension, image_target);
560 int InsetGraphics::latex(Buffer const *buf, ostream & os,
561 bool /*fragile*/, bool/*fs*/) const
563 // MISSING: We have to decide how to do the order of the options
564 // that is dependent of order, like width, height, angle. Should
565 // we rotate before scale? Should we let the user decide?
566 // bool rot_before_scale; ?
568 // (BE) As a first step we should do a scale before rotate since this is
569 // more like the natural thought of how to do it.
570 // (BE) I believe that a priority list presented to the user with
571 // a default order would be the best, though it would be better to
572 // hide such a thing in an "Advanced options" dialog.
573 // (BE) This should go an advanced LaTeX options dialog.
575 // If there is no file specified, just output a message about it in
577 if (params.filename.empty()) {
578 os << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
579 << _("empty figure path")
582 return 1; // One end of line marker added to the stream.
585 // Keep count of newlines that we issued.
588 // This variables collect all the latex code that should be before and
589 // after the actual includegraphics command.
593 // Do we want subcaptions?
594 if (params.subcaption) {
595 before += "\\subfigure[" + params.subcaptionText + "]{";
599 // We never use the starred form, we use the "clip" option instead.
600 os << before << "\\includegraphics";
602 // Write the options if there are any.
603 string const opts = createLatexOptions();
605 os << '[' << opts << ']';
608 // Make the filename relative to the lyx file
609 // and remove the extension so the LaTeX will use whatever is
610 // appropriate (when there are several versions in different formats)
611 string const filename = prepareFile(buf);
613 os << '{' << filename << '}' << after;
615 // Return how many newlines we issued.
620 int InsetGraphics::ascii(Buffer const *, ostream &, int) const
622 // No graphics in ascii output. Possible to use gifscii to convert
623 // images to ascii approximation.
625 // 1. Convert file to ascii using gifscii
626 // 2. Read ascii output file and add it to the output stream.
632 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
634 // No graphics in LinuxDoc output. Should check how/what to add.
639 // For explanation on inserting graphics into DocBook checkout:
640 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
641 // See also the docbook guide at http://www.docbook.org/
642 int InsetGraphics::docBook(Buffer const * buf, ostream & os) const
644 // Change the path to be relative to the main file.
645 string const buffer_dir = OnlyPath(buf->fileName());
646 string const filename = RemoveExtension(
647 MakeRelPath(params.filename, buffer_dir));
649 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
650 // need to switch to MediaObject. However, for now this is sufficient and
652 os << "<graphic fileref=\"" << filename << "\"></graphic>";
657 void InsetGraphics::validate(LaTeXFeatures & features) const
659 // If we have no image, we should not require anything.
660 if (params.filename.empty())
663 features.graphicx = true;
665 if (params.subcaption)
666 features.subfigure = true;
670 // Update the inset after parameters changed (read from file or changed in
672 void InsetGraphics::updateInset() const
674 GraphicsCache & gc = GraphicsCache::getInstance();
675 boost::shared_ptr<GraphicsCacheItem> temp(0);
677 // We do it this way so that in the face of some error, we will still
678 // be in a valid state.
679 if (!params.filename.empty()) {
680 temp = gc.addFile(params.filename);
683 // Mark the image as unloaded so that it gets updated.
690 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
692 // If nothing is changed, just return and say so.
696 // Copy the new parameters.
699 // Update the inset with the new parameters.
702 // We have changed data, report it.
707 InsetGraphicsParams InsetGraphics::getParams() const
713 Inset * InsetGraphics::clone(Buffer const &, bool same_id) const
715 return new InsetGraphics(*this, same_id);