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