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