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