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