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