]> git.lyx.org Git - lyx.git/blob - src/graphics/PreviewLoader.C
Prevent a crash if the user is not using a tmp directory.
[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 #include "PreviewLoader.h"
14 #include "PreviewImage.h"
15
16 #include "buffer.h"
17 #include "converter.h"
18 #include "debug.h"
19 #include "lyxrc.h"
20 #include "LColor.h"
21
22 #include "insets/inset.h"
23
24 #include "frontends/lyx_gui.h" // hexname
25
26 #include "support/filetools.h"
27 #include "support/forkedcall.h"
28 #include "support/forkedcontr.h"
29 #include "support/lstrings.h"
30 #include "support/lyxlib.h"
31
32 #include <boost/bind.hpp>
33 #include <boost/signals/trackable.hpp>
34
35 #include <fstream>
36 #include <iomanip>
37 #include <list>
38 #include <map>
39 #include <utility>
40 #include <vector>
41
42 using std::endl;
43 using std::find;
44 using std::fill;
45 using std::find_if;
46 using std::getline;
47 using std::make_pair;
48 using std::setfill;
49 using std::setw;
50
51 using std::list;
52 using std::map;
53 using std::ifstream;
54 using std::ofstream;
55 using std::ostream;
56 using std::pair;
57 using std::vector;
58
59 namespace {
60
61 typedef pair<string, string> StrPair;
62
63 // A list of alll snippets to be converted to previews
64 typedef list<string> PendingSnippets;
65
66 // Each item in the vector is a pair<snippet, image file name>.
67 typedef vector<StrPair> BitmapFile;
68
69 string const unique_filename(string const bufferpath);
70
71 Converter const * setConverter();
72
73 void setAscentFractions(vector<double> & ascent_fractions,
74                         string const & metrics_file);
75
76 struct FindFirst {
77         FindFirst(string const & comp) : comp_(comp) {}
78         bool operator()(StrPair const & sp)
79         {
80                 return sp.first == comp_;
81         }
82 private:
83         string const comp_;
84 };
85
86
87 /// Store info on a currently executing, forked process.
88 struct InProgress {
89         ///
90         InProgress() : pid(0) {}
91         ///
92         InProgress(string const & filename_base,
93                    PendingSnippets const & pending,
94                    string const & to_format);
95         /// Remove any files left lying around and kill the forked process.
96         void stop() const;
97
98         ///
99         pid_t pid;
100         ///
101         string command;
102         ///
103         string metrics_file;
104         ///
105         BitmapFile snippets;
106 };
107
108 typedef map<pid_t, InProgress>  InProgressProcesses;
109
110 typedef InProgressProcesses::value_type InProgressProcess;
111
112 } // namespace anon
113
114
115 namespace grfx {
116
117 struct PreviewLoader::Impl : public boost::signals::trackable {
118         ///
119         Impl(PreviewLoader & p, Buffer const & b);
120         /// Stop any InProgress items still executing.
121         ~Impl();
122         ///
123         PreviewImage const * preview(string const & latex_snippet) const;
124         ///
125         PreviewLoader::Status status(string const & latex_snippet) const;
126         ///
127         void add(string const & latex_snippet);
128         ///
129         void remove(string const & latex_snippet);
130         ///
131         void startLoading();
132
133         /// Emit this signal when an image is ready for display.
134         boost::signal1<void, PreviewImage const &> imageReady;
135
136         Buffer const & buffer() const { return buffer_; }
137
138 private:
139         /// Called by the Forkedcall process that generated the bitmap files.
140         void finishedGenerating(pid_t, int);
141         ///
142         void dumpPreamble(ostream &) const;
143         ///
144         void dumpData(ostream &, BitmapFile const &) const;
145
146         /** cache_ allows easy retrieval of already-generated images
147          *  using the LaTeX snippet as the identifier.
148          */
149         typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
150         ///
151         typedef map<string, PreviewImagePtr> Cache;
152         ///
153         Cache cache_;
154
155         /** pending_ stores the LaTeX snippets in anticipation of them being
156          *  sent to the converter.
157          */
158         PendingSnippets pending_;
159
160         /** in_progress_ stores all forked processes so that we can proceed
161          *  thereafter.
162             The map uses the conversion commands as its identifiers.
163          */
164         InProgressProcesses in_progress_;
165
166         ///
167         PreviewLoader & parent_;
168         ///
169         Buffer const & buffer_;
170         ///
171         double font_scaling_factor_;
172
173         /// We don't own this
174         static Converter const * pconverter_;
175 };
176
177
178 Converter const * PreviewLoader::Impl::pconverter_;
179
180
181 // The public interface, defined in PreviewLoader.h
182 // ================================================
183 PreviewLoader::PreviewLoader(Buffer const & b)
184         : pimpl_(new Impl(*this, b))
185 {}
186
187
188 PreviewLoader::~PreviewLoader()
189 {}
190
191
192 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
193 {
194         return pimpl_->preview(latex_snippet);
195 }
196
197
198 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
199 {
200         return pimpl_->status(latex_snippet);
201 }
202
203
204 void PreviewLoader::add(string const & latex_snippet) const
205 {
206         pimpl_->add(latex_snippet);
207 }
208
209
210 void PreviewLoader::remove(string const & latex_snippet) const
211 {
212         pimpl_->remove(latex_snippet);
213 }
214
215
216 void PreviewLoader::startLoading() const
217 {
218         pimpl_->startLoading();
219 }
220
221
222 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
223 {
224         return pimpl_->imageReady.connect(slot);
225 }
226
227
228 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
229 {
230         pimpl_->imageReady(pimage);
231 }
232
233
234 Buffer const & PreviewLoader::buffer() const
235 {
236         return pimpl_->buffer();
237 }
238
239 } // namespace grfx
240
241
242 // The details of the Impl
243 // =======================
244
245 namespace {
246
247 struct IncrementedFileName {
248         IncrementedFileName(string const & to_format,
249                             string const & filename_base)
250                 : to_format_(to_format), base_(filename_base), counter_(1)
251         {}
252
253         StrPair const operator()(string const & snippet)
254         {
255                 ostringstream os;
256                 os << base_ << counter_++ << '.' << to_format_;
257                 string const file = STRCONV(os.str());
258
259                 return make_pair(snippet, file);
260         }
261
262 private:
263         string const & to_format_;
264         string const & base_;
265         int counter_;
266 };
267
268
269 InProgress::InProgress(string const & filename_base,
270                        PendingSnippets const & pending,
271                        string const & to_format)
272         : pid(0),
273           metrics_file(filename_base + ".metrics"),
274           snippets(pending.size())
275 {
276         PendingSnippets::const_iterator pit  = pending.begin();
277         PendingSnippets::const_iterator pend = pending.end();
278         BitmapFile::iterator sit = snippets.begin();
279
280         std::transform(pit, pend, sit,
281                        IncrementedFileName(to_format, filename_base));
282 }
283
284
285 void InProgress::stop() const
286 {
287         if (pid)
288                 ForkedcallsController::get().kill(pid, 0);
289
290         if (!metrics_file.empty())
291                 lyx::unlink(metrics_file);
292
293         BitmapFile::const_iterator vit  = snippets.begin();
294         BitmapFile::const_iterator vend = snippets.end();
295         for (; vit != vend; ++vit) {
296                 if (!vit->second.empty())
297                         lyx::unlink(vit->second);
298         }
299 }
300
301 } // namespace anon
302
303
304 namespace grfx {
305
306 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
307         : parent_(p), buffer_(b), font_scaling_factor_(0.0)
308 {
309         font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
310                 lyxrc.preview_scale_factor;
311
312         lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
313                                 << font_scaling_factor_ << endl;
314
315         if (!pconverter_)
316                 pconverter_ = setConverter();
317 }
318
319
320 PreviewLoader::Impl::~Impl()
321 {
322         InProgressProcesses::iterator ipit  = in_progress_.begin();
323         InProgressProcesses::iterator ipend = in_progress_.end();
324
325         for (; ipit != ipend; ++ipit) {
326                 ipit->second.stop();
327         }
328 }
329
330
331 PreviewImage const *
332 PreviewLoader::Impl::preview(string const & latex_snippet) const
333 {
334         Cache::const_iterator it = cache_.find(latex_snippet);
335         return (it == cache_.end()) ? 0 : it->second.get();
336 }
337
338
339 namespace {
340
341 struct FindSnippet {
342         FindSnippet(string const & s) : snippet_(s) {}
343         bool operator()(InProgressProcess const & process)
344         {
345                 BitmapFile const & snippets = process.second.snippets;
346                 BitmapFile::const_iterator it  = snippets.begin();
347                 BitmapFile::const_iterator end = snippets.end();
348                 it = find_if(it, end, FindFirst(snippet_));
349                 return it != end;
350         }
351
352 private:
353         string const & snippet_;
354 };
355
356 } // namespace anon
357
358 PreviewLoader::Status
359 PreviewLoader::Impl::status(string const & latex_snippet) const
360 {
361         Cache::const_iterator cit = cache_.find(latex_snippet);
362         if (cit != cache_.end())
363                 return Ready;
364
365         PendingSnippets::const_iterator pit  = pending_.begin();
366         PendingSnippets::const_iterator pend = pending_.end();
367
368         pit = find(pit, pend, latex_snippet);
369         if (pit != pend)
370                 return InQueue;
371
372         InProgressProcesses::const_iterator ipit  = in_progress_.begin();
373         InProgressProcesses::const_iterator ipend = in_progress_.end();
374
375         ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
376         if (ipit != ipend)
377                 return Processing;
378
379         return NotFound;
380 }
381
382
383 void PreviewLoader::Impl::add(string const & latex_snippet)
384 {
385         if (!pconverter_ || status(latex_snippet) != NotFound)
386                 return;
387
388         string const snippet = trim(latex_snippet);
389         if (snippet.empty())
390                 return;
391
392         lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
393
394         pending_.push_back(snippet);
395 }
396
397
398 namespace {
399
400 struct EraseSnippet {
401         EraseSnippet(string const & s) : snippet_(s) {}
402         void operator()(InProgressProcess & process)
403         {
404                 BitmapFile & snippets = process.second.snippets;
405                 BitmapFile::iterator it  = snippets.begin();
406                 BitmapFile::iterator end = snippets.end();
407
408                 it = find_if(it, end, FindFirst(snippet_));
409                 if (it != end)
410                         snippets.erase(it, it+1);
411         }
412
413 private:
414         string const & snippet_;
415 };
416
417 } // namespace anon
418
419
420 void PreviewLoader::Impl::remove(string const & latex_snippet)
421 {
422         Cache::iterator cit = cache_.find(latex_snippet);
423         if (cit != cache_.end())
424                 cache_.erase(cit);
425
426         PendingSnippets::iterator pit  = pending_.begin();
427         PendingSnippets::iterator pend = pending_.end();
428
429         pending_.erase(std::remove(pit, pend, latex_snippet), pend);
430
431         InProgressProcesses::iterator ipit  = in_progress_.begin();
432         InProgressProcesses::iterator ipend = in_progress_.end();
433
434         std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
435
436         for (; ipit != ipend; ++ipit) {
437                 InProgressProcesses::iterator curr = ipit++;
438                 if (curr->second.snippets.empty())
439                         in_progress_.erase(curr);
440         }
441 }
442
443
444 void PreviewLoader::Impl::startLoading()
445 {
446         if (pending_.empty() || !pconverter_)
447                 return;
448
449         lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
450
451         // As used by the LaTeX file and by the resulting image files
452         string directory = buffer_.tmppath;
453         if (directory.empty())
454                 directory = buffer_.filePath();
455         
456         string const filename_base(unique_filename(directory));
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_reverse_iterator
551                 nit  = newimages.rbegin();
552         std::list<PreviewImagePtr>::const_reverse_iterator
553                 nend = newimages.rend();
554         for (; nit != nend; ++nit) {
555                 imageReady(*nit->get());
556         }
557 }
558
559
560 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
561 {
562         // Why on earth is Buffer::makeLaTeXFile a non-const method?
563         Buffer & tmp = const_cast<Buffer &>(buffer_);
564         // Dump the preamble only.
565         tmp.makeLaTeXFile(os, buffer_.filePath(), true, false, true);
566
567         // FIXME! This is a HACK! The proper fix is to control the 'true'
568         // passed to WriteStream below:
569         // int InsetFormula::latex(Buffer const *, ostream & os,
570         //                         bool fragile, bool) const
571         // {
572         //      WriteStream wi(os, fragile, true);
573         //      par_->write(wi);
574         //      return wi.line();
575         // }
576         os << "\n"
577            << "\\def\\lyxlock{}\n"
578            << "\n";
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