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