]> git.lyx.org Git - lyx.git/blob - src/graphics/PreviewLoader.C
Fix InsetInclude properly. Data is now stored in an InsetCommandParams
[lyx.git] / src / graphics / PreviewLoader.C
1 /**
2  * \file PreviewLoader.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "PreviewLoader.h"
14 #include "PreviewImage.h"
15
16 #include "buffer.h"
17 #include "converter.h"
18 #include "debug.h"
19 #include "format.h"
20 #include "latexrunparams.h"
21 #include "LColor.h"
22 #include "lyxrc.h"
23
24 #include "frontends/lyx_gui.h" // hexname
25
26 #include "insets/inset.h"
27
28 #include "support/filetools.h"
29 #include "support/forkedcall.h"
30 #include "support/forkedcontr.h"
31 #include "support/lstrings.h"
32 #include "support/lyxlib.h"
33 #include "support/tostr.h"
34
35 #include <boost/bind.hpp>
36
37 #include "support/std_sstream.h"
38 #include <fstream>
39 #include <iomanip>
40
41 namespace support = lyx::support;
42
43 using std::endl;
44 using std::find;
45 using std::fill;
46 using std::find_if;
47 using std::make_pair;
48
49 using std::ifstream;
50 using std::list;
51 using std::map;
52 using std::ofstream;
53 using std::ostream;
54 using std::ostringstream;
55 using std::pair;
56 using std::vector;
57
58
59 namespace {
60
61 typedef pair<string, string> StrPair;
62
63 // A list of alll snippets to be converted to previews
64 typedef list<string> PendingSnippets;
65
66 // Each item in the vector is a pair<snippet, image file name>.
67 typedef vector<StrPair> BitmapFile;
68
69 string const unique_filename(string const bufferpath);
70
71 Converter const * setConverter();
72
73 void setAscentFractions(vector<double> & ascent_fractions,
74                         string const & metrics_file);
75
76 struct FindFirst {
77         FindFirst(string const & comp) : comp_(comp) {}
78         bool operator()(StrPair const & sp)
79         {
80                 return sp.first == comp_;
81         }
82 private:
83         string const comp_;
84 };
85
86
87 /// Store info on a currently executing, forked process.
88 struct InProgress {
89         ///
90         InProgress() : pid(0) {}
91         ///
92         InProgress(string const & filename_base,
93                    PendingSnippets const & pending,
94                    string const & to_format);
95         /// Remove any files left lying around and kill the forked process.
96         void stop() const;
97
98         ///
99         pid_t pid;
100         ///
101         string command;
102         ///
103         string metrics_file;
104         ///
105         BitmapFile snippets;
106 };
107
108 typedef map<pid_t, InProgress>  InProgressProcesses;
109
110 typedef InProgressProcesses::value_type InProgressProcess;
111
112 } // namespace anon
113
114
115 namespace lyx {
116 namespace graphics {
117
118 struct PreviewLoader::Impl : public boost::signals::trackable {
119         ///
120         Impl(PreviewLoader & p, Buffer const & b);
121         /// Stop any InProgress items still executing.
122         ~Impl();
123         ///
124         PreviewImage const * preview(string const & latex_snippet) const;
125         ///
126         PreviewLoader::Status status(string const & latex_snippet) const;
127         ///
128         void add(string const & latex_snippet);
129         ///
130         void remove(string const & latex_snippet);
131         ///
132         void startLoading();
133
134         /// Emit this signal when an image is ready for display.
135         boost::signal1<void, PreviewImage const &> imageReady;
136
137         Buffer const & buffer() const { return buffer_; }
138
139 private:
140         /// Called by the Forkedcall process that generated the bitmap files.
141         void finishedGenerating(pid_t, int);
142         ///
143         void dumpPreamble(ostream &) const;
144         ///
145         void dumpData(ostream &, BitmapFile const &) const;
146
147         /** cache_ allows easy retrieval of already-generated images
148          *  using the LaTeX snippet as the identifier.
149          */
150         typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
151         ///
152         typedef map<string, PreviewImagePtr> Cache;
153         ///
154         Cache cache_;
155
156         /** pending_ stores the LaTeX snippets in anticipation of them being
157          *  sent to the converter.
158          */
159         PendingSnippets pending_;
160
161         /** in_progress_ stores all forked processes so that we can proceed
162          *  thereafter.
163             The map uses the conversion commands as its identifiers.
164          */
165         InProgressProcesses in_progress_;
166
167         ///
168         PreviewLoader & parent_;
169         ///
170         Buffer const & buffer_;
171         ///
172         double font_scaling_factor_;
173
174         /// We don't own this
175         static Converter const * pconverter_;
176 };
177
178
179 Converter const * PreviewLoader::Impl::pconverter_;
180
181
182 // The public interface, defined in PreviewLoader.h
183 // ================================================
184 PreviewLoader::PreviewLoader(Buffer const & b)
185         : pimpl_(new Impl(*this, b))
186 {}
187
188
189 PreviewLoader::~PreviewLoader()
190 {}
191
192
193 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
194 {
195         return pimpl_->preview(latex_snippet);
196 }
197
198
199 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
200 {
201         return pimpl_->status(latex_snippet);
202 }
203
204
205 void PreviewLoader::add(string const & latex_snippet) const
206 {
207         pimpl_->add(latex_snippet);
208 }
209
210
211 void PreviewLoader::remove(string const & latex_snippet) const
212 {
213         pimpl_->remove(latex_snippet);
214 }
215
216
217 void PreviewLoader::startLoading() const
218 {
219         pimpl_->startLoading();
220 }
221
222
223 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
224 {
225         return pimpl_->imageReady.connect(slot);
226 }
227
228
229 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
230 {
231         pimpl_->imageReady(pimage);
232 }
233
234
235 Buffer const & PreviewLoader::buffer() const
236 {
237         return pimpl_->buffer();
238 }
239
240 } // namespace graphics
241 } // namespace lyx
242
243
244 // The details of the Impl
245 // =======================
246
247 namespace {
248
249 struct IncrementedFileName {
250         IncrementedFileName(string const & to_format,
251                             string const & filename_base)
252                 : to_format_(to_format), base_(filename_base), counter_(1)
253         {}
254
255         StrPair const operator()(string const & snippet)
256         {
257                 ostringstream os;
258                 os << base_ << counter_++ << '.' << to_format_;
259                 string const file = os.str();
260
261                 return make_pair(snippet, file);
262         }
263
264 private:
265         string const & to_format_;
266         string const & base_;
267         int counter_;
268 };
269
270
271 InProgress::InProgress(string const & filename_base,
272                        PendingSnippets const & pending,
273                        string const & to_format)
274         : pid(0),
275           metrics_file(filename_base + ".metrics"),
276           snippets(pending.size())
277 {
278         PendingSnippets::const_iterator pit  = pending.begin();
279         PendingSnippets::const_iterator pend = pending.end();
280         BitmapFile::iterator sit = snippets.begin();
281
282         std::transform(pit, pend, sit,
283                        IncrementedFileName(to_format, filename_base));
284 }
285
286
287 void InProgress::stop() const
288 {
289         if (pid)
290                 support::ForkedcallsController::get().kill(pid, 0);
291
292         if (!metrics_file.empty())
293                 support::unlink(metrics_file);
294
295         BitmapFile::const_iterator vit  = snippets.begin();
296         BitmapFile::const_iterator vend = snippets.end();
297         for (; vit != vend; ++vit) {
298                 if (!vit->second.empty())
299                         support::unlink(vit->second);
300         }
301 }
302
303 } // namespace anon
304
305
306 namespace lyx {
307 namespace graphics {
308
309 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
310         : parent_(p), buffer_(b), font_scaling_factor_(0.0)
311 {
312         font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
313                 lyxrc.preview_scale_factor;
314
315         lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
316                                 << font_scaling_factor_ << endl;
317
318         if (!pconverter_)
319                 pconverter_ = setConverter();
320 }
321
322
323 PreviewLoader::Impl::~Impl()
324 {
325         InProgressProcesses::iterator ipit  = in_progress_.begin();
326         InProgressProcesses::iterator ipend = in_progress_.end();
327
328         for (; ipit != ipend; ++ipit) {
329                 ipit->second.stop();
330         }
331 }
332
333
334 PreviewImage const *
335 PreviewLoader::Impl::preview(string const & latex_snippet) const
336 {
337         Cache::const_iterator it = cache_.find(latex_snippet);
338         return (it == cache_.end()) ? 0 : it->second.get();
339 }
340
341
342 namespace {
343
344 struct FindSnippet {
345         FindSnippet(string const & s) : snippet_(s) {}
346         bool operator()(InProgressProcess const & process)
347         {
348                 BitmapFile const & snippets = process.second.snippets;
349                 BitmapFile::const_iterator it  = snippets.begin();
350                 BitmapFile::const_iterator end = snippets.end();
351                 it = find_if(it, end, FindFirst(snippet_));
352                 return it != end;
353         }
354
355 private:
356         string const & snippet_;
357 };
358
359 } // namespace anon
360
361 PreviewLoader::Status
362 PreviewLoader::Impl::status(string const & latex_snippet) const
363 {
364         Cache::const_iterator cit = cache_.find(latex_snippet);
365         if (cit != cache_.end())
366                 return Ready;
367
368         PendingSnippets::const_iterator pit  = pending_.begin();
369         PendingSnippets::const_iterator pend = pending_.end();
370
371         pit = find(pit, pend, latex_snippet);
372         if (pit != pend)
373                 return InQueue;
374
375         InProgressProcesses::const_iterator ipit  = in_progress_.begin();
376         InProgressProcesses::const_iterator ipend = in_progress_.end();
377
378         ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
379         if (ipit != ipend)
380                 return Processing;
381
382         return NotFound;
383 }
384
385
386 void PreviewLoader::Impl::add(string const & latex_snippet)
387 {
388         if (!pconverter_ || status(latex_snippet) != NotFound)
389                 return;
390
391         string const snippet = support::trim(latex_snippet);
392         if (snippet.empty())
393                 return;
394
395         lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
396
397         pending_.push_back(snippet);
398 }
399
400
401 namespace {
402
403 struct EraseSnippet {
404         EraseSnippet(string const & s) : snippet_(s) {}
405         void operator()(InProgressProcess & process)
406         {
407                 BitmapFile & snippets = process.second.snippets;
408                 BitmapFile::iterator it  = snippets.begin();
409                 BitmapFile::iterator end = snippets.end();
410
411                 it = find_if(it, end, FindFirst(snippet_));
412                 if (it != end)
413                         snippets.erase(it, it+1);
414         }
415
416 private:
417         string const & snippet_;
418 };
419
420 } // namespace anon
421
422
423 void PreviewLoader::Impl::remove(string const & latex_snippet)
424 {
425         Cache::iterator cit = cache_.find(latex_snippet);
426         if (cit != cache_.end())
427                 cache_.erase(cit);
428
429         PendingSnippets::iterator pit  = pending_.begin();
430         PendingSnippets::iterator pend = pending_.end();
431
432         pending_.erase(std::remove(pit, pend, latex_snippet), pend);
433
434         InProgressProcesses::iterator ipit  = in_progress_.begin();
435         InProgressProcesses::iterator ipend = in_progress_.end();
436
437         std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
438
439         while (ipit != ipend) {
440                 InProgressProcesses::iterator curr = ipit++;
441                 if (curr->second.snippets.empty())
442                         in_progress_.erase(curr);
443         }
444 }
445
446
447 void PreviewLoader::Impl::startLoading()
448 {
449         if (pending_.empty() || !pconverter_)
450                 return;
451
452         lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
453
454         // As used by the LaTeX file and by the resulting image files
455         string directory = buffer_.temppath();
456         if (directory.empty())
457                 directory = buffer_.filePath();
458
459         string const filename_base(unique_filename(directory));
460
461         // Create an InProgress instance to place in the map of all
462         // such processes if it starts correctly.
463         InProgress inprogress(filename_base, pending_, pconverter_->to);
464
465         // clear pending_, so we're ready to start afresh.
466         pending_.clear();
467
468         // Output the LaTeX file.
469         string const latexfile = filename_base + ".tex";
470
471         ofstream of(latexfile.c_str());
472         of << "\\batchmode\n";
473         dumpPreamble(of);
474         of << "\n\\begin{document}\n";
475         dumpData(of, inprogress.snippets);
476         of << "\n\\end{document}\n";
477         of.close();
478
479         // The conversion command.
480         ostringstream cs;
481         cs << pconverter_->command << ' ' << latexfile << ' '
482            << int(font_scaling_factor_) << ' ' << pconverter_->to;
483
484         string const command = "sh " + support::LibScriptSearch(cs.str());
485
486         // Initiate the conversion from LaTeX to bitmap images files.
487         support::Forkedcall::SignalTypePtr
488                 convert_ptr(new support::Forkedcall::SignalType);
489         convert_ptr->connect(
490                 boost::bind(&Impl::finishedGenerating, this, _1, _2));
491
492         support::Forkedcall call;
493         int ret = call.startscript(command, convert_ptr);
494
495         if (ret != 0) {
496                 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
497                                         << "Unable to start process \n"
498                                         << command << endl;
499                 return;
500         }
501
502         // Store the generation process in a list of all such processes
503         inprogress.pid = call.pid();
504         inprogress.command = command;
505         in_progress_[inprogress.pid] = inprogress;
506 }
507
508
509 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
510 {
511         // Paranoia check!
512         InProgressProcesses::iterator git = in_progress_.find(pid);
513         if (git == in_progress_.end()) {
514                 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
515                         "data for PID " << pid << endl;
516                 return;
517         }
518
519         string const command = git->second.command;
520         string const status = retval > 0 ? "failed" : "succeeded";
521         lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
522                                 << retval << "): processing " << status
523                                 << " for " << command << endl;
524         if (retval > 0)
525                 return;
526
527         // Read the metrics file, if it exists
528         vector<double> ascent_fractions(git->second.snippets.size());
529         setAscentFractions(ascent_fractions, git->second.metrics_file);
530
531         // Add these newly generated bitmap files to the cache and
532         // start loading them into LyX.
533         BitmapFile::const_iterator it  = git->second.snippets.begin();
534         BitmapFile::const_iterator end = git->second.snippets.end();
535
536         std::list<PreviewImagePtr> newimages;
537
538         int metrics_counter = 0;
539         for (; it != end; ++it, ++metrics_counter) {
540                 string const & snip = it->first;
541                 string const & file = it->second;
542                 double af = ascent_fractions[metrics_counter];
543
544                 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
545                 cache_[snip] = ptr;
546
547                 newimages.push_back(ptr);
548         }
549
550         // Remove the item from the list of still-executing processes.
551         in_progress_.erase(git);
552
553         // Tell the outside world
554         std::list<PreviewImagePtr>::const_reverse_iterator
555                 nit  = newimages.rbegin();
556         std::list<PreviewImagePtr>::const_reverse_iterator
557                 nend = newimages.rend();
558         for (; nit != nend; ++nit) {
559                 imageReady(*nit->get());
560         }
561 }
562
563
564 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
565 {
566         // Why on earth is Buffer::makeLaTeXFile a non-const method?
567         Buffer & tmp = const_cast<Buffer &>(buffer_);
568         // Dump the preamble only.
569         LatexRunParams runparams;
570         runparams.flavor = LatexRunParams::LATEX;
571         runparams.nice = true;
572         runparams.moving_arg = true;
573         runparams.free_spacing = true;
574         tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
575
576         // FIXME! This is a HACK! The proper fix is to control the 'true'
577         // passed to WriteStream below:
578         // int InsetFormula::latex(Buffer const &, ostream & os,
579         //                         LatexRunParams const & runparams) const
580         // {
581         //      WriteStream wi(os, runparams.moving_arg, true);
582         //      par_->write(wi);
583         //      return wi.line();
584         // }
585         os << "\n"
586            << "\\def\\lyxlock{}\n"
587            << "\n";
588
589         // Loop over the insets in the buffer and dump all the math-macros.
590         Buffer::inset_iterator it  = buffer_.inset_const_iterator_begin();
591         Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
592
593         for (; it != end; ++it)
594                 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
595                         it->latex(buffer_, os, runparams);
596
597         // All equation lables appear as "(#)" + preview.sty's rendering of
598         // the label name
599         if (lyxrc.preview_hashed_labels)
600                 os << "\\renewcommand{\\theequation}{\\#}\n";
601
602         // Use the preview style file to ensure that each snippet appears on a
603         // fresh page.
604         os << "\n"
605            << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
606            << "\n";
607
608         // This piece of PostScript magic ensures that the foreground and
609         // background colors are the same as the LyX screen.
610         string fg = lyx_gui::hexname(LColor::preview);
611         if (fg.empty()) fg = "000000";
612
613         string bg = lyx_gui::hexname(LColor::background);
614         if (bg.empty()) bg = "ffffff";
615
616         os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
617            << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
618            << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
619            << "clippath fill setrgbcolor}bind def end}}}\n";
620 }
621
622
623 void PreviewLoader::Impl::dumpData(ostream & os,
624                                    BitmapFile const & vec) const
625 {
626         if (vec.empty())
627                 return;
628
629         BitmapFile::const_iterator it  = vec.begin();
630         BitmapFile::const_iterator end = vec.end();
631
632         for (; it != end; ++it) {
633                 os << "\\begin{preview}\n"
634                    << it->first
635                    << "\n\\end{preview}\n\n";
636         }
637 }
638
639 } // namespace graphics
640 } // namespace lyx
641
642 namespace {
643
644 string const unique_filename(string const bufferpath)
645 {
646         static int theCounter = 0;
647         string const filename = tostr(theCounter++) + "lyxpreview";
648         return support::AddName(bufferpath, filename);
649 }
650
651
652 Converter const * setConverter()
653 {
654         string const from = "lyxpreview";
655
656         Formats::FormatList::const_iterator it  = formats.begin();
657         Formats::FormatList::const_iterator end = formats.end();
658
659         for (; it != end; ++it) {
660                 string const to = it->name();
661                 if (from == to)
662                         continue;
663
664                 Converter const * ptr = converters.getConverter(from, to);
665                 if (ptr)
666                         return ptr;
667         }
668
669         static bool first = true;
670         if (first) {
671                 first = false;
672                 lyxerr << "PreviewLoader::startLoading()\n"
673                        << "No converter from \"lyxpreview\" format has been "
674                         "defined."
675                        << endl;
676         }
677
678         return 0;
679 }
680
681
682 void setAscentFractions(vector<double> & ascent_fractions,
683                         string const & metrics_file)
684 {
685         // If all else fails, then the images will have equal ascents and
686         // descents.
687         vector<double>::iterator it  = ascent_fractions.begin();
688         vector<double>::iterator end = ascent_fractions.end();
689         fill(it, end, 0.5);
690
691         ifstream in(metrics_file.c_str());
692         if (!in.good()) {
693                 lyxerr[Debug::GRAPHICS]
694                         << "setAscentFractions(" << metrics_file << ")\n"
695                         << "Unable to open file!" << endl;
696                 return;
697         }
698
699         bool error = false;
700
701         // Tightpage dimensions affect all subsequent dimensions
702         int tp_ascent;
703         int tp_descent;
704
705         int snippet_counter = 0;
706         while (!in.eof()) {
707                 // Expecting lines of the form
708                 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
709                 // Preview: Snippet id ascent descent width
710                 string preview;
711                 string type;
712                 in >> preview >> type;
713
714                 if (!in.good())
715                         // eof after all
716                         break;
717
718                 error = preview != "Preview:"
719                         || (type != "Tightpage" && type != "Snippet");
720                 if (error)
721                         break;
722
723                 if (type == "Tightpage") {
724                         int dummy;
725                         in >> dummy >> tp_descent >> dummy >> tp_ascent;
726
727                         error = !in.good();
728                         if (error)
729                                 break;
730
731                 } else {
732                         int dummy;
733                         int snippet_id;
734                         int ascent;
735                         int descent;
736                         in >> snippet_id >> ascent >> descent >> dummy;
737
738                         error = !in.good() || ++snippet_counter != snippet_id;
739                         if (error)
740                                 break;
741
742                         double const a = ascent + tp_ascent;
743                         double const d = descent - tp_descent;
744
745                         if (!support::float_equal(a + d, 0, 0.1))
746                                 *it = a / (a + d);
747
748                         if (++it == end)
749                                 break;
750                 }
751         }
752
753         if (error) {
754                 lyxerr[Debug::GRAPHICS]
755                         << "setAscentFractions(" << metrics_file << ")\n"
756                         << "Error reading file!\n" << endl;
757         }
758 }
759
760 } // namespace anon