]> git.lyx.org Git - lyx.git/blob - src/graphics/PreviewLoader.C
Be more specific that 'using 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 namespace support = lyx::support;
46
47
48 using std::endl;
49 using std::find;
50 using std::fill;
51 using std::find_if;
52 using std::getline;
53 using std::make_pair;
54 using std::setfill;
55 using std::setw;
56
57 using std::list;
58 using std::map;
59 using std::ifstream;
60 using std::ofstream;
61 using std::ostream;
62 using std::pair;
63 using std::vector;
64
65 namespace {
66
67 typedef pair<string, string> StrPair;
68
69 // A list of alll snippets to be converted to previews
70 typedef list<string> PendingSnippets;
71
72 // Each item in the vector is a pair<snippet, image file name>.
73 typedef vector<StrPair> BitmapFile;
74
75 string const unique_filename(string const bufferpath);
76
77 Converter const * setConverter();
78
79 void setAscentFractions(vector<double> & ascent_fractions,
80                         string const & metrics_file);
81
82 struct FindFirst {
83         FindFirst(string const & comp) : comp_(comp) {}
84         bool operator()(StrPair const & sp)
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 = STRCONV(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 struct FindSnippet {
351         FindSnippet(string const & s) : snippet_(s) {}
352         bool operator()(InProgressProcess const & process)
353         {
354                 BitmapFile const & snippets = process.second.snippets;
355                 BitmapFile::const_iterator it  = snippets.begin();
356                 BitmapFile::const_iterator end = snippets.end();
357                 it = find_if(it, end, FindFirst(snippet_));
358                 return it != 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         for (; ipit != ipend; ++ipit) {
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         lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
459
460         // As used by the LaTeX file and by the resulting image files
461         string directory = buffer_.tmppath;
462         if (directory.empty())
463                 directory = buffer_.filePath();
464
465         string const filename_base(unique_filename(directory));
466
467         // Create an InProgress instance to place in the map of all
468         // such processes if it starts correctly.
469         InProgress inprogress(filename_base, pending_, pconverter_->to);
470
471         // clear pending_, so we're ready to start afresh.
472         pending_.clear();
473
474         // Output the LaTeX file.
475         string const latexfile = filename_base + ".tex";
476
477         ofstream of(latexfile.c_str());
478         of << "\\batchmode\n";
479         dumpPreamble(of);
480         of << "\n\\begin{document}\n";
481         dumpData(of, inprogress.snippets);
482         of << "\n\\end{document}\n";
483         of.close();
484
485         // The conversion command.
486         ostringstream cs;
487         cs << pconverter_->command << ' ' << latexfile << ' '
488            << int(font_scaling_factor_) << ' ' << pconverter_->to;
489
490         string const command = "sh " + support::LibScriptSearch(STRCONV(cs.str()));
491
492         // Initiate the conversion from LaTeX to bitmap images files.
493         support::Forkedcall::SignalTypePtr
494                 convert_ptr(new support::Forkedcall::SignalType);
495         convert_ptr->connect(
496                 boost::bind(&Impl::finishedGenerating, this, _1, _2));
497
498         support::Forkedcall call;
499         int ret = call.startscript(command, convert_ptr);
500
501         if (ret != 0) {
502                 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
503                                         << "Unable to start process \n"
504                                         << command << endl;
505                 return;
506         }
507
508         // Store the generation process in a list of all such processes
509         inprogress.pid = call.pid();
510         inprogress.command = command;
511         in_progress_[inprogress.pid] = inprogress;
512 }
513
514
515 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
516 {
517         // Paranoia check!
518         InProgressProcesses::iterator git = in_progress_.find(pid);
519         if (git == in_progress_.end()) {
520                 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
521                         "data for PID " << pid << endl;
522                 return;
523         }
524
525         string const command = git->second.command;
526         string const status = retval > 0 ? "failed" : "succeeded";
527         lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
528                                 << retval << "): processing " << status
529                                 << " for " << command << endl;
530         if (retval > 0)
531                 return;
532
533         // Read the metrics file, if it exists
534         vector<double> ascent_fractions(git->second.snippets.size());
535         setAscentFractions(ascent_fractions, git->second.metrics_file);
536
537         // Add these newly generated bitmap files to the cache and
538         // start loading them into LyX.
539         BitmapFile::const_iterator it  = git->second.snippets.begin();
540         BitmapFile::const_iterator end = git->second.snippets.end();
541
542         std::list<PreviewImagePtr> newimages;
543
544         int metrics_counter = 0;
545         for (; it != end; ++it, ++metrics_counter) {
546                 string const & snip = it->first;
547                 string const & file = it->second;
548                 double af = ascent_fractions[metrics_counter];
549
550                 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
551                 cache_[snip] = ptr;
552
553                 newimages.push_back(ptr);
554         }
555
556         // Remove the item from the list of still-executing processes.
557         in_progress_.erase(git);
558
559         // Tell the outside world
560         std::list<PreviewImagePtr>::const_reverse_iterator
561                 nit  = newimages.rbegin();
562         std::list<PreviewImagePtr>::const_reverse_iterator
563                 nend = newimages.rend();
564         for (; nit != nend; ++nit) {
565                 imageReady(*nit->get());
566         }
567 }
568
569
570 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
571 {
572         // Why on earth is Buffer::makeLaTeXFile a non-const method?
573         Buffer & tmp = const_cast<Buffer &>(buffer_);
574         // Dump the preamble only.
575         LatexRunParams runparams;
576         runparams.flavor = LatexRunParams::LATEX;
577         runparams.nice = true;
578         runparams.moving_arg = true;
579         runparams.free_spacing = true;
580         tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
581
582         // FIXME! This is a HACK! The proper fix is to control the 'true'
583         // passed to WriteStream below:
584         // int InsetFormula::latex(Buffer const &, ostream & os,
585         //                         LatexRunParams const & runparams) const
586         // {
587         //      WriteStream wi(os, runparams.moving_arg, true);
588         //      par_->write(wi);
589         //      return wi.line();
590         // }
591         os << "\n"
592            << "\\def\\lyxlock{}\n"
593            << "\n";
594
595         // Loop over the insets in the buffer and dump all the math-macros.
596         Buffer::inset_iterator it  = buffer_.inset_const_iterator_begin();
597         Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
598
599         for (; it != end; ++it)
600                 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
601                         it->latex(buffer_, os, runparams);
602
603         // All equation lables appear as "(#)" + preview.sty's rendering of
604         // the label name
605         if (lyxrc.preview_hashed_labels)
606                 os << "\\renewcommand{\\theequation}{\\#}\n";
607
608         // Use the preview style file to ensure that each snippet appears on a
609         // fresh page.
610         os << "\n"
611            << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
612            << "\n";
613
614         // This piece of PostScript magic ensures that the foreground and
615         // background colors are the same as the LyX screen.
616         string fg = lyx_gui::hexname(LColor::preview);
617         if (fg.empty()) fg = "000000";
618
619         string bg = lyx_gui::hexname(LColor::background);
620         if (bg.empty()) bg = "ffffff";
621
622         os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
623            << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
624            << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
625            << "clippath fill setrgbcolor}bind def end}}}\n";
626 }
627
628
629 void PreviewLoader::Impl::dumpData(ostream & os,
630                                    BitmapFile const & vec) const
631 {
632         if (vec.empty())
633                 return;
634
635         BitmapFile::const_iterator it  = vec.begin();
636         BitmapFile::const_iterator end = vec.end();
637
638         for (; it != end; ++it) {
639                 os << "\\begin{preview}\n"
640                    << it->first
641                    << "\n\\end{preview}\n\n";
642         }
643 }
644
645 } // namespace graphics
646 } // namespace lyx
647
648 namespace {
649
650 string const unique_filename(string const bufferpath)
651 {
652         static int theCounter = 0;
653         string const filename = tostr(theCounter++) + "lyxpreview";
654         return support::AddName(bufferpath, filename);
655 }
656
657
658 Converter const * setConverter()
659 {
660         string const from = "lyxpreview";
661
662         Formats::FormatList::const_iterator it  = formats.begin();
663         Formats::FormatList::const_iterator end = formats.end();
664
665         for (; it != end; ++it) {
666                 string const to = it->name();
667                 if (from == to)
668                         continue;
669
670                 Converter const * ptr = converters.getConverter(from, to);
671                 if (ptr)
672                         return ptr;
673         }
674
675         static bool first = true;
676         if (first) {
677                 first = false;
678                 lyxerr << "PreviewLoader::startLoading()\n"
679                        << "No converter from \"lyxpreview\" format has been "
680                         "defined."
681                        << endl;
682         }
683
684         return 0;
685 }
686
687
688 void setAscentFractions(vector<double> & ascent_fractions,
689                         string const & metrics_file)
690 {
691         // If all else fails, then the images will have equal ascents and
692         // descents.
693         vector<double>::iterator it  = ascent_fractions.begin();
694         vector<double>::iterator end = ascent_fractions.end();
695         fill(it, end, 0.5);
696
697         ifstream in(metrics_file.c_str());
698         if (!in.good()) {
699                 lyxerr[Debug::GRAPHICS]
700                         << "setAscentFractions(" << metrics_file << ")\n"
701                         << "Unable to open file!" << endl;
702                 return;
703         }
704
705         bool error = false;
706
707         // Tightpage dimensions affect all subsequent dimensions
708         int tp_ascent;
709         int tp_descent;
710
711         int snippet_counter = 0;
712         while (!in.eof()) {
713                 // Expecting lines of the form
714                 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
715                 // Preview: Snippet id ascent descent width
716                 string preview;
717                 string type;
718                 in >> preview >> type;
719
720                 if (!in.good())
721                         // eof after all
722                         break;
723
724                 error = preview != "Preview:"
725                         || (type != "Tightpage" && type != "Snippet");
726                 if (error)
727                         break;
728
729                 if (type == "Tightpage") {
730                         int dummy;
731                         in >> dummy >> tp_descent >> dummy >> tp_ascent;
732
733                         error = !in.good();
734                         if (error)
735                                 break;
736
737                 } else {
738                         int dummy;
739                         int snippet_id;
740                         int ascent;
741                         int descent;
742                         in >> snippet_id >> ascent >> descent >> dummy;
743
744                         error = !in.good() || ++snippet_counter != snippet_id;
745                         if (error)
746                                 break;
747
748                         double const a = ascent + tp_ascent;
749                         double const d = descent - tp_descent;
750
751                         if (!support::float_equal(a + d, 0, 0.1))
752                                 *it = a / (a + d);
753
754                         if (++it == end)
755                                 break;
756                 }
757         }
758
759         if (error) {
760                 lyxerr[Debug::GRAPHICS]
761                         << "setAscentFractions(" << metrics_file << ")\n"
762                         << "Error reading file!\n" << endl;
763         }
764 }
765
766 } // namespace anon