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