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