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