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