]> git.lyx.org Git - features.git/blob - src/insets/insetgraphics.C
two-phase-drawing for InsetText & InsetTabular
[features.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         dim_ = dim;
208 }
209
210
211 void InsetGraphics::draw(PainterInfo & pi, int x, int y) const
212 {
213         graphic_->draw(pi, x, y);
214 }
215
216
217 Inset::EDITABLE InsetGraphics::editable() const
218 {
219         return IS_EDITABLE;
220 }
221
222
223 void InsetGraphics::write(Buffer const * buf, ostream & os) const
224 {
225         os << "Graphics\n";
226         params().Write(os, buf->filePath());
227 }
228
229
230 void InsetGraphics::read(Buffer const * buf, LyXLex & lex)
231 {
232         string const token = lex.getString();
233
234         if (token == "Graphics")
235                 readInsetGraphics(lex, buf->filePath());
236         else
237                 lyxerr[Debug::GRAPHICS] << "Not a Graphics inset!\n";
238
239         graphic_->update(params().as_grfxParams());
240 }
241
242
243 void InsetGraphics::readInsetGraphics(LyXLex & lex, string const & bufpath)
244 {
245         bool finished = false;
246
247         while (lex.isOK() && !finished) {
248                 lex.next();
249
250                 string const token = lex.getString();
251                 lyxerr[Debug::GRAPHICS] << "Token: '" << token << '\''
252                                     << std::endl;
253
254                 if (token.empty()) {
255                         continue;
256                 } else if (token == "\\end_inset") {
257                         finished = true;
258                 } else if (token == "FormatVersion") {
259                         lex.next();
260                         int version = lex.getInteger();
261                         if (version > VersionNumber)
262                                 lyxerr
263                                 << "This document was created with a newer Graphics widget"
264                                 ", You should use a newer version of LyX to read this"
265                                 " file."
266                                 << std::endl;
267                         // TODO: Possibly open up a dialog?
268                 }
269                 else {
270                         if (!params_.Read(lex, token, bufpath))
271                                 lyxerr << "Unknown token, " << token << ", skipping."
272                                         << std::endl;
273                 }
274         }
275 }
276
277
278 string const InsetGraphics::createLatexOptions() const
279 {
280         // Calculate the options part of the command, we must do it to a string
281         // stream since we might have a trailing comma that we would like to remove
282         // before writing it to the output stream.
283         ostringstream options;
284         if (!params().bb.empty())
285             options << "  bb=" << rtrim(params().bb) << ",\n";
286         if (params().draft)
287             options << "  draft,\n";
288         if (params().clip)
289             options << "  clip,\n";
290         if (!float_equal(params().scale, 0.0, 0.05)) {
291                 if (!float_equal(params().scale, 100.0, 0.05))
292                         options << "  scale=" << params().scale / 100.0
293                                 << ",\n";
294         } else {
295                 if (!params().width.zero())
296                         options << "  width=" << params().width.asLatexString() << ",\n";
297                 if (!params().height.zero())
298                         options << "  height=" << params().height.asLatexString() << ",\n";
299                 if (params().keepAspectRatio)
300                         options << "  keepaspectratio,\n";
301         }
302
303         // Make sure rotation angle is not very close to zero;
304         // a float can be effectively zero but not exactly zero.
305         if (!float_equal(params().rotateAngle, 0, 0.001)) {
306             options << "  angle=" << params().rotateAngle << ",\n";
307             if (!params().rotateOrigin.empty()) {
308                 options << "  origin=" << params().rotateOrigin[0];
309                 if (contains(params().rotateOrigin,"Top"))
310                     options << 't';
311                 else if (contains(params().rotateOrigin,"Bottom"))
312                     options << 'b';
313                 else if (contains(params().rotateOrigin,"Baseline"))
314                     options << 'B';
315                 options << ",\n";
316             }
317         }
318
319         if (!params().special.empty())
320             options << params().special << ",\n";
321
322         string opts = STRCONV(options.str());
323         // delete last ",\n"
324         return opts.substr(0, opts.size() - 2);
325 }
326
327
328 string const InsetGraphics::prepareFile(Buffer const * buf,
329                                         LatexRunParams const & runparams) const
330 {
331         // LaTeX can cope if the graphics file doesn't exist, so just return the
332         // filename.
333         string orig_file = params().filename;
334         string const rel_file = MakeRelPath(orig_file, buf->filePath());
335
336         if (!IsFileReadable(orig_file)) {
337                 lyxerr[Debug::GRAPHICS]
338                         << "InsetGraphics::prepareFile\n"
339                         << "No file '" << orig_file << "' can be found!" << endl;
340                 return rel_file;
341         }
342
343         bool const zipped = zippedFile(orig_file);
344
345         // If the file is compressed and we have specified that it
346         // should not be uncompressed, then just return its name and
347         // let LaTeX do the rest!
348         if (zipped && params().noUnzip) {
349                 lyxerr[Debug::GRAPHICS]
350                         << "\tpass zipped file to LaTeX but with full path.\n";
351                 // LaTeX needs an absolute path, otherwise the
352                 // coresponding *.eps.bb file isn't found
353                 return orig_file;
354         }
355
356         // temp_file will contain the file for LaTeX to act on if, for example,
357         // we move it to a temp dir or uncompress it.
358         string temp_file = orig_file;
359
360         if (zipped) {
361                 // Uncompress the file if necessary.
362                 // If it has been uncompressed in a previous call to
363                 // prepareFile, do nothing.
364                 temp_file = MakeAbsPath(OnlyFilename(temp_file), buf->tmppath);
365                 lyxerr[Debug::GRAPHICS]
366                         << "\ttemp_file: " << temp_file << endl;
367                 if (graphic_->hasFileChanged() || !IsFileReadable(temp_file)) {
368                         bool const success = copy(orig_file, temp_file);
369                         lyxerr[Debug::GRAPHICS]
370                                 << "\tCopying zipped file from "
371                                 << orig_file << " to " << temp_file
372                                 << (success ? " succeeded\n" : " failed\n");
373                 } else
374                         lyxerr[Debug::GRAPHICS]
375                                 << "\tzipped file " << temp_file
376                                 << " exists! Maybe no tempdir ...\n";
377                 orig_file = unzipFile(temp_file);
378                 lyxerr[Debug::GRAPHICS]
379                         << "\tunzipped to " << orig_file << endl;
380         }
381
382         string const from = getExtFromContents(orig_file);
383         string const to   = findTargetFormat(from, runparams);
384         lyxerr[Debug::GRAPHICS]
385                 << "\t we have: from " << from << " to " << to << '\n';
386
387         if (from == to && !lyxrc.use_tempdir) {
388                 // No conversion is needed. LaTeX can handle the
389                 // graphic file as is.
390                 // This is true even if the orig_file is compressed.
391                 if (formats.getFormat(to)->extension() == GetExtension(orig_file))
392                         return RemoveExtension(orig_file);
393                 return orig_file;
394         }
395
396         // We're going to be running the exported buffer through the LaTeX
397         // compiler, so must ensure that LaTeX can cope with the graphics
398         // file format.
399
400         // Perform all these manipulations on a temporary file if possible.
401         // If we are not using a temp dir, then temp_file contains the
402         // original file.
403         // to allow files with the same name in different dirs
404         // we manipulate the original file "any.dir/file.ext"
405         // to "any_dir_file.ext"! changing the dots in the
406         // dirname is important for the use of ChangeExtension
407         lyxerr[Debug::GRAPHICS]
408                 << "\tthe orig file is: " << orig_file << endl;
409
410         if (lyxrc.use_tempdir) {
411                 temp_file = copyFileToDir(buf->tmppath, orig_file);
412                 if (temp_file.empty()) {
413                         string str = bformat(_("Could not copy the file\n%1$s\n"
414                                                "into the temporary directory."),
415                                              orig_file);
416                         Alert::error(_("Graphics display failed"), str);
417                         return orig_file;
418                 }
419
420                 if (from == to) {
421                         // No conversion is needed. LaTeX can handle the
422                         // graphic file as is.
423                         if (formats.getFormat(to)->extension() == GetExtension(orig_file))
424                                 return RemoveExtension(temp_file);
425                         return temp_file;
426                 }
427         }
428
429         string const outfile_base = RemoveExtension(temp_file);
430         lyxerr[Debug::GRAPHICS]
431                 << "\tThe original file is " << orig_file << "\n"
432                 << "\tA copy has been made and convert is to be called with:\n"
433                 << "\tfile to convert = " << temp_file << '\n'
434                 << "\toutfile_base = " << outfile_base << '\n'
435                 << "\t from " << from << " to " << to << '\n';
436
437         // if no special converter defined, than we take the default one
438         // from ImageMagic: convert from:inname.from to:outname.to
439         if (!converters.convert(buf, temp_file, outfile_base, from, to)) {
440                 string const command =
441                         LibFileSearch("scripts", "convertDefault.sh") +
442                                 ' ' + from + ':' + temp_file + ' ' +
443                                 to + ':' + outfile_base + '.' + to;
444                 lyxerr[Debug::GRAPHICS]
445                         << "No converter defined! I use convertDefault.sh:\n\t"
446                         << command << endl;
447                 Systemcall one;
448                 one.startscript(Systemcall::Wait, command);
449                 if (!IsFileReadable(ChangeExtension(outfile_base, to))) {
450                         string str = bformat(_("No information for converting %1$s "
451                                 "format files to %2$s.\n"
452                                 "Try defining a convertor in the preferences."), from, to);
453                         Alert::error(_("Could not convert image"), str);
454                 }
455         }
456
457         return RemoveExtension(temp_file);
458 }
459
460
461 int InsetGraphics::latex(Buffer const * buf, ostream & os,
462                          LatexRunParams const & runparams) const
463 {
464         // If there is no file specified or not existing,
465         // just output a message about it in the latex output.
466         lyxerr[Debug::GRAPHICS]
467                 << "insetgraphics::latex: Filename = "
468                 << params().filename << endl;
469
470         string const relative_file = MakeRelPath(params().filename, buf->filePath());
471
472         // A missing (e)ps-extension is no problem for LaTeX, so
473         // we have to test three different cases
474 #warning uh, but can our cache handle it ? no.
475         string const file_ = params().filename;
476         bool const file_exists =
477                 !file_.empty() &&
478                 (IsFileReadable(file_) ||               // original
479                  IsFileReadable(file_ + ".eps") ||      // original.eps
480                  IsFileReadable(file_ + ".ps"));        // original.ps
481         string const message = file_exists ?
482                 string() : string("bb = 0 0 200 100, draft, type=eps");
483         // if !message.empty() than there was no existing file
484         // "filename(.(e)ps)" found. In this case LaTeX
485         // draws only a rectangle with the above bb and the
486         // not found filename in it.
487         lyxerr[Debug::GRAPHICS]
488                 << "\tMessage = \"" << message << '\"' << endl;
489
490         // These variables collect all the latex code that should be before and
491         // after the actual includegraphics command.
492         string before;
493         string after;
494         // Do we want subcaptions?
495         if (params().subcaption) {
496                 before += "\\subfigure[" + params().subcaptionText + "]{";
497                 after = '}';
498         }
499         // We never use the starred form, we use the "clip" option instead.
500         before += "\\includegraphics";
501
502         // Write the options if there are any.
503         string const opts = createLatexOptions();
504         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
505
506         if (!opts.empty() && !message.empty())
507                 before += ("[%\n" + opts + ',' + message + ']');
508         else if (!opts.empty() || !message.empty())
509                 before += ("[%\n" + opts + message + ']');
510
511         lyxerr[Debug::GRAPHICS]
512                 << "\tBefore = " << before
513                 << "\n\tafter = " << after << endl;
514
515
516         // "nice" means that the buffer is exported to LaTeX format but not
517         //        run through the LaTeX compiler.
518         if (runparams.nice) {
519                 os << before <<'{' << relative_file << '}' << after;
520                 return 1;
521         }
522
523         // Make the filename relative to the lyx file
524         // and remove the extension so the LaTeX will use whatever is
525         // appropriate (when there are several versions in different formats)
526         string const latex_str = message.empty() ?
527                 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
528                 (before + '{' + relative_file + " not found!}" + after);
529         os << latex_str;
530
531         lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
532                                 << latex_str << endl;
533         // Return how many newlines we issued.
534         return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
535 }
536
537
538 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
539 {
540         // No graphics in ascii output. Possible to use gifscii to convert
541         // images to ascii approximation.
542         // 1. Convert file to ascii using gifscii
543         // 2. Read ascii output file and add it to the output stream.
544         // at least we send the filename
545         os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
546         return 0;
547 }
548
549
550 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
551 {
552         // No graphics in LinuxDoc output. Should check how/what to add.
553         return 0;
554 }
555
556
557 // For explanation on inserting graphics into DocBook checkout:
558 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
559 // See also the docbook guide at http://www.docbook.org/
560 int InsetGraphics::docbook(Buffer const *, ostream & os,
561                            bool /*mixcont*/) const
562 {
563         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
564         // need to switch to MediaObject. However, for now this is sufficient and
565         // easier to use.
566         os << "<graphic fileref=\"&" << graphic_label << ";\">";
567         return 0;
568 }
569
570
571 void InsetGraphics::validate(LaTeXFeatures & features) const
572 {
573         // If we have no image, we should not require anything.
574         if (params().filename.empty())
575                 return;
576
577         features.includeFile(graphic_label, RemoveExtension(params().filename));
578
579         features.require("graphicx");
580
581         if (params().subcaption)
582                 features.require("subfigure");
583 }
584
585
586 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
587 {
588         // If nothing is changed, just return and say so.
589         if (params() == p && !p.filename.empty())
590                 return false;
591
592         // Copy the new parameters.
593         params_ = p;
594
595         // Update the display using the new parameters.
596         graphic_->update(params().as_grfxParams());
597
598         // We have changed data, report it.
599         return true;
600 }
601
602
603 InsetGraphicsParams const & InsetGraphics::params() const
604 {
605         return params_;
606 }
607
608
609 string const InsetGraphicsMailer::name_("graphics");
610
611 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
612         : inset_(inset)
613 {}
614
615
616 string const InsetGraphicsMailer::inset2string() const
617 {
618         return params2string(inset_.params());
619 }
620
621
622 void InsetGraphicsMailer::string2params(string const & in,
623                                         InsetGraphicsParams & params)
624 {
625         params = InsetGraphicsParams();
626
627         if (in.empty())
628                 return;
629
630         istringstream data(STRCONV(in));
631         LyXLex lex(0,0);
632         lex.setStream(data);
633
634         if (lex.isOK()) {
635                 lex.next();
636                 string const token = lex.getString();
637                 if (token != name_)
638                         return;
639         }
640
641         if (lex.isOK()) {
642                 InsetGraphics inset;
643 #warning FIXME not setting bufpath is dubious
644                 inset.readInsetGraphics(lex, string());
645                 params = inset.params();
646         }
647 }
648
649
650 string const
651 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params)
652 {
653         ostringstream data;
654         data << name_ << ' ';
655 #warning FIXME not setting bufpath is dubious
656         params.Write(data, string());
657         data << "\\end_inset\n";
658         return STRCONV(data.str());
659 }