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