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