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