]> git.lyx.org Git - features.git/blob - src/insets/insetgraphics.C
port the graphics dialog to the new scheme and get rid of the ControlInset
[features.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         default:
245                 result = DISPATCHED;
246                 break;
247         }
248
249         return result;
250 }
251
252
253 string const InsetGraphics::statusMessage() const
254 {
255         using namespace grfx;
256
257         switch (cache_->loader.status()) {
258                 case WaitingToLoad:
259                         return _("Not shown.");
260                 case Loading:
261                         return _("Loading...");
262                 case Converting:
263                         return _("Converting to loadable format...");
264                 case Loaded:
265                         return _("Loaded into memory. Must now generate pixmap.");
266                 case ScalingEtc:
267                         return _("Scaling etc...");
268                 case Ready:
269                         return _("Ready to display");
270                 case ErrorNoFile:
271                         return _("No file found!");
272                 case ErrorConverting:
273                         return _("Error converting to loadable format");
274                 case ErrorLoading:
275                         return _("Error loading file into memory");
276                 case ErrorGeneratingPixmap:
277                         return _("Error generating the pixmap");
278                 case ErrorUnknown:
279                         return _("No image");
280         }
281         return string();
282 }
283
284
285 bool InsetGraphics::imageIsDrawable() const
286 {
287         if (!cache_->loader.image() || cache_->loader.status() != grfx::Ready)
288                 return false;
289
290         return cache_->loader.image()->isDrawable();
291 }
292
293
294 int InsetGraphics::ascent(BufferView *, LyXFont const &) const
295 {
296         cache_->old_ascent = 50;
297         if (imageIsDrawable())
298                 cache_->old_ascent = cache_->loader.image()->getHeight();
299         return cache_->old_ascent;
300 }
301
302
303 int InsetGraphics::descent(BufferView *, LyXFont const &) const
304 {
305         return 0;
306 }
307
308
309 int InsetGraphics::width(BufferView *, LyXFont const & font) const
310 {
311         if (imageIsDrawable())
312                 return cache_->loader.image()->getWidth() + 2 * TEXT_TO_INSET_OFFSET;
313
314         int font_width = 0;
315
316         LyXFont msgFont(font);
317         msgFont.setFamily(LyXFont::SANS_FAMILY);
318
319         string const justname = OnlyFilename (params().filename);
320         if (!justname.empty()) {
321                 msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
322                 font_width = font_metrics::width(justname, msgFont);
323         }
324
325         string const msg = statusMessage();
326         if (!msg.empty()) {
327                 msgFont.setSize(LyXFont::SIZE_TINY);
328                 int const msg_width = font_metrics::width(msg, msgFont);
329                 font_width = std::max(font_width, msg_width);
330         }
331
332         return std::max(50, font_width + 15);
333 }
334
335
336 BufferView * InsetGraphics::view() const
337 {
338         return cache_->view.lock().get();
339 }
340
341
342 void InsetGraphics::draw(BufferView * bv, LyXFont const & font,
343                          int baseline, float & x, bool) const
344 {
345         // MakeAbsPath returns params().filename unchanged if it absolute
346         // already.
347         string const file_with_path =
348                 MakeAbsPath(params().filename, bv->buffer()->filePath());
349
350         // A 'paste' operation creates a new inset with the correct filepath,
351         // but then the 'old' inset stored in the 'copy' operation is actually
352         // added to the buffer.
353         // Thus, we should ensure that the filepath is correct.
354         if (file_with_path != cache_->loader.filename())
355                 cache_->update(file_with_path);
356
357         cache_->view = bv->owner()->view();
358         int oasc = cache_->old_ascent;
359
360         int ldescent = descent(bv, font);
361         int lascent  = ascent(bv, font);
362         int lwidth   = width(bv, font);
363
364         // we may have changed while someone other was drawing us so better
365         // to not draw anything as we surely call to redraw ourself soon.
366         // This is not a nice thing to do and should be fixed properly somehow.
367         // But I still don't know the best way to go. So let's do this like this
368         // for now (Jug 20020311)
369         if (lascent != oasc)
370                 return;
371
372         // Make sure now that x is updated upon exit from this routine
373         int old_x = int(x);
374         x += lwidth;
375
376         grfx::Params const & gparams = params().as_grfxParams();
377
378         if (gparams.display != grfx::NoDisplay &&
379                         cache_->loader.status() == grfx::WaitingToLoad)
380                 cache_->loader.startLoading();
381
382         if (!cache_->loader.monitoring())
383                 cache_->loader.startMonitoring();
384
385         // This will draw the graphics. If the graphics has not been loaded yet,
386         // we draw just a rectangle.
387         Painter & paint = bv->painter();
388
389         if (imageIsDrawable()) {
390                 paint.image(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
391                             lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent,
392                             *cache_->loader.image());
393
394         } else {
395
396                 paint.rectangle(old_x + TEXT_TO_INSET_OFFSET, baseline - lascent,
397                                 lwidth - 2 * TEXT_TO_INSET_OFFSET, lascent + ldescent);
398
399                 // Print the file name.
400                 LyXFont msgFont(font);
401                 msgFont.setFamily(LyXFont::SANS_FAMILY);
402                 string const justname = OnlyFilename (params().filename);
403                 if (!justname.empty()) {
404                         msgFont.setSize(LyXFont::SIZE_FOOTNOTE);
405                         paint.text(old_x + TEXT_TO_INSET_OFFSET + 6,
406                                    baseline - font_metrics::maxAscent(msgFont) - 4,
407                                    justname, msgFont);
408                 }
409
410                 // Print the message.
411                 string const msg = statusMessage();
412                 if (!msg.empty()) {
413                         msgFont.setSize(LyXFont::SIZE_TINY);
414                         paint.text(old_x + TEXT_TO_INSET_OFFSET + 6, baseline - 4, msg, msgFont);
415                 }
416         }
417
418         // the status message may mean we changed size, so indicate
419         // we need a row redraw
420 #if 0
421         if (old_status_ != grfx::ErrorUnknown && old_status_ != cached_status_) {
422                 bv->getLyXText()->status(bv, LyXText::CHANGED_IN_DRAW);
423         }
424 #endif
425
426         // Reset the cache, ready for the next draw request
427 #if 0
428         cached_status_ = grfx::ErrorUnknown;
429         cached_image_.reset();
430         cache_filled_ = false;
431 #endif
432 }
433
434
435 void InsetGraphics::edit(BufferView *, int, int, mouse_button::state)
436 {
437         InsetGraphicsMailer mailer(*this);
438         mailer.showDialog();
439 }
440
441
442 void InsetGraphics::edit(BufferView * bv, bool)
443 {
444         edit(bv, 0, 0, mouse_button::none);
445 }
446
447
448 Inset::EDITABLE InsetGraphics::editable() const
449 {
450         return IS_EDITABLE;
451 }
452
453
454 void InsetGraphics::write(Buffer const *, ostream & os) const
455 {
456         os << "Graphics\n";
457         params().Write(os);
458 }
459
460
461 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
462 {
463         string const token = lex.getString();
464
465         if (token == "Graphics")
466                 readInsetGraphics(lex);
467         else
468                 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
469
470         cache_->update(MakeAbsPath(params().filename, buf->filePath()));
471 }
472
473
474 void InsetGraphics::readInsetGraphics(LyXLex & lex)
475 {
476         bool finished = false;
477
478         while (lex.isOK() && !finished) {
479                 lex.next();
480
481                 string const token = lex.getString();
482                 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
483                                     << std::endl;
484
485                 if (token.empty()) {
486                         continue;
487                 } else if (token == "\\end_inset") {
488                         finished = true;
489                 } else if (token == "FormatVersion") {
490                         lex.next();
491                         int version = lex.getInteger();
492                         if (version > VersionNumber)
493                                 lyxerr
494                                 << "This document was created with a newer Graphics widget"
495                                 ", You should use a newer version of LyX to read this"
496                                 " file."
497                                 << std::endl;
498                         // TODO: Possibly open up a dialog?
499                 }
500                 else {
501                         if (! params_.Read(lex, token))
502                                 lyxerr << "Unknown token, " << token << ", skipping."
503                                         << std::endl;
504                 }
505         }
506 }
507
508
509 string const InsetGraphics::createLatexOptions() const
510 {
511         // Calculate the options part of the command, we must do it to a string
512         // stream since we might have a trailing comma that we would like to remove
513         // before writing it to the output stream.
514         ostringstream options;
515         if (!params().bb.empty())
516             options << "  bb=" << rtrim(params().bb) << ",\n";
517         if (params().draft)
518             options << "  draft,\n";
519         if (params().clip)
520             options << "  clip,\n";
521         if (!lyx::float_equal(params().scale, 0.0, 0.05)) {
522                 if (!lyx::float_equal(params().scale, 100.0, 0.05))
523                         options << "  scale=" << params().scale / 100.0
524                                 << ",\n";
525         } else {
526                 if (!params().width.zero())
527                         options << "  width=" << params().width.asLatexString() << ",\n";
528                 if (!params().height.zero())
529                         options << "  height=" << params().height.asLatexString() << ",\n";
530                 if (params().keepAspectRatio)
531                         options << "  keepaspectratio,\n";
532         }
533
534         // Make sure rotation angle is not very close to zero;
535         // a float can be effectively zero but not exactly zero.
536         if (!lyx::float_equal(params().rotateAngle, 0, 0.001)) {
537             options << "  angle=" << params().rotateAngle << ",\n";
538             if (!params().rotateOrigin.empty()) {
539                 options << "  origin=" << params().rotateOrigin[0];
540                 if (contains(params().rotateOrigin,"Top"))
541                     options << 't';
542                 else if (contains(params().rotateOrigin,"Bottom"))
543                     options << 'b';
544                 else if (contains(params().rotateOrigin,"Baseline"))
545                     options << 'B';
546                 options << ",\n";
547             }
548         }
549
550         if (!params().special.empty())
551             options << params().special << ",\n";
552
553         string opts = STRCONV(options.str());
554         // delete last ",\n"
555         return opts.substr(0, opts.size() - 2);
556 }
557
558
559 string const InsetGraphics::prepareFile(Buffer const * buf) const
560 {
561         // LaTeX can cope if the graphics file doesn't exist, so just return the
562         // filename.
563         string const orig_file = params().filename;
564         string orig_file_with_path =
565                 MakeAbsPath(orig_file, buf->filePath());
566         lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
567                     << orig_file << "\n\twith path: "
568                     << orig_file_with_path << endl;
569
570         if (!IsFileReadable(orig_file_with_path))
571                 return orig_file;
572
573         bool const zipped = zippedFile(orig_file_with_path);
574
575         // If the file is compressed and we have specified that it
576         // should not be uncompressed, then just return its name and
577         // let LaTeX do the rest!
578         if (zipped && params().noUnzip) {
579                 lyxerr[Debug::GRAPHICS]
580                         << "\tpass zipped file to LaTeX but with full path.\n";
581                 // LaTeX needs an absolue path, otherwise the
582                 // coresponding *.eps.bb file isn't found
583                 return orig_file_with_path;
584         }
585
586         // Ascertain whether the file has changed.
587         unsigned long const new_checksum = cache_->loader.checksum();
588         bool const file_has_changed = cache_->checksum != new_checksum;
589         if (file_has_changed)
590                 cache_->checksum = new_checksum;
591
592         // temp_file will contain the file for LaTeX to act on if, for example,
593         // we move it to a temp dir or uncompress it.
594         string temp_file = orig_file;
595
596         if (zipped) {
597                 // Uncompress the file if necessary.
598                 // If it has been uncompressed in a previous call to
599                 // prepareFile, do nothing.
600                 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
601                 lyxerr[Debug::GRAPHICS]
602                         << "\ttemp_file: " << temp_file << endl;
603                 if (file_has_changed || !IsFileReadable(temp_file)) {
604                         bool const success = lyx::copy(orig_file_with_path,
605                                                        temp_file);
606                         lyxerr[Debug::GRAPHICS]
607                                 << "\tCopying zipped file from "
608                                 << orig_file_with_path << " to " << temp_file
609                                 << (success ? " succeeded\n" : " failed\n");
610                 } else
611                         lyxerr[Debug::GRAPHICS]
612                                 << "\tzipped file " << temp_file
613                                 << " exists! Maybe no tempdir ...\n";
614                 orig_file_with_path = unzipFile(temp_file);
615                 lyxerr[Debug::GRAPHICS]
616                         << "\tunzipped to " << orig_file_with_path << endl;
617         }
618
619         string const from = getExtFromContents(orig_file_with_path);
620         string const to   = findTargetFormat(from);
621         lyxerr[Debug::GRAPHICS]
622                 << "\t we have: from " << from << " to " << to << '\n';
623
624         if (from == to && !lyxrc.use_tempdir) {
625                 // No conversion is needed. LaTeX can handle the
626                 // graphic file as is.
627                 // This is true even if the orig_file is compressed.
628                 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
629                         return RemoveExtension(orig_file_with_path);
630                 return orig_file_with_path;
631         }
632
633         // We're going to be running the exported buffer through the LaTeX
634         // compiler, so must ensure that LaTeX can cope with the graphics
635         // file format.
636
637         // Perform all these manipulations on a temporary file if possible.
638         // If we are not using a temp dir, then temp_file contains the
639         // original file.
640         // to allow files with the same name in different dirs
641         // we manipulate the original file "any.dir/file.ext"
642         // to "any_dir_file.ext"! changing the dots in the
643         // dirname is important for the use of ChangeExtension
644         lyxerr[Debug::GRAPHICS]
645                 << "\tthe orig file is: " << orig_file_with_path << endl;
646
647         if (lyxrc.use_tempdir) {
648                 string const ext_tmp = GetExtension(orig_file_with_path);
649                 // without ext and /
650                 temp_file = subst(
651                         ChangeExtension(orig_file_with_path, string()), "/", "_");
652                 // without dots and again with ext
653                 temp_file = ChangeExtension(
654                         subst(temp_file, ".", "_"), ext_tmp);
655                 // now we have any_dir_file.ext
656                 temp_file = MakeAbsPath(temp_file, buf->tmppath);
657                 lyxerr[Debug::GRAPHICS]
658                         << "\tchanged to: " << temp_file << endl;
659
660                 // if the file doen't exists, copy it into the tempdir
661                 if (file_has_changed || !IsFileReadable(temp_file)) {
662                         bool const success = lyx::copy(orig_file_with_path, temp_file);
663                         lyxerr[Debug::GRAPHICS]
664                                 << "\tcopying from " << orig_file_with_path << " to "
665                                 << temp_file
666                                 << (success ? " succeeded\n" : " failed\n");
667                         if (!success) {
668                                 Alert::alert(_("Cannot copy file"), orig_file_with_path,
669                                         _("into tempdir"));
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                         Alert::alert(_("Cannot convert Image (not existing file?)"),
706                                      boost::io::str(boost::format(_("No information for converting from %1$s to %2$s"))
707                                 % from % to));
708 #else
709                         Alert::alert(_("Cannot convert Image (not existing file?)"),
710                                      _("No information for converting from ") + from + " to " + to);
711 #endif
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 #if USE_BOOST_FORMAT
798         os << '<'
799            << boost::format(_("Graphics file: %1$s")) % params().filename
800            << ">\n";
801 #else
802         os << '<'
803            << _("Graphics file: ") << params().filename
804            << ">\n";
805 #endif
806         return 0;
807 }
808
809
810 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
811 {
812         // No graphics in LinuxDoc output. Should check how/what to add.
813         return 0;
814 }
815
816
817 // For explanation on inserting graphics into DocBook checkout:
818 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
819 // See also the docbook guide at http://www.docbook.org/
820 int InsetGraphics::docbook(Buffer const *, ostream & os,
821                            bool /*mixcont*/) const
822 {
823         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
824         // need to switch to MediaObject. However, for now this is sufficient and
825         // easier to use.
826         os << "<graphic fileref=\"&" << graphic_label << ";\">";
827         return 0;
828 }
829
830
831 void InsetGraphics::validate(LaTeXFeatures & features) const
832 {
833         // If we have no image, we should not require anything.
834         if (params().filename.empty())
835                 return;
836
837         features.includeFile(graphic_label, RemoveExtension(params().filename));
838
839         features.require("graphicx");
840
841         if (params().subcaption)
842                 features.require("subfigure");
843 }
844
845
846 void InsetGraphics::statusChanged()
847 {
848         if (!cache_->view.expired())
849                 cache_->view.lock()->updateInset(this, false);
850 }
851
852
853 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
854                               string const & filepath)
855 {
856         // If nothing is changed, just return and say so.
857         if (params() == p && !p.filename.empty())
858                 return false;
859
860         // Copy the new parameters.
861         params_ = p;
862
863         // Update the inset with the new parameters.
864         cache_->update(MakeAbsPath(params().filename, filepath));
865
866         // We have changed data, report it.
867         return true;
868 }
869
870
871 InsetGraphicsParams const & InsetGraphics::params() const
872 {
873         return params_;
874 }
875
876
877 string const InsetGraphicsMailer::name_("graphics");
878
879 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
880         : inset_(inset)
881 {}
882
883
884 string const InsetGraphicsMailer::inset2string() const
885 {
886         return params2string(inset_.params());
887 }
888
889
890 void InsetGraphicsMailer::string2params(string const & in,
891                                         InsetGraphicsParams & params)
892 {
893         params = InsetGraphicsParams();
894
895         istringstream data(in);
896         LyXLex lex(0,0);
897         lex.setStream(data);
898
899         if (lex.isOK()) {
900                 lex.next();
901                 string const token = lex.getString();
902                 if (token != name_)
903                         return;
904         }
905
906         InsetGraphics inset;    
907         inset.readInsetGraphics(lex);
908         params = inset.params();
909 }
910
911
912 string const
913 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
914 {
915         ostringstream data;
916         data << name_ << ' ';
917         params.Write(data);
918         data << "\\end_inset\n";
919
920         return data.str();
921 }