]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
5a5f25ffc83fa8bf8af737db0da0ae5f67ff6753
[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 "Lsstream.h"
73 #include "lyxlex.h"
74 #include "lyxrc.h"
75 #include "Lsstream.h"
76
77 #include "frontends/lyx_gui.h"
78 #include "frontends/Alert.h"
79 #include "frontends/Dialogs.h"
80 #include "frontends/font_metrics.h"
81 #include "frontends/LyXView.h"
82 #include "frontends/Painter.h"
83
84 #include "support/LAssert.h"
85 #include "support/filetools.h"
86 #include "support/lyxalgo.h" // lyx::count
87 #include "support/lyxlib.h" // float_equal
88 #include "support/path.h"
89 #include "support/tostr.h"
90 #include "support/systemcall.h"
91 #include "support/os.h"
92 #include "support/lstrings.h"
93
94 #include <boost/weak_ptr.hpp>
95 #include <boost/bind.hpp>
96 #include <boost/signals/trackable.hpp>
97
98 #include <algorithm> // For the std::max
99
100 extern string system_tempdir;
101 // set by Exporters
102 extern bool pdf_mode;
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)
131 {
132         // pdf_mode means:
133         // Are we creating a PDF or a PS file?
134         // (Should actually mean, are we using latex or pdflatex).
135         if (pdf_mode) {
136                 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
137                 if (contains(suffix, "ps") || suffix == "pdf")
138                         return "pdf";
139                 if (suffix == "jpg")    // pdflatex can use jpeg
140                         return suffix;
141                 return "png";         // and also png
142         }
143         // If it's postscript, we always do eps.
144         lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
145         if (suffix != "ps")     // any other than ps
146                 return "eps";         // is changed to eps
147         return suffix;          // let ps untouched
148 }
149
150 } // namespace anon
151
152
153 struct InsetGraphics::Cache : boost::signals::trackable
154 {
155         ///
156         Cache(InsetGraphics &);
157         ///
158         void update(string const & file_with_path);
159
160         ///
161         int old_ascent;
162         ///
163         grfx::Loader loader;
164         ///
165         unsigned long checksum;
166         ///
167         boost::weak_ptr<BufferView> view;
168
169 private:
170         ///
171         InsetGraphics & parent_;
172 };
173
174
175 InsetGraphics::Cache::Cache(InsetGraphics & p)
176         : old_ascent(0), checksum(0), parent_(p)
177 {
178         loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
179 }
180
181
182 void InsetGraphics::Cache::update(string const & file_with_path)
183 {
184         lyx::Assert(!file_with_path.empty());
185
186         string const path = OnlyPath(file_with_path);
187         loader.reset(file_with_path, parent_.params().as_grfxParams(path));
188 }
189
190
191 InsetGraphics::InsetGraphics()
192         : graphic_label(uniqueID()),
193           cache_(new Cache(*this))
194 {}
195
196
197 InsetGraphics::InsetGraphics(InsetGraphics const & ig,
198                              string const & filepath,
199                              bool same_id)
200         : Inset(ig, same_id),
201           graphic_label(uniqueID()),
202           cache_(new Cache(*this))
203 {
204         setParams(ig.params(), filepath);
205 }
206
207
208 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
209 {
210         return new InsetGraphics(*this, buffer.filePath(), same_id);
211 }
212
213
214 InsetGraphics::~InsetGraphics()
215 {
216         InsetGraphicsMailer mailer(*this);
217         mailer.hideDialog();
218 }
219
220
221 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
222 {
223         switch (cmd.action) {
224         case LFUN_INSET_MODIFY: {
225                 InsetGraphicsParams p;
226                 InsetGraphicsMailer::string2params(cmd.argument, p);
227                 if (!p.filename.empty()) {
228                         string const filepath = cmd.view()->buffer()->filePath();
229                         setParams(p, filepath);
230                         cmd.view()->updateInset(this);
231                 }
232                 return DISPATCHED;
233         }
234
235         case LFUN_INSET_DIALOG_UPDATE: 
236                 InsetGraphicsMailer(*this).updateDialog(cmd.view());
237                 return DISPATCHED;
238
239         case LFUN_INSET_EDIT:
240         case LFUN_MOUSE_RELEASE:
241                 InsetGraphicsMailer(*this).showDialog(cmd.view());
242                 return DISPATCHED;
243
244         default:
245                 return Inset::localDispatch(cmd);
246         }
247 }
248
249
250 string const InsetGraphics::statusMessage() const
251 {
252         using namespace grfx;
253
254         switch (cache_->loader.status()) {
255                 case WaitingToLoad:
256                         return _("Not shown.");
257                 case Loading:
258                         return _("Loading...");
259                 case Converting:
260                         return _("Converting to loadable format...");
261                 case Loaded:
262                         return _("Loaded into memory. Must now generate pixmap.");
263                 case ScalingEtc:
264                         return _("Scaling etc...");
265                 case Ready:
266                         return _("Ready to display");
267                 case ErrorNoFile:
268                         return _("No file found!");
269                 case ErrorConverting:
270                         return _("Error converting to loadable format");
271                 case ErrorLoading:
272                         return _("Error loading file into memory");
273                 case ErrorGeneratingPixmap:
274                         return _("Error generating the pixmap");
275                 case ErrorUnknown:
276                         return _("No image");
277         }
278         return string();
279 }
280
281
282 bool InsetGraphics::imageIsDrawable() const
283 {
284         if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
285                 return false;
286
287         return cache_->loader.image()->isDrawable();
288 }
289
290
291 void InsetGraphics::dimension(BufferView *, LyXFont const & font,
292         Dimension & dim) const
293 {
294         cache_->old_ascent = 50;
295         if (imageIsDrawable())
296                 cache_->old_ascent = cache_->loader.image()->getHeight();
297         dim.a = cache_->old_ascent;
298         dim.d = 0;
299         if (imageIsDrawable())
300                 dim.w = cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
301         else {
302                 int font_width = 0;
303
304                 LyXFont msgFont(font);
305                 msgFont.setFamily(LyXFont::SANS_FAMILY);
306
307                 string const justname = OnlyFilename(params().filename);
308                 if (!justname.empty()) {
309                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
310                         font_width = font_metrics::width(justname, msgFont);
311                 }
312
313                 string const msg = statusMessage();
314                 if (!msg.empty()) {
315                         msgFont.setSize(LyXFont::SIZE_TINY);
316                         font_width = std::max(font_width, font_metrics::width(msg, msgFont));
317                 }
318
319                 dim.w = std::max(50, font_width + 15);
320         }
321 }
322
323
324 BufferView * InsetGraphics::view() const
325 {
326         return cache_->view.lock().get();
327 }
328
329
330 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
331                          int baseline, float & x) const
332 {
333         // MakeAbsPath returns params().filename unchanged if it absolute
334         // already.
335         string const file_with_path =
336                 MakeAbsPath(params().filename, bv->buffer()->filePath());
337
338         // A 'paste' operation creates a new inset with the correct filepath,
339         // but then the 'old' inset stored in the 'copy' operation is actually
340         // added to the buffer.
341         // Thus, we should ensure that the filepath is correct.
342         if (file_with_path != cache_->loader.filename())
343                 cache_->update(file_with_path);
344
345         cache_->view = bv->owner()->view();
346         int oasc = cache_->old_ascent;
347
348         int ldescent = descent(bv, font);
349         int lascent  = ascent(bv, font);
350         int lwidth   = width(bv, font);
351
352         // we may have changed while someone other was drawing us so better
353         // to not draw anything as we surely call to redraw ourself soon.
354         // This is not a nice thing to do and should be fixed properly somehow.
355         // But I still don't know the best way to go. So let's do this like this
356         // for now (Jug 20020311)
357         if (lascent != oasc)
358                 return;
359
360         // Make sure now that x is updated upon exit from this routine
361         int old_x = int(x);
362         x += lwidth;
363
364         grfx::Params const & gparams = params().as_grfxParams();
365
366         if (gparams.display != grfx::NoDisplay &&
367                         cache_->loader.status() == grfx::WaitingToLoad)
368                 cache_->loader.startLoading();
369
370         if (!cache_->loader.monitoring())
371                 cache_->loader.startMonitoring();
372
373         // This will draw the graphics. If the graphics has not been loaded yet,
374         // we draw just a rectangle.
375         Painter & paint = bv->painter();
376
377         if (imageIsDrawable()) {
378                 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
379                             lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
380                             *cache_->loader.image());
381
382         } else {
383
384                 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
385                                 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
386
387                 // Print the file name.
388                 LyXFont msgFont(font);
389                 msgFont.setFamily(LyXFont::SANS_FAMILY);
390                 string const justname = OnlyFilename (params().filename);
391                 if (!justname.empty()) {
392                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
393                         paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
394                                    baseline - font_metrics::maxAscent(msgFont) - 4,
395                                    justname, msgFont);
396                 }
397
398                 // Print the message.
399                 string const msg = statusMessage();
400                 if (!msg.empty()) {
401                         msgFont.setSize(LyXFont::SIZE_TINY);
402                         paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
403                 }
404         }
405 }
406
407
408 Inset::EDITABLE InsetGraphics::editable() const
409 {
410         return IS_EDITABLE;
411 }
412
413
414 void InsetGraphics::write(Buffer const *, ostream & os) const
415 {
416         os << "Graphics\n";
417         params().Write(os);
418 }
419
420
421 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
422 {
423         string const token = lex.getString();
424
425         if (token == "Graphics")
426                 readInsetGraphics(lex);
427         else
428                 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
429
430         cache_->update(MakeAbsPath(params().filename, buf->filePath()));
431 }
432
433
434 void InsetGraphics::readInsetGraphics(LyXLex & lex)
435 {
436         bool finished = false;
437
438         while (lex.isOK() && !finished) {
439                 lex.next();
440
441                 string const token = lex.getString();
442                 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
443                                     << std::endl;
444
445                 if (token.empty()) {
446                         continue;
447                 } else if (token == "\\end_inset") {
448                         finished = true;
449                 } else if (token == "FormatVersion") {
450                         lex.next();
451                         int version = lex.getInteger();
452                         if (version > VersionNumber)
453                                 lyxerr
454                                 << "This document was created with a newer Graphics widget"
455                                 ", You should use a newer version of LyX to read this"
456                                 " file."
457                                 << std::endl;
458                         // TODO: Possibly open up a dialog?
459                 }
460                 else {
461                         if (! params_.Read(lex, token))
462                                 lyxerr << "Unknown token, " << token << ", skipping."
463                                         << std::endl;
464                 }
465         }
466 }
467
468
469 string const InsetGraphics::createLatexOptions() const
470 {
471         // Calculate the options part of the command, we must do it to a string
472         // stream since we might have a trailing comma that we would like to remove
473         // before writing it to the output stream.
474         ostringstream options;
475         if (!params().bb.empty())
476             options << "  bb=" << rtrim(params().bb) << ",\n";
477         if (params().draft)
478             options << "  draft,\n";
479         if (params().clip)
480             options << "  clip,\n";
481         if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
482                 if (!lyx::float_equal(params().scale, 100.0, 0.05))
483                         options << "  scale=" << params().scale / 100.0
484                                 << ",\n";
485         } else {
486                 if (!params().width.zero())
487                         options << "  width=" << params().width.asLatexString() << ",\n";
488                 if (!params().height.zero())
489                         options << "  height=" << params().height.asLatexString() << ",\n";
490                 if (params().keepAspectRatio)
491                         options << "  keepaspectratio,\n";
492         }
493
494         // Make sure rotation angle is not very close to zero;
495         // a float can be effectively zero but not exactly zero.
496         if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
497             options << "  angle=" << params().rotateAngle << ",\n";
498             if (!params().rotateOrigin.empty()) {
499                 options << "  origin=" << params().rotateOrigin[0];
500                 if (contains(params().rotateOrigin,"Top"))
501                     options << 't';
502                 else if (contains(params().rotateOrigin,"Bottom"))
503                     options << 'b';
504                 else if (contains(params().rotateOrigin,"Baseline"))
505                     options << 'B';
506                 options << ",\n";
507             }
508         }
509
510         if (!params().special.empty())
511             options << params().special << ",\n";
512
513         string opts = STRCONV(options.str());
514         // delete last ",\n"
515         return opts.substr(0, opts.size() - 2);
516 }
517
518
519 string const InsetGraphics::prepareFile(Buffer const * buf) const
520 {
521         // LaTeX can cope if the graphics file doesn't exist, so just return the
522         // filename.
523         string const orig_file = params().filename;
524         string orig_file_with_path =
525                 MakeAbsPath(orig_file, buf->filePath());
526         lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
527                     << orig_file << "\n\twith path: "
528                     << orig_file_with_path << endl;
529
530         if (!IsFileReadable(orig_file_with_path))
531                 return orig_file;
532
533         bool const zipped = zippedFile(orig_file_with_path);
534
535         // If the file is compressed and we have specified that it
536         // should not be uncompressed, then just return its name and
537         // let LaTeX do the rest!
538         if (zipped && params().noUnzip) {
539                 lyxerr[Debug::GRAPHICS]
540                         << "\tpass zipped file to LaTeX but with full path.\n";
541                 // LaTeX needs an absolue path, otherwise the
542                 // coresponding *.eps.bb file isn't found
543                 return orig_file_with_path;
544         }
545
546         // Ascertain whether the file has changed.
547         unsigned long const new_checksum = cache_->loader.checksum();
548         bool const file_has_changed = cache_->checksum != new_checksum;
549         if (file_has_changed)
550                 cache_->checksum = new_checksum;
551
552         // temp_file will contain the file for LaTeX to act on if, for example,
553         // we move it to a temp dir or uncompress it.
554         string temp_file = orig_file;
555
556         if (zipped) {
557                 // Uncompress the file if necessary.
558                 // If it has been uncompressed in a previous call to
559                 // prepareFile, do nothing.
560                 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
561                 lyxerr[Debug::GRAPHICS]
562                         << "\ttemp_file: " << temp_file << endl;
563                 if (file_has_changed || !IsFileReadable(temp_file)) {
564                         bool const success = lyx::copy(orig_file_with_path,
565                                                        temp_file);
566                         lyxerr[Debug::GRAPHICS]
567                                 << "\tCopying zipped file from "
568                                 << orig_file_with_path << " to " << temp_file
569                                 << (success ? " succeeded\n" : " failed\n");
570                 } else
571                         lyxerr[Debug::GRAPHICS]
572                                 << "\tzipped file " << temp_file
573                                 << " exists! Maybe no tempdir ...\n";
574                 orig_file_with_path = unzipFile(temp_file);
575                 lyxerr[Debug::GRAPHICS]
576                         << "\tunzipped to " << orig_file_with_path << endl;
577         }
578
579         string const from = getExtFromContents(orig_file_with_path);
580         string const to   = findTargetFormat(from);
581         lyxerr[Debug::GRAPHICS]
582                 << "\t we have: from " << from << " to " << to << '\n';
583
584         if (from == to && !lyxrc.use_tempdir) {
585                 // No conversion is needed. LaTeX can handle the
586                 // graphic file as is.
587                 // This is true even if the orig_file is compressed.
588                 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
589                         return RemoveExtension(orig_file_with_path);
590                 return orig_file_with_path;
591         }
592
593         // We're going to be running the exported buffer through the LaTeX
594         // compiler, so must ensure that LaTeX can cope with the graphics
595         // file format.
596
597         // Perform all these manipulations on a temporary file if possible.
598         // If we are not using a temp dir, then temp_file contains the
599         // original file.
600         // to allow files with the same name in different dirs
601         // we manipulate the original file "any.dir/file.ext"
602         // to "any_dir_file.ext"! changing the dots in the
603         // dirname is important for the use of ChangeExtension
604         lyxerr[Debug::GRAPHICS]
605                 << "\tthe orig file is: " << orig_file_with_path << endl;
606
607         if (lyxrc.use_tempdir) {
608                 string const ext_tmp = GetExtension(orig_file_with_path);
609                 // without ext and /
610                 temp_file = subst(
611                         ChangeExtension(orig_file_with_path, string()), "/", "_");
612                 // without dots and again with ext
613                 temp_file = ChangeExtension(
614                         subst(temp_file, ".", "_"), ext_tmp);
615                 // now we have any_dir_file.ext
616                 temp_file = MakeAbsPath(temp_file, buf->tmppath);
617                 lyxerr[Debug::GRAPHICS]
618                         << "\tchanged to: " << temp_file << endl;
619
620                 // if the file doen't exists, copy it into the tempdir
621                 if (file_has_changed || !IsFileReadable(temp_file)) {
622                         bool const success = lyx::copy(orig_file_with_path, temp_file);
623                         lyxerr[Debug::GRAPHICS]
624                                 << "\tcopying from " << orig_file_with_path << " to "
625                                 << temp_file
626                                 << (success ? " succeeded\n" : " failed\n");
627                         if (!success) {
628                                 string str = bformat(_("Could not copy the file\n%1$s\n"
629                                         "into the temporary directory."), orig_file_with_path);
630                                 Alert::error(_("Graphics display failed"), str);
631                                 return orig_file;
632                         }
633                 }
634
635                 if (from == to) {
636                         // No conversion is needed. LaTeX can handle the
637                         // graphic file as is.
638                         if (formats.getFormat(to)->extension() == GetExtension(orig_file))
639                                 return RemoveExtension(temp_file);
640                         return temp_file;
641                 }
642         }
643
644         string const outfile_base = RemoveExtension(temp_file);
645         lyxerr[Debug::GRAPHICS]
646                 << "\tThe original file is " << orig_file << "\n"
647                 << "\tA copy has been made and convert is to be called with:\n"
648                 << "\tfile to convert = " << temp_file << '\n'
649                 << "\toutfile_base = " << outfile_base << '\n'
650                 << "\t from " << from << " to " << to << '\n';
651
652         // if no special converter defined, than we take the default one
653         // from ImageMagic: convert from:inname.from to:outname.to
654         if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
655                 string const command =
656                         LibFileSearch("scripts", "convertDefault.sh") +
657                                 ' ' + from + ':' + temp_file + ' ' +
658                                 to + ':' + outfile_base + '.' + to;
659                 lyxerr[Debug::GRAPHICS]
660                         << "No converter defined! I use convertDefault.sh:\n\t"
661                         << command << endl;
662                 Systemcall one;
663                 one.startscript(Systemcall::Wait, command);
664                 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
665                         string str = bformat(_("No information for converting %1$s "
666                                 "format files to %1$s.\n"
667                                 "Try defining a convertor in the preferences."), from, to);
668                         Alert::error(_("Could not convert image"), str);
669                 }
670         }
671
672         return RemoveExtension(temp_file);
673 }
674
675
676 int InsetGraphics::latex(Buffer const * buf, ostream & os,
677                          bool /*fragile*/, 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 (buf->niceFile) {
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)) + '}' + 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 }