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