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