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