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