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