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"
25 #include "LaTeXFeatures.h"
28 #include "OutputParams.h"
31 #include "frontends/Application.h" // hexName
33 #include "insets/Inset.h"
35 #include "support/filetools.h"
36 #include "support/Forkedcall.h"
37 #include "support/ForkedcallsController.h"
38 #include "support/lstrings.h"
39 #include "support/lyxlib.h"
40 #include "support/convert.h"
42 #include <boost/bind.hpp>
48 using lyx::support::FileName;
61 using std::ostringstream;
69 typedef pair<string, FileName> SnippetPair;
71 // A list of all snippets to be converted to previews
72 typedef list<string> PendingSnippets;
74 // Each item in the vector is a pair<snippet, image file name>.
75 typedef vector<SnippetPair> BitmapFile;
78 string const unique_filename(string const & bufferpath)
80 static int theCounter = 0;
81 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
82 return lyx::support::addName(bufferpath, filename);
86 lyx::Converter const * setConverter()
88 string const from = "lyxpreview";
90 typedef vector<string> FmtList;
91 typedef lyx::graphics::Cache GCache;
92 FmtList const loadableFormats = GCache::get().loadableFormats();
93 FmtList::const_iterator it = loadableFormats.begin();
94 FmtList::const_iterator const end = loadableFormats.end();
96 for (; it != end; ++it) {
97 string const to = *it;
101 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
106 static bool first = true;
109 lyx::lyxerr << "PreviewLoader::startLoading()\n"
110 << "No converter from \"lyxpreview\" format has been "
118 void setAscentFractions(vector<double> & ascent_fractions,
119 FileName const & metrics_file)
121 // If all else fails, then the images will have equal ascents and
123 vector<double>::iterator it = ascent_fractions.begin();
124 vector<double>::iterator end = ascent_fractions.end();
127 ifstream in(metrics_file.toFilesystemEncoding().c_str());
129 lyx::lyxerr[lyx::Debug::GRAPHICS]
130 << "setAscentFractions(" << metrics_file << ")\n"
131 << "Unable to open file!" << endl;
137 int snippet_counter = 1;
138 while (!in.eof() && it != end) {
141 double ascent_fraction;
143 in >> snippet >> id >> ascent_fraction;
149 error = snippet != "Snippet";
153 error = id != snippet_counter;
157 *it = ascent_fraction;
164 lyx::lyxerr[lyx::Debug::GRAPHICS]
165 << "setAscentFractions(" << metrics_file << ")\n"
166 << "Error reading file!\n" << endl;
171 class FindFirst : public std::unary_function<SnippetPair, bool> {
173 FindFirst(string const & comp) : comp_(comp) {}
174 bool operator()(SnippetPair const & sp) const
176 return sp.first == comp_;
183 /// Store info on a currently executing, forked process.
187 InProgress() : pid(0) {}
189 InProgress(string const & filename_base,
190 PendingSnippets const & pending,
191 string const & to_format);
192 /// Remove any files left lying around and kill the forked process.
200 FileName metrics_file;
205 typedef map<pid_t, InProgress> InProgressProcesses;
207 typedef InProgressProcesses::value_type InProgressProcess;
217 class PreviewLoader::Impl : public boost::signals::trackable {
220 Impl(PreviewLoader & p, Buffer const & b);
221 /// Stop any InProgress items still executing.
224 PreviewImage const * preview(string const & latex_snippet) const;
226 PreviewLoader::Status status(string const & latex_snippet) const;
228 void add(string const & latex_snippet);
230 void remove(string const & latex_snippet);
234 /// Emit this signal when an image is ready for display.
235 boost::signal<void(PreviewImage const &)> imageReady;
237 Buffer const & buffer() const { return buffer_; }
240 /// Called by the Forkedcall process that generated the bitmap files.
241 void finishedGenerating(pid_t, int);
243 void dumpPreamble(odocstream &) const;
245 void dumpData(odocstream &, BitmapFile const &) const;
247 /** cache_ allows easy retrieval of already-generated images
248 * using the LaTeX snippet as the identifier.
250 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
252 typedef map<string, PreviewImagePtr> Cache;
256 /** pending_ stores the LaTeX snippets in anticipation of them being
257 * sent to the converter.
259 PendingSnippets pending_;
261 /** in_progress_ stores all forked processes so that we can proceed
263 The map uses the conversion commands as its identifiers.
265 InProgressProcesses in_progress_;
268 PreviewLoader & parent_;
270 Buffer const & buffer_;
272 double font_scaling_factor_;
274 /// We don't own this
275 static lyx::Converter const * pconverter_;
279 lyx::Converter const * PreviewLoader::Impl::pconverter_;
283 // The public interface, defined in PreviewLoader.h
286 PreviewLoader::PreviewLoader(Buffer const & b)
287 : pimpl_(new Impl(*this, b))
291 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 lyx::support::unlink(metrics_file);
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 lyx::support::unlink(vit->second);
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_ << endl;
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 << endl;
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()" << endl;
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"
590 << latexfile << endl;
593 of << "\\batchmode\n";
595 // handle inputenc etc.
596 buffer_.params().writeEncodingPreamble(of, features, texrow);
597 of << "\n\\begin{document}\n";
598 dumpData(of, inprogress.snippets);
599 of << "\n\\end{document}\n";
602 LYXERR(Debug::GRAPHICS) << "PreviewLoader::startLoading()\n"
603 << "File was not closed properly."
608 // The conversion command.
610 cs << pconverter_->command << ' ' << pconverter_->to << ' '
611 << support::quoteName(latexfile.toFilesystemEncoding()) << ' '
612 << int(font_scaling_factor_) << ' '
613 << theApp()->hexName(Color::preview) << ' '
614 << theApp()->hexName(Color::background);
616 string const command = support::libScriptSearch(cs.str());
618 // Initiate the conversion from LaTeX to bitmap images files.
619 support::Forkedcall::SignalTypePtr
620 convert_ptr(new support::Forkedcall::SignalType);
621 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
623 support::Forkedcall call;
624 int ret = call.startscript(command, convert_ptr);
627 LYXERR(Debug::GRAPHICS) << "PreviewLoader::startLoading()\n"
628 << "Unable to start process\n"
633 // Store the generation process in a list of all such processes
634 inprogress.pid = call.pid();
635 inprogress.command = command;
636 in_progress_[inprogress.pid] = inprogress;
640 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
643 InProgressProcesses::iterator git = in_progress_.find(pid);
644 if (git == in_progress_.end()) {
645 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
646 "data for PID " << pid << endl;
650 string const command = git->second.command;
651 string const status = retval > 0 ? "failed" : "succeeded";
652 LYXERR(Debug::GRAPHICS) << "PreviewLoader::finishedInProgress("
653 << retval << "): processing " << status
654 << " for " << command << endl;
658 // Read the metrics file, if it exists
659 vector<double> ascent_fractions(git->second.snippets.size());
660 setAscentFractions(ascent_fractions, git->second.metrics_file);
662 // Add these newly generated bitmap files to the cache and
663 // start loading them into LyX.
664 BitmapFile::const_iterator it = git->second.snippets.begin();
665 BitmapFile::const_iterator end = git->second.snippets.end();
667 std::list<PreviewImagePtr> newimages;
669 int metrics_counter = 0;
670 for (; it != end; ++it, ++metrics_counter) {
671 string const & snip = it->first;
672 FileName const & file = it->second;
673 double af = ascent_fractions[metrics_counter];
675 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
678 newimages.push_back(ptr);
681 // Remove the item from the list of still-executing processes.
682 in_progress_.erase(git);
684 // Tell the outside world
685 std::list<PreviewImagePtr>::const_reverse_iterator
686 nit = newimages.rbegin();
687 std::list<PreviewImagePtr>::const_reverse_iterator
688 nend = newimages.rend();
689 for (; nit != nend; ++nit) {
690 imageReady(*nit->get());
695 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
697 // Why on earth is Buffer::makeLaTeXFile a non-const method?
698 Buffer & tmp = const_cast<Buffer &>(buffer_);
699 // Dump the preamble only.
700 // We don't need an encoding for runparams since it is not used by
702 OutputParams runparams(0);
703 runparams.flavor = OutputParams::LATEX;
704 runparams.nice = true;
705 runparams.moving_arg = true;
706 runparams.free_spacing = true;
707 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
709 // FIXME! This is a HACK! The proper fix is to control the 'true'
710 // passed to WriteStream below:
711 // int InsetMathNest::latex(Buffer const &, odocstream & os,
712 // OutputParams const & runparams) const
714 // WriteStream wi(os, runparams.moving_arg, true);
719 << "\\def\\lyxlock{}\n"
722 // Loop over the insets in the buffer and dump all the math-macros.
723 Inset & inset = buffer_.inset();
724 InsetIterator it = inset_iterator_begin(inset);
725 InsetIterator const end = inset_iterator_end(inset);
727 for (; it != end; ++it)
728 if (it->lyxCode() == MATHMACRO_CODE)
729 it->latex(buffer_, os, runparams);
731 // All equation labels appear as "(#)" + preview.sty's rendering of
733 if (lyxrc.preview_hashed_labels)
734 os << "\\renewcommand{\\theequation}{\\#}\n";
736 // Use the preview style file to ensure that each snippet appears on a
739 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
744 void PreviewLoader::Impl::dumpData(odocstream & os,
745 BitmapFile const & vec) const
750 BitmapFile::const_iterator it = vec.begin();
751 BitmapFile::const_iterator end = vec.end();
753 for (; it != end; ++it) {
755 os << "\\begin{preview}\n"
756 << from_utf8(it->first)
757 << "\n\\end{preview}\n\n";
761 } // namespace graphics