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