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