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