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