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