]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
0d7d406164d9d1aa34c258165252dc6e482416bd
[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 oldUnitsWidth =
450                 getVectorFromString("pt, cm, in, text%, col%");
451         std::vector<string> const oldUnitsHeight =
452                 getVectorFromString("pt, cm, in, theight%");
453         bool finished = false;
454         // set the display default
455         if (lyxrc.display_graphics == "mono")
456             params_.display = InsetGraphicsParams::MONOCHROME;
457         else if (lyxrc.display_graphics == "gray")
458             params_.display = InsetGraphicsParams::GRAYSCALE;
459         else if (lyxrc.display_graphics == "color")
460             params_.display = InsetGraphicsParams::COLOR;
461         else
462             params_.display = InsetGraphicsParams::NONE;
463         while (lex.isOK() && !finished) {
464                 lex.next();
465
466                 string const token = lex.getString();
467                 lyxerr[Debug::GRAPHICS] << "Token: " << token << endl;
468
469                 if (token.empty())
470                         continue;
471                 else if (token == "\\end_inset") {
472                         finished = true;
473                 } else if (token == "file") {
474                         if (lex.next()) {
475                                 params_.filename = lex.getString();
476                         }
477                 } else if (token == "extra") {
478                         if (lex.next());
479                         // kept for backwards compability. Delete in 0.13.x
480                 } else if (token == "subcaption") {
481                         if (lex.eatLine())
482                                 params_.subcaptionText = lex.getString();
483                 } else if (token == "label") {
484                         if (lex.next());
485                         // kept for backwards compability. Delete in 0.13.x
486                 } else if (token == "angle") {
487                         if (lex.next()) {
488                                 params_.rotate = true;
489                                 params_.rotateAngle = lex.getFloat();
490                         }
491                 } else if (token == "size") {
492                         if (lex.next())
493                                 params_.lyxwidth = LyXLength(lex.getString()+"pt");
494                         if (lex.next())
495                                 params_.lyxheight = LyXLength(lex.getString()+"pt");
496                         params_.lyxsize_kind = InsetGraphicsParams::WH;
497                 } else if (token == "flags") {
498                         if (lex.next())
499                                 switch (lex.getInteger()) {
500                                 case 1: params_.display = InsetGraphicsParams::MONOCHROME;
501                                     break;
502                                 case 2: params_.display = InsetGraphicsParams::GRAYSCALE;
503                                     break;
504                                 case 3: params_.display = InsetGraphicsParams::COLOR;
505                                     break;
506                                 case 8: params_.display = InsetGraphicsParams::NONE;
507                                     break;
508                                 }
509                 } else if (token == "subfigure") {
510                         params_.subcaption = true;
511                 } else if (token == "width") {
512                     if (lex.next()) {
513                         int i = lex.getInteger();
514                         if (lex.next()) {
515                             if (i == 5) {
516                                 params_.scale = lex.getInteger();
517                                 params_.size_kind = InsetGraphicsParams::SCALE;
518                             } else {
519                                 string const value = lex.getString();
520                                 lyxerr[Debug::GRAPHICS] << "readFiginset::oldWidth: "
521                                         << value << oldUnitsWidth[i] << endl;
522                                 params_.width = LyXLength(value + oldUnitsWidth[i]);
523                                 lyxerr[Debug::GRAPHICS] << "readFiginset::newWidth: "
524                                         << params_.width.asString() << endl;
525                                 params_.size_kind = InsetGraphicsParams::WH;
526                             }
527                         }
528                     }
529                 } else if (token == "height") {
530                     if (lex.next()) {
531                         int i = lex.getInteger();
532                         if (lex.next()) {
533                                 string const value = lex.getString();
534                                 lyxerr[Debug::GRAPHICS] << "readFiginset::oldHeight: "
535                                         << value << oldUnitsHeight[i] << endl;
536                                 params_.height = LyXLength(value + oldUnitsHeight[i]);
537                                 lyxerr[Debug::GRAPHICS] << "readFiginset::newHeight: "
538                                         << params_.height.asString() << endl;
539                             params_.size_kind = InsetGraphicsParams::WH;
540                         }
541                     }
542                 }
543         }
544 }
545
546 string const InsetGraphics::createLatexOptions() const
547 {
548         // Calculate the options part of the command, we must do it to a string
549         // stream since we might have a trailing comma that we would like to remove
550         // before writing it to the output stream.
551         ostringstream options;
552         if (!params().bb.empty())
553             options << "  bb=" << strip(params().bb) << ",\n";
554         if (params().draft)
555             options << "  draft,\n";
556         if (params().clip)
557             options << "  clip,\n";
558         if (params().size_kind == InsetGraphicsParams::WH) {
559             if (!params().width.zero())
560                 options << "  width=" << params().width.asLatexString() << ",\n";
561             if (!params().height.zero())
562                 options << "  height=" << params().height.asLatexString() << ",\n";
563         } else if (params().size_kind == InsetGraphicsParams::SCALE) {
564             if (params().scale > 0)
565                 options << "  scale=" << double(params().scale)/100.0 << ",\n";
566         }
567         if (params().keepAspectRatio)
568             options << "  keepaspectratio,\n";
569         // Make sure it's not very close to zero, a float can be effectively
570         // zero but not exactly zero.
571         if (!lyx::float_equal(params().rotateAngle, 0, 0.001) && params().rotate) {
572             options << "  angle=" << params().rotateAngle << ",\n";
573             if (!params().rotateOrigin.empty()) {
574                 options << "  origin=" << params().rotateOrigin[0];
575                 if (contains(params().rotateOrigin,"Top"))
576                     options << 't';
577                 else if (contains(params().rotateOrigin,"Bottom"))
578                     options << 'b';
579                 else if (contains(params().rotateOrigin,"Baseline"))
580                     options << 'B';
581                 options << ",\n";
582             }
583         }
584         if (!params().special.empty())
585             options << params().special << ",\n";
586         string opts = options.str().c_str();
587         return opts.substr(0,opts.size()-2);    // delete last ",\n"
588 }
589
590 namespace {
591 string findTargetFormat(string const & suffix)
592 {
593         // lyxrc.pdf_mode means:
594         // Are we creating a PDF or a PS file?
595         // (Should actually mean, are we using latex or pdflatex).
596         if (lyxrc.pdf_mode) {
597                 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
598                 if (contains(suffix, "ps") || suffix == "pdf")
599                         return "pdf";
600                 else if (suffix == "jpg")       // pdflatex can use jpeg
601                         return suffix;
602                 else
603                         return "png";           // and also png
604         }
605         // If it's postscript, we always do eps.
606         lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
607         if (suffix != "ps")                     // any other than ps
608             return "eps";                       // is changed to eps
609         else
610             return suffix;                      // let ps untouched
611 }
612
613 } // Anon. namespace
614
615
616 string const InsetGraphics::prepareFile(Buffer const *buf) const
617 {
618         // LaTeX can cope if the graphics file doesn't exist, so just return the
619         // filename.
620         string const orig_file = params().filename;
621         string orig_file_with_path =
622                 MakeAbsPath(orig_file, buf->filePath());
623         lyxerr[Debug::GRAPHICS] << "[InsetGraphics::prepareFile] orig_file = "
624                     << orig_file << "\n\twith path: "
625                     << orig_file_with_path << endl;
626
627         if (!IsFileReadable(orig_file_with_path))
628                 return orig_file;
629
630         bool const zipped = zippedFile(orig_file_with_path);
631
632         // If the file is compressed and we have specified that it
633         // should not be uncompressed, then just return its name and
634         // let LaTeX do the rest!
635         if (zipped && params().noUnzip) {
636                 lyxerr[Debug::GRAPHICS]
637                         << "\tpass zipped file to LaTeX but with full path.\n";
638                 // LaTeX needs an absolue path, otherwise the
639                 // coresponding *.eps.bb file isn't found
640                 return orig_file_with_path;
641         }
642
643         // Ascertain whether the file has changed.
644         unsigned long const new_checksum = cache_->loader.checksum();
645         bool const file_has_changed = cache_->checksum != new_checksum;
646         if (file_has_changed)
647                 cache_->checksum = new_checksum;
648
649         // temp_file will contain the file for LaTeX to act on if, for example,
650         // we move it to a temp dir or uncompress it.
651         string temp_file(orig_file);
652
653         if (zipped) {
654                 // Uncompress the file if necessary.
655                 // If it has been uncompressed in a previous call to
656                 // prepareFile, do nothing.
657                 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
658                 lyxerr[Debug::GRAPHICS]
659                         << "\ttemp_file: " << temp_file << endl;
660                 if (file_has_changed || !IsFileReadable(temp_file)) {
661                         bool const success = lyx::copy(orig_file_with_path,
662                                                        temp_file);
663                         lyxerr[Debug::GRAPHICS]
664                                 << "\tCopying zipped file from "
665                                 << orig_file_with_path << " to " << temp_file
666                                 << (success ? " succeeded\n" : " failed\n");
667                 } else
668                         lyxerr[Debug::GRAPHICS]
669                                 << "\tzipped file " << temp_file
670                                 << " exists! Maybe no tempdir ...\n";
671                 orig_file_with_path = unzipFile(temp_file);
672                 lyxerr[Debug::GRAPHICS]
673                         << "\tunzipped to " << orig_file_with_path << endl;
674         }
675
676         string const from = getExtFromContents(orig_file_with_path);
677         string const to   = findTargetFormat(from);
678         lyxerr[Debug::GRAPHICS]
679                 << "\t we have: from " << from << " to " << to << '\n';
680
681         if (from == to && !lyxrc.use_tempdir)
682                 // No conversion is needed. LaTeX can handle the
683                 // graphic file as is.
684                 // This is true even if the orig_file is compressed.
685                 return RemoveExtension(orig_file_with_path);
686
687         // We're going to be running the exported buffer through the LaTeX
688         // compiler, so must ensure that LaTeX can cope with the graphics
689         // file format.
690
691         // Perform all these manipulations on a temporary file if possible.
692         // If we are not using a temp dir, then temp_file contains the
693         // original file.
694         // to allow files with the same name in different dirs
695         // we manipulate the original file "any.dir/file.ext"
696         // to "any_dir_file.ext"! changing the dots in the
697         // dirname is important for the use of ChangeExtension
698         lyxerr[Debug::GRAPHICS]
699                 << "\tthe orig file is: " << orig_file_with_path << endl;
700
701         if (lyxrc.use_tempdir) {
702                 string const ext_tmp = GetExtension(orig_file_with_path);
703                 // without ext and /
704                 temp_file = subst(
705                         ChangeExtension(orig_file_with_path, string()), "/", "_");
706                 // without dots and again with ext
707                 temp_file = ChangeExtension(
708                         subst(temp_file, ".", "_"), ext_tmp);
709                 // now we have any_dir_file.ext
710                 temp_file = MakeAbsPath(temp_file, buf->tmppath);
711                 lyxerr[Debug::GRAPHICS]
712                         << "\tchanged to: " << temp_file << endl;
713
714                 // if the file doen't exists, copy it into the tempdir
715                 if (file_has_changed || !IsFileReadable(temp_file)) {
716                         bool const success = lyx::copy(orig_file_with_path, temp_file);
717                         lyxerr[Debug::GRAPHICS]
718                                 << "\tcopying from " << orig_file_with_path << " to "
719                                 << temp_file
720                                 << (success ? " succeeded\n" : " failed\n");
721                         if (!success) {
722                                 Alert::alert(_("Cannot copy file"), orig_file_with_path,
723                                         _("into tempdir"));
724                                 return orig_file;
725                         }
726                 }
727
728                 if (from == to)
729                         // No conversion is needed. LaTeX can handle the
730                         // graphic file as is.
731                         return RemoveExtension(temp_file);
732         }
733
734         string const outfile_base = RemoveExtension(temp_file);
735         lyxerr[Debug::GRAPHICS]
736                 << "\tThe original file is " << orig_file << "\n"
737                 << "\tA copy has been made and convert is to be called with:\n"
738                 << "\tfile to convert = " << temp_file << '\n'
739                 << "\toutfile_base = " << outfile_base << '\n'
740                 << "\t from " << from << " to " << to << '\n';
741
742         // if no special converter defined, than we take the default one
743         // from ImageMagic: convert from:inname.from to:outname.to
744         if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
745                 string const command =
746                         LibFileSearch("scripts", "convertDefault.sh") +
747                                 ' ' + from + ':' + temp_file + ' ' +
748                                 to + ':' + outfile_base + '.' + to;
749                 lyxerr[Debug::GRAPHICS]
750                         << "No converter defined! I use convertDefault.sh:\n\t"
751                         << command << endl;
752                 Systemcall one;
753                 one.startscript(Systemcall::Wait, command);
754                 if (!IsFileReadable(ChangeExtension(outfile_base, to)))
755                         Alert::alert(_("Cannot convert Image (not existing file?)"),
756                                 _("No information for converting from ")
757                                 + from + _(" to ") + to);
758         }
759
760         return RemoveExtension(temp_file);
761 }
762
763
764 int InsetGraphics::latex(Buffer const *buf, ostream & os,
765                          bool /*fragile*/, bool/*fs*/) const
766 {
767         // If there is no file specified or not existing,
768         // just output a message about it in the latex output.
769         lyxerr[Debug::GRAPHICS]
770                 << "insetgraphics::latex: Filename = "
771                 << params().filename << endl;
772
773         // A missing (e)ps-extension is no problem for LaTeX, so
774         // we have to test three different cases
775         string const file_(MakeAbsPath(params().filename, buf->filePath()));
776         bool const file_exists =
777                 !file_.empty() &&
778                 (IsFileReadable(file_) ||               // original
779                  IsFileReadable(file_ + ".eps") ||      // original.eps
780                  IsFileReadable(file_ + ".ps"));        // original.ps
781         string const message = file_exists ?
782                 string() : string("bb = 0 0 200 100, draft, type=eps]");
783         // if !message.empty() than there was no existing file
784         // "filename(.(e)ps)" found. In this case LaTeX
785         // draws only a rectangle with the above bb and the
786         // not found filename in it.
787         lyxerr[Debug::GRAPHICS]
788                 << "\tMessage = \"" << message << '\"' << endl;
789
790         // These variables collect all the latex code that should be before and
791         // after the actual includegraphics command.
792         string before;
793         string after;
794         // Do we want subcaptions?
795         if (params().subcaption) {
796                 before += "\\subfigure[" + params().subcaptionText + "]{";
797                 after = '}';
798         }
799         // We never use the starred form, we use the "clip" option instead.
800         before += "\\includegraphics";
801
802         // Write the options if there are any.
803         string const opts = createLatexOptions();
804         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
805
806         if (!opts.empty() && !message.empty())
807                 before += ("[%\n" + opts + ',' + message);
808         else if (!message.empty())
809                 before += ("[%\n" + message);
810         else if (!opts.empty())
811                 before += ("[%\n" + opts + ']');
812
813         lyxerr[Debug::GRAPHICS]
814                 << "\tBefore = " << before
815                 << "\n\tafter = " << after << endl;
816
817
818         // "nice" means that the buffer is exported to LaTeX format but not
819         //        run through the LaTeX compiler.
820         if (buf->niceFile) {
821                 os << before <<'{' << params().filename << '}' << after;
822                 return 1;
823         }
824
825         // Make the filename relative to the lyx file
826         // and remove the extension so the LaTeX will use whatever is
827         // appropriate (when there are several versions in different formats)
828         string const latex_str = message.empty() ?
829                 (before + '{' + os::external_path(prepareFile(buf)) + '}' + after) :
830                 (before + '{' + params().filename + " not found!}" + after);
831         os << latex_str;
832
833         // Return how many newlines we issued.
834         int const newlines =
835                 int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
836
837         return newlines;
838 }
839
840
841 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
842 {
843         // No graphics in ascii output. Possible to use gifscii to convert
844         // images to ascii approximation.
845         // 1. Convert file to ascii using gifscii
846         // 2. Read ascii output file and add it to the output stream.
847         // at least we send the filename
848         os << '<' << _("Graphic file:") << params().filename << ">\n";
849         return 0;
850 }
851
852
853 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
854 {
855         // No graphics in LinuxDoc output. Should check how/what to add.
856         return 0;
857 }
858
859
860 // For explanation on inserting graphics into DocBook checkout:
861 // http://linuxdoc.org/LDP/LDP-Author-Guide/inserting-pictures.html
862 // See also the docbook guide at http://www.docbook.org/
863 int InsetGraphics::docbook(Buffer const *, ostream & os,
864                            bool /*mixcont*/) const
865 {
866         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
867         // need to switch to MediaObject. However, for now this is sufficient and
868         // easier to use.
869         os << "<graphic fileref=\"&" << graphic_label << ";\">";
870         return 0;
871 }
872
873
874 void InsetGraphics::validate(LaTeXFeatures & features) const
875 {
876         // If we have no image, we should not require anything.
877         if (params().filename.empty())
878                 return ;
879
880         features.includeFile(graphic_label, RemoveExtension(params().filename));
881
882         features.require("graphicx");
883
884         if (params().subcaption)
885                 features.require("subfigure");
886 }
887
888
889 void InsetGraphics::statusChanged()
890 {
891         current_view->updateInset(this, false);
892 }
893
894
895 bool InsetGraphics::setParams(InsetGraphicsParams const & p,
896                               string const & filepath)
897 {
898         // If nothing is changed, just return and say so.
899         if (params() == p && !p.filename.empty()) {
900                 return false;
901         }
902
903         // Copy the new parameters.
904         params_ = p;
905
906         // Update the inset with the new parameters.
907         cache_->update(MakeAbsPath(params().filename, filepath));
908
909         // We have changed data, report it.
910         return true;
911 }
912
913
914 InsetGraphicsParams const & InsetGraphics::params() const
915 {
916         return params_;
917 }
918
919
920 Inset * InsetGraphics::clone(Buffer const & buffer, bool same_id) const
921 {
922         return new InsetGraphics(*this, buffer.filePath(), same_id);
923 }