]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
b250a80fc1bf93ec23653369a5019b7bf257f9e9
[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 "Lsstream.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(path));
186 }
187
188
189 InsetGraphics::InsetGraphics()
190         : graphic_label(uniqueID()),
191           cache_(new Cache(*this))
192 {}
193
194
195 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
196                              string const & filepath)
197         : Inset(ig),
198           graphic_label(uniqueID()),
199           cache_(new Cache(*this))
200 {
201         setParams(ig.params(), filepath);
202 }
203
204
205 Inset * InsetGraphics::clone(Buffer const & buffer) const
206 {
207         return new InsetGraphics(*this, buffer.filePath());
208 }
209
210
211 InsetGraphics::~InsetGraphics()
212 {
213         InsetGraphicsMailer mailer(*this);
214         mailer.hideDialog();
215 }
216
217
218 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
219 {
220         switch (cmd.action) {
221         case LFUN_INSET_MODIFY: {
222                 InsetGraphicsParams p;
223                 InsetGraphicsMailer::string2params(cmd.argument, p);
224                 if (!p.filename.empty()) {
225                         string const filepath = cmd.view()->buffer()->filePath();
226                         setParams(p, filepath);
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::dimension(BufferView *, LyXFont const & font,
289         Dimension & dim) const
290 {
291         cache_->old_ascent = 50;
292         if (imageIsDrawable())
293                 cache_->old_ascent = cache_->loader.image()->getHeight();
294         dim.asc = cache_->old_ascent;
295         dim.des = 0;
296         if (imageIsDrawable())
297                 dim.wid = cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
298         else {
299                 int font_width = 0;
300
301                 LyXFont msgFont(font);
302                 msgFont.setFamily(LyXFont::SANS_FAMILY);
303
304                 string const justname = OnlyFilename(params().filename);
305                 if (!justname.empty()) {
306                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
307                         font_width = font_metrics::width(justname, msgFont);
308                 }
309
310                 string const msg = statusMessage();
311                 if (!msg.empty()) {
312                         msgFont.setSize(LyXFont::SIZE_TINY);
313                         font_width = std::max(font_width, font_metrics::width(msg, msgFont));
314                 }
315
316                 dim.wid = std::max(50, font_width + 15);
317         }
318 }
319
320
321 BufferView * InsetGraphics::view() const
322 {
323         return cache_->view.lock().get();
324 }
325
326
327 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
328                          int baseline, float & x) const
329 {
330         // MakeAbsPath returns params().filename unchanged if it absolute
331         // already.
332         string const file_with_path =
333                 MakeAbsPath(params().filename, bv->buffer()->filePath());
334
335         // A 'paste' operation creates a new inset with the correct filepath,
336         // but then the 'old' inset stored in the 'copy' operation is actually
337         // added to the buffer.
338         // Thus, we should ensure that the filepath is correct.
339         if (file_with_path != cache_->loader.filename())
340                 cache_->update(file_with_path);
341
342         cache_->view = bv->owner()->view();
343         int oasc = cache_->old_ascent;
344
345         int ldescent = descent(bv, font);
346         int lascent  = ascent(bv, font);
347         int lwidth   = width(bv, font);
348
349         // we may have changed while someone other was drawing us so better
350         // to not draw anything as we surely call to redraw ourself soon.
351         // This is not a nice thing to do and should be fixed properly somehow.
352         // But I still don't know the best way to go. So let's do this like this
353         // for now (Jug 20020311)
354         if (lascent != oasc)
355                 return;
356
357         // Make sure now that x is updated upon exit from this routine
358         int old_x = int(x);
359         x += lwidth;
360
361         grfx::Params const & gparams = params().as_grfxParams();
362
363         if (gparams.display != grfx::NoDisplay &&
364                         cache_->loader.status() == grfx::WaitingToLoad)
365                 cache_->loader.startLoading();
366
367         if (!cache_->loader.monitoring())
368                 cache_->loader.startMonitoring();
369
370         // This will draw the graphics. If the graphics has not been loaded yet,
371         // we draw just a rectangle.
372         Painter & paint = bv->painter();
373
374         if (imageIsDrawable()) {
375                 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
376                             lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
377                             *cache_->loader.image());
378
379         } else {
380
381                 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
382                                 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
383
384                 // Print the file name.
385                 LyXFont msgFont(font);
386                 msgFont.setFamily(LyXFont::SANS_FAMILY);
387                 string const justname = OnlyFilename (params().filename);
388                 if (!justname.empty()) {
389                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
390                         paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
391                                    baseline - font_metrics::maxAscent(msgFont) - 4,
392                                    justname, msgFont);
393                 }
394
395                 // Print the message.
396                 string const msg = statusMessage();
397                 if (!msg.empty()) {
398                         msgFont.setSize(LyXFont::SIZE_TINY);
399                         paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
400                 }
401         }
402 }
403
404
405 Inset::EDITABLE InsetGraphics::editable() const
406 {
407         return IS_EDITABLE;
408 }
409
410
411 void InsetGraphics::write(Buffer const *, ostream & os) const
412 {
413         os << "Graphics\n";
414         params().Write(os);
415 }
416
417
418 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
419 {
420         string const token = lex.getString();
421
422         if (token == "Graphics")
423                 readInsetGraphics(lex);
424         else
425                 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
426
427         cache_->update(MakeAbsPath(params().filename, buf->filePath()));
428 }
429
430
431 void InsetGraphics::readInsetGraphics(LyXLex & lex)
432 {
433         bool finished = false;
434
435         while (lex.isOK() && !finished) {
436                 lex.next();
437
438                 string const token = lex.getString();
439                 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
440                                     << std::endl;
441
442                 if (token.empty()) {
443                         continue;
444                 } else if (token == "\\end_inset") {
445                         finished = true;
446                 } else if (token == "FormatVersion") {
447                         lex.next();
448                         int version = lex.getInteger();
449                         if (version > VersionNumber)
450                                 lyxerr
451                                 << "This document was created with a newer Graphics widget"
452                                 ", You should use a newer version of LyX to read this"
453                                 " file."
454                                 << std::endl;
455                         // TODO: Possibly open up a dialog?
456                 }
457                 else {
458                         if (! params_.Read(lex, token))
459                                 lyxerr << "Unknown token, " << token << ", skipping."
460                                         << std::endl;
461                 }
462         }
463 }
464
465
466 string const InsetGraphics::createLatexOptions() const
467 {
468         // Calculate the options part of the command, we must do it to a string
469         // stream since we might have a trailing comma that we would like to remove
470         // before writing it to the output stream.
471         ostringstream options;
472         if (!params().bb.empty())
473             options << "  bb=" << rtrim(params().bb) << ",\n";
474         if (params().draft)
475             options << "  draft,\n";
476         if (params().clip)
477             options << "  clip,\n";
478         if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
479                 if (!lyx::float_equal(params().scale, 100.0, 0.05))
480                         options << "  scale=" << params().scale / 100.0
481                                 << ",\n";
482         } else {
483                 if (!params().width.zero())
484                         options << "  width=" << params().width.asLatexString() << ",\n";
485                 if (!params().height.zero())
486                         options << "  height=" << params().height.asLatexString() << ",\n";
487                 if (params().keepAspectRatio)
488                         options << "  keepaspectratio,\n";
489         }
490
491         // Make sure rotation angle is not very close to zero;
492         // a float can be effectively zero but not exactly zero.
493         if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
494             options << "  angle=" << params().rotateAngle << ",\n";
495             if (!params().rotateOrigin.empty()) {
496                 options << "  origin=" << params().rotateOrigin[0];
497                 if (contains(params().rotateOrigin,"Top"))
498                     options << 't';
499                 else if (contains(params().rotateOrigin,"Bottom"))
500                     options << 'b';
501                 else if (contains(params().rotateOrigin,"Baseline"))
502                     options << 'B';
503                 options << ",\n";
504             }
505         }
506
507         if (!params().special.empty())
508             options << params().special << ",\n";
509
510         string opts = STRCONV(options.str());
511         // delete last ",\n"
512         return opts.substr(0, opts.size() - 2);
513 }
514
515
516 string const InsetGraphics::prepareFile(Buffer const * buf,
517                                         LatexRunParams const & runparams) const
518 {
519         // LaTeX can cope if the graphics file doesn't exist, so just return the
520         // filename.
521         string const orig_file = params().filename;
522         string orig_file_with_path =
523                 MakeAbsPath(orig_file, buf->filePath());
524         lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
525                     << orig_file << "\n\twith path: "
526                     << orig_file_with_path << endl;
527
528         if (!IsFileReadable(orig_file_with_path))
529                 return orig_file;
530
531         bool const zipped = zippedFile(orig_file_with_path);
532
533         // If the file is compressed and we have specified that it
534         // should not be uncompressed, then just return its name and
535         // let LaTeX do the rest!
536         if (zipped && params().noUnzip) {
537                 lyxerr[Debug::GRAPHICS]
538                         << "\tpass zipped file to LaTeX but with full path.\n";
539                 // LaTeX needs an absolue path, otherwise the
540                 // coresponding *.eps.bb file isn't found
541                 return orig_file_with_path;
542         }
543
544         // Ascertain whether the file has changed.
545         unsigned long const new_checksum = cache_->loader.checksum();
546         bool const file_has_changed = cache_->checksum != new_checksum;
547         if (file_has_changed)
548                 cache_->checksum = new_checksum;
549
550         // temp_file will contain the file for LaTeX to act on if, for example,
551         // we move it to a temp dir or uncompress it.
552         string temp_file = orig_file;
553
554         if (zipped) {
555                 // Uncompress the file if necessary.
556                 // If it has been uncompressed in a previous call to
557                 // prepareFile, do nothing.
558                 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
559                 lyxerr[Debug::GRAPHICS]
560                         << "\ttemp_file: " << temp_file << endl;
561                 if (file_has_changed || !IsFileReadable(temp_file)) {
562                         bool const success = lyx::copy(orig_file_with_path,
563                                                        temp_file);
564                         lyxerr[Debug::GRAPHICS]
565                                 << "\tCopying zipped file from "
566                                 << orig_file_with_path << " to " << temp_file
567                                 << (success ? " succeeded\n" : " failed\n");
568                 } else
569                         lyxerr[Debug::GRAPHICS]
570                                 << "\tzipped file " << temp_file
571                                 << " exists! Maybe no tempdir ...\n";
572                 orig_file_with_path = unzipFile(temp_file);
573                 lyxerr[Debug::GRAPHICS]
574                         << "\tunzipped to " << orig_file_with_path << endl;
575         }
576
577         string const from = getExtFromContents(orig_file_with_path);
578         string const to   = findTargetFormat(from, runparams);
579         lyxerr[Debug::GRAPHICS]
580                 << "\t we have: from " << from << " to " << to << '\n';
581
582         if (from == to && !lyxrc.use_tempdir) {
583                 // No conversion is needed. LaTeX can handle the
584                 // graphic file as is.
585                 // This is true even if the orig_file is compressed.
586                 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
587                         return RemoveExtension(orig_file_with_path);
588                 return orig_file_with_path;
589         }
590
591         // We're going to be running the exported buffer through the LaTeX
592         // compiler, so must ensure that LaTeX can cope with the graphics
593         // file format.
594
595         // Perform all these manipulations on a temporary file if possible.
596         // If we are not using a temp dir, then temp_file contains the
597         // original file.
598         // to allow files with the same name in different dirs
599         // we manipulate the original file "any.dir/file.ext"
600         // to "any_dir_file.ext"! changing the dots in the
601         // dirname is important for the use of ChangeExtension
602         lyxerr[Debug::GRAPHICS]
603                 << "\tthe orig file is: " << orig_file_with_path << endl;
604
605         if (lyxrc.use_tempdir) {
606                 string const ext_tmp = GetExtension(orig_file_with_path);
607                 // without ext and /
608                 temp_file = subst(
609                         ChangeExtension(orig_file_with_path, string()), "/", "_");
610                 // without dots and again with ext
611                 temp_file = ChangeExtension(
612                         subst(temp_file, ".", "_"), ext_tmp);
613                 // now we have any_dir_file.ext
614                 temp_file = MakeAbsPath(temp_file, buf->tmppath);
615                 lyxerr[Debug::GRAPHICS]
616                         << "\tchanged to: " << temp_file << endl;
617
618                 // if the file doen't exists, copy it into the tempdir
619                 if (file_has_changed || !IsFileReadable(temp_file)) {
620                         bool const success = lyx::copy(orig_file_with_path, temp_file);
621                         lyxerr[Debug::GRAPHICS]
622                                 << "\tcopying from " << orig_file_with_path << " to "
623                                 << temp_file
624                                 << (success ? " succeeded\n" : " failed\n");
625                         if (!success) {
626                                 string str = bformat(_("Could not copy the file\n%1$s\n"
627                                         "into the temporary directory."), orig_file_with_path);
628                                 Alert::error(_("Graphics display failed"), str);
629                                 return orig_file;
630                         }
631                 }
632
633                 if (from == to) {
634                         // No conversion is needed. LaTeX can handle the
635                         // graphic file as is.
636                         if (formats.getFormat(to)->extension() == GetExtension(orig_file))
637                                 return RemoveExtension(temp_file);
638                         return temp_file;
639                 }
640         }
641
642         string const outfile_base = RemoveExtension(temp_file);
643         lyxerr[Debug::GRAPHICS]
644                 << "\tThe original file is " << orig_file << "\n"
645                 << "\tA copy has been made and convert is to be called with:\n"
646                 << "\tfile to convert = " << temp_file << '\n'
647                 << "\toutfile_base = " << outfile_base << '\n'
648                 << "\t from " << from << " to " << to << '\n';
649
650         // if no special converter defined, than we take the default one
651         // from ImageMagic: convert from:inname.from to:outname.to
652         if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
653                 string const command =
654                         LibFileSearch("scripts", "convertDefault.sh") +
655                                 ' ' + from + ':' + temp_file + ' ' +
656                                 to + ':' + outfile_base + '.' + to;
657                 lyxerr[Debug::GRAPHICS]
658                         << "No converter defined! I use convertDefault.sh:\n\t"
659                         << command << endl;
660                 Systemcall one;
661                 one.startscript(Systemcall::Wait, command);
662                 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
663                         string str = bformat(_("No information for converting %1$s "
664                                 "format files to %2$s.\n"
665                                 "Try defining a convertor in the preferences."), from, to);
666                         Alert::error(_("Could not convert image"), str);
667                 }
668         }
669
670         return RemoveExtension(temp_file);
671 }
672
673
674 int InsetGraphics::latex(Buffer const * buf, ostream & os,
675                          LatexRunParams const & runparams) const
676 {
677         // If there is no file specified or not existing,
678         // just output a message about it in the latex output.
679         lyxerr[Debug::GRAPHICS]
680                 << "insetgraphics::latex: Filename = "
681                 << params().filename << endl;
682
683         // A missing (e)ps-extension is no problem for LaTeX, so
684         // we have to test three different cases
685         string const file_ = MakeAbsPath(params().filename, buf->filePath());
686         bool const file_exists =
687                 !file_.empty() &&
688                 (IsFileReadable(file_) ||               // original
689                  IsFileReadable(file_ + ".eps") ||      // original.eps
690                  IsFileReadable(file_ + ".ps"));        // original.ps
691         string const message = file_exists ?
692                 string() : string("bb = 0 0 200 100, draft, type=eps");
693         // if !message.empty() than there was no existing file
694         // "filename(.(e)ps)" found. In this case LaTeX
695         // draws only a rectangle with the above bb and the
696         // not found filename in it.
697         lyxerr[Debug::GRAPHICS]
698                 << "\tMessage = \"" << message << '\"' << endl;
699
700         // These variables collect all the latex code that should be before and
701         // after the actual includegraphics command.
702         string before;
703         string after;
704         // Do we want subcaptions?
705         if (params().subcaption) {
706                 before += "\\subfigure[" + params().subcaptionText + "]{";
707                 after = '}';
708         }
709         // We never use the starred form, we use the "clip" option instead.
710         before += "\\includegraphics";
711
712         // Write the options if there are any.
713         string const opts = createLatexOptions();
714         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
715
716         if (!opts.empty() && !message.empty())
717                 before += ("[%\n" + opts + ',' + message + ']');
718         else if (!opts.empty() || !message.empty())
719                 before += ("[%\n" + opts + message + ']');
720
721         lyxerr[Debug::GRAPHICS]
722                 << "\tBefore = " << before
723                 << "\n\tafter = " << after << endl;
724
725
726         // "nice" means that the buffer is exported to LaTeX format but not
727         //        run through the LaTeX compiler.
728         if (runparams.nice) {
729                 os << before <<'{' << params().filename << '}' << after;
730                 return 1;
731         }
732
733         // Make the filename relative to the lyx file
734         // and remove the extension so the LaTeX will use whatever is
735         // appropriate (when there are several versions in different formats)
736         string const latex_str = message.empty() ?
737                 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
738                 (before + '{' + params().filename + " not found!}" + after);
739         os << latex_str;
740
741         // Return how many newlines we issued.
742         return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
743 }
744
745
746 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
747 {
748         // No graphics in ascii output. Possible to use gifscii to convert
749         // images to ascii approximation.
750         // 1. Convert file to ascii using gifscii
751         // 2. Read ascii output file and add it to the output stream.
752         // at least we send the filename
753         os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
754         return 0;
755 }
756
757
758 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
759 {
760         // No graphics in LinuxDoc output. Should check how/what to add.
761         return 0;
762 }
763
764
765 // For explanation on inserting graphics into DocBook checkout:
766 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
767 // See also the docbook guide at http://www.docbook.org/
768 int InsetGraphics::docbook(Buffer const *, ostream & os,
769                            bool /*mixcont*/) const
770 {
771         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
772         // need to switch to MediaObject. However, for now this is sufficient and
773         // easier to use.
774         os << "<graphic fileref=\"&" << graphic_label << ";\">";
775         return 0;
776 }
777
778
779 void InsetGraphics::validate(LaTeXFeatures & features) const
780 {
781         // If we have no image, we should not require anything.
782         if (params().filename.empty())
783                 return;
784
785         features.includeFile(graphic_label, RemoveExtension(params().filename));
786
787         features.require("graphicx");
788
789         if (params().subcaption)
790                 features.require("subfigure");
791 }
792
793
794 void InsetGraphics::statusChanged()
795 {
796         if (!cache_->view.expired())
797                 cache_->view.lock()->updateInset(this);
798 }
799
800
801 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
802                               string const & filepath)
803 {
804         // If nothing is changed, just return and say so.
805         if (params() == p && !p.filename.empty())
806                 return false;
807
808         // Copy the new parameters.
809         params_ = p;
810
811         // Update the inset with the new parameters.
812         cache_->update(MakeAbsPath(params().filename, filepath));
813
814         // We have changed data, report it.
815         return true;
816 }
817
818
819 InsetGraphicsParams const & InsetGraphics::params() const
820 {
821         return params_;
822 }
823
824
825 string const InsetGraphicsMailer::name_("graphics");
826
827 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
828         : inset_(inset)
829 {}
830
831
832 string const InsetGraphicsMailer::inset2string() const
833 {
834         return params2string(inset_.params());
835 }
836
837
838 void InsetGraphicsMailer::string2params(string const & in,
839                                         InsetGraphicsParams & params)
840 {
841         params = InsetGraphicsParams();
842
843         if (in.empty())
844                 return;
845
846         istringstream data(STRCONV(in));
847         LyXLex lex(0,0);
848         lex.setStream(data);
849
850         if (lex.isOK()) {
851                 lex.next();
852                 string const token = lex.getString();
853                 if (token != name_)
854                         return;
855         }
856
857         if (lex.isOK()) {
858                 InsetGraphics inset;
859                 inset.readInsetGraphics(lex);
860                 params = inset.params();
861         }
862 }
863
864
865 string const
866 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
867 {
868         ostringstream data;
869         data << name_ << ' ';
870         params.Write(data);
871         data << "\\end_inset\n";
872         return STRCONV(data.str());
873 }