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