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