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