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