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