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