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