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;
154 // This function is a utility function
156 string const RemoveExtension(string const & filename)
158 return ChangeExtension(filename, string());
162 // Initialize only those variables that do not have a constructor.
163 InsetGraphics::InsetGraphics()
164 : cacheHandle(0), imageLoaded(false)
168 InsetGraphics::~InsetGraphics()
170 // Emits the hide signal to the dialog connected (if any)
176 InsetGraphics::statusMessage() const
178 char const * msg = 0;
180 if (cacheHandle.get()) {
181 switch (cacheHandle->getImageStatus()) {
182 case GraphicsCacheItem::UnknownError:
183 msg = _("Unknown Error");
186 case GraphicsCacheItem::Loading:
187 msg = _("Loading...");
190 case GraphicsCacheItem::ErrorReading:
191 msg = _("Error reading");
194 case GraphicsCacheItem::ErrorConverting:
195 msg = _("Error converting");
198 case GraphicsCacheItem::Loaded:
199 // No message to write.
208 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
210 LyXImage * pixmap = 0;
211 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
212 return pixmap->getHeight();
218 int InsetGraphics::descent(BufferView *, LyXFont const &) const
220 // this is not true if viewport is used and clip is not.
225 int InsetGraphics::width(BufferView *, LyXFont const & font) const
227 LyXImage * pixmap = 0;
229 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
230 return pixmap->getWidth();
232 char const * msg = statusMessage();
236 font_width = lyxfont::width(msg, font);
238 return std::max(50, font_width + 15);
243 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
244 int baseline, float & x, bool) const
246 Painter & paint = bv->painter();
248 int ldescent = descent(bv, font);
249 int lascent = ascent(bv, font);
250 int lwidth = width(bv, font);
252 // Make sure x is updated upon exit from this routine
256 // This will draw the graphics. If the graphics has not been loaded yet,
257 // we draw just a rectangle.
260 paint.image(int(old_x) + 2, baseline - lascent,
261 lwidth - 4, lascent + ldescent,
262 cacheHandle->getImage());
265 // Get the image status, default to unknown error.
266 GraphicsCacheItem::ImageStatus status = GraphicsCacheItem::UnknownError;
267 if (cacheHandle.get())
268 status = cacheHandle->getImageStatus();
270 // Check if the image is now ready.
271 if (status == GraphicsCacheItem::Loaded) {
274 // Tell BufferView we need to be updated!
275 bv->text->status = LyXText::CHANGED_IN_DRAW;
279 char const * msg = statusMessage();
281 paint.rectangle(int(old_x) + 2, baseline - lascent,
286 // Print the message.
287 LyXFont msgFont(font);
288 msgFont.setFamily(LyXFont::SANS_FAMILY);
289 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
290 string const justname = OnlyFilename (params.filename);
291 paint.text(int(old_x) + 8,
292 baseline - lyxfont::maxAscent(msgFont) - 4,
295 msgFont.setSize(LyXFont::SIZE_TINY);
296 paint.text(int(old_x) + 8, baseline - 4,
297 msg, strlen(msg), msgFont);
303 void InsetGraphics::Edit(BufferView *bv, int, int, unsigned int)
305 bv->owner()->getDialogs()->showGraphics(this);
309 Inset::EDITABLE InsetGraphics::Editable() const
315 void InsetGraphics::Write(Buffer const * buf, ostream & os) const
317 os << "GRAPHICS FormatVersion 1\n";
319 params.Write(buf, os);
323 void InsetGraphics::Read(Buffer const * buf, LyXLex & lex)
325 bool finished = false;
327 while (lex.IsOK() && !finished) {
330 string const token = lex.GetString();
331 lyxerr.debug() << "Token: '" << token << '\'' << std::endl;
335 } else if (token == "\\end_inset") {
337 } else if (token == "FormatVersion") {
339 int version = lex.GetInteger();
342 << "This document was created with a newer Graphics widget"
343 ", You should use a newer version of LyX to read this"
346 // TODO: Possibly open up a dialog?
349 if (! params.Read(buf, lex, token))
350 lyxerr << "Unknown token, " << token << ", skipping."
361 void formatResize(ostream & os, string const & key,
362 InsetGraphicsParams::Resize resizeType, double size)
364 switch (resizeType) {
365 case InsetGraphicsParams::DEFAULT_SIZE:
368 case InsetGraphicsParams::CM:
369 os << key << '=' << size << "cm,";
372 case InsetGraphicsParams::INCH:
373 os << key << '=' << size << "in,";
376 case InsetGraphicsParams::PERCENT_PAGE:
377 os << key << '=' << size / 100 << "\\text" << key << ',';
380 case InsetGraphicsParams::PERCENT_COLUMN:
381 os << key << '=' << size / 100 << "\\column" << key << ',';
391 InsetGraphics::createLatexOptions() const
393 // Calculate the options part of the command, we must do it to a string
394 // stream since we might have a trailing comma that we would like to remove
395 // before writing it to the output stream.
396 std::ostringstream options;
398 formatResize(options, "width", params.widthResize, params.widthSize);
399 formatResize(options, "height", params.heightResize, params.heightSize);
401 if (params.rotateAngle != 0) {
403 << params.rotateAngle << ',';
406 string opts = options.str().c_str();
407 opts = strip(opts, ',');
414 InsetGraphics::prepareFile(Buffer const *buf) const
417 // do_convert = Do we need to convert the file?
418 // nice = Do we create a nice version?
419 // This is used when exporting the latex file only.
423 // return original filename
426 // convert_place = temp directory
427 // return new filename in temp directory
429 // convert_place = original file directory
430 // return original filename without the extension
433 // Get the extension (format) of the original file.
434 string const extension = GetExtension(params.filename);
436 // Are we creating a PDF or a PS file?
437 // (Should actually mean, are we usind latex or pdflatex).
438 string const image_target = (lyxrc.pdf_mode ? "png" : "eps");
440 if (extension == image_target)
441 return params.filename;
444 if (!buf->niceFile) {
445 string const temp = AddName(buf->tmppath, params.filename);
446 outfile = RemoveExtension(temp);
448 //lyxerr << "buf::tmppath = " << buf->tmppath << "\n";
449 //lyxerr << "filename = " << params.filename << "\n";
450 //lyxerr << "temp = " << temp << "\n";
451 //lyxerr << "outfile = " << outfile << endl;
453 string const path = OnlyPath(buf->fileName());
454 string const relname = MakeRelPath(params.filename, path);
455 outfile = RemoveExtension(relname);
458 converters.Convert(buf, params.filename, outfile, extension, image_target);
464 int InsetGraphics::Latex(Buffer const *buf, ostream & os,
465 bool /*fragile*/, bool/*fs*/) const
467 // MISSING: We have to decide how to do the order of the options
468 // that is dependent of order, like width, height, angle. Should
469 // we rotate before scale? Should we let the user decide?
470 // bool rot_before_scale; ?
472 // (BE) As a first step we should do a scale before rotate since this is
473 // more like the natural thought of how to do it.
474 // (BE) I believe that a priority list presented to the user with
475 // a default order would be the best, though it would be better to
476 // hide such a thing in an "Advanced options" dialog.
477 // (BE) This should go an advanced LaTeX options dialog.
479 // If there is no file specified, just output a message about it in
481 if (params.filename.empty()) {
482 os << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
483 << _("empty figure path")
486 return 1; // One end of line marker added to the stream.
489 // Keep count of newlines that we issued.
492 // This variables collect all the latex code that should be before and
493 // after the actual includegraphics command.
497 // If it's not an inline image, surround it with the centering paragraph.
498 if (! params.inlineFigure) {
499 before += "\n" "\\vspace{0.3cm}\n" "{\\par\\centering ";
500 after = " \\par}\n" "\\vspace{0.3cm}\n" + after;
504 // Do we want subcaptions?
505 if (params.subcaption) {
506 before += "\\subfigure[" + params.subcaptionText + "]{";
510 // We never use the starred form, we use the "clip" option instead.
511 os << before << "\\includegraphics";
513 // Write the options if there are any.
514 string const opts = createLatexOptions();
516 os << '[' << opts << ']';
519 // Make the filename relative to the lyx file
520 // and remove the extension so the LaTeX will use whatever is
521 // appropriate (when there are several versions in different formats)
522 string const filename = prepareFile(buf);
524 os << '{' << filename << '}' << after;
526 // Return how many newlines we issued.
531 int InsetGraphics::Ascii(Buffer const *, ostream &, int) const
533 // No graphics in ascii output. Possible to use gifscii to convert
534 // images to ascii approximation.
536 // 1. Convert file to ascii using gifscii
537 // 2. Read ascii output file and add it to the output stream.
543 int InsetGraphics::Linuxdoc(Buffer const *, ostream &) const
545 // No graphics in LinuxDoc output. Should check how/what to add.
550 // For explanation on inserting graphics into DocBook checkout:
551 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
552 // See also the docbook guide at http://www.docbook.org/
553 int InsetGraphics::DocBook(Buffer const * buf, ostream & os) const
555 // Change the path to be relative to the main file.
556 string const buffer_dir = OnlyPath(buf->fileName());
557 string const filename = RemoveExtension(MakeRelPath(params.filename, buffer_dir));
559 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
560 // need to switch to MediaObject. However, for now this is sufficient and
562 os << "<graphic fileref=\"" << filename << "\"></graphic>";
567 void InsetGraphics::Validate(LaTeXFeatures & features) const
569 // If we have no image, we should not require anything.
570 if (params.filename.empty())
573 features.graphicx = true;
575 if (params.subcaption)
576 features.subfigure = true;
580 // Update the inset after parameters changed (read from file or changed in
582 void InsetGraphics::updateInset() const
584 GraphicsCache & gc = GraphicsCache::getInstance();
585 boost::shared_ptr<GraphicsCacheItem> temp(0);
587 // We do it this way so that in the face of some error, we will still
588 // be in a valid state.
589 if (!params.filename.empty()) {
590 temp = gc.addFile(params.filename);
593 // Mark the image as unloaded so that it gets updated.
600 bool InsetGraphics::setParams(InsetGraphicsParams const & params)
602 // If nothing is changed, just return and say so.
603 if (this->params == params)
606 // Copy the new parameters.
607 this->params = params;
609 // Update the inset with the new parameters.
612 // We have changed data, report it.
617 InsetGraphicsParams InsetGraphics::getParams() const
623 Inset * InsetGraphics::Clone(Buffer const &) const
625 #warning use the copy constructor instead. (Lgb)
626 InsetGraphics * newInset = new InsetGraphics;
628 newInset->cacheHandle = cacheHandle;
629 newInset->imageLoaded = imageLoaded;
631 newInset->setParams(getParams());