2 * \file PreviewLoader.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
8 * Full author contact details are available in file CREDITS.
13 #include "PreviewLoader.h"
14 #include "PreviewImage.h"
15 #include "GraphicsCache.h"
18 #include "converter.h"
21 #include "insetiterator.h"
24 #include "outputparams.h"
25 #include "paragraph.h"
27 #include "frontends/Application.h" // hexName
29 #include "insets/Inset.h"
31 #include "support/filetools.h"
32 #include "support/forkedcall.h"
33 #include "support/forkedcontr.h"
34 #include "support/lstrings.h"
35 #include "support/lyxlib.h"
36 #include "support/convert.h"
38 #include <boost/bind.hpp>
44 using lyx::support::FileName;
57 using std::ostringstream;
65 typedef pair<string, FileName> SnippetPair;
67 // A list of all snippets to be converted to previews
68 typedef list<string> PendingSnippets;
70 // Each item in the vector is a pair<snippet, image file name>.
71 typedef vector<SnippetPair> BitmapFile;
74 string const unique_filename(string const & bufferpath)
76 static int theCounter = 0;
77 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
78 return lyx::support::addName(bufferpath, filename);
82 lyx::Converter const * setConverter()
84 string const from = "lyxpreview";
86 typedef vector<string> FmtList;
87 typedef lyx::graphics::Cache GCache;
88 FmtList const loadableFormats = GCache::get().loadableFormats();
89 FmtList::const_iterator it = loadableFormats.begin();
90 FmtList::const_iterator const end = loadableFormats.end();
92 for (; it != end; ++it) {
93 string const to = *it;
97 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
102 static bool first = true;
105 lyx::lyxerr << "PreviewLoader::startLoading()\n"
106 << "No converter from \"lyxpreview\" format has been "
114 void setAscentFractions(vector<double> & ascent_fractions,
115 FileName const & metrics_file)
117 // If all else fails, then the images will have equal ascents and
119 vector<double>::iterator it = ascent_fractions.begin();
120 vector<double>::iterator end = ascent_fractions.end();
123 ifstream in(metrics_file.toFilesystemEncoding().c_str());
125 lyx::lyxerr[lyx::Debug::GRAPHICS]
126 << "setAscentFractions(" << metrics_file << ")\n"
127 << "Unable to open file!" << endl;
133 int snippet_counter = 1;
134 while (!in.eof() && it != end) {
137 double ascent_fraction;
139 in >> snippet >> id >> ascent_fraction;
145 error = snippet != "Snippet";
149 error = id != snippet_counter;
153 *it = ascent_fraction;
160 lyx::lyxerr[lyx::Debug::GRAPHICS]
161 << "setAscentFractions(" << metrics_file << ")\n"
162 << "Error reading file!\n" << endl;
167 class FindFirst : public std::unary_function<SnippetPair, bool> {
169 FindFirst(string const & comp) : comp_(comp) {}
170 bool operator()(SnippetPair const & sp) const
172 return sp.first == comp_;
179 /// Store info on a currently executing, forked process.
183 InProgress() : pid(0) {}
185 InProgress(string const & filename_base,
186 PendingSnippets const & pending,
187 string const & to_format);
188 /// Remove any files left lying around and kill the forked process.
196 FileName metrics_file;
201 typedef map<pid_t, InProgress> InProgressProcesses;
203 typedef InProgressProcesses::value_type InProgressProcess;
213 class PreviewLoader::Impl : public boost::signals::trackable {
216 Impl(PreviewLoader & p, Buffer const & b);
217 /// Stop any InProgress items still executing.
220 PreviewImage const * preview(string const & latex_snippet) const;
222 PreviewLoader::Status status(string const & latex_snippet) const;
224 void add(string const & latex_snippet);
226 void remove(string const & latex_snippet);
230 /// Emit this signal when an image is ready for display.
231 boost::signal<void(PreviewImage const &)> imageReady;
233 Buffer const & buffer() const { return buffer_; }
236 /// Called by the Forkedcall process that generated the bitmap files.
237 void finishedGenerating(pid_t, int);
239 void dumpPreamble(odocstream &) const;
241 void dumpData(odocstream &, BitmapFile const &) const;
243 /** cache_ allows easy retrieval of already-generated images
244 * using the LaTeX snippet as the identifier.
246 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
248 typedef map<string, PreviewImagePtr> Cache;
252 /** pending_ stores the LaTeX snippets in anticipation of them being
253 * sent to the converter.
255 PendingSnippets pending_;
257 /** in_progress_ stores all forked processes so that we can proceed
259 The map uses the conversion commands as its identifiers.
261 InProgressProcesses in_progress_;
264 PreviewLoader & parent_;
266 Buffer const & buffer_;
268 double font_scaling_factor_;
270 /// We don't own this
271 static lyx::Converter const * pconverter_;
275 lyx::Converter const * PreviewLoader::Impl::pconverter_;
279 // The public interface, defined in PreviewLoader.h
282 PreviewLoader::PreviewLoader(Buffer const & b)
283 : pimpl_(new Impl(*this, b))
287 PreviewLoader::~PreviewLoader()
291 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
293 return pimpl_->preview(latex_snippet);
297 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
299 return pimpl_->status(latex_snippet);
303 void PreviewLoader::add(string const & latex_snippet) const
305 pimpl_->add(latex_snippet);
309 void PreviewLoader::remove(string const & latex_snippet) const
311 pimpl_->remove(latex_snippet);
315 void PreviewLoader::startLoading() const
317 pimpl_->startLoading();
321 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
323 return pimpl_->imageReady.connect(slot);
327 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
329 pimpl_->imageReady(pimage);
333 Buffer const & PreviewLoader::buffer() const
335 return pimpl_->buffer();
338 } // namespace graphics
342 // The details of the Impl
343 // =======================
347 class IncrementedFileName {
349 IncrementedFileName(string const & to_format,
350 string const & filename_base)
351 : to_format_(to_format), base_(filename_base), counter_(1)
354 SnippetPair const operator()(string const & snippet)
357 os << base_ << counter_++ << '.' << to_format_;
358 string const file = os.str();
360 return make_pair(snippet, FileName(file));
364 string const & to_format_;
365 string const & base_;
370 InProgress::InProgress(string const & filename_base,
371 PendingSnippets const & pending,
372 string const & to_format)
374 metrics_file(FileName(filename_base + ".metrics")),
375 snippets(pending.size())
377 PendingSnippets::const_iterator pit = pending.begin();
378 PendingSnippets::const_iterator pend = pending.end();
379 BitmapFile::iterator sit = snippets.begin();
381 std::transform(pit, pend, sit,
382 IncrementedFileName(to_format, filename_base));
386 void InProgress::stop() const
389 lyx::support::ForkedcallsController::get().kill(pid, 0);
391 if (!metrics_file.empty())
392 lyx::support::unlink(metrics_file);
394 BitmapFile::const_iterator vit = snippets.begin();
395 BitmapFile::const_iterator vend = snippets.end();
396 for (; vit != vend; ++vit) {
397 if (!vit->second.empty())
398 lyx::support::unlink(vit->second);
408 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
409 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
411 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
412 convert<double>(lyxrc.preview_scale_factor);
414 LYXERR(Debug::GRAPHICS) << "The font scaling factor is "
415 << font_scaling_factor_ << endl;
418 pconverter_ = setConverter();
422 PreviewLoader::Impl::~Impl()
424 InProgressProcesses::iterator ipit = in_progress_.begin();
425 InProgressProcesses::iterator ipend = in_progress_.end();
427 for (; ipit != ipend; ++ipit) {
434 PreviewLoader::Impl::preview(string const & latex_snippet) const
436 Cache::const_iterator it = cache_.find(latex_snippet);
437 return (it == cache_.end()) ? 0 : it->second.get();
443 class FindSnippet : public std::unary_function<InProgressProcess, bool> {
445 FindSnippet(string const & s) : snippet_(s) {}
446 bool operator()(InProgressProcess const & process) const
448 BitmapFile const & snippets = process.second.snippets;
449 BitmapFile::const_iterator beg = snippets.begin();
450 BitmapFile::const_iterator end = snippets.end();
451 return find_if(beg, end, FindFirst(snippet_)) != end;
455 string const snippet_;
460 PreviewLoader::Status
461 PreviewLoader::Impl::status(string const & latex_snippet) const
463 Cache::const_iterator cit = cache_.find(latex_snippet);
464 if (cit != cache_.end())
467 PendingSnippets::const_iterator pit = pending_.begin();
468 PendingSnippets::const_iterator pend = pending_.end();
470 pit = find(pit, pend, latex_snippet);
474 InProgressProcesses::const_iterator ipit = in_progress_.begin();
475 InProgressProcesses::const_iterator ipend = in_progress_.end();
477 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
485 void PreviewLoader::Impl::add(string const & latex_snippet)
487 if (!pconverter_ || status(latex_snippet) != NotFound)
490 string const snippet = support::trim(latex_snippet);
494 LYXERR(Debug::GRAPHICS) << "adding snippet:\n" << snippet << endl;
496 pending_.push_back(snippet);
504 EraseSnippet(string const & s) : snippet_(s) {}
505 void operator()(InProgressProcess & process)
507 BitmapFile & snippets = process.second.snippets;
508 BitmapFile::iterator it = snippets.begin();
509 BitmapFile::iterator end = snippets.end();
511 it = find_if(it, end, FindFirst(snippet_));
513 snippets.erase(it, it+1);
517 string const & snippet_;
523 void PreviewLoader::Impl::remove(string const & latex_snippet)
525 Cache::iterator cit = cache_.find(latex_snippet);
526 if (cit != cache_.end())
529 PendingSnippets::iterator pit = pending_.begin();
530 PendingSnippets::iterator pend = pending_.end();
532 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
534 InProgressProcesses::iterator ipit = in_progress_.begin();
535 InProgressProcesses::iterator ipend = in_progress_.end();
537 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
539 while (ipit != ipend) {
540 InProgressProcesses::iterator curr = ipit++;
541 if (curr->second.snippets.empty())
542 in_progress_.erase(curr);
547 void PreviewLoader::Impl::startLoading()
549 if (pending_.empty() || !pconverter_)
552 // Only start the process off after the buffer is loaded from file.
553 if (!buffer_.fully_loaded())
556 LYXERR(Debug::GRAPHICS) << "PreviewLoader::startLoading()" << endl;
558 // As used by the LaTeX file and by the resulting image files
559 string const directory = buffer_.temppath();
561 string const filename_base = unique_filename(directory);
563 // Create an InProgress instance to place in the map of all
564 // such processes if it starts correctly.
565 InProgress inprogress(filename_base, pending_, pconverter_->to);
567 // clear pending_, so we're ready to start afresh.
570 // Output the LaTeX file.
571 FileName const latexfile(filename_base + ".tex");
574 // This creates an utf8 encoded file, but the proper inputenc
575 // command is missing.
576 odocfstream of(latexfile.toFilesystemEncoding().c_str());
578 LYXERR(Debug::GRAPHICS) << "PreviewLoader::startLoading()\n"
579 << "Unable to create LaTeX file\n"
580 << latexfile << endl;
583 of << "\\batchmode\n";
585 of << "\n\\begin{document}\n";
586 dumpData(of, inprogress.snippets);
587 of << "\n\\end{document}\n";
590 // The conversion command.
592 cs << pconverter_->command << ' ' << pconverter_->to << ' '
593 << support::quoteName(latexfile.toFilesystemEncoding()) << ' '
594 << int(font_scaling_factor_) << ' '
595 << theApp()->hexName(LColor::preview) << ' '
596 << theApp()->hexName(LColor::background);
598 string const command = support::libScriptSearch(cs.str());
600 // Initiate the conversion from LaTeX to bitmap images files.
601 support::Forkedcall::SignalTypePtr
602 convert_ptr(new support::Forkedcall::SignalType);
603 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
605 support::Forkedcall call;
606 int ret = call.startscript(command, convert_ptr);
609 LYXERR(Debug::GRAPHICS) << "PreviewLoader::startLoading()\n"
610 << "Unable to start process\n"
615 // Store the generation process in a list of all such processes
616 inprogress.pid = call.pid();
617 inprogress.command = command;
618 in_progress_[inprogress.pid] = inprogress;
622 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
625 InProgressProcesses::iterator git = in_progress_.find(pid);
626 if (git == in_progress_.end()) {
627 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
628 "data for PID " << pid << endl;
632 string const command = git->second.command;
633 string const status = retval > 0 ? "failed" : "succeeded";
634 LYXERR(Debug::GRAPHICS) << "PreviewLoader::finishedInProgress("
635 << retval << "): processing " << status
636 << " for " << command << endl;
640 // Read the metrics file, if it exists
641 vector<double> ascent_fractions(git->second.snippets.size());
642 setAscentFractions(ascent_fractions, git->second.metrics_file);
644 // Add these newly generated bitmap files to the cache and
645 // start loading them into LyX.
646 BitmapFile::const_iterator it = git->second.snippets.begin();
647 BitmapFile::const_iterator end = git->second.snippets.end();
649 std::list<PreviewImagePtr> newimages;
651 int metrics_counter = 0;
652 for (; it != end; ++it, ++metrics_counter) {
653 string const & snip = it->first;
654 FileName const & file = it->second;
655 double af = ascent_fractions[metrics_counter];
657 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
660 newimages.push_back(ptr);
663 // Remove the item from the list of still-executing processes.
664 in_progress_.erase(git);
666 // Tell the outside world
667 std::list<PreviewImagePtr>::const_reverse_iterator
668 nit = newimages.rbegin();
669 std::list<PreviewImagePtr>::const_reverse_iterator
670 nend = newimages.rend();
671 for (; nit != nend; ++nit) {
672 imageReady(*nit->get());
677 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
679 // Why on earth is Buffer::makeLaTeXFile a non-const method?
680 Buffer & tmp = const_cast<Buffer &>(buffer_);
681 // Dump the preamble only.
682 // We don't need an encoding for runparams since it is not used by
684 OutputParams runparams(0);
685 runparams.flavor = OutputParams::LATEX;
686 runparams.nice = true;
687 runparams.moving_arg = true;
688 runparams.free_spacing = true;
689 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
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
696 // WriteStream wi(os, runparams.moving_arg, true);
701 << "\\def\\lyxlock{}\n"
704 // Loop over the insets in the buffer and dump all the math-macros.
705 InsetBase & inset = buffer_.inset();
706 InsetIterator it = inset_iterator_begin(inset);
707 InsetIterator const end = inset_iterator_end(inset);
709 for (; it != end; ++it)
710 if (it->lyxCode() == InsetBase::MATHMACRO_CODE)
711 it->latex(buffer_, os, runparams);
713 // All equation labels appear as "(#)" + preview.sty's rendering of
715 if (lyxrc.preview_hashed_labels)
716 os << "\\renewcommand{\\theequation}{\\#}\n";
718 // Use the preview style file to ensure that each snippet appears on a
721 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
726 void PreviewLoader::Impl::dumpData(odocstream & os,
727 BitmapFile const & vec) const
732 BitmapFile::const_iterator it = vec.begin();
733 BitmapFile::const_iterator end = vec.end();
735 for (; it != end; ++it) {
737 os << "\\begin{preview}\n"
738 << from_utf8(it->first)
739 << "\n\\end{preview}\n\n";
743 } // namespace graphics