]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
Remove the 'gross hack' of calling inset->edit when LFUN_MOUSE_RELEASE
[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
75 #include "frontends/Alert.h"
76 #include "frontends/Dialogs.h"
77 #include "frontends/font_metrics.h"
78 #include "frontends/LyXView.h"
79 #include "frontends/Painter.h"
80
81 #include "support/LAssert.h"
82 #include "support/filetools.h"
83 #include "support/lyxalgo.h" // lyx::count
84 #include "support/lyxlib.h" // float_equal
85 #include "support/path.h"
86 #include "support/systemcall.h"
87 #include "support/os.h"
88
89 #include <boost/weak_ptr.hpp>
90 #include <boost/bind.hpp>
91 #include <boost/signals/trackable.hpp>
92 #include "BoostFormat.h"
93
94 #include <algorithm> // For the std::max
95
96 extern string system_tempdir;
97
98 using std::ostream;
99 using std::endl;
100
101
102 namespace {
103
104 ///////////////////////////////////////////////////////////////////////////
105 int const VersionNumber = 1;
106 ///////////////////////////////////////////////////////////////////////////
107
108 // This function is a utility function
109 // ... that should be with ChangeExtension ...
110 inline
111 string const RemoveExtension(string const & filename)
112 {
113         return ChangeExtension(filename, string());
114 }
115
116
117 string const uniqueID()
118 {
119         static unsigned int seed = 1000;
120
121         ostringstream ost;
122         ost << "graph" << ++seed;
123
124         // Needed if we use lyxstring.
125         return STRCONV(ost.str());
126 }
127
128
129 string findTargetFormat(string const & suffix)
130 {
131         // lyxrc.pdf_mode means:
132         // Are we creating a PDF or a PS file?
133         // (Should actually mean, are we using latex or pdflatex).
134         if (lyxrc.pdf_mode) {
135                 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
136                 if (contains(suffix, "ps") || suffix == "pdf")
137                         return "pdf";
138                 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         dispatch_result result = UNDISPATCHED;
223
224         switch (cmd.action) {
225         case LFUN_INSET_MODIFY: {
226                 InsetGraphicsParams p;
227                 InsetGraphicsMailer::string2params(cmd.argument, p);
228                 if (p.filename.empty())
229                         break;
230
231                 string const filepath = cmd.view()->buffer()->filePath();
232                 setParams(p, filepath);
233                 cmd.view()->updateInset(this, true);
234                 result = DISPATCHED;
235         }
236         break;
237
238         case LFUN_INSET_DIALOG_UPDATE: {
239                 InsetGraphicsMailer mailer(*this);
240                 mailer.updateDialog();
241         }
242         break;
243
244         case LFUN_MOUSE_RELEASE:
245                 edit(cmd.view(), cmd.x, cmd.y, cmd.button());
246                 break;
247
248         default:
249                 result = DISPATCHED;
250                 break;
251         }
252
253         return result;
254 }
255
256
257 string const InsetGraphics::statusMessage() const
258 {
259         using namespace grfx;
260
261         switch (cache_->loader.status()) {
262                 case WaitingToLoad:
263                         return _("Not shown.");
264                 case Loading:
265                         return _("Loading...");
266                 case Converting:
267                         return _("Converting to loadable format...");
268                 case Loaded:
269                         return _("Loaded into memory. Must now generate pixmap.");
270                 case ScalingEtc:
271                         return _("Scaling etc...");
272                 case Ready:
273                         return _("Ready to display");
274                 case ErrorNoFile:
275                         return _("No file found!");
276                 case ErrorConverting:
277                         return _("Error converting to loadable format");
278                 case ErrorLoading:
279                         return _("Error loading file into memory");
280                 case ErrorGeneratingPixmap:
281                         return _("Error generating the pixmap");
282                 case ErrorUnknown:
283                         return _("No image");
284         }
285         return string();
286 }
287
288
289 bool InsetGraphics::imageIsDrawable() const
290 {
291         if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
292                 return false;
293
294         return cache_->loader.image()->isDrawable();
295 }
296
297
298 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
299 {
300         cache_->old_ascent = 50;
301         if (imageIsDrawable())
302                 cache_->old_ascent = cache_->loader.image()->getHeight();
303         return cache_->old_ascent;
304 }
305
306
307 int InsetGraphics::descent(BufferView *, LyXFont const &) const
308 {
309         return 0;
310 }
311
312
313 int InsetGraphics::width(BufferView *, LyXFont const & font) const
314 {
315         if (imageIsDrawable())
316                 return cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
317
318         int font_width = 0;
319
320         LyXFont msgFont(font);
321         msgFont.setFamily(LyXFont::SANS_FAMILY);
322
323         string const justname = OnlyFilename (params().filename);
324         if (!justname.empty()) {
325                 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
326                 font_width = font_metrics::width(justname, msgFont);
327         }
328
329         string const msg = statusMessage();
330         if (!msg.empty()) {
331                 msgFont.setSize(LyXFont::SIZE_TINY);
332                 int const msg_width = font_metrics::width(msg, msgFont);
333                 font_width = std::max(font_width, msg_width);
334         }
335
336         return std::max(50, font_width + 15);
337 }
338
339
340 BufferView * InsetGraphics::view() const
341 {
342         return cache_->view.lock().get();
343 }
344
345
346 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
347                          int baseline, float & x, bool) const
348 {
349         // MakeAbsPath returns params().filename unchanged if it absolute
350         // already.
351         string const file_with_path =
352                 MakeAbsPath(params().filename, bv->buffer()->filePath());
353
354         // A 'paste' operation creates a new inset with the correct filepath,
355         // but then the 'old' inset stored in the 'copy' operation is actually
356         // added to the buffer.
357         // Thus, we should ensure that the filepath is correct.
358         if (file_with_path != cache_->loader.filename())
359                 cache_->update(file_with_path);
360
361         cache_->view = bv->owner()->view();
362         int oasc = cache_->old_ascent;
363
364         int ldescent = descent(bv, font);
365         int lascent  = ascent(bv, font);
366         int lwidth   = width(bv, font);
367
368         // we may have changed while someone other was drawing us so better
369         // to not draw anything as we surely call to redraw ourself soon.
370         // This is not a nice thing to do and should be fixed properly somehow.
371         // But I still don't know the best way to go. So let's do this like this
372         // for now (Jug 20020311)
373         if (lascent != oasc)
374                 return;
375
376         // Make sure now that x is updated upon exit from this routine
377         int old_x = int(x);
378         x += lwidth;
379
380         grfx::Params const & gparams = params().as_grfxParams();
381
382         if (gparams.display != grfx::NoDisplay &&
383                         cache_->loader.status() == grfx::WaitingToLoad)
384                 cache_->loader.startLoading();
385
386         if (!cache_->loader.monitoring())
387                 cache_->loader.startMonitoring();
388
389         // This will draw the graphics. If the graphics has not been loaded yet,
390         // we draw just a rectangle.
391         Painter & paint = bv->painter();
392
393         if (imageIsDrawable()) {
394                 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
395                             lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
396                             *cache_->loader.image());
397
398         } else {
399
400                 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
401                                 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
402
403                 // Print the file name.
404                 LyXFont msgFont(font);
405                 msgFont.setFamily(LyXFont::SANS_FAMILY);
406                 string const justname = OnlyFilename (params().filename);
407                 if (!justname.empty()) {
408                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
409                         paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
410                                    baseline - font_metrics::maxAscent(msgFont) - 4,
411                                    justname, msgFont);
412                 }
413
414                 // Print the message.
415                 string const msg = statusMessage();
416                 if (!msg.empty()) {
417                         msgFont.setSize(LyXFont::SIZE_TINY);
418                         paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
419                 }
420         }
421
422         // the status message may mean we changed size, so indicate
423         // we need a row redraw
424 #if 0
425         if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
426                 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
427         }
428 #endif
429
430         // Reset the cache, ready for the next draw request
431 #if 0
432         cached_status_ = grfx::ErrorUnknown;
433         cached_image_.reset();
434         cache_filled_ = false;
435 #endif
436 }
437
438
439 void InsetGraphics::edit(BufferView *, int, int, mouse_button::state)
440 {
441         InsetGraphicsMailer mailer(*this);
442         mailer.showDialog();
443 }
444
445
446 void InsetGraphics::edit(BufferView * bv, bool)
447 {
448         edit(bv, 0, 0, mouse_button::none);
449 }
450
451
452 Inset::EDITABLE InsetGraphics::editable() const
453 {
454         return IS_EDITABLE;
455 }
456
457
458 void InsetGraphics::write(Buffer const *, ostream & os) const
459 {
460         os << "Graphics\n";
461         params().Write(os);
462 }
463
464
465 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
466 {
467         string const token = lex.getString();
468
469         if (token == "Graphics")
470                 readInsetGraphics(lex);
471         else
472                 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
473
474         cache_->update(MakeAbsPath(params().filename, buf->filePath()));
475 }
476
477
478 void InsetGraphics::readInsetGraphics(LyXLex & lex)
479 {
480         bool finished = false;
481
482         while (lex.isOK() && !finished) {
483                 lex.next();
484
485                 string const token = lex.getString();
486                 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
487                                     << std::endl;
488
489                 if (token.empty()) {
490                         continue;
491                 } else if (token == "\\end_inset") {
492                         finished = true;
493                 } else if (token == "FormatVersion") {
494                         lex.next();
495                         int version = lex.getInteger();
496                         if (version > VersionNumber)
497                                 lyxerr
498                                 << "This document was created with a newer Graphics widget"
499                                 ", You should use a newer version of LyX to read this"
500                                 " file."
501                                 << std::endl;
502                         // TODO: Possibly open up a dialog?
503                 }
504                 else {
505                         if (! params_.Read(lex, token))
506                                 lyxerr << "Unknown token, " << token << ", skipping."
507                                         << std::endl;
508                 }
509         }
510 }
511
512
513 string const InsetGraphics::createLatexOptions() const
514 {
515         // Calculate the options part of the command, we must do it to a string
516         // stream since we might have a trailing comma that we would like to remove
517         // before writing it to the output stream.
518         ostringstream options;
519         if (!params().bb.empty())
520             options << "  bb=" << rtrim(params().bb) << ",\n";
521         if (params().draft)
522             options << "  draft,\n";
523         if (params().clip)
524             options << "  clip,\n";
525         if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
526                 if (!lyx::float_equal(params().scale, 100.0, 0.05))
527                         options << "  scale=" << params().scale / 100.0
528                                 << ",\n";
529         } else {
530                 if (!params().width.zero())
531                         options << "  width=" << params().width.asLatexString() << ",\n";
532                 if (!params().height.zero())
533                         options << "  height=" << params().height.asLatexString() << ",\n";
534                 if (params().keepAspectRatio)
535                         options << "  keepaspectratio,\n";
536         }
537
538         // Make sure rotation angle is not very close to zero;
539         // a float can be effectively zero but not exactly zero.
540         if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
541             options << "  angle=" << params().rotateAngle << ",\n";
542             if (!params().rotateOrigin.empty()) {
543                 options << "  origin=" << params().rotateOrigin[0];
544                 if (contains(params().rotateOrigin,"Top"))
545                     options << 't';
546                 else if (contains(params().rotateOrigin,"Bottom"))
547                     options << 'b';
548                 else if (contains(params().rotateOrigin,"Baseline"))
549                     options << 'B';
550                 options << ",\n";
551             }
552         }
553
554         if (!params().special.empty())
555             options << params().special << ",\n";
556
557         string opts = STRCONV(options.str());
558         // delete last ",\n"
559         return opts.substr(0, opts.size() - 2);
560 }
561
562
563 string const InsetGraphics::prepareFile(Buffer const * buf) const
564 {
565         // LaTeX can cope if the graphics file doesn't exist, so just return the
566         // filename.
567         string const orig_file = params().filename;
568         string orig_file_with_path =
569                 MakeAbsPath(orig_file, buf->filePath());
570         lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
571                     << orig_file << "\n\twith path: "
572                     << orig_file_with_path << endl;
573
574         if (!IsFileReadable(orig_file_with_path))
575                 return orig_file;
576
577         bool const zipped = zippedFile(orig_file_with_path);
578
579         // If the file is compressed and we have specified that it
580         // should not be uncompressed, then just return its name and
581         // let LaTeX do the rest!
582         if (zipped && params().noUnzip) {
583                 lyxerr[Debug::GRAPHICS]
584                         << "\tpass zipped file to LaTeX but with full path.\n";
585                 // LaTeX needs an absolue path, otherwise the
586                 // coresponding *.eps.bb file isn't found
587                 return orig_file_with_path;
588         }
589
590         // Ascertain whether the file has changed.
591         unsigned long const new_checksum = cache_->loader.checksum();
592         bool const file_has_changed = cache_->checksum != new_checksum;
593         if (file_has_changed)
594                 cache_->checksum = new_checksum;
595
596         // temp_file will contain the file for LaTeX to act on if, for example,
597         // we move it to a temp dir or uncompress it.
598         string temp_file = orig_file;
599
600         if (zipped) {
601                 // Uncompress the file if necessary.
602                 // If it has been uncompressed in a previous call to
603                 // prepareFile, do nothing.
604                 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
605                 lyxerr[Debug::GRAPHICS]
606                         << "\ttemp_file: " << temp_file << endl;
607                 if (file_has_changed || !IsFileReadable(temp_file)) {
608                         bool const success = lyx::copy(orig_file_with_path,
609                                                        temp_file);
610                         lyxerr[Debug::GRAPHICS]
611                                 << "\tCopying zipped file from "
612                                 << orig_file_with_path << " to " << temp_file
613                                 << (success ? " succeeded\n" : " failed\n");
614                 } else
615                         lyxerr[Debug::GRAPHICS]
616                                 << "\tzipped file " << temp_file
617                                 << " exists! Maybe no tempdir ...\n";
618                 orig_file_with_path = unzipFile(temp_file);
619                 lyxerr[Debug::GRAPHICS]
620                         << "\tunzipped to " << orig_file_with_path << endl;
621         }
622
623         string const from = getExtFromContents(orig_file_with_path);
624         string const to   = findTargetFormat(from);
625         lyxerr[Debug::GRAPHICS]
626                 << "\t we have: from " << from << " to " << to << '\n';
627
628         if (from == to && !lyxrc.use_tempdir) {
629                 // No conversion is needed. LaTeX can handle the
630                 // graphic file as is.
631                 // This is true even if the orig_file is compressed.
632                 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
633                         return RemoveExtension(orig_file_with_path);
634                 return orig_file_with_path;
635         }
636
637         // We're going to be running the exported buffer through the LaTeX
638         // compiler, so must ensure that LaTeX can cope with the graphics
639         // file format.
640
641         // Perform all these manipulations on a temporary file if possible.
642         // If we are not using a temp dir, then temp_file contains the
643         // original file.
644         // to allow files with the same name in different dirs
645         // we manipulate the original file "any.dir/file.ext"
646         // to "any_dir_file.ext"! changing the dots in the
647         // dirname is important for the use of ChangeExtension
648         lyxerr[Debug::GRAPHICS]
649                 << "\tthe orig file is: " << orig_file_with_path << endl;
650
651         if (lyxrc.use_tempdir) {
652                 string const ext_tmp = GetExtension(orig_file_with_path);
653                 // without ext and /
654                 temp_file = subst(
655                         ChangeExtension(orig_file_with_path, string()), "/", "_");
656                 // without dots and again with ext
657                 temp_file = ChangeExtension(
658                         subst(temp_file, ".", "_"), ext_tmp);
659                 // now we have any_dir_file.ext
660                 temp_file = MakeAbsPath(temp_file, buf->tmppath);
661                 lyxerr[Debug::GRAPHICS]
662                         << "\tchanged to: " << temp_file << endl;
663
664                 // if the file doen't exists, copy it into the tempdir
665                 if (file_has_changed || !IsFileReadable(temp_file)) {
666                         bool const success = lyx::copy(orig_file_with_path, temp_file);
667                         lyxerr[Debug::GRAPHICS]
668                                 << "\tcopying from " << orig_file_with_path << " to "
669                                 << temp_file
670                                 << (success ? " succeeded\n" : " failed\n");
671                         if (!success) {
672                                 Alert::alert(_("Cannot copy file"), orig_file_with_path,
673                                         _("into tempdir"));
674                                 return orig_file;
675                         }
676                 }
677
678                 if (from == to) {
679                         // No conversion is needed. LaTeX can handle the
680                         // graphic file as is.
681                         if (formats.getFormat(to)->extension() == GetExtension(orig_file))
682                                 return RemoveExtension(temp_file);
683                         return temp_file;
684                 }
685         }
686
687         string const outfile_base = RemoveExtension(temp_file);
688         lyxerr[Debug::GRAPHICS]
689                 << "\tThe original file is " << orig_file << "\n"
690                 << "\tA copy has been made and convert is to be called with:\n"
691                 << "\tfile to convert = " << temp_file << '\n'
692                 << "\toutfile_base = " << outfile_base << '\n'
693                 << "\t from " << from << " to " << to << '\n';
694
695         // if no special converter defined, than we take the default one
696         // from ImageMagic: convert from:inname.from to:outname.to
697         if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
698                 string const command =
699                         LibFileSearch("scripts", "convertDefault.sh") +
700                                 ' ' + from + ':' + temp_file + ' ' +
701                                 to + ':' + outfile_base + '.' + to;
702                 lyxerr[Debug::GRAPHICS]
703                         << "No converter defined! I use convertDefault.sh:\n\t"
704                         << command << endl;
705                 Systemcall one;
706                 one.startscript(Systemcall::Wait, command);
707                 if (!IsFileReadable(ChangeExtension(outfile_base, to)))
708 #if USE_BOOST_FORMAT
709                         Alert::alert(_("Cannot convert Image (not existing file?)"),
710                                      boost::io::str(boost::format(_("No information for converting from %1$s to %2$s"))
711                                 % from % to));
712 #else
713                         Alert::alert(_("Cannot convert Image (not existing file?)"),
714                                      _("No information for converting from ") + from + " to " + to);
715 #endif
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, false);
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         InsetGraphics inset;    
911         inset.readInsetGraphics(lex);
912         params = inset.params();
913 }
914
915
916 string const
917 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
918 {
919         ostringstream data;
920         data << name_ << ' ';
921         params.Write(data);
922         data << "\\end_inset\n";
923
924         return data.str();
925 }