]> git.lyx.org Git - features.git/blob - src/insets/insetgraphics.C
(Rob Lahaye): read and write latex height data of graphic correctly.
[features.git] / src / insets / insetgraphics.C
1 /**
2  * \file insetgraphics.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Baruch Even
7  * \author Herbert Voss
8  *
9  * Full author contact details are available in file CREDITS
10  */
11
12 /*
13 TODO
14
15     * What advanced features the users want to do?
16       Implement them in a non latex dependent way, but a logical way.
17       LyX should translate it to latex or any other fitting format.
18     * Add a way to roll the image file into the file format.
19     * When loading, if the image is not found in the expected place, try
20       to find it in the clipart, or in the same directory with the image.
21     * The image choosing dialog could show thumbnails of the image formats
22       it knows of, thus selection based on the image instead of based on
23       filename.
24     * Add support for the 'picins' package.
25     * Add support for the 'picinpar' package.
26     * Improve support for 'subfigure' - Allow to set the various options
27       that are possible.
28 */
29
30 /* NOTES:
31  * Fileformat:
32  * Current version is 1 (inset file format version), when changing it
33  * it should be changed in the Write() function when writing in one place
34  * and when reading one should change the version check and the error message.
35  * The filename is kept in  the lyx file in a relative way, so as to allow
36  * moving the document file and its images with no problem.
37  *
38  *
39  * Conversions:
40  *   Postscript output means EPS figures.
41  *
42  *   PDF output is best done with PDF figures if it's a direct conversion
43  *   or PNG figures otherwise.
44  *      Image format
45  *      from        to
46  *      EPS         epstopdf
47  *      PS          ps2pdf
48  *      JPG/PNG     direct
49  *      PDF         direct
50  *      others      PNG
51  */
52
53 #include <config.h>
54
55 #ifdef __GNUG__
56 #pragma implementation
57 #endif
58
59 #include "insets/insetgraphics.h"
60 #include "insets/insetgraphicsParams.h"
61
62 #include "graphics/GraphicsLoader.h"
63 #include "graphics/GraphicsImage.h"
64 #include "graphics/GraphicsParams.h"
65
66 #include "lyxtext.h"
67 #include "buffer.h"
68 #include "BufferView.h"
69 #include "converter.h"
70 #include "frontends/Painter.h"
71 #include "lyxrc.h"
72 #include "frontends/font_metrics.h"
73 #include "debug.h"
74 #include "gettext.h"
75 #include "LaTeXFeatures.h"
76 #include "lyxlex.h"
77
78 #include "frontends/Alert.h"
79 #include "frontends/Dialogs.h"
80 #include "frontends/LyXView.h"
81
82 #include "frontends/controllers/helper_funcs.h" // getVectorFromString
83
84 #include "support/LAssert.h"
85 #include "support/filetools.h"
86 #include "support/lyxalgo.h" // lyx::count
87 #include "support/lyxlib.h" // float_equal
88 #include "support/path.h"
89 #include "support/systemcall.h"
90 #include "support/os.h"
91
92 #include <boost/weak_ptr.hpp>
93 #include <boost/bind.hpp>
94 #include <boost/signals/trackable.hpp>
95
96 #include <algorithm> // For the std::max
97
98 extern string system_tempdir;
99
100 using std::ostream;
101 using std::endl;
102
103 ///////////////////////////////////////////////////////////////////////////
104 int const VersionNumber = 1;
105 ///////////////////////////////////////////////////////////////////////////
106
107 namespace {
108
109 // This function is a utility function
110 // ... that should be with ChangeExtension ...
111 inline
112 string const RemoveExtension(string const & filename)
113 {
114         return ChangeExtension(filename, string());
115 }
116
117 } // namespace anon
118
119
120 namespace {
121
122 string const uniqueID()
123 {
124         static unsigned int seed = 1000;
125
126         ostringstream ost;
127         ost << "graph" << ++seed;
128
129         // Needed if we use lyxstring.
130         return ost.str().c_str();
131 }
132
133 } // namespace anon
134
135
136 struct InsetGraphics::Cache : boost::signals::trackable
137 {
138         ///
139         Cache(InsetGraphics &);
140         ///
141         void update(string const & file_with_path);
142
143         ///
144         int old_ascent;
145         ///
146         grfx::Loader loader;
147         ///
148         unsigned long checksum;
149         ///
150         boost::weak_ptr<BufferView> view;
151
152 private:
153         ///
154         InsetGraphics & parent_;
155 };
156
157
158 InsetGraphics::Cache::Cache(InsetGraphics & p)
159         : old_ascent(0), checksum(0), parent_(p)
160 {
161         loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
162 }
163
164
165 void InsetGraphics::Cache::update(string const & file_with_path)
166 {
167         lyx::Assert(!file_with_path.empty());
168
169         string const path = OnlyPath(file_with_path);
170         loader.reset(file_with_path, parent_.params().as_grfxParams(path));
171 }
172
173
174 InsetGraphics::InsetGraphics()
175         : graphic_label(uniqueID()),
176           cache_(new Cache(*this))
177 {}
178
179
180 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
181                              string const & filepath,
182                              bool same_id)
183         : Inset(ig, same_id),
184           graphic_label(uniqueID()),
185           cache_(new Cache(*this))
186 {
187         setParams(ig.params(), filepath);
188 }
189
190
191 InsetGraphics::~InsetGraphics()
192 {
193         // Emits the hide signal to the dialog connected (if any)
194         hideDialog();
195 }
196
197
198 string const InsetGraphics::statusMessage() const
199 {
200         string msg;
201
202         switch (cache_->loader.status()) {
203         case grfx::WaitingToLoad:
204                 msg = _("Waiting for draw request to start loading...");
205                 break;
206         case grfx::Loading:
207                 msg = _("Loading...");
208                 break;
209         case grfx::Converting:
210                 msg = _("Converting to loadable format...");
211                 break;
212         case grfx::Loaded:
213                 msg = _("Loaded into memory. Must now generate pixmap.");
214                 break;
215         case grfx::ScalingEtc:
216                 msg = _("Scaling etc...");
217                 break;
218         case grfx::Ready:
219                 msg = _("Ready to display");
220                 break;
221         case grfx::ErrorNoFile:
222                 msg = _("No file found!");
223                 break;
224         case grfx::ErrorConverting:
225                 msg = _("Error converting to loadable format");
226                 break;
227         case grfx::ErrorLoading:
228                 msg = _("Error loading file into memory");
229                 break;
230         case grfx::ErrorGeneratingPixmap:
231                 msg = _("Error generating the pixmap");
232                 break;
233         case grfx::ErrorUnknown:
234                 msg = _("No image");
235                 break;
236         }
237
238         return msg;
239 }
240
241
242 bool InsetGraphics::imageIsDrawable() const
243 {
244         if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
245                 return false;
246
247         return cache_->loader.image()->isDrawable();
248 }
249
250
251 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
252 {
253         cache_->old_ascent = 50;
254         if (imageIsDrawable())
255                 cache_->old_ascent = cache_->loader.image()->getHeight();
256         return cache_->old_ascent;
257 }
258
259
260 int InsetGraphics::descent(BufferView *, LyXFont const &) const
261 {
262         return 0;
263 }
264
265
266 int InsetGraphics::width(BufferView *, LyXFont const & font) const
267 {
268         if (imageIsDrawable())
269                 return cache_->loader.image()->getWidth();
270         else {
271                 int font_width = 0;
272
273                 LyXFont msgFont(font);
274                 msgFont.setFamily(LyXFont::SANS_FAMILY);
275
276                 string const justname = OnlyFilename (params().filename);
277                 if (!justname.empty()) {
278                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
279                         font_width = font_metrics::width(justname, msgFont);
280                 }
281
282                 string const msg = statusMessage();
283                 if (!msg.empty()) {
284                         msgFont.setSize(LyXFont::SIZE_TINY);
285                         int const msg_width = font_metrics::width(msg, msgFont);
286                         font_width = std::max(font_width, msg_width);
287                 }
288
289                 return std::max(50, font_width + 15);
290         }
291 }
292
293
294 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
295                          int baseline, float & x, bool) const
296 {
297         // MakeAbsPath returns params().filename unchanged if it absolute
298         // already.
299         string const file_with_path =
300                 MakeAbsPath(params().filename, bv->buffer()->filePath());
301
302         // A 'paste' operation creates a new inset with the correct filepath,
303         // but then the 'old' inset stored in the 'copy' operation is actually
304         // added to the buffer.
305         // Thus, we should ensure that the filepath is correct.
306         if (file_with_path != cache_->loader.filename())
307                 cache_->update(file_with_path);
308
309         cache_->view = bv->owner()->view();
310         int oasc = cache_->old_ascent;
311
312         int ldescent = descent(bv, font);
313         int lascent  = ascent(bv, font);
314         int lwidth   = width(bv, font);
315
316         // we may have changed while someone other was drawing us so better
317         // to not draw anything as we surely call to redraw ourself soon.
318         // This is not a nice thing to do and should be fixed properly somehow.
319         // But I still don't know the best way to go. So let's do this like this
320         // for now (Jug 20020311)
321         if (lascent != oasc) {
322                 return;
323         }
324
325         // Make sure now that x is updated upon exit from this routine
326         int old_x = int(x);
327         x += lwidth;
328
329         if (cache_->loader.status() == grfx::WaitingToLoad)
330                 cache_->loader.startLoading(*this, *bv);
331
332         if (!cache_->loader.monitoring())
333                 cache_->loader.startMonitoring();
334
335         // This will draw the graphics. If the graphics has not been loaded yet,
336         // we draw just a rectangle.
337         Painter & paint = bv->painter();
338
339         if (imageIsDrawable()) {
340                 paint.image(old_x + 2, baseline - lascent,
341                             lwidth - 4, lascent + ldescent,
342                             *cache_->loader.image());
343
344         } else {
345
346                 paint.rectangle(old_x + 2, baseline - lascent,
347                                 lwidth - 4,
348                                 lascent + ldescent);
349
350                 // Print the file name.
351                 LyXFont msgFont(font);
352                 msgFont.setFamily(LyXFont::SANS_FAMILY);
353                 string const justname = OnlyFilename (params().filename);
354                 if (!justname.empty()) {
355                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
356                         paint.text(old_x + 8,
357                                    baseline - font_metrics::maxAscent(msgFont) - 4,
358                                    justname, msgFont);
359                 }
360
361                 // Print the message.
362                 string const msg = statusMessage();
363                 if (!msg.empty()) {
364                         msgFont.setSize(LyXFont::SIZE_TINY);
365                         paint.text(old_x + 8, baseline - 4, msg, msgFont);
366                 }
367         }
368
369         // the status message may mean we changed size, so indicate
370         // we need a row redraw
371 #if 0
372         if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
373                 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
374         }
375 #endif
376
377         // Reset the cache, ready for the next draw request
378 #if 0
379         cached_status_ = grfx::ErrorUnknown;
380         cached_image_.reset();
381         cache_filled_ = false;
382 #endif
383 }
384
385
386 void InsetGraphics::edit(BufferView *bv, int, int, mouse_button::state)
387 {
388         bv->owner()->getDialogs().showGraphics(this);
389 }
390
391
392 void InsetGraphics::edit(BufferView * bv, bool)
393 {
394         edit(bv, 0, 0, mouse_button::none);
395 }
396
397
398 Inset::EDITABLE InsetGraphics::editable() const
399 {
400         return IS_EDITABLE;
401 }
402
403
404 void InsetGraphics::write(Buffer const *, ostream & os) const
405 {
406         os << "Graphics\n";
407         params().Write(os);
408 }
409
410
411 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
412 {
413         string const token = lex.getString();
414
415         if (token == "Graphics")
416                 readInsetGraphics(lex);
417         else
418                 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
419
420         cache_->update(MakeAbsPath(params().filename, buf->filePath()));
421 }
422
423
424 void InsetGraphics::readInsetGraphics(LyXLex & lex)
425 {
426         bool finished = false;
427
428         while (lex.isOK() && !finished) {
429                 lex.next();
430
431                 string const token = lex.getString();
432                 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
433                                     << std::endl;
434
435                 if (token.empty()) {
436                         continue;
437                 } else if (token == "\\end_inset") {
438                         finished = true;
439                 } else if (token == "FormatVersion") {
440                         lex.next();
441                         int version = lex.getInteger();
442                         if (version > VersionNumber)
443                                 lyxerr
444                                 << "This document was created with a newer Graphics widget"
445                                 ", You should use a newer version of LyX to read this"
446                                 " file."
447                                 << std::endl;
448                         // TODO: Possibly open up a dialog?
449                 }
450                 else {
451                         if (! params_.Read(lex, token))
452                                 lyxerr << "Unknown token, " << token << ", skipping."
453                                         << std::endl;
454                 }
455         }
456 }
457
458
459 string const InsetGraphics::createLatexOptions() const
460 {
461         // Calculate the options part of the command, we must do it to a string
462         // stream since we might have a trailing comma that we would like to remove
463         // before writing it to the output stream.
464         ostringstream options;
465         if (!params().bb.empty())
466             options << "  bb=" << rtrim(params().bb) << ",\n";
467         if (params().draft)
468             options << "  draft,\n";
469         if (params().clip)
470             options << "  clip,\n";
471         
472         if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
473                 if (!lyx::float_equal(params().scale, 100.0, 0.05))
474                         options << "  scale=" << params().scale / 100.0
475                                 << ",\n";
476         } else {
477                 if (!params().width.zero())
478                         options << "  width=" << params().width.asLatexString() << ",\n";
479                 if (!params().height.zero())
480                         options << "  height=" << params().height.asLatexString() << ",\n";
481                 if (params().keepAspectRatio)
482                         options << "  keepaspectratio,\n";
483         }
484
485         // Make sure rotation angle is not very close to zero;
486         // a float can be effectively zero but not exactly zero.
487         if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
488             options << "  angle=" << params().rotateAngle << ",\n";
489             if (!params().rotateOrigin.empty()) {
490                 options << "  origin=" << params().rotateOrigin[0];
491                 if (contains(params().rotateOrigin,"Top"))
492                     options << 't';
493                 else if (contains(params().rotateOrigin,"Bottom"))
494                     options << 'b';
495                 else if (contains(params().rotateOrigin,"Baseline"))
496                     options << 'B';
497                 options << ",\n";
498             }
499         }
500
501         if (!params().special.empty())
502             options << params().special << ",\n";
503
504         string opts = options.str().c_str();
505         return opts.substr(0,opts.size()-2);    // delete last ",\n"
506 }
507
508 namespace {
509 string findTargetFormat(string const & suffix)
510 {
511         // lyxrc.pdf_mode means:
512         // Are we creating a PDF or a PS file?
513         // (Should actually mean, are we using latex or pdflatex).
514         if (lyxrc.pdf_mode) {
515                 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
516                 if (contains(suffix, "ps") || suffix == "pdf")
517                         return "pdf";
518                 else if (suffix == "jpg")       // pdflatex can use jpeg
519                         return suffix;
520                 else
521                         return "png";           // and also png
522         }
523         // If it's postscript, we always do eps.
524         lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
525         if (suffix != "ps")                     // any other than ps
526             return "eps";                       // is changed to eps
527         else
528             return suffix;                      // let ps untouched
529 }
530
531 } // Anon. namespace
532
533
534 string const InsetGraphics::prepareFile(Buffer const *buf) const
535 {
536         // LaTeX can cope if the graphics file doesn't exist, so just return the
537         // filename.
538         string const orig_file = params().filename;
539         string orig_file_with_path =
540                 MakeAbsPath(orig_file, buf->filePath());
541         lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
542                     << orig_file << "\n\twith path: "
543                     << orig_file_with_path << endl;
544
545         if (!IsFileReadable(orig_file_with_path))
546                 return orig_file;
547
548         bool const zipped = zippedFile(orig_file_with_path);
549
550         // If the file is compressed and we have specified that it
551         // should not be uncompressed, then just return its name and
552         // let LaTeX do the rest!
553         if (zipped && params().noUnzip) {
554                 lyxerr[Debug::GRAPHICS]
555                         << "\tpass zipped file to LaTeX but with full path.\n";
556                 // LaTeX needs an absolue path, otherwise the
557                 // coresponding *.eps.bb file isn't found
558                 return orig_file_with_path;
559         }
560
561         // Ascertain whether the file has changed.
562         unsigned long const new_checksum = cache_->loader.checksum();
563         bool const file_has_changed = cache_->checksum != new_checksum;
564         if (file_has_changed)
565                 cache_->checksum = new_checksum;
566
567         // temp_file will contain the file for LaTeX to act on if, for example,
568         // we move it to a temp dir or uncompress it.
569         string temp_file(orig_file);
570
571         if (zipped) {
572                 // Uncompress the file if necessary.
573                 // If it has been uncompressed in a previous call to
574                 // prepareFile, do nothing.
575                 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
576                 lyxerr[Debug::GRAPHICS]
577                         << "\ttemp_file: " << temp_file << endl;
578                 if (file_has_changed || !IsFileReadable(temp_file)) {
579                         bool const success = lyx::copy(orig_file_with_path,
580                                                        temp_file);
581                         lyxerr[Debug::GRAPHICS]
582                                 << "\tCopying zipped file from "
583                                 << orig_file_with_path << " to " << temp_file
584                                 << (success ? " succeeded\n" : " failed\n");
585                 } else
586                         lyxerr[Debug::GRAPHICS]
587                                 << "\tzipped file " << temp_file
588                                 << " exists! Maybe no tempdir ...\n";
589                 orig_file_with_path = unzipFile(temp_file);
590                 lyxerr[Debug::GRAPHICS]
591                         << "\tunzipped to " << orig_file_with_path << endl;
592         }
593
594         string const from = getExtFromContents(orig_file_with_path);
595         string const to   = findTargetFormat(from);
596         lyxerr[Debug::GRAPHICS]
597                 << "\t we have: from " << from << " to " << to << '\n';
598
599         if (from == to && !lyxrc.use_tempdir)
600                 // No conversion is needed. LaTeX can handle the
601                 // graphic file as is.
602                 // This is true even if the orig_file is compressed.
603                 return RemoveExtension(orig_file_with_path);
604
605         // We're going to be running the exported buffer through the LaTeX
606         // compiler, so must ensure that LaTeX can cope with the graphics
607         // file format.
608
609         // Perform all these manipulations on a temporary file if possible.
610         // If we are not using a temp dir, then temp_file contains the
611         // original file.
612         // to allow files with the same name in different dirs
613         // we manipulate the original file "any.dir/file.ext"
614         // to "any_dir_file.ext"! changing the dots in the
615         // dirname is important for the use of ChangeExtension
616         lyxerr[Debug::GRAPHICS]
617                 << "\tthe orig file is: " << orig_file_with_path << endl;
618
619         if (lyxrc.use_tempdir) {
620                 string const ext_tmp = GetExtension(orig_file_with_path);
621                 // without ext and /
622                 temp_file = subst(
623                         ChangeExtension(orig_file_with_path, string()), "/", "_");
624                 // without dots and again with ext
625                 temp_file = ChangeExtension(
626                         subst(temp_file, ".", "_"), ext_tmp);
627                 // now we have any_dir_file.ext
628                 temp_file = MakeAbsPath(temp_file, buf->tmppath);
629                 lyxerr[Debug::GRAPHICS]
630                         << "\tchanged to: " << temp_file << endl;
631
632                 // if the file doen't exists, copy it into the tempdir
633                 if (file_has_changed || !IsFileReadable(temp_file)) {
634                         bool const success = lyx::copy(orig_file_with_path, temp_file);
635                         lyxerr[Debug::GRAPHICS]
636                                 << "\tcopying from " << orig_file_with_path << " to "
637                                 << temp_file
638                                 << (success ? " succeeded\n" : " failed\n");
639                         if (!success) {
640                                 Alert::alert(_("Cannot copy file"), orig_file_with_path,
641                                         _("into tempdir"));
642                                 return orig_file;
643                         }
644                 }
645
646                 if (from == to)
647                         // No conversion is needed. LaTeX can handle the
648                         // graphic file as is.
649                         return RemoveExtension(temp_file);
650         }
651
652         string const outfile_base = RemoveExtension(temp_file);
653         lyxerr[Debug::GRAPHICS]
654                 << "\tThe original file is " << orig_file << "\n"
655                 << "\tA copy has been made and convert is to be called with:\n"
656                 << "\tfile to convert = " << temp_file << '\n'
657                 << "\toutfile_base = " << outfile_base << '\n'
658                 << "\t from " << from << " to " << to << '\n';
659
660         // if no special converter defined, than we take the default one
661         // from ImageMagic: convert from:inname.from to:outname.to
662         if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
663                 string const command =
664                         LibFileSearch("scripts", "convertDefault.sh") +
665                                 ' ' + from + ':' + temp_file + ' ' +
666                                 to + ':' + outfile_base + '.' + to;
667                 lyxerr[Debug::GRAPHICS]
668                         << "No converter defined! I use convertDefault.sh:\n\t"
669                         << command << endl;
670                 Systemcall one;
671                 one.startscript(Systemcall::Wait, command);
672                 if (!IsFileReadable(ChangeExtension(outfile_base, to)))
673                         Alert::alert(_("Cannot convert Image (not existing file?)"),
674                                 _("No information for converting from ")
675                                 + from + _(" to ") + to);
676         }
677
678         return RemoveExtension(temp_file);
679 }
680
681
682 int InsetGraphics::latex(Buffer const *buf, ostream & os,
683                          bool /*fragile*/, bool/*fs*/) const
684 {
685         // If there is no file specified or not existing,
686         // just output a message about it in the latex output.
687         lyxerr[Debug::GRAPHICS]
688                 << "insetgraphics::latex: Filename = "
689                 << params().filename << endl;
690
691         // A missing (e)ps-extension is no problem for LaTeX, so
692         // we have to test three different cases
693         string const file_(MakeAbsPath(params().filename, buf->filePath()));
694         bool const file_exists =
695                 !file_.empty() &&
696                 (IsFileReadable(file_) ||               // original
697                  IsFileReadable(file_ + ".eps") ||      // original.eps
698                  IsFileReadable(file_ + ".ps"));        // original.ps
699         string const message = file_exists ?
700                 string() : string("bb = 0 0 200 100, draft, type=eps");
701         // if !message.empty() than there was no existing file
702         // "filename(.(e)ps)" found. In this case LaTeX
703         // draws only a rectangle with the above bb and the
704         // not found filename in it.
705         lyxerr[Debug::GRAPHICS]
706                 << "\tMessage = \"" << message << '\"' << endl;
707
708         // These variables collect all the latex code that should be before and
709         // after the actual includegraphics command.
710         string before;
711         string after;
712         // Do we want subcaptions?
713         if (params().subcaption) {
714                 before += "\\subfigure[" + params().subcaptionText + "]{";
715                 after = '}';
716         }
717         // We never use the starred form, we use the "clip" option instead.
718         before += "\\includegraphics";
719
720         // Write the options if there are any.
721         string const opts = createLatexOptions();
722         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
723
724         if (!opts.empty() && !message.empty())
725                 before += ("[%\n" + opts + ',' + message + ']');
726         else if (!opts.empty() || !message.empty())
727                 before += ("[%\n" + opts + message + ']');
728
729         lyxerr[Debug::GRAPHICS]
730                 << "\tBefore = " << before
731                 << "\n\tafter = " << after << endl;
732
733
734         // "nice" means that the buffer is exported to LaTeX format but not
735         //        run through the LaTeX compiler.
736         if (buf->niceFile) {
737                 os << before <<'{' << params().filename << '}' << after;
738                 return 1;
739         }
740
741         // Make the filename relative to the lyx file
742         // and remove the extension so the LaTeX will use whatever is
743         // appropriate (when there are several versions in different formats)
744         string const latex_str = message.empty() ?
745                 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
746                 (before + '{' + params().filename + " not found!}" + after);
747         os << latex_str;
748
749         // Return how many newlines we issued.
750         int const newlines =
751                 int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
752
753         return newlines;
754 }
755
756
757 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
758 {
759         // No graphics in ascii output. Possible to use gifscii to convert
760         // images to ascii approximation.
761         // 1. Convert file to ascii using gifscii
762         // 2. Read ascii output file and add it to the output stream.
763         // at least we send the filename
764         os << '<' << _("Graphic file:") << params().filename << ">\n";
765         return 0;
766 }
767
768
769 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
770 {
771         // No graphics in LinuxDoc output. Should check how/what to add.
772         return 0;
773 }
774
775
776 // For explanation on inserting graphics into DocBook checkout:
777 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
778 // See also the docbook guide at http://www.docbook.org/
779 int InsetGraphics::docbook(Buffer const *, ostream & os,
780                            bool /*mixcont*/) const
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=\"&" << graphic_label << ";\">";
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.includeFile(graphic_label, RemoveExtension(params().filename));
797
798         features.require("graphicx");
799
800         if (params().subcaption)
801                 features.require("subfigure");
802 }
803
804
805 void InsetGraphics::statusChanged()
806 {
807         if (cache_->view.get())
808                 cache_->view.get()->updateInset(this, false);
809 }
810
811
812 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
813                               string const & filepath)
814 {
815         // If nothing is changed, just return and say so.
816         if (params() == p && !p.filename.empty()) {
817                 return false;
818         }
819
820         // Copy the new parameters.
821         params_ = p;
822
823         // Update the inset with the new parameters.
824         cache_->update(MakeAbsPath(params().filename, filepath));
825
826         // We have changed data, report it.
827         return true;
828 }
829
830
831 InsetGraphicsParams const & InsetGraphics::params() const
832 {
833         return params_;
834 }
835
836
837 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
838 {
839         return new InsetGraphics(*this, buffer.filePath(), same_id);
840 }