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 "BufferParams.h"
19 #include "Converter.h"
22 #include "InsetIterator.h"
23 #include "LaTeXFeatures.h"
26 #include "OutputParams.h"
29 #include "frontends/Application.h" // hexName
31 #include "insets/Inset.h"
33 #include "support/convert.h"
34 #include "support/debug.h"
35 #include "support/filetools.h"
36 #include "support/ForkedCalls.h"
37 #include "support/lstrings.h"
38 #include "support/lyxlib.h"
40 #include <boost/bind.hpp>
47 using namespace lyx::support;
53 typedef pair<string, FileName> SnippetPair;
55 // A list of all snippets to be converted to previews
56 typedef list<string> PendingSnippets;
58 // Each item in the vector is a pair<snippet, image file name>.
59 typedef vector<SnippetPair> BitmapFile;
62 string const unique_filename(string const & bufferpath)
64 static int theCounter = 0;
65 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
66 return lyx::support::addName(bufferpath, filename);
70 lyx::Converter const * setConverter()
72 string const from = "lyxpreview";
74 typedef vector<string> FmtList;
75 typedef lyx::graphics::Cache GCache;
76 FmtList const loadableFormats = GCache::get().loadableFormats();
77 FmtList::const_iterator it = loadableFormats.begin();
78 FmtList::const_iterator const end = loadableFormats.end();
80 for (; it != end; ++it) {
81 string const to = *it;
85 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
90 static bool first = true;
93 LYXERR0("PreviewLoader::startLoading()\n"
94 << "No converter from \"lyxpreview\" format has been defined.");
100 void setAscentFractions(vector<double> & ascent_fractions,
101 FileName const & metrics_file)
103 // If all else fails, then the images will have equal ascents and
105 vector<double>::iterator it = ascent_fractions.begin();
106 vector<double>::iterator end = ascent_fractions.end();
109 ifstream in(metrics_file.toFilesystemEncoding().c_str());
111 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
112 << "Unable to open file!");
118 int snippet_counter = 1;
119 while (!in.eof() && it != end) {
122 double ascent_fraction;
124 in >> snippet >> id >> ascent_fraction;
130 error = snippet != "Snippet";
134 error = id != snippet_counter;
138 *it = ascent_fraction;
145 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
146 << "Error reading file!\n");
154 FindFirst(string const & comp) : comp_(comp) {}
155 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
161 /// Store info on a currently executing, forked process.
165 InProgress() : pid(0) {}
167 InProgress(string const & filename_base,
168 PendingSnippets const & pending,
169 string const & to_format);
170 /// Remove any files left lying around and kill the forked process.
178 FileName metrics_file;
183 typedef map<pid_t, InProgress> InProgressProcesses;
185 typedef InProgressProcesses::value_type InProgressProcess;
194 class PreviewLoader::Impl : public boost::signals::trackable {
197 Impl(PreviewLoader & p, Buffer const & b);
198 /// Stop any InProgress items still executing.
201 PreviewImage const * preview(string const & latex_snippet) const;
203 PreviewLoader::Status status(string const & latex_snippet) const;
205 void add(string const & latex_snippet);
207 void remove(string const & latex_snippet);
211 /// Emit this signal when an image is ready for display.
212 boost::signal<void(PreviewImage const &)> imageReady;
214 Buffer const & buffer() const { return buffer_; }
217 /// Called by the ForkedCall process that generated the bitmap files.
218 void finishedGenerating(pid_t, int);
220 void dumpPreamble(odocstream &) const;
222 void dumpData(odocstream &, BitmapFile const &) const;
224 /** cache_ allows easy retrieval of already-generated images
225 * using the LaTeX snippet as the identifier.
227 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
229 typedef map<string, PreviewImagePtr> Cache;
233 /** pending_ stores the LaTeX snippets in anticipation of them being
234 * sent to the converter.
236 PendingSnippets pending_;
238 /** in_progress_ stores all forked processes so that we can proceed
240 The map uses the conversion commands as its identifiers.
242 InProgressProcesses in_progress_;
245 PreviewLoader & parent_;
247 Buffer const & buffer_;
249 double font_scaling_factor_;
251 /// We don't own this
252 static lyx::Converter const * pconverter_;
256 lyx::Converter const * PreviewLoader::Impl::pconverter_;
260 // The public interface, defined in PreviewLoader.h
263 PreviewLoader::PreviewLoader(Buffer const & b)
264 : pimpl_(new Impl(*this, b))
268 PreviewLoader::~PreviewLoader()
274 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
276 return pimpl_->preview(latex_snippet);
280 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
282 return pimpl_->status(latex_snippet);
286 void PreviewLoader::add(string const & latex_snippet) const
288 pimpl_->add(latex_snippet);
292 void PreviewLoader::remove(string const & latex_snippet) const
294 pimpl_->remove(latex_snippet);
298 void PreviewLoader::startLoading() const
300 pimpl_->startLoading();
304 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
306 return pimpl_->imageReady.connect(slot);
310 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
312 pimpl_->imageReady(pimage);
316 Buffer const & PreviewLoader::buffer() const
318 return pimpl_->buffer();
321 } // namespace graphics
325 // The details of the Impl
326 // =======================
330 class IncrementedFileName {
332 IncrementedFileName(string const & to_format,
333 string const & filename_base)
334 : to_format_(to_format), base_(filename_base), counter_(1)
337 SnippetPair const operator()(string const & snippet)
340 os << base_ << counter_++ << '.' << to_format_;
341 string const file = os.str();
343 return make_pair(snippet, FileName(file));
347 string const & to_format_;
348 string const & base_;
353 InProgress::InProgress(string const & filename_base,
354 PendingSnippets const & pending,
355 string const & to_format)
357 metrics_file(FileName(filename_base + ".metrics")),
358 snippets(pending.size())
360 PendingSnippets::const_iterator pit = pending.begin();
361 PendingSnippets::const_iterator pend = pending.end();
362 BitmapFile::iterator sit = snippets.begin();
364 transform(pit, pend, sit,
365 IncrementedFileName(to_format, filename_base));
369 void InProgress::stop() const
372 lyx::support::ForkedCallsController::kill(pid, 0);
374 if (!metrics_file.empty())
375 metrics_file.removeFile();
377 BitmapFile::const_iterator vit = snippets.begin();
378 BitmapFile::const_iterator vend = snippets.end();
379 for (; vit != vend; ++vit) {
380 if (!vit->second.empty())
381 vit->second.removeFile();
391 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
392 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
394 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
395 convert<double>(lyxrc.preview_scale_factor);
397 LYXERR(Debug::GRAPHICS, "The font scaling factor is "
398 << font_scaling_factor_);
401 pconverter_ = setConverter();
405 PreviewLoader::Impl::~Impl()
407 InProgressProcesses::iterator ipit = in_progress_.begin();
408 InProgressProcesses::iterator ipend = in_progress_.end();
410 for (; ipit != ipend; ++ipit)
416 PreviewLoader::Impl::preview(string const & latex_snippet) const
418 Cache::const_iterator it = cache_.find(latex_snippet);
419 return (it == cache_.end()) ? 0 : it->second.get();
427 FindSnippet(string const & s) : snippet_(s) {}
428 bool operator()(InProgressProcess const & process) const
430 BitmapFile const & snippets = process.second.snippets;
431 BitmapFile::const_iterator beg = snippets.begin();
432 BitmapFile::const_iterator end = snippets.end();
433 return find_if(beg, end, FindFirst(snippet_)) != end;
437 string const snippet_;
442 PreviewLoader::Status
443 PreviewLoader::Impl::status(string const & latex_snippet) const
445 Cache::const_iterator cit = cache_.find(latex_snippet);
446 if (cit != cache_.end())
449 PendingSnippets::const_iterator pit = pending_.begin();
450 PendingSnippets::const_iterator pend = pending_.end();
452 pit = find(pit, pend, latex_snippet);
456 InProgressProcesses::const_iterator ipit = in_progress_.begin();
457 InProgressProcesses::const_iterator ipend = in_progress_.end();
459 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
467 void PreviewLoader::Impl::add(string const & latex_snippet)
469 if (!pconverter_ || status(latex_snippet) != NotFound)
472 string const snippet = support::trim(latex_snippet);
476 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
478 pending_.push_back(snippet);
486 EraseSnippet(string const & s) : snippet_(s) {}
487 void operator()(InProgressProcess & process)
489 BitmapFile & snippets = process.second.snippets;
490 BitmapFile::iterator it = snippets.begin();
491 BitmapFile::iterator end = snippets.end();
493 it = find_if(it, end, FindFirst(snippet_));
495 snippets.erase(it, it+1);
499 string const & snippet_;
505 void PreviewLoader::Impl::remove(string const & latex_snippet)
507 Cache::iterator cit = cache_.find(latex_snippet);
508 if (cit != cache_.end())
511 PendingSnippets::iterator pit = pending_.begin();
512 PendingSnippets::iterator pend = pending_.end();
514 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
516 InProgressProcesses::iterator ipit = in_progress_.begin();
517 InProgressProcesses::iterator ipend = in_progress_.end();
519 for_each(ipit, ipend, EraseSnippet(latex_snippet));
521 while (ipit != ipend) {
522 InProgressProcesses::iterator curr = ipit++;
523 if (curr->second.snippets.empty())
524 in_progress_.erase(curr);
529 void PreviewLoader::Impl::startLoading()
531 if (pending_.empty() || !pconverter_)
534 // Only start the process off after the buffer is loaded from file.
535 if (!buffer_.isFullyLoaded())
538 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
540 // As used by the LaTeX file and by the resulting image files
541 string const directory = buffer_.temppath();
543 string const filename_base = unique_filename(directory);
545 // Create an InProgress instance to place in the map of all
546 // such processes if it starts correctly.
547 InProgress inprogress(filename_base, pending_, pconverter_->to);
549 // clear pending_, so we're ready to start afresh.
552 // Output the LaTeX file.
553 FileName const latexfile(filename_base + ".tex");
555 // we use the encoding of the buffer
556 Encoding const & enc = buffer_.params().encoding();
557 odocfstream of(enc.iconvName());
559 OutputParams runparams(&enc);
560 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
562 if (!openFileWrite(of, latexfile))
566 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
567 << "Unable to create LaTeX file\n" << latexfile);
570 of << "\\batchmode\n";
572 // handle inputenc etc.
573 buffer_.params().writeEncodingPreamble(of, features, texrow);
574 of << "\n\\begin{document}\n";
575 dumpData(of, inprogress.snippets);
576 of << "\n\\end{document}\n";
579 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
580 << "File was not closed properly.");
584 // The conversion command.
586 cs << pconverter_->command << ' ' << pconverter_->to << ' '
587 << support::quoteName(latexfile.toFilesystemEncoding()) << ' '
588 << int(font_scaling_factor_) << ' '
589 << theApp()->hexName(Color_preview) << ' '
590 << theApp()->hexName(Color_background);
592 string const command = support::libScriptSearch(cs.str());
594 // Initiate the conversion from LaTeX to bitmap images files.
595 support::ForkedCall::SignalTypePtr
596 convert_ptr(new support::ForkedCall::SignalType);
597 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
599 support::ForkedCall call;
600 int ret = call.startScript(command, convert_ptr);
603 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
604 << "Unable to start process\n" << command);
608 // Store the generation process in a list of all such processes
609 inprogress.pid = call.pid();
610 inprogress.command = command;
611 in_progress_[inprogress.pid] = inprogress;
615 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
618 InProgressProcesses::iterator git = in_progress_.find(pid);
619 if (git == in_progress_.end()) {
620 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
621 "data for PID " << pid << endl;
625 string const command = git->second.command;
626 string const status = retval > 0 ? "failed" : "succeeded";
627 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
628 << retval << "): processing " << status
629 << " for " << command);
633 // Read the metrics file, if it exists
634 vector<double> ascent_fractions(git->second.snippets.size());
635 setAscentFractions(ascent_fractions, git->second.metrics_file);
637 // Add these newly generated bitmap files to the cache and
638 // start loading them into LyX.
639 BitmapFile::const_iterator it = git->second.snippets.begin();
640 BitmapFile::const_iterator end = git->second.snippets.end();
642 list<PreviewImagePtr> newimages;
644 int metrics_counter = 0;
645 for (; it != end; ++it, ++metrics_counter) {
646 string const & snip = it->first;
647 FileName const & file = it->second;
648 double af = ascent_fractions[metrics_counter];
650 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
653 newimages.push_back(ptr);
656 // Remove the item from the list of still-executing processes.
657 in_progress_.erase(git);
659 // Tell the outside world
660 list<PreviewImagePtr>::const_reverse_iterator
661 nit = newimages.rbegin();
662 list<PreviewImagePtr>::const_reverse_iterator
663 nend = newimages.rend();
664 for (; nit != nend; ++nit) {
665 imageReady(*nit->get());
670 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
672 // Why on earth is Buffer::makeLaTeXFile a non-const method?
673 Buffer & tmp = const_cast<Buffer &>(buffer_);
674 // Dump the preamble only.
675 // We don't need an encoding for runparams since it is not used by
677 OutputParams runparams(0);
678 runparams.flavor = OutputParams::LATEX;
679 runparams.nice = true;
680 runparams.moving_arg = true;
681 runparams.free_spacing = true;
682 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
684 // FIXME! This is a HACK! The proper fix is to control the 'true'
685 // passed to WriteStream below:
686 // int InsetMathNest::latex(Buffer const &, odocstream & os,
687 // OutputParams const & runparams) const
689 // WriteStream wi(os, runparams.moving_arg, true);
694 << "\\def\\lyxlock{}\n"
697 // Loop over the insets in the buffer and dump all the math-macros.
698 Inset & inset = buffer_.inset();
699 InsetIterator it = inset_iterator_begin(inset);
700 InsetIterator const end = inset_iterator_end(inset);
702 for (; it != end; ++it)
703 if (it->lyxCode() == MATHMACRO_CODE)
704 it->latex(buffer_, os, runparams);
706 // All equation labels appear as "(#)" + preview.sty's rendering of
708 if (lyxrc.preview_hashed_labels)
709 os << "\\renewcommand{\\theequation}{\\#}\n";
711 // Use the preview style file to ensure that each snippet appears on a
714 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
719 void PreviewLoader::Impl::dumpData(odocstream & os,
720 BitmapFile const & vec) const
725 BitmapFile::const_iterator it = vec.begin();
726 BitmapFile::const_iterator end = vec.end();
728 for (; it != end; ++it) {
730 os << "\\begin{preview}\n"
731 << from_utf8(it->first)
732 << "\n\\end{preview}\n\n";
736 } // namespace graphics