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