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