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