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