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>
46 using lyx::support::FileName;
59 using std::ostringstream;
67 typedef pair<string, FileName> SnippetPair;
69 // A list of all snippets to be converted to previews
70 typedef list<string> PendingSnippets;
72 // Each item in the vector is a pair<snippet, image file name>.
73 typedef vector<SnippetPair> BitmapFile;
76 string const unique_filename(string const & bufferpath)
78 static int theCounter = 0;
79 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
80 return lyx::support::addName(bufferpath, filename);
84 lyx::Converter const * setConverter()
86 string const from = "lyxpreview";
88 typedef vector<string> FmtList;
89 typedef lyx::graphics::Cache GCache;
90 FmtList const loadableFormats = GCache::get().loadableFormats();
91 FmtList::const_iterator it = loadableFormats.begin();
92 FmtList::const_iterator const end = loadableFormats.end();
94 for (; it != end; ++it) {
95 string const to = *it;
99 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
104 static bool first = true;
107 LYXERR0("PreviewLoader::startLoading()\n"
108 << "No converter from \"lyxpreview\" format has been defined.");
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 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
126 << "Unable to open file!");
132 int snippet_counter = 1;
133 while (!in.eof() && it != end) {
136 double ascent_fraction;
138 in >> snippet >> id >> ascent_fraction;
144 error = snippet != "Snippet";
148 error = id != snippet_counter;
152 *it = ascent_fraction;
159 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
160 << "Error reading file!\n");
168 FindFirst(string const & comp) : comp_(comp) {}
169 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
175 /// Store info on a currently executing, forked process.
179 InProgress() : pid(0) {}
181 InProgress(string const & filename_base,
182 PendingSnippets const & pending,
183 string const & to_format);
184 /// Remove any files left lying around and kill the forked process.
192 FileName metrics_file;
197 typedef map<pid_t, InProgress> InProgressProcesses;
199 typedef InProgressProcesses::value_type InProgressProcess;
208 class PreviewLoader::Impl : public boost::signals::trackable {
211 Impl(PreviewLoader & p, Buffer const & b);
212 /// Stop any InProgress items still executing.
215 PreviewImage const * preview(string const & latex_snippet) const;
217 PreviewLoader::Status status(string const & latex_snippet) const;
219 void add(string const & latex_snippet);
221 void remove(string const & latex_snippet);
225 /// Emit this signal when an image is ready for display.
226 boost::signal<void(PreviewImage const &)> imageReady;
228 Buffer const & buffer() const { return buffer_; }
231 /// Called by the ForkedCall process that generated the bitmap files.
232 void finishedGenerating(pid_t, int);
234 void dumpPreamble(odocstream &) const;
236 void dumpData(odocstream &, BitmapFile const &) const;
238 /** cache_ allows easy retrieval of already-generated images
239 * using the LaTeX snippet as the identifier.
241 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
243 typedef map<string, PreviewImagePtr> Cache;
247 /** pending_ stores the LaTeX snippets in anticipation of them being
248 * sent to the converter.
250 PendingSnippets pending_;
252 /** in_progress_ stores all forked processes so that we can proceed
254 The map uses the conversion commands as its identifiers.
256 InProgressProcesses in_progress_;
259 PreviewLoader & parent_;
261 Buffer const & buffer_;
263 double font_scaling_factor_;
265 /// We don't own this
266 static lyx::Converter const * pconverter_;
270 lyx::Converter const * PreviewLoader::Impl::pconverter_;
274 // The public interface, defined in PreviewLoader.h
277 PreviewLoader::PreviewLoader(Buffer const & b)
278 : pimpl_(new Impl(*this, b))
282 PreviewLoader::~PreviewLoader()
288 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
290 return pimpl_->preview(latex_snippet);
294 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
296 return pimpl_->status(latex_snippet);
300 void PreviewLoader::add(string const & latex_snippet) const
302 pimpl_->add(latex_snippet);
306 void PreviewLoader::remove(string const & latex_snippet) const
308 pimpl_->remove(latex_snippet);
312 void PreviewLoader::startLoading() const
314 pimpl_->startLoading();
318 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
320 return pimpl_->imageReady.connect(slot);
324 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
326 pimpl_->imageReady(pimage);
330 Buffer const & PreviewLoader::buffer() const
332 return pimpl_->buffer();
335 } // namespace graphics
339 // The details of the Impl
340 // =======================
344 class IncrementedFileName {
346 IncrementedFileName(string const & to_format,
347 string const & filename_base)
348 : to_format_(to_format), base_(filename_base), counter_(1)
351 SnippetPair const operator()(string const & snippet)
354 os << base_ << counter_++ << '.' << to_format_;
355 string const file = os.str();
357 return make_pair(snippet, FileName(file));
361 string const & to_format_;
362 string const & base_;
367 InProgress::InProgress(string const & filename_base,
368 PendingSnippets const & pending,
369 string const & to_format)
371 metrics_file(FileName(filename_base + ".metrics")),
372 snippets(pending.size())
374 PendingSnippets::const_iterator pit = pending.begin();
375 PendingSnippets::const_iterator pend = pending.end();
376 BitmapFile::iterator sit = snippets.begin();
378 std::transform(pit, pend, sit,
379 IncrementedFileName(to_format, filename_base));
383 void InProgress::stop() const
386 lyx::support::ForkedCallsController::get().kill(pid, 0);
388 if (!metrics_file.empty())
389 metrics_file.removeFile();
391 BitmapFile::const_iterator vit = snippets.begin();
392 BitmapFile::const_iterator vend = snippets.end();
393 for (; vit != vend; ++vit) {
394 if (!vit->second.empty())
395 vit->second.removeFile();
405 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
406 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
408 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
409 convert<double>(lyxrc.preview_scale_factor);
411 LYXERR(Debug::GRAPHICS, "The font scaling factor is "
412 << font_scaling_factor_);
415 pconverter_ = setConverter();
419 PreviewLoader::Impl::~Impl()
421 InProgressProcesses::iterator ipit = in_progress_.begin();
422 InProgressProcesses::iterator ipend = in_progress_.end();
424 for (; ipit != ipend; ++ipit) {
431 PreviewLoader::Impl::preview(string const & latex_snippet) const
433 Cache::const_iterator it = cache_.find(latex_snippet);
434 return (it == cache_.end()) ? 0 : it->second.get();
440 class FindSnippet : public std::unary_function<InProgressProcess, bool> {
442 FindSnippet(string const & s) : snippet_(s) {}
443 bool operator()(InProgressProcess const & process) const
445 BitmapFile const & snippets = process.second.snippets;
446 BitmapFile::const_iterator beg = snippets.begin();
447 BitmapFile::const_iterator end = snippets.end();
448 return find_if(beg, end, FindFirst(snippet_)) != end;
452 string const snippet_;
457 PreviewLoader::Status
458 PreviewLoader::Impl::status(string const & latex_snippet) const
460 Cache::const_iterator cit = cache_.find(latex_snippet);
461 if (cit != cache_.end())
464 PendingSnippets::const_iterator pit = pending_.begin();
465 PendingSnippets::const_iterator pend = pending_.end();
467 pit = find(pit, pend, latex_snippet);
471 InProgressProcesses::const_iterator ipit = in_progress_.begin();
472 InProgressProcesses::const_iterator ipend = in_progress_.end();
474 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
482 void PreviewLoader::Impl::add(string const & latex_snippet)
484 if (!pconverter_ || status(latex_snippet) != NotFound)
487 string const snippet = support::trim(latex_snippet);
491 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
493 pending_.push_back(snippet);
501 EraseSnippet(string const & s) : snippet_(s) {}
502 void operator()(InProgressProcess & process)
504 BitmapFile & snippets = process.second.snippets;
505 BitmapFile::iterator it = snippets.begin();
506 BitmapFile::iterator end = snippets.end();
508 it = find_if(it, end, FindFirst(snippet_));
510 snippets.erase(it, it+1);
514 string const & snippet_;
520 void PreviewLoader::Impl::remove(string const & latex_snippet)
522 Cache::iterator cit = cache_.find(latex_snippet);
523 if (cit != cache_.end())
526 PendingSnippets::iterator pit = pending_.begin();
527 PendingSnippets::iterator pend = pending_.end();
529 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
531 InProgressProcesses::iterator ipit = in_progress_.begin();
532 InProgressProcesses::iterator ipend = in_progress_.end();
534 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
536 while (ipit != ipend) {
537 InProgressProcesses::iterator curr = ipit++;
538 if (curr->second.snippets.empty())
539 in_progress_.erase(curr);
544 void PreviewLoader::Impl::startLoading()
546 if (pending_.empty() || !pconverter_)
549 // Only start the process off after the buffer is loaded from file.
550 if (!buffer_.isFullyLoaded())
553 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
555 // As used by the LaTeX file and by the resulting image files
556 string const directory = buffer_.temppath();
558 string const filename_base = unique_filename(directory);
560 // Create an InProgress instance to place in the map of all
561 // such processes if it starts correctly.
562 InProgress inprogress(filename_base, pending_, pconverter_->to);
564 // clear pending_, so we're ready to start afresh.
567 // Output the LaTeX file.
568 FileName const latexfile(filename_base + ".tex");
570 // we use the encoding of the buffer
571 Encoding const & enc = buffer_.params().encoding();
572 odocfstream of(enc.iconvName());
574 OutputParams runparams(&enc);
575 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
577 if (!openFileWrite(of, latexfile))
581 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
582 << "Unable to create LaTeX file\n" << latexfile);
585 of << "\\batchmode\n";
587 // handle inputenc etc.
588 buffer_.params().writeEncodingPreamble(of, features, texrow);
589 of << "\n\\begin{document}\n";
590 dumpData(of, inprogress.snippets);
591 of << "\n\\end{document}\n";
594 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
595 << "File was not closed properly.");
599 // The conversion command.
601 cs << pconverter_->command << ' ' << pconverter_->to << ' '
602 << support::quoteName(latexfile.toFilesystemEncoding()) << ' '
603 << int(font_scaling_factor_) << ' '
604 << theApp()->hexName(Color_preview) << ' '
605 << theApp()->hexName(Color_background);
607 string const command = support::libScriptSearch(cs.str());
609 // Initiate the conversion from LaTeX to bitmap images files.
610 support::ForkedCall::SignalTypePtr
611 convert_ptr(new support::ForkedCall::SignalType);
612 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
614 support::ForkedCall call;
615 int ret = call.startScript(command, convert_ptr);
618 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
619 << "Unable to start process\n" << command);
623 // Store the generation process in a list of all such processes
624 inprogress.pid = call.pid();
625 inprogress.command = command;
626 in_progress_[inprogress.pid] = inprogress;
630 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
633 InProgressProcesses::iterator git = in_progress_.find(pid);
634 if (git == in_progress_.end()) {
635 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
636 "data for PID " << pid << endl;
640 string const command = git->second.command;
641 string const status = retval > 0 ? "failed" : "succeeded";
642 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
643 << retval << "): processing " << status
644 << " for " << command);
648 // Read the metrics file, if it exists
649 vector<double> ascent_fractions(git->second.snippets.size());
650 setAscentFractions(ascent_fractions, git->second.metrics_file);
652 // Add these newly generated bitmap files to the cache and
653 // start loading them into LyX.
654 BitmapFile::const_iterator it = git->second.snippets.begin();
655 BitmapFile::const_iterator end = git->second.snippets.end();
657 std::list<PreviewImagePtr> newimages;
659 int metrics_counter = 0;
660 for (; it != end; ++it, ++metrics_counter) {
661 string const & snip = it->first;
662 FileName const & file = it->second;
663 double af = ascent_fractions[metrics_counter];
665 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
668 newimages.push_back(ptr);
671 // Remove the item from the list of still-executing processes.
672 in_progress_.erase(git);
674 // Tell the outside world
675 std::list<PreviewImagePtr>::const_reverse_iterator
676 nit = newimages.rbegin();
677 std::list<PreviewImagePtr>::const_reverse_iterator
678 nend = newimages.rend();
679 for (; nit != nend; ++nit) {
680 imageReady(*nit->get());
685 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
687 // Why on earth is Buffer::makeLaTeXFile a non-const method?
688 Buffer & tmp = const_cast<Buffer &>(buffer_);
689 // Dump the preamble only.
690 // We don't need an encoding for runparams since it is not used by
692 OutputParams runparams(0);
693 runparams.flavor = OutputParams::LATEX;
694 runparams.nice = true;
695 runparams.moving_arg = true;
696 runparams.free_spacing = true;
697 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
699 // FIXME! This is a HACK! The proper fix is to control the 'true'
700 // passed to WriteStream below:
701 // int InsetMathNest::latex(Buffer const &, odocstream & os,
702 // OutputParams const & runparams) const
704 // WriteStream wi(os, runparams.moving_arg, true);
709 << "\\def\\lyxlock{}\n"
712 // Loop over the insets in the buffer and dump all the math-macros.
713 Inset & inset = buffer_.inset();
714 InsetIterator it = inset_iterator_begin(inset);
715 InsetIterator const end = inset_iterator_end(inset);
717 for (; it != end; ++it)
718 if (it->lyxCode() == MATHMACRO_CODE)
719 it->latex(buffer_, os, runparams);
721 // All equation labels appear as "(#)" + preview.sty's rendering of
723 if (lyxrc.preview_hashed_labels)
724 os << "\\renewcommand{\\theequation}{\\#}\n";
726 // Use the preview style file to ensure that each snippet appears on a
729 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
734 void PreviewLoader::Impl::dumpData(odocstream & os,
735 BitmapFile const & vec) const
740 BitmapFile::const_iterator it = vec.begin();
741 BitmapFile::const_iterator end = vec.end();
743 for (; it != end; ++it) {
745 os << "\\begin{preview}\n"
746 << from_utf8(it->first)
747 << "\n\\end{preview}\n\n";
751 } // namespace graphics