]> git.lyx.org Git - lyx.git/blob - src/insets/InsetGraphics.cpp
de.po
[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 latexing to DVI or PDF?
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                 // Also take into account that if the name of the zipped file
590                 // has no zip extension then the name of the unzipped one is
591                 // prefixed by "unzipped_".
592                 string const base = removeExtension(file.unzippedFileName());
593                 string::size_type const prefix_len =
594                         prefixIs(onlyFileName(base), "unzipped_") ? 9 : 0;
595                 string::size_type const ext_len =
596                         file_in.length() + prefix_len - base.length();
597                 mangled[mangled.length() - ext_len] = '.';
598         }
599         FileName const file_out(makeAbsPath(mangled, dir));
600
601         return copyFileIfNeeded(file, file_out);
602 }
603
604
605 string const stripExtensionIfPossible(string const & file, bool nice)
606 {
607         // Remove the extension so the LaTeX compiler will use whatever
608         // is appropriate (when there are several versions in different
609         // formats).
610         // Do this only if we are not exporting for internal usage, because
611         // pdflatex prefers png over pdf and it would pick up the png images
612         // that we generate for preview.
613         // This works only if the filename contains no dots besides
614         // the just removed one. We can fool here by replacing all
615         // dots with a macro whose definition is just a dot ;-)
616         // The automatic format selection does not work if the file
617         // name is escaped.
618         string const latex_name = latex_path(file, EXCLUDE_EXTENSION);
619         if (!nice || contains(latex_name, '"'))
620                 return latex_name;
621         return latex_path(removeExtension(file), PROTECT_EXTENSION, ESCAPE_DOTS);
622 }
623
624
625 string const stripExtensionIfPossible(string const & file, string const & to, bool nice)
626 {
627         // No conversion is needed. LaTeX can handle the graphic file as is.
628         // This is true even if the orig_file is compressed.
629         string const to_format = theFormats().getFormat(to)->extension();
630         string const file_format = getExtension(file);
631         // for latex .ps == .eps
632         if (to_format == file_format ||
633             (to_format == "eps" && file_format ==  "ps") ||
634             (to_format ==  "ps" && file_format == "eps"))
635                 return stripExtensionIfPossible(file, nice);
636         return latex_path(file, EXCLUDE_EXTENSION);
637 }
638
639 } // namespace
640
641
642 string InsetGraphics::prepareFile(OutputParams const & runparams) const
643 {
644         // The following code depends on non-empty filenames
645         if (params().filename.empty())
646                 return string();
647
648         string const orig_file = params().filename.absFileName();
649         // this is for dryrun and display purposes, do not use latexFilename
650         string const rel_file = params().filename.relFileName(buffer().filePath());
651
652         // previewing source code, no file copying or file format conversion
653         if (runparams.dryrun)
654                 return stripExtensionIfPossible(rel_file, runparams.nice);
655
656         // The master buffer. This is useful when there are multiple levels
657         // of include files
658         Buffer const * masterBuffer = buffer().masterBuffer();
659
660         // Return the output name if we are inside a comment or the file does
661         // not exist.
662         // We are not going to change the extension or using the name of the
663         // temporary file, the code is already complicated enough.
664         if (runparams.inComment || !params().filename.isReadableFile())
665                 return params().filename.outputFileName(masterBuffer->filePath());
666
667         // We place all temporary files in the master buffer's temp dir.
668         // This is possible because we use mangled file names.
669         // This is necessary for DVI export.
670         string const temp_path = masterBuffer->temppath();
671
672         // temp_file will contain the file for LaTeX to act on if, for example,
673         // we move it to a temp dir or uncompress it.
674         FileName temp_file;
675         GraphicsCopyStatus status;
676         tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
677
678         if (status == FAILURE)
679                 return orig_file;
680
681         // a relative filename should be relative to the master buffer.
682         // "nice" means that the buffer is exported to LaTeX format but not
683         // run through the LaTeX compiler.
684         string output_file = runparams.nice ?
685                 params().filename.outputFileName(masterBuffer->filePath()) :
686                 onlyFileName(temp_file.absFileName());
687
688         if (runparams.nice) {
689                 if (!isValidLaTeXFileName(output_file)) {
690                         frontend::Alert::warning(_("Invalid filename"),
691                                 _("The following filename will cause troubles "
692                                   "when running the exported file through LaTeX: ") +
693                                 from_utf8(output_file));
694                 }
695                 // only show DVI-specific warning when export format is plain latex
696                 if (!isValidDVIFileName(output_file)
697                         && runparams.flavor == OutputParams::LATEX) {
698                                 frontend::Alert::warning(_("Problematic filename for DVI"),
699                                          _("The following filename can cause troubles "
700                                                "when running the exported file through LaTeX "
701                                                    "and opening the resulting DVI: ") +
702                                              from_utf8(output_file), true);
703                 }
704         }
705
706         FileName source_file = runparams.nice ? FileName(params().filename) : temp_file;
707         // determine the export format
708         string const tex_format = flavor2format(runparams.flavor);
709
710         if (theFormats().isZippedFile(params().filename)) {
711                 FileName const unzipped_temp_file =
712                         FileName(unzippedFileName(temp_file.absFileName()));
713                 output_file = unzippedFileName(output_file);
714                 source_file = FileName(unzippedFileName(source_file.absFileName()));
715                 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
716                         // temp_file has been unzipped already and
717                         // orig_file has not changed in the meantime.
718                         temp_file = unzipped_temp_file;
719                         LYXERR(Debug::GRAPHICS, "\twas already unzipped to " << temp_file);
720                 } else {
721                         // unzipped_temp_file does not exist or is too old
722                         temp_file = unzipFile(temp_file);
723                         LYXERR(Debug::GRAPHICS, "\tunzipped to " << temp_file);
724                 }
725         }
726
727         string const from = theFormats().getFormatFromFile(temp_file);
728         if (from.empty())
729                 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
730
731         string const to   = findTargetFormat(from, runparams);
732         string const ext  = theFormats().extension(to);
733         LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
734
735         // We're going to be running the exported buffer through the LaTeX
736         // compiler, so must ensure that LaTeX can cope with the graphics
737         // file format.
738
739         LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
740
741         if (from == to) {
742                 // source and destination formats are the same
743                 if (!runparams.nice && !FileName(temp_file).hasExtension(ext)) {
744                         // The LaTeX compiler will not be able to determine
745                         // the file format from the extension, so we must
746                         // change it.
747                         FileName const new_file =
748                                 FileName(changeExtension(temp_file.absFileName(), ext));
749                         if (temp_file.moveTo(new_file)) {
750                                 temp_file = new_file;
751                                 output_file = changeExtension(output_file, ext);
752                                 source_file =
753                                         FileName(changeExtension(source_file.absFileName(), ext));
754                         } else {
755                                 LYXERR(Debug::GRAPHICS, "Could not rename file `"
756                                         << temp_file << "' to `" << new_file << "'.");
757                         }
758                 }
759                 // The extension of temp_file might be != ext!
760                 runparams.exportdata->addExternalFile(tex_format, source_file,
761                                                       output_file);
762                 runparams.exportdata->addExternalFile("dvi", source_file,
763                                                       output_file);
764                 return stripExtensionIfPossible(output_file, to, runparams.nice);
765         }
766
767         // so the source and destination formats are different
768         FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
769         string const output_to_file = changeExtension(output_file, ext);
770
771         // Do we need to perform the conversion?
772         // Yes if to_file does not exist or if temp_file is newer than to_file
773         if (compare_timestamps(temp_file, to_file) < 0) {
774                 // FIXME UNICODE
775                 LYXERR(Debug::GRAPHICS,
776                         to_utf8(bformat(_("No conversion of %1$s is needed after all"),
777                                    from_utf8(rel_file))));
778                 runparams.exportdata->addExternalFile(tex_format, to_file,
779                                                       output_to_file);
780                 runparams.exportdata->addExternalFile("dvi", to_file,
781                                                       output_to_file);
782                 return stripExtensionIfPossible(output_to_file, runparams.nice);
783         }
784
785         LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
786                 << "\tA copy has been made and convert is to be called with:\n"
787                 << "\tfile to convert = " << temp_file << '\n'
788                 << "\t from " << from << " to " << to);
789
790         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
791         ErrorList el;
792         Converters::RetVal const rv = 
793             theConverters().convert(&buffer(), temp_file, to_file, params().filename,
794                                from, to, el,
795                                Converters::try_default | Converters::try_cache);
796         if (rv == Converters::KILLED) {
797                 LYXERR0("Graphics preparation killed.");
798                 if (buffer().isClone() && buffer().isExporting())
799                         throw ConversionException();
800         } else if (rv == Converters::SUCCESS) {
801                 runparams.exportdata->addExternalFile(tex_format,
802                                 to_file, output_to_file);
803                 runparams.exportdata->addExternalFile("dvi",
804                                 to_file, output_to_file);
805         }
806
807         return stripExtensionIfPossible(output_to_file, runparams.nice);
808 }
809
810
811 void InsetGraphics::latex(otexstream & os,
812                           OutputParams const & runparams) const
813 {
814         // If there is no file specified or not existing,
815         // just output a message about it in the latex output.
816         LYXERR(Debug::GRAPHICS, "insetgraphics::latex: Filename = "
817                 << params().filename.absFileName());
818
819         bool const file_exists = !params().filename.empty()
820                         && params().filename.isReadableFile();
821         string message;
822         if (!file_exists) {
823                 if (params().bbox.empty())
824                     message = "bb = 0 0 200 100";
825                 if (!params().draft) {
826                         if (!message.empty())
827                                 message += ", ";
828                         message += "draft";
829                 }
830                 if (!message.empty())
831                         message += ", ";
832                 message += "type=eps";
833         }
834         // If no existing file "filename" was found LaTeX
835         // draws only a rectangle with the above bb and the
836         // not found filename in it.
837         LYXERR(Debug::GRAPHICS, "\tMessage = \"" << message << '\"');
838
839         // These variables collect all the latex code that should be before and
840         // after the actual includegraphics command.
841         string before;
842         string after;
843
844         if (runparams.moving_arg)
845                 before += "\\protect";
846
847         // We never use the starred form, we use the "clip" option instead.
848         before += "\\includegraphics";
849
850         // Write the options if there are any.
851         bool const ps = runparams.flavor == OutputParams::LATEX
852                 || runparams.flavor == OutputParams::DVILUATEX;
853         string const opts = createLatexOptions(ps);
854         LYXERR(Debug::GRAPHICS, "\tOpts = " << opts);
855
856         if (!opts.empty() && !message.empty())
857                 before += ('[' + opts + ',' + message + ']');
858         else if (!opts.empty() || !message.empty())
859                 before += ('[' + opts + message + ']');
860
861         LYXERR(Debug::GRAPHICS, "\tBefore = " << before << "\n\tafter = " << after);
862
863         string latex_str = before + '{';
864         // Convert the file if necessary.
865         // Remove the extension so LaTeX will use whatever is appropriate
866         // (when there are several versions in different formats)
867         string file_path = prepareFile(runparams);
868         latex_str += file_path;
869         latex_str += '}' + after;
870         // FIXME UNICODE
871         os << from_utf8(latex_str);
872
873         LYXERR(Debug::GRAPHICS, "InsetGraphics::latex outputting:\n" << latex_str);
874 }
875
876
877 int InsetGraphics::plaintext(odocstringstream & os,
878         OutputParams const &, size_t) const
879 {
880         // No graphics in ascii output. Possible to use gifscii to convert
881         // images to ascii approximation.
882         // 1. Convert file to ascii using gifscii
883         // 2. Read ascii output file and add it to the output stream.
884         // at least we send the filename
885         // FIXME UNICODE
886         // FIXME: We have no idea what the encoding of the filename is
887
888         docstring const str = bformat(buffer().B_("Graphics file: %1$s"),
889                                       from_utf8(params().filename.absFileName()));
890         os << '<' << str << '>';
891
892         return 2 + str.size();
893 }
894
895
896 static int writeImageObject(char const * format, odocstream & os,
897         OutputParams const & runparams, docstring const & graphic_label,
898         docstring const & attributes)
899 {
900         if (runparams.flavor != OutputParams::XML)
901                 os << "<![ %output.print." << format
902                          << "; [" << endl;
903
904         os <<"<imageobject><imagedata fileref=\"&"
905                  << graphic_label
906                  << ";."
907                  << format
908                  << "\" "
909                  << attributes;
910
911         if (runparams.flavor == OutputParams::XML)
912                 os <<  " role=\"" << format << "\"/>" ;
913         else
914                 os << " format=\"" << format << "\">" ;
915
916         os << "</imageobject>";
917
918         if (runparams.flavor != OutputParams::XML)
919                 os << endl << "]]>" ;
920
921         return runparams.flavor == OutputParams::XML ? 0 : 2;
922 }
923
924
925 // For explanation on inserting graphics into DocBook checkout:
926 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
927 // See also the docbook guide at http://www.docbook.org/
928 int InsetGraphics::docbook(odocstream & os,
929                            OutputParams const & runparams) const
930 {
931         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
932         // need to switch to MediaObject. However, for now this is sufficient and
933         // easier to use.
934         if (runparams.flavor == OutputParams::XML)
935                 runparams.exportdata->addExternalFile("docbook-xml",
936                                                       params().filename);
937         else
938                 runparams.exportdata->addExternalFile("docbook",
939                                                       params().filename);
940
941         os << "<inlinemediaobject>";
942
943         int r = 0;
944         docstring attributes = createDocBookAttributes();
945         r += writeImageObject("png", os, runparams, graphic_label, attributes);
946         r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
947         r += writeImageObject("eps", os, runparams, graphic_label, attributes);
948         r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
949
950         os << "</inlinemediaobject>";
951         return r;
952 }
953
954
955 string InsetGraphics::prepareHTMLFile(OutputParams const & runparams) const
956 {
957         // The following code depends on non-empty filenames
958         if (params().filename.empty())
959                 return string();
960
961         if (!params().filename.isReadableFile())
962                 return string();
963
964         // The master buffer. This is useful when there are multiple levels
965         // of include files
966         Buffer const * masterBuffer = buffer().masterBuffer();
967
968         // We place all temporary files in the master buffer's temp dir.
969         // This is possible because we use mangled file names.
970         // FIXME We may want to put these files in some special temporary
971         // directory.
972         string const temp_path = masterBuffer->temppath();
973
974         // Copy to temporary directory.
975         FileName temp_file;
976         GraphicsCopyStatus status;
977         tie(status, temp_file) = copyToDirIfNeeded(params().filename, temp_path);
978
979         if (status == FAILURE)
980                 return string();
981
982         string const from = theFormats().getFormatFromFile(temp_file);
983         if (from.empty()) {
984                 LYXERR(Debug::GRAPHICS, "\tCould not get file format.");
985                 return string();
986         }
987
988         string const to   = findTargetFormat(from, runparams);
989         string const ext  = theFormats().extension(to);
990         string const orig_file = params().filename.absFileName();
991         string output_file = onlyFileName(temp_file.absFileName());
992         LYXERR(Debug::GRAPHICS, "\t we have: from " << from << " to " << to);
993         LYXERR(Debug::GRAPHICS, "\tthe orig file is: " << orig_file);
994
995         if (from == to) {
996                 // source and destination formats are the same
997                 runparams.exportdata->addExternalFile("xhtml", temp_file, output_file);
998                 return output_file;
999         }
1000
1001         // so the source and destination formats are different
1002         FileName const to_file = FileName(changeExtension(temp_file.absFileName(), ext));
1003         string const output_to_file = changeExtension(output_file, ext);
1004
1005         // Do we need to perform the conversion?
1006         // Yes if to_file does not exist or if temp_file is newer than to_file
1007         if (compare_timestamps(temp_file, to_file) < 0) {
1008                 // FIXME UNICODE
1009                 LYXERR(Debug::GRAPHICS,
1010                         to_utf8(bformat(_("No conversion of %1$s is needed after all"),
1011                                    from_utf8(orig_file))));
1012                 runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1013                 return output_to_file;
1014         }
1015
1016         LYXERR(Debug::GRAPHICS,"\tThe original file is " << orig_file << "\n"
1017                 << "\tA copy has been made and convert is to be called with:\n"
1018                 << "\tfile to convert = " << temp_file << '\n'
1019                 << "\t from " << from << " to " << to);
1020
1021         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
1022         ErrorList el;
1023         Converters::RetVal const rv =
1024                 theConverters().convert(&buffer(), temp_file, to_file, params().filename,
1025                         from, to, el, Converters::try_default | Converters::try_cache);
1026         if (rv == Converters::KILLED) {
1027                 if (buffer().isClone() && buffer().isExporting())
1028                         throw ConversionException();
1029                 return string();
1030         }
1031         if (rv != Converters::SUCCESS)
1032                 return string();
1033         runparams.exportdata->addExternalFile("xhtml", to_file, output_to_file);
1034         return output_to_file;
1035 }
1036
1037
1038 docstring InsetGraphics::xhtml(XHTMLStream & xs, OutputParams const & op) const
1039 {
1040         string const output_file = op.dryrun ? string() : prepareHTMLFile(op);
1041
1042         if (output_file.empty() && !op.dryrun) {
1043                 LYXERR0("InsetGraphics::xhtml: Unable to prepare file `"
1044                         << params().filename << "' for output. File missing?");
1045                 string const attr = "src='" + params().filename.absFileName()
1046                                     + "' alt='image: " + output_file + "'";
1047                 xs << html::CompTag("img", attr);
1048                 return docstring();
1049         }
1050
1051         // FIXME XHTML
1052         // We aren't doing anything with the crop and rotate parameters, and it would
1053         // really be better to do width and height conversion, rather than to output
1054         // these parameters here.
1055         string imgstyle;
1056         bool const havewidth  = !params().width.zero();
1057         bool const haveheight = !params().height.zero();
1058         if (havewidth || haveheight) {
1059                 if (havewidth)
1060                         imgstyle += "width:" + params().width.asHTMLString() + ";";
1061                 if (haveheight)
1062                         imgstyle += " height:" + params().height.asHTMLString() + ";";
1063         } else if (params().scale != "100") {
1064                 // Note that this will not have the same effect as in LaTeX export:
1065                 // There, the image will be scaled from its original size. Here, the
1066                 // percentage will be interpreted by the browser, and the image will
1067                 // be scaled to a percentage of the window size.
1068                 imgstyle = "width:" + params().scale + "%;";
1069         }
1070         if (!imgstyle.empty())
1071                 imgstyle = "style='" + imgstyle + "' ";
1072
1073         string const attr = imgstyle + "src='" + output_file + "' alt='image: "
1074                             + output_file + "'";
1075         xs << html::CompTag("img", attr);
1076         return docstring();
1077 }
1078
1079
1080 void InsetGraphics::validate(LaTeXFeatures & features) const
1081 {
1082         // If we have no image, we should not require anything.
1083         if (params().filename.empty())
1084                 return;
1085
1086         features.includeFile(graphic_label,
1087                              removeExtension(params().filename.absFileName()));
1088
1089         features.require("graphicx");
1090
1091         if (features.runparams().nice) {
1092                 string const rel_file = params().filename.onlyFileNameWithoutExt();
1093                 if (contains(rel_file, "."))
1094                         features.require("lyxdot");
1095         }
1096 }
1097
1098
1099 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
1100 {
1101         // If nothing is changed, just return and say so.
1102         if (params() == p && !p.filename.empty())
1103                 return false;
1104
1105         // Copy the new parameters.
1106         params_ = p;
1107
1108         // Update the display using the new parameters.
1109         graphic_->update(params().as_grfxParams());
1110
1111         // We have changed data, report it.
1112         return true;
1113 }
1114
1115
1116 InsetGraphicsParams const & InsetGraphics::params() const
1117 {
1118         return params_;
1119 }
1120
1121
1122 void InsetGraphics::editGraphics(InsetGraphicsParams const & p) const
1123 {
1124         theFormats().edit(buffer(), p.filename,
1125                      theFormats().getFormatFromFile(p.filename));
1126 }
1127
1128
1129 void InsetGraphics::addToToc(DocIterator const & cpit, bool output_active,
1130                                                          UpdateType, TocBackend & backend) const
1131 {
1132         //FIXME UNICODE
1133         docstring const str = from_utf8(params_.filename.onlyFileName());
1134         TocBuilder & b = backend.builder("graphics");
1135         b.pushItem(cpit, str, output_active);
1136         b.pop();
1137 }
1138
1139
1140 string InsetGraphics::contextMenuName() const
1141 {
1142         return "context-graphics";
1143 }
1144
1145
1146 void InsetGraphics::string2params(string const & in, Buffer const & buffer,
1147         InsetGraphicsParams & params)
1148 {
1149         if (in.empty())
1150                 return;
1151
1152         istringstream data(in);
1153         Lexer lex;
1154         lex.setStream(data);
1155         lex.setContext("InsetGraphics::string2params");
1156         lex >> "graphics";
1157         params = InsetGraphicsParams();
1158         readInsetGraphics(lex, buffer, false, params);
1159 }
1160
1161
1162 string InsetGraphics::params2string(InsetGraphicsParams const & params,
1163         Buffer const & buffer)
1164 {
1165         ostringstream data;
1166         data << "graphics" << ' ';
1167         params.Write(data, buffer);
1168         data << "\\end_inset\n";
1169         return data.str();
1170 }
1171
1172
1173 docstring InsetGraphics::toolTip(BufferView const &, int, int) const
1174 {
1175         return from_utf8(params().filename.onlyFileName());
1176 }
1177
1178 namespace graphics {
1179
1180 void getGraphicsGroups(Buffer const & b, set<string> & ids)
1181 {
1182         Inset & inset = b.inset();
1183         InsetIterator it  = inset_iterator_begin(inset);
1184         InsetIterator const end = inset_iterator_end(inset);
1185         for (; it != end; ++it) {
1186                 InsetGraphics const * ins = it->asInsetGraphics();
1187                 if (!ins)
1188                         continue;
1189                 InsetGraphicsParams const & inspar = ins->getParams();
1190                 if (!inspar.groupId.empty())
1191                         ids.insert(inspar.groupId);
1192         }
1193 }
1194
1195
1196 int countGroupMembers(Buffer const & b, string const & groupId)
1197 {
1198         int n = 0;
1199         if (groupId.empty())
1200                 return n;
1201         Inset & inset = b.inset();
1202         InsetIterator it = inset_iterator_begin(inset);
1203         InsetIterator const end = inset_iterator_end(inset);
1204         for (; it != end; ++it) {
1205                 InsetGraphics const * ins = it->asInsetGraphics();
1206                 if (!ins)
1207                         continue; 
1208                 if (ins->getParams().groupId == groupId)
1209                         ++n;
1210         }
1211         return n;
1212 }
1213
1214
1215 string getGroupParams(Buffer const & b, string const & groupId)
1216 {
1217         if (groupId.empty())
1218                 return string();
1219         Inset & inset = b.inset();
1220         InsetIterator it  = inset_iterator_begin(inset);
1221         InsetIterator const end = inset_iterator_end(inset);
1222         for (; it != end; ++it) {
1223                 InsetGraphics const * ins = it->asInsetGraphics();
1224                 if (!ins)
1225                         continue;
1226                 InsetGraphicsParams const & inspar = ins->getParams();
1227                 if (inspar.groupId == groupId) {
1228                         InsetGraphicsParams tmp = inspar;
1229                         tmp.filename.erase();
1230                         return InsetGraphics::params2string(tmp, b);
1231                 }
1232         }
1233         return string();
1234 }
1235
1236
1237 void unifyGraphicsGroups(Buffer & b, string const & argument)
1238 {
1239         InsetGraphicsParams params;
1240         InsetGraphics::string2params(argument, b, params);
1241
1242         // This handles undo groups automagically
1243         UndoGroupHelper ugh(&b);
1244         Inset & inset = b.inset();
1245         InsetIterator it  = inset_iterator_begin(inset);
1246         InsetIterator const end = inset_iterator_end(inset);
1247         for (; it != end; ++it) {
1248                 InsetGraphics * ins = it->asInsetGraphics();
1249                 if (!ins)
1250                         continue;
1251                 InsetGraphicsParams const & inspar = ins->getParams();
1252                 if (params.groupId == inspar.groupId) {
1253                         CursorData(it).recordUndo();
1254                         params.filename = inspar.filename;
1255                         ins->setParams(params);
1256                 }
1257         }
1258 }
1259
1260
1261 InsetGraphics * getCurrentGraphicsInset(Cursor const & cur)
1262 {
1263         Inset * instmp = &cur.inset();
1264         if (!instmp->asInsetGraphics())
1265                 instmp = cur.nextInset();
1266         if (!instmp || !instmp->asInsetGraphics())
1267                 return 0;
1268
1269         return instmp->asInsetGraphics();
1270 }
1271
1272 } // namespace graphics
1273
1274 } // namespace lyx