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