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