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