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