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