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