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