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