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