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