]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
Small fixes:
[lyx.git] / src / insets / insetgraphics.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *       
6  *           Copyright 1995-2001 the LyX Team.
7  *           
8  *           This file Copyright 2000 Baruch Even.
9  * ====================================================== */
10
11 /*
12 Major tasks:
13         * Switch to convert the images in the background, this requires work on
14                 the converter, the systemcontroller and the graphics cache.
15
16 Minor tasks:
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(?)
19         
20 */
21
22 /*
23 Known BUGS:
24     
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 
30        what the user meant.
31        [Note that browseRelFile in helper_funcs.* provides a file name
32         which is relative if it is at reference path (here puffer path)
33         level or below, and an absolute path if the file name is not a
34         `natural' relative file name. In any case,
35             MakeAbsPath(filename, buf->filePath())
36         is guaranteed to provide the correct absolute path. This is what is
37         done know for include insets. Feel free to ask me -- JMarc
38         14/01/2002]
39         
40         * If we are trying to create a file in a read-only directory and there
41                 are graphics that need converting, the converting will fail because
42                 it is done in-place, into the same directory as the original image.
43                 This needs to be fixed in the src/converter.C file
44                 [ This is presumed to be fixed, needs testing.]
45
46         * We do not dither or resize the image in a WYSIWYM way, we load it at
47                 its original size and color, resizing is done in the final output,
48                 but not in the LyX window.
49
50         * The scale option is only handled for the horizontal part, the vertical
51                 part will not work. For now it is also shown only for horizontal
52                 resizing on the form.
53
54         * EPS figures are not fully detected, they may have a lot of possible
55                 suffixes so we need to read the file and detect if it's EPS or not.
56                 [Implemented, need testing]
57                 
58 TODO Before initial production release:
59     * Replace insetfig everywhere
60         * Search for comments of the form
61             // INSET_GRAPHICS: remove this when InsetFig is thrown.
62           And act upon them. Make sure not to remove InsetFig code for the 
63                   1.2.0 release, only afterwards, after deployment shows InsetGraphics
64                   to be ok.
65  
66 TODO Extended features:
67  
68     * Advanced Latex tab folder.
69     * Add support for more features so that it will be better than insetfig.
70         * Keep aspect ratio radio button
71         * Support for complete control over the latex parameters for TeXperts
72         * What advanced features the users want to do?
73             Implement them in a non latex dependent way, but a logical way.
74             LyX should translate it to latex or any other fitting format.
75     * Add a way to roll the image file into the file format.
76     * When loading, if the image is not found in the expected place, try
77        to find it in the clipart, or in the same directory with the image.
78     * Keep a tab on the image file, if it changes, update the lyx view.
79         * The image choosing dialog could show thumbnails of the image formats
80           it knows of, thus selection based on the image instead of based on
81           filename.
82         * Add support for the 'picins' package.
83         * Add support for the 'picinpar' package.
84         * Improve support for 'subfigure' - Allow to set the various options
85                 that are possible.
86         * Add resizing by percentage of image size (50%, 150%) -
87           usefull for two images of different size to be resized where
88           they both should have the same scale compared to each other.
89  */
90
91 /* NOTES:
92  *
93  * Intentions:
94  *  This is currently a moving target, I'm trying stuff and learning what
95  *  is needed and how to accomplish it, since there is no predefined goal or
96  *  way to go I invent it as I go.
97  *
98  *  My current intention is for seperation from LaTeX, the basic needs are 
99  *  resizing and rotating, displaying on screen in various depths and printing
100  *  conversion of depths (independent of the display depth). For this I'll 
101  *  provide a simple interface.
102  *
103  *  The medium level includes clipping of the image, but in a limited way.
104  *
105  *  For the LaTeX gurus I'll provide a complete control over the output, but
106  *  this is latex dependent and guru dependent so I'd rather avoid doing this
107  *  for the normal user. This stuff includes clipping, special image size
108  *  specifications (\textwidth\minus 2in) which I see no way to generalize
109  *  to non-latex specific way.
110  *
111  * Used packages:
112  *  'graphicx' for the graphics inclusion.
113  *  'subfigure' for the subfigures.
114  *
115  * Fileformat:
116  *
117  * Current version is 1 (inset file format version), when changing it
118  * it should be changed in the Write() function when writing in one place
119  * and when reading one should change the version check and the error message.
120  *
121  * The filename is kept in  the lyx file in a relative way, so as to allow
122  * moving the document file and its images with no problem.
123  *
124  * Conversions:
125  *   Postscript output means EPS figures.
126  *
127  *   PDF output is best done with PDF figures if it's a direct conversion
128  *   or PNG figures otherwise.
129  *      Image format
130  *      from        to
131  *      EPS         epstopdf
132  *      JPG/PNG     direct
133  *      PDF         direct
134  *      others      PNG
135  */
136
137 #include <config.h> 
138
139 #ifdef __GNUG__
140 #pragma implementation
141 #endif 
142
143 #include "insets/insetgraphics.h"
144 #include "insets/insetgraphicsParams.h"
145 #include "graphics/GraphicsCache.h"
146 #include "graphics/GraphicsCacheItem.h"
147
148 #include "frontends/Dialogs.h"
149 #include "LyXView.h"
150 #include "buffer.h"
151 #include "BufferView.h"
152 #include "converter.h"
153 #include "frontends/support/LyXImage.h"
154 #include "Painter.h"
155 #include "lyx_gui_misc.h"
156 #include "support/FileInfo.h"
157 #include "support/filetools.h"
158 #include "support/lyxlib.h"
159 #include "lyxtext.h"
160 #include "lyxrc.h"
161 #include "font.h" // For the lyxfont class.
162 #include "fstream" // for ifstream in isEPS
163 #include <algorithm> // For the std::max
164 #include "support/lyxmanip.h"
165 #include "debug.h"
166 #include "gettext.h"
167
168 extern string system_tempdir;
169
170 using std::ifstream;
171 using std::ostream;
172 using std::endl;
173
174
175 // This function is a utility function
176 // ... that should be with ChangeExtension ...
177 inline
178 string const RemoveExtension(string const & filename)
179 {
180         return ChangeExtension(filename, string());
181 }
182
183
184 // Initialize only those variables that do not have a constructor.
185 InsetGraphics::InsetGraphics()
186         : cacheHandle(0), imageLoaded(false)
187 {}
188
189
190 InsetGraphics::InsetGraphics(InsetGraphics const & ig, bool same_id)
191         : Inset(), SigC::Object()
192         , cacheHandle(ig.cacheHandle)
193         , imageLoaded(ig.imageLoaded)
194 {
195         setParams(ig.getParams());
196         if (same_id)
197                 id_ = ig.id_;
198 }
199
200
201 InsetGraphics::~InsetGraphics()
202 {
203         // Emits the hide signal to the dialog connected (if any)
204         hideDialog();
205 }
206
207
208 string const
209 InsetGraphics::statusMessage() const
210 {
211         string msg;
212
213         if (cacheHandle.get()) {
214                 switch (cacheHandle->getImageStatus()) {
215                 case GraphicsCacheItem::UnknownError:
216                         msg = _("Unknown Error");
217                         break;
218
219                 case GraphicsCacheItem::Loading:
220                         msg = _("Loading...");
221                         break;
222
223                 case GraphicsCacheItem::ErrorReading:
224                         msg = _("Error reading");
225                         break;
226
227                 case GraphicsCacheItem::ErrorConverting:
228                         msg = _("Error converting");
229                         break;
230
231                 case GraphicsCacheItem::Loaded:
232                         // No message to write.
233                         break;
234                 }
235         }
236
237         return msg;
238 }
239
240
241 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
242 {
243         LyXImage * pixmap = 0;
244         if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
245                 return pixmap->getHeight();
246         else
247                 return 50;
248 }
249
250
251 int InsetGraphics::descent(BufferView *, LyXFont const &) const
252 {
253         // this is not true if viewport is used and clip is not.
254         return 0;
255 }
256
257
258 int InsetGraphics::width(BufferView *, LyXFont const & font) const
259 {
260         LyXImage * pixmap = 0;
261         
262         if (cacheHandle.get() && (pixmap = cacheHandle->getImage()))
263                 return pixmap->getWidth();
264         else {
265                 int font_width = 0;
266
267                 LyXFont msgFont(font);
268                 msgFont.setFamily(LyXFont::SANS_FAMILY);
269
270                 string const justname = OnlyFilename (params.filename);
271                 if (!justname.empty()) {
272                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
273                         font_width = lyxfont::width(justname, msgFont);
274                 }
275
276                 string const msg = statusMessage();
277                 if (!msg.empty()) {
278                         msgFont.setSize(LyXFont::SIZE_TINY);
279                         int const msg_width = lyxfont::width(msg, msgFont);
280                         font_width = std::max(font_width, msg_width);
281                 }
282                 
283                 return std::max(50, font_width + 15);
284         }
285 }
286
287
288 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
289                          int baseline, float & x, bool) const
290 {
291         Painter & paint = bv->painter();
292
293         int ldescent = descent(bv, font);
294         int lascent = ascent(bv, font);
295         int lwidth = width(bv, font);
296
297         // Make sure x is updated upon exit from this routine
298         int old_x = int(x);
299         x += lwidth;
300
301         // This will draw the graphics. If the graphics has not been loaded yet,
302         // we draw just a rectangle.
303         if (imageLoaded) {
304
305                 paint.image(old_x + 2, baseline - lascent,
306                             lwidth - 4, lascent + ldescent,
307                             cacheHandle->getImage());
308         } else {
309                 
310                 // Get the image status, default to unknown error.
311                 GraphicsCacheItem::ImageStatus status = GraphicsCacheItem::UnknownError;
312                 if (lyxrc.display_graphics != "no" && lyxrc.use_gui
313                     && params.display != InsetGraphicsParams::NONE &&
314                     cacheHandle.get())
315                         status = cacheHandle->getImageStatus();
316                 
317                 // Check if the image is now ready.
318                 if (status == GraphicsCacheItem::Loaded) {
319                         imageLoaded = true;
320
321                         // Tell BufferView we need to be updated!
322                         bv->text->status(bv, LyXText::CHANGED_IN_DRAW);
323                         return;
324                 }
325
326                 paint.rectangle(old_x + 2, baseline - lascent,
327                                 lwidth - 4,
328                                 lascent + ldescent);
329
330                 // Print the file name.
331                 LyXFont msgFont(font);
332                 msgFont.setFamily(LyXFont::SANS_FAMILY);
333
334                 string const justname = OnlyFilename (params.filename);
335                 if (!justname.empty()) {
336                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
337                         paint.text(old_x + 8, 
338                                    baseline - lyxfont::maxAscent(msgFont) - 4,
339                                    justname, msgFont);
340                 }
341
342                 // Print the message.
343                 string const msg = statusMessage();
344                 if (!msg.empty()) {
345                         msgFont.setSize(LyXFont::SIZE_TINY);
346                         paint.text(old_x + 8, baseline - 4, msg, msgFont);
347                 }
348         }
349 }
350
351
352 void InsetGraphics::edit(BufferView *bv, int, int, unsigned int)
353 {
354         bv->owner()->getDialogs()->showGraphics(this);
355 }
356
357
358 void InsetGraphics::edit(BufferView * bv, bool)
359 {
360         edit(bv, 0, 0, 0);
361 }
362
363
364 Inset::EDITABLE InsetGraphics::editable() const
365 {
366         return IS_EDITABLE;
367 }
368
369
370 void InsetGraphics::write(Buffer const * buf, ostream & os) const
371 {
372         os << "Graphics FormatVersion 1\n";
373
374         params.Write(buf, os);
375 }
376
377
378 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
379 {
380         string const token = lex.getString();
381
382         if (token == "Graphics")
383                 readInsetGraphics(buf, lex);
384         else if (token == "Figure") // Compatibility reading of FigInset figures.
385                 readFigInset(buf, lex);
386         else
387                 lyxerr[Debug::INFO] << "Not a Graphics or Figure inset!\n";
388
389         updateInset();
390 }
391
392 void InsetGraphics::readInsetGraphics(Buffer const * buf, LyXLex & lex)
393 {
394         bool finished = false;
395
396         while (lex.isOK() && !finished) {
397                 lex.next();
398
399                 string const token = lex.getString();
400                 lyxerr[Debug::INFO] << "Token: '" << token << '\'' 
401                                     << std::endl;
402
403                 if (token.empty()) {
404                         continue;
405                 } else if (token == "\\end_inset") {
406                         finished = true;
407                 } else if (token == "FormatVersion") {
408                         lex.next();
409                         int version = lex.getInteger();
410                         if (version > 1)
411                                 lyxerr
412                                 << "This document was created with a newer Graphics widget"
413                                 ", You should use a newer version of LyX to read this"
414                                 " file."
415                                 << std::endl;
416                         // TODO: Possibly open up a dialog?
417                 }
418                 else {
419                         if (! params.Read(buf, lex, token))
420                                 lyxerr << "Unknown token, " << token << ", skipping." 
421                                         << std::endl;
422                 }
423         }
424 }
425
426
427 void InsetGraphics::readFigInset(Buffer const * buf, LyXLex & lex)
428 {
429         bool finished = false;
430         
431         while (lex.isOK() && !finished) {
432                 lex.next();
433
434                 string const token = lex.getString();
435                 lyxerr[Debug::INFO] << "Token: " << token << endl;
436                 
437                 if (token.empty())
438                         continue;
439                 else if (token == "\\end_inset") {
440                         finished = true;
441                 } else if (token == "file") {
442                         if (lex.next()) {
443                                 string const name = lex.getString();
444                                 string const path = buf->filePath();
445                                 params.filename = MakeAbsPath(name, path);
446                         }
447                 } else if (token == "extra") {
448                         if (lex.next());
449                         // kept for backwards compability. Delete in 0.13.x
450                 } else if (token == "subcaption") {
451                         if (lex.eatLine())
452                                 params.subcaptionText = lex.getString();
453                 } else if (token == "label") {
454                         if (lex.next());
455                         // kept for backwards compability. Delete in 0.13.x
456                 } else if (token == "angle") {
457                         if (lex.next())
458                                 params.rotateAngle = lex.getFloat();
459                 } else if (token == "size") {
460                         // Size of image on screen is ignored in InsetGraphics, just eat
461                         // the input.
462                         if (lex.next()) {
463                                 lex.getInteger();
464                         }
465                         if (lex.next()) {
466                                 lex.getInteger();
467                         }
468                 } else if (token == "flags") {
469                         InsetGraphicsParams::DisplayType tmp = InsetGraphicsParams::COLOR;
470                         if (lex.next())
471                                 switch (lex.getInteger()) {
472                                 case 1: tmp = InsetGraphicsParams::MONOCHROME; break;
473                                 case 2: tmp = InsetGraphicsParams::GRAYSCALE; break;
474                                 }
475                         params.display = tmp;
476                 } else if (token == "subfigure") {
477                         params.subcaption = true;
478                 } else if (token == "width") {
479                         if (lex.next()) {
480                                 params.widthResize = static_cast<InsetGraphicsParams::Resize>(lex.getInteger());
481                         }
482                         if (lex.next()) {
483                                 params.widthSize = lex.getFloat();
484                         }
485                 } else if (token == "height") {
486                         if (lex.next()) {
487                                 params.heightResize = static_cast<InsetGraphicsParams::Resize>(lex.getInteger());
488                         }
489                         if (lex.next()) {
490                                 params.heightSize = lex.getFloat();
491                         }
492                 }
493         }
494 }
495
496
497 namespace {
498
499 void formatResize(ostream & os, string const & key,
500                   InsetGraphicsParams::Resize resizeType, double size)
501 {
502         switch (resizeType) {
503         case InsetGraphicsParams::DEFAULT_SIZE:
504                 break;
505
506         case InsetGraphicsParams::CM:
507                 os << key << '=' << size << "cm,";
508                 break;
509
510         case InsetGraphicsParams::INCH:
511                 os << key << '=' << size << "in,";
512                 break;
513
514         case InsetGraphicsParams::PERCENT_PAGE:
515                 os << key << '=' << size / 100 << "\\text" << key << ',';
516                 break;
517
518         case InsetGraphicsParams::PERCENT_COLUMN:
519                 os << key << '=' << size / 100 << "\\column" << key << ',';
520                 break;
521
522         case InsetGraphicsParams::SCALE:
523                 os << "scale" << '=' << size/100 << ',';
524         }
525 }
526
527 } // namespace anon
528
529
530 string const
531 InsetGraphics::createLatexOptions() const
532 {
533         // Calculate the options part of the command, we must do it to a string
534         // stream since we might have a trailing comma that we would like to remove
535         // before writing it to the output stream.
536         ostringstream options;
537
538         formatResize(options, "width", params.widthResize, params.widthSize);
539         formatResize(options, "height", params.heightResize, params.heightSize);
540
541         // Make sure it's not very close to zero, a float can be effectively
542         // zero but not exactly zero.
543         if (!lyx::float_equal(params.rotateAngle, 0, 0.001)) {
544                 options << "angle="
545                         << params.rotateAngle << ',';
546         }
547
548         string opts = options.str().c_str();
549         opts = strip(opts, ',');
550
551         return opts;
552 }
553
554 namespace {
555
556 enum FileType {
557         EPS,
558         PNG,
559         JPEG,
560         GIF,
561         PDF,
562         UNKNOWN
563 };
564
565 bool isEPS(string const & filename)
566 {
567         if (filename.empty() || !IsFileReadable(filename)) return false;
568
569         ifstream ifs(filename.c_str());
570
571         if (!ifs) return false; // Couldn't open file...
572
573         bool is_eps = false; // Have we recognized the file as EPS?
574         string to_find = "%!PS-Adobe-"; // The string we use to recognize
575         int const max_attempts = 500; // Maximum strings to read to attempt recognition
576         int count = 0; // Counter of attempts.
577         string str;
578         for (; count < max_attempts; ++count) {
579                 if (ifs.eof()) {
580                         lyxerr[Debug::INFO] << "InsetGraphics (isEPS)"
581                                 " End of file reached and it wasn't found to be EPS!" << endl;
582                         break;
583                 }
584
585                 ifs >> str;
586                 if (str.find(to_find)) {
587                         is_eps = true;
588                         break;
589                 }
590         }
591
592         return is_eps;
593 }
594
595 enum FileType classifyFileType(string const & filename, string const & suffix)
596 {
597         if (suffix == "png")
598                 return PNG;
599         else if (suffix == "jpg" || suffix == "jpeg")
600                 return JPEG;
601         else if (suffix == "gif")
602                 return GIF;
603         else if (suffix == "pdf")
604                 return PDF;
605         else if (isEPS(filename))
606                 return EPS;
607
608         return UNKNOWN;
609 }
610
611 string decideOutputImageFormat(string const & suffix, enum FileType type)
612 {
613         // lyxrc.pdf_mode means:
614         // Are we creating a PDF or a PS file?
615         // (Should actually mean, are we using latex or pdflatex).
616         
617         if (lyxrc.pdf_mode) {
618                 if (type == EPS || type == EPS || type == PDF)
619                         return "pdf";
620                 else if (type == JPEG)
621                         return suffix;
622                 else
623                         return "png";
624         }
625
626         // If it's postscript, we always do eps.
627         // There are many suffixes that are actually EPS (ask Garst for example)
628         // so we detect if it's an EPS by looking in the file, if it is, we return
629         // the same suffix of the file so it won't be converted.
630         if (type == EPS)
631                 return suffix;
632         
633         return "eps";
634 }
635
636 } // Anon. namespace
637
638 string const 
639 InsetGraphics::prepareFile(Buffer const *buf) const
640 {
641
642         // do_convert = Do we need to convert the file?
643         // nice = Do we create a nice version?
644         //        This is used when exporting the latex file only.
645         // 
646         // 
647         // if (!do_convert)
648         //   return original filename
649         // 
650         // if (!nice)
651         //   convert_place = temp directory
652         //   return new filename in temp directory
653         // else
654         //   convert_place = original file directory
655         //   return original filename without the extension
656         //
657         
658         // Get the extension (format) of the original file.
659         string const extension = GetExtension(params.filename);
660         FileType type = classifyFileType(params.filename, extension);
661         
662         // Are we creating a PDF or a PS file?
663         // (Should actually mean, are we usind latex or pdflatex).
664         string const image_target = decideOutputImageFormat(extension, type);
665
666         if (extension == image_target)
667                 return params.filename;
668
669         string outfile;
670         if (!buf->niceFile) {
671                 string const temp = AddName(buf->tmppath, params.filename);
672                 outfile = RemoveExtension(temp);
673                 
674                 //lyxerr << "buf::tmppath = " << buf->tmppath << "\n";
675                 //lyxerr << "filename = " << params.filename << "\n";
676                 //lyxerr << "temp = " << temp << "\n";
677                 //lyxerr << "outfile = " << outfile << endl;
678         } else {
679                 string const path = buf->filePath();
680                 string const relname = MakeRelPath(params.filename, path);
681                 outfile = RemoveExtension(relname);
682         }
683
684         converters.convert(buf, params.filename, outfile, extension, image_target);
685         
686         return outfile;
687 }
688
689
690 int InsetGraphics::latex(Buffer const *buf, ostream & os,
691                          bool /*fragile*/, bool/*fs*/) const
692 {
693         // MISSING: We have to decide how to do the order of the options
694         // that is dependent of order, like width, height, angle. Should
695         // we rotate before scale? Should we let the user decide?
696         // bool rot_before_scale; ?
697
698         // (BE) As a first step we should do a scale before rotate since this is
699         // more like the natural thought of how to do it.
700         // (BE) I believe that a priority list presented to the user with
701         // a default order would be the best, though it would be better to
702         // hide such a thing in an "Advanced options" dialog.
703         // (BE) This should go an advanced LaTeX options dialog.
704
705         // If there is no file specified, just output a message about it in
706         // the latex output.
707         if (params.filename.empty()) {
708                 os  << "\\fbox{\\rule[-0.5in]{0pt}{1in}"
709                         << _("empty figure path")
710                         << "}\n";
711
712                 return 1; // One end of line marker added to the stream.
713         }
714
715         // Keep count of newlines that we issued.
716         int newlines = 0;
717
718         // This variables collect all the latex code that should be before and
719         // after the actual includegraphics command.
720         string before;
721         string after;
722
723         // Do we want subcaptions?
724         if (params.subcaption) {
725                 before += "\\subfigure[" + params.subcaptionText + "]{";
726                 after = '}' + after;
727         }
728
729         // We never use the starred form, we use the "clip" option instead.
730         os << before << "\\includegraphics";
731
732         // Write the options if there are any.
733         string const opts = createLatexOptions();
734         if (!opts.empty()) {
735                 os << '[' << opts << ']';
736         }
737
738         // Make the filename relative to the lyx file
739         // and remove the extension so the LaTeX will use whatever is
740         // appropriate (when there are several versions in different formats)
741         string const filename = prepareFile(buf);
742         
743         os << '{' << filename << '}' << after;
744
745         // Return how many newlines we issued.
746         return newlines;
747 }
748
749
750 int InsetGraphics::ascii(Buffer const *, ostream &, int) const
751 {
752         // No graphics in ascii output. Possible to use gifscii to convert
753         // images to ascii approximation.
754         
755         // 1. Convert file to ascii using gifscii
756         // 2. Read ascii output file and add it to the output stream.
757         
758         return 0;
759 }
760
761
762 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
763 {
764         // No graphics in LinuxDoc output. Should check how/what to add.
765         return 0;
766 }
767
768
769 // For explanation on inserting graphics into DocBook checkout:
770 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
771 // See also the docbook guide at http://www.docbook.org/
772 int InsetGraphics::docbook(Buffer const * buf, ostream & os) const
773 {
774         // Change the path to be relative to the main file.
775         string const buffer_dir = buf->filePath();
776         string filename = RemoveExtension(
777                 MakeRelPath(params.filename, buffer_dir));
778
779         if (suffixIs(filename, ".eps"))
780                 filename.erase(filename.length() - 4);
781
782         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will 
783         // need to switch to MediaObject. However, for now this is sufficient and 
784         // easier to use.
785         os << "<graphic fileref=\"" << filename << "\"></graphic>";
786         return 0;
787 }
788
789
790 void InsetGraphics::validate(LaTeXFeatures & features) const
791 {
792         // If we have no image, we should not require anything.
793         if (params.filename.empty())
794                 return ;
795
796         features.require("graphicx");
797
798         if (params.subcaption)
799                 features.require("subfigure");
800 }
801
802
803 // Update the inset after parameters changed (read from file or changed in
804 // dialog.
805 void InsetGraphics::updateInset() const
806 {
807         GraphicsCache & gc = GraphicsCache::getInstance();
808         boost::shared_ptr<GraphicsCacheItem> temp(0);
809
810         // We do it this way so that in the face of some error, we will still
811         // be in a valid state.
812         if (!params.filename.empty() && lyxrc.use_gui
813             && lyxrc.display_graphics != "no" 
814             && params.display != InsetGraphicsParams::NONE) {
815                 temp = gc.addFile(params.filename);
816         }
817
818         // Mark the image as unloaded so that it gets updated.
819         imageLoaded = false;
820
821         cacheHandle = temp;
822 }
823
824
825 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
826 {
827         // If nothing is changed, just return and say so.
828         if (params == p)
829                 return false;
830
831         // Copy the new parameters.
832         params = p;
833
834         // Update the inset with the new parameters.
835         updateInset();
836
837         // We have changed data, report it.
838         return true;
839 }
840
841
842 InsetGraphicsParams InsetGraphics::getParams() const
843 {
844         return params;
845 }
846
847
848 Inset * InsetGraphics::clone(Buffer const &, bool same_id) const
849 {
850         return new InsetGraphics(*this, same_id);
851 }