]> git.lyx.org Git - lyx.git/blob - src/insets/InsetGraphics.cpp
7daa40d9aaf392438b293f99ac81b2b18b7ee25f
[lyx.git] / src / insets / InsetGraphics.cpp
1 /**
2  * \file InsetGraphics.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Baruch Even
7  * \author Herbert Voß
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 /*
13 TODO
14
15     * What advanced features the users want to do?
16       Implement them in a non latex dependent way, but a logical way.
17       LyX should translate it to latex or any other fitting format.
18     * When loading, if the image is not found in the expected place, try
19       to find it in the clipart, or in the same directory with the image.
20     * The image choosing dialog could show thumbnails of the image formats
21       it knows of, thus selection based on the image instead of based on
22       filename.
23     * Add support for the 'picins' package.
24     * Add support for the 'picinpar' package.
25 */
26
27 /* NOTES:
28  * Fileformat:
29  * The filename is kept in  the lyx file in a relative way, so as to allow
30  * moving the document file and its images with no problem.
31  *
32  *
33  * Conversions:
34  *   Postscript output means EPS figures.
35  *
36  *   PDF output is best done with PDF figures if it's a direct conversion
37  *   or PNG figures otherwise.
38  *      Image format
39  *      from        to
40  *      EPS         epstopdf
41  *      PS          ps2pdf
42  *      JPG/PNG     direct
43  *      PDF         direct
44  *      others      PNG
45  */
46
47 #include <config.h>
48
49 #include "insets/InsetGraphics.h"
50 #include "insets/RenderGraphic.h"
51
52 #include "Buffer.h"
53 #include "BufferView.h"
54 #include "Converter.h"
55 #include "Cursor.h"
56 #include "DispatchResult.h"
57 #include "Encoding.h"
58 #include "ErrorList.h"
59 #include "Exporter.h"
60 #include "Format.h"
61 #include "FuncRequest.h"
62 #include "FuncStatus.h"
63 #include "InsetIterator.h"
64 #include "LaTeXFeatures.h"
65 #include "Lexer.h"
66 #include "MetricsInfo.h"
67 #include "Mover.h"
68 #include "output_docbook.h"
69 #include "output_xhtml.h"
70 #include "xml.h"
71 #include "texstream.h"
72 #include "TocBackend.h"
73
74 #include "frontends/alert.h"
75 #include "frontends/Application.h"
76
77 #include "graphics/GraphicsCache.h"
78 #include "graphics/GraphicsCacheItem.h"
79 #include "graphics/GraphicsImage.h"
80
81 #include "support/convert.h"
82 #include "support/debug.h"
83 #include "support/docstream.h"
84 #include "support/ExceptionMessage.h"
85 #include "support/filetools.h"
86 #include "support/gettext.h"
87 #include "support/Length.h"
88 #include "support/lyxlib.h"
89 #include "support/lstrings.h"
90 #include "support/os.h"
91 #include "support/qstring_helpers.h"
92 #include "support/Systemcall.h"
93
94 #include <QProcess>
95 #include <QtGui/QImage>
96
97 #include <algorithm>
98 #include <sstream>
99
100 using namespace std;
101 using namespace lyx::support;
102
103 namespace lyx {
104
105 namespace Alert = frontend::Alert;
106
107 namespace {
108
109 /// Find the most suitable image format for images in \p format
110 /// Note that \p format may be unknown (i.e. an empty string)
111 string findTargetFormat(string const & format, OutputParams const & runparams)
112 {
113         // Are we latexing to DVI or PDF?
114         if (runparams.flavor == Flavor::PdfLaTeX
115             || runparams.flavor == Flavor::XeTeX
116             || runparams.flavor == Flavor::LuaTeX) {
117                 LYXERR(Debug::GRAPHICS, "findTargetFormat: PDF mode");
118                 Format const * const f = theFormats().getFormat(format);
119                 // Convert vector graphics to pdf
120                 if (f && f->vectorFormat())
121                         return "pdf6";
122                 // pdflatex can use jpeg, png and pdf directly
123                 if (format == "jpg")
124                         return format;
125                 // Convert everything else to png
126                 return "png";
127         }
128
129         // for HTML and DocBook, we leave the known formats and otherwise convert to png
130         if (runparams.flavor == Flavor::Html || runparams.flavor == Flavor::DocBook5) {
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(xml::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(xml::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, params_.darkModeSensitive);
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 vector 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 (theFormats().getFormat(format)->vectorFormat())
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         // Even if cached, the image is not loaded without GUI
344         if  (width == 0 && height == 0) {
345                 QImage image(toqstr(file.absFileName()));
346                 width  = image.width();
347                 height = image.height();
348         }
349         if (width == 0 || height == 0)
350                 return;
351
352         // Use extractbb to find the dimensions in the typeset output
353         QProcess extractbb;
354         extractbb.start("extractbb", QStringList() << "-O" << toqstr(file.absFileName()));
355         if (!extractbb.waitForStarted() || !extractbb.waitForFinished()) {
356                 LYXERR0("Cannot read output bounding box of " << file);
357                 return;
358         }
359
360         string const result = extractbb.readAll().constData();
361         size_t i = result.find("%%BoundingBox:");
362         if (i == string::npos) {
363                 LYXERR0("Cannot find output bounding box of " << file);
364                 return;
365         }
366
367         string const bb = result.substr(i);
368         int out_width = convert<int>(token(bb, ' ', 3));
369         int out_height = convert<int>(token(bb, ' ', 4));
370
371         // Compute the scaling ratio and correct the bounding box
372         double scalex = out_width / double(width);
373         double scaley = out_height / double(height);
374
375         bbox.xl.value(scalex * bbox.xl.value());
376         bbox.xr.value(scalex * bbox.xr.value());
377         bbox.yb.value(scaley * bbox.yb.value());
378         bbox.yt.value(scaley * bbox.yt.value());
379 }
380
381
382 string InsetGraphics::createLatexOptions(bool const ps) const
383 {
384         // Calculate the options part of the command, we must do it to a string
385         // stream since we might have a trailing comma that we would like to remove
386         // before writing it to the output stream.
387         ostringstream options;
388         if (!params().bbox.empty()) {
389                 graphics::BoundingBox out_bbox = params().bbox;
390                 outBoundingBox(out_bbox);
391                 string const key = ps ? "bb=" : "viewport=";
392                 options << key << out_bbox.xl.asLatexString() << ' '
393                         << out_bbox.yb.asLatexString() << ' '
394                         << out_bbox.xr.asLatexString() << ' '
395                         << out_bbox.yt.asLatexString() << ',';
396         }
397         if (params().draft)
398             options << "draft,";
399         if (params().clip)
400             options << "clip,";
401         ostringstream size;
402         double const scl = convert<double>(params().scale);
403         if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
404                 if (!float_equal(scl, 100.0, 0.05))
405                         size << "scale=" << scl / 100.0 << ',';
406         } else {
407                 if (!params().width.zero())
408                         size << "width=" << params().width.asLatexString() << ',';
409                 if (!params().height.zero())
410                         size << "totalheight=" << params().height.asLatexString() << ',';
411                 if (params().keepAspectRatio)
412                         size << "keepaspectratio,";
413         }
414         if (params().scaleBeforeRotation && !size.str().empty())
415                 options << size.str();
416
417         // Make sure rotation angle is not very close to zero;
418         // a float can be effectively zero but not exactly zero.
419         if (!params().rotateAngle.empty()
420                 && !float_equal(convert<double>(params().rotateAngle), 0.0, 0.001)) {
421             options << "angle=" << params().rotateAngle << ',';
422             if (!params().rotateOrigin.empty()) {
423                 options << "origin=" << params().rotateOrigin[0];
424                 if (contains(params().rotateOrigin,"Top"))
425                     options << 't';
426                 else if (contains(params().rotateOrigin,"Bottom"))
427                     options << 'b';
428                 else if (contains(params().rotateOrigin,"Baseline"))
429                     options << 'B';
430                 options << ',';
431             }
432         }
433         if (!params().scaleBeforeRotation && !size.str().empty())
434                 options << size.str();
435
436         if (!params().special.empty())
437             options << params().special << ',';
438
439         string opts = options.str();
440         // delete last ','
441         if (suffixIs(opts, ','))
442                 opts = opts.substr(0, opts.size() - 1);
443
444         return opts;
445 }
446
447
448 docstring InsetGraphics::toDocbookLength(Length const & len) const
449 {
450         odocstringstream result;
451         switch (len.unit()) {
452         case Length::SP: // Scaled point (65536sp = 1pt) TeX's smallest unit.
453                 result << len.value() * 65536.0 * 72 / 72.27 << "pt";
454                 break;
455         case Length::PT: // Point = 1/72.27in = 0.351mm
456                 result << len.value() * 72 / 72.27 << "pt";
457                 break;
458         case Length::BP: // Big point (72bp = 1in), also PostScript point
459                 result << len.value() << "pt";
460                 break;
461         case Length::DD: // Didot point = 1/72 of a French inch, = 0.376mm
462                 result << len.value() * 0.376 << "mm";
463                 break;
464         case Length::MM: // Millimeter = 2.845pt
465                 result << len.value() << "mm";
466                 break;
467         case Length::PC: // Pica = 12pt = 4.218mm
468                 result << len.value() << "pc";
469                 break;
470         case Length::CC: // Cicero = 12dd = 4.531mm
471                 result << len.value() * 4.531 << "mm";
472                 break;
473         case Length::CM: // Centimeter = 10mm = 2.371pc
474                 result << len.value() << "cm";
475                 break;
476         case Length::IN: // Inch = 25.4mm = 72.27pt = 6.022pc
477                 result << len.value() << "in";
478                 break;
479         case Length::EX: // Height of a small "x" for the current font.
480                 // Obviously we have to compromise here. Any better ratio than 1.5 ?
481                 result << len.value() / 1.5 << "em";
482                 break;
483         case Length::EM: // Width of capital "M" in current font.
484                 result << len.value() << "em";
485                 break;
486         case Length::MU: // Math unit (18mu = 1em) for positioning in math mode
487                 result << len.value() * 18 << "em";
488                 break;
489         case Length::PTW: // Percent of TextWidth
490         case Length::PCW: // Percent of ColumnWidth
491         case Length::PPW: // Percent of PageWidth
492         case Length::PLW: // Percent of LineWidth
493         case Length::PTH: // Percent of TextHeight
494         case Length::PPH: // Percent of PaperHeight
495         case Length::BLS: // Percent of BaselineSkip
496                 // Sigh, this will go wrong.
497                 result << len.value() << "%";
498                 break;
499         default:
500                 result << len.asDocstring();
501                 break;
502         }
503         return result.str();
504 }
505
506
507 docstring InsetGraphics::createDocBookAttributes() const
508 {
509         // Calculate the options part of the command, we must do it to a string
510         // stream since we copied the code from createLatexParams() ;-)
511
512         odocstringstream options;
513         auto const scl = convert<double>(params().scale);
514         if (!params().scale.empty() && !float_equal(scl, 0.0, 0.05)) {
515                 if (!float_equal(scl, 100.0, 0.05))
516                         options << " scale=\""
517                                     << support::iround(scl)
518                                     << "\" ";
519         } else {
520                 if (!params().width.zero())
521                         options << " width=\"" << toDocbookLength(params().width)  << "\" ";
522                 if (!params().height.zero())
523                         options << " depth=\"" << toDocbookLength(params().height)  << "\" ";
524                 if (params().keepAspectRatio)
525                         // This will be irrelevant unless both width and height are set
526                         options << "scalefit=\"1\" ";
527         }
528
529         // TODO: parse params().special?
530
531         // trailing blanks are ok ...
532         return options.str();
533 }
534
535
536 namespace {
537
538 enum GraphicsCopyStatus {
539         SUCCESS,
540         FAILURE,
541         IDENTICAL_PATHS,
542         IDENTICAL_CONTENTS
543 };
544
545
546 pair<GraphicsCopyStatus, FileName> const
547 copyFileIfNeeded(FileName const & file_in, FileName const & file_out)
548 {
549         LYXERR(Debug::FILES, "Comparing " << file_in << " and " << file_out);
550         unsigned long const checksum_in  = file_in.checksum();
551         unsigned long const checksum_out = file_out.checksum();
552
553         if (checksum_in == checksum_out)
554                 // Nothing to do...
555                 return make_pair(IDENTICAL_CONTENTS, file_out);
556
557         Mover const & mover = getMover(theFormats().getFormatFromFile(file_in));
558         bool const success = mover.copy(file_in, file_out);
559         if (!success) {
560                 // FIXME UNICODE
561                 LYXERR(Debug::GRAPHICS,
562                         to_utf8(bformat(_("Could not copy the file\n%1$s\n"
563                                                            "into the temporary directory."),
564                                                 from_utf8(file_in.absFileName()))));
565         }
566
567         GraphicsCopyStatus status = success ? SUCCESS : FAILURE;
568         return make_pair(status, file_out);
569 }
570
571
572 pair<GraphicsCopyStatus, FileName> const
573 copyToDirIfNeeded(DocFileName const & file, string const & dir)
574 {
575         string const file_in = file.absFileName();
576         string const only_path = onlyPath(file_in);
577         if (rtrim(only_path, "/") == rtrim(dir, "/"))
578                 return make_pair(IDENTICAL_PATHS, FileName(file_in));
579
580         string mangled = file.mangledFileName(empty_string(), false, true);
581         if (theFormats().isZippedFile(file)) {
582                 // We need to change _eps.gz to .eps.gz. The mangled name is
583                 // still unique because of the counter in mangledFileName().
584                 // We can't just call mangledFileName() with the zip
585                 // extension removed, because base.eps and base.eps.gz may
586                 // have different content but would get the same mangled
587                 // name in this case.
588                 // Also take into account that if the name of the zipped file
589                 // has no zip extension then the name of the unzipped one is
590                 // prefixed by "unzipped_".
591                 string const base = removeExtension(file.unzippedFileName());
592                 string::size_type const prefix_len =
593                         prefixIs(onlyFileName(base), "unzipped_") ? 9 : 0;
594                 string::size_type const ext_len =
595                         file_in.length() + prefix_len - base.length();
596                 mangled[mangled.length() - ext_len] = '.';
597         }
598         FileName const file_out(makeAbsPath(mangled, dir));
599
600         return copyFileIfNeeded(file, file_out);
601 }
602
603
604 string const stripExtensionIfPossible(string const & file, bool nice)
605 {
606         // Remove the extension so the LaTeX compiler will use whatever
607         // is appropriate (when there are several versions in different
608         // formats).
609         // Do this only if we are not exporting for internal usage, because
610         // pdflatex prefers png over pdf and it would pick up the png images
611         // that we generate for preview.
612         // This works only if the filename contains no dots besides
613         // the just removed one. We can fool here by replacing all
614         // dots with a macro whose definition is just a dot ;-)
615         // The automatic format selection does not work if the file
616         // name is escaped.
617         string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
618         if (!nice || contains(latex_name, '"'))
619                 return latex_name;
620         return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
621 }
622
623
624 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
625 {
626         // No conversion is needed. LaTeX can handle the graphic file as is.
627         // This is true even if the orig_file is compressed.
628         Format const * f = theFormats().getFormat(to);
629         if (!f)
630                 return latex_path(file, EXCLUDE_EXTENSION);
631         string const to_format = f->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 == Flavor::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         Converters::RetVal const rv = 
795             theConverters().convert(&buffer(), temp_file, to_file, params().filename,
796                                from, to, el,
797                                Converters::try_default | Converters::try_cache);
798         if (rv == Converters::KILLED) {
799                 LYXERR0("Graphics preparation killed.");
800                 if (buffer().isClone() && buffer().isExporting())
801                         throw ConversionException();
802         } else if (rv == Converters::SUCCESS) {
803                 runparams.exportdata->addExternalFile(tex_format,
804                                 to_file, output_to_file);
805                 runparams.exportdata->addExternalFile("dvi",
806                                 to_file, output_to_file);
807         }
808
809         return stripExtensionIfPossible(output_to_file, runparams.nice);
810 }
811
812
813 void InsetGraphics::latex(otexstream & os,
814                           OutputParams const & runparams) const
815 {
816         // If there is no file specified or not existing,
817         // just output a message about it in the latex output.
818         LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
819                 << params().filename.absFileName());
820
821         bool const file_exists = !params().filename.empty()
822                         && params().filename.isReadableFile();
823         string message;
824         if (!file_exists) {
825                 if (params().bbox.empty())
826                     message = "bb = 0 0 200 100";
827                 if (!params().draft) {
828                         if (!message.empty())
829                                 message += ", ";
830                         message += "draft";
831                 }
832                 if (!message.empty())
833                         message += ", ";
834                 message += "type=eps";
835         }
836         // If no existing file "filename" was found LaTeX
837         // draws only a rectangle with the above bb and the
838         // not found filename in it.
839         LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
840
841         // These variables collect all the latex code that should be before and
842         // after the actual includegraphics command.
843         string before;
844         string after;
845
846         // Write the options if there are any.
847         bool const ps = runparams.flavor == Flavor::LaTeX
848                 || runparams.flavor == Flavor::DviLuaTeX;
849         string const opts = createLatexOptions(ps);
850         LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
851
852         if (contains(opts, '=') && contains(runparams.active_chars, '=')) {
853                 // We have a language that makes = active. Deactivate locally
854                 // for keyval option parsing (#2005).
855                 before = "\\begingroup\\catcode`\\=12";
856                 after = "\\endgroup ";
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 (char_type c : file_path) {
882                 try {
883                         if (runparams.encoding->encodable(c))
884                                 encodable_file_path += c;
885                         else if (runparams.dryrun) {
886                                 encodable_file_path += "<" + _("LyX Warning: ")
887                                                 + _("uncodable character") + " '";
888                                 encodable_file_path += docstring(1, c);
889                                 encodable_file_path += "'>";
890                         } else
891                                 uncodable += c;
892                 } catch (EncodingException & /* e */) {
893                         if (runparams.dryrun) {
894                                 encodable_file_path += "<" + _("LyX Warning: ")
895                                                 + _("uncodable character") + " '";
896                                 encodable_file_path += docstring(1, c);
897                                 encodable_file_path += "'>";
898                         } else
899                                 uncodable += c;
900                 }
901         }
902         if (!uncodable.empty() && !runparams.silent) {
903                 // issue a warning about omitted characters
904                 // FIXME: should be passed to the error dialog
905                 frontend::Alert::warning(_("Uncodable character in file path"),
906                         bformat(_("The following characters in one of the graphic paths are\n"
907                                   "not representable in the current encoding and have been omitted: %1$s.\n"
908                                   "You need to adapt either the encoding or the path."),
909                         uncodable));
910         }
911         latex_str += to_utf8(encodable_file_path);
912         latex_str += '}' + after;
913         // FIXME UNICODE
914         os << from_utf8(latex_str);
915
916         LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
917 }
918
919
920 int InsetGraphics::plaintext(odocstringstream & os,
921         OutputParams const &, size_t) const
922 {
923         // No graphics in ascii output. Possible to use gifscii to convert
924         // images to ascii approximation.
925         // 1. Convert file to ascii using gifscii
926         // 2. Read ascii output file and add it to the output stream.
927         // at least we send the filename
928         // FIXME UNICODE
929         // FIXME: We have no idea what the encoding of the filename is
930
931         docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
932                                       from_utf8(params().filename.absFileName()));
933         os << '<' << str << '>';
934
935         return 2 + str.size();
936 }
937
938
939 // For explanation on inserting graphics into DocBook checkout:
940 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
941 // See also the docbook guide at http://www.docbook.org/
942 void InsetGraphics::docbook(XMLStream & xs, OutputParams const & runparams) const
943 {
944         string fn = params().filename.relFileName(runparams.export_folder);
945         string tag = runparams.docbook_in_float ? "mediaobject" : "inlinemediaobject";
946
947         xs << xml::StartTag(tag);
948         xs << xml::CR();
949         xs << xml::StartTag("imageobject");
950         xs << xml::CR();
951         xs << xml::CompTag("imagedata", "fileref=\"" + fn + "\" " + to_utf8(createDocBookAttributes()));
952         xs << xml::CR();
953         xs << xml::EndTag("imageobject");
954         xs << xml::CR();
955         xs << xml::EndTag(tag);
956         xs << xml::CR();
957 }
958
959
960 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
961 {
962         // The following code depends on non-empty filenames
963         if (params().filename.empty())
964                 return string();
965
966         if (!params().filename.isReadableFile())
967                 return string();
968
969         // The master buffer. This is useful when there are multiple levels
970         // of include files
971         Buffer const * masterBuffer = buffer().masterBuffer();
972
973         // We place all temporary files in the master buffer's temp dir.
974         // This is possible because we use mangled file names.
975         // FIXME We may want to put these files in some special temporary
976         // directory.
977         string const temp_path = masterBuffer->temppath();
978
979         // Copy to temporary directory.
980         FileName temp_file;
981         GraphicsCopyStatus status;
982         tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
983
984         if (status == FAILURE)
985                 return string();
986
987         string const from = theFormats().getFormatFromFile(temp_file);
988         if (from.empty()) {
989                 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
990                 return string();
991         }
992
993         string const to   = findTargetFormat(from, runparams);
994         string const ext  = theFormats().extension(to);
995         string const orig_file = params().filename.absFileName();
996         string output_file = onlyFileName(temp_file.absFileName());
997         LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
998         LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
999
1000         if (from == to) {
1001                 // source and destination formats are the same
1002                 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
1003                 return output_file;
1004         }
1005
1006         // so the source and destination formats are different
1007         FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
1008         string const output_to_file = changeExtension(output_file, ext);
1009
1010         // Do we need to perform the conversion?
1011         // Yes if to_file does not exist or if temp_file is newer than to_file
1012         if (compare_timestamps(temp_file, to_file) < 0) {
1013                 // FIXME UNICODE
1014                 LYXERR(Debug::GRAPHICS,
1015                         to_utf8(bformat(_("No conversion of %1$s is needed after all"),
1016                                    from_utf8(orig_file))));
1017                 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1018                 return output_to_file;
1019         }
1020
1021         LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
1022                 << "\tA copy has been made and convert is to be called with:\n"
1023                 << "\tfile to convert = " << temp_file << '\n'
1024                 << "\t from " << from << " to " << to);
1025
1026         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
1027         ErrorList el;
1028         Converters::RetVal const rv =
1029                 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
1030                         from, to, el, Converters::try_default | Converters::try_cache);
1031         if (rv == Converters::KILLED) {
1032                 if (buffer().isClone() && buffer().isExporting())
1033                         throw ConversionException();
1034                 return string();
1035         }
1036         if (rv != Converters::SUCCESS)
1037                 return string();
1038         runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1039         return output_to_file;
1040 }
1041
1042
1043 CtObject InsetGraphics::getCtObject(OutputParams const &) const
1044 {
1045         return CtObject::Object;
1046 }
1047
1048
1049 docstring InsetGraphics::xhtml(XMLStream & xs, OutputParams const & op) const
1050 {
1051         string const output_file = op.dryrun ? string() : prepareHTMLFile(op);
1052
1053         if (output_file.empty() && !op.dryrun) {
1054                 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
1055                         << params().filename << "' for output. File missing?");
1056                 string const attr = "src='" + params().filename.absFileName()
1057                                     + "' alt='image: " + output_file + "'";
1058                 xs << xml::CompTag("img", attr);
1059                 return docstring();
1060         }
1061
1062         // FIXME XHTML
1063         // We aren't doing anything with the crop and rotate parameters, and it would
1064         // really be better to do width and height conversion, rather than to output
1065         // these parameters here.
1066         string imgstyle;
1067         bool const havewidth  = !params().width.zero();
1068         bool const haveheight = !params().height.zero();
1069         if (havewidth || haveheight) {
1070                 if (havewidth)
1071                         imgstyle += "width:" + params().width.asHTMLString() + ";";
1072                 if (haveheight)
1073                         imgstyle += " height:" + params().height.asHTMLString() + ";";
1074         } else if (params().scale != "100") {
1075                 // Note that this will not have the same effect as in LaTeX export:
1076                 // There, the image will be scaled from its original size. Here, the
1077                 // percentage will be interpreted by the browser, and the image will
1078                 // be scaled to a percentage of the window size.
1079                 imgstyle = "width:" + params().scale + "%;";
1080         }
1081         if (!imgstyle.empty())
1082                 imgstyle = "style='" + imgstyle + "' ";
1083
1084         string const attr = imgstyle + "src='" + output_file + "' alt='image: "
1085                             + output_file + "'";
1086         xs << xml::CompTag("img", attr);
1087         return docstring();
1088 }
1089
1090
1091 void InsetGraphics::validate(LaTeXFeatures & features) const
1092 {
1093         // If we have no image, we should not require anything.
1094         if (params().filename.empty())
1095                 return;
1096
1097         features.includeFile(graphic_label,
1098                              removeExtension(params().filename.absFileName()));
1099
1100         features.require("graphicx");
1101
1102         if (features.runparams().nice) {
1103                 string const rel_file = params().filename.onlyFileNameWithoutExt();
1104                 if (contains(rel_file, "."))
1105                         features.require("lyxdot");
1106         }
1107         if (features.inDeletedInset()) {
1108                 features.require("tikz");
1109                 features.require("ct-tikz-object-sout");
1110         }
1111 }
1112
1113
1114 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1115 {
1116         // If nothing is changed, just return and say so.
1117         if (params() == p && !p.filename.empty())
1118                 return false;
1119
1120         // Copy the new parameters.
1121         params_ = p;
1122
1123         // Update the display using the new parameters.
1124         graphic_->update(params().as_grfxParams());
1125
1126         // We have changed data, report it.
1127         return true;
1128 }
1129
1130
1131 InsetGraphicsParams const & InsetGraphics::params() const
1132 {
1133         return params_;
1134 }
1135
1136
1137 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1138 {
1139         theFormats().edit(buffer(), p.filename,
1140                      theFormats().getFormatFromFile(p.filename));
1141 }
1142
1143
1144 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active,
1145                                                          UpdateType, TocBackend & backend) const
1146 {
1147         //FIXME UNICODE
1148         docstring const str = from_utf8(params_.filename.onlyFileName());
1149         TocBuilder & b = backend.builder("graphics");
1150         b.pushItem(cpit, str, output_active);
1151         b.pop();
1152 }
1153
1154
1155 string InsetGraphics::contextMenuName() const
1156 {
1157         return "context-graphics";
1158 }
1159
1160
1161 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1162         InsetGraphicsParams & params)
1163 {
1164         if (in.empty())
1165                 return;
1166
1167         istringstream data(in);
1168         Lexer lex;
1169         lex.setStream(data);
1170         lex.setContext("InsetGraphics::string2params");
1171         lex >> "graphics";
1172         params = InsetGraphicsParams();
1173         readInsetGraphics(lex, buffer, false, params);
1174 }
1175
1176
1177 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1178         Buffer const & buffer)
1179 {
1180         ostringstream data;
1181         data << "graphics" << ' ';
1182         params.Write(data, buffer);
1183         data << "\\end_inset\n";
1184         return data.str();
1185 }
1186
1187
1188 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1189 {
1190         return from_utf8(params().filename.onlyFileName());
1191 }
1192
1193 namespace graphics {
1194
1195 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1196 {
1197         for (Inset const & it : b.inset()) {
1198                 InsetGraphics const * ins = it.asInsetGraphics();
1199                 if (!ins)
1200                         continue;
1201                 InsetGraphicsParams const & inspar = ins->getParams();
1202                 if (!inspar.groupId.empty())
1203                         ids.insert(inspar.groupId);
1204         }
1205 }
1206
1207
1208 int countGroupMembers(Buffer const & b, string const & groupId)
1209 {
1210         int n = 0;
1211         if (groupId.empty())
1212                 return n;
1213         for (Inset const & it : b.inset()) {
1214                 InsetGraphics const * ins = it.asInsetGraphics();
1215                 if (!ins)
1216                         continue; 
1217                 if (ins->getParams().groupId == groupId)
1218                         ++n;
1219         }
1220         return n;
1221 }
1222
1223
1224 string getGroupParams(Buffer const & b, string const & groupId)
1225 {
1226         if (groupId.empty())
1227                 return string();
1228         for (Inset const & it : b.inset()) {
1229                 InsetGraphics const * ins = it.asInsetGraphics();
1230                 if (!ins)
1231                         continue;
1232                 InsetGraphicsParams const & inspar = ins->getParams();
1233                 if (inspar.groupId == groupId) {
1234                         InsetGraphicsParams tmp = inspar;
1235                         tmp.filename.erase();
1236                         return InsetGraphics::params2string(tmp, b);
1237                 }
1238         }
1239         return string();
1240 }
1241
1242
1243 void unifyGraphicsGroups(Buffer & b, string const & argument)
1244 {
1245         InsetGraphicsParams params;
1246         InsetGraphics::string2params(argument, b, params);
1247
1248         // This handles undo groups automagically
1249         UndoGroupHelper ugh(&b);
1250         Inset & inset = b.inset();
1251         InsetIterator it  = begin(inset);
1252         InsetIterator const itend = end(inset);
1253         for (; it != itend; ++it) {
1254                 InsetGraphics * ins = it->asInsetGraphics();
1255                 if (!ins)
1256                         continue;
1257                 InsetGraphicsParams const & inspar = ins->getParams();
1258                 if (params.groupId == inspar.groupId) {
1259                         CursorData(it).recordUndo();
1260                         params.filename = inspar.filename;
1261                         ins->setParams(params);
1262                 }
1263         }
1264 }
1265
1266
1267 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1268 {
1269         Inset * instmp = &cur.inset();
1270         if (!instmp->asInsetGraphics())
1271                 instmp = cur.nextInset();
1272         if (!instmp || !instmp->asInsetGraphics())
1273                 return 0;
1274
1275         return instmp->asInsetGraphics();
1276 }
1277
1278 } // namespace graphics
1279
1280 } // namespace lyx