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