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