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