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