]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
reduce number of metrics calls in InsetTabular calculate_dimensions_
[lyx.git] / src / insets / insetgraphics.C
1 /**
2  * \file insetgraphics.C
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 Voss
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     * Add a way to roll the image file into the file format.
19     * When loading, if the image is not found in the expected place, try
20       to find it in the clipart, or in the same directory with the image.
21     * The image choosing dialog could show thumbnails of the image formats
22       it knows of, thus selection based on the image instead of based on
23       filename.
24     * Add support for the 'picins' package.
25     * Add support for the 'picinpar' package.
26     * Improve support for 'subfigure' - Allow to set the various options
27       that are possible.
28 */
29
30 /* NOTES:
31  * Fileformat:
32  * Current version is 1 (inset file format version), when changing it
33  * it should be changed in the Write() function when writing in one place
34  * and when reading one should change the version check and the error message.
35  * The filename is kept in  the lyx file in a relative way, so as to allow
36  * moving the document file and its images with no problem.
37  *
38  *
39  * Conversions:
40  *   Postscript output means EPS figures.
41  *
42  *   PDF output is best done with PDF figures if it's a direct conversion
43  *   or PNG figures otherwise.
44  *      Image format
45  *      from        to
46  *      EPS         epstopdf
47  *      PS          ps2pdf
48  *      JPG/PNG     direct
49  *      PDF         direct
50  *      others      PNG
51  */
52
53 #include <config.h>
54
55 #include "insets/insetgraphics.h"
56 #include "insets/insetgraphicsParams.h"
57 #include "insets/renderers.h"
58
59 #include "buffer.h"
60 #include "BufferView.h"
61 #include "converter.h"
62 #include "debug.h"
63 #include "format.h"
64 #include "funcrequest.h"
65 #include "gettext.h"
66 #include "LaTeXFeatures.h"
67 #include "latexrunparams.h"
68 #include "Lsstream.h"
69 #include "lyxlex.h"
70 #include "lyxrc.h"
71
72 #include "frontends/Alert.h"
73 #include "frontends/Dialogs.h"
74
75 #include "support/filetools.h"
76 #include "support/lyxalgo.h" // lyx::count
77 #include "support/lyxlib.h" // float_equal
78 #include "support/tostr.h"
79 #include "support/systemcall.h"
80
81 #include <boost/bind.hpp>
82
83 #include <algorithm> // For the std::max
84
85 extern string system_tempdir;
86 // set by Exporters
87
88 using namespace lyx::support;
89
90 using std::ostream;
91 using std::endl;
92
93
94 namespace {
95
96 ///////////////////////////////////////////////////////////////////////////
97 int const VersionNumber = 1;
98 ///////////////////////////////////////////////////////////////////////////
99
100 // This function is a utility function
101 // ... that should be with ChangeExtension ...
102 inline
103 string const RemoveExtension(string const & filename)
104 {
105         return ChangeExtension(filename, string());
106 }
107
108
109 string const uniqueID()
110 {
111         static unsigned int seed = 1000;
112         return "graph" + tostr(++seed);
113 }
114
115
116 string findTargetFormat(string const & suffix, LatexRunParams const & runparams)
117 {
118         // Are we using latex or pdflatex).
119         if (runparams.flavor == LatexRunParams::PDFLATEX) {
120                 lyxerr[Debug::GRAPHICS] << "findTargetFormat: PDF mode\n";
121                 if (contains(suffix, "ps") || suffix == "pdf")
122                         return "pdf";
123                 if (suffix == "jpg")    // pdflatex can use jpeg
124                         return suffix;
125                 return "png";         // and also png
126         }
127         // If it's postscript, we always do eps.
128         lyxerr[Debug::GRAPHICS] << "findTargetFormat: PostScript mode\n";
129         if (suffix != "ps")     // any other than ps
130                 return "eps";         // is changed to eps
131         return suffix;          // let ps untouched
132 }
133
134 } // namespace anon
135
136
137 InsetGraphics::InsetGraphics()
138         : graphic_label(uniqueID()),
139           graphic_(new GraphicRenderer)
140 {
141         graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
142 }
143
144
145 InsetGraphics::InsetGraphics(InsetGraphics const & ig)
146         : Inset(ig),
147           boost::signals::trackable(),
148           graphic_label(uniqueID()),
149           graphic_(new GraphicRenderer(*ig.graphic_))
150 {
151         graphic_->connect(boost::bind(&InsetGraphics::statusChanged, this));
152         setParams(ig.params());
153 }
154
155
156 InsetBase * InsetGraphics::clone() const
157 {
158         return new InsetGraphics(*this);
159 }
160
161
162 InsetGraphics::~InsetGraphics()
163 {
164         InsetGraphicsMailer(*this).hideDialog();
165 }
166
167
168 void InsetGraphics::statusChanged()
169 {
170         BufferView * bv = graphic_->view();
171         if (bv)
172                 bv->updateInset(this);
173 }
174
175
176 dispatch_result InsetGraphics::localDispatch(FuncRequest const & cmd)
177 {
178         switch (cmd.action) {
179         case LFUN_INSET_MODIFY: {
180                 InsetGraphicsParams p;
181                 InsetGraphicsMailer::string2params(cmd.argument, p);
182                 if (!p.filename.empty()) {
183                         setParams(p);
184                         cmd.view()->updateInset(this);
185                 }
186                 return DISPATCHED;
187         }
188
189         case LFUN_INSET_DIALOG_UPDATE:
190                 InsetGraphicsMailer(*this).updateDialog(cmd.view());
191                 return DISPATCHED;
192
193         case LFUN_INSET_EDIT:
194         case LFUN_MOUSE_RELEASE:
195                 InsetGraphicsMailer(*this).showDialog(cmd.view());
196                 return DISPATCHED;
197
198         default:
199                 return Inset::localDispatch(cmd);
200         }
201 }
202
203
204 void InsetGraphics::metrics(MetricsInfo & mi, Dimension & dim) const
205 {
206         graphic_->metrics(mi, dim);
207 }
208
209
210 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
211 {
212         graphic_->draw(pi, x, y);
213 }
214
215
216 Inset::EDITABLE InsetGraphics::editable() const
217 {
218         return IS_EDITABLE;
219 }
220
221
222 void InsetGraphics::write(Buffer const * buf, ostream & os) const
223 {
224         os << "Graphics\n";
225         params().Write(os, buf->filePath());
226 }
227
228
229 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
230 {
231         string const token = lex.getString();
232
233         if (token == "Graphics")
234                 readInsetGraphics(lex, buf->filePath());
235         else
236                 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
237
238         graphic_->update(params().as_grfxParams());
239 }
240
241
242 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
243 {
244         bool finished = false;
245
246         while (lex.isOK() && !finished) {
247                 lex.next();
248
249                 string const token = lex.getString();
250                 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
251                                     << std::endl;
252
253                 if (token.empty()) {
254                         continue;
255                 } else if (token == "\\end_inset") {
256                         finished = true;
257                 } else if (token == "FormatVersion") {
258                         lex.next();
259                         int version = lex.getInteger();
260                         if (version > VersionNumber)
261                                 lyxerr
262                                 << "This document was created with a newer Graphics widget"
263                                 ", You should use a newer version of LyX to read this"
264                                 " file."
265                                 << std::endl;
266                         // TODO: Possibly open up a dialog?
267                 }
268                 else {
269                         if (!params_.Read(lex, token, bufpath))
270                                 lyxerr << "Unknown token, " << token << ", skipping."
271                                         << std::endl;
272                 }
273         }
274 }
275
276
277 string const InsetGraphics::createLatexOptions() const
278 {
279         // Calculate the options part of the command, we must do it to a string
280         // stream since we might have a trailing comma that we would like to remove
281         // before writing it to the output stream.
282         ostringstream options;
283         if (!params().bb.empty())
284             options << "  bb=" << rtrim(params().bb) << ",\n";
285         if (params().draft)
286             options << "  draft,\n";
287         if (params().clip)
288             options << "  clip,\n";
289         if (!float_equal(params().scale, 0.0, 0.05)) {
290                 if (!float_equal(params().scale, 100.0, 0.05))
291                         options << "  scale=" << params().scale / 100.0
292                                 << ",\n";
293         } else {
294                 if (!params().width.zero())
295                         options << "  width=" << params().width.asLatexString() << ",\n";
296                 if (!params().height.zero())
297                         options << "  height=" << params().height.asLatexString() << ",\n";
298                 if (params().keepAspectRatio)
299                         options << "  keepaspectratio,\n";
300         }
301
302         // Make sure rotation angle is not very close to zero;
303         // a float can be effectively zero but not exactly zero.
304         if (!float_equal(params().rotateAngle, 0, 0.001)) {
305             options << "  angle=" << params().rotateAngle << ",\n";
306             if (!params().rotateOrigin.empty()) {
307                 options << "  origin=" << params().rotateOrigin[0];
308                 if (contains(params().rotateOrigin,"Top"))
309                     options << 't';
310                 else if (contains(params().rotateOrigin,"Bottom"))
311                     options << 'b';
312                 else if (contains(params().rotateOrigin,"Baseline"))
313                     options << 'B';
314                 options << ",\n";
315             }
316         }
317
318         if (!params().special.empty())
319             options << params().special << ",\n";
320
321         string opts = STRCONV(options.str());
322         // delete last ",\n"
323         return opts.substr(0, opts.size() - 2);
324 }
325
326
327 string const InsetGraphics::prepareFile(Buffer const * buf,
328                                         LatexRunParams const & runparams) const
329 {
330         // LaTeX can cope if the graphics file doesn't exist, so just return the
331         // filename.
332         string orig_file = params().filename;
333         string const rel_file = MakeRelPath(orig_file, buf->filePath());
334
335         if (!IsFileReadable(orig_file)) {
336                 lyxerr[Debug::GRAPHICS]
337                         << "InsetGraphics::prepareFile\n"
338                         << "No file '" << orig_file << "' can be found!" << endl;
339                 return rel_file;
340         }
341
342         bool const zipped = zippedFile(orig_file);
343
344         // If the file is compressed and we have specified that it
345         // should not be uncompressed, then just return its name and
346         // let LaTeX do the rest!
347         if (zipped && params().noUnzip) {
348                 lyxerr[Debug::GRAPHICS]
349                         << "\tpass zipped file to LaTeX but with full path.\n";
350                 // LaTeX needs an absolute path, otherwise the
351                 // coresponding *.eps.bb file isn't found
352                 return orig_file;
353         }
354
355         // temp_file will contain the file for LaTeX to act on if, for example,
356         // we move it to a temp dir or uncompress it.
357         string temp_file = orig_file;
358
359         if (zipped) {
360                 // Uncompress the file if necessary.
361                 // If it has been uncompressed in a previous call to
362                 // prepareFile, do nothing.
363                 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
364                 lyxerr[Debug::GRAPHICS]
365                         << "\ttemp_file: " << temp_file << endl;
366                 if (graphic_->hasFileChanged() || !IsFileReadable(temp_file)) {
367                         bool const success = copy(orig_file, temp_file);
368                         lyxerr[Debug::GRAPHICS]
369                                 << "\tCopying zipped file from "
370                                 << orig_file << " to " << temp_file
371                                 << (success ? " succeeded\n" : " failed\n");
372                 } else
373                         lyxerr[Debug::GRAPHICS]
374                                 << "\tzipped file " << temp_file
375                                 << " exists! Maybe no tempdir ...\n";
376                 orig_file = unzipFile(temp_file);
377                 lyxerr[Debug::GRAPHICS]
378                         << "\tunzipped to " << orig_file << endl;
379         }
380
381         string const from = getExtFromContents(orig_file);
382         string const to   = findTargetFormat(from, runparams);
383         lyxerr[Debug::GRAPHICS]
384                 << "\t we have: from " << from << " to " << to << '\n';
385
386         if (from == to && !lyxrc.use_tempdir) {
387                 // No conversion is needed. LaTeX can handle the
388                 // graphic file as is.
389                 // This is true even if the orig_file is compressed.
390                 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
391                         return RemoveExtension(orig_file);
392                 return orig_file;
393         }
394
395         // We're going to be running the exported buffer through the LaTeX
396         // compiler, so must ensure that LaTeX can cope with the graphics
397         // file format.
398
399         // Perform all these manipulations on a temporary file if possible.
400         // If we are not using a temp dir, then temp_file contains the
401         // original file.
402         // to allow files with the same name in different dirs
403         // we manipulate the original file "any.dir/file.ext"
404         // to "any_dir_file.ext"! changing the dots in the
405         // dirname is important for the use of ChangeExtension
406         lyxerr[Debug::GRAPHICS]
407                 << "\tthe orig file is: " << orig_file << endl;
408
409         if (lyxrc.use_tempdir) {
410                 temp_file = copyFileToDir(buf->tmppath, orig_file);
411                 if (temp_file.empty()) {
412                         string str = bformat(_("Could not copy the file\n%1$s\n"
413                                                "into the temporary directory."),
414                                              orig_file);
415                         Alert::error(_("Graphics display failed"), str);
416                         return orig_file;
417                 }
418
419                 if (from == to) {
420                         // No conversion is needed. LaTeX can handle the
421                         // graphic file as is.
422                         if (formats.getFormat(to)->extension() == GetExtension(orig_file))
423                                 return RemoveExtension(temp_file);
424                         return temp_file;
425                 }
426         }
427
428         string const outfile_base = RemoveExtension(temp_file);
429         lyxerr[Debug::GRAPHICS]
430                 << "\tThe original file is " << orig_file << "\n"
431                 << "\tA copy has been made and convert is to be called with:\n"
432                 << "\tfile to convert = " << temp_file << '\n'
433                 << "\toutfile_base = " << outfile_base << '\n'
434                 << "\t from " << from << " to " << to << '\n';
435
436         // if no special converter defined, than we take the default one
437         // from ImageMagic: convert from:inname.from to:outname.to
438         if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
439                 string const command =
440                         LibFileSearch("scripts", "convertDefault.sh") +
441                                 ' ' + from + ':' + temp_file + ' ' +
442                                 to + ':' + outfile_base + '.' + to;
443                 lyxerr[Debug::GRAPHICS]
444                         << "No converter defined! I use convertDefault.sh:\n\t"
445                         << command << endl;
446                 Systemcall one;
447                 one.startscript(Systemcall::Wait, command);
448                 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
449                         string str = bformat(_("No information for converting %1$s "
450                                 "format files to %2$s.\n"
451                                 "Try defining a convertor in the preferences."), from, to);
452                         Alert::error(_("Could not convert image"), str);
453                 }
454         }
455
456         return RemoveExtension(temp_file);
457 }
458
459
460 int InsetGraphics::latex(Buffer const * buf, ostream & os,
461                          LatexRunParams const & runparams) const
462 {
463         // If there is no file specified or not existing,
464         // just output a message about it in the latex output.
465         lyxerr[Debug::GRAPHICS]
466                 << "insetgraphics::latex: Filename = "
467                 << params().filename << endl;
468
469         string const relative_file = MakeRelPath(params().filename, buf->filePath());
470
471         // A missing (e)ps-extension is no problem for LaTeX, so
472         // we have to test three different cases
473 #warning uh, but can our cache handle it ? no.
474         string const file_ = params().filename;
475         bool const file_exists =
476                 !file_.empty() &&
477                 (IsFileReadable(file_) ||               // original
478                  IsFileReadable(file_ + ".eps") ||      // original.eps
479                  IsFileReadable(file_ + ".ps"));        // original.ps
480         string const message = file_exists ?
481                 string() : string("bb = 0 0 200 100, draft, type=eps");
482         // if !message.empty() than there was no existing file
483         // "filename(.(e)ps)" found. In this case LaTeX
484         // draws only a rectangle with the above bb and the
485         // not found filename in it.
486         lyxerr[Debug::GRAPHICS]
487                 << "\tMessage = \"" << message << '\"' << endl;
488
489         // These variables collect all the latex code that should be before and
490         // after the actual includegraphics command.
491         string before;
492         string after;
493         // Do we want subcaptions?
494         if (params().subcaption) {
495                 before += "\\subfigure[" + params().subcaptionText + "]{";
496                 after = '}';
497         }
498         // We never use the starred form, we use the "clip" option instead.
499         before += "\\includegraphics";
500
501         // Write the options if there are any.
502         string const opts = createLatexOptions();
503         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
504
505         if (!opts.empty() && !message.empty())
506                 before += ("[%\n" + opts + ',' + message + ']');
507         else if (!opts.empty() || !message.empty())
508                 before += ("[%\n" + opts + message + ']');
509
510         lyxerr[Debug::GRAPHICS]
511                 << "\tBefore = " << before
512                 << "\n\tafter = " << after << endl;
513
514
515         // "nice" means that the buffer is exported to LaTeX format but not
516         //        run through the LaTeX compiler.
517         if (runparams.nice) {
518                 os << before <<'{' << relative_file << '}' << after;
519                 return 1;
520         }
521
522         // Make the filename relative to the lyx file
523         // and remove the extension so the LaTeX will use whatever is
524         // appropriate (when there are several versions in different formats)
525         string const latex_str = message.empty() ?
526                 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
527                 (before + '{' + relative_file + " not found!}" + after);
528         os << latex_str;
529
530         lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
531                                 << latex_str << endl;
532         // Return how many newlines we issued.
533         return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
534 }
535
536
537 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
538 {
539         // No graphics in ascii output. Possible to use gifscii to convert
540         // images to ascii approximation.
541         // 1. Convert file to ascii using gifscii
542         // 2. Read ascii output file and add it to the output stream.
543         // at least we send the filename
544         os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
545         return 0;
546 }
547
548
549 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
550 {
551         // No graphics in LinuxDoc output. Should check how/what to add.
552         return 0;
553 }
554
555
556 // For explanation on inserting graphics into DocBook checkout:
557 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
558 // See also the docbook guide at http://www.docbook.org/
559 int InsetGraphics::docbook(Buffer const *, ostream & os,
560                            bool /*mixcont*/) const
561 {
562         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
563         // need to switch to MediaObject. However, for now this is sufficient and
564         // easier to use.
565         os << "<graphic fileref=\"&" << graphic_label << ";\">";
566         return 0;
567 }
568
569
570 void InsetGraphics::validate(LaTeXFeatures & features) const
571 {
572         // If we have no image, we should not require anything.
573         if (params().filename.empty())
574                 return;
575
576         features.includeFile(graphic_label, RemoveExtension(params().filename));
577
578         features.require("graphicx");
579
580         if (params().subcaption)
581                 features.require("subfigure");
582 }
583
584
585 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
586 {
587         // If nothing is changed, just return and say so.
588         if (params() == p && !p.filename.empty())
589                 return false;
590
591         // Copy the new parameters.
592         params_ = p;
593
594         // Update the display using the new parameters.
595         graphic_->update(params().as_grfxParams());
596
597         // We have changed data, report it.
598         return true;
599 }
600
601
602 InsetGraphicsParams const & InsetGraphics::params() const
603 {
604         return params_;
605 }
606
607
608 string const InsetGraphicsMailer::name_("graphics");
609
610 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
611         : inset_(inset)
612 {}
613
614
615 string const InsetGraphicsMailer::inset2string() const
616 {
617         return params2string(inset_.params());
618 }
619
620
621 void InsetGraphicsMailer::string2params(string const & in,
622                                         InsetGraphicsParams & params)
623 {
624         params = InsetGraphicsParams();
625
626         if (in.empty())
627                 return;
628
629         istringstream data(STRCONV(in));
630         LyXLex lex(0,0);
631         lex.setStream(data);
632
633         if (lex.isOK()) {
634                 lex.next();
635                 string const token = lex.getString();
636                 if (token != name_)
637                         return;
638         }
639
640         if (lex.isOK()) {
641                 InsetGraphics inset;
642 #warning FIXME not setting bufpath is dubious
643                 inset.readInsetGraphics(lex, string());
644                 params = inset.params();
645         }
646 }
647
648
649 string const
650 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
651 {
652         ostringstream data;
653         data << name_ << ' ';
654 #warning FIXME not setting bufpath is dubious
655         params.Write(data, string());
656         data << "\\end_inset\n";
657         return STRCONV(data.str());
658 }