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