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