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