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