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