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