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