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