]> git.lyx.org Git - lyx.git/blob - src/graphics/PreviewLoader.cpp
58fb336294a355a03b9e664450ff30efa486ff8a
[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         double font_scaling_factor_;
248
249         /// We don't own this
250         static lyx::Converter const * pconverter_;
251 };
252
253
254 lyx::Converter const * PreviewLoader::Impl::pconverter_;
255
256
257 //
258 // The public interface, defined in PreviewLoader.h
259 //
260
261 PreviewLoader::PreviewLoader(Buffer const & b)
262         : pimpl_(new Impl(*this, b))
263 {}
264
265
266 PreviewLoader::~PreviewLoader()
267 {
268         delete pimpl_;
269 }
270
271
272 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
273 {
274         return pimpl_->preview(latex_snippet);
275 }
276
277
278 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
279 {
280         return pimpl_->status(latex_snippet);
281 }
282
283
284 void PreviewLoader::add(string const & latex_snippet) const
285 {
286         pimpl_->add(latex_snippet);
287 }
288
289
290 void PreviewLoader::remove(string const & latex_snippet) const
291 {
292         pimpl_->remove(latex_snippet);
293 }
294
295
296 void PreviewLoader::startLoading() const
297 {
298         pimpl_->startLoading();
299 }
300
301
302 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
303 {
304         return pimpl_->imageReady.connect(slot);
305 }
306
307
308 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
309 {
310         pimpl_->imageReady(pimage);
311 }
312
313
314 Buffer const & PreviewLoader::buffer() const
315 {
316         return pimpl_->buffer();
317 }
318
319 } // namespace graphics
320 } // namespace lyx
321
322
323 // The details of the Impl
324 // =======================
325
326 namespace {
327
328 class IncrementedFileName {
329 public:
330         IncrementedFileName(string const & to_format,
331                             string const & filename_base)
332                 : to_format_(to_format), base_(filename_base), counter_(1)
333         {}
334
335         SnippetPair const operator()(string const & snippet)
336         {
337                 ostringstream os;
338                 os << base_ << counter_++ << '.' << to_format_;
339                 string const file = os.str();
340
341                 return make_pair(snippet, FileName(file));
342         }
343
344 private:
345         string const & to_format_;
346         string const & base_;
347         int counter_;
348 };
349
350
351 InProgress::InProgress(string const & filename_base,
352                        PendingSnippets const & pending,
353                        string const & to_format)
354         : pid(0),
355           metrics_file(filename_base + ".metrics"),
356           snippets(pending.size())
357 {
358         PendingSnippets::const_iterator pit  = pending.begin();
359         PendingSnippets::const_iterator pend = pending.end();
360         BitmapFile::iterator sit = snippets.begin();
361
362         transform(pit, pend, sit,
363                        IncrementedFileName(to_format, filename_base));
364 }
365
366
367 void InProgress::stop() const
368 {
369         if (pid)
370                 ForkedCallsController::kill(pid, 0);
371
372         if (!metrics_file.empty())
373                 metrics_file.removeFile();
374
375         BitmapFile::const_iterator vit  = snippets.begin();
376         BitmapFile::const_iterator vend = snippets.end();
377         for (; vit != vend; ++vit) {
378                 if (!vit->second.empty())
379                         vit->second.removeFile();
380         }
381 }
382
383 } // namespace anon
384
385
386 namespace lyx {
387 namespace graphics {
388
389 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
390         : parent_(p), buffer_(b), font_scaling_factor_(0.0)
391 {
392         font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
393                 lyxrc.preview_scale_factor;
394
395         LYXERR(Debug::GRAPHICS, "The font scaling factor is "
396                                 << font_scaling_factor_);
397
398         if (!pconverter_){
399                 if (b.params().encoding().package() == Encoding::japanese)
400                         pconverter_ = setConverter("lyxpreview-platex");
401                 else
402                         pconverter_ = setConverter("lyxpreview");
403         }
404 }
405
406
407 PreviewLoader::Impl::~Impl()
408 {
409         InProgressProcesses::iterator ipit  = in_progress_.begin();
410         InProgressProcesses::iterator ipend = in_progress_.end();
411
412         for (; ipit != ipend; ++ipit)
413                 ipit->second.stop();
414 }
415
416
417 PreviewImage const *
418 PreviewLoader::Impl::preview(string const & latex_snippet) const
419 {
420         Cache::const_iterator it = cache_.find(latex_snippet);
421         return (it == cache_.end()) ? 0 : it->second.get();
422 }
423
424
425 namespace {
426
427 class FindSnippet {
428 public:
429         FindSnippet(string const & s) : snippet_(s) {}
430         bool operator()(InProgressProcess const & process) const
431         {
432                 BitmapFile const & snippets = process.second.snippets;
433                 BitmapFile::const_iterator beg  = snippets.begin();
434                 BitmapFile::const_iterator end = snippets.end();
435                 return find_if(beg, end, FindFirst(snippet_)) != end;
436         }
437
438 private:
439         string const snippet_;
440 };
441
442 } // namespace anon
443
444 PreviewLoader::Status
445 PreviewLoader::Impl::status(string const & latex_snippet) const
446 {
447         Cache::const_iterator cit = cache_.find(latex_snippet);
448         if (cit != cache_.end())
449                 return Ready;
450
451         PendingSnippets::const_iterator pit  = pending_.begin();
452         PendingSnippets::const_iterator pend = pending_.end();
453
454         pit = find(pit, pend, latex_snippet);
455         if (pit != pend)
456                 return InQueue;
457
458         InProgressProcesses::const_iterator ipit  = in_progress_.begin();
459         InProgressProcesses::const_iterator ipend = in_progress_.end();
460
461         ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
462         if (ipit != ipend)
463                 return Processing;
464
465         return NotFound;
466 }
467
468
469 void PreviewLoader::Impl::add(string const & latex_snippet)
470 {
471         if (!pconverter_ || status(latex_snippet) != NotFound)
472                 return;
473
474         string const snippet = trim(latex_snippet);
475         if (snippet.empty())
476                 return;
477
478         LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
479
480         pending_.push_back(snippet);
481 }
482
483
484 namespace {
485
486 class EraseSnippet {
487 public:
488         EraseSnippet(string const & s) : snippet_(s) {}
489         void operator()(InProgressProcess & process)
490         {
491                 BitmapFile & snippets = process.second.snippets;
492                 BitmapFile::iterator it  = snippets.begin();
493                 BitmapFile::iterator end = snippets.end();
494
495                 it = find_if(it, end, FindFirst(snippet_));
496                 if (it != end)
497                         snippets.erase(it, it+1);
498         }
499
500 private:
501         string const & snippet_;
502 };
503
504 } // namespace anon
505
506
507 void PreviewLoader::Impl::remove(string const & latex_snippet)
508 {
509         Cache::iterator cit = cache_.find(latex_snippet);
510         if (cit != cache_.end())
511                 cache_.erase(cit);
512
513         PendingSnippets::iterator pit  = pending_.begin();
514         PendingSnippets::iterator pend = pending_.end();
515
516         pending_.erase(std::remove(pit, pend, latex_snippet), pend);
517
518         InProgressProcesses::iterator ipit  = in_progress_.begin();
519         InProgressProcesses::iterator ipend = in_progress_.end();
520
521         for_each(ipit, ipend, EraseSnippet(latex_snippet));
522
523         while (ipit != ipend) {
524                 InProgressProcesses::iterator curr = ipit++;
525                 if (curr->second.snippets.empty())
526                         in_progress_.erase(curr);
527         }
528 }
529
530
531 void PreviewLoader::Impl::startLoading()
532 {
533         if (pending_.empty() || !pconverter_)
534                 return;
535
536         // Only start the process off after the buffer is loaded from file.
537         if (!buffer_.isFullyLoaded())
538                 return;
539
540         LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
541
542         // As used by the LaTeX file and by the resulting image files
543         string const directory = buffer_.temppath();
544
545         string const filename_base = unique_filename(directory);
546
547         // Create an InProgress instance to place in the map of all
548         // such processes if it starts correctly.
549         InProgress inprogress(filename_base, pending_, pconverter_->to);
550
551         // clear pending_, so we're ready to start afresh.
552         pending_.clear();
553
554         // Output the LaTeX file.
555         FileName const latexfile(filename_base + ".tex");
556
557         // we use the encoding of the buffer
558         Encoding const & enc = buffer_.params().encoding();
559         ofdocstream of;
560         try { of.reset(enc.iconvName()); }
561         catch (iconv_codecvt_facet_exception & e) {
562                 LYXERR0("Caught iconv exception: " << e.what()
563                         << "\nUnable to create LaTeX file: " << latexfile);
564                 return;
565         }
566
567         TexRow texrow;
568         OutputParams runparams(&enc);
569         LaTeXFeatures features(buffer_, buffer_.params(), runparams);
570
571         if (!openFileWrite(of, latexfile))
572                 return;
573
574         if (!of) {
575                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
576                                         << "Unable to create LaTeX file\n" << latexfile);
577                 return;
578         }
579         of << "\\batchmode\n";
580         dumpPreamble(of);
581         // handle inputenc etc.
582         buffer_.params().writeEncodingPreamble(of, features, texrow);
583         of << "\n\\begin{document}\n";
584         dumpData(of, inprogress.snippets);
585         of << "\n\\end{document}\n";
586         of.close();
587         if (of.fail()) {
588                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
589                                          << "File was not closed properly.");
590                 return;
591         }
592
593         // The conversion command.
594         ostringstream cs;
595         cs << pconverter_->command << ' ' << pconverter_->to << ' '
596            << quoteName(latexfile.toFilesystemEncoding()) << ' '
597            << int(font_scaling_factor_) << ' '
598            << theApp()->hexName(PreviewLoader::foregroundColor()) << ' '
599            << theApp()->hexName(PreviewLoader::backgroundColor());
600
601         string const command = libScriptSearch(cs.str());
602
603         // Initiate the conversion from LaTeX to bitmap images files.
604         ForkedCall::SignalTypePtr
605                 convert_ptr(new ForkedCall::SignalType);
606         convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
607
608         ForkedCall call;
609         int ret = call.startScript(command, convert_ptr);
610
611         if (ret != 0) {
612                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
613                                         << "Unable to start process\n" << command);
614                 return;
615         }
616
617         // Store the generation process in a list of all such processes
618         inprogress.pid = call.pid();
619         inprogress.command = command;
620         in_progress_[inprogress.pid] = inprogress;
621 }
622
623
624 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
625 {
626         // Paranoia check!
627         InProgressProcesses::iterator git = in_progress_.find(pid);
628         if (git == in_progress_.end()) {
629                 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
630                         "data for PID " << pid << endl;
631                 return;
632         }
633
634         string const command = git->second.command;
635         string const status = retval > 0 ? "failed" : "succeeded";
636         LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
637                                 << retval << "): processing " << status
638                                 << " for " << command);
639         if (retval > 0)
640                 return;
641
642         // Read the metrics file, if it exists
643         vector<double> ascent_fractions(git->second.snippets.size());
644         setAscentFractions(ascent_fractions, git->second.metrics_file);
645
646         // Add these newly generated bitmap files to the cache and
647         // start loading them into LyX.
648         BitmapFile::const_iterator it  = git->second.snippets.begin();
649         BitmapFile::const_iterator end = git->second.snippets.end();
650
651         list<PreviewImagePtr> newimages;
652
653         int metrics_counter = 0;
654         for (; it != end; ++it, ++metrics_counter) {
655                 string const & snip = it->first;
656                 FileName const & file = it->second;
657                 double af = ascent_fractions[metrics_counter];
658
659                 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
660                 cache_[snip] = ptr;
661
662                 newimages.push_back(ptr);
663         }
664
665         // Remove the item from the list of still-executing processes.
666         in_progress_.erase(git);
667
668         // Tell the outside world
669         list<PreviewImagePtr>::const_reverse_iterator
670                 nit  = newimages.rbegin();
671         list<PreviewImagePtr>::const_reverse_iterator
672                 nend = newimages.rend();
673         for (; nit != nend; ++nit) {
674                 imageReady(*nit->get());
675         }
676 }
677
678
679 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
680 {
681         // Dump the preamble only.
682         // We don't need an encoding for runparams since it is not used by
683         // the preamble.
684         OutputParams runparams(0);
685         runparams.flavor = OutputParams::LATEX;
686         runparams.nice = true;
687         runparams.moving_arg = true;
688         runparams.free_spacing = true;
689         buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
690
691         // FIXME! This is a HACK! The proper fix is to control the 'true'
692         // passed to WriteStream below:
693         // int InsetMathNest::latex(Buffer const &, odocstream & os,
694         //                          OutputParams const & runparams) const
695         // {
696         //      WriteStream wi(os, runparams.moving_arg, true);
697         //      par_->write(wi);
698         //      return wi.line();
699         // }
700         os << "\n"
701            << "\\def\\lyxlock{}\n"
702            << "\n";
703
704         // All equation labels appear as "(#)" + preview.sty's rendering of
705         // the label name
706         if (lyxrc.preview_hashed_labels)
707                 os << "\\renewcommand{\\theequation}{\\#}\n";
708
709         // Use the preview style file to ensure that each snippet appears on a
710         // fresh page.
711         // Also support PDF output (automatically generated e.g. when
712         // \usepackage[pdftex]{hyperref} is used.
713         os << "\n"
714            << "\\newif\\ifpdf\n"
715            << "\\ifx\\pdfoutput\\undefined\n"
716            << "\\else\\ifx\\pdfoutput\\relax\n"
717            << "\\else\\ifnum0=\\pdfoutput\n"
718            << "\\else\\pdftrue\\fi\\fi\\fi\n"
719            << "\\ifpdf\n"
720            << "  \\usepackage[active,delayed,tightpage,showlabels,lyx,pdftex]{preview}\n"
721            << "\\else\n"
722            << "  \\usepackage[active,delayed,showlabels,lyx,dvips]{preview}\n"
723            << "\\fi\n"
724            << "\n";
725 }
726
727
728 void PreviewLoader::Impl::dumpData(odocstream & os,
729                                    BitmapFile const & vec) const
730 {
731         if (vec.empty())
732                 return;
733
734         BitmapFile::const_iterator it  = vec.begin();
735         BitmapFile::const_iterator end = vec.end();
736
737         for (; it != end; ++it) {
738                 // FIXME UNICODE
739                 os << "\\begin{preview}\n"
740                    << from_utf8(it->first)
741                    << "\n\\end{preview}\n\n";
742         }
743 }
744
745 } // namespace graphics
746 } // namespace lyx