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