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