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"
23 #include "InsetIterator.h"
24 #include "LaTeXFeatures.h"
27 #include "OutputParams.h"
30 #include "frontends/Application.h" // hexName
32 #include "insets/Inset.h"
34 #include "support/filetools.h"
35 #include "support/Forkedcall.h"
36 #include "support/ForkedcallsController.h"
37 #include "support/lstrings.h"
38 #include "support/lyxlib.h"
39 #include "support/convert.h"
41 #include <boost/bind.hpp>
47 using lyx::support::FileName;
60 using std::ostringstream;
68 typedef pair<string, FileName> SnippetPair;
70 // A list of all snippets to be converted to previews
71 typedef list<string> PendingSnippets;
73 // Each item in the vector is a pair<snippet, image file name>.
74 typedef vector<SnippetPair> BitmapFile;
77 string const unique_filename(string const & bufferpath)
79 static int theCounter = 0;
80 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
81 return lyx::support::addName(bufferpath, filename);
85 lyx::Converter const * setConverter()
87 string const from = "lyxpreview";
89 typedef vector<string> FmtList;
90 typedef lyx::graphics::Cache GCache;
91 FmtList const loadableFormats = GCache::get().loadableFormats();
92 FmtList::const_iterator it = loadableFormats.begin();
93 FmtList::const_iterator const end = loadableFormats.end();
95 for (; it != end; ++it) {
96 string const to = *it;
100 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
105 static bool first = true;
108 lyx::lyxerr << "PreviewLoader::startLoading()\n"
109 << "No converter from \"lyxpreview\" format has been "
117 void setAscentFractions(vector<double> & ascent_fractions,
118 FileName const & metrics_file)
120 // If all else fails, then the images will have equal ascents and
122 vector<double>::iterator it = ascent_fractions.begin();
123 vector<double>::iterator end = ascent_fractions.end();
126 ifstream in(metrics_file.toFilesystemEncoding().c_str());
128 lyx::lyxerr[lyx::Debug::GRAPHICS]
129 << "setAscentFractions(" << metrics_file << ")\n"
130 << "Unable to open file!" << endl;
136 int snippet_counter = 1;
137 while (!in.eof() && it != end) {
140 double ascent_fraction;
142 in >> snippet >> id >> ascent_fraction;
148 error = snippet != "Snippet";
152 error = id != snippet_counter;
156 *it = ascent_fraction;
163 lyx::lyxerr[lyx::Debug::GRAPHICS]
164 << "setAscentFractions(" << metrics_file << ")\n"
165 << "Error reading file!\n" << endl;
170 class FindFirst : public std::unary_function<SnippetPair, bool> {
172 FindFirst(string const & comp) : comp_(comp) {}
173 bool operator()(SnippetPair const & sp) const
175 return sp.first == comp_;
182 /// Store info on a currently executing, forked process.
186 InProgress() : pid(0) {}
188 InProgress(string const & filename_base,
189 PendingSnippets const & pending,
190 string const & to_format);
191 /// Remove any files left lying around and kill the forked process.
199 FileName metrics_file;
204 typedef map<pid_t, InProgress> InProgressProcesses;
206 typedef InProgressProcesses::value_type InProgressProcess;
215 class PreviewLoader::Impl : public boost::signals::trackable {
218 Impl(PreviewLoader & p, Buffer const & b);
219 /// Stop any InProgress items still executing.
222 PreviewImage const * preview(string const & latex_snippet) const;
224 PreviewLoader::Status status(string const & latex_snippet) const;
226 void add(string const & latex_snippet);
228 void remove(string const & latex_snippet);
232 /// Emit this signal when an image is ready for display.
233 boost::signal<void(PreviewImage const &)> imageReady;
235 Buffer const & buffer() const { return buffer_; }
238 /// Called by the Forkedcall process that generated the bitmap files.
239 void finishedGenerating(pid_t, int);
241 void dumpPreamble(odocstream &) const;
243 void dumpData(odocstream &, BitmapFile const &) const;
245 /** cache_ allows easy retrieval of already-generated images
246 * using the LaTeX snippet as the identifier.
248 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
250 typedef map<string, PreviewImagePtr> Cache;
254 /** pending_ stores the LaTeX snippets in anticipation of them being
255 * sent to the converter.
257 PendingSnippets pending_;
259 /** in_progress_ stores all forked processes so that we can proceed
261 The map uses the conversion commands as its identifiers.
263 InProgressProcesses in_progress_;
266 PreviewLoader & parent_;
268 Buffer const & buffer_;
270 double font_scaling_factor_;
272 /// We don't own this
273 static lyx::Converter const * pconverter_;
277 lyx::Converter const * PreviewLoader::Impl::pconverter_;
281 // The public interface, defined in PreviewLoader.h
284 PreviewLoader::PreviewLoader(Buffer const & b)
285 : pimpl_(new Impl(*this, b))
289 PreviewLoader::~PreviewLoader()
295 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
297 return pimpl_->preview(latex_snippet);
301 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
303 return pimpl_->status(latex_snippet);
307 void PreviewLoader::add(string const & latex_snippet) const
309 pimpl_->add(latex_snippet);
313 void PreviewLoader::remove(string const & latex_snippet) const
315 pimpl_->remove(latex_snippet);
319 void PreviewLoader::startLoading() const
321 pimpl_->startLoading();
325 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
327 return pimpl_->imageReady.connect(slot);
331 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
333 pimpl_->imageReady(pimage);
337 Buffer const & PreviewLoader::buffer() const
339 return pimpl_->buffer();
342 } // namespace graphics
346 // The details of the Impl
347 // =======================
351 class IncrementedFileName {
353 IncrementedFileName(string const & to_format,
354 string const & filename_base)
355 : to_format_(to_format), base_(filename_base), counter_(1)
358 SnippetPair const operator()(string const & snippet)
361 os << base_ << counter_++ << '.' << to_format_;
362 string const file = os.str();
364 return make_pair(snippet, FileName(file));
368 string const & to_format_;
369 string const & base_;
374 InProgress::InProgress(string const & filename_base,
375 PendingSnippets const & pending,
376 string const & to_format)
378 metrics_file(FileName(filename_base + ".metrics")),
379 snippets(pending.size())
381 PendingSnippets::const_iterator pit = pending.begin();
382 PendingSnippets::const_iterator pend = pending.end();
383 BitmapFile::iterator sit = snippets.begin();
385 std::transform(pit, pend, sit,
386 IncrementedFileName(to_format, filename_base));
390 void InProgress::stop() const
393 lyx::support::ForkedcallsController::get().kill(pid, 0);
395 if (!metrics_file.empty())
396 metrics_file.removeFile();
398 BitmapFile::const_iterator vit = snippets.begin();
399 BitmapFile::const_iterator vend = snippets.end();
400 for (; vit != vend; ++vit) {
401 if (!vit->second.empty())
402 vit->second.removeFile();
412 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
413 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
415 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
416 convert<double>(lyxrc.preview_scale_factor);
418 LYXERR(Debug::GRAPHICS, "The font scaling factor is "
419 << font_scaling_factor_);
422 pconverter_ = setConverter();
426 PreviewLoader::Impl::~Impl()
428 InProgressProcesses::iterator ipit = in_progress_.begin();
429 InProgressProcesses::iterator ipend = in_progress_.end();
431 for (; ipit != ipend; ++ipit) {
438 PreviewLoader::Impl::preview(string const & latex_snippet) const
440 Cache::const_iterator it = cache_.find(latex_snippet);
441 return (it == cache_.end()) ? 0 : it->second.get();
447 class FindSnippet : public std::unary_function<InProgressProcess, bool> {
449 FindSnippet(string const & s) : snippet_(s) {}
450 bool operator()(InProgressProcess const & process) const
452 BitmapFile const & snippets = process.second.snippets;
453 BitmapFile::const_iterator beg = snippets.begin();
454 BitmapFile::const_iterator end = snippets.end();
455 return find_if(beg, end, FindFirst(snippet_)) != end;
459 string const snippet_;
464 PreviewLoader::Status
465 PreviewLoader::Impl::status(string const & latex_snippet) const
467 Cache::const_iterator cit = cache_.find(latex_snippet);
468 if (cit != cache_.end())
471 PendingSnippets::const_iterator pit = pending_.begin();
472 PendingSnippets::const_iterator pend = pending_.end();
474 pit = find(pit, pend, latex_snippet);
478 InProgressProcesses::const_iterator ipit = in_progress_.begin();
479 InProgressProcesses::const_iterator ipend = in_progress_.end();
481 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
489 void PreviewLoader::Impl::add(string const & latex_snippet)
491 if (!pconverter_ || status(latex_snippet) != NotFound)
494 string const snippet = support::trim(latex_snippet);
498 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
500 pending_.push_back(snippet);
508 EraseSnippet(string const & s) : snippet_(s) {}
509 void operator()(InProgressProcess & process)
511 BitmapFile & snippets = process.second.snippets;
512 BitmapFile::iterator it = snippets.begin();
513 BitmapFile::iterator end = snippets.end();
515 it = find_if(it, end, FindFirst(snippet_));
517 snippets.erase(it, it+1);
521 string const & snippet_;
527 void PreviewLoader::Impl::remove(string const & latex_snippet)
529 Cache::iterator cit = cache_.find(latex_snippet);
530 if (cit != cache_.end())
533 PendingSnippets::iterator pit = pending_.begin();
534 PendingSnippets::iterator pend = pending_.end();
536 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
538 InProgressProcesses::iterator ipit = in_progress_.begin();
539 InProgressProcesses::iterator ipend = in_progress_.end();
541 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
543 while (ipit != ipend) {
544 InProgressProcesses::iterator curr = ipit++;
545 if (curr->second.snippets.empty())
546 in_progress_.erase(curr);
551 void PreviewLoader::Impl::startLoading()
553 if (pending_.empty() || !pconverter_)
556 // Only start the process off after the buffer is loaded from file.
557 if (!buffer_.isFullyLoaded())
560 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
562 // As used by the LaTeX file and by the resulting image files
563 string const directory = buffer_.temppath();
565 string const filename_base = unique_filename(directory);
567 // Create an InProgress instance to place in the map of all
568 // such processes if it starts correctly.
569 InProgress inprogress(filename_base, pending_, pconverter_->to);
571 // clear pending_, so we're ready to start afresh.
574 // Output the LaTeX file.
575 FileName const latexfile(filename_base + ".tex");
577 // we use the encoding of the buffer
578 Encoding const & enc = buffer_.params().encoding();
579 odocfstream of(enc.iconvName());
581 OutputParams runparams(&enc);
582 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
584 if (!openFileWrite(of, latexfile))
588 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
589 << "Unable to create LaTeX file\n" << latexfile);
592 of << "\\batchmode\n";
594 // handle inputenc etc.
595 buffer_.params().writeEncodingPreamble(of, features, texrow);
596 of << "\n\\begin{document}\n";
597 dumpData(of, inprogress.snippets);
598 of << "\n\\end{document}\n";
601 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
602 << "File was not closed properly.");
606 // The conversion command.
608 cs << pconverter_->command << ' ' << pconverter_->to << ' '
609 << support::quoteName(latexfile.toFilesystemEncoding()) << ' '
610 << int(font_scaling_factor_) << ' '
611 << theApp()->hexName(Color_preview) << ' '
612 << theApp()->hexName(Color_background);
614 string const command = support::libScriptSearch(cs.str());
616 // Initiate the conversion from LaTeX to bitmap images files.
617 support::Forkedcall::SignalTypePtr
618 convert_ptr(new support::Forkedcall::SignalType);
619 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
621 support::Forkedcall call;
622 int ret = call.startscript(command, convert_ptr);
625 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
626 << "Unable to start process\n" << command);
630 // Store the generation process in a list of all such processes
631 inprogress.pid = call.pid();
632 inprogress.command = command;
633 in_progress_[inprogress.pid] = inprogress;
637 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
640 InProgressProcesses::iterator git = in_progress_.find(pid);
641 if (git == in_progress_.end()) {
642 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
643 "data for PID " << pid << endl;
647 string const command = git->second.command;
648 string const status = retval > 0 ? "failed" : "succeeded";
649 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
650 << retval << "): processing " << status
651 << " for " << command);
655 // Read the metrics file, if it exists
656 vector<double> ascent_fractions(git->second.snippets.size());
657 setAscentFractions(ascent_fractions, git->second.metrics_file);
659 // Add these newly generated bitmap files to the cache and
660 // start loading them into LyX.
661 BitmapFile::const_iterator it = git->second.snippets.begin();
662 BitmapFile::const_iterator end = git->second.snippets.end();
664 std::list<PreviewImagePtr> newimages;
666 int metrics_counter = 0;
667 for (; it != end; ++it, ++metrics_counter) {
668 string const & snip = it->first;
669 FileName const & file = it->second;
670 double af = ascent_fractions[metrics_counter];
672 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
675 newimages.push_back(ptr);
678 // Remove the item from the list of still-executing processes.
679 in_progress_.erase(git);
681 // Tell the outside world
682 std::list<PreviewImagePtr>::const_reverse_iterator
683 nit = newimages.rbegin();
684 std::list<PreviewImagePtr>::const_reverse_iterator
685 nend = newimages.rend();
686 for (; nit != nend; ++nit) {
687 imageReady(*nit->get());
692 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
694 // Why on earth is Buffer::makeLaTeXFile a non-const method?
695 Buffer & tmp = const_cast<Buffer &>(buffer_);
696 // Dump the preamble only.
697 // We don't need an encoding for runparams since it is not used by
699 OutputParams runparams(0);
700 runparams.flavor = OutputParams::LATEX;
701 runparams.nice = true;
702 runparams.moving_arg = true;
703 runparams.free_spacing = true;
704 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
706 // FIXME! This is a HACK! The proper fix is to control the 'true'
707 // passed to WriteStream below:
708 // int InsetMathNest::latex(Buffer const &, odocstream & os,
709 // OutputParams const & runparams) const
711 // WriteStream wi(os, runparams.moving_arg, true);
716 << "\\def\\lyxlock{}\n"
719 // Loop over the insets in the buffer and dump all the math-macros.
720 Inset & inset = buffer_.inset();
721 InsetIterator it = inset_iterator_begin(inset);
722 InsetIterator const end = inset_iterator_end(inset);
724 for (; it != end; ++it)
725 if (it->lyxCode() == MATHMACRO_CODE)
726 it->latex(buffer_, os, runparams);
728 // All equation labels appear as "(#)" + preview.sty's rendering of
730 if (lyxrc.preview_hashed_labels)
731 os << "\\renewcommand{\\theequation}{\\#}\n";
733 // Use the preview style file to ensure that each snippet appears on a
736 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
741 void PreviewLoader::Impl::dumpData(odocstream & os,
742 BitmapFile const & vec) const
747 BitmapFile::const_iterator it = vec.begin();
748 BitmapFile::const_iterator end = vec.end();
750 for (; it != end; ++it) {
752 os << "\\begin{preview}\n"
753 << from_utf8(it->first)
754 << "\n\\end{preview}\n\n";
758 } // namespace graphics