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