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