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