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