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