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