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