]> git.lyx.org Git - lyx.git/blob - src/graphics/PreviewLoader.C
a72cf57085e88c664f7ffbf57d2f8b586d914855
[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 private:
141         /// Called by the Forkedcall process that generated the bitmap files.
142         void finishedGenerating(string const &, 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 } // namespace grfx
236
237
238 // The details of the Impl
239 // =======================
240
241 namespace {
242
243 struct IncrementedFileName {
244         IncrementedFileName(string const & to_format,
245                             string const & filename_base)
246                 : to_format_(to_format), base_(filename_base), counter_(1)
247         {}
248
249         StrPair const operator()(string const & snippet)
250         {
251                 ostringstream os;
252                 os << base_
253                    << setfill('0') << setw(3) << counter_++
254                    << "." << to_format_;
255
256                 string const file = os.str().c_str();
257
258                 return make_pair(snippet, file);
259         }
260
261 private:
262         string const & to_format_;
263         string const & base_;
264         int counter_;
265 };
266
267
268 InProgress::InProgress(string const & filename_base,
269                        PendingSnippets const & pending,
270                        string const & to_format)
271         : pid(0),
272           metrics_file(filename_base + ".metrics"),
273           snippets(pending.size())
274 {
275         PendingSnippets::const_iterator pit  = pending.begin();
276         PendingSnippets::const_iterator pend = pending.end();
277         BitmapFile::iterator sit = snippets.begin();
278
279         std::transform(pit, pend, sit,
280                        IncrementedFileName(to_format, filename_base));
281 }
282
283
284 void InProgress::stop() const
285 {
286         if (pid)
287                 ForkedcallsController::get().kill(pid, 0);
288
289         if (!metrics_file.empty())
290                 lyx::unlink(metrics_file);
291
292         BitmapFile::const_iterator vit  = snippets.begin();
293         BitmapFile::const_iterator vend = snippets.end();
294         for (; vit != vend; ++vit) {
295                 if (!vit->second.empty())
296                         lyx::unlink(vit->second);
297         }
298 }
299
300 } // namespace anon
301
302
303 namespace grfx {
304
305 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
306         : parent_(p), buffer_(b), font_scaling_factor_(0.0)
307 {
308         font_scaling_factor_ = setFontScalingFactor(const_cast<Buffer &>(b));
309
310         lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
311                                 << font_scaling_factor_ << endl;
312
313         if (!pconverter_)
314                 pconverter_ = setConverter();
315 }
316
317
318 PreviewLoader::Impl::~Impl()
319 {
320         InProgressProcesses::iterator ipit  = in_progress_.begin();
321         InProgressProcesses::iterator ipend = in_progress_.end();
322
323         for (; ipit != ipend; ++ipit) {
324                 ipit->second.stop();
325         }
326 }
327
328
329 PreviewImage const *
330 PreviewLoader::Impl::preview(string const & latex_snippet) const
331 {
332         Cache::const_iterator it = cache_.find(latex_snippet);
333         return (it == cache_.end()) ? 0 : it->second.get();
334 }
335
336
337 namespace {
338
339 struct FindSnippet {
340         FindSnippet(string const & s) : snippet_(s) {}
341         bool operator()(InProgressProcess const & process)
342         {
343                 BitmapFile const & snippets = process.second.snippets;
344                 BitmapFile::const_iterator it  = snippets.begin();
345                 BitmapFile::const_iterator end = snippets.end();
346                 it = find_if(it, end, FindFirst(snippet_));
347                 return it != end;
348         }
349
350 private:
351         string const & snippet_;
352 };
353
354 } // namespace anon
355
356 PreviewLoader::Status
357 PreviewLoader::Impl::status(string const & latex_snippet) const
358 {
359         Cache::const_iterator cit = cache_.find(latex_snippet);
360         if (cit != cache_.end())
361                 return Ready;
362
363         PendingSnippets::const_iterator pit  = pending_.begin();
364         PendingSnippets::const_iterator pend = pending_.end();
365
366         pit = find(pit, pend, latex_snippet);
367         if (pit != pend)
368                 return InQueue;
369
370         InProgressProcesses::const_iterator ipit  = in_progress_.begin();
371         InProgressProcesses::const_iterator ipend = in_progress_.end();
372
373         ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
374         if (ipit != ipend)
375                 return Processing;
376
377         return NotFound;
378 }
379
380
381 void PreviewLoader::Impl::add(string const & latex_snippet)
382 {
383         if (!pconverter_ || status(latex_snippet) != NotFound)
384                 return;
385
386         lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << latex_snippet << endl;
387
388         pending_.push_back(latex_snippet);
389 }
390
391
392 namespace {
393
394 struct EraseSnippet {
395         EraseSnippet(string const & s) : snippet_(s) {}
396         void operator()(InProgressProcess & process)
397         {
398                 BitmapFile & snippets = process.second.snippets;
399                 BitmapFile::iterator it  = snippets.begin();
400                 BitmapFile::iterator end = snippets.end();
401
402                 it = find_if(it, end, FindFirst(snippet_));
403                 if (it != end)
404                         snippets.erase(it, it+1);
405         }
406
407 private:
408         string const & snippet_;
409 };
410
411 } // namespace anon
412
413
414 void PreviewLoader::Impl::remove(string const & latex_snippet)
415 {
416         Cache::iterator cit = cache_.find(latex_snippet);
417         if (cit != cache_.end())
418                 cache_.erase(cit);
419
420         PendingSnippets::iterator pit  = pending_.begin();
421         PendingSnippets::iterator pend = pending_.end();
422
423         pending_.erase(std::remove(pit, pend, latex_snippet), pend);
424
425         InProgressProcesses::iterator ipit  = in_progress_.begin();
426         InProgressProcesses::iterator ipend = in_progress_.end();
427
428         std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
429
430         for (; ipit != ipend; ++ipit) {
431                 InProgressProcesses::iterator curr = ipit++;
432                 if (curr->second.snippets.empty())
433                         in_progress_.erase(curr);
434         }
435 }
436
437
438 void PreviewLoader::Impl::startLoading()
439 {
440         if (pending_.empty() || !pconverter_)
441                 return;
442
443         lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
444
445         // As used by the LaTeX file and by the resulting image files
446         string const filename_base(unique_filename(buffer_.tmppath));
447
448         // Create an InProgress instance to place in the map of all
449         // such processes if it starts correctly.
450         InProgress inprogress(filename_base, pending_, pconverter_->to);
451
452         // clear pending_, so we're ready to start afresh.
453         pending_.clear();
454
455         // Output the LaTeX file.
456         string const latexfile = filename_base + ".tex";
457
458         ofstream of(latexfile.c_str());
459         of << "\\batchmode\n";
460         dumpPreamble(of);
461         of << "\n\\begin{document}\n";
462         dumpData(of, inprogress.snippets);
463         of << "\n\\end{document}\n";
464         of.close();
465
466         // The conversion command.
467         ostringstream cs;
468         cs << pconverter_->command << " " << latexfile << " "
469            << int(font_scaling_factor_);
470
471         string const command = LibScriptSearch(cs.str().c_str());
472
473         // Initiate the conversion from LaTeX to bitmap images files.
474         Forkedcall::SignalTypePtr convert_ptr;
475         convert_ptr.reset(new Forkedcall::SignalType);
476
477         convert_ptr->connect(
478                 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
479
480         Forkedcall call;
481         int ret = call.startscript(command, convert_ptr);
482
483         if (ret != 0) {
484                 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
485                                         << "Unable to start process \n"
486                                         << command << endl;
487                 return;
488         }
489
490         // Store the generation process in a list of all such processes
491         inprogress.pid = call.pid();
492         in_progress_[command] = inprogress;
493 }
494
495
496 void PreviewLoader::Impl::finishedGenerating(string const & command,
497                                              pid_t /* pid */, int retval)
498 {
499         string const status = retval > 0 ? "failed" : "succeeded";
500         lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
501                                 << retval << "): processing " << status
502                                 << " for " << command << endl;
503         if (retval > 0)
504                 return;
505
506         // Paranoia check!
507         InProgressProcesses::iterator git = in_progress_.find(command);
508         if (git == in_progress_.end()) {
509                 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
510                         "data for\n"
511                        << command << "!" << endl;
512                 return;
513         }
514
515         // Read the metrics file, if it exists
516         vector<double> ascent_fractions(git->second.snippets.size());
517         setAscentFractions(ascent_fractions, git->second.metrics_file);
518
519         // Add these newly generated bitmap files to the cache and
520         // start loading them into LyX.
521         BitmapFile::const_iterator it  = git->second.snippets.begin();
522         BitmapFile::const_iterator end = git->second.snippets.end();
523
524         std::list<PreviewImagePtr> newimages;
525
526         int metrics_counter = 0;
527         for (; it != end; ++it, ++metrics_counter) {
528                 string const & snip = it->first;
529                 string const & file = it->second;
530                 double af = ascent_fractions[metrics_counter];
531
532                 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
533                 cache_[snip] = ptr;
534
535                 newimages.push_back(ptr);
536         }
537
538         // Remove the item from the list of still-executing processes.
539         in_progress_.erase(git);
540
541         // Tell the outside world
542         std::list<PreviewImagePtr>::const_iterator nit  = newimages.begin();
543         std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
544         for (; nit != nend; ++nit) {
545                 imageReady(*nit->get());
546         }
547 }
548
549
550 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
551 {
552         // Why on earth is Buffer::makeLaTeXFile a non-const method?
553         Buffer & tmp = const_cast<Buffer &>(buffer_);
554         // Dump the preamble only.
555         tmp.makeLaTeXFile(os, string(), true, false, true);
556
557         // Loop over the insets in the buffer and dump all the math-macros.
558         Buffer::inset_iterator it  = buffer_.inset_const_iterator_begin();
559         Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
560
561         for (; it != end; ++it) {
562                 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
563                         (*it)->latex(&buffer_, os, true, true);
564                 }
565         }
566
567         // All equation lables appear as "(#)" + preview.sty's rendering of
568         // the label name
569         if (lyxrc.preview_hashed_labels)
570                 os << "\\renewcommand{\\theequation}{\\#}\n";
571
572         // Use the preview style file to ensure that each snippet appears on a
573         // fresh page.
574         os << "\n"
575            << "\\usepackage[active,delayed,dvips,tightpage,showlabels]{preview}\n"
576            << "\n";
577
578         // This piece of PostScript magic ensures that the foreground and
579         // background colors are the same as the LyX screen.
580         string fg = lyx_gui::hexname(LColor::preview);
581         if (fg.empty()) fg = "000000";
582
583         string bg = lyx_gui::hexname(LColor::background);
584         if (bg.empty()) bg = "ffffff";
585
586         os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
587            << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
588            << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
589            << "clippath fill setrgbcolor}bind def end}}}\n";
590 }
591
592
593 void PreviewLoader::Impl::dumpData(ostream & os,
594                                    BitmapFile const & vec) const
595 {
596         if (vec.empty())
597                 return;
598
599         BitmapFile::const_iterator it  = vec.begin();
600         BitmapFile::const_iterator end = vec.end();
601
602         for (; it != end; ++it) {
603                 os << "\\begin{preview}\n"
604                    << it->first
605                    << "\n\\end{preview}\n\n";
606         }
607 }
608
609 } // namespace grfx
610
611
612 namespace {
613
614 string const unique_filename(string const bufferpath)
615 {
616         static int theCounter = 0;
617         string const filename = tostr(theCounter++) + "lyxpreview";
618         return AddName(bufferpath, filename);
619 }
620
621
622 Converter const * setConverter()
623 {
624         string const from = "lyxpreview";
625
626         Formats::FormatList::const_iterator it  = formats.begin();
627         Formats::FormatList::const_iterator end = formats.end();
628
629         for (; it != end; ++it) {
630                 string const to = it->name();
631                 if (from == to)
632                         continue;
633
634                 Converter const * ptr = converters.getConverter(from, to);
635                 if (ptr)
636                         return ptr;
637         }
638
639         static bool first = true;
640         if (first) {
641                 first = false;
642                 lyxerr << "PreviewLoader::startLoading()\n"
643                        << "No converter from \"lyxpreview\" format has been "
644                         "defined."
645                        << endl;
646         }
647
648         return 0;
649 }
650
651
652 double setFontScalingFactor(Buffer & buffer)
653 {
654         double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
655                 lyxrc.preview_scale_factor;
656
657         // Has the font size been set explicitly?
658         string const & fontsize = buffer.params.fontsize;
659         lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
660                                 << "font size is " << fontsize << endl;
661
662         if (isStrUnsignedInt(fontsize))
663                 return 10.0 * scale_factor / strToDbl(fontsize);
664
665         // No. We must extract it from the LaTeX class file.
666         LyXTextClass const & tclass = buffer.params.getLyXTextClass();
667         string const textclass(tclass.latexname() + ".cls");
668         string const classfile(findtexfile(textclass, "cls"));
669
670         lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
671                                 << "class file is " << classfile << endl;
672
673         ifstream ifs(classfile.c_str());
674         if (!ifs.good()) {
675                 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
676                 return scale_factor;
677         }
678
679         string str;
680         double scaling = scale_factor;
681
682         while (ifs.good()) {
683                 getline(ifs, str);
684                 // To get the default font size, look for a line like
685                 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
686                 if (!prefixIs(ltrim(str), "\\ExecuteOptions"))
687                         continue;
688
689                 // str contains just the options of \ExecuteOptions
690                 string const tmp = split(str, '{');
691                 split(tmp, str, '}');
692
693                 int count = 0;
694                 string tok = token(str, ',', count++);
695                 while (!isValidLength(tok) && !tok.empty())
696                         tok = token(str, ',', count++);
697
698                 if (!tok.empty()) {
699                         lyxerr[Debug::GRAPHICS]
700                                 << "Extracted default font size from "
701                                 "LaTeX class file successfully!" << endl;
702                         LyXLength fsize(tok);
703                         scaling *= 10.0 / fsize.value();
704                         break;
705                 }
706         }
707
708         return scaling;
709 }
710
711
712 void setAscentFractions(vector<double> & ascent_fractions,
713                         string const & metrics_file)
714 {
715         // If all else fails, then the images will have equal ascents and
716         // descents.
717         vector<double>::iterator it  = ascent_fractions.begin();
718         vector<double>::iterator end = ascent_fractions.end();
719         fill(it, end, 0.5);
720
721         ifstream ifs(metrics_file.c_str());
722         if (!ifs.good()) {
723                 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
724                                         << metrics_file << ")\n"
725                                         << "Unable to open file!"
726                                         << endl;
727                 return;
728         }
729
730         for (; it != end; ++it) {
731                 string page;
732                 string page_id;
733                 int dummy;
734                 double ascent;
735                 double descent;
736
737                 ifs >> page >> page_id >> dummy >> dummy >> dummy >> dummy
738                     >> ascent >> descent >> dummy;
739
740                 if (!ifs.good() ||
741                     page != "%%Page" ||
742                     !isStrUnsignedInt(rtrim(page_id, ":"))) {
743                         lyxerr[Debug::GRAPHICS] << "setAscentFractions("
744                                                 << metrics_file << ")\n"
745                                                 << "Error reading file!"
746                                                 << endl;
747                         break;
748                 }
749
750                 if (ascent + descent != 0)
751                         *it = ascent / (ascent + descent);
752         }
753 }
754
755 } // namespace anon