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