1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995-2000 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 * Make the inline viewing work, there is a preliminary work going on,
20 * Support automatic image format conversion, create both a PNG and EPS output.
23 * Add messages in the empty rectangle (in the buffer view) to say how are
25 - Implemented, needs testing.
26 * Clean up GraphicsCacheItem(_pimpl)
27 * Pop up a dialog if the widget version is higher than what we accept.
28 * Prepare code to read FigInset insets to upgrade upwards
29 * Provide sed/awk/C code to downgrade from InsetGraphics to FigInset.
36 * If the image is from the clipart, and the document is moved to another
37 directory, the user is screwed. Need a way to handle it.
38 This amounts to a problem of when to use relative or absolute file paths
39 We should probably use what the user asks to use... but when he chooses
40 by the file dialog we normally get an absolute path and this may not be
42 * Bug in FileDlg class (src/filedlg.[hC]) when selecting a file and then
43 pressing ok, it counts as if no real selection done. Apparently
44 when choosing a file it doesn't update the select file input line.
45 * If we are trying to create a file in a read-only directory and there
46 are graphics that need converting, the converting will fail because
47 it is done in-place, into the same directory as the original image.
48 This needs to be fixed in the src/converter.C file
50 TODO Before initial production release:
51 * Replace insetfig everywhere
52 * Read it's file format
53 * Get created by all commands used to create figinset currently.
54 * Search for comments of the form
55 // INSET_GRAPHICS: remove this when InsetFig is thrown.
58 * Finish the basic To-do list.
59 * Extract the general logic of the dialog in order to allow easier porting
60 to Gnome/KDE, and put the general logic in frontends and the inherited
61 platform dependent code in the appropriate dirs.
62 (Something of this kind is getting done by the GUII guys)
64 TODO Extended features:
66 * Advanced Latex tab folder.
67 * Add support for more features so that it will be better than insetfig.
68 * Keep aspect ratio radio button
69 * Support for complete control over the latex parameters for TeXperts
70 * What advanced features the users want to do?
71 Implement them in a non latex dependent way, but a logical way.
72 LyX should translate it to latex or any other fitting format.
73 * Add a way to roll the image file into the file format.
74 * When loading, if the image is not found in the expected place, try
75 to find it in the clipart, or in the same directory with the image.
76 * Keep a tab on the image file, if it changes, update the lyx view.
77 * The image choosing dialog could show thumbnails of the image formats
78 it knows of, thus selection based on the image instead of based on
80 * Add support for the 'picins' package.
81 * Add support for the 'picinpar' package.
82 * Improve support for 'subfigure' - Allow to set the various options
89 * This is currently a moving target, I'm trying stuff and learning what
90 * is needed and how to accomplish it, since there is no predefined goal or
91 * way to go I invent it as I go.
93 * My current intention is for seperation from LaTeX, the basic needs are
94 * resizing and rotating, displaying on screen in various depths and printing
95 * conversion of depths (independent of the display depth). For this I'll
96 * provide a simple interface.
98 * The medium level includes clipping of the image, but in a limited way.
100 * For the LaTeX gurus I'll provide a complete control over the output, but
101 * this is latex dependent and guru dependent so I'd rather avoid doing this
102 * for the normal user. This stuff includes clipping, special image size
103 * specifications (\textwidth\minus 2in) which I see no way to generalize
104 * to non-latex specific way.
107 * 'graphicx' for the graphics inclusion.
108 * 'subfigure' for the subfigures.
112 * Current version is 1 (inset file format version), when changing it
113 * it should be changed in the Write() function when writing in one place
114 * and when reading one should change the version check and the error message.
116 * The filename is kept in the lyx file in a relative way, so as to allow
117 * moving the document file and its images with no problem.
121 * Apparently the PNG output is preferred over PDF images when doing PDF
122 * documents (i.e. prefer imagemagick eps2png over eps2pdf)
128 #pragma implementation
131 #include "insets/insetgraphics.h"
132 #include "insets/insetgraphicsParams.h"
133 #include "graphics/GraphicsCache.h"
134 #include "graphics/GraphicsCacheItem.h"
136 #include "frontends/Dialogs.h"
139 #include "BufferView.h"
140 #include "converter.h"
141 #include "frontends/support/LyXImage.h"
143 #include "lyx_gui_misc.h"
144 #include "support/FileInfo.h"
145 #include "support/filetools.h"
146 #include "support/lyxlib.h"
149 #include "font.h" // For the lyxfont class.
150 #include <algorithm> // For the std::max
151 #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)
173 InsetGraphics::~InsetGraphics()
175 // Emits the hide signal to the dialog connected (if any)
180 InsetGraphics::statusMessage() const
182 char const * msg = 0;
184 if (cacheHandle.get()) {
185 switch (cacheHandle->getImageStatus()) {
186 case GraphicsCacheItem::UnknownError:
187 msg = _("Unknown Error");
190 case GraphicsCacheItem::Loading:
191 msg = _("Loading...");
194 case GraphicsCacheItem::ErrorReading:
195 msg = _("Error reading");
198 case GraphicsCacheItem::ErrorConverting:
199 msg = _("Error converting");
202 case GraphicsCacheItem::Loaded:
203 // No message to write.
211 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
213 LyXImage * pixmap = 0;
214 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
215 return pixmap->getHeight();
221 int InsetGraphics::descent(BufferView *, LyXFont const &) const
223 // this is not true if viewport is used and clip is not.
228 int InsetGraphics::width(BufferView *, LyXFont const & font) const
230 LyXImage * pixmap = 0;
232 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
233 return pixmap->getWidth();
235 char const * msg = statusMessage();
239 font_width = lyxfont::width(msg, font);
241 return max(50, font_width + 15);
245 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
246 int baseline, float & x, bool) const
248 Painter & paint = bv->painter();
250 int ldescent = descent(bv, font);
251 int lascent = ascent(bv, font);
252 int lwidth = width(bv, font);
254 // Make sure x is updated upon exit from this routine
258 // This will draw the graphics. If the graphics has not been loaded yet,
259 // we draw just a rectangle.
262 paint.image(int(old_x) + 2, baseline - lascent,
263 lwidth - 4, lascent + ldescent,
264 cacheHandle->getImage());
267 // Get the image status, default to unknown error.
268 GraphicsCacheItem::ImageStatus status = GraphicsCacheItem::UnknownError;
269 if (cacheHandle.get())
270 status = cacheHandle->getImageStatus();
272 // Check if the image is now ready.
273 if (status == GraphicsCacheItem::Loaded) {
276 // Tell BufferView we need to be updated!
277 bv->text->status = LyXText::CHANGED_IN_DRAW;
281 char const * msg = statusMessage();
283 paint.rectangle(int(old_x) + 2, baseline - lascent,
288 // Print the message.
289 LyXFont msgFont(font);
290 msgFont.setFamily(LyXFont::SANS_FAMILY);
291 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
292 string const justname = OnlyFilename (params.filename);
293 paint.text(int(old_x) + 8,
294 baseline - lyxfont::maxAscent(msgFont) - 4,
297 msgFont.setSize(LyXFont::SIZE_TINY);
298 paint.text(int(old_x) + 8, baseline - 4,
299 msg, strlen(msg), msgFont);
305 void InsetGraphics::Edit(BufferView *bv, int, int, unsigned int)
307 bv->owner()->getDialogs()->showGraphics(this);
311 Inset::EDITABLE InsetGraphics::Editable() const
317 void InsetGraphics::Write(Buffer const * buf, ostream & os) const
319 os << "GRAPHICS FormatVersion 1" << endl;
321 params.Write(buf, os);
325 void InsetGraphics::Read(Buffer const * buf, LyXLex & lex)
327 bool finished = false;
329 while (lex.IsOK() && !finished) {
332 string const token = lex.GetString();
333 lyxerr.debug() << "Token: '" << token << '\'' << endl;
337 } else if (token == "\\end_inset") {
339 } else if (token == "FormatVersion") {
341 int version = lex.GetInteger();
344 << "This document was created with a newer Graphics widget"
345 ", You should use a newer version of LyX to read this"
348 // TODO: Possibly open up a dialog?
351 if (! params.Read(buf, lex, token))
352 lyxerr << "Unknown token, " << token << ", skipping." << endl;
360 void formatResize(ostream & os, string const & key,
361 InsetGraphicsParams::Resize resizeType, double size)
363 switch (resizeType) {
364 case InsetGraphicsParams::DEFAULT_SIZE:
367 case InsetGraphicsParams::CM:
368 os << key << '=' << size << "cm,";
371 case InsetGraphicsParams::INCH:
372 os << key << '=' << size << "in,";
375 case InsetGraphicsParams::PERCENT_PAGE:
376 os << key << '=' << size / 100 << "\\text" << key << ',';
379 case InsetGraphicsParams::PERCENT_COLUMN:
380 os << key << '=' << size / 100 << "\\column" << key << ',';
387 InsetGraphics::createLatexOptions() const
389 // Calculate the options part of the command, we must do it to a string
390 // stream since we might have a trailing comma that we would like to remove
391 // before writing it to the output stream.
392 std::ostringstream options;
394 formatResize(options, "width", params.widthResize, params.widthSize);
395 formatResize(options, "height", params.heightResize, params.heightSize);
397 if (params.rotateAngle != 0) {
399 << params.rotateAngle << ',';
402 string opts = options.str().c_str();
403 opts = strip(opts, ',');
411 InsetGraphics::prepareFile(Buffer const *buf) const
414 // do_convert = Do we need to convert the file?
415 // nice = Do we create a nice version?
416 // This is used when exporting the latex file only.
420 // return original filename
423 // convert_place = temp directory
424 // return new filename in temp directory
426 // convert_place = original file directory
427 // return original filename without the extension
430 // Get the extension (format) of the original file.
431 string const extension = GetExtension(params.filename);
433 // Are we creating a PDF or a PS file?
434 // (Should actually mean, are we usind latex or pdflatex).
435 string const image_target = (lyxrc.pdf_mode ? "png" : "eps");
437 if (extension == image_target)
438 return params.filename;
441 if (!buf->niceFile) {
442 string const temp = AddName(buf->tmppath, params.filename);
443 outfile = RemoveExtension(temp);
445 //lyxerr << "buf::tmppath = " << buf->tmppath << "\n";
446 //lyxerr << "filename = " << params.filename << "\n";
447 //lyxerr << "temp = " << temp << "\n";
448 //lyxerr << "outfile = " << outfile << endl;
450 string const path = OnlyPath(buf->fileName());
451 string const relname = MakeRelPath(params.filename, path);
452 outfile = RemoveExtension(relname);
455 converters.Convert(buf, params.filename, outfile, extension, image_target);
460 int InsetGraphics::Latex(Buffer const *buf, ostream & os,
461 bool /*fragile*/, bool/*fs*/) const
463 // MISSING: We have to decide how to do the order of the options
464 // that is dependent of order, like width, height, angle. Should
465 // we rotate before scale? Should we let the user decide?
466 // bool rot_before_scale; ?
468 // (BE) As a first step we should do a scale before rotate since this is
469 // more like the natural thought of how to do it.
470 // (BE) I believe that a priority list presented to the user with
471 // a default order would be the best, though it would be better to
472 // hide such a thing in an "Advanced options" dialog.
473 // (BE) This should go an advanced LaTeX options dialog.
475 // If there is no file specified, just output a message about it in
477 if (params.filename.empty()) {
478 os << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
479 << _("empty figure path")
482 return 1; // One end of line marker added to the stream.
485 // Keep count of newlines that we issued.
488 // This variables collect all the latex code that should be before and
489 // after the actual includegraphics command.
493 // If it's not an inline image, surround it with the centering paragraph.
494 if (! params.inlineFigure) {
495 before += "\n" "\\vspace{0.3cm}\n" "{\\par\\centering ";
496 after = " \\par}\n" "\\vspace{0.3cm}\n" + after;
500 // Do we want subcaptions?
501 if (params.subcaption) {
502 before += "\\subfigure[" + params.subcaptionText + "]{";
506 // We never use the starred form, we use the "clip" option instead.
507 os << before << "\\includegraphics";
509 // Write the options if there are any.
510 string const opts = createLatexOptions();
512 os << '[' << opts << ']';
515 // Make the filename relative to the lyx file
516 // and remove the extension so the LaTeX will use whatever is
517 // appropriate (when there are several versions in different formats)
518 string const filename = prepareFile(buf);
520 os << '{' << filename << '}' << after;
522 // Return how many newlines we issued.
527 int InsetGraphics::Ascii(Buffer const *, ostream &, int) const
529 // No graphics in ascii output. Possible to use gifscii to convert
530 // images to ascii approximation.
532 // 1. Convert file to ascii using gifscii
533 // 2. Read ascii output file and add it to the output stream.
539 int InsetGraphics::Linuxdoc(Buffer const *, ostream &) const
541 // No graphics in LinuxDoc output. Should check how/what to add.
545 // For explanation on inserting graphics into DocBook checkout:
546 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
547 // See also the docbook guide at http://www.docbook.org/
548 int InsetGraphics::DocBook(Buffer const * buf, ostream & os) const
550 // Change the path to be relative to the main file.
551 string const buffer_dir = OnlyPath(buf->fileName());
552 string const filename = RemoveExtension(MakeRelPath(params.filename, buffer_dir));
554 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
555 // need to switch to MediaObject. However, for now this is sufficient and
557 os << "<graphic fileref=\"" << filename << "\"></graphic>";
562 void InsetGraphics::Validate(LaTeXFeatures & features) const
564 // If we have no image, we should not require anything.
565 if (params.filename.empty())
568 features.graphicx = true;
570 if (params.subcaption)
571 features.subfigure = true;
574 // Update the inset after parameters changed (read from file or changed in
576 void InsetGraphics::updateInset() const
578 GraphicsCache * gc = GraphicsCache::getInstance();
579 boost::shared_ptr<GraphicsCacheItem> temp(0);
581 // We do it this way so that in the face of some error, we will still
582 // be in a valid state.
583 if (!params.filename.empty()) {
584 temp = gc->addFile(params.filename);
587 // Mark the image as unloaded so that it gets updated.
593 bool InsetGraphics::setParams(InsetGraphicsParams const & params)
595 // If nothing is changed, just return and say so.
596 if (this->params == params)
599 // Copy the new parameters.
600 this->params = params;
602 // Update the inset with the new parameters.
605 // We have changed data, report it.
609 InsetGraphicsParams InsetGraphics::getParams() const
614 Inset * InsetGraphics::Clone(Buffer const &) const
616 InsetGraphics * newInset = new InsetGraphics;
618 newInset->cacheHandle = cacheHandle;
619 newInset->imageLoaded = imageLoaded;
621 newInset->setParams(getParams());