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 * The scale option is only handled for the horizontal part, the vertical
46 part will not work. For now it is also shown only for horizontal
49 * EPS figures are not fully detected, they may have a lot of possible
50 suffixes so we need to read the file and detect if it's EPS or not.
51 [Implemented, need testing]
53 TODO Before initial production release:
54 * Replace insetfig everywhere
55 * Search for comments of the form
56 // INSET_GRAPHICS: remove this when InsetFig is thrown.
57 And act upon them. Make sure not to remove InsetFig code for the
58 1.2.0 release, only afterwards, after deployment shows InsetGraphics
61 TODO Extended features:
63 * Advanced Latex tab folder.
64 * Add support for more features so that it will be better than insetfig.
65 * Keep aspect ratio radio button
66 * Support for complete control over the latex parameters for TeXperts
67 * What advanced features the users want to do?
68 Implement them in a non latex dependent way, but a logical way.
69 LyX should translate it to latex or any other fitting format.
70 * Add a way to roll the image file into the file format.
71 * When loading, if the image is not found in the expected place, try
72 to find it in the clipart, or in the same directory with the image.
73 * Keep a tab on the image file, if it changes, update the lyx view.
74 * The image choosing dialog could show thumbnails of the image formats
75 it knows of, thus selection based on the image instead of based on
77 * Add support for the 'picins' package.
78 * Add support for the 'picinpar' package.
79 * Improve support for 'subfigure' - Allow to set the various options
81 * Add resizing by percentage of image size (50%, 150%) - usefull for two
82 images of different size to be resized where they both should have
83 the same scale compared to each other.
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.
120 * Postscript output means EPS figures.
122 * PDF output is best done with PDF figures if it's a direct conversion
123 * or PNG figures otherwise.
135 #pragma implementation
138 #include "insets/insetgraphics.h"
139 #include "insets/insetgraphicsParams.h"
140 #include "graphics/GraphicsCache.h"
141 #include "graphics/GraphicsCacheItem.h"
143 #include "frontends/Dialogs.h"
146 #include "BufferView.h"
147 #include "converter.h"
148 #include "frontends/support/LyXImage.h"
150 #include "lyx_gui_misc.h"
151 #include "support/FileInfo.h"
152 #include "support/filetools.h"
153 #include "support/lyxlib.h"
156 #include "font.h" // For the lyxfont class.
157 #include "fstream" // for ifstream in isEPS
158 #include <algorithm> // For the std::max
159 #include "support/lyxmanip.h"
163 extern string system_tempdir;
170 // This function is a utility function
172 string const RemoveExtension(string const & filename)
174 return ChangeExtension(filename, string());
178 // Initialize only those variables that do not have a constructor.
179 InsetGraphics::InsetGraphics()
180 : cacheHandle(0), imageLoaded(false)
184 InsetGraphics::InsetGraphics(InsetGraphics const & ig, bool same_id)
185 : Inset(), SigC::Object()
186 , cacheHandle(ig.cacheHandle)
187 , imageLoaded(ig.imageLoaded)
189 setParams(ig.getParams());
195 InsetGraphics::~InsetGraphics()
197 // Emits the hide signal to the dialog connected (if any)
203 InsetGraphics::statusMessage() const
207 if (cacheHandle.get()) {
208 switch (cacheHandle->getImageStatus()) {
209 case GraphicsCacheItem::UnknownError:
210 msg = _("Unknown Error");
213 case GraphicsCacheItem::Loading:
214 msg = _("Loading...");
217 case GraphicsCacheItem::ErrorReading:
218 msg = _("Error reading");
221 case GraphicsCacheItem::ErrorConverting:
222 msg = _("Error converting");
225 case GraphicsCacheItem::Loaded:
226 // No message to write.
235 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
237 LyXImage * pixmap = 0;
238 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
239 return pixmap->getHeight();
245 int InsetGraphics::descent(BufferView *, LyXFont const &) const
247 // this is not true if viewport is used and clip is not.
252 int InsetGraphics::width(BufferView *, LyXFont const & font) const
254 LyXImage * pixmap = 0;
256 if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
257 return pixmap->getWidth();
259 string const msg = statusMessage();
263 font_width = lyxfont::width(msg, font);
265 return std::max(50, font_width + 15);
270 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
271 int baseline, float & x, bool) const
273 Painter & paint = bv->painter();
275 int ldescent = descent(bv, font);
276 int lascent = ascent(bv, font);
277 int lwidth = width(bv, font);
279 // Make sure x is updated upon exit from this routine
283 // This will draw the graphics. If the graphics has not been loaded yet,
284 // we draw just a rectangle.
287 paint.image(old_x + 2, baseline - lascent,
288 lwidth - 4, lascent + ldescent,
289 cacheHandle->getImage());
292 // Get the image status, default to unknown error.
293 GraphicsCacheItem::ImageStatus status = GraphicsCacheItem::UnknownError;
294 if (cacheHandle.get())
295 status = cacheHandle->getImageStatus();
297 // Check if the image is now ready.
298 if (status == GraphicsCacheItem::Loaded) {
301 // Tell BufferView we need to be updated!
302 bv->text->status(bv, LyXText::CHANGED_IN_DRAW);
307 paint.rectangle(old_x + 2, baseline - lascent,
311 string const msg = statusMessage();
313 // Print the message.
314 LyXFont msgFont(font);
315 msgFont.setFamily(LyXFont::SANS_FAMILY);
316 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
317 string const justname = OnlyFilename (params.filename);
318 paint.text(old_x + 8,
319 baseline - lyxfont::maxAscent(msgFont) - 4,
322 msgFont.setSize(LyXFont::SIZE_TINY);
323 paint.text(old_x + 8, baseline - 4, msg, msgFont);
329 void InsetGraphics::edit(BufferView *bv, int, int, unsigned int)
331 bv->owner()->getDialogs()->showGraphics(this);
335 void InsetGraphics::edit(BufferView * bv, bool)
341 Inset::EDITABLE InsetGraphics::editable() const
347 void InsetGraphics::write(Buffer const * buf, ostream & os) const
349 os << "Graphics FormatVersion 1\n";
351 params.Write(buf, os);
355 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
357 string const token = lex.GetString();
359 if (token == "Graphics")
360 readInsetGraphics(buf, lex);
361 else if (token == "Figure") // Compatibility reading of FigInset figures.
362 readFigInset(buf, lex);
364 lyxerr[Debug::INFO] << "Not a Graphics or Figure inset!\n";
369 void InsetGraphics::readInsetGraphics(Buffer const * buf, LyXLex & lex)
371 bool finished = false;
373 while (lex.IsOK() && !finished) {
376 string const token = lex.GetString();
377 lyxerr[Debug::INFO] << "Token: '" << token << '\''
382 } else if (token == "\\end_inset") {
384 } else if (token == "FormatVersion") {
386 int version = lex.GetInteger();
389 << "This document was created with a newer Graphics widget"
390 ", You should use a newer version of LyX to read this"
393 // TODO: Possibly open up a dialog?
396 if (! params.Read(buf, lex, token))
397 lyxerr << "Unknown token, " << token << ", skipping."
404 void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
406 bool finished = false;
408 while (lex.IsOK() && !finished) {
411 string const token = lex.GetString();
412 lyxerr[Debug::INFO] << "Token: " << token << endl;
416 else if (token == "\\end_inset") {
418 } else if (token == "file") {
420 string const name = lex.GetString();
421 string const path = OnlyPath(buf->fileName());
422 params.filename = MakeAbsPath(name, path);
424 } else if (token == "extra") {
426 // kept for backwards compability. Delete in 0.13.x
427 } else if (token == "subcaption") {
429 params.subcaptionText = lex.GetString();
430 } else if (token == "label") {
432 // kept for backwards compability. Delete in 0.13.x
433 } else if (token == "angle") {
435 params.rotateAngle = lex.GetFloat();
436 } else if (token == "size") {
437 // Size of image on screen is ignored in InsetGraphics, just eat
443 } else if (token == "flags") {
444 InsetGraphicsParams::DisplayType tmp = InsetGraphicsParams::COLOR;
446 switch (lex.GetInteger()) {
447 case 1: tmp = InsetGraphicsParams::MONOCHROME; break;
448 case 2: tmp = InsetGraphicsParams::GRAYSCALE; break;
450 params.display = tmp;
451 } else if (token == "subfigure") {
452 params.subcaption = true;
453 } else if (token == "width") {
455 params.widthResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
457 params.widthSize = lex.GetFloat();
458 } else if (token == "height") {
460 params.heightResize = static_cast<InsetGraphicsParams::Resize>(lex.GetInteger());
462 params.heightSize = lex.GetFloat();
470 void formatResize(ostream & os, string const & key,
471 InsetGraphicsParams::Resize resizeType, double size)
473 switch (resizeType) {
474 case InsetGraphicsParams::DEFAULT_SIZE:
477 case InsetGraphicsParams::CM:
478 os << key << '=' << size << "cm,";
481 case InsetGraphicsParams::INCH:
482 os << key << '=' << size << "in,";
485 case InsetGraphicsParams::PERCENT_PAGE:
486 os << key << '=' << size / 100 << "\\text" << key << ',';
489 case InsetGraphicsParams::PERCENT_COLUMN:
490 os << key << '=' << size / 100 << "\\column" << key << ',';
493 case InsetGraphicsParams::SCALE:
494 os << "scale" << '=' << size << ',';
502 InsetGraphics::createLatexOptions() const
504 // Calculate the options part of the command, we must do it to a string
505 // stream since we might have a trailing comma that we would like to remove
506 // before writing it to the output stream.
507 ostringstream options;
509 formatResize(options, "width", params.widthResize, params.widthSize);
510 formatResize(options, "height", params.heightResize, params.heightSize);
512 // Make sure it's not very close to zero, a float can be effectively
513 // zero but not exactly zero.
514 if (lyx::float_equal(params.rotateAngle, 0, 0.001)) {
516 << params.rotateAngle << ',';
519 string opts = options.str().c_str();
520 opts = strip(opts, ',');
536 bool isEPS(string const & filename)
538 if (filename.empty() || !IsFileReadable(filename)) return false;
540 ifstream ifs(filename.c_str());
542 if (!ifs) return false; // Couldn't open file...
544 bool is_eps = false; // Have we recognized the file as EPS?
545 string to_find = "%!PS-Adobe-"; // The string we use to recognize
546 int const max_attempts = 500; // Maximum strings to read to attempt recognition
547 int count = 0; // Counter of attempts.
549 for (; count < max_attempts; ++count) {
551 lyxerr[Debug::INFO] << "InsetGraphics (isEPS)"
552 " End of file reached and it wasn't found to be EPS!" << endl;
557 if (str.find(to_find)) {
566 enum FileType classifyFileType(string const & filename, string const & suffix)
570 else if (suffix == "jpg" || suffix == "jpeg")
572 else if (suffix == "gif")
574 else if (suffix == "pdf")
576 else if (isEPS(filename))
582 string decideOutputImageFormat(string const & suffix, enum FileType type)
584 // lyxrc.pdf_mode means:
585 // Are we creating a PDF or a PS file?
586 // (Should actually mean, are we using latex or pdflatex).
588 if (lyxrc.pdf_mode) {
589 if (type == EPS || type == EPS || type == PDF)
591 else if (type == JPEG)
597 // If it's postscript, we always do eps.
598 // There are many suffixes that are actually EPS (ask Garst for example)
599 // so we detect if it's an EPS by looking in the file, if it is, we return
600 // the same suffix of the file so it won't be converted.
610 InsetGraphics::prepareFile(Buffer const *buf) const
613 // do_convert = Do we need to convert the file?
614 // nice = Do we create a nice version?
615 // This is used when exporting the latex file only.
619 // return original filename
622 // convert_place = temp directory
623 // return new filename in temp directory
625 // convert_place = original file directory
626 // return original filename without the extension
629 // Get the extension (format) of the original file.
630 string const extension = GetExtension(params.filename);
631 FileType type = classifyFileType(params.filename, extension);
633 // Are we creating a PDF or a PS file?
634 // (Should actually mean, are we usind latex or pdflatex).
635 string const image_target = decideOutputImageFormat(extension, type);
637 if (extension == image_target)
638 return params.filename;
641 if (!buf->niceFile) {
642 string const temp = AddName(buf->tmppath, params.filename);
643 outfile = RemoveExtension(temp);
645 //lyxerr << "buf::tmppath = " << buf->tmppath << "\n";
646 //lyxerr << "filename = " << params.filename << "\n";
647 //lyxerr << "temp = " << temp << "\n";
648 //lyxerr << "outfile = " << outfile << endl;
650 string const path = OnlyPath(buf->fileName());
651 string const relname = MakeRelPath(params.filename, path);
652 outfile = RemoveExtension(relname);
655 converters.convert(buf, params.filename, outfile, extension, image_target);
661 int InsetGraphics::latex(Buffer const *buf, ostream & os,
662 bool /*fragile*/, bool/*fs*/) const
664 // MISSING: We have to decide how to do the order of the options
665 // that is dependent of order, like width, height, angle. Should
666 // we rotate before scale? Should we let the user decide?
667 // bool rot_before_scale; ?
669 // (BE) As a first step we should do a scale before rotate since this is
670 // more like the natural thought of how to do it.
671 // (BE) I believe that a priority list presented to the user with
672 // a default order would be the best, though it would be better to
673 // hide such a thing in an "Advanced options" dialog.
674 // (BE) This should go an advanced LaTeX options dialog.
676 // If there is no file specified, just output a message about it in
678 if (params.filename.empty()) {
679 os << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
680 << _("empty figure path")
683 return 1; // One end of line marker added to the stream.
686 // Keep count of newlines that we issued.
689 // This variables collect all the latex code that should be before and
690 // after the actual includegraphics command.
694 // Do we want subcaptions?
695 if (params.subcaption) {
696 before += "\\subfigure[" + params.subcaptionText + "]{";
700 // We never use the starred form, we use the "clip" option instead.
701 os << before << "\\includegraphics";
703 // Write the options if there are any.
704 string const opts = createLatexOptions();
706 os << '[' << opts << ']';
709 // Make the filename relative to the lyx file
710 // and remove the extension so the LaTeX will use whatever is
711 // appropriate (when there are several versions in different formats)
712 string const filename = prepareFile(buf);
714 os << '{' << filename << '}' << after;
716 // Return how many newlines we issued.
721 int InsetGraphics::ascii(Buffer const *, ostream &, int) const
723 // No graphics in ascii output. Possible to use gifscii to convert
724 // images to ascii approximation.
726 // 1. Convert file to ascii using gifscii
727 // 2. Read ascii output file and add it to the output stream.
733 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
735 // No graphics in LinuxDoc output. Should check how/what to add.
740 // For explanation on inserting graphics into DocBook checkout:
741 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
742 // See also the docbook guide at http://www.docbook.org/
743 int InsetGraphics::docBook(Buffer const * buf, ostream & os) const
745 // Change the path to be relative to the main file.
746 string const buffer_dir = OnlyPath(buf->fileName());
747 string const filename = RemoveExtension(
748 MakeRelPath(params.filename, buffer_dir));
750 // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
751 // need to switch to MediaObject. However, for now this is sufficient and
753 os << "<graphic fileref=\"" << filename << "\"></graphic>";
758 void InsetGraphics::validate(LaTeXFeatures & features) const
760 // If we have no image, we should not require anything.
761 if (params.filename.empty())
764 features.graphicx = true;
766 if (params.subcaption)
767 features.subfigure = true;
771 // Update the inset after parameters changed (read from file or changed in
773 void InsetGraphics::updateInset() const
775 GraphicsCache & gc = GraphicsCache::getInstance();
776 boost::shared_ptr<GraphicsCacheItem> temp(0);
778 // We do it this way so that in the face of some error, we will still
779 // be in a valid state.
780 if (!params.filename.empty()) {
781 temp = gc.addFile(params.filename);
784 // Mark the image as unloaded so that it gets updated.
791 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
793 // If nothing is changed, just return and say so.
797 // Copy the new parameters.
800 // Update the inset with the new parameters.
803 // We have changed data, report it.
808 InsetGraphicsParams InsetGraphics::getParams() const
814 Inset * InsetGraphics::clone(Buffer const &, bool same_id) const
816 return new InsetGraphics(*this, same_id);