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