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