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