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;
216 class PreviewLoader::Impl : public boost::signals::trackable {
219 Impl(PreviewLoader & p, Buffer const & b);
220 /// Stop any InProgress items still executing.
223 PreviewImage const * preview(string const & latex_snippet) const;
225 PreviewLoader::Status status(string const & latex_snippet) const;
227 void add(string const & latex_snippet);
229 void remove(string const & latex_snippet);
233 /// Emit this signal when an image is ready for display.
234 boost::signal<void(PreviewImage const &)> imageReady;
236 Buffer const & buffer() const { return buffer_; }
239 /// Called by the Forkedcall process that generated the bitmap files.
240 void finishedGenerating(pid_t, int);
242 void dumpPreamble(odocstream &) const;
244 void dumpData(odocstream &, BitmapFile const &) const;
246 /** cache_ allows easy retrieval of already-generated images
247 * using the LaTeX snippet as the identifier.
249 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
251 typedef map<string, PreviewImagePtr> Cache;
255 /** pending_ stores the LaTeX snippets in anticipation of them being
256 * sent to the converter.
258 PendingSnippets pending_;
260 /** in_progress_ stores all forked processes so that we can proceed
262 The map uses the conversion commands as its identifiers.
264 InProgressProcesses in_progress_;
267 PreviewLoader & parent_;
269 Buffer const & buffer_;
271 double font_scaling_factor_;
273 /// We don't own this
274 static lyx::Converter const * pconverter_;
278 lyx::Converter const * PreviewLoader::Impl::pconverter_;
282 // The public interface, defined in PreviewLoader.h
285 PreviewLoader::PreviewLoader(Buffer const & b)
286 : pimpl_(new Impl(*this, b))
290 PreviewLoader::~PreviewLoader()
294 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
296 return pimpl_->preview(latex_snippet);
300 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
302 return pimpl_->status(latex_snippet);
306 void PreviewLoader::add(string const & latex_snippet) const
308 pimpl_->add(latex_snippet);
312 void PreviewLoader::remove(string const & latex_snippet) const
314 pimpl_->remove(latex_snippet);
318 void PreviewLoader::startLoading() const
320 pimpl_->startLoading();
324 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
326 return pimpl_->imageReady.connect(slot);
330 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
332 pimpl_->imageReady(pimage);
336 Buffer const & PreviewLoader::buffer() const
338 return pimpl_->buffer();
341 } // namespace graphics
345 // The details of the Impl
346 // =======================
350 class IncrementedFileName {
352 IncrementedFileName(string const & to_format,
353 string const & filename_base)
354 : to_format_(to_format), base_(filename_base), counter_(1)
357 SnippetPair const operator()(string const & snippet)
360 os << base_ << counter_++ << '.' << to_format_;
361 string const file = os.str();
363 return make_pair(snippet, FileName(file));
367 string const & to_format_;
368 string const & base_;
373 InProgress::InProgress(string const & filename_base,
374 PendingSnippets const & pending,
375 string const & to_format)
377 metrics_file(FileName(filename_base + ".metrics")),
378 snippets(pending.size())
380 PendingSnippets::const_iterator pit = pending.begin();
381 PendingSnippets::const_iterator pend = pending.end();
382 BitmapFile::iterator sit = snippets.begin();
384 std::transform(pit, pend, sit,
385 IncrementedFileName(to_format, filename_base));
389 void InProgress::stop() const
392 lyx::support::ForkedcallsController::get().kill(pid, 0);
394 if (!metrics_file.empty())
395 lyx::support::unlink(metrics_file);
397 BitmapFile::const_iterator vit = snippets.begin();
398 BitmapFile::const_iterator vend = snippets.end();
399 for (; vit != vend; ++vit) {
400 if (!vit->second.empty())
401 lyx::support::unlink(vit->second);
411 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
412 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
414 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
415 convert<double>(lyxrc.preview_scale_factor);
417 LYXERR(Debug::GRAPHICS) << "The font scaling factor is "
418 << font_scaling_factor_ << endl;
421 pconverter_ = setConverter();
425 PreviewLoader::Impl::~Impl()
427 InProgressProcesses::iterator ipit = in_progress_.begin();
428 InProgressProcesses::iterator ipend = in_progress_.end();
430 for (; ipit != ipend; ++ipit) {
437 PreviewLoader::Impl::preview(string const & latex_snippet) const
439 Cache::const_iterator it = cache_.find(latex_snippet);
440 return (it == cache_.end()) ? 0 : it->second.get();
446 class FindSnippet : public std::unary_function<InProgressProcess, bool> {
448 FindSnippet(string const & s) : snippet_(s) {}
449 bool operator()(InProgressProcess const & process) const
451 BitmapFile const & snippets = process.second.snippets;
452 BitmapFile::const_iterator beg = snippets.begin();
453 BitmapFile::const_iterator end = snippets.end();
454 return find_if(beg, end, FindFirst(snippet_)) != end;
458 string const snippet_;
463 PreviewLoader::Status
464 PreviewLoader::Impl::status(string const & latex_snippet) const
466 Cache::const_iterator cit = cache_.find(latex_snippet);
467 if (cit != cache_.end())
470 PendingSnippets::const_iterator pit = pending_.begin();
471 PendingSnippets::const_iterator pend = pending_.end();
473 pit = find(pit, pend, latex_snippet);
477 InProgressProcesses::const_iterator ipit = in_progress_.begin();
478 InProgressProcesses::const_iterator ipend = in_progress_.end();
480 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
488 void PreviewLoader::Impl::add(string const & latex_snippet)
490 if (!pconverter_ || status(latex_snippet) != NotFound)
493 string const snippet = support::trim(latex_snippet);
497 LYXERR(Debug::GRAPHICS) << "adding snippet:\n" << snippet << endl;
499 pending_.push_back(snippet);
507 EraseSnippet(string const & s) : snippet_(s) {}
508 void operator()(InProgressProcess & process)
510 BitmapFile & snippets = process.second.snippets;
511 BitmapFile::iterator it = snippets.begin();
512 BitmapFile::iterator end = snippets.end();
514 it = find_if(it, end, FindFirst(snippet_));
516 snippets.erase(it, it+1);
520 string const & snippet_;
526 void PreviewLoader::Impl::remove(string const & latex_snippet)
528 Cache::iterator cit = cache_.find(latex_snippet);
529 if (cit != cache_.end())
532 PendingSnippets::iterator pit = pending_.begin();
533 PendingSnippets::iterator pend = pending_.end();
535 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
537 InProgressProcesses::iterator ipit = in_progress_.begin();
538 InProgressProcesses::iterator ipend = in_progress_.end();
540 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
542 while (ipit != ipend) {
543 InProgressProcesses::iterator curr = ipit++;
544 if (curr->second.snippets.empty())
545 in_progress_.erase(curr);
550 void PreviewLoader::Impl::startLoading()
552 if (pending_.empty() || !pconverter_)
555 // Only start the process off after the buffer is loaded from file.
556 if (!buffer_.isFullyLoaded())
559 LYXERR(Debug::GRAPHICS) << "PreviewLoader::startLoading()" << endl;
561 // As used by the LaTeX file and by the resulting image files
562 string const directory = buffer_.temppath();
564 string const filename_base = unique_filename(directory);
566 // Create an InProgress instance to place in the map of all
567 // such processes if it starts correctly.
568 InProgress inprogress(filename_base, pending_, pconverter_->to);
570 // clear pending_, so we're ready to start afresh.
573 // Output the LaTeX file.
574 FileName const latexfile(filename_base + ".tex");
576 // we use the encoding of the buffer
577 Encoding const & enc = buffer_.params().encoding();
578 odocfstream of(enc.iconvName());
580 OutputParams runparams(&enc);
581 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
583 if (!openFileWrite(of, latexfile))
587 LYXERR(Debug::GRAPHICS) << "PreviewLoader::startLoading()\n"
588 << "Unable to create LaTeX file\n"
589 << latexfile << endl;
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."
607 // The conversion command.
609 cs << pconverter_->command << ' ' << pconverter_->to << ' '
610 << support::quoteName(latexfile.toFilesystemEncoding()) << ' '
611 << int(font_scaling_factor_) << ' '
612 << theApp()->hexName(Color_preview) << ' '
613 << theApp()->hexName(Color_background);
615 string const command = support::libScriptSearch(cs.str());
617 // Initiate the conversion from LaTeX to bitmap images files.
618 support::Forkedcall::SignalTypePtr
619 convert_ptr(new support::Forkedcall::SignalType);
620 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
622 support::Forkedcall call;
623 int ret = call.startscript(command, convert_ptr);
626 LYXERR(Debug::GRAPHICS) << "PreviewLoader::startLoading()\n"
627 << "Unable to start process\n"
632 // Store the generation process in a list of all such processes
633 inprogress.pid = call.pid();
634 inprogress.command = command;
635 in_progress_[inprogress.pid] = inprogress;
639 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
642 InProgressProcesses::iterator git = in_progress_.find(pid);
643 if (git == in_progress_.end()) {
644 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
645 "data for PID " << pid << endl;
649 string const command = git->second.command;
650 string const status = retval > 0 ? "failed" : "succeeded";
651 LYXERR(Debug::GRAPHICS) << "PreviewLoader::finishedInProgress("
652 << retval << "): processing " << status
653 << " for " << command << endl;
657 // Read the metrics file, if it exists
658 vector<double> ascent_fractions(git->second.snippets.size());
659 setAscentFractions(ascent_fractions, git->second.metrics_file);
661 // Add these newly generated bitmap files to the cache and
662 // start loading them into LyX.
663 BitmapFile::const_iterator it = git->second.snippets.begin();
664 BitmapFile::const_iterator end = git->second.snippets.end();
666 std::list<PreviewImagePtr> newimages;
668 int metrics_counter = 0;
669 for (; it != end; ++it, ++metrics_counter) {
670 string const & snip = it->first;
671 FileName const & file = it->second;
672 double af = ascent_fractions[metrics_counter];
674 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
677 newimages.push_back(ptr);
680 // Remove the item from the list of still-executing processes.
681 in_progress_.erase(git);
683 // Tell the outside world
684 std::list<PreviewImagePtr>::const_reverse_iterator
685 nit = newimages.rbegin();
686 std::list<PreviewImagePtr>::const_reverse_iterator
687 nend = newimages.rend();
688 for (; nit != nend; ++nit) {
689 imageReady(*nit->get());
694 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
696 // Why on earth is Buffer::makeLaTeXFile a non-const method?
697 Buffer & tmp = const_cast<Buffer &>(buffer_);
698 // Dump the preamble only.
699 // We don't need an encoding for runparams since it is not used by
701 OutputParams runparams(0);
702 runparams.flavor = OutputParams::LATEX;
703 runparams.nice = true;
704 runparams.moving_arg = true;
705 runparams.free_spacing = true;
706 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
708 // FIXME! This is a HACK! The proper fix is to control the 'true'
709 // passed to WriteStream below:
710 // int InsetMathNest::latex(Buffer const &, odocstream & os,
711 // OutputParams const & runparams) const
713 // WriteStream wi(os, runparams.moving_arg, true);
718 << "\\def\\lyxlock{}\n"
721 // Loop over the insets in the buffer and dump all the math-macros.
722 Inset & inset = buffer_.inset();
723 InsetIterator it = inset_iterator_begin(inset);
724 InsetIterator const end = inset_iterator_end(inset);
726 for (; it != end; ++it)
727 if (it->lyxCode() == MATHMACRO_CODE)
728 it->latex(buffer_, os, runparams);
730 // All equation labels appear as "(#)" + preview.sty's rendering of
732 if (lyxrc.preview_hashed_labels)
733 os << "\\renewcommand{\\theequation}{\\#}\n";
735 // Use the preview style file to ensure that each snippet appears on a
738 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
743 void PreviewLoader::Impl::dumpData(odocstream & os,
744 BitmapFile const & vec) const
749 BitmapFile::const_iterator it = vec.begin();
750 BitmapFile::const_iterator end = vec.end();
752 for (; it != end; ++it) {
754 os << "\\begin{preview}\n"
755 << from_utf8(it->first)
756 << "\n\\end{preview}\n\n";
760 } // namespace graphics