]> git.lyx.org Git - features.git/blob - src/insets/InsetGraphics.cpp
39c5d8ad3af427f7d92e1879ffe2c55dd2740da1
[features.git] / src / insets / InsetGraphics.cpp
1 /**
2  * \file InsetGraphics.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Baruch Even
7  * \author Herbert Voß
8  *
9  * Full author contact details are available in file CREDITS.
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     * When loading, if the image is not found in the expected place, try
19       to find it in the clipart, or in the same directory with the image.
20     * The image choosing dialog could show thumbnails of the image formats
21       it knows of, thus selection based on the image instead of based on
22       filename.
23     * Add support for the 'picins' package.
24     * Add support for the 'picinpar' package.
25 */
26
27 /* NOTES:
28  * Fileformat:
29  * The filename is kept in  the lyx file in a relative way, so as to allow
30  * moving the document file and its images with no problem.
31  *
32  *
33  * Conversions:
34  *   Postscript output means EPS figures.
35  *
36  *   PDF output is best done with PDF figures if it's a direct conversion
37  *   or PNG figures otherwise.
38  *      Image format
39  *      from        to
40  *      EPS         epstopdf
41  *      PS          ps2pdf
42  *      JPG/PNG     direct
43  *      PDF         direct
44  *      others      PNG
45  */
46
47 #include <config.h>
48
49 #include "insets/InsetGraphics.h"
50 #include "insets/RenderGraphic.h"
51
52 #include "Buffer.h"
53 #include "BufferView.h"
54 #include "Converter.h"
55 #include "Cursor.h"
56 #include "DispatchResult.h"
57 #include "EmbeddedFiles.h"
58 #include "ErrorList.h"
59 #include "Exporter.h"
60 #include "Format.h"
61 #include "FuncRequest.h"
62 #include "FuncStatus.h"
63 #include "LaTeXFeatures.h"
64 #include "Length.h"
65 #include "Lexer.h"
66 #include "MetricsInfo.h"
67 #include "Mover.h"
68 #include "OutputParams.h"
69 #include "sgml.h"
70 #include "TocBackend.h"
71
72 #include "frontends/alert.h"
73
74 #include "support/convert.h"
75 #include "support/debug.h"
76 #include "support/docstream.h"
77 #include "support/ExceptionMessage.h"
78 #include "support/filetools.h"
79 #include "support/gettext.h"
80 #include "support/lyxlib.h"
81 #include "support/lstrings.h"
82 #include "support/os.h"
83 #include "support/Systemcall.h"
84
85 #include <boost/bind.hpp>
86 #include <boost/tuple/tuple.hpp>
87
88 #include <algorithm>
89 #include <sstream>
90
91 using namespace std;
92 using namespace lyx::support;
93
94 namespace lyx {
95
96 namespace Alert = frontend::Alert;
97
98 namespace {
99
100 /// Find the most suitable image format for images in \p format
101 /// Note that \p format may be unknown (i. e. an empty string)
102 string findTargetFormat(string const & format, OutputParams const & runparams)
103 {
104         // Are we using latex or pdflatex?
105         if (runparams.flavor == OutputParams::PDFLATEX) {
106                 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
107                 Format const * const f = formats.getFormat(format);
108                 // Convert vector graphics to pdf
109                 if (f && f->vectorFormat())
110                         return "pdf";
111                 // pdflatex can use jpeg, png and pdf directly
112                 if (format == "jpg")
113                         return format;
114                 // Convert everything else to png
115                 return "png";
116         }
117         // If it's postscript, we always do eps.
118         LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
119         if (format != "ps")
120                 // any other than ps is changed to eps
121                 return "eps";
122         // let ps untouched
123         return format;
124 }
125
126 } // namespace anon
127
128
129 InsetGraphics::InsetGraphics()
130         : graphic_label(sgml::uniqueID(from_ascii("graph"))),
131           graphic_(new RenderGraphic(this))
132 {}
133
134
135 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
136         : Inset(ig),
137           boost::signals::trackable(),
138                 graphic_label(sgml::uniqueID(from_ascii("graph"))),
139           graphic_(new RenderGraphic(*ig.graphic_, this))
140 {
141         setParams(ig.params());
142 }
143
144
145 Inset * InsetGraphics::clone() const
146 {
147         return new InsetGraphics(*this);
148 }
149
150
151 InsetGraphics::~InsetGraphics()
152 {
153         InsetGraphicsMailer(*this).hideDialog();
154 }
155
156
157 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
158 {
159         switch (cmd.action) {
160         case LFUN_GRAPHICS_EDIT: {
161                 InsetGraphicsParams p;
162                 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
163                 editGraphics(p, buffer());
164                 break;
165         }
166
167         case LFUN_INSET_MODIFY: {
168                 InsetGraphicsParams p;
169                 InsetGraphicsMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
170                 if (!p.filename.empty())
171                         setParams(p);
172                 else
173                         cur.noUpdate();
174                 break;
175         }
176
177         case LFUN_INSET_DIALOG_UPDATE:
178                 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
179                 break;
180
181         case LFUN_MOUSE_RELEASE:
182                 if (!cur.selection())
183                         InsetGraphicsMailer(*this).showDialog(&cur.bv());
184                 break;
185
186         default:
187                 Inset::doDispatch(cur, cmd);
188                 break;
189         }
190 }
191
192
193 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
194                 FuncStatus & flag) const
195 {
196         switch (cmd.action) {
197         case LFUN_GRAPHICS_EDIT:
198         case LFUN_INSET_MODIFY:
199         case LFUN_INSET_DIALOG_UPDATE:
200                 flag.enabled(true);
201                 return true;
202
203         default:
204                 return Inset::getStatus(cur, cmd, flag);
205         }
206 }
207
208
209 void InsetGraphics::registerEmbeddedFiles(EmbeddedFileList & files) const
210 {
211         files.registerFile(params().filename, this, buffer());
212 }
213
214
215 void InsetGraphics::updateEmbeddedFile(EmbeddedFile const & file)
216 {
217         // only properties of an embedded file can be changed here.
218         params_.filename = file;
219 }
220
221
222 void InsetGraphics::edit(Cursor & cur, bool, EntryDirection)
223 {
224         InsetGraphicsMailer(*this).showDialog(&cur.bv());
225 }
226
227
228 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
229 {
230         graphic_->metrics(mi, dim);
231 }
232
233
234 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
235 {
236         graphic_->draw(pi, x, y);
237 }
238
239
240 Inset::EDITABLE InsetGraphics::editable() const
241 {
242         return IS_EDITABLE;
243 }
244
245
246 void InsetGraphics::write(ostream & os) const
247 {
248         os << "Graphics\n";
249         params().Write(os, buffer());
250 }
251
252
253 void InsetGraphics::read(Lexer & lex)
254 {
255         string const token = lex.getString();
256
257         if (token == "Graphics")
258                 readInsetGraphics(lex, buffer().filePath());
259         else
260                 LYXERR(Debug::GRAPHICS, "Not a Graphics inset!");
261
262         params_.filename.enable(buffer().embedded(), &buffer(), false);
263         graphic_->update(params().as_grfxParams());
264 }
265
266
267 void InsetGraphics::readInsetGraphics(Lexer & lex, string const & bufpath)
268 {
269         bool finished = false;
270
271         while (lex.isOK() && !finished) {
272                 lex.next();
273
274                 string const token = lex.getString();
275                 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
276
277                 if (token.empty())
278                         continue;
279
280                 if (token == "\\end_inset") {
281                         finished = true;
282                 } else {
283                         if (!params_.Read(lex, token, bufpath))
284                                 lyxerr << "Unknown token, " << token << ", skipping."
285                                         << endl;
286                 }
287         }
288 }
289
290
291 string const InsetGraphics::createLatexOptions() const
292 {
293         // Calculate the options part of the command, we must do it to a string
294         // stream since we might have a trailing comma that we would like to remove
295         // before writing it to the output stream.
296         ostringstream options;
297         if (!params().bb.empty())
298             options << "bb=" << rtrim(params().bb) << ',';
299         if (params().draft)
300             options << "draft,";
301         if (params().clip)
302             options << "clip,";
303         ostringstream size;
304         double const scl = convert<double>(params().scale);
305         if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
306                 if (!float_equal(scl, 100.0, 0.05))
307                         size << "scale=" << scl / 100.0 << ',';
308         } else {
309                 if (!params().width.zero())
310                         size << "width=" << params().width.asLatexString() << ',';
311                 if (!params().height.zero())
312                         size << "height=" << params().height.asLatexString() << ',';
313                 if (params().keepAspectRatio)
314                         size << "keepaspectratio,";
315         }
316         if (params().scaleBeforeRotation && !size.str().empty())
317                 options << size.str();
318
319         // Make sure rotation angle is not very close to zero;
320         // a float can be effectively zero but not exactly zero.
321         if (!params().rotateAngle.empty()
322                 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
323             options << "angle=" << params().rotateAngle << ',';
324             if (!params().rotateOrigin.empty()) {
325                 options << "origin=" << params().rotateOrigin[0];
326                 if (contains(params().rotateOrigin,"Top"))
327                     options << 't';
328                 else if (contains(params().rotateOrigin,"Bottom"))
329                     options << 'b';
330                 else if (contains(params().rotateOrigin,"Baseline"))
331                     options << 'B';
332                 options << ',';
333             }
334         }
335         if (!params().scaleBeforeRotation && !size.str().empty())
336                 options << size.str();
337
338         if (!params().special.empty())
339             options << params().special << ',';
340
341         string opts = options.str();
342         // delete last ','
343         if (suffixIs(opts, ','))
344                 opts = opts.substr(0, opts.size() - 1);
345
346         return opts;
347 }
348
349
350 docstring const InsetGraphics::toDocbookLength(Length const & len) const
351 {
352         odocstringstream result;
353         switch (len.unit()) {
354                 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
355                         result << len.value() * 65536.0 * 72 / 72.27 << "pt";
356                         break;
357                 case Length::PT: // Point = 1/72.27in = 0.351mm
358                         result << len.value() * 72 / 72.27 << "pt";
359                         break;
360                 case Length::BP: // Big point (72bp = 1in), also PostScript point
361                         result << len.value() << "pt";
362                         break;
363                 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
364                         result << len.value() * 0.376 << "mm";
365                         break;
366                 case Length::MM: // Millimeter = 2.845pt
367                         result << len.value() << "mm";
368                         break;
369                 case Length::PC: // Pica = 12pt = 4.218mm
370                         result << len.value() << "pc";
371                         break;
372                 case Length::CC: // Cicero = 12dd = 4.531mm
373                         result << len.value() * 4.531 << "mm";
374                         break;
375                 case Length::CM: // Centimeter = 10mm = 2.371pc
376                         result << len.value() << "cm";
377                         break;
378                 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
379                         result << len.value() << "in";
380                         break;
381                 case Length::EX: // Height of a small "x" for the current font.
382                         // Obviously we have to compromise here. Any better ratio than 1.5 ?
383                         result << len.value() / 1.5 << "em";
384                         break;
385                 case Length::EM: // Width of capital "M" in current font.
386                         result << len.value() << "em";
387                         break;
388                 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
389                         result << len.value() * 18 << "em";
390                         break;
391                 case Length::PTW: // Percent of TextWidth
392                 case Length::PCW: // Percent of ColumnWidth
393                 case Length::PPW: // Percent of PageWidth
394                 case Length::PLW: // Percent of LineWidth
395                 case Length::PTH: // Percent of TextHeight
396                 case Length::PPH: // Percent of Paper
397                         // Sigh, this will go wrong.
398                         result << len.value() << "%";
399                         break;
400                 default:
401                         result << len.asDocstring();
402                         break;
403         }
404         return result.str();
405 }
406
407 docstring const InsetGraphics::createDocBookAttributes() const
408 {
409         // Calculate the options part of the command, we must do it to a string
410         // stream since we copied the code from createLatexParams() ;-)
411
412         // FIXME: av: need to translate spec -> Docbook XSL spec
413         // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
414         // Right now it only works with my version of db2latex :-)
415
416         odocstringstream options;
417         double const scl = convert<double>(params().scale);
418         if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
419                 if (!float_equal(scl, 100.0, 0.05))
420                         options << " scale=\""
421                                 << static_cast<int>( (scl) + 0.5 )
422                                 << "\" ";
423         } else {
424                 if (!params().width.zero()) {
425                         options << " width=\"" << toDocbookLength(params().width)  << "\" ";
426                 }
427                 if (!params().height.zero()) {
428                         options << " depth=\"" << toDocbookLength(params().height)  << "\" ";
429                 }
430                 if (params().keepAspectRatio) {
431                         // This will be irrelevant unless both width and height are set
432                         options << "scalefit=\"1\" ";
433                 }
434         }
435
436
437         if (!params().special.empty())
438                 options << from_ascii(params().special) << " ";
439
440         // trailing blanks are ok ...
441         return options.str();
442 }
443
444
445 namespace {
446
447 enum GraphicsCopyStatus {
448         SUCCESS,
449         FAILURE,
450         IDENTICAL_PATHS,
451         IDENTICAL_CONTENTS
452 };
453
454
455 pair<GraphicsCopyStatus, FileName> const
456 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
457 {
458         LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
459         unsigned long const checksum_in  = file_in.checksum();
460         unsigned long const checksum_out = file_out.checksum();
461
462         if (checksum_in == checksum_out)
463                 // Nothing to do...
464                 return make_pair(IDENTICAL_CONTENTS, file_out);
465
466         Mover const & mover = getMover(formats.getFormatFromFile(file_in));
467         bool const success = mover.copy(file_in, file_out);
468         if (!success) {
469                 // FIXME UNICODE
470                 LYXERR(Debug::GRAPHICS,
471                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
472                                                            "into the temporary directory."),
473                                                 from_utf8(file_in.absFilename()))));
474         }
475
476         GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
477         return make_pair(status, file_out);
478 }
479
480
481 pair<GraphicsCopyStatus, FileName> const
482 copyToDirIfNeeded(DocFileName const & file, string const & dir)
483 {
484         string const file_in = file.absFilename();
485         string const only_path = onlyPath(file_in);
486         if (rtrim(onlyPath(file_in) , "/") == rtrim(dir, "/"))
487                 return make_pair(IDENTICAL_PATHS, file_in);
488
489         string mangled = file.mangledFilename();
490         if (file.isZipped()) {
491                 // We need to change _eps.gz to .eps.gz. The mangled name is
492                 // still unique because of the counter in mangledFilename().
493                 // We can't just call mangledFilename() with the zip
494                 // extension removed, because base.eps and base.eps.gz may
495                 // have different content but would get the same mangled
496                 // name in this case.
497                 string const base = removeExtension(file.unzippedFilename());
498                 string::size_type const ext_len = file_in.length() - base.length();
499                 mangled[mangled.length() - ext_len] = '.';
500         }
501         FileName const file_out(makeAbsPath(mangled, dir));
502
503         return copyFileIfNeeded(file, file_out);
504 }
505
506
507 string const stripExtensionIfPossible(string const & file, bool nice)
508 {
509         // Remove the extension so the LaTeX compiler will use whatever
510         // is appropriate (when there are several versions in different
511         // formats).
512         // Do this only if we are not exporting for internal usage, because
513         // pdflatex prefers png over pdf and it would pick up the png images
514         // that we generate for preview.
515         // This works only if the filename contains no dots besides
516         // the just removed one. We can fool here by replacing all
517         // dots with a macro whose definition is just a dot ;-)
518         // The automatic format selection does not work if the file
519         // name is escaped.
520         string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
521         if (!nice || contains(latex_name, '"'))
522                 return latex_name;
523         return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
524 }
525
526
527 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
528 {
529         // No conversion is needed. LaTeX can handle the graphic file as is.
530         // This is true even if the orig_file is compressed.
531         string const to_format = formats.getFormat(to)->extension();
532         string const file_format = getExtension(file);
533         // for latex .ps == .eps
534         if (to_format == file_format ||
535             (to_format == "eps" && file_format ==  "ps") ||
536             (to_format ==  "ps" && file_format == "eps"))
537                 return stripExtensionIfPossible(file, nice);
538         return latex_path(file, EXCLUDE_EXTENSION);
539 }
540
541 } // namespace anon
542
543
544 string InsetGraphics::prepareFile(OutputParams const & runparams) const
545 {
546         // The following code depends on non-empty filenames
547         if (params().filename.empty())
548                 return string();
549
550         string const orig_file = params().filename.availableFile().absFilename();
551         // this is for dryrun and display purposes, do not use latexFilename
552         string const rel_file = params().filename.relFilename(buffer().filePath());
553
554         // previewing source code, no file copying or file format conversion
555         if (runparams.dryrun)
556                 return stripExtensionIfPossible(rel_file, runparams.nice);
557
558         // temp_file will contain the file for LaTeX to act on if, for example,
559         // we move it to a temp dir or uncompress it.
560         FileName temp_file = params().filename.availableFile();
561
562         // The master buffer. This is useful when there are multiple levels
563         // of include files
564         Buffer const * masterBuffer = buffer().masterBuffer();
565
566         // Return the output name if we are inside a comment or the file does
567         // not exist.
568         // We are not going to change the extension or using the name of the
569         // temporary file, the code is already complicated enough.
570         if (runparams.inComment || !params().filename.isReadableFile())
571                 return params().filename.outputFilename(masterBuffer->filePath());
572
573         // We place all temporary files in the master buffer's temp dir.
574         // This is possible because we use mangled file names.
575         // This is necessary for DVI export.
576         string const temp_path = masterBuffer->temppath();
577
578         GraphicsCopyStatus status;
579         boost::tie(status, temp_file) =
580                         copyToDirIfNeeded(params().filename.availableFile(), temp_path);
581
582         if (status == FAILURE)
583                 return orig_file;
584
585         // a relative filename should be relative to the master buffer.
586         // "nice" means that the buffer is exported to LaTeX format but not
587         // run through the LaTeX compiler.
588         string output_file = runparams.nice ?
589                 params().filename.outputFilename(masterBuffer->filePath()) :
590                 onlyFilename(temp_file.absFilename());
591
592         if (runparams.nice && !isValidLaTeXFilename(output_file)) {
593                 frontend::Alert::warning(_("Invalid filename"),
594                                          _("The following filename is likely to cause trouble "
595                                            "when running the exported file through LaTeX: ") +
596                                             from_utf8(output_file));
597         }
598
599         FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
600         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
601                         "latex" : "pdflatex";
602
603         // If the file is compressed and we have specified that it
604         // should not be uncompressed, then just return its name and
605         // let LaTeX do the rest!
606         if (params().filename.isZipped()) {
607                 if (params().noUnzip) {
608                         // We don't know whether latex can actually handle
609                         // this file, but we can't check, because that would
610                         // mean to unzip the file and thereby making the
611                         // noUnzip parameter meaningless.
612                         LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
613
614                         FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
615                         if (runparams.nice) {
616                                 runparams.exportdata->addExternalFile(tex_format,
617                                                 bb_orig_file,
618                                                 changeExtension(output_file, "bb"));
619                         } else {
620                                 // LaTeX needs the bounding box file in the
621                                 // tmp dir
622                                 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
623                                 boost::tie(status, bb_file) =
624                                         copyFileIfNeeded(bb_orig_file, bb_file);
625                                 if (status == FAILURE)
626                                         return orig_file;
627                                 runparams.exportdata->addExternalFile(tex_format,
628                                                 bb_file);
629                         }
630                         runparams.exportdata->addExternalFile(tex_format,
631                                         source_file, output_file);
632                         runparams.exportdata->addExternalFile("dvi",
633                                         source_file, output_file);
634                         // We can't strip the extension, because we don't know
635                         // the unzipped file format
636                         return latex_path(output_file, EXCLUDE_EXTENSION);
637                 }
638
639                 FileName const unzipped_temp_file =
640                         FileName(unzippedFileName(temp_file.absFilename()));
641                 output_file = unzippedFileName(output_file);
642                 source_file = FileName(unzippedFileName(source_file.absFilename()));
643                 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
644                         // temp_file has been unzipped already and
645                         // orig_file has not changed in the meantime.
646                         temp_file = unzipped_temp_file;
647                         LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
648                 } else {
649                         // unzipped_temp_file does not exist or is too old
650                         temp_file = unzipFile(temp_file);
651                         LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
652                 }
653         }
654
655         string const from = formats.getFormatFromFile(temp_file);
656         if (from.empty())
657                 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
658
659         string const to   = findTargetFormat(from, runparams);
660         string const ext  = formats.extension(to);
661         LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
662
663         // We're going to be running the exported buffer through the LaTeX
664         // compiler, so must ensure that LaTeX can cope with the graphics
665         // file format.
666
667         LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
668
669         if (from == to) {
670                 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
671                         // The LaTeX compiler will not be able to determine
672                         // the file format from the extension, so we must
673                         // change it.
674                         FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
675                         if (temp_file.moveTo(new_file)) {
676                                 temp_file = new_file;
677                                 output_file = changeExtension(output_file, ext);
678                                 source_file = FileName(changeExtension(source_file.absFilename(), ext));
679                         } else {
680                                 LYXERR(Debug::GRAPHICS, "Could not rename file `"
681                                         << temp_file << "' to `" << new_file << "'.");
682                         }
683                 }
684                 // The extension of temp_file might be != ext!
685                 runparams.exportdata->addExternalFile(tex_format, source_file,
686                                                       output_file);
687                 runparams.exportdata->addExternalFile("dvi", source_file,
688                                                       output_file);
689                 return stripExtensionIfPossible(output_file, to, runparams.nice);
690         }
691
692         FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
693         string const output_to_file = changeExtension(output_file, ext);
694
695         // Do we need to perform the conversion?
696         // Yes if to_file does not exist or if temp_file is newer than to_file
697         if (compare_timestamps(temp_file, to_file) < 0) {
698                 // FIXME UNICODE
699                 LYXERR(Debug::GRAPHICS,
700                         to_utf8(bformat(_("No conversion of %1$s is needed after all"),
701                                    from_utf8(rel_file))));
702                 runparams.exportdata->addExternalFile(tex_format, to_file,
703                                                       output_to_file);
704                 runparams.exportdata->addExternalFile("dvi", to_file,
705                                                       output_to_file);
706                 return stripExtensionIfPossible(output_to_file, runparams.nice);
707         }
708
709         LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
710                 << "\tA copy has been made and convert is to be called with:\n"
711                 << "\tfile to convert = " << temp_file << '\n'
712                 << "\t from " << from << " to " << to);
713
714         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
715         ErrorList el;
716         if (theConverters().convert(&buffer(), temp_file, to_file, params().filename,
717                                from, to, el,
718                                Converters::try_default | Converters::try_cache)) {
719                 runparams.exportdata->addExternalFile(tex_format,
720                                 to_file, output_to_file);
721                 runparams.exportdata->addExternalFile("dvi",
722                                 to_file, output_to_file);
723         }
724
725         return stripExtensionIfPossible(output_to_file, runparams.nice);
726 }
727
728
729 int InsetGraphics::latex(odocstream & os,
730                          OutputParams const & runparams) const
731 {
732         // If there is no file specified or not existing,
733         // just output a message about it in the latex output.
734         LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
735                 << params().filename.absFilename());
736
737         bool const file_exists = !params().filename.empty()
738                         && params().filename.isReadableFile();
739         string const message = file_exists ?
740                 string() : string("bb = 0 0 200 100, draft, type=eps");
741         // if !message.empty() then there was no existing file
742         // "filename" found. In this case LaTeX
743         // draws only a rectangle with the above bb and the
744         // not found filename in it.
745         LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
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
752         if (runparams.moving_arg)
753                 before += "\\protect";
754
755         // We never use the starred form, we use the "clip" option instead.
756         before += "\\includegraphics";
757
758         // Write the options if there are any.
759         string const opts = createLatexOptions();
760         LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
761
762         if (!opts.empty() && !message.empty())
763                 before += ('[' + opts + ',' + message + ']');
764         else if (!opts.empty() || !message.empty())
765                 before += ('[' + opts + message + ']');
766
767         LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
768
769         string latex_str = before + '{';
770         // Convert the file if necessary.
771         // Remove the extension so LaTeX will use whatever is appropriate
772         // (when there are several versions in different formats)
773         latex_str += prepareFile(runparams);
774         latex_str += '}' + after;
775         // FIXME UNICODE
776         os << from_utf8(latex_str);
777
778         LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
779         // Return how many newlines we issued.
780         return int(count(latex_str.begin(), latex_str.end(),'\n'));
781 }
782
783
784 int InsetGraphics::plaintext(odocstream & os, OutputParams const &) const
785 {
786         // No graphics in ascii output. Possible to use gifscii to convert
787         // images to ascii approximation.
788         // 1. Convert file to ascii using gifscii
789         // 2. Read ascii output file and add it to the output stream.
790         // at least we send the filename
791         // FIXME UNICODE
792         // FIXME: We have no idea what the encoding of the filename is
793
794         docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
795                                       from_utf8(params().filename.absFilename()));
796         os << '<' << str << '>';
797
798         return 2 + str.size();
799 }
800
801
802 static int writeImageObject(char const * format, odocstream & os,
803         OutputParams const & runparams, docstring const & graphic_label,
804         docstring const & attributes)
805 {
806         if (runparams.flavor != OutputParams::XML)
807                 os << "<![ %output.print." << format
808                          << "; [" << endl;
809
810         os <<"<imageobject><imagedata fileref=\"&"
811                  << graphic_label
812                  << ";."
813                  << format
814                  << "\" "
815                  << attributes;
816
817         if (runparams.flavor == OutputParams::XML)
818                 os <<  " role=\"" << format << "\"/>" ;
819         else
820                 os << " format=\"" << format << "\">" ;
821
822         os << "</imageobject>";
823
824         if (runparams.flavor != OutputParams::XML)
825                 os << endl << "]]>" ;
826
827         return runparams.flavor == OutputParams::XML ? 0 : 2;
828 }
829
830
831 // For explanation on inserting graphics into DocBook checkout:
832 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
833 // See also the docbook guide at http://www.docbook.org/
834 int InsetGraphics::docbook(odocstream & os,
835                            OutputParams const & runparams) const
836 {
837         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
838         // need to switch to MediaObject. However, for now this is sufficient and
839         // easier to use.
840         if (runparams.flavor == OutputParams::XML)
841                 runparams.exportdata->addExternalFile("docbook-xml",
842                                                       params().filename);
843         else
844                 runparams.exportdata->addExternalFile("docbook",
845                                                       params().filename);
846
847         os << "<inlinemediaobject>";
848
849         int r = 0;
850         docstring attributes = createDocBookAttributes();
851         r += writeImageObject("png", os, runparams, graphic_label, attributes);
852         r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
853         r += writeImageObject("eps", os, runparams, graphic_label, attributes);
854         r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
855
856         os << "</inlinemediaobject>";
857         return r;
858 }
859
860
861 void InsetGraphics::validate(LaTeXFeatures & features) const
862 {
863         // If we have no image, we should not require anything.
864         if (params().filename.empty())
865                 return;
866
867         features.includeFile(graphic_label,
868                              removeExtension(params().filename.absFilename()));
869
870         features.require("graphicx");
871
872         if (features.runparams().nice) {
873                 Buffer const * masterBuffer = features.buffer().masterBuffer();
874                 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->filePath()));
875                 if (contains(rel_file, "."))
876                         features.require("lyxdot");
877         }
878 }
879
880
881 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
882 {
883         // If nothing is changed, just return and say so.
884         if (params() == p && !p.filename.empty())
885                 return false;
886
887         // Copy the new parameters.
888         params_ = p;
889
890         // Update the display using the new parameters.
891         graphic_->update(params().as_grfxParams());
892
893         // We have changed data, report it.
894         return true;
895 }
896
897
898 InsetGraphicsParams const & InsetGraphics::params() const
899 {
900         return params_;
901 }
902
903
904 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
905                                  Buffer const & buffer) const
906 {
907         formats.edit(buffer, p.filename,
908                      formats.getFormatFromFile(p.filename));
909 }
910
911
912 void InsetGraphics::addToToc(ParConstIterator const & cpit) const
913 {
914         TocBackend & backend = buffer().tocBackend();
915
916         docstring str = params_.filename.displayName();
917         if (params_.filename.embedded()) {
918                 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
919                 str += _(" (embedded)");
920         }
921         backend.toc("graphics").push_back(TocItem(cpit, 0, str));
922 }
923
924
925 string const InsetGraphicsMailer::name_("graphics");
926
927 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
928         : inset_(inset)
929 {}
930
931
932 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
933 {
934         return params2string(inset_.params(), buffer);
935 }
936
937
938 void InsetGraphicsMailer::string2params(string const & in,
939                                         Buffer const & buffer,
940                                         InsetGraphicsParams & params)
941 {
942         params = InsetGraphicsParams();
943         if (in.empty())
944                 return;
945
946         istringstream data(in);
947         Lexer lex(0,0);
948         lex.setStream(data);
949
950         string name;
951         lex >> name;
952         if (!lex || name != name_)
953                 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
954
955         InsetGraphics inset;
956         inset.readInsetGraphics(lex, buffer.filePath());
957         params = inset.params();
958 }
959
960
961 string const
962 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
963                                    Buffer const & buffer)
964 {
965         ostringstream data;
966         data << name_ << ' ';
967         params.Write(data, buffer);
968         data << "\\end_inset\n";
969         return data.str();
970 }
971
972
973 } // namespace lyx