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