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