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"
20 #include "support/debug.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 LYXERR0("PreviewLoader::startLoading()\n"
109 << "No converter from \"lyxpreview\" format has been defined.");
115 void setAscentFractions(vector<double> & ascent_fractions,
116 FileName const & metrics_file)
118 // If all else fails, then the images will have equal ascents and
120 vector<double>::iterator it = ascent_fractions.begin();
121 vector<double>::iterator end = ascent_fractions.end();
124 ifstream in(metrics_file.toFilesystemEncoding().c_str());
126 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
127 << "Unable to open file!");
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 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
161 << "Error reading file!\n");
169 FindFirst(string const & comp) : comp_(comp) {}
170 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
176 /// Store info on a currently executing, forked process.
180 InProgress() : pid(0) {}
182 InProgress(string const & filename_base,
183 PendingSnippets const & pending,
184 string const & to_format);
185 /// Remove any files left lying around and kill the forked process.
193 FileName metrics_file;
198 typedef map<pid_t, InProgress> InProgressProcesses;
200 typedef InProgressProcesses::value_type InProgressProcess;
209 class PreviewLoader::Impl : public boost::signals::trackable {
212 Impl(PreviewLoader & p, Buffer const & b);
213 /// Stop any InProgress items still executing.
216 PreviewImage const * preview(string const & latex_snippet) const;
218 PreviewLoader::Status status(string const & latex_snippet) const;
220 void add(string const & latex_snippet);
222 void remove(string const & latex_snippet);
226 /// Emit this signal when an image is ready for display.
227 boost::signal<void(PreviewImage const &)> imageReady;
229 Buffer const & buffer() const { return buffer_; }
232 /// Called by the Forkedcall process that generated the bitmap files.
233 void finishedGenerating(pid_t, int);
235 void dumpPreamble(odocstream &) const;
237 void dumpData(odocstream &, BitmapFile const &) const;
239 /** cache_ allows easy retrieval of already-generated images
240 * using the LaTeX snippet as the identifier.
242 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
244 typedef map<string, PreviewImagePtr> Cache;
248 /** pending_ stores the LaTeX snippets in anticipation of them being
249 * sent to the converter.
251 PendingSnippets pending_;
253 /** in_progress_ stores all forked processes so that we can proceed
255 The map uses the conversion commands as its identifiers.
257 InProgressProcesses in_progress_;
260 PreviewLoader & parent_;
262 Buffer const & buffer_;
264 double font_scaling_factor_;
266 /// We don't own this
267 static lyx::Converter const * pconverter_;
271 lyx::Converter const * PreviewLoader::Impl::pconverter_;
275 // The public interface, defined in PreviewLoader.h
278 PreviewLoader::PreviewLoader(Buffer const & b)
279 : pimpl_(new Impl(*this, b))
283 PreviewLoader::~PreviewLoader()
289 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
291 return pimpl_->preview(latex_snippet);
295 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
297 return pimpl_->status(latex_snippet);
301 void PreviewLoader::add(string const & latex_snippet) const
303 pimpl_->add(latex_snippet);
307 void PreviewLoader::remove(string const & latex_snippet) const
309 pimpl_->remove(latex_snippet);
313 void PreviewLoader::startLoading() const
315 pimpl_->startLoading();
319 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
321 return pimpl_->imageReady.connect(slot);
325 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
327 pimpl_->imageReady(pimage);
331 Buffer const & PreviewLoader::buffer() const
333 return pimpl_->buffer();
336 } // namespace graphics
340 // The details of the Impl
341 // =======================
345 class IncrementedFileName {
347 IncrementedFileName(string const & to_format,
348 string const & filename_base)
349 : to_format_(to_format), base_(filename_base), counter_(1)
352 SnippetPair const operator()(string const & snippet)
355 os << base_ << counter_++ << '.' << to_format_;
356 string const file = os.str();
358 return make_pair(snippet, FileName(file));
362 string const & to_format_;
363 string const & base_;
368 InProgress::InProgress(string const & filename_base,
369 PendingSnippets const & pending,
370 string const & to_format)
372 metrics_file(FileName(filename_base + ".metrics")),
373 snippets(pending.size())
375 PendingSnippets::const_iterator pit = pending.begin();
376 PendingSnippets::const_iterator pend = pending.end();
377 BitmapFile::iterator sit = snippets.begin();
379 std::transform(pit, pend, sit,
380 IncrementedFileName(to_format, filename_base));
384 void InProgress::stop() const
387 lyx::support::ForkedcallsController::get().kill(pid, 0);
389 if (!metrics_file.empty())
390 metrics_file.removeFile();
392 BitmapFile::const_iterator vit = snippets.begin();
393 BitmapFile::const_iterator vend = snippets.end();
394 for (; vit != vend; ++vit) {
395 if (!vit->second.empty())
396 vit->second.removeFile();
406 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
407 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
409 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
410 convert<double>(lyxrc.preview_scale_factor);
412 LYXERR(Debug::GRAPHICS, "The font scaling factor is "
413 << font_scaling_factor_);
416 pconverter_ = setConverter();
420 PreviewLoader::Impl::~Impl()
422 InProgressProcesses::iterator ipit = in_progress_.begin();
423 InProgressProcesses::iterator ipend = in_progress_.end();
425 for (; ipit != ipend; ++ipit) {
432 PreviewLoader::Impl::preview(string const & latex_snippet) const
434 Cache::const_iterator it = cache_.find(latex_snippet);
435 return (it == cache_.end()) ? 0 : it->second.get();
441 class FindSnippet : public std::unary_function<InProgressProcess, bool> {
443 FindSnippet(string const & s) : snippet_(s) {}
444 bool operator()(InProgressProcess const & process) const
446 BitmapFile const & snippets = process.second.snippets;
447 BitmapFile::const_iterator beg = snippets.begin();
448 BitmapFile::const_iterator end = snippets.end();
449 return find_if(beg, end, FindFirst(snippet_)) != end;
453 string const snippet_;
458 PreviewLoader::Status
459 PreviewLoader::Impl::status(string const & latex_snippet) const
461 Cache::const_iterator cit = cache_.find(latex_snippet);
462 if (cit != cache_.end())
465 PendingSnippets::const_iterator pit = pending_.begin();
466 PendingSnippets::const_iterator pend = pending_.end();
468 pit = find(pit, pend, latex_snippet);
472 InProgressProcesses::const_iterator ipit = in_progress_.begin();
473 InProgressProcesses::const_iterator ipend = in_progress_.end();
475 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
483 void PreviewLoader::Impl::add(string const & latex_snippet)
485 if (!pconverter_ || status(latex_snippet) != NotFound)
488 string const snippet = support::trim(latex_snippet);
492 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
494 pending_.push_back(snippet);
502 EraseSnippet(string const & s) : snippet_(s) {}
503 void operator()(InProgressProcess & process)
505 BitmapFile & snippets = process.second.snippets;
506 BitmapFile::iterator it = snippets.begin();
507 BitmapFile::iterator end = snippets.end();
509 it = find_if(it, end, FindFirst(snippet_));
511 snippets.erase(it, it+1);
515 string const & snippet_;
521 void PreviewLoader::Impl::remove(string const & latex_snippet)
523 Cache::iterator cit = cache_.find(latex_snippet);
524 if (cit != cache_.end())
527 PendingSnippets::iterator pit = pending_.begin();
528 PendingSnippets::iterator pend = pending_.end();
530 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
532 InProgressProcesses::iterator ipit = in_progress_.begin();
533 InProgressProcesses::iterator ipend = in_progress_.end();
535 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
537 while (ipit != ipend) {
538 InProgressProcesses::iterator curr = ipit++;
539 if (curr->second.snippets.empty())
540 in_progress_.erase(curr);
545 void PreviewLoader::Impl::startLoading()
547 if (pending_.empty() || !pconverter_)
550 // Only start the process off after the buffer is loaded from file.
551 if (!buffer_.isFullyLoaded())
554 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
556 // As used by the LaTeX file and by the resulting image files
557 string const directory = buffer_.temppath();
559 string const filename_base = unique_filename(directory);
561 // Create an InProgress instance to place in the map of all
562 // such processes if it starts correctly.
563 InProgress inprogress(filename_base, pending_, pconverter_->to);
565 // clear pending_, so we're ready to start afresh.
568 // Output the LaTeX file.
569 FileName const latexfile(filename_base + ".tex");
571 // we use the encoding of the buffer
572 Encoding const & enc = buffer_.params().encoding();
573 odocfstream of(enc.iconvName());
575 OutputParams runparams(&enc);
576 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
578 if (!openFileWrite(of, latexfile))
582 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
583 << "Unable to create LaTeX file\n" << latexfile);
586 of << "\\batchmode\n";
588 // handle inputenc etc.
589 buffer_.params().writeEncodingPreamble(of, features, texrow);
590 of << "\n\\begin{document}\n";
591 dumpData(of, inprogress.snippets);
592 of << "\n\\end{document}\n";
595 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
596 << "File was not closed properly.");
600 // The conversion command.
602 cs << pconverter_->command << ' ' << pconverter_->to << ' '
603 << support::quoteName(latexfile.toFilesystemEncoding()) << ' '
604 << int(font_scaling_factor_) << ' '
605 << theApp()->hexName(Color_preview) << ' '
606 << theApp()->hexName(Color_background);
608 string const command = support::libScriptSearch(cs.str());
610 // Initiate the conversion from LaTeX to bitmap images files.
611 support::Forkedcall::SignalTypePtr
612 convert_ptr(new support::Forkedcall::SignalType);
613 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
615 support::Forkedcall call;
616 int ret = call.startscript(command, convert_ptr);
619 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
620 << "Unable to start process\n" << command);
624 // Store the generation process in a list of all such processes
625 inprogress.pid = call.pid();
626 inprogress.command = command;
627 in_progress_[inprogress.pid] = inprogress;
631 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
634 InProgressProcesses::iterator git = in_progress_.find(pid);
635 if (git == in_progress_.end()) {
636 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
637 "data for PID " << pid << endl;
641 string const command = git->second.command;
642 string const status = retval > 0 ? "failed" : "succeeded";
643 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
644 << retval << "): processing " << status
645 << " for " << command);
649 // Read the metrics file, if it exists
650 vector<double> ascent_fractions(git->second.snippets.size());
651 setAscentFractions(ascent_fractions, git->second.metrics_file);
653 // Add these newly generated bitmap files to the cache and
654 // start loading them into LyX.
655 BitmapFile::const_iterator it = git->second.snippets.begin();
656 BitmapFile::const_iterator end = git->second.snippets.end();
658 std::list<PreviewImagePtr> newimages;
660 int metrics_counter = 0;
661 for (; it != end; ++it, ++metrics_counter) {
662 string const & snip = it->first;
663 FileName const & file = it->second;
664 double af = ascent_fractions[metrics_counter];
666 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
669 newimages.push_back(ptr);
672 // Remove the item from the list of still-executing processes.
673 in_progress_.erase(git);
675 // Tell the outside world
676 std::list<PreviewImagePtr>::const_reverse_iterator
677 nit = newimages.rbegin();
678 std::list<PreviewImagePtr>::const_reverse_iterator
679 nend = newimages.rend();
680 for (; nit != nend; ++nit) {
681 imageReady(*nit->get());
686 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
688 // Why on earth is Buffer::makeLaTeXFile a non-const method?
689 Buffer & tmp = const_cast<Buffer &>(buffer_);
690 // Dump the preamble only.
691 // We don't need an encoding for runparams since it is not used by
693 OutputParams runparams(0);
694 runparams.flavor = OutputParams::LATEX;
695 runparams.nice = true;
696 runparams.moving_arg = true;
697 runparams.free_spacing = true;
698 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
700 // FIXME! This is a HACK! The proper fix is to control the 'true'
701 // passed to WriteStream below:
702 // int InsetMathNest::latex(Buffer const &, odocstream & os,
703 // OutputParams const & runparams) const
705 // WriteStream wi(os, runparams.moving_arg, true);
710 << "\\def\\lyxlock{}\n"
713 // Loop over the insets in the buffer and dump all the math-macros.
714 Inset & inset = buffer_.inset();
715 InsetIterator it = inset_iterator_begin(inset);
716 InsetIterator const end = inset_iterator_end(inset);
718 for (; it != end; ++it)
719 if (it->lyxCode() == MATHMACRO_CODE)
720 it->latex(buffer_, os, runparams);
722 // All equation labels appear as "(#)" + preview.sty's rendering of
724 if (lyxrc.preview_hashed_labels)
725 os << "\\renewcommand{\\theequation}{\\#}\n";
727 // Use the preview style file to ensure that each snippet appears on a
730 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
735 void PreviewLoader::Impl::dumpData(odocstream & os,
736 BitmapFile const & vec) const
741 BitmapFile::const_iterator it = vec.begin();
742 BitmapFile::const_iterator end = vec.end();
744 for (; it != end; ++it) {
746 os << "\\begin{preview}\n"
747 << from_utf8(it->first)
748 << "\n\\end{preview}\n\n";
752 } // namespace graphics