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