]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
Change to use preffered calling of Boost.Function
[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 namespace {
341
342 enum CopyStatus {
343         SUCCESS,
344         FAILURE,
345         IDENTICAL_PATHS,
346         IDENTICAL_CONTENTS
347 };
348
349
350 std::pair<CopyStatus, string> const
351 copyFileIfNeeded(string const & file_in, string const & file_out)
352 {
353         BOOST_ASSERT(AbsolutePath(file_in));
354         BOOST_ASSERT(AbsolutePath(file_out));
355
356         unsigned long const checksum_in  = support::sum(file_in);
357         unsigned long const checksum_out = support::sum(file_out);
358
359         if (checksum_in == checksum_out)
360                 // Nothing to do...
361                 return std::make_pair(IDENTICAL_CONTENTS, file_out);
362
363         bool const success = support::copy(file_in, file_out);
364         if (!success) {
365                 lyxerr[Debug::GRAPHICS]
366                         << support::bformat(_("Could not copy the file\n%1$s\n"
367                                               "into the temporary directory."),
368                                             file_in)
369                         << std::endl;
370         }
371
372         CopyStatus status = success ? SUCCESS : FAILURE;
373         return std::make_pair(status, file_out);
374 }
375
376
377 std::pair<CopyStatus, string> const
378 copyToDirIfNeeded(string const & file_in, string const & dir, bool zipped)
379 {
380         using support::rtrim;
381
382         BOOST_ASSERT(AbsolutePath(file_in));
383
384         string const only_path = support::OnlyPath(file_in);
385         if (rtrim(support::OnlyPath(file_in) , "/") == rtrim(dir, "/"))
386                 return std::make_pair(IDENTICAL_PATHS, file_in);
387
388         string mangled = FileName(file_in).mangledFilename();
389         if (zipped) {
390                 // We need to change _eps.gz to .eps.gz. The mangled name is
391                 // still unique because of the counter in mangledFilename().
392                 // We can't just call mangledFilename() with the zip
393                 // extension removed, because base.eps and base.eps.gz may
394                 // have different content but would get the same mangled
395                 // name in this case.
396                 string const base = RemoveExtension(unzippedFileName(file_in));
397                 string::size_type const ext_len = file_in.length() - base.length();
398                 mangled[mangled.length() - ext_len] = '.';
399         }
400         string const file_out = support::MakeAbsPath(mangled, dir);
401
402         return copyFileIfNeeded(file_in, file_out);
403 }
404
405
406 string const stripExtension(string const & file)
407 {
408         // Remove the extension so the LaTeX will use whatever
409         // is appropriate (when there are several versions in
410         // different formats)
411         // This works only if the filename contains no dots besides
412         // the just removed one. We can fool here by replacing all
413         // dots with a macro whose definition is just a dot ;-)
414         return subst(RemoveExtension(file), ".", "\\lyxdot ");
415 }
416
417
418 string const stripExtensionIfPossible(string const & file, string const & to)
419 {
420         // No conversion is needed. LaTeX can handle the graphic file as is.
421         // This is true even if the orig_file is compressed.
422         string const to_format = formats.getFormat(to)->extension();
423         string const file_format = GetExtension(file);
424         // for latex .ps == .eps
425         if (to_format == file_format ||
426             (to_format == "eps" && file_format ==  "ps") ||
427             (to_format ==  "ps" && file_format == "eps"))
428                 return stripExtension(file);
429         return file;
430 }
431
432 } // namespace anon
433
434
435 string const InsetGraphics::prepareFile(Buffer const & buf,
436                                         OutputParams const & runparams) const
437 {
438         // We assume that the file exists (the caller checks this)
439         string const orig_file = params().filename.absFilename();
440         string const rel_file = params().filename.relFilename(buf.filePath());
441
442         // If the file is compressed and we have specified that it
443         // should not be uncompressed, then just return its name and
444         // let LaTeX do the rest!
445         bool const zipped = params().filename.isZipped();
446
447         // temp_file will contain the file for LaTeX to act on if, for example,
448         // we move it to a temp dir or uncompress it.
449         string temp_file = orig_file;
450
451         // The master buffer. This is useful when there are multiple levels
452         // of include files
453         Buffer const * m_buffer = buf.getMasterBuffer();
454
455         // We place all temporary files in the master buffer's temp dir.
456         // This is possible because we use mangled file names.
457         // This is necessary for DVI export.
458         string const temp_path = m_buffer->temppath();
459
460         CopyStatus status;
461         boost::tie(status, temp_file) =
462                         copyToDirIfNeeded(orig_file, temp_path, zipped);
463
464         if (status == FAILURE)
465                 return orig_file;
466
467         // a relative filename should be relative to the master
468         // buffer.
469         // "nice" means that the buffer is exported to LaTeX format but not
470         //        run through the LaTeX compiler.
471         string const output_file = os::external_path(runparams.nice ?
472                 params().filename.outputFilename(m_buffer->filePath()) :
473                 OnlyFilename(temp_file));
474         string const source_file = runparams.nice ? orig_file : temp_file;
475
476         if (zipped) {
477                 if (params().noUnzip) {
478                         // We don't know whether latex can actually handle
479                         // this file, but we can't check, because that would
480                         // mean to unzip the file and thereby making the
481                         // noUnzip parameter meaningless.
482                         lyxerr[Debug::GRAPHICS]
483                                 << "\tpass zipped file to LaTeX.\n";
484
485                         string const bb_orig_file = ChangeExtension(orig_file, "bb");
486                         if (runparams.nice) {
487                                 runparams.exportdata->addExternalFile("latex",
488                                                 bb_orig_file,
489                                                 ChangeExtension(output_file, "bb"));
490                         } else {
491                                 // LaTeX needs the bounding box file in the
492                                 // tmp dir
493                                 string bb_file = ChangeExtension(temp_file, "bb");
494                                 boost::tie(status, bb_file) =
495                                         copyFileIfNeeded(bb_orig_file, bb_file);
496                                 if (status == FAILURE)
497                                         return orig_file;
498                                 runparams.exportdata->addExternalFile("latex",
499                                                 bb_file);
500                         }
501                         runparams.exportdata->addExternalFile("latex",
502                                         source_file, output_file);
503                         runparams.exportdata->addExternalFile("dvi",
504                                         source_file, output_file);
505                         // We can't strip the extension, because we don't know
506                         // the unzipped file format
507                         return output_file;
508                 }
509
510                 string const unzipped_temp_file = unzippedFileName(temp_file);
511                 if (compare_timestamps(unzipped_temp_file, temp_file) > 0) {
512                         // temp_file has been unzipped already and
513                         // orig_file has not changed in the meantime.
514                         temp_file = unzipped_temp_file;
515                         lyxerr[Debug::GRAPHICS]
516                                 << "\twas already unzipped to " << temp_file
517                                 << endl;
518                 } else {
519                         // unzipped_temp_file does not exist or is too old
520                         temp_file = unzipFile(temp_file);
521                         lyxerr[Debug::GRAPHICS]
522                                 << "\tunzipped to " << temp_file << endl;
523                 }
524         }
525
526         string const from = getExtFromContents(temp_file);
527         string const to   = findTargetFormat(from, runparams);
528         lyxerr[Debug::GRAPHICS]
529                 << "\t we have: from " << from << " to " << to << '\n';
530
531         // We're going to be running the exported buffer through the LaTeX
532         // compiler, so must ensure that LaTeX can cope with the graphics
533         // file format.
534
535         lyxerr[Debug::GRAPHICS]
536                 << "\tthe orig file is: " << orig_file << endl;
537
538         if (from == to) {
539                 // The extension of temp_file might be != to!
540                 runparams.exportdata->addExternalFile("latex", source_file,
541                                                       output_file);
542                 runparams.exportdata->addExternalFile("dvi", source_file,
543                                                       output_file);
544                 return stripExtensionIfPossible(output_file, to);
545         }
546
547         string const to_file = ChangeExtension(temp_file, to);
548         string const output_to_file = ChangeExtension(output_file, to);
549
550         // Do we need to perform the conversion?
551         // Yes if to_file does not exist or if temp_file is newer than to_file
552         if (compare_timestamps(temp_file, to_file) < 0) {
553                 lyxerr[Debug::GRAPHICS]
554                         << bformat(_("No conversion of %1$s is needed after all"),
555                                    rel_file)
556                         << std::endl;
557                 runparams.exportdata->addExternalFile("latex", to_file,
558                                                       output_to_file);
559                 runparams.exportdata->addExternalFile("dvi", to_file,
560                                                       output_to_file);
561                 return stripExtension(output_file);
562         }
563
564         lyxerr[Debug::GRAPHICS]
565                 << "\tThe original file is " << orig_file << "\n"
566                 << "\tA copy has been made and convert is to be called with:\n"
567                 << "\tfile to convert = " << temp_file << '\n'
568                 << "\t from " << from << " to " << to << '\n';
569
570         // if no special converter defined, then we take the default one
571         // from ImageMagic: convert from:inname.from to:outname.to
572         if (!converters.convert(&buf, temp_file, temp_file, from, to)) {
573                 string const command =
574                         "sh " + LibFileSearch("scripts", "convertDefault.sh") +
575                                 ' ' + from + ':' + temp_file + ' ' +
576                                 to + ':' + to_file;
577                 lyxerr[Debug::GRAPHICS]
578                         << "No converter defined! I use convertDefault.sh:\n\t"
579                         << command << endl;
580                 Systemcall one;
581                 one.startscript(Systemcall::Wait, command);
582                 if (IsFileReadable(to_file)) {
583                         runparams.exportdata->addExternalFile("latex",
584                                         to_file, output_to_file);
585                         runparams.exportdata->addExternalFile("dvi",
586                                         to_file, output_to_file);
587                 } else {
588                         string str = bformat(_("No information for converting %1$s "
589                                 "format files to %2$s.\n"
590                                 "Try defining a convertor in the preferences."), from, to);
591                         Alert::error(_("Could not convert image"), str);
592                 }
593         }
594
595         return stripExtension(output_file);
596 }
597
598
599 int InsetGraphics::latex(Buffer const & buf, ostream & os,
600                          OutputParams const & runparams) const
601 {
602         // If there is no file specified or not existing,
603         // just output a message about it in the latex output.
604         lyxerr[Debug::GRAPHICS]
605                 << "insetgraphics::latex: Filename = "
606                 << params().filename.absFilename() << endl;
607
608         string const relative_file =
609                 params().filename.relFilename(buf.filePath());
610
611         string const file_ = params().filename.absFilename();
612         bool const file_exists = !file_.empty() && IsFileReadable(file_);
613         string const message = file_exists ?
614                 string() : string("bb = 0 0 200 100, draft, type=eps");
615         // if !message.empty() then there was no existing file
616         // "filename" found. In this case LaTeX
617         // draws only a rectangle with the above bb and the
618         // not found filename in it.
619         lyxerr[Debug::GRAPHICS]
620                 << "\tMessage = \"" << message << '\"' << endl;
621
622         // These variables collect all the latex code that should be before and
623         // after the actual includegraphics command.
624         string before;
625         string after;
626         // Do we want subcaptions?
627         if (params().subcaption) {
628                 before += "\\subfigure[" + params().subcaptionText + "]{";
629                 after = '}';
630         }
631         // We never use the starred form, we use the "clip" option instead.
632         before += "\\includegraphics";
633
634         // Write the options if there are any.
635         string const opts = createLatexOptions();
636         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
637
638         if (!opts.empty() && !message.empty())
639                 before += ("[%\n" + opts + ',' + message + ']');
640         else if (!opts.empty() || !message.empty())
641                 before += ("[%\n" + opts + message + ']');
642
643         lyxerr[Debug::GRAPHICS]
644                 << "\tBefore = " << before
645                 << "\n\tafter = " << after << endl;
646
647
648         string latex_str = before + '{';
649         if (file_exists)
650                 // Convert the file if necessary.
651                 // Remove the extension so the LaTeX will use whatever
652                 // is appropriate (when there are several versions in
653                 // different formats)
654                 latex_str += prepareFile(buf, runparams);
655         else
656                 latex_str += relative_file + " not found!";
657
658         latex_str += '}' + after;
659         os << latex_str;
660
661         lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
662                                 << latex_str << endl;
663         // Return how many newlines we issued.
664         return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
665 }
666
667
668 int InsetGraphics::plaintext(Buffer const &, ostream & os,
669                          OutputParams const &) const
670 {
671         // No graphics in ascii output. Possible to use gifscii to convert
672         // images to ascii approximation.
673         // 1. Convert file to ascii using gifscii
674         // 2. Read ascii output file and add it to the output stream.
675         // at least we send the filename
676         os << '<' << bformat(_("Graphics file: %1$s"),
677                              params().filename.absFilename()) << ">\n";
678         return 0;
679 }
680
681
682 int InsetGraphics::linuxdoc(Buffer const & buf, ostream & os,
683                             OutputParams const & runparams) const
684 {
685         string const file_name = runparams.nice ?
686                                 params().filename.relFilename(buf.filePath()):
687                                 params().filename.absFilename();
688
689         runparams.exportdata->addExternalFile("linuxdoc",
690                                               params().filename.absFilename());
691         os << "<eps file=\"" << file_name << "\">\n";
692         os << "<img src=\"" << file_name << "\">";
693         return 0;
694 }
695
696
697 // For explanation on inserting graphics into DocBook checkout:
698 // http://en.tldp.org/LDP/LDP-Author-Guide/html/inserting-pictures.html
699 // See also the docbook guide at http://www.docbook.org/
700 int InsetGraphics::docbook(Buffer const &, ostream & os,
701                            OutputParams const & runparams) const
702 {
703         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
704         // need to switch to MediaObject. However, for now this is sufficient and
705         // easier to use.
706         if (runparams.flavor == OutputParams::XML) {
707                 runparams.exportdata->addExternalFile("docbook-xml",
708                                                       params().filename.absFilename());
709                 os << "<graphic fileref=\"&" << graphic_label << ";\"/>";
710         } else {
711                 runparams.exportdata->addExternalFile("docbook",
712                                                       params().filename.absFilename());
713                 os << "<graphic fileref=\"&" << graphic_label << ";\">";
714         }
715         return 0;
716 }
717
718
719 void InsetGraphics::validate(LaTeXFeatures & features) const
720 {
721         // If we have no image, we should not require anything.
722         if (params().filename.empty())
723                 return;
724
725         features.includeFile(graphic_label,
726                              RemoveExtension(params().filename.absFilename()));
727
728         features.require("graphicx");
729
730         if (features.nice()) {
731                 Buffer const * m_buffer = features.buffer().getMasterBuffer();
732                 string basename =
733                         params().filename.outputFilename(m_buffer->filePath());
734                 basename = RemoveExtension(basename);
735                 if(params().filename.isZipped())
736                         basename = RemoveExtension(basename);
737                 if (contains(basename, "."))
738                         features.require("lyxdot");
739         }
740
741         if (params().subcaption)
742                 features.require("subfigure");
743 }
744
745
746 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
747 {
748         // If nothing is changed, just return and say so.
749         if (params() == p && !p.filename.empty())
750                 return false;
751
752         // Copy the new parameters.
753         params_ = p;
754
755         // Update the display using the new parameters.
756         graphic_->update(params().as_grfxParams());
757
758         // We have changed data, report it.
759         return true;
760 }
761
762
763 InsetGraphicsParams const & InsetGraphics::params() const
764 {
765         return params_;
766 }
767
768
769 void InsetGraphics::editGraphics(InsetGraphicsParams const & p, Buffer const & buffer) const
770 {
771         string const file_with_path = p.filename.absFilename();
772         formats.edit(buffer, file_with_path, getExtFromContents(file_with_path));
773 }
774
775
776 string const InsetGraphicsMailer::name_("graphics");
777
778 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
779         : inset_(inset)
780 {}
781
782
783 string const InsetGraphicsMailer::inset2string(Buffer const & buffer) const
784 {
785         return params2string(inset_.params(), buffer);
786 }
787
788
789 void InsetGraphicsMailer::string2params(string const & in,
790                                         Buffer const & buffer,
791                                         InsetGraphicsParams & params)
792 {
793         params = InsetGraphicsParams();
794         if (in.empty())
795                 return;
796
797         istringstream data(in);
798         LyXLex lex(0,0);
799         lex.setStream(data);
800
801         string name;
802         lex >> name;
803         if (!lex || name != name_)
804                 return print_mailer_error("InsetGraphicsMailer", in, 1, name_);
805
806         InsetGraphics inset;
807         inset.readInsetGraphics(lex, buffer.filePath());
808         params = inset.params();
809 }
810
811
812 string const
813 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
814                                    Buffer const & buffer)
815 {
816         ostringstream data;
817         data << name_ << ' ';
818         params.Write(data, buffer.filePath());
819         data << "\\end_inset\n";
820         return data.str();
821 }