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