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