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