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