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