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