]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
5bbc846cf8c7c3be40b3ccb61405ba698cf8ae2e
[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 "lyxlex.h"
68 #include "metricsinfo.h"
69 #include "outputparams.h"
70
71 #include "frontends/Alert.h"
72 #include "frontends/LyXView.h"
73
74 #include "support/filetools.h"
75 #include "support/lyxalgo.h" // lyx::count
76 #include "support/lyxlib.h" // float_equal
77 #include "support/os.h"
78 #include "support/systemcall.h"
79 #include "support/tostr.h"
80
81 #include <boost/bind.hpp>
82 #include <boost/tuple/tuple.hpp>
83
84 #include <sstream>
85
86 namespace support = lyx::support;
87
88 using lyx::support::AbsolutePath;
89 using lyx::support::bformat;
90 using lyx::support::ChangeExtension;
91 using lyx::support::compare_timestamps;
92 using lyx::support::contains;
93 using lyx::support::FileName;
94 using lyx::support::float_equal;
95 using lyx::support::GetExtension;
96 using lyx::support::getExtFromContents;
97 using lyx::support::IsFileReadable;
98 using lyx::support::LibFileSearch;
99 using lyx::support::OnlyFilename;
100 using lyx::support::rtrim;
101 using lyx::support::subst;
102 using lyx::support::Systemcall;
103 using lyx::support::unzipFile;
104 using lyx::support::unzippedFileName;
105
106 namespace os = lyx::support::os;
107
108 using std::endl;
109 using std::string;
110 using std::auto_ptr;
111 using std::istringstream;
112 using std::ostream;
113 using std::ostringstream;
114
115
116 namespace {
117
118 // This function is a utility function
119 // ... that should be with ChangeExtension ...
120 inline
121 string const RemoveExtension(string const & filename)
122 {
123         return ChangeExtension(filename, string());
124 }
125
126
127 string const uniqueID()
128 {
129         static unsigned int seed = 1000;
130         return "graph" + tostr(++seed);
131 }
132
133
134 string findTargetFormat(string const & suffix, OutputParams const & runparams)
135 {
136         // Are we using latex or pdflatex).
137         if (runparams.flavor == OutputParams::PDFLATEX) {
138                 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode" << endl;
139                 if (contains(suffix, "ps") || suffix == "pdf")
140                         return "pdf";
141                 if (suffix == "jpg")    // pdflatex can use jpeg
142                         return suffix;
143                 return "png";         // and also png
144         }
145         // If it's postscript, we always do eps.
146         lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode" << endl;
147         if (suffix != "ps")     // any other than ps
148                 return "eps";         // is changed to eps
149         return suffix;          // let ps untouched
150 }
151
152 } // namespace anon
153
154
155 InsetGraphics::InsetGraphics()
156         : graphic_label(uniqueID()),
157           graphic_(new RenderGraphic(this))
158 {}
159
160
161 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
162         : InsetOld(ig),
163           boost::signals::trackable(),
164           graphic_label(uniqueID()),
165           graphic_(new RenderGraphic(*ig.graphic_, this))
166 {
167         setParams(ig.params());
168 }
169
170
171 auto_ptr<InsetBase> InsetGraphics::clone() 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::priv_dispatch(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                 InsetOld::priv_dispatch(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 InsetOld::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         if (!float_equal(params().scale, 0.0, 0.05)) {
303                 if (!float_equal(params().scale, 100.0, 0.05))
304                         options << "  scale=" << params().scale / 100.0
305                                 << ",\n";
306         } else {
307                 if (!params().width.zero())
308                         options << "  width=" << params().width.asLatexString() << ",\n";
309                 if (!params().height.zero())
310                         options << "  height=" << params().height.asLatexString() << ",\n";
311                 if (params().keepAspectRatio)
312                         options << "  keepaspectratio,\n";
313         }
314
315         // Make sure rotation angle is not very close to zero;
316         // a float can be effectively zero but not exactly zero.
317         if (!float_equal(params().rotateAngle, 0, 0.001)) {
318             options << "  angle=" << params().rotateAngle << ",\n";
319             if (!params().rotateOrigin.empty()) {
320                 options << "  origin=" << params().rotateOrigin[0];
321                 if (contains(params().rotateOrigin,"Top"))
322                     options << 't';
323                 else if (contains(params().rotateOrigin,"Bottom"))
324                     options << 'b';
325                 else if (contains(params().rotateOrigin,"Baseline"))
326                     options << 'B';
327                 options << ",\n";
328             }
329         }
330
331         if (!params().special.empty())
332             options << params().special << ",\n";
333
334         string opts = options.str();
335         // delete last ",\n"
336         return opts.substr(0, opts.size() - 2);
337 }
338
339
340 string const InsetGraphics::createDocBookAttributes() const
341 {
342         // Calculate the options part of the command, we must do it to a string
343         // stream since we copied the code from createLatexParams()
344
345         // FIXME: av: need to translate spec -> Docbook XSL spec (http://www.sagehill.net/docbookxsl/ImageSizing.html)
346         // Right now it only works with my version of db2latex :-)
347
348         ostringstream options;
349         if (!float_equal(params().scale, 0.0, 0.05)) {
350                 if (!float_equal(params().scale, 100.0, 0.05))
351                         options << " scale=\"" << params().scale / 100.0
352                                 << "\" ";
353         } else {
354                 if (!params().width.zero())
355                         options << " width=\"" << params().width.asLatexString()  << "\" ";
356                 if (!params().height.zero())
357                         options << " depth=\"" << params().height.asLatexString()  << "\" ";
358         }
359
360         if (!params().special.empty())
361             options << params().special << " ";
362
363         string opts = options.str();
364         // trailing blanks are ok ...
365         return opts;
366 }
367
368
369 namespace {
370
371 enum CopyStatus {
372         SUCCESS,
373         FAILURE,
374         IDENTICAL_PATHS,
375         IDENTICAL_CONTENTS
376 };
377
378
379 std::pair<CopyStatus, string> const
380 copyFileIfNeeded(string const & file_in, string const & file_out)
381 {
382         BOOST_ASSERT(AbsolutePath(file_in));
383         BOOST_ASSERT(AbsolutePath(file_out));
384
385         unsigned long const checksum_in  = support::sum(file_in);
386         unsigned long const checksum_out = support::sum(file_out);
387
388         if (checksum_in == checksum_out)
389                 // Nothing to do...
390                 return std::make_pair(IDENTICAL_CONTENTS, file_out);
391
392         bool const success = support::copy(file_in, file_out);
393         if (!success) {
394                 lyxerr[Debug::GRAPHICS]
395                         << support::bformat(_("Could not copy the file\n%1$s\n"
396                                               "into the temporary directory."),
397                                             file_in)
398                         << std::endl;
399         }
400
401         CopyStatus status = success ? SUCCESS : FAILURE;
402         return std::make_pair(status, file_out);
403 }
404
405
406 std::pair<CopyStatus, string> const
407 copyToDirIfNeeded(string const & file_in, string const & dir, bool zipped)
408 {
409         using support::rtrim;
410
411         BOOST_ASSERT(AbsolutePath(file_in));
412
413         string const only_path = support::OnlyPath(file_in);
414         if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
415                 return std::make_pair(IDENTICAL_PATHS, file_in);
416
417         string mangled = FileName(file_in).mangledFilename();
418         if (zipped) {
419                 // We need to change _eps.gz to .eps.gz. The mangled name is
420                 // still unique because of the counter in mangledFilename().
421                 // We can't just call mangledFilename() with the zip
422                 // extension removed, because base.eps and base.eps.gz may
423                 // have different content but would get the same mangled
424                 // name in this case.
425                 string const base = RemoveExtension(unzippedFileName(file_in));
426                 string::size_type const ext_len = file_in.length() - base.length();
427                 mangled[mangled.length() - ext_len] = '.';
428         }
429         string const file_out = support::MakeAbsPath(mangled, dir);
430
431         return copyFileIfNeeded(file_in, file_out);
432 }
433
434
435 string const stripExtension(string const & file)
436 {
437         // Remove the extension so the LaTeX will use whatever
438         // is appropriate (when there are several versions in
439         // different formats)
440         // This works only if the filename contains no dots besides
441         // the just removed one. We can fool here by replacing all
442         // dots with a macro whose definition is just a dot ;-)
443         return subst(RemoveExtension(file), ".", "\\lyxdot ");
444 }
445
446
447 string const stripExtensionIfPossible(string const & file, string const & to)
448 {
449         // No conversion is needed. LaTeX can handle the graphic file as is.
450         // This is true even if the orig_file is compressed.
451         string const to_format = formats.getFormat(to)->extension();
452         string const file_format = GetExtension(file);
453         // for latex .ps == .eps
454         if (to_format == file_format ||
455             (to_format == "eps" && file_format ==  "ps") ||
456             (to_format ==  "ps" && file_format == "eps"))
457                 return stripExtension(file);
458         return file;
459 }
460
461 } // namespace anon
462
463
464 string const InsetGraphics::prepareFile(Buffer const & buf,
465                                         OutputParams const & runparams) const
466 {
467         // We assume that the file exists (the caller checks this)
468         string const orig_file = params().filename.absFilename();
469         string const rel_file = params().filename.relFilename(buf.filePath());
470
471         // If the file is compressed and we have specified that it
472         // should not be uncompressed, then just return its name and
473         // let LaTeX do the rest!
474         bool const zipped = params().filename.isZipped();
475
476         // temp_file will contain the file for LaTeX to act on if, for example,
477         // we move it to a temp dir or uncompress it.
478         string temp_file = orig_file;
479
480         // The master buffer. This is useful when there are multiple levels
481         // of include files
482         Buffer const * m_buffer = buf.getMasterBuffer();
483
484         // We place all temporary files in the master buffer's temp dir.
485         // This is possible because we use mangled file names.
486         // This is necessary for DVI export.
487         string const temp_path = m_buffer->temppath();
488
489         CopyStatus status;
490         boost::tie(status, temp_file) =
491                         copyToDirIfNeeded(orig_file, temp_path, zipped);
492
493         if (status == FAILURE)
494                 return orig_file;
495
496         // a relative filename should be relative to the master
497         // buffer.
498         // "nice" means that the buffer is exported to LaTeX format but not
499         //        run through the LaTeX compiler.
500         string const output_file = os::external_path(runparams.nice ?
501                 params().filename.outputFilename(m_buffer->filePath()) :
502                 OnlyFilename(temp_file));
503         string const source_file = runparams.nice ? orig_file : temp_file;
504
505         if (zipped) {
506                 if (params().noUnzip) {
507                         // We don't know whether latex can actually handle
508                         // this file, but we can't check, because that would
509                         // mean to unzip the file and thereby making the
510                         // noUnzip parameter meaningless.
511                         lyxerr[Debug::GRAPHICS]
512                                 << "\tpass zipped file to LaTeX.\n";
513
514                         string const bb_orig_file = ChangeExtension(orig_file, "bb");
515                         if (runparams.nice) {
516                                 runparams.exportdata->addExternalFile("latex",
517                                                 bb_orig_file,
518                                                 ChangeExtension(output_file, "bb"));
519                         } else {
520                                 // LaTeX needs the bounding box file in the
521                                 // tmp dir
522                                 string bb_file = ChangeExtension(temp_file, "bb");
523                                 boost::tie(status, bb_file) =
524                                         copyFileIfNeeded(bb_orig_file, bb_file);
525                                 if (status == FAILURE)
526                                         return orig_file;
527                                 runparams.exportdata->addExternalFile("latex",
528                                                 bb_file);
529                         }
530                         runparams.exportdata->addExternalFile("latex",
531                                         source_file, output_file);
532                         runparams.exportdata->addExternalFile("dvi",
533                                         source_file, output_file);
534                         // We can't strip the extension, because we don't know
535                         // the unzipped file format
536                         return output_file;
537                 }
538
539                 string const unzipped_temp_file = unzippedFileName(temp_file);
540                 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
541                         // temp_file has been unzipped already and
542                         // orig_file has not changed in the meantime.
543                         temp_file = unzipped_temp_file;
544                         lyxerr[Debug::GRAPHICS]
545                                 << "\twas already unzipped to " << temp_file
546                                 << endl;
547                 } else {
548                         // unzipped_temp_file does not exist or is too old
549                         temp_file = unzipFile(temp_file);
550                         lyxerr[Debug::GRAPHICS]
551                                 << "\tunzipped to " << temp_file << endl;
552                 }
553         }
554
555         string const from = getExtFromContents(temp_file);
556         string const to   = findTargetFormat(from, runparams);
557         lyxerr[Debug::GRAPHICS]
558                 << "\t we have: from " << from << " to " << to << '\n';
559
560         // We're going to be running the exported buffer through the LaTeX
561         // compiler, so must ensure that LaTeX can cope with the graphics
562         // file format.
563
564         lyxerr[Debug::GRAPHICS]
565                 << "\tthe orig file is: " << orig_file << endl;
566
567         if (from == to) {
568                 // The extension of temp_file might be != to!
569                 runparams.exportdata->addExternalFile("latex", source_file,
570                                                       output_file);
571                 runparams.exportdata->addExternalFile("dvi", source_file,
572                                                       output_file);
573                 return stripExtensionIfPossible(output_file, to);
574         }
575
576         string const to_file = ChangeExtension(temp_file, to);
577         string const output_to_file = ChangeExtension(output_file, to);
578
579         // Do we need to perform the conversion?
580         // Yes if to_file does not exist or if temp_file is newer than to_file
581         if (compare_timestamps(temp_file, to_file) < 0) {
582                 lyxerr[Debug::GRAPHICS]
583                         << bformat(_("No conversion of %1$s is needed after all"),
584                                    rel_file)
585                         << std::endl;
586                 runparams.exportdata->addExternalFile("latex", to_file,
587                                                       output_to_file);
588                 runparams.exportdata->addExternalFile("dvi", to_file,
589                                                       output_to_file);
590                 return stripExtension(output_file);
591         }
592
593         lyxerr[Debug::GRAPHICS]
594                 << "\tThe original file is " << orig_file << "\n"
595                 << "\tA copy has been made and convert is to be called with:\n"
596                 << "\tfile to convert = " << temp_file << '\n'
597                 << "\t from " << from << " to " << to << '\n';
598
599         // if no special converter defined, then we take the default one
600         // from ImageMagic: convert from:inname.from to:outname.to
601         if (!converters.convert(&buf, temp_file, temp_file, from, to)) {
602                 string const command =
603                         "sh " + LibFileSearch("scripts", "convertDefault.sh") +
604                                 ' ' + from + ':' + temp_file + ' ' +
605                                 to + ':' + to_file;
606                 lyxerr[Debug::GRAPHICS]
607                         << "No converter defined! I use convertDefault.sh:\n\t"
608                         << command << endl;
609                 Systemcall one;
610                 one.startscript(Systemcall::Wait, command);
611                 if (IsFileReadable(to_file)) {
612                         runparams.exportdata->addExternalFile("latex",
613                                         to_file, output_to_file);
614                         runparams.exportdata->addExternalFile("dvi",
615                                         to_file, output_to_file);
616                 } else {
617                         string str = bformat(_("No information for converting %1$s "
618                                 "format files to %2$s.\n"
619                                 "Try defining a convertor in the preferences."), from, to);
620                         Alert::error(_("Could not convert image"), str);
621                 }
622         }
623
624         return stripExtension(output_file);
625 }
626
627
628 int InsetGraphics::latex(Buffer const & buf, ostream & os,
629                          OutputParams const & runparams) const
630 {
631         // If there is no file specified or not existing,
632         // just output a message about it in the latex output.
633         lyxerr[Debug::GRAPHICS]
634                 << "insetgraphics::latex: Filename = "
635                 << params().filename.absFilename() << endl;
636
637         string const relative_file =
638                 params().filename.relFilename(buf.filePath());
639
640         string const file_ = params().filename.absFilename();
641         bool const file_exists = !file_.empty() && IsFileReadable(file_);
642         string const message = file_exists ?
643                 string() : string("bb = 0 0 200 100, draft, type=eps");
644         // if !message.empty() then there was no existing file
645         // "filename" found. In this case LaTeX
646         // draws only a rectangle with the above bb and the
647         // not found filename in it.
648         lyxerr[Debug::GRAPHICS]
649                 << "\tMessage = \"" << message << '\"' << endl;
650
651         // These variables collect all the latex code that should be before and
652         // after the actual includegraphics command.
653         string before;
654         string after;
655         // Do we want subcaptions?
656         if (params().subcaption) {
657                 before += "\\subfigure[" + params().subcaptionText + "]{";
658                 after = '}';
659         }
660         // We never use the starred form, we use the "clip" option instead.
661         before += "\\includegraphics";
662
663         // Write the options if there are any.
664         string const opts = createLatexOptions();
665         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
666
667         if (!opts.empty() && !message.empty())
668                 before += ("[%\n" + opts + ',' + message + ']');
669         else if (!opts.empty() || !message.empty())
670                 before += ("[%\n" + opts + message + ']');
671
672         lyxerr[Debug::GRAPHICS]
673                 << "\tBefore = " << before
674                 << "\n\tafter = " << after << endl;
675
676
677         string latex_str = before + '{';
678         if (file_exists)
679                 // Convert the file if necessary.
680                 // Remove the extension so the LaTeX will use whatever
681                 // is appropriate (when there are several versions in
682                 // different formats)
683                 latex_str += prepareFile(buf, runparams);
684         else
685                 latex_str += relative_file + " not found!";
686
687         latex_str += '}' + after;
688         os << latex_str;
689
690         lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
691                                 << latex_str << endl;
692         // Return how many newlines we issued.
693         return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
694 }
695
696
697 int InsetGraphics::plaintext(Buffer const &, ostream & os,
698                          OutputParams const &) const
699 {
700         // No graphics in ascii output. Possible to use gifscii to convert
701         // images to ascii approximation.
702         // 1. Convert file to ascii using gifscii
703         // 2. Read ascii output file and add it to the output stream.
704         // at least we send the filename
705         os << '<' << bformat(_("Graphics file: %1$s"),
706                              params().filename.absFilename()) << ">\n";
707         return 0;
708 }
709
710
711 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
712                             OutputParams const & runparams) const
713 {
714         string const file_name = runparams.nice ?
715                                 params().filename.relFilename(buf.filePath()):
716                                 params().filename.absFilename();
717
718         runparams.exportdata->addExternalFile("linuxdoc",
719                                               params().filename.absFilename());
720         os << "<eps file=\"" << file_name << "\">\n";
721         os << "<img src=\"" << file_name << "\">";
722         return 0;
723 }
724
725
726 // For explanation on inserting graphics into DocBook checkout:
727 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
728 // See also the docbook guide at http://www.docbook.org/
729 int InsetGraphics::docbook(Buffer const &, ostream & os,
730                            OutputParams const & runparams) const
731 {
732         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
733         // need to switch to MediaObject. However, for now this is sufficient and
734         // easier to use.
735         if (runparams.flavor == OutputParams::XML) {
736                 runparams.exportdata->addExternalFile("docbook-xml",
737                                                       params().filename.absFilename());
738                 os << "<inlinegraphic fileref=\"&" << graphic_label << ";\" " + createDocBookAttributes() + "/>";
739         } else {
740                 runparams.exportdata->addExternalFile("docbook",
741                                                       params().filename.absFilename());
742                 os << "<inlinegraphic fileref=\"&" << graphic_label << ";\" " + createDocBookAttributes() + "/>";
743         }
744         return 0;
745 }
746
747
748 void InsetGraphics::validate(LaTeXFeatures & features) const
749 {
750         // If we have no image, we should not require anything.
751         if (params().filename.empty())
752                 return;
753
754         features.includeFile(graphic_label,
755                              RemoveExtension(params().filename.absFilename()));
756
757         features.require("graphicx");
758
759         if (features.nice()) {
760                 Buffer const * m_buffer = features.buffer().getMasterBuffer();
761                 string basename =
762                         params().filename.outputFilename(m_buffer->filePath());
763                 basename = RemoveExtension(basename);
764                 if(params().filename.isZipped())
765                         basename = RemoveExtension(basename);
766                 if (contains(basename, "."))
767                         features.require("lyxdot");
768         }
769
770         if (params().subcaption)
771                 features.require("subfigure");
772 }
773
774
775 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
776 {
777         // If nothing is changed, just return and say so.
778         if (params() == p && !p.filename.empty())
779                 return false;
780
781         // Copy the new parameters.
782         params_ = p;
783
784         // Update the display using the new parameters.
785         graphic_->update(params().as_grfxParams());
786
787         // We have changed data, report it.
788         return true;
789 }
790
791
792 InsetGraphicsParams const & InsetGraphics::params() const
793 {
794         return params_;
795 }
796
797
798 void InsetGraphics::editGraphics(InsetGraphicsParams const & p, Buffer const & buffer) const
799 {
800         string const file_with_path = p.filename.absFilename();
801         formats.edit(buffer, file_with_path, getExtFromContents(file_with_path));
802 }
803
804
805 string const InsetGraphicsMailer::name_("graphics");
806
807 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
808         : inset_(inset)
809 {}
810
811
812 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
813 {
814         return params2string(inset_.params(), buffer);
815 }
816
817
818 void InsetGraphicsMailer::string2params(string const & in,
819                                         Buffer const & buffer,
820                                         InsetGraphicsParams & params)
821 {
822         params = InsetGraphicsParams();
823         if (in.empty())
824                 return;
825
826         istringstream data(in);
827         LyXLex lex(0,0);
828         lex.setStream(data);
829
830         string name;
831         lex >> name;
832         if (!lex || name != name_)
833                 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
834
835         InsetGraphics inset;
836         inset.readInsetGraphics(lex, buffer.filePath());
837         params = inset.params();
838 }
839
840
841 string const
842 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
843                                    Buffer const & buffer)
844 {
845         ostringstream data;
846         data << name_ << ' ';
847         params.Write(data, buffer.filePath());
848         data << "\\end_inset\n";
849         return data.str();
850 }