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