]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
86df4442a0eeba444b3be1b22b349da8737e500e
[lyx.git] / src / insets / insetgraphics.C
1 /**
2  * \file insetgraphics.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Baruch Even
7  * \author Herbert Voss
8  *
9  * Full author contact details are available in file CREDITS
10  */
11
12 /*
13 TODO
14
15     * What advanced features the users want to do?
16       Implement them in a non latex dependent way, but a logical way.
17       LyX should translate it to latex or any other fitting format.
18     * Add a way to roll the image file into the file format.
19     * When loading, if the image is not found in the expected place, try
20       to find it in the clipart, or in the same directory with the image.
21     * The image choosing dialog could show thumbnails of the image formats
22       it knows of, thus selection based on the image instead of based on
23       filename.
24     * Add support for the 'picins' package.
25     * Add support for the 'picinpar' package.
26     * Improve support for 'subfigure' - Allow to set the various options
27       that are possible.
28 */
29
30 /* NOTES:
31  * Fileformat:
32  * Current version is 1 (inset file format version), when changing it
33  * it should be changed in the Write() function when writing in one place
34  * and when reading one should change the version check and the error message.
35  * The filename is kept in  the lyx file in a relative way, so as to allow
36  * moving the document file and its images with no problem.
37  *
38  *
39  * Conversions:
40  *   Postscript output means EPS figures.
41  *
42  *   PDF output is best done with PDF figures if it's a direct conversion
43  *   or PNG figures otherwise.
44  *      Image format
45  *      from        to
46  *      EPS         epstopdf
47  *      PS          ps2pdf
48  *      JPG/PNG     direct
49  *      PDF         direct
50  *      others      PNG
51  */
52
53 #include <config.h>
54
55 #include "insets/insetgraphics.h"
56 #include "insets/insetgraphicsParams.h"
57
58 #include "graphics/GraphicsLoader.h"
59 #include "graphics/GraphicsImage.h"
60 #include "graphics/GraphicsParams.h"
61
62 #include "lyxtext.h"
63 #include "dimension.h"
64 #include "buffer.h"
65 #include "BufferView.h"
66 #include "converter.h"
67 #include "debug.h"
68 #include "format.h"
69 #include "funcrequest.h"
70 #include "gettext.h"
71 #include "LaTeXFeatures.h"
72 #include "latexrunparams.h"
73 #include "Lsstream.h"
74 #include "lyxlex.h"
75 #include "lyxrc.h"
76 #include "metricsinfo.h"
77
78 #include "frontends/lyx_gui.h"
79 #include "frontends/Alert.h"
80 #include "frontends/Dialogs.h"
81 #include "frontends/font_metrics.h"
82 #include "frontends/LyXView.h"
83 #include "frontends/Painter.h"
84
85 #include "support/LAssert.h"
86 #include "support/filetools.h"
87 #include "support/lyxalgo.h" // lyx::count
88 #include "support/lyxlib.h" // float_equal
89 #include "support/path.h"
90 #include "support/tostr.h"
91 #include "support/systemcall.h"
92 #include "support/os.h"
93 #include "support/lstrings.h"
94
95 #include <boost/weak_ptr.hpp>
96 #include <boost/bind.hpp>
97 #include <boost/signals/trackable.hpp>
98
99 #include <algorithm> // For the std::max
100
101 extern string system_tempdir;
102 // set by Exporters
103
104 using std::ostream;
105 using std::endl;
106
107
108 namespace {
109
110 ///////////////////////////////////////////////////////////////////////////
111 int const VersionNumber = 1;
112 ///////////////////////////////////////////////////////////////////////////
113
114 // This function is a utility function
115 // ... that should be with ChangeExtension ...
116 inline
117 string const RemoveExtension(string const & filename)
118 {
119         return ChangeExtension(filename, string());
120 }
121
122
123 string const uniqueID()
124 {
125         static unsigned int seed = 1000;
126         return "graph" + tostr(++seed);
127 }
128
129
130 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
131 {
132         // Are we using latex or pdflatex).
133         if (runparams.flavor == LatexRunParams::PDFLATEX) {
134                 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
135                 if (contains(suffix, "ps") || suffix == "pdf")
136                         return "pdf";
137                 if (suffix == "jpg")    // pdflatex can use jpeg
138                         return suffix;
139                 return "png";         // and also png
140         }
141         // If it's postscript, we always do eps.
142         lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
143         if (suffix != "ps")     // any other than ps
144                 return "eps";         // is changed to eps
145         return suffix;          // let ps untouched
146 }
147
148 } // namespace anon
149
150
151 struct InsetGraphics::Cache : boost::signals::trackable
152 {
153         ///
154         Cache(InsetGraphics &);
155         ///
156         void update(string const & file_with_path);
157
158         ///
159         int old_ascent;
160         ///
161         grfx::Loader loader;
162         ///
163         unsigned long checksum;
164         ///
165         boost::weak_ptr<BufferView> view;
166
167 private:
168         ///
169         InsetGraphics & parent_;
170 };
171
172
173 InsetGraphics::Cache::Cache(InsetGraphics & p)
174         : old_ascent(0), checksum(0), parent_(p)
175 {
176         loader.connect(boost::bind(&InsetGraphics::statusChanged, &parent_));
177 }
178
179
180 void InsetGraphics::Cache::update(string const & file_with_path)
181 {
182         lyx::Assert(!file_with_path.empty());
183
184         string const path = OnlyPath(file_with_path);
185         loader.reset(file_with_path, parent_.params().as_grfxParams(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::metrics(MetricsInfo & mi, Dimension & dim) const
289 {
290         cache_->old_ascent = 50;
291         if (imageIsDrawable())
292                 cache_->old_ascent = cache_->loader.image()->getHeight();
293         dim.asc = cache_->old_ascent;
294         dim.des = 0;
295         if (imageIsDrawable())
296                 dim.wid = cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
297         else {
298                 int font_width = 0;
299
300                 LyXFont msgFont(mi.base.font);
301                 msgFont.setFamily(LyXFont::SANS_FAMILY);
302
303                 string const justname = OnlyFilename(params().filename);
304                 if (!justname.empty()) {
305                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
306                         font_width = font_metrics::width(justname, msgFont);
307                 }
308
309                 string const msg = statusMessage();
310                 if (!msg.empty()) {
311                         msgFont.setSize(LyXFont::SIZE_TINY);
312                         font_width = std::max(font_width, font_metrics::width(msg, msgFont));
313                 }
314
315                 dim.wid = std::max(50, font_width + 15);
316         }
317         dim_ = dim;
318 }
319
320
321 BufferView * InsetGraphics::view() const
322 {
323         return cache_->view.lock().get();
324 }
325
326
327 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
328 {
329         BufferView * bv = pi.base.bv;
330         // 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         Dimension dim;
346         MetricsInfo mi;
347         mi.base.bv = pi.base.bv;
348         mi.base.font = pi.base.font;
349         metrics(mi, dim);
350         dim_ = dim;
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 (dim.asc != oasc)
358                 return;
359
360         // Make sure now that x is updated upon exit from this routine
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
373         if (imageIsDrawable()) {
374                 pi.pain.image(x + TEXT_TO_INSET_OFFSET, y - dim_.asc,
375                             dim_.wid - 2 * TEXT_TO_INSET_OFFSET, dim_.asc + dim_.des,
376                             *cache_->loader.image());
377
378         } else {
379
380                 pi.pain.rectangle(x + TEXT_TO_INSET_OFFSET, y - dim_.asc,
381                                 dim_.wid - 2 * TEXT_TO_INSET_OFFSET, dim_.asc + dim_.des);
382
383                 // Print the file name.
384                 LyXFont msgFont = pi.base.font;
385                 msgFont.setFamily(LyXFont::SANS_FAMILY);
386                 string const justname = OnlyFilename (params().filename);
387                 if (!justname.empty()) {
388                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
389                         pi.pain.text(x + TEXT_TO_INSET_OFFSET + 6,
390                                    y - font_metrics::maxAscent(msgFont) - 4,
391                                    justname, msgFont);
392                 }
393
394                 // Print the message.
395                 string const msg = statusMessage();
396                 if (!msg.empty()) {
397                         msgFont.setSize(LyXFont::SIZE_TINY);
398                         pi.pain.text(x + TEXT_TO_INSET_OFFSET + 6, y - 4, msg, msgFont);
399                 }
400         }
401 }
402
403
404 Inset::EDITABLE InsetGraphics::editable() const
405 {
406         return IS_EDITABLE;
407 }
408
409
410 void InsetGraphics::write(Buffer const *, ostream & os) const
411 {
412         os << "Graphics\n";
413         params().Write(os);
414 }
415
416
417 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
418 {
419         string const token = lex.getString();
420
421         if (token == "Graphics")
422                 readInsetGraphics(lex);
423         else
424                 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
425
426         cache_->update(MakeAbsPath(params().filename, buf->filePath()));
427 }
428
429
430 void InsetGraphics::readInsetGraphics(LyXLex & lex)
431 {
432         bool finished = false;
433
434         while (lex.isOK() && !finished) {
435                 lex.next();
436
437                 string const token = lex.getString();
438                 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
439                                     << std::endl;
440
441                 if (token.empty()) {
442                         continue;
443                 } else if (token == "\\end_inset") {
444                         finished = true;
445                 } else if (token == "FormatVersion") {
446                         lex.next();
447                         int version = lex.getInteger();
448                         if (version > VersionNumber)
449                                 lyxerr
450                                 << "This document was created with a newer Graphics widget"
451                                 ", You should use a newer version of LyX to read this"
452                                 " file."
453                                 << std::endl;
454                         // TODO: Possibly open up a dialog?
455                 }
456                 else {
457                         if (! params_.Read(lex, token))
458                                 lyxerr << "Unknown token, " << token << ", skipping."
459                                         << std::endl;
460                 }
461         }
462 }
463
464
465 string const InsetGraphics::createLatexOptions() const
466 {
467         // Calculate the options part of the command, we must do it to a string
468         // stream since we might have a trailing comma that we would like to remove
469         // before writing it to the output stream.
470         ostringstream options;
471         if (!params().bb.empty())
472             options << "  bb=" << rtrim(params().bb) << ",\n";
473         if (params().draft)
474             options << "  draft,\n";
475         if (params().clip)
476             options << "  clip,\n";
477         if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
478                 if (!lyx::float_equal(params().scale, 100.0, 0.05))
479                         options << "  scale=" << params().scale / 100.0
480                                 << ",\n";
481         } else {
482                 if (!params().width.zero())
483                         options << "  width=" << params().width.asLatexString() << ",\n";
484                 if (!params().height.zero())
485                         options << "  height=" << params().height.asLatexString() << ",\n";
486                 if (params().keepAspectRatio)
487                         options << "  keepaspectratio,\n";
488         }
489
490         // Make sure rotation angle is not very close to zero;
491         // a float can be effectively zero but not exactly zero.
492         if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
493             options << "  angle=" << params().rotateAngle << ",\n";
494             if (!params().rotateOrigin.empty()) {
495                 options << "  origin=" << params().rotateOrigin[0];
496                 if (contains(params().rotateOrigin,"Top"))
497                     options << 't';
498                 else if (contains(params().rotateOrigin,"Bottom"))
499                     options << 'b';
500                 else if (contains(params().rotateOrigin,"Baseline"))
501                     options << 'B';
502                 options << ",\n";
503             }
504         }
505
506         if (!params().special.empty())
507             options << params().special << ",\n";
508
509         string opts = STRCONV(options.str());
510         // delete last ",\n"
511         return opts.substr(0, opts.size() - 2);
512 }
513
514
515 string const InsetGraphics::prepareFile(Buffer const * buf,
516                                         LatexRunParams const & runparams) const
517 {
518         // LaTeX can cope if the graphics file doesn't exist, so just return the
519         // filename.
520         string const orig_file = params().filename;
521         string orig_file_with_path =
522                 MakeAbsPath(orig_file, buf->filePath());
523         lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
524                     << orig_file << "\n\twith path: "
525                     << orig_file_with_path << endl;
526
527         if (!IsFileReadable(orig_file_with_path))
528                 return orig_file;
529
530         bool const zipped = zippedFile(orig_file_with_path);
531
532         // If the file is compressed and we have specified that it
533         // should not be uncompressed, then just return its name and
534         // let LaTeX do the rest!
535         if (zipped && params().noUnzip) {
536                 lyxerr[Debug::GRAPHICS]
537                         << "\tpass zipped file to LaTeX but with full path.\n";
538                 // LaTeX needs an absolue path, otherwise the
539                 // coresponding *.eps.bb file isn't found
540                 return orig_file_with_path;
541         }
542
543         // Ascertain whether the file has changed.
544         unsigned long const new_checksum = cache_->loader.checksum();
545         bool const file_has_changed = cache_->checksum != new_checksum;
546         if (file_has_changed)
547                 cache_->checksum = new_checksum;
548
549         // temp_file will contain the file for LaTeX to act on if, for example,
550         // we move it to a temp dir or uncompress it.
551         string temp_file = orig_file;
552
553         if (zipped) {
554                 // Uncompress the file if necessary.
555                 // If it has been uncompressed in a previous call to
556                 // prepareFile, do nothing.
557                 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
558                 lyxerr[Debug::GRAPHICS]
559                         << "\ttemp_file: " << temp_file << endl;
560                 if (file_has_changed || !IsFileReadable(temp_file)) {
561                         bool const success = lyx::copy(orig_file_with_path,
562                                                        temp_file);
563                         lyxerr[Debug::GRAPHICS]
564                                 << "\tCopying zipped file from "
565                                 << orig_file_with_path << " to " << temp_file
566                                 << (success ? " succeeded\n" : " failed\n");
567                 } else
568                         lyxerr[Debug::GRAPHICS]
569                                 << "\tzipped file " << temp_file
570                                 << " exists! Maybe no tempdir ...\n";
571                 orig_file_with_path = unzipFile(temp_file);
572                 lyxerr[Debug::GRAPHICS]
573                         << "\tunzipped to " << orig_file_with_path << endl;
574         }
575
576         string const from = getExtFromContents(orig_file_with_path);
577         string const to   = findTargetFormat(from, runparams);
578         lyxerr[Debug::GRAPHICS]
579                 << "\t we have: from " << from << " to " << to << '\n';
580
581         if (from == to && !lyxrc.use_tempdir) {
582                 // No conversion is needed. LaTeX can handle the
583                 // graphic file as is.
584                 // This is true even if the orig_file is compressed.
585                 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
586                         return RemoveExtension(orig_file_with_path);
587                 return orig_file_with_path;
588         }
589
590         // We're going to be running the exported buffer through the LaTeX
591         // compiler, so must ensure that LaTeX can cope with the graphics
592         // file format.
593
594         // Perform all these manipulations on a temporary file if possible.
595         // If we are not using a temp dir, then temp_file contains the
596         // original file.
597         // to allow files with the same name in different dirs
598         // we manipulate the original file "any.dir/file.ext"
599         // to "any_dir_file.ext"! changing the dots in the
600         // dirname is important for the use of ChangeExtension
601         lyxerr[Debug::GRAPHICS]
602                 << "\tthe orig file is: " << orig_file_with_path << endl;
603
604         if (lyxrc.use_tempdir) {
605                 string const ext_tmp = GetExtension(orig_file_with_path);
606                 // without ext and /
607                 temp_file = subst(
608                         ChangeExtension(orig_file_with_path, string()), "/", "_");
609                 // without dots and again with ext
610                 temp_file = ChangeExtension(
611                         subst(temp_file, ".", "_"), ext_tmp);
612                 // now we have any_dir_file.ext
613                 temp_file = MakeAbsPath(temp_file, buf->tmppath);
614                 lyxerr[Debug::GRAPHICS]
615                         << "\tchanged to: " << temp_file << endl;
616
617                 // if the file doen't exists, copy it into the tempdir
618                 if (file_has_changed || !IsFileReadable(temp_file)) {
619                         bool const success = lyx::copy(orig_file_with_path, temp_file);
620                         lyxerr[Debug::GRAPHICS]
621                                 << "\tcopying from " << orig_file_with_path << " to "
622                                 << temp_file
623                                 << (success ? " succeeded\n" : " failed\n");
624                         if (!success) {
625                                 string str = bformat(_("Could not copy the file\n%1$s\n"
626                                         "into the temporary directory."), orig_file_with_path);
627                                 Alert::error(_("Graphics display failed"), str);
628                                 return orig_file;
629                         }
630                 }
631
632                 if (from == to) {
633                         // No conversion is needed. LaTeX can handle the
634                         // graphic file as is.
635                         if (formats.getFormat(to)->extension() == GetExtension(orig_file))
636                                 return RemoveExtension(temp_file);
637                         return temp_file;
638                 }
639         }
640
641         string const outfile_base = RemoveExtension(temp_file);
642         lyxerr[Debug::GRAPHICS]
643                 << "\tThe original file is " << orig_file << "\n"
644                 << "\tA copy has been made and convert is to be called with:\n"
645                 << "\tfile to convert = " << temp_file << '\n'
646                 << "\toutfile_base = " << outfile_base << '\n'
647                 << "\t from " << from << " to " << to << '\n';
648
649         // if no special converter defined, than we take the default one
650         // from ImageMagic: convert from:inname.from to:outname.to
651         if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
652                 string const command =
653                         LibFileSearch("scripts", "convertDefault.sh") +
654                                 ' ' + from + ':' + temp_file + ' ' +
655                                 to + ':' + outfile_base + '.' + to;
656                 lyxerr[Debug::GRAPHICS]
657                         << "No converter defined! I use convertDefault.sh:\n\t"
658                         << command << endl;
659                 Systemcall one;
660                 one.startscript(Systemcall::Wait, command);
661                 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
662                         string str = bformat(_("No information for converting %1$s "
663                                 "format files to %2$s.\n"
664                                 "Try defining a convertor in the preferences."), from, to);
665                         Alert::error(_("Could not convert image"), str);
666                 }
667         }
668
669         return RemoveExtension(temp_file);
670 }
671
672
673 int InsetGraphics::latex(Buffer const * buf, ostream & os,
674                          LatexRunParams const & runparams) const
675 {
676         // If there is no file specified or not existing,
677         // just output a message about it in the latex output.
678         lyxerr[Debug::GRAPHICS]
679                 << "insetgraphics::latex: Filename = "
680                 << params().filename << endl;
681
682         // A missing (e)ps-extension is no problem for LaTeX, so
683         // we have to test three different cases
684         string const file_ = MakeAbsPath(params().filename, buf->filePath());
685         bool const file_exists =
686                 !file_.empty() &&
687                 (IsFileReadable(file_) ||               // original
688                  IsFileReadable(file_ + ".eps") ||      // original.eps
689                  IsFileReadable(file_ + ".ps"));        // original.ps
690         string const message = file_exists ?
691                 string() : string("bb = 0 0 200 100, draft, type=eps");
692         // if !message.empty() than there was no existing file
693         // "filename(.(e)ps)" found. In this case LaTeX
694         // draws only a rectangle with the above bb and the
695         // not found filename in it.
696         lyxerr[Debug::GRAPHICS]
697                 << "\tMessage = \"" << message << '\"' << endl;
698
699         // These variables collect all the latex code that should be before and
700         // after the actual includegraphics command.
701         string before;
702         string after;
703         // Do we want subcaptions?
704         if (params().subcaption) {
705                 before += "\\subfigure[" + params().subcaptionText + "]{";
706                 after = '}';
707         }
708         // We never use the starred form, we use the "clip" option instead.
709         before += "\\includegraphics";
710
711         // Write the options if there are any.
712         string const opts = createLatexOptions();
713         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
714
715         if (!opts.empty() && !message.empty())
716                 before += ("[%\n" + opts + ',' + message + ']');
717         else if (!opts.empty() || !message.empty())
718                 before += ("[%\n" + opts + message + ']');
719
720         lyxerr[Debug::GRAPHICS]
721                 << "\tBefore = " << before
722                 << "\n\tafter = " << after << endl;
723
724
725         // "nice" means that the buffer is exported to LaTeX format but not
726         //        run through the LaTeX compiler.
727         if (runparams.nice) {
728                 os << before <<'{' << params().filename << '}' << after;
729                 return 1;
730         }
731
732         // Make the filename relative to the lyx file
733         // and remove the extension so the LaTeX will use whatever is
734         // appropriate (when there are several versions in different formats)
735         string const latex_str = message.empty() ?
736                 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
737                 (before + '{' + params().filename + " not found!}" + after);
738         os << latex_str;
739
740         // Return how many newlines we issued.
741         return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
742 }
743
744
745 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
746 {
747         // No graphics in ascii output. Possible to use gifscii to convert
748         // images to ascii approximation.
749         // 1. Convert file to ascii using gifscii
750         // 2. Read ascii output file and add it to the output stream.
751         // at least we send the filename
752         os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
753         return 0;
754 }
755
756
757 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
758 {
759         // No graphics in LinuxDoc output. Should check how/what to add.
760         return 0;
761 }
762
763
764 // For explanation on inserting graphics into DocBook checkout:
765 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
766 // See also the docbook guide at http://www.docbook.org/
767 int InsetGraphics::docbook(Buffer const *, ostream & os,
768                            bool /*mixcont*/) const
769 {
770         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
771         // need to switch to MediaObject. However, for now this is sufficient and
772         // easier to use.
773         os << "<graphic fileref=\"&" << graphic_label << ";\">";
774         return 0;
775 }
776
777
778 void InsetGraphics::validate(LaTeXFeatures & features) const
779 {
780         // If we have no image, we should not require anything.
781         if (params().filename.empty())
782                 return;
783
784         features.includeFile(graphic_label, RemoveExtension(params().filename));
785
786         features.require("graphicx");
787
788         if (params().subcaption)
789                 features.require("subfigure");
790 }
791
792
793 void InsetGraphics::statusChanged()
794 {
795         if (!cache_->view.expired())
796                 cache_->view.lock()->updateInset(this);
797 }
798
799
800 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
801                               string const & filepath)
802 {
803         // If nothing is changed, just return and say so.
804         if (params() == p && !p.filename.empty())
805                 return false;
806
807         // Copy the new parameters.
808         params_ = p;
809
810         // Update the inset with the new parameters.
811         cache_->update(MakeAbsPath(params().filename, filepath));
812
813         // We have changed data, report it.
814         return true;
815 }
816
817
818 InsetGraphicsParams const & InsetGraphics::params() const
819 {
820         return params_;
821 }
822
823
824 string const InsetGraphicsMailer::name_("graphics");
825
826 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
827         : inset_(inset)
828 {}
829
830
831 string const InsetGraphicsMailer::inset2string() const
832 {
833         return params2string(inset_.params());
834 }
835
836
837 void InsetGraphicsMailer::string2params(string const & in,
838                                         InsetGraphicsParams & params)
839 {
840         params = InsetGraphicsParams();
841
842         if (in.empty())
843                 return;
844
845         istringstream data(STRCONV(in));
846         LyXLex lex(0,0);
847         lex.setStream(data);
848
849         if (lex.isOK()) {
850                 lex.next();
851                 string const token = lex.getString();
852                 if (token != name_)
853                         return;
854         }
855
856         if (lex.isOK()) {
857                 InsetGraphics inset;
858                 inset.readInsetGraphics(lex);
859                 params = inset.params();
860         }
861 }
862
863
864 string const
865 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
866 {
867         ostringstream data;
868         data << name_ << ' ';
869         params.Write(data);
870         data << "\\end_inset\n";
871         return STRCONV(data.str());
872 }