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