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