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