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