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