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