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