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