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