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