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