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