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