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