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