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