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