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