]> git.lyx.org Git - lyx.git/blob - src/graphics/PreviewLoader.C
The std::string mammoth path.
[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 "format.h"
20 #include "latexrunparams.h"
21 #include "LColor.h"
22 #include "lyxrc.h"
23
24 #include "frontends/lyx_gui.h" // hexname
25
26 #include "insets/inset.h"
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 #include "support/tostr.h"
34
35 #include <boost/bind.hpp>
36
37 #include "support/std_sstream.h"
38 #include <fstream>
39 #include <iomanip>
40
41 namespace support = lyx::support;
42
43 using std::endl;
44 using std::find;
45 using std::fill;
46 using std::find_if;
47 using std::make_pair;
48
49 using std::ifstream;
50 using std::list;
51 using std::map;
52 using std::ofstream;
53 using std::ostream;
54 using std::ostringstream;
55 using std::pair;
56 using std::vector;
57 using std::string;
58
59
60 namespace {
61
62 typedef pair<string, string> StrPair;
63
64 // A list of alll snippets to be converted to previews
65 typedef list<string> PendingSnippets;
66
67 // Each item in the vector is a pair<snippet, image file name>.
68 typedef vector<StrPair> BitmapFile;
69
70 string const unique_filename(string const bufferpath);
71
72 Converter const * setConverter();
73
74 void setAscentFractions(vector<double> & ascent_fractions,
75                         string const & metrics_file);
76
77 struct FindFirst {
78         FindFirst(string const & comp) : comp_(comp) {}
79         bool operator()(StrPair const & sp)
80         {
81                 return sp.first == comp_;
82         }
83 private:
84         string const comp_;
85 };
86
87
88 /// Store info on a currently executing, forked process.
89 struct InProgress {
90         ///
91         InProgress() : pid(0) {}
92         ///
93         InProgress(string const & filename_base,
94                    PendingSnippets const & pending,
95                    string const & to_format);
96         /// Remove any files left lying around and kill the forked process.
97         void stop() const;
98
99         ///
100         pid_t pid;
101         ///
102         string command;
103         ///
104         string metrics_file;
105         ///
106         BitmapFile snippets;
107 };
108
109 typedef map<pid_t, InProgress>  InProgressProcesses;
110
111 typedef InProgressProcesses::value_type InProgressProcess;
112
113 } // namespace anon
114
115
116 namespace lyx {
117 namespace graphics {
118
119 struct PreviewLoader::Impl : public boost::signals::trackable {
120         ///
121         Impl(PreviewLoader & p, Buffer const & b);
122         /// Stop any InProgress items still executing.
123         ~Impl();
124         ///
125         PreviewImage const * preview(string const & latex_snippet) const;
126         ///
127         PreviewLoader::Status status(string const & latex_snippet) const;
128         ///
129         void add(string const & latex_snippet);
130         ///
131         void remove(string const & latex_snippet);
132         ///
133         void startLoading();
134
135         /// Emit this signal when an image is ready for display.
136         boost::signal1<void, PreviewImage const &> imageReady;
137
138         Buffer const & buffer() const { return buffer_; }
139
140 private:
141         /// Called by the Forkedcall process that generated the bitmap files.
142         void finishedGenerating(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
236 Buffer const & PreviewLoader::buffer() const
237 {
238         return pimpl_->buffer();
239 }
240
241 } // namespace graphics
242 } // namespace lyx
243
244
245 // The details of the Impl
246 // =======================
247
248 namespace {
249
250 struct IncrementedFileName {
251         IncrementedFileName(string const & to_format,
252                             string const & filename_base)
253                 : to_format_(to_format), base_(filename_base), counter_(1)
254         {}
255
256         StrPair const operator()(string const & snippet)
257         {
258                 ostringstream os;
259                 os << base_ << counter_++ << '.' << to_format_;
260                 string const file = os.str();
261
262                 return make_pair(snippet, file);
263         }
264
265 private:
266         string const & to_format_;
267         string const & base_;
268         int counter_;
269 };
270
271
272 InProgress::InProgress(string const & filename_base,
273                        PendingSnippets const & pending,
274                        string const & to_format)
275         : pid(0),
276           metrics_file(filename_base + ".metrics"),
277           snippets(pending.size())
278 {
279         PendingSnippets::const_iterator pit  = pending.begin();
280         PendingSnippets::const_iterator pend = pending.end();
281         BitmapFile::iterator sit = snippets.begin();
282
283         std::transform(pit, pend, sit,
284                        IncrementedFileName(to_format, filename_base));
285 }
286
287
288 void InProgress::stop() const
289 {
290         if (pid)
291                 support::ForkedcallsController::get().kill(pid, 0);
292
293         if (!metrics_file.empty())
294                 support::unlink(metrics_file);
295
296         BitmapFile::const_iterator vit  = snippets.begin();
297         BitmapFile::const_iterator vend = snippets.end();
298         for (; vit != vend; ++vit) {
299                 if (!vit->second.empty())
300                         support::unlink(vit->second);
301         }
302 }
303
304 } // namespace anon
305
306
307 namespace lyx {
308 namespace graphics {
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 = support::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         while (ipit != ipend) {
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 directory = buffer_.temppath();
457         if (directory.empty())
458                 directory = buffer_.filePath();
459
460         string const filename_base(unique_filename(directory));
461
462         // Create an InProgress instance to place in the map of all
463         // such processes if it starts correctly.
464         InProgress inprogress(filename_base, pending_, pconverter_->to);
465
466         // clear pending_, so we're ready to start afresh.
467         pending_.clear();
468
469         // Output the LaTeX file.
470         string const latexfile = filename_base + ".tex";
471
472         ofstream of(latexfile.c_str());
473         of << "\\batchmode\n";
474         dumpPreamble(of);
475         of << "\n\\begin{document}\n";
476         dumpData(of, inprogress.snippets);
477         of << "\n\\end{document}\n";
478         of.close();
479
480         // The conversion command.
481         ostringstream cs;
482         cs << pconverter_->command << ' ' << latexfile << ' '
483            << int(font_scaling_factor_) << ' ' << pconverter_->to;
484
485         string const command = "sh " + support::LibScriptSearch(cs.str());
486
487         // Initiate the conversion from LaTeX to bitmap images files.
488         support::Forkedcall::SignalTypePtr
489                 convert_ptr(new support::Forkedcall::SignalType);
490         convert_ptr->connect(
491                 boost::bind(&Impl::finishedGenerating, this, _1, _2));
492
493         support::Forkedcall call;
494         int ret = call.startscript(command, convert_ptr);
495
496         if (ret != 0) {
497                 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
498                                         << "Unable to start process \n"
499                                         << command << endl;
500                 return;
501         }
502
503         // Store the generation process in a list of all such processes
504         inprogress.pid = call.pid();
505         inprogress.command = command;
506         in_progress_[inprogress.pid] = inprogress;
507 }
508
509
510 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
511 {
512         // Paranoia check!
513         InProgressProcesses::iterator git = in_progress_.find(pid);
514         if (git == in_progress_.end()) {
515                 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
516                         "data for PID " << pid << endl;
517                 return;
518         }
519
520         string const command = git->second.command;
521         string const status = retval > 0 ? "failed" : "succeeded";
522         lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
523                                 << retval << "): processing " << status
524                                 << " for " << command << endl;
525         if (retval > 0)
526                 return;
527
528         // Read the metrics file, if it exists
529         vector<double> ascent_fractions(git->second.snippets.size());
530         setAscentFractions(ascent_fractions, git->second.metrics_file);
531
532         // Add these newly generated bitmap files to the cache and
533         // start loading them into LyX.
534         BitmapFile::const_iterator it  = git->second.snippets.begin();
535         BitmapFile::const_iterator end = git->second.snippets.end();
536
537         std::list<PreviewImagePtr> newimages;
538
539         int metrics_counter = 0;
540         for (; it != end; ++it, ++metrics_counter) {
541                 string const & snip = it->first;
542                 string const & file = it->second;
543                 double af = ascent_fractions[metrics_counter];
544
545                 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
546                 cache_[snip] = ptr;
547
548                 newimages.push_back(ptr);
549         }
550
551         // Remove the item from the list of still-executing processes.
552         in_progress_.erase(git);
553
554         // Tell the outside world
555         std::list<PreviewImagePtr>::const_reverse_iterator
556                 nit  = newimages.rbegin();
557         std::list<PreviewImagePtr>::const_reverse_iterator
558                 nend = newimages.rend();
559         for (; nit != nend; ++nit) {
560                 imageReady(*nit->get());
561         }
562 }
563
564
565 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
566 {
567         // Why on earth is Buffer::makeLaTeXFile a non-const method?
568         Buffer & tmp = const_cast<Buffer &>(buffer_);
569         // Dump the preamble only.
570         LatexRunParams runparams;
571         runparams.flavor = LatexRunParams::LATEX;
572         runparams.nice = true;
573         runparams.moving_arg = true;
574         runparams.free_spacing = true;
575         tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
576
577         // FIXME! This is a HACK! The proper fix is to control the 'true'
578         // passed to WriteStream below:
579         // int InsetFormula::latex(Buffer const &, ostream & os,
580         //                         LatexRunParams const & runparams) const
581         // {
582         //      WriteStream wi(os, runparams.moving_arg, true);
583         //      par_->write(wi);
584         //      return wi.line();
585         // }
586         os << "\n"
587            << "\\def\\lyxlock{}\n"
588            << "\n";
589
590         // Loop over the insets in the buffer and dump all the math-macros.
591         Buffer::inset_iterator it  = buffer_.inset_const_iterator_begin();
592         Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
593
594         for (; it != end; ++it)
595                 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
596                         it->latex(buffer_, os, runparams);
597
598         // All equation lables appear as "(#)" + preview.sty's rendering of
599         // the label name
600         if (lyxrc.preview_hashed_labels)
601                 os << "\\renewcommand{\\theequation}{\\#}\n";
602
603         // Use the preview style file to ensure that each snippet appears on a
604         // fresh page.
605         os << "\n"
606            << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
607            << "\n";
608
609         // This piece of PostScript magic ensures that the foreground and
610         // background colors are the same as the LyX screen.
611         string fg = lyx_gui::hexname(LColor::preview);
612         if (fg.empty()) fg = "000000";
613
614         string bg = lyx_gui::hexname(LColor::background);
615         if (bg.empty()) bg = "ffffff";
616
617         os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
618            << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
619            << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
620            << "clippath fill setrgbcolor}bind def end}}}\n";
621 }
622
623
624 void PreviewLoader::Impl::dumpData(ostream & os,
625                                    BitmapFile const & vec) const
626 {
627         if (vec.empty())
628                 return;
629
630         BitmapFile::const_iterator it  = vec.begin();
631         BitmapFile::const_iterator end = vec.end();
632
633         for (; it != end; ++it) {
634                 os << "\\begin{preview}\n"
635                    << it->first
636                    << "\n\\end{preview}\n\n";
637         }
638 }
639
640 } // namespace graphics
641 } // namespace lyx
642
643 namespace {
644
645 string const unique_filename(string const bufferpath)
646 {
647         static int theCounter = 0;
648         string const filename = tostr(theCounter++) + "lyxpreview";
649         return support::AddName(bufferpath, filename);
650 }
651
652
653 Converter const * setConverter()
654 {
655         string const from = "lyxpreview";
656
657         Formats::FormatList::const_iterator it  = formats.begin();
658         Formats::FormatList::const_iterator end = formats.end();
659
660         for (; it != end; ++it) {
661                 string const to = it->name();
662                 if (from == to)
663                         continue;
664
665                 Converter const * ptr = converters.getConverter(from, to);
666                 if (ptr)
667                         return ptr;
668         }
669
670         static bool first = true;
671         if (first) {
672                 first = false;
673                 lyxerr << "PreviewLoader::startLoading()\n"
674                        << "No converter from \"lyxpreview\" format has been "
675                         "defined."
676                        << endl;
677         }
678
679         return 0;
680 }
681
682
683 void setAscentFractions(vector<double> & ascent_fractions,
684                         string const & metrics_file)
685 {
686         // If all else fails, then the images will have equal ascents and
687         // descents.
688         vector<double>::iterator it  = ascent_fractions.begin();
689         vector<double>::iterator end = ascent_fractions.end();
690         fill(it, end, 0.5);
691
692         ifstream in(metrics_file.c_str());
693         if (!in.good()) {
694                 lyxerr[Debug::GRAPHICS]
695                         << "setAscentFractions(" << metrics_file << ")\n"
696                         << "Unable to open file!" << endl;
697                 return;
698         }
699
700         bool error = false;
701
702         // Tightpage dimensions affect all subsequent dimensions
703         int tp_ascent;
704         int tp_descent;
705
706         int snippet_counter = 0;
707         while (!in.eof()) {
708                 // Expecting lines of the form
709                 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
710                 // Preview: Snippet id ascent descent width
711                 string preview;
712                 string type;
713                 in >> preview >> type;
714
715                 if (!in.good())
716                         // eof after all
717                         break;
718
719                 error = preview != "Preview:"
720                         || (type != "Tightpage" && type != "Snippet");
721                 if (error)
722                         break;
723
724                 if (type == "Tightpage") {
725                         int dummy;
726                         in >> dummy >> tp_descent >> dummy >> tp_ascent;
727
728                         error = !in.good();
729                         if (error)
730                                 break;
731
732                 } else {
733                         int dummy;
734                         int snippet_id;
735                         int ascent;
736                         int descent;
737                         in >> snippet_id >> ascent >> descent >> dummy;
738
739                         error = !in.good() || ++snippet_counter != snippet_id;
740                         if (error)
741                                 break;
742
743                         double const a = ascent + tp_ascent;
744                         double const d = descent - tp_descent;
745
746                         if (!support::float_equal(a + d, 0, 0.1))
747                                 *it = a / (a + d);
748
749                         if (++it == end)
750                                 break;
751                 }
752         }
753
754         if (error) {
755                 lyxerr[Debug::GRAPHICS]
756                         << "setAscentFractions(" << metrics_file << ")\n"
757                         << "Error reading file!\n" << endl;
758         }
759 }
760
761 } // namespace anon