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