]> git.lyx.org Git - lyx.git/blob - src/insets/InsetGraphics.cpp
a07296c6eecc03fc0e4562c94f042802080cd01b
[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 "InsetIterator.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 "output_xhtml.h"
70 #include "sgml.h"
71 #include "texstream.h"
72 #include "TocBackend.h"
73
74 #include "frontends/alert.h"
75 #include "frontends/Application.h"
76
77 #include "support/convert.h"
78 #include "support/debug.h"
79 #include "support/docstream.h"
80 #include "support/ExceptionMessage.h"
81 #include "support/filetools.h"
82 #include "support/gettext.h"
83 #include "support/lyxlib.h"
84 #include "support/lstrings.h"
85 #include "support/os.h"
86 #include "support/Systemcall.h"
87
88 #include <algorithm>
89 #include <sstream>
90 #include <tuple>
91
92 using namespace std;
93 using namespace lyx::support;
94
95 namespace lyx {
96
97 namespace Alert = frontend::Alert;
98
99 namespace {
100
101 /// Find the most suitable image format for images in \p format
102 /// Note that \p format may be unknown (i. e. an empty string)
103 string findTargetFormat(string const & format, OutputParams const & runparams)
104 {
105         // Are we using latex or XeTeX/LuaTeX/pdflatex?
106         if (runparams.flavor == OutputParams::PDFLATEX
107             || runparams.flavor == OutputParams::XETEX
108             || runparams.flavor == OutputParams::LUATEX) {
109                 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
110                 Format const * const f = theFormats().getFormat(format);
111                 // Convert vector graphics to pdf
112                 if (f && f->vectorFormat())
113                         return "pdf6";
114                 // pdflatex can use jpeg, png and pdf directly
115                 if (format == "jpg")
116                         return format;
117                 // Convert everything else to png
118                 return "png";
119         }
120         // for HTML, we leave the known formats and otherwise convert to png
121         if (runparams.flavor == OutputParams::HTML) {
122                 Format const * const f = theFormats().getFormat(format);
123                 // Convert vector graphics to svg
124                 if (f && f->vectorFormat() && theConverters().isReachable(format, "svg"))
125                         return "svg";
126                 // Leave the known formats alone
127                 if (format == "jpg" || format == "png" || format == "gif")
128                         return format;
129                 // Convert everything else to png
130                 return "png";
131         }
132         // If it's postscript, we always do eps.
133         LYXERR(Debug::GRAPHICS, "findTargetFormat: PostScript mode");
134         if (format != "ps")
135                 // any other than ps is changed to eps
136                 return "eps";
137         // let ps untouched
138         return format;
139 }
140
141
142 void readInsetGraphics(Lexer & lex, Buffer const & buf, bool allowOrigin,
143         InsetGraphicsParams & params)
144 {
145         bool finished = false;
146
147         while (lex.isOK() && !finished) {
148                 lex.next();
149
150                 string const token = lex.getString();
151                 LYXERR(Debug::GRAPHICS, "Token: '" << token << '\'');
152
153                 if (token.empty())
154                         continue;
155
156                 if (token == "\\end_inset") {
157                         finished = true;
158                 } else {
159                         if (!params.Read(lex, token, buf, allowOrigin))
160                                 lyxerr << "Unknown token, "
161                                        << token
162                                        << ", skipping."
163                                        << endl;
164                 }
165         }
166 }
167
168 } // namespace
169
170
171 InsetGraphics::InsetGraphics(Buffer * buf)
172         : Inset(buf), graphic_label(sgml::uniqueID(from_ascii("graph"))),
173           graphic_(new RenderGraphic(this))
174 {
175 }
176
177
178 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
179         : Inset(ig),
180           graphic_label(sgml::uniqueID(from_ascii("graph"))),
181           graphic_(new RenderGraphic(*ig.graphic_, this))
182 {
183         setParams(ig.params());
184 }
185
186
187 Inset * InsetGraphics::clone() const
188 {
189         return new InsetGraphics(*this);
190 }
191
192
193 InsetGraphics::~InsetGraphics()
194 {
195         hideDialogs("graphics", this);
196         delete graphic_;
197 }
198
199
200 void InsetGraphics::doDispatch(Cursor & cur, FuncRequest & cmd)
201 {
202         switch (cmd.action()) {
203         case LFUN_INSET_EDIT: {
204                 InsetGraphicsParams p = params();
205                 if (!cmd.argument().empty())
206                         string2params(to_utf8(cmd.argument()), buffer(), p);
207                 editGraphics(p);
208                 break;
209         }
210
211         case LFUN_INSET_MODIFY: {
212                 if (cmd.getArg(0) != "graphics") {
213                         Inset::doDispatch(cur, cmd);
214                         break;
215                 }
216
217                 InsetGraphicsParams p;
218                 string2params(to_utf8(cmd.argument()), buffer(), p);
219                 if (p.filename.empty()) {
220                         cur.noScreenUpdate();
221                         break;
222                 }
223
224                 cur.recordUndo();
225                 setParams(p);
226                 // if the inset is part of a graphics group, all the
227                 // other members should be updated too.
228                 if (!params_.groupId.empty())
229                         graphics::unifyGraphicsGroups(buffer(),
230                                                       to_utf8(cmd.argument()));
231                 break;
232         }
233
234         case LFUN_INSET_DIALOG_UPDATE:
235                 cur.bv().updateDialog("graphics", params2string(params(), buffer()));
236                 break;
237
238         case LFUN_GRAPHICS_RELOAD:
239                 params_.filename.refresh();
240                 graphic_->reload();
241                 break;
242
243         default:
244                 Inset::doDispatch(cur, cmd);
245                 break;
246         }
247 }
248
249
250 bool InsetGraphics::getStatus(Cursor & cur, FuncRequest const & cmd,
251                 FuncStatus & flag) const
252 {
253         switch (cmd.action()) {
254         case LFUN_INSET_MODIFY:
255                 if (cmd.getArg(0) != "graphics")
256                         return Inset::getStatus(cur, cmd, flag);
257         // fall through
258         case LFUN_INSET_EDIT:
259         case LFUN_INSET_DIALOG_UPDATE:
260         case LFUN_GRAPHICS_RELOAD:
261                 flag.setEnabled(true);
262                 return true;
263
264         default:
265                 return Inset::getStatus(cur, cmd, flag);
266         }
267 }
268
269
270 bool InsetGraphics::showInsetDialog(BufferView * bv) const
271 {
272         bv->showDialog("graphics", params2string(params(), bv->buffer()),
273                 const_cast<InsetGraphics *>(this));
274         return true;
275 }
276
277
278
279 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
280 {
281         graphic_->metrics(mi, dim);
282 }
283
284
285 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
286 {
287         graphic_->draw(pi, x, y);
288 }
289
290
291 void InsetGraphics::write(ostream & os) const
292 {
293         os << "Graphics\n";
294         params().Write(os, buffer());
295 }
296
297
298 void InsetGraphics::read(Lexer & lex)
299 {
300         lex.setContext("InsetGraphics::read");
301         //lex >> "Graphics";
302         readInsetGraphics(lex, buffer(), true, params_);
303         graphic_->update(params().as_grfxParams());
304 }
305
306
307 string InsetGraphics::createLatexOptions(bool const ps) 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().bbox.empty()) {
314                 string const key = ps ? "bb=" : "viewport=";
315                 options << key << params().bbox.xl.asLatexString() << ' '
316                         << params().bbox.yb.asLatexString() << ' '
317                         << params().bbox.xr.asLatexString() << ' '
318                         << params().bbox.yt.asLatexString() << ',';
319         }
320         if (params().draft)
321             options << "draft,";
322         if (params().clip)
323             options << "clip,";
324         ostringstream size;
325         double const scl = convert<double>(params().scale);
326         if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
327                 if (!float_equal(scl, 100.0, 0.05))
328                         size << "scale=" << scl / 100.0 << ',';
329         } else {
330                 if (!params().width.zero())
331                         size << "width=" << params().width.asLatexString() << ',';
332                 if (!params().height.zero())
333                         size << "height=" << params().height.asLatexString() << ',';
334                 if (params().keepAspectRatio)
335                         size << "keepaspectratio,";
336         }
337         if (params().scaleBeforeRotation && !size.str().empty())
338                 options << size.str();
339
340         // Make sure rotation angle is not very close to zero;
341         // a float can be effectively zero but not exactly zero.
342         if (!params().rotateAngle.empty()
343                 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
344             options << "angle=" << params().rotateAngle << ',';
345             if (!params().rotateOrigin.empty()) {
346                 options << "origin=" << params().rotateOrigin[0];
347                 if (contains(params().rotateOrigin,"Top"))
348                     options << 't';
349                 else if (contains(params().rotateOrigin,"Bottom"))
350                     options << 'b';
351                 else if (contains(params().rotateOrigin,"Baseline"))
352                     options << 'B';
353                 options << ',';
354             }
355         }
356         if (!params().scaleBeforeRotation && !size.str().empty())
357                 options << size.str();
358
359         if (!params().special.empty())
360             options << params().special << ',';
361
362         string opts = options.str();
363         // delete last ','
364         if (suffixIs(opts, ','))
365                 opts = opts.substr(0, opts.size() - 1);
366
367         return opts;
368 }
369
370
371 docstring InsetGraphics::toDocbookLength(Length const & len) const
372 {
373         odocstringstream result;
374         switch (len.unit()) {
375                 case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
376                         result << len.value() * 65536.0 * 72 / 72.27 << "pt";
377                         break;
378                 case Length::PT: // Point = 1/72.27in = 0.351mm
379                         result << len.value() * 72 / 72.27 << "pt";
380                         break;
381                 case Length::BP: // Big point (72bp = 1in), also PostScript point
382                         result << len.value() << "pt";
383                         break;
384                 case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
385                         result << len.value() * 0.376 << "mm";
386                         break;
387                 case Length::MM: // Millimeter = 2.845pt
388                         result << len.value() << "mm";
389                         break;
390                 case Length::PC: // Pica = 12pt = 4.218mm
391                         result << len.value() << "pc";
392                         break;
393                 case Length::CC: // Cicero = 12dd = 4.531mm
394                         result << len.value() * 4.531 << "mm";
395                         break;
396                 case Length::CM: // Centimeter = 10mm = 2.371pc
397                         result << len.value() << "cm";
398                         break;
399                 case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
400                         result << len.value() << "in";
401                         break;
402                 case Length::EX: // Height of a small "x" for the current font.
403                         // Obviously we have to compromise here. Any better ratio than 1.5 ?
404                         result << len.value() / 1.5 << "em";
405                         break;
406                 case Length::EM: // Width of capital "M" in current font.
407                         result << len.value() << "em";
408                         break;
409                 case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
410                         result << len.value() * 18 << "em";
411                         break;
412                 case Length::PTW: // Percent of TextWidth
413                 case Length::PCW: // Percent of ColumnWidth
414                 case Length::PPW: // Percent of PageWidth
415                 case Length::PLW: // Percent of LineWidth
416                 case Length::PTH: // Percent of TextHeight
417                 case Length::PPH: // Percent of PaperHeight
418                 case Length::BLS: // Percent of BaselineSkip
419                         // Sigh, this will go wrong.
420                         result << len.value() << "%";
421                         break;
422                 default:
423                         result << len.asDocstring();
424                         break;
425         }
426         return result.str();
427 }
428
429
430 docstring InsetGraphics::createDocBookAttributes() const
431 {
432         // Calculate the options part of the command, we must do it to a string
433         // stream since we copied the code from createLatexParams() ;-)
434
435         // FIXME: av: need to translate spec -> Docbook XSL spec
436         // (http://www.sagehill.net/docbookxsl/ImageSizing.html)
437         // Right now it only works with my version of db2latex :-)
438
439         odocstringstream options;
440         double const scl = convert<double>(params().scale);
441         if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
442                 if (!float_equal(scl, 100.0, 0.05))
443                         options << " scale=\""
444                                 << support::iround(scl)
445                                 << "\" ";
446         } else {
447                 if (!params().width.zero()) {
448                         options << " width=\"" << toDocbookLength(params().width)  << "\" ";
449                 }
450                 if (!params().height.zero()) {
451                         options << " depth=\"" << toDocbookLength(params().height)  << "\" ";
452                 }
453                 if (params().keepAspectRatio) {
454                         // This will be irrelevant unless both width and height are set
455                         options << "scalefit=\"1\" ";
456                 }
457         }
458
459
460         if (!params().special.empty())
461                 options << from_ascii(params().special) << " ";
462
463         // trailing blanks are ok ...
464         return options.str();
465 }
466
467
468 namespace {
469
470 enum GraphicsCopyStatus {
471         SUCCESS,
472         FAILURE,
473         IDENTICAL_PATHS,
474         IDENTICAL_CONTENTS
475 };
476
477
478 pair<GraphicsCopyStatus, FileName> const
479 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
480 {
481         LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
482         unsigned long const checksum_in  = file_in.checksum();
483         unsigned long const checksum_out = file_out.checksum();
484
485         if (checksum_in == checksum_out)
486                 // Nothing to do...
487                 return make_pair(IDENTICAL_CONTENTS, file_out);
488
489         Mover const & mover = getMover(theFormats().getFormatFromFile(file_in));
490         bool const success = mover.copy(file_in, file_out);
491         if (!success) {
492                 // FIXME UNICODE
493                 LYXERR(Debug::GRAPHICS,
494                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
495                                                            "into the temporary directory."),
496                                                 from_utf8(file_in.absFileName()))));
497         }
498
499         GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
500         return make_pair(status, file_out);
501 }
502
503
504 pair<GraphicsCopyStatus, FileName> const
505 copyToDirIfNeeded(DocFileName const & file, string const & dir)
506 {
507         string const file_in = file.absFileName();
508         string const only_path = onlyPath(file_in);
509         if (rtrim(only_path, "/") == rtrim(dir, "/"))
510                 return make_pair(IDENTICAL_PATHS, FileName(file_in));
511
512         string mangled = file.mangledFileName();
513         if (theFormats().isZippedFile(file)) {
514                 // We need to change _eps.gz to .eps.gz. The mangled name is
515                 // still unique because of the counter in mangledFileName().
516                 // We can't just call mangledFileName() with the zip
517                 // extension removed, because base.eps and base.eps.gz may
518                 // have different content but would get the same mangled
519                 // name in this case.
520                 string const base = removeExtension(file.unzippedFileName());
521                 string::size_type const ext_len = file_in.length() - base.length();
522                 mangled[mangled.length() - ext_len] = '.';
523         }
524         FileName const file_out(makeAbsPath(mangled, dir));
525
526         return copyFileIfNeeded(file, file_out);
527 }
528
529
530 string const stripExtensionIfPossible(string const & file, bool nice)
531 {
532         // Remove the extension so the LaTeX compiler will use whatever
533         // is appropriate (when there are several versions in different
534         // formats).
535         // Do this only if we are not exporting for internal usage, because
536         // pdflatex prefers png over pdf and it would pick up the png images
537         // that we generate for preview.
538         // This works only if the filename contains no dots besides
539         // the just removed one. We can fool here by replacing all
540         // dots with a macro whose definition is just a dot ;-)
541         // The automatic format selection does not work if the file
542         // name is escaped.
543         string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
544         if (!nice || contains(latex_name, '"'))
545                 return latex_name;
546         return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
547 }
548
549
550 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
551 {
552         // No conversion is needed. LaTeX can handle the graphic file as is.
553         // This is true even if the orig_file is compressed.
554         string const to_format = theFormats().getFormat(to)->extension();
555         string const file_format = getExtension(file);
556         // for latex .ps == .eps
557         if (to_format == file_format ||
558             (to_format == "eps" && file_format ==  "ps") ||
559             (to_format ==  "ps" && file_format == "eps"))
560                 return stripExtensionIfPossible(file, nice);
561         return latex_path(file, EXCLUDE_EXTENSION);
562 }
563
564 } // namespace
565
566
567 string InsetGraphics::prepareFile(OutputParams const & runparams) const
568 {
569         // The following code depends on non-empty filenames
570         if (params().filename.empty())
571                 return string();
572
573         string const orig_file = params().filename.absFileName();
574         // this is for dryrun and display purposes, do not use latexFilename
575         string const rel_file = params().filename.relFileName(buffer().filePath());
576
577         // previewing source code, no file copying or file format conversion
578         if (runparams.dryrun)
579                 return stripExtensionIfPossible(rel_file, runparams.nice);
580
581         // The master buffer. This is useful when there are multiple levels
582         // of include files
583         Buffer const * masterBuffer = buffer().masterBuffer();
584
585         // Return the output name if we are inside a comment or the file does
586         // not exist.
587         // We are not going to change the extension or using the name of the
588         // temporary file, the code is already complicated enough.
589         if (runparams.inComment || !params().filename.isReadableFile())
590                 return params().filename.outputFileName(masterBuffer->filePath());
591
592         // We place all temporary files in the master buffer's temp dir.
593         // This is possible because we use mangled file names.
594         // This is necessary for DVI export.
595         string const temp_path = masterBuffer->temppath();
596
597         // temp_file will contain the file for LaTeX to act on if, for example,
598         // we move it to a temp dir or uncompress it.
599         FileName temp_file;
600         GraphicsCopyStatus status;
601         tie(status, temp_file) = 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) {
614                 if (!isValidLaTeXFileName(output_file)) {
615                         frontend::Alert::warning(_("Invalid filename"),
616                                 _("The following filename will cause troubles "
617                                   "when running the exported file through LaTeX: ") +
618                                 from_utf8(output_file));
619                 }
620                 // only show DVI-specific warning when export format is plain latex
621                 if (!isValidDVIFileName(output_file)
622                         && runparams.flavor == OutputParams::LATEX) {
623                                 frontend::Alert::warning(_("Problematic filename for DVI"),
624                                          _("The following filename can cause troubles "
625                                                "when running the exported file through LaTeX "
626                                                    "and opening the resulting DVI: ") +
627                                              from_utf8(output_file), true);
628                 }
629         }
630
631         FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
632         // determine the export format
633         string const tex_format = flavor2format(runparams.flavor);
634
635         if (theFormats().isZippedFile(params().filename)) {
636                 FileName const unzipped_temp_file =
637                         FileName(unzippedFileName(temp_file.absFileName()));
638                 output_file = unzippedFileName(output_file);
639                 source_file = FileName(unzippedFileName(source_file.absFileName()));
640                 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
641                         // temp_file has been unzipped already and
642                         // orig_file has not changed in the meantime.
643                         temp_file = unzipped_temp_file;
644                         LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
645                 } else {
646                         // unzipped_temp_file does not exist or is too old
647                         temp_file = unzipFile(temp_file);
648                         LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
649                 }
650         }
651
652         string const from = theFormats().getFormatFromFile(temp_file);
653         if (from.empty())
654                 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
655
656         string const to   = findTargetFormat(from, runparams);
657         string const ext  = theFormats().extension(to);
658         LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
659
660         // We're going to be running the exported buffer through the LaTeX
661         // compiler, so must ensure that LaTeX can cope with the graphics
662         // file format.
663
664         LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
665
666         if (from == to) {
667                 // source and destination formats are the same
668                 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
669                         // The LaTeX compiler will not be able to determine
670                         // the file format from the extension, so we must
671                         // change it.
672                         FileName const new_file =
673                                 FileName(changeExtension(temp_file.absFileName(), ext));
674                         if (temp_file.moveTo(new_file)) {
675                                 temp_file = new_file;
676                                 output_file = changeExtension(output_file, ext);
677                                 source_file =
678                                         FileName(changeExtension(source_file.absFileName(), ext));
679                         } else {
680                                 LYXERR(Debug::GRAPHICS, "Could not rename file `"
681                                         << temp_file << "' to `" << new_file << "'.");
682                         }
683                 }
684                 // The extension of temp_file might be != ext!
685                 runparams.exportdata->addExternalFile(tex_format, source_file,
686                                                       output_file);
687                 runparams.exportdata->addExternalFile("dvi", source_file,
688                                                       output_file);
689                 return stripExtensionIfPossible(output_file, to, runparams.nice);
690         }
691
692         // so the source and destination formats are different
693         FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
694         string const output_to_file = changeExtension(output_file, ext);
695
696         // Do we need to perform the conversion?
697         // Yes if to_file does not exist or if temp_file is newer than to_file
698         if (compare_timestamps(temp_file, to_file) < 0) {
699                 // FIXME UNICODE
700                 LYXERR(Debug::GRAPHICS,
701                         to_utf8(bformat(_("No conversion of %1$s is needed after all"),
702                                    from_utf8(rel_file))));
703                 runparams.exportdata->addExternalFile(tex_format, to_file,
704                                                       output_to_file);
705                 runparams.exportdata->addExternalFile("dvi", to_file,
706                                                       output_to_file);
707                 return stripExtensionIfPossible(output_to_file, runparams.nice);
708         }
709
710         LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
711                 << "\tA copy has been made and convert is to be called with:\n"
712                 << "\tfile to convert = " << temp_file << '\n'
713                 << "\t from " << from << " to " << to);
714
715         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
716         ErrorList el;
717         Converters::RetVal const rv = 
718             theConverters().convert(&buffer(), temp_file, to_file, params().filename,
719                                from, to, el,
720                                Converters::try_default | Converters::try_cache);
721         if (rv == Converters::KILLED) {
722                 LYXERR0("Graphics preparation killed.");
723                 if (buffer().isClone() && buffer().isExporting())
724                         throw ConversionException();
725         } else if (rv == Converters::SUCCESS) {
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 void InsetGraphics::latex(otexstream & 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 message;
747         if (!file_exists) {
748                 if (params().bbox.empty())
749                     message = "bb = 0 0 200 100";
750                 if (!params().draft) {
751                         if (!message.empty())
752                                 message += ", ";
753                         message += "draft";
754                 }
755                 if (!message.empty())
756                         message += ", ";
757                 message += "type=eps";
758         }
759         // If no existing file "filename" was found LaTeX
760         // draws only a rectangle with the above bb and the
761         // not found filename in it.
762         LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
763
764         // These variables collect all the latex code that should be before and
765         // after the actual includegraphics command.
766         string before;
767         string after;
768
769         if (runparams.moving_arg)
770                 before += "\\protect";
771
772         // We never use the starred form, we use the "clip" option instead.
773         before += "\\includegraphics";
774
775         // Write the options if there are any.
776         bool const ps = runparams.flavor == OutputParams::LATEX
777                 || runparams.flavor == OutputParams::DVILUATEX;
778         string const opts = createLatexOptions(ps);
779         LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
780
781         if (!opts.empty() && !message.empty())
782                 before += ('[' + opts + ',' + message + ']');
783         else if (!opts.empty() || !message.empty())
784                 before += ('[' + opts + message + ']');
785
786         LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
787
788         string latex_str = before + '{';
789         // Convert the file if necessary.
790         // Remove the extension so LaTeX will use whatever is appropriate
791         // (when there are several versions in different formats)
792         string file_path = prepareFile(runparams);
793         latex_str += file_path;
794         latex_str += '}' + after;
795         // FIXME UNICODE
796         os << from_utf8(latex_str);
797
798         LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
799 }
800
801
802 int InsetGraphics::plaintext(odocstringstream & os,
803         OutputParams const &, size_t) const
804 {
805         // No graphics in ascii output. Possible to use gifscii to convert
806         // images to ascii approximation.
807         // 1. Convert file to ascii using gifscii
808         // 2. Read ascii output file and add it to the output stream.
809         // at least we send the filename
810         // FIXME UNICODE
811         // FIXME: We have no idea what the encoding of the filename is
812
813         docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
814                                       from_utf8(params().filename.absFileName()));
815         os << '<' << str << '>';
816
817         return 2 + str.size();
818 }
819
820
821 static int writeImageObject(char const * format, odocstream & os,
822         OutputParams const & runparams, docstring const & graphic_label,
823         docstring const & attributes)
824 {
825         if (runparams.flavor != OutputParams::XML)
826                 os << "<![ %output.print." << format
827                          << "; [" << endl;
828
829         os <<"<imageobject><imagedata fileref=\"&"
830                  << graphic_label
831                  << ";."
832                  << format
833                  << "\" "
834                  << attributes;
835
836         if (runparams.flavor == OutputParams::XML)
837                 os <<  " role=\"" << format << "\"/>" ;
838         else
839                 os << " format=\"" << format << "\">" ;
840
841         os << "</imageobject>";
842
843         if (runparams.flavor != OutputParams::XML)
844                 os << endl << "]]>" ;
845
846         return runparams.flavor == OutputParams::XML ? 0 : 2;
847 }
848
849
850 // For explanation on inserting graphics into DocBook checkout:
851 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
852 // See also the docbook guide at http://www.docbook.org/
853 int InsetGraphics::docbook(odocstream & os,
854                            OutputParams const & runparams) const
855 {
856         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
857         // need to switch to MediaObject. However, for now this is sufficient and
858         // easier to use.
859         if (runparams.flavor == OutputParams::XML)
860                 runparams.exportdata->addExternalFile("docbook-xml",
861                                                       params().filename);
862         else
863                 runparams.exportdata->addExternalFile("docbook",
864                                                       params().filename);
865
866         os << "<inlinemediaobject>";
867
868         int r = 0;
869         docstring attributes = createDocBookAttributes();
870         r += writeImageObject("png", os, runparams, graphic_label, attributes);
871         r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
872         r += writeImageObject("eps", os, runparams, graphic_label, attributes);
873         r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
874
875         os << "</inlinemediaobject>";
876         return r;
877 }
878
879
880 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
881 {
882         // The following code depends on non-empty filenames
883         if (params().filename.empty())
884                 return string();
885
886         if (!params().filename.isReadableFile())
887                 return string();
888
889         // The master buffer. This is useful when there are multiple levels
890         // of include files
891         Buffer const * masterBuffer = buffer().masterBuffer();
892
893         // We place all temporary files in the master buffer's temp dir.
894         // This is possible because we use mangled file names.
895         // FIXME We may want to put these files in some special temporary
896         // directory.
897         string const temp_path = masterBuffer->temppath();
898
899         // Copy to temporary directory.
900         FileName temp_file;
901         GraphicsCopyStatus status;
902         tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
903
904         if (status == FAILURE)
905                 return string();
906
907         string const from = theFormats().getFormatFromFile(temp_file);
908         if (from.empty()) {
909                 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
910                 return string();
911         }
912
913         string const to   = findTargetFormat(from, runparams);
914         string const ext  = theFormats().extension(to);
915         string const orig_file = params().filename.absFileName();
916         string output_file = onlyFileName(temp_file.absFileName());
917         LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
918         LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
919
920         if (from == to) {
921                 // source and destination formats are the same
922                 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
923                 return output_file;
924         }
925
926         // so the source and destination formats are different
927         FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
928         string const output_to_file = changeExtension(output_file, ext);
929
930         // Do we need to perform the conversion?
931         // Yes if to_file does not exist or if temp_file is newer than to_file
932         if (compare_timestamps(temp_file, to_file) < 0) {
933                 // FIXME UNICODE
934                 LYXERR(Debug::GRAPHICS,
935                         to_utf8(bformat(_("No conversion of %1$s is needed after all"),
936                                    from_utf8(orig_file))));
937                 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
938                 return output_to_file;
939         }
940
941         LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
942                 << "\tA copy has been made and convert is to be called with:\n"
943                 << "\tfile to convert = " << temp_file << '\n'
944                 << "\t from " << from << " to " << to);
945
946         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
947         ErrorList el;
948         Converters::RetVal const rv =
949                 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
950                         from, to, el, Converters::try_default | Converters::try_cache);
951         if (rv == Converters::KILLED) {
952                 if (buffer().isClone() && buffer().isExporting())
953                         throw ConversionException();
954                 return string();
955         }
956         if (rv != Converters::SUCCESS)
957                 return string();
958         runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
959         return output_to_file;
960 }
961
962
963 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
964 {
965         string const output_file = op.dryrun ? string() : prepareHTMLFile(op);
966
967         if (output_file.empty() && !op.dryrun) {
968                 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
969                         << params().filename << "' for output. File missing?");
970                 string const attr = "src='" + params().filename.absFileName()
971                                     + "' alt='image: " + output_file + "'";
972                 xs << html::CompTag("img", attr);
973                 return docstring();
974         }
975
976         // FIXME XHTML
977         // We aren't doing anything with the crop and rotate parameters, and it would
978         // really be better to do width and height conversion, rather than to output
979         // these parameters here.
980         string imgstyle;
981         bool const havewidth  = !params().width.zero();
982         bool const haveheight = !params().height.zero();
983         if (havewidth || haveheight) {
984                 if (havewidth)
985                         imgstyle += "width:" + params().width.asHTMLString() + ";";
986                 if (haveheight)
987                         imgstyle += " height:" + params().height.asHTMLString() + ";";
988         } else if (params().scale != "100") {
989                 // Note that this will not have the same effect as in LaTeX export:
990                 // There, the image will be scaled from its original size. Here, the
991                 // percentage will be interpreted by the browser, and the image will
992                 // be scaled to a percentage of the window size.
993                 imgstyle = "width:" + params().scale + "%;";
994         }
995         if (!imgstyle.empty())
996                 imgstyle = "style='" + imgstyle + "' ";
997
998         string const attr = imgstyle + "src='" + output_file + "' alt='image: "
999                             + output_file + "'";
1000         xs << html::CompTag("img", attr);
1001         return docstring();
1002 }
1003
1004
1005 void InsetGraphics::validate(LaTeXFeatures & features) const
1006 {
1007         // If we have no image, we should not require anything.
1008         if (params().filename.empty())
1009                 return;
1010
1011         features.includeFile(graphic_label,
1012                              removeExtension(params().filename.absFileName()));
1013
1014         features.require("graphicx");
1015
1016         if (features.runparams().nice) {
1017                 string const rel_file = params().filename.onlyFileNameWithoutExt();
1018                 if (contains(rel_file, "."))
1019                         features.require("lyxdot");
1020         }
1021 }
1022
1023
1024 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1025 {
1026         // If nothing is changed, just return and say so.
1027         if (params() == p && !p.filename.empty())
1028                 return false;
1029
1030         // Copy the new parameters.
1031         params_ = p;
1032
1033         // Update the display using the new parameters.
1034         graphic_->update(params().as_grfxParams());
1035
1036         // We have changed data, report it.
1037         return true;
1038 }
1039
1040
1041 InsetGraphicsParams const & InsetGraphics::params() const
1042 {
1043         return params_;
1044 }
1045
1046
1047 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1048 {
1049         theFormats().edit(buffer(), p.filename,
1050                      theFormats().getFormatFromFile(p.filename));
1051 }
1052
1053
1054 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active,
1055                                                          UpdateType, TocBackend & backend) const
1056 {
1057         //FIXME UNICODE
1058         docstring const str = from_utf8(params_.filename.onlyFileName());
1059         TocBuilder & b = backend.builder("graphics");
1060         b.pushItem(cpit, str, output_active);
1061         b.pop();
1062 }
1063
1064
1065 string InsetGraphics::contextMenuName() const
1066 {
1067         return "context-graphics";
1068 }
1069
1070
1071 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1072         InsetGraphicsParams & params)
1073 {
1074         if (in.empty())
1075                 return;
1076
1077         istringstream data(in);
1078         Lexer lex;
1079         lex.setStream(data);
1080         lex.setContext("InsetGraphics::string2params");
1081         lex >> "graphics";
1082         params = InsetGraphicsParams();
1083         readInsetGraphics(lex, buffer, false, params);
1084 }
1085
1086
1087 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1088         Buffer const & buffer)
1089 {
1090         ostringstream data;
1091         data << "graphics" << ' ';
1092         params.Write(data, buffer);
1093         data << "\\end_inset\n";
1094         return data.str();
1095 }
1096
1097
1098 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1099 {
1100         return from_utf8(params().filename.onlyFileName());
1101 }
1102
1103 namespace graphics {
1104
1105 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1106 {
1107         Inset & inset = b.inset();
1108         InsetIterator it  = inset_iterator_begin(inset);
1109         InsetIterator const end = inset_iterator_end(inset);
1110         for (; it != end; ++it) {
1111                 InsetGraphics const * ins = it->asInsetGraphics();
1112                 if (!ins)
1113                         continue;
1114                 InsetGraphicsParams const & inspar = ins->getParams();
1115                 if (!inspar.groupId.empty())
1116                         ids.insert(inspar.groupId);
1117         }
1118 }
1119
1120
1121 int countGroupMembers(Buffer const & b, string const & groupId)
1122 {
1123         int n = 0;
1124         if (groupId.empty())
1125                 return n;
1126         Inset & inset = b.inset();
1127         InsetIterator it = inset_iterator_begin(inset);
1128         InsetIterator const end = inset_iterator_end(inset);
1129         for (; it != end; ++it) {
1130                 InsetGraphics const * ins = it->asInsetGraphics();
1131                 if (!ins)
1132                         continue; 
1133                 if (ins->getParams().groupId == groupId)
1134                         ++n;
1135         }
1136         return n;
1137 }
1138
1139
1140 string getGroupParams(Buffer const & b, string const & groupId)
1141 {
1142         if (groupId.empty())
1143                 return string();
1144         Inset & inset = b.inset();
1145         InsetIterator it  = inset_iterator_begin(inset);
1146         InsetIterator const end = inset_iterator_end(inset);
1147         for (; it != end; ++it) {
1148                 InsetGraphics const * ins = it->asInsetGraphics();
1149                 if (!ins)
1150                         continue;
1151                 InsetGraphicsParams const & inspar = ins->getParams();
1152                 if (inspar.groupId == groupId) {
1153                         InsetGraphicsParams tmp = inspar;
1154                         tmp.filename.erase();
1155                         return InsetGraphics::params2string(tmp, b);
1156                 }
1157         }
1158         return string();
1159 }
1160
1161
1162 void unifyGraphicsGroups(Buffer & b, string const & argument)
1163 {
1164         InsetGraphicsParams params;
1165         InsetGraphics::string2params(argument, b, params);
1166
1167         // This handles undo groups automagically
1168         UndoGroupHelper ugh(&b);
1169         Inset & inset = b.inset();
1170         InsetIterator it  = inset_iterator_begin(inset);
1171         InsetIterator const end = inset_iterator_end(inset);
1172         for (; it != end; ++it) {
1173                 InsetGraphics * ins = it->asInsetGraphics();
1174                 if (!ins)
1175                         continue;
1176                 InsetGraphicsParams const & inspar = ins->getParams();
1177                 if (params.groupId == inspar.groupId) {
1178                         CursorData(it).recordUndo();
1179                         params.filename = inspar.filename;
1180                         ins->setParams(params);
1181                 }
1182         }
1183 }
1184
1185
1186 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1187 {
1188         Inset * instmp = &cur.inset();
1189         if (!instmp->asInsetGraphics())
1190                 instmp = cur.nextInset();
1191         if (!instmp || !instmp->asInsetGraphics())
1192                 return 0;
1193
1194         return instmp->asInsetGraphics();
1195 }
1196
1197 } // namespace graphics
1198
1199 } // namespace lyx