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/FileName.h"
36 #include "support/filetools.h"
37 #include "support/ForkedCalls.h"
38 #include "support/lstrings.h"
40 #include <boost/bind.hpp>
47 using namespace lyx::support;
53 typedef pair<string, FileName> SnippetPair;
55 // A list of all snippets to be converted to previews
56 typedef list<string> PendingSnippets;
58 // Each item in the vector is a pair<snippet, image file name>.
59 typedef vector<SnippetPair> BitmapFile;
62 string const unique_filename(string const & bufferpath)
64 static int theCounter = 0;
65 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
66 return addName(bufferpath, filename);
70 lyx::Converter const * setConverter()
72 string const from = "lyxpreview";
74 typedef vector<string> FmtList;
75 typedef lyx::graphics::Cache GCache;
76 FmtList const loadableFormats = GCache::get().loadableFormats();
77 FmtList::const_iterator it = loadableFormats.begin();
78 FmtList::const_iterator const end = loadableFormats.end();
80 for (; it != end; ++it) {
81 string const to = *it;
85 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
90 static bool first = true;
93 LYXERR0("PreviewLoader::startLoading()\n"
94 << "No converter from \"lyxpreview\" format has been defined.");
100 void setAscentFractions(vector<double> & ascent_fractions,
101 FileName const & metrics_file)
103 // If all else fails, then the images will have equal ascents and
105 vector<double>::iterator it = ascent_fractions.begin();
106 vector<double>::iterator end = ascent_fractions.end();
109 ifstream in(metrics_file.toFilesystemEncoding().c_str());
111 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
112 << "Unable to open file!");
118 int snippet_counter = 1;
119 while (!in.eof() && it != end) {
122 double ascent_fraction;
124 in >> snippet >> id >> ascent_fraction;
130 error = snippet != "Snippet";
134 error = id != snippet_counter;
138 *it = ascent_fraction;
145 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
146 << "Error reading file!\n");
154 FindFirst(string const & comp) : comp_(comp) {}
155 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
161 /// Store info on a currently executing, forked process.
165 InProgress() : pid(0) {}
167 InProgress(string const & filename_base,
168 PendingSnippets const & pending,
169 string const & to_format);
170 /// Remove any files left lying around and kill the forked process.
178 FileName metrics_file;
183 typedef map<pid_t, InProgress> InProgressProcesses;
185 typedef InProgressProcesses::value_type InProgressProcess;
194 class PreviewLoader::Impl : public boost::signals::trackable {
197 Impl(PreviewLoader & p, Buffer const & b);
198 /// Stop any InProgress items still executing.
201 PreviewImage const * preview(string const & latex_snippet) const;
203 PreviewLoader::Status status(string const & latex_snippet) const;
205 void add(string const & latex_snippet);
207 void remove(string const & latex_snippet);
211 /// Emit this signal when an image is ready for display.
212 boost::signal<void(PreviewImage const &)> imageReady;
214 Buffer const & buffer() const { return buffer_; }
217 /// Called by the ForkedCall process that generated the bitmap files.
218 void finishedGenerating(pid_t, int);
220 void dumpPreamble(odocstream &) const;
222 void dumpData(odocstream &, BitmapFile const &) const;
224 /** cache_ allows easy retrieval of already-generated images
225 * using the LaTeX snippet as the identifier.
227 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
229 typedef map<string, PreviewImagePtr> Cache;
233 /** pending_ stores the LaTeX snippets in anticipation of them being
234 * sent to the converter.
236 PendingSnippets pending_;
238 /** in_progress_ stores all forked processes so that we can proceed
240 The map uses the conversion commands as its identifiers.
242 InProgressProcesses in_progress_;
245 PreviewLoader & parent_;
247 Buffer const & buffer_;
249 double font_scaling_factor_;
251 /// We don't own this
252 static lyx::Converter const * pconverter_;
256 lyx::Converter const * PreviewLoader::Impl::pconverter_;
260 // The public interface, defined in PreviewLoader.h
263 PreviewLoader::PreviewLoader(Buffer const & b)
264 : pimpl_(new Impl(*this, b))
268 PreviewLoader::~PreviewLoader()
274 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
276 return pimpl_->preview(latex_snippet);
280 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
282 return pimpl_->status(latex_snippet);
286 void PreviewLoader::add(string const & latex_snippet) const
288 pimpl_->add(latex_snippet);
292 void PreviewLoader::remove(string const & latex_snippet) const
294 pimpl_->remove(latex_snippet);
298 void PreviewLoader::startLoading() const
300 pimpl_->startLoading();
304 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
306 return pimpl_->imageReady.connect(slot);
310 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
312 pimpl_->imageReady(pimage);
316 Buffer const & PreviewLoader::buffer() const
318 return pimpl_->buffer();
321 } // namespace graphics
325 // The details of the Impl
326 // =======================
330 class IncrementedFileName {
332 IncrementedFileName(string const & to_format,
333 string const & filename_base)
334 : to_format_(to_format), base_(filename_base), counter_(1)
337 SnippetPair const operator()(string const & snippet)
340 os << base_ << counter_++ << '.' << to_format_;
341 string const file = os.str();
343 return make_pair(snippet, FileName(file));
347 string const & to_format_;
348 string const & base_;
353 InProgress::InProgress(string const & filename_base,
354 PendingSnippets const & pending,
355 string const & to_format)
357 metrics_file(FileName(filename_base + ".metrics")),
358 snippets(pending.size())
360 PendingSnippets::const_iterator pit = pending.begin();
361 PendingSnippets::const_iterator pend = pending.end();
362 BitmapFile::iterator sit = snippets.begin();
364 transform(pit, pend, sit,
365 IncrementedFileName(to_format, filename_base));
369 void InProgress::stop() const
372 ForkedCallsController::kill(pid, 0);
374 if (!metrics_file.empty())
375 metrics_file.removeFile();
377 BitmapFile::const_iterator vit = snippets.begin();
378 BitmapFile::const_iterator vend = snippets.end();
379 for (; vit != vend; ++vit) {
380 if (!vit->second.empty())
381 vit->second.removeFile();
391 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
392 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
394 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
395 convert<double>(lyxrc.preview_scale_factor);
397 LYXERR(Debug::GRAPHICS, "The font scaling factor is "
398 << font_scaling_factor_);
401 pconverter_ = setConverter();
405 PreviewLoader::Impl::~Impl()
407 InProgressProcesses::iterator ipit = in_progress_.begin();
408 InProgressProcesses::iterator ipend = in_progress_.end();
410 for (; ipit != ipend; ++ipit)
416 PreviewLoader::Impl::preview(string const & latex_snippet) const
418 Cache::const_iterator it = cache_.find(latex_snippet);
419 return (it == cache_.end()) ? 0 : it->second.get();
427 FindSnippet(string const & s) : snippet_(s) {}
428 bool operator()(InProgressProcess const & process) const
430 BitmapFile const & snippets = process.second.snippets;
431 BitmapFile::const_iterator beg = snippets.begin();
432 BitmapFile::const_iterator end = snippets.end();
433 return find_if(beg, end, FindFirst(snippet_)) != end;
437 string const snippet_;
442 PreviewLoader::Status
443 PreviewLoader::Impl::status(string const & latex_snippet) const
445 Cache::const_iterator cit = cache_.find(latex_snippet);
446 if (cit != cache_.end())
449 PendingSnippets::const_iterator pit = pending_.begin();
450 PendingSnippets::const_iterator pend = pending_.end();
452 pit = find(pit, pend, latex_snippet);
456 InProgressProcesses::const_iterator ipit = in_progress_.begin();
457 InProgressProcesses::const_iterator ipend = in_progress_.end();
459 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
467 void PreviewLoader::Impl::add(string const & latex_snippet)
469 if (!pconverter_ || status(latex_snippet) != NotFound)
472 string const snippet = trim(latex_snippet);
476 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
478 pending_.push_back(snippet);
486 EraseSnippet(string const & s) : snippet_(s) {}
487 void operator()(InProgressProcess & process)
489 BitmapFile & snippets = process.second.snippets;
490 BitmapFile::iterator it = snippets.begin();
491 BitmapFile::iterator end = snippets.end();
493 it = find_if(it, end, FindFirst(snippet_));
495 snippets.erase(it, it+1);
499 string const & snippet_;
505 void PreviewLoader::Impl::remove(string const & latex_snippet)
507 Cache::iterator cit = cache_.find(latex_snippet);
508 if (cit != cache_.end())
511 PendingSnippets::iterator pit = pending_.begin();
512 PendingSnippets::iterator pend = pending_.end();
514 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
516 InProgressProcesses::iterator ipit = in_progress_.begin();
517 InProgressProcesses::iterator ipend = in_progress_.end();
519 for_each(ipit, ipend, EraseSnippet(latex_snippet));
521 while (ipit != ipend) {
522 InProgressProcesses::iterator curr = ipit++;
523 if (curr->second.snippets.empty())
524 in_progress_.erase(curr);
529 void PreviewLoader::Impl::startLoading()
531 if (pending_.empty() || !pconverter_)
534 // Only start the process off after the buffer is loaded from file.
535 if (!buffer_.isFullyLoaded())
538 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
540 // As used by the LaTeX file and by the resulting image files
541 string const directory = buffer_.temppath();
543 string const filename_base = unique_filename(directory);
545 // Create an InProgress instance to place in the map of all
546 // such processes if it starts correctly.
547 InProgress inprogress(filename_base, pending_, pconverter_->to);
549 // clear pending_, so we're ready to start afresh.
552 // Output the LaTeX file.
553 FileName const latexfile(filename_base + ".tex");
555 // we use the encoding of the buffer
556 Encoding const & enc = buffer_.params().encoding();
558 try { of.reset(enc.iconvName()); }
559 catch (iconv_codecvt_facet_exception & e) {
560 LYXERR0("Caught iconv exception: " << e.what()
561 << "\nUnable to create LaTeX file: " << latexfile);
566 OutputParams runparams(&enc);
567 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
569 if (!openFileWrite(of, latexfile))
573 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
574 << "Unable to create LaTeX file\n" << latexfile);
577 of << "\\batchmode\n";
579 // handle inputenc etc.
580 buffer_.params().writeEncodingPreamble(of, features, texrow);
581 of << "\n\\begin{document}\n";
582 dumpData(of, inprogress.snippets);
583 of << "\n\\end{document}\n";
586 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
587 << "File was not closed properly.");
591 // The conversion command.
593 cs << pconverter_->command << ' ' << pconverter_->to << ' '
594 << quoteName(latexfile.toFilesystemEncoding()) << ' '
595 << int(font_scaling_factor_) << ' '
596 << theApp()->hexName(Color_preview) << ' '
597 << theApp()->hexName(Color_background);
599 string const command = libScriptSearch(cs.str());
601 // Initiate the conversion from LaTeX to bitmap images files.
602 ForkedCall::SignalTypePtr
603 convert_ptr(new ForkedCall::SignalType);
604 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
607 int ret = call.startScript(command, convert_ptr);
610 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
611 << "Unable to start process\n" << command);
615 // Store the generation process in a list of all such processes
616 inprogress.pid = call.pid();
617 inprogress.command = command;
618 in_progress_[inprogress.pid] = inprogress;
622 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
625 InProgressProcesses::iterator git = in_progress_.find(pid);
626 if (git == in_progress_.end()) {
627 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
628 "data for PID " << pid << endl;
632 string const command = git->second.command;
633 string const status = retval > 0 ? "failed" : "succeeded";
634 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
635 << retval << "): processing " << status
636 << " for " << command);
640 // Read the metrics file, if it exists
641 vector<double> ascent_fractions(git->second.snippets.size());
642 setAscentFractions(ascent_fractions, git->second.metrics_file);
644 // Add these newly generated bitmap files to the cache and
645 // start loading them into LyX.
646 BitmapFile::const_iterator it = git->second.snippets.begin();
647 BitmapFile::const_iterator end = git->second.snippets.end();
649 list<PreviewImagePtr> newimages;
651 int metrics_counter = 0;
652 for (; it != end; ++it, ++metrics_counter) {
653 string const & snip = it->first;
654 FileName const & file = it->second;
655 double af = ascent_fractions[metrics_counter];
657 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
660 newimages.push_back(ptr);
663 // Remove the item from the list of still-executing processes.
664 in_progress_.erase(git);
666 // Tell the outside world
667 list<PreviewImagePtr>::const_reverse_iterator
668 nit = newimages.rbegin();
669 list<PreviewImagePtr>::const_reverse_iterator
670 nend = newimages.rend();
671 for (; nit != nend; ++nit) {
672 imageReady(*nit->get());
677 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
679 // Why on earth is Buffer::makeLaTeXFile a non-const method?
680 Buffer & tmp = const_cast<Buffer &>(buffer_);
681 // Dump the preamble only.
682 // We don't need an encoding for runparams since it is not used by
684 OutputParams runparams(0);
685 runparams.flavor = OutputParams::LATEX;
686 runparams.nice = true;
687 runparams.moving_arg = true;
688 runparams.free_spacing = true;
689 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
691 // FIXME! This is a HACK! The proper fix is to control the 'true'
692 // passed to WriteStream below:
693 // int InsetMathNest::latex(Buffer const &, odocstream & os,
694 // OutputParams const & runparams) const
696 // WriteStream wi(os, runparams.moving_arg, true);
701 << "\\def\\lyxlock{}\n"
704 // Loop over the insets in the buffer and dump all the math-macros.
705 Inset & inset = buffer_.inset();
706 InsetIterator it = inset_iterator_begin(inset);
707 InsetIterator const end = inset_iterator_end(inset);
709 for (; it != end; ++it)
710 if (it->lyxCode() == MATHMACRO_CODE)
711 it->latex(os, runparams);
713 // All equation labels appear as "(#)" + preview.sty's rendering of
715 if (lyxrc.preview_hashed_labels)
716 os << "\\renewcommand{\\theequation}{\\#}\n";
718 // Use the preview style file to ensure that each snippet appears on a
721 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
726 void PreviewLoader::Impl::dumpData(odocstream & os,
727 BitmapFile const & vec) const
732 BitmapFile::const_iterator it = vec.begin();
733 BitmapFile::const_iterator end = vec.end();
735 for (; it != end; ++it) {
737 os << "\\begin{preview}\n"
738 << from_utf8(it->first)
739 << "\n\\end{preview}\n\n";
743 } // namespace graphics