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