]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
A bunch of conversion to docstring.
[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 "lyx_main.h"
68 #include "lyxlength.h"
69 #include "lyxlex.h"
70 #include "metricsinfo.h"
71 #include "mover.h"
72 #include "outputparams.h"
73 #include "sgml.h"
74
75 #include "frontends/Alert.h"
76 #include "frontends/LyXView.h"
77
78 #include "support/convert.h"
79 #include "support/filetools.h"
80 #include "support/lyxalgo.h" // lyx::count
81 #include "support/lyxlib.h" // lyx::sum
82 #include "support/lstrings.h"
83 #include "support/os.h"
84 #include "support/systemcall.h"
85
86 #include <boost/bind.hpp>
87 #include <boost/tuple/tuple.hpp>
88
89 #include <sstream>
90
91 namespace support = lyx::support;
92
93 using lyx::support::absolutePath;
94 using lyx::support::bformat;
95 using lyx::support::changeExtension;
96 using lyx::support::compare_timestamps;
97 using lyx::support::contains;
98 using lyx::support::FileName;
99 using lyx::support::float_equal;
100 using lyx::support::getExtension;
101 using lyx::support::isFileReadable;
102 using lyx::support::latex_path;
103 using lyx::support::onlyFilename;
104 using lyx::support::removeExtension;
105 using lyx::support::rtrim;
106 using lyx::support::subst;
107 using lyx::support::Systemcall;
108 using lyx::support::unzipFile;
109 using lyx::support::unzippedFileName;
110
111 namespace os = lyx::support::os;
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                 // Convert postscript to pdf
131                 if (format == "eps" || format == "ps")
132                         return "pdf";
133                 // pdflatex can use jpeg, png and pdf directly
134                 if (format == "jpg" || format == "pdf")
135                         return format;
136                 // Convert everything else to png
137                 return "png";
138         }
139         // If it's postscript, we always do eps.
140         lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
141         if (format != "ps")
142                 // any other than ps is changed to eps
143                 return "eps";
144         // let ps untouched
145         return format;
146 }
147
148 } // namespace anon
149
150
151 InsetGraphics::InsetGraphics()
152         : graphic_label(sgml::uniqueID("graph")),
153           graphic_(new RenderGraphic(this))
154 {}
155
156
157 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
158         : InsetOld(ig),
159           boost::signals::trackable(),
160           graphic_label(sgml::uniqueID("graph")),
161           graphic_(new RenderGraphic(*ig.graphic_, this))
162 {
163         setParams(ig.params());
164 }
165
166
167 auto_ptr<InsetBase> InsetGraphics::doClone() const
168 {
169         return auto_ptr<InsetBase>(new InsetGraphics(*this));
170 }
171
172
173 InsetGraphics::~InsetGraphics()
174 {
175         InsetGraphicsMailer(*this).hideDialog();
176 }
177
178
179 void InsetGraphics::doDispatch(LCursor & cur, FuncRequest & cmd)
180 {
181         switch (cmd.action) {
182         case LFUN_GRAPHICS_EDIT: {
183                 Buffer const & buffer = *cur.bv().buffer();
184                 InsetGraphicsParams p;
185                 InsetGraphicsMailer::string2params(lyx::to_utf8(cmd.argument()), buffer, p);
186                 editGraphics(p, buffer);
187                 break;
188         }
189
190         case LFUN_INSET_MODIFY: {
191                 Buffer const & buffer = cur.buffer();
192                 InsetGraphicsParams p;
193                 InsetGraphicsMailer::string2params(lyx::to_utf8(cmd.argument()), buffer, p);
194                 if (!p.filename.empty())
195                         setParams(p);
196                 else
197                         cur.noUpdate();
198                 break;
199         }
200
201         case LFUN_INSET_DIALOG_UPDATE:
202                 InsetGraphicsMailer(*this).updateDialog(&cur.bv());
203                 break;
204
205         case LFUN_MOUSE_RELEASE:
206                 InsetGraphicsMailer(*this).showDialog(&cur.bv());
207                 break;
208
209         default:
210                 InsetBase::doDispatch(cur, cmd);
211                 break;
212         }
213 }
214
215
216 bool InsetGraphics::getStatus(LCursor & cur, FuncRequest const & cmd,
217                 FuncStatus & flag) const
218 {
219         switch (cmd.action) {
220         case LFUN_GRAPHICS_EDIT:
221         case LFUN_INSET_MODIFY:
222         case LFUN_INSET_DIALOG_UPDATE:
223                 flag.enabled(true);
224                 return true;
225
226         default:
227                 return InsetBase::getStatus(cur, cmd, flag);
228         }
229 }
230
231
232 void InsetGraphics::edit(LCursor & cur, bool)
233 {
234         InsetGraphicsMailer(*this).showDialog(&cur.bv());
235 }
236
237
238 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
239 {
240         graphic_->metrics(mi, dim);
241         dim_ = dim;
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 string const InsetGraphics::toDocbookLength(LyXLength const & len) const
354 {
355         ostringstream 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.asString();
405                         break;
406         }
407         return result.str();
408 }
409
410 string 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         ostringstream 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 << params().special << " ";
441
442         string opts = options.str();
443         // trailing blanks are ok ...
444         return opts;
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, string> const
459 copyFileIfNeeded(string const & file_in, string const & file_out)
460 {
461         BOOST_ASSERT(absolutePath(file_in));
462         BOOST_ASSERT(absolutePath(file_out));
463
464         unsigned long const checksum_in  = support::sum(file_in);
465         unsigned long const checksum_out = support::sum(file_out);
466
467         if (checksum_in == checksum_out)
468                 // Nothing to do...
469                 return std::make_pair(IDENTICAL_CONTENTS, file_out);
470
471         Mover const & mover = movers(formats.getFormatFromFile(file_in));
472         bool const success = mover.copy(file_in, file_out);
473         if (!success) {
474                 // FIXME UNICODE
475                 lyxerr[Debug::GRAPHICS]
476                         << lyx::to_utf8(support::bformat(_("Could not copy the file\n%1$s\n"
477                                                            "into the temporary directory."),
478                                             lyx::from_utf8(file_in)))
479                         << std::endl;
480         }
481
482         CopyStatus status = success ? SUCCESS : FAILURE;
483         return std::make_pair(status, file_out);
484 }
485
486
487 std::pair<CopyStatus, string> const
488 copyToDirIfNeeded(FileName const & file, string const & dir)
489 {
490         using support::rtrim;
491
492         string const file_in = file.absFilename();
493         string const only_path = support::onlyPath(file_in);
494         if (rtrim(support::onlyPath(file_in) , "/") == rtrim(dir, "/"))
495                 return std::make_pair(IDENTICAL_PATHS, file_in);
496
497         string mangled = file.mangledFilename();
498         if (file.isZipped()) {
499                 // We need to change _eps.gz to .eps.gz. The mangled name is
500                 // still unique because of the counter in mangledFilename().
501                 // We can't just call mangledFilename() with the zip
502                 // extension removed, because base.eps and base.eps.gz may
503                 // have different content but would get the same mangled
504                 // name in this case.
505                 string const base = removeExtension(file.unzippedFilename());
506                 string::size_type const ext_len = file_in.length() - base.length();
507                 mangled[mangled.length() - ext_len] = '.';
508         }
509         string const file_out = support::makeAbsPath(mangled, dir);
510
511         return copyFileIfNeeded(file_in, file_out);
512 }
513
514
515 string const stripExtensionIfPossible(string const & file)
516 {
517         // Remove the extension so the LaTeX will use whatever
518         // is appropriate (when there are several versions in
519         // different formats)
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                                              lyx::support::EXCLUDE_EXTENSION);
527         if (contains(latex_name, '"'))
528                 return latex_name;
529         return latex_path(removeExtension(file),
530                           lyx::support::PROTECT_EXTENSION,
531                           lyx::support::ESCAPE_DOTS);
532 }
533
534
535 string const stripExtensionIfPossible(string const & file, string const & to)
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);
546         return latex_path(file, lyx::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);
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         string temp_file = orig_file;
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(orig_file))
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 = os::external_path(runparams.nice ?
598                 params().filename.outputFilename(m_buffer->filePath()) :
599                 onlyFilename(temp_file));
600         string source_file = runparams.nice ? orig_file : 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                         string const bb_orig_file = 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                                 string bb_file = changeExtension(temp_file, "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                                           lyx::support::EXCLUDE_EXTENSION);
640                 }
641
642                 string const unzipped_temp_file = unzippedFileName(temp_file);
643                 output_file = unzippedFileName(output_file);
644                 source_file = unzippedFileName(source_file);
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) != 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                         string const new_file = changeExtension(temp_file, ext);
683                         if (lyx::support::rename(temp_file, new_file)) {
684                                 temp_file = new_file;
685                                 output_file = changeExtension(output_file, ext);
686                                 source_file = changeExtension(source_file, 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);
699         }
700
701         string const to_file = changeExtension(temp_file, 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                         << lyx::to_utf8(bformat(_("No conversion of %1$s is needed after all"),
710                                    lyx::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_file);
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 (converters.convert(&buf, temp_file, temp_file, from, to, el, true)) {
728                 runparams.exportdata->addExternalFile(tex_format,
729                                 to_file, output_to_file);
730                 runparams.exportdata->addExternalFile("dvi",
731                                 to_file, output_to_file);
732         }
733
734         return stripExtensionIfPossible(output_file);
735 }
736
737
738 int InsetGraphics::latex(Buffer const & buf, ostream & os,
739                          OutputParams const & runparams) const
740 {
741         // If there is no file specified or not existing,
742         // just output a message about it in the latex output.
743         lyxerr[Debug::GRAPHICS]
744                 << "insetgraphics::latex: Filename = "
745                 << params().filename.absFilename() << endl;
746
747         string const relative_file =
748                 params().filename.relFilename(buf.filePath());
749
750         string const file_ = params().filename.absFilename();
751         bool const file_exists = !file_.empty() && isFileReadable(file_);
752         string const message = file_exists ?
753                 string() : string("bb = 0 0 200 100, draft, type=eps");
754         // if !message.empty() then there was no existing file
755         // "filename" found. In this case LaTeX
756         // draws only a rectangle with the above bb and the
757         // not found filename in it.
758         lyxerr[Debug::GRAPHICS]
759                 << "\tMessage = \"" << message << '\"' << endl;
760
761         // These variables collect all the latex code that should be before and
762         // after the actual includegraphics command.
763         string before;
764         string after;
765         // Do we want subcaptions?
766         if (params().subcaption) {
767                 if (runparams.moving_arg)
768                         before += "\\protect";
769                 before += "\\subfigure[" + params().subcaptionText + "]{";
770                 after = '}';
771         }
772
773         if (runparams.moving_arg)
774                 before += "\\protect";
775
776         // We never use the starred form, we use the "clip" option instead.
777         before += "\\includegraphics";
778
779         // Write the options if there are any.
780         string const opts = createLatexOptions();
781         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
782
783         if (!opts.empty() && !message.empty())
784                 before += ('[' + opts + ',' + message + ']');
785         else if (!opts.empty() || !message.empty())
786                 before += ('[' + opts + message + ']');
787
788         lyxerr[Debug::GRAPHICS]
789                 << "\tBefore = " << before
790                 << "\n\tafter = " << after << endl;
791
792         string latex_str = before + '{';
793         // Convert the file if necessary.
794         // Remove the extension so LaTeX will use whatever is appropriate
795         // (when there are several versions in different formats)
796         latex_str += prepareFile(buf, runparams);
797         latex_str += '}' + after;
798         os << latex_str;
799
800         lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
801                                 << latex_str << endl;
802         // Return how many newlines we issued.
803         return int(lyx::count(latex_str.begin(), latex_str.end(),'\n'));
804 }
805
806
807 int InsetGraphics::plaintext(Buffer const &, ostream & os,
808                          OutputParams const &) const
809 {
810         // No graphics in ascii output. Possible to use gifscii to convert
811         // images to ascii approximation.
812         // 1. Convert file to ascii using gifscii
813         // 2. Read ascii output file and add it to the output stream.
814         // at least we send the filename
815         // FIXME UNICODE
816         os << '<' << lyx::to_utf8(bformat(_("Graphics file: %1$s"),
817                              lyx::from_utf8(params().filename.absFilename()))) << ">\n";
818         return 0;
819 }
820
821
822 namespace {
823
824 int writeImageObject(char * format, ostream& os, OutputParams const & runparams,
825                                          string const graphic_label, string const attributes)
826 {
827                 if (runparams.flavor != OutputParams::XML) {
828                         os << "<![ %output.print." << format << "; [" << std::endl;
829                 }
830                 os <<"<imageobject><imagedata fileref=\"&"
831                    << graphic_label << ";." << format << "\" " << attributes ;
832                 if (runparams.flavor == OutputParams::XML) {
833                         os <<  " role=\"" << format << "\"/>" ;
834                 }
835                 else {
836                         os << " format=\"" << format << "\">" ;
837                 }
838                 os << "</imageobject>";
839                 if (runparams.flavor != OutputParams::XML) {
840                         os << std::endl << "]]>" ;
841                 }
842                 return runparams.flavor == OutputParams::XML ? 0 : 2;
843 }
844 // end anonymous namespace
845 }
846
847
848 // For explanation on inserting graphics into DocBook checkout:
849 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
850 // See also the docbook guide at http://www.docbook.org/
851 int InsetGraphics::docbook(Buffer const &, ostream & os,
852                            OutputParams const & runparams) const
853 {
854         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
855         // need to switch to MediaObject. However, for now this is sufficient and
856         // easier to use.
857         if (runparams.flavor == OutputParams::XML) {
858                 runparams.exportdata->addExternalFile("docbook-xml",
859                                                       params().filename.absFilename());
860         } else {
861                 runparams.exportdata->addExternalFile("docbook",
862                                                       params().filename.absFilename());
863         }
864         os << "<inlinemediaobject>";
865
866         int r = 0;
867         string attributes = createDocBookAttributes();
868         r += writeImageObject("png", os, runparams, graphic_label, attributes);
869         r += writeImageObject("pdf", os, runparams, graphic_label, attributes);
870         r += writeImageObject("eps", os, runparams, graphic_label, attributes);
871         r += writeImageObject("bmp", os, runparams, graphic_label, attributes);
872
873         os << "</inlinemediaobject>";
874         return r;
875 }
876
877
878 void InsetGraphics::validate(LaTeXFeatures & features) const
879 {
880         // If we have no image, we should not require anything.
881         if (params().filename.empty())
882                 return;
883
884         features.includeFile(graphic_label,
885                              removeExtension(params().filename.absFilename()));
886
887         features.require("graphicx");
888
889         if (features.runparams().nice) {
890                 Buffer const * m_buffer = features.buffer().getMasterBuffer();
891                 string basename =
892                         params().filename.outputFilename(m_buffer->filePath());
893                 basename = removeExtension(basename);
894                 if(params().filename.isZipped())
895                         basename = removeExtension(basename);
896                 if (contains(basename, "."))
897                         features.require("lyxdot");
898         }
899
900         if (params().subcaption)
901                 features.require("subfigure");
902 }
903
904
905 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
906 {
907         // If nothing is changed, just return and say so.
908         if (params() == p && !p.filename.empty())
909                 return false;
910
911         // Copy the new parameters.
912         params_ = p;
913
914         // Update the display using the new parameters.
915         graphic_->update(params().as_grfxParams());
916
917         // We have changed data, report it.
918         return true;
919 }
920
921
922 InsetGraphicsParams const & InsetGraphics::params() const
923 {
924         return params_;
925 }
926
927
928 void InsetGraphics::editGraphics(InsetGraphicsParams const & p,
929                                  Buffer const & buffer) const
930 {
931         string const file_with_path = p.filename.absFilename();
932         formats.edit(buffer, file_with_path,
933                      formats.getFormatFromFile(file_with_path));
934 }
935
936
937 string const InsetGraphicsMailer::name_("graphics");
938
939 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
940         : inset_(inset)
941 {}
942
943
944 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
945 {
946         return params2string(inset_.params(), buffer);
947 }
948
949
950 void InsetGraphicsMailer::string2params(string const & in,
951                                         Buffer const & buffer,
952                                         InsetGraphicsParams & params)
953 {
954         params = InsetGraphicsParams();
955         if (in.empty())
956                 return;
957
958         istringstream data(in);
959         LyXLex lex(0,0);
960         lex.setStream(data);
961
962         string name;
963         lex >> name;
964         if (!lex || name != name_)
965                 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
966
967         InsetGraphics inset;
968         inset.readInsetGraphics(lex, buffer.filePath());
969         params = inset.params();
970 }
971
972
973 string const
974 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
975                                    Buffer const & buffer)
976 {
977         ostringstream data;
978         data << name_ << ' ';
979         params.Write(data, buffer.filePath());
980         data << "\\end_inset\n";
981         return data.str();
982 }