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