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