]> git.lyx.org Git - lyx.git/blob - src/insets/insetgraphics.C
cf6917c091473d8c1652009b22a5b9f6378fb57d
[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                 string const bufpath = cmd.view()->buffer()->filePath();
181                 InsetGraphicsParams p;
182                 InsetGraphicsMailer::string2params(cmd.argument, bufpath, 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 Inset::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 Inset::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;
335         string const rel_file = MakeRelPath(orig_file, 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 << endl;
470
471         string const relative_file = MakeRelPath(params().filename, buf->filePath());
472
473         // A missing (e)ps-extension is no problem for LaTeX, so
474         // we have to test three different cases
475 #warning uh, but can our cache handle it ? no.
476         string const file_ = params().filename;
477         bool const file_exists =
478                 !file_.empty() &&
479                 (IsFileReadable(file_) ||               // original
480                  IsFileReadable(file_ + ".eps") ||      // original.eps
481                  IsFileReadable(file_ + ".ps"));        // original.ps
482         string const message = file_exists ?
483                 string() : string("bb = 0 0 200 100, draft, type=eps");
484         // if !message.empty() than there was no existing file
485         // "filename(.(e)ps)" found. In this case LaTeX
486         // draws only a rectangle with the above bb and the
487         // not found filename in it.
488         lyxerr[Debug::GRAPHICS]
489                 << "\tMessage = \"" << message << '\"' << endl;
490
491         // These variables collect all the latex code that should be before and
492         // after the actual includegraphics command.
493         string before;
494         string after;
495         // Do we want subcaptions?
496         if (params().subcaption) {
497                 before += "\\subfigure[" + params().subcaptionText + "]{";
498                 after = '}';
499         }
500         // We never use the starred form, we use the "clip" option instead.
501         before += "\\includegraphics";
502
503         // Write the options if there are any.
504         string const opts = createLatexOptions();
505         lyxerr[Debug::GRAPHICS] << "\tOpts = " << opts << endl;
506
507         if (!opts.empty() && !message.empty())
508                 before += ("[%\n" + opts + ',' + message + ']');
509         else if (!opts.empty() || !message.empty())
510                 before += ("[%\n" + opts + message + ']');
511
512         lyxerr[Debug::GRAPHICS]
513                 << "\tBefore = " << before
514                 << "\n\tafter = " << after << endl;
515
516
517         // "nice" means that the buffer is exported to LaTeX format but not
518         //        run through the LaTeX compiler.
519         if (runparams.nice) {
520                 os << before <<'{' << relative_file << '}' << after;
521                 return 1;
522         }
523
524         // Make the filename relative to the lyx file
525         // and remove the extension so the LaTeX will use whatever is
526         // appropriate (when there are several versions in different formats)
527         string const latex_str = message.empty() ?
528                 (before + '{' + os::external_path(prepareFile(buf, runparams)) + '}' + after) :
529                 (before + '{' + relative_file + " not found!}" + after);
530         os << latex_str;
531
532         lyxerr[Debug::GRAPHICS] << "InsetGraphics::latex outputting:\n"
533                                 << latex_str << endl;
534         // Return how many newlines we issued.
535         return int(lyx::count(latex_str.begin(), latex_str.end(),'\n') + 1);
536 }
537
538
539 int InsetGraphics::ascii(Buffer const *, ostream & os, int) const
540 {
541         // No graphics in ascii output. Possible to use gifscii to convert
542         // images to ascii approximation.
543         // 1. Convert file to ascii using gifscii
544         // 2. Read ascii output file and add it to the output stream.
545         // at least we send the filename
546         os << '<' << bformat(_("Graphics file: %1$s"), params().filename) << ">\n";
547         return 0;
548 }
549
550
551 int InsetGraphics::linuxdoc(Buffer const *, ostream &) const
552 {
553         // No graphics in LinuxDoc output. Should check how/what to add.
554         return 0;
555 }
556
557
558 // For explanation on inserting graphics into DocBook checkout:
559 // http://en.tldp.org/LDP/LDP-Author-Guide/inserting-pictures.html
560 // See also the docbook guide at http://www.docbook.org/
561 int InsetGraphics::docbook(Buffer const *, ostream & os,
562                            bool /*mixcont*/) const
563 {
564         // In DocBook v5.0, the graphic tag will be eliminated from DocBook, will
565         // need to switch to MediaObject. However, for now this is sufficient and
566         // easier to use.
567         os << "<graphic fileref=\"&" << graphic_label << ";\">";
568         return 0;
569 }
570
571
572 void InsetGraphics::validate(LaTeXFeatures & features) const
573 {
574         // If we have no image, we should not require anything.
575         if (params().filename.empty())
576                 return;
577
578         features.includeFile(graphic_label, RemoveExtension(params().filename));
579
580         features.require("graphicx");
581
582         if (params().subcaption)
583                 features.require("subfigure");
584 }
585
586
587 bool InsetGraphics::setParams(InsetGraphicsParams const & p)
588 {
589         // If nothing is changed, just return and say so.
590         if (params() == p && !p.filename.empty())
591                 return false;
592
593         // Copy the new parameters.
594         params_ = p;
595
596         // Update the display using the new parameters.
597         graphic_->update(params().as_grfxParams());
598
599         // We have changed data, report it.
600         return true;
601 }
602
603
604 InsetGraphicsParams const & InsetGraphics::params() const
605 {
606         return params_;
607 }
608
609
610 BufferView * InsetGraphics::view() const
611 {
612         return graphic_->view();
613 }
614
615
616 string const InsetGraphicsMailer::name_("graphics");
617
618 InsetGraphicsMailer::InsetGraphicsMailer(InsetGraphics & inset)
619         : inset_(inset)
620 {}
621
622
623 string const InsetGraphicsMailer::inset2string() const
624 {
625         BufferView * bv = inset_.view();
626         if (bv)
627                 return params2string(inset_.params(), bv->buffer()->filePath());
628         return string();
629 }
630
631
632 void InsetGraphicsMailer::string2params(string const & in,
633                                         string const & buffer_path,
634                                         InsetGraphicsParams & params)
635 {
636         params = InsetGraphicsParams();
637
638         if (in.empty())
639                 return;
640
641         istringstream data(STRCONV(in));
642         LyXLex lex(0,0);
643         lex.setStream(data);
644
645         if (lex.isOK()) {
646                 lex.next();
647                 string const token = lex.getString();
648                 if (token != name_)
649                         return;
650         }
651
652         if (lex.isOK()) {
653                 InsetGraphics inset;
654                 inset.readInsetGraphics(lex, buffer_path);
655                 params = inset.params();
656         }
657 }
658
659
660 string const
661 InsetGraphicsMailer::params2string(InsetGraphicsParams const & params,
662                                    string const & buffer_path)
663 {
664         ostringstream data;
665         data << name_ << ' ';
666         params.Write(data, buffer_path);
667         data << "\\end_inset\n";
668         return STRCONV(data.str());
669 }