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