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