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