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