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