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