]> git.lyx.org Git - lyx.git/blob - src/insets/InsetGraphics.cpp
26e8be32c80e023c6a7513d841101bdf2d553bbf
[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                                         << std::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 std::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 std::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(support::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 std::make_pair(status, file_out);
494 }
495
496
497 std::pair<GraphicsCopyStatus, FileName> const
498 copyToDirIfNeeded(DocFileName const & file, string const & dir)
499 {
500         using support::rtrim;
501
502         string const file_in = file.absFilename();
503         string const only_path = support::onlyPath(file_in);
504         if (rtrim(support::onlyPath(file_in) , "/") == rtrim(dir, "/"))
505                 return std::make_pair(IDENTICAL_PATHS, file_in);
506
507         string mangled = file.mangledFilename();
508         if (file.isZipped()) {
509                 // We need to change _eps.gz to .eps.gz. The mangled name is
510                 // still unique because of the counter in mangledFilename().
511                 // We can't just call mangledFilename() with the zip
512                 // extension removed, because base.eps and base.eps.gz may
513                 // have different content but would get the same mangled
514                 // name in this case.
515                 string const base = removeExtension(file.unzippedFilename());
516                 string::size_type const ext_len = file_in.length() - base.length();
517                 mangled[mangled.length() - ext_len] = '.';
518         }
519         FileName const file_out(support::makeAbsPath(mangled, dir));
520
521         return copyFileIfNeeded(file, file_out);
522 }
523
524
525 string const stripExtensionIfPossible(string const & file, bool nice)
526 {
527         // Remove the extension so the LaTeX compiler will use whatever
528         // is appropriate (when there are several versions in different
529         // formats).
530         // Do this only if we are not exporting for internal usage, because
531         // pdflatex prefers png over pdf and it would pick up the png images
532         // that we generate for preview.
533         // This works only if the filename contains no dots besides
534         // the just removed one. We can fool here by replacing all
535         // dots with a macro whose definition is just a dot ;-)
536         // The automatic format selection does not work if the file
537         // name is escaped.
538         string const latex_name = latex_path(file,
539                                              support::EXCLUDE_EXTENSION);
540         if (!nice || contains(latex_name, '"'))
541                 return latex_name;
542         return latex_path(removeExtension(file),
543                           support::PROTECT_EXTENSION,
544                           support::ESCAPE_DOTS);
545 }
546
547
548 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
549 {
550         // No conversion is needed. LaTeX can handle the graphic file as is.
551         // This is true even if the orig_file is compressed.
552         string const to_format = formats.getFormat(to)->extension();
553         string const file_format = getExtension(file);
554         // for latex .ps == .eps
555         if (to_format == file_format ||
556             (to_format == "eps" && file_format ==  "ps") ||
557             (to_format ==  "ps" && file_format == "eps"))
558                 return stripExtensionIfPossible(file, nice);
559         return latex_path(file, support::EXCLUDE_EXTENSION);
560 }
561
562 } // namespace anon
563
564
565 string const InsetGraphics::prepareFile(Buffer const & buf,
566                                         OutputParams const & runparams) const
567 {
568         // The following code depends on non-empty filenames
569         if (params().filename.empty())
570                 return string();
571
572         string const orig_file = params().filename.absFilename();
573         string const rel_file = params().filename.relFilename(buf.filePath());
574
575         // previewing source code, no file copying or file format conversion
576         if (runparams.dryrun)
577                 return stripExtensionIfPossible(rel_file, runparams.nice);
578
579         // temp_file will contain the file for LaTeX to act on if, for example,
580         // we move it to a temp dir or uncompress it.
581         FileName temp_file = params().filename;
582
583         // The master buffer. This is useful when there are multiple levels
584         // of include files
585         Buffer const * masterBuffer = buf.masterBuffer();
586
587         // Return the output name if we are inside a comment or the file does
588         // not exist.
589         // We are not going to change the extension or using the name of the
590         // temporary file, the code is already complicated enough.
591         if (runparams.inComment || !params().filename.isReadableFile())
592                 return params().filename.outputFilename(masterBuffer->filePath());
593
594         // We place all temporary files in the master buffer's temp dir.
595         // This is possible because we use mangled file names.
596         // This is necessary for DVI export.
597         string const temp_path = masterBuffer->temppath();
598
599         GraphicsCopyStatus status;
600         boost::tie(status, temp_file) =
601                         copyToDirIfNeeded(params().filename, temp_path);
602
603         if (status == FAILURE)
604                 return orig_file;
605
606         // a relative filename should be relative to the master buffer.
607         // "nice" means that the buffer is exported to LaTeX format but not
608         // run through the LaTeX compiler.
609         string output_file = runparams.nice ?
610                 params().filename.outputFilename(masterBuffer->filePath()) :
611                 onlyFilename(temp_file.absFilename());
612
613         if (runparams.nice && !isValidLaTeXFilename(output_file)) {
614                 frontend::Alert::warning(_("Invalid filename"),
615                                          _("The following filename is likely to cause trouble "
616                                            "when running the exported file through LaTeX: ") +
617                                             from_utf8(output_file));
618         }
619
620         FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
621         string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
622                         "latex" : "pdflatex";
623
624         // If the file is compressed and we have specified that it
625         // should not be uncompressed, then just return its name and
626         // let LaTeX do the rest!
627         if (params().filename.isZipped()) {
628                 if (params().noUnzip) {
629                         // We don't know whether latex can actually handle
630                         // this file, but we can't check, because that would
631                         // mean to unzip the file and thereby making the
632                         // noUnzip parameter meaningless.
633                         LYXERR(Debug::GRAPHICS, "\tpass zipped file to LaTeX.");
634
635                         FileName const bb_orig_file = FileName(changeExtension(orig_file, "bb"));
636                         if (runparams.nice) {
637                                 runparams.exportdata->addExternalFile(tex_format,
638                                                 bb_orig_file,
639                                                 changeExtension(output_file, "bb"));
640                         } else {
641                                 // LaTeX needs the bounding box file in the
642                                 // tmp dir
643                                 FileName bb_file = FileName(changeExtension(temp_file.absFilename(), "bb"));
644                                 boost::tie(status, bb_file) =
645                                         copyFileIfNeeded(bb_orig_file, bb_file);
646                                 if (status == FAILURE)
647                                         return orig_file;
648                                 runparams.exportdata->addExternalFile(tex_format,
649                                                 bb_file);
650                         }
651                         runparams.exportdata->addExternalFile(tex_format,
652                                         source_file, output_file);
653                         runparams.exportdata->addExternalFile("dvi",
654                                         source_file, output_file);
655                         // We can't strip the extension, because we don't know
656                         // the unzipped file format
657                         return latex_path(output_file,
658                                           support::EXCLUDE_EXTENSION);
659                 }
660
661                 FileName const unzipped_temp_file =
662                         FileName(unzippedFileName(temp_file.absFilename()));
663                 output_file = unzippedFileName(output_file);
664                 source_file = FileName(unzippedFileName(source_file.absFilename()));
665                 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
666                         // temp_file has been unzipped already and
667                         // orig_file has not changed in the meantime.
668                         temp_file = unzipped_temp_file;
669                         LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
670                 } else {
671                         // unzipped_temp_file does not exist or is too old
672                         temp_file = unzipFile(temp_file);
673                         LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
674                 }
675         }
676
677         string const from = formats.getFormatFromFile(temp_file);
678         if (from.empty())
679                 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
680
681         string const to   = findTargetFormat(from, runparams);
682         string const ext  = formats.extension(to);
683         LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
684
685         // We're going to be running the exported buffer through the LaTeX
686         // compiler, so must ensure that LaTeX can cope with the graphics
687         // file format.
688
689         LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
690
691         if (from == to) {
692                 if (!runparams.nice && getExtension(temp_file.absFilename()) != ext) {
693                         // The LaTeX compiler will not be able to determine
694                         // the file format from the extension, so we must
695                         // change it.
696                         FileName const new_file = FileName(changeExtension(temp_file.absFilename(), ext));
697                         if (support::rename(temp_file, new_file)) {
698                                 temp_file = new_file;
699                                 output_file = changeExtension(output_file, ext);
700                                 source_file = FileName(changeExtension(source_file.absFilename(), ext));
701                         } else {
702                                 LYXERR(Debug::GRAPHICS, "Could not rename file `"
703                                         << temp_file << "' to `" << new_file << "'.");
704                         }
705                 }
706                 // The extension of temp_file might be != ext!
707                 runparams.exportdata->addExternalFile(tex_format, source_file,
708                                                       output_file);
709                 runparams.exportdata->addExternalFile("dvi", source_file,
710                                                       output_file);
711                 return stripExtensionIfPossible(output_file, to, runparams.nice);
712         }
713
714         FileName const to_file = FileName(changeExtension(temp_file.absFilename(), ext));
715         string const output_to_file = changeExtension(output_file, ext);
716
717         // Do we need to perform the conversion?
718         // Yes if to_file does not exist or if temp_file is newer than to_file
719         if (compare_timestamps(temp_file, to_file) < 0) {
720                 // FIXME UNICODE
721                 LYXERR(Debug::GRAPHICS,
722                         to_utf8(bformat(_("No conversion of %1$s is needed after all"),
723                                    from_utf8(rel_file))));
724                 runparams.exportdata->addExternalFile(tex_format, to_file,
725                                                       output_to_file);
726                 runparams.exportdata->addExternalFile("dvi", to_file,
727                                                       output_to_file);
728                 return stripExtensionIfPossible(output_to_file, runparams.nice);
729         }
730
731         LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
732                 << "\tA copy has been made and convert is to be called with:\n"
733                 << "\tfile to convert = " << temp_file << '\n'
734                 << "\t from " << from << " to " << to);
735
736         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
737         ErrorList el;
738         if (theConverters().convert(&buf, temp_file, to_file, params().filename,
739                                from, to, el,
740                                Converters::try_default | Converters::try_cache)) {
741                 runparams.exportdata->addExternalFile(tex_format,
742                                 to_file, output_to_file);
743                 runparams.exportdata->addExternalFile("dvi",
744                                 to_file, output_to_file);
745         }
746
747         return stripExtensionIfPossible(output_to_file, runparams.nice);
748 }
749
750
751 int InsetGraphics::latex(Buffer const & buf, odocstream & os,
752                          OutputParams const & runparams) const
753 {
754         // If there is no file specified or not existing,
755         // just output a message about it in the latex output.
756         LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
757                 << params().filename.absFilename());
758
759         string const relative_file =
760                 params().filename.relFilename(buf.filePath());
761
762         bool const file_exists = !params().filename.empty()
763                         && params().filename.isReadableFile();
764         string const message = file_exists ?
765                 string() : string("bb = 0 0 200 100, draft, type=eps");
766         // if !message.empty() then there was no existing file
767         // "filename" found. In this case LaTeX
768         // draws only a rectangle with the above bb and the
769         // not found filename in it.
770         LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
771
772         // These variables collect all the latex code that should be before and
773         // after the actual includegraphics command.
774         string before;
775         string after;
776         // Do we want subcaptions?
777         if (params().subcaption) {
778                 if (runparams.moving_arg)
779                         before += "\\protect";
780                 before += "\\subfigure[" + params().subcaptionText + "]{";
781                 after = '}';
782         }
783
784         if (runparams.moving_arg)
785                 before += "\\protect";
786
787         // We never use the starred form, we use the "clip" option instead.
788         before += "\\includegraphics";
789
790         // Write the options if there are any.
791         string const opts = createLatexOptions();
792         LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
793
794         if (!opts.empty() && !message.empty())
795                 before += ('[' + opts + ',' + message + ']');
796         else if (!opts.empty() || !message.empty())
797                 before += ('[' + opts + message + ']');
798
799         LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
800
801         string latex_str = before + '{';
802         // Convert the file if necessary.
803         // Remove the extension so LaTeX will use whatever is appropriate
804         // (when there are several versions in different formats)
805         latex_str += prepareFile(buf, runparams);
806         latex_str += '}' + after;
807         // FIXME UNICODE
808         os << from_utf8(latex_str);
809
810         LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
811         // Return how many newlines we issued.
812         return int(std::count(latex_str.begin(), latex_str.end(),'\n'));
813 }
814
815
816 int InsetGraphics::plaintext(Buffer const & buf, odocstream & os,
817                              OutputParams const &) const
818 {
819         // No graphics in ascii output. Possible to use gifscii to convert
820         // images to ascii approximation.
821         // 1. Convert file to ascii using gifscii
822         // 2. Read ascii output file and add it to the output stream.
823         // at least we send the filename
824         // FIXME UNICODE
825         // FIXME: We have no idea what the encoding of the filename is
826
827         docstring const str = bformat(buf.B_("Graphics file: %1$s"),
828                                       from_utf8(params().filename.absFilename()));
829         os << '<' << str << '>';
830
831         return 2 + str.size();
832 }
833
834
835 static int writeImageObject(char const * format, odocstream & os,
836         OutputParams const & runparams, docstring const & graphic_label,
837         docstring const & attributes)
838 {
839         if (runparams.flavor != OutputParams::XML)
840                 os << "<![ %output.print." << format
841                          << "; [" << std::endl;
842
843         os <<"<imageobject><imagedata fileref=\"&"
844                  << graphic_label
845                  << ";."
846                  << format
847                  << "\" "
848                  << attributes;
849
850         if (runparams.flavor == OutputParams::XML)
851                 os <<  " role=\"" << format << "\"/>" ;
852         else
853                 os << " format=\"" << format << "\">" ;
854
855         os << "</imageobject>";
856
857         if (runparams.flavor != OutputParams::XML)
858                 os << std::endl << "]]>" ;
859
860         return runparams.flavor == OutputParams::XML ? 0 : 2;
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 * masterBuffer = features.buffer().masterBuffer();
907                 string const rel_file = removeExtension(params().filename.relFilename(masterBuffer->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);
991         data << "\\end_inset\n";
992         return data.str();
993 }
994
995
996 } // namespace lyx