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