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