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