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