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::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)
430 PreviewLoader::Impl::preview(string const & latex_snippet) const
432 Cache::const_iterator it = cache_.find(latex_snippet);
433 return (it == cache_.end()) ? 0 : it->second.get();
441 FindSnippet(string const & s) : snippet_(s) {}
442 bool operator()(InProgressProcess const & process) const
444 BitmapFile const & snippets = process.second.snippets;
445 BitmapFile::const_iterator beg = snippets.begin();
446 BitmapFile::const_iterator end = snippets.end();
447 return find_if(beg, end, FindFirst(snippet_)) != end;
451 string const snippet_;
456 PreviewLoader::Status
457 PreviewLoader::Impl::status(string const & latex_snippet) const
459 Cache::const_iterator cit = cache_.find(latex_snippet);
460 if (cit != cache_.end())
463 PendingSnippets::const_iterator pit = pending_.begin();
464 PendingSnippets::const_iterator pend = pending_.end();
466 pit = find(pit, pend, latex_snippet);
470 InProgressProcesses::const_iterator ipit = in_progress_.begin();
471 InProgressProcesses::const_iterator ipend = in_progress_.end();
473 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
481 void PreviewLoader::Impl::add(string const & latex_snippet)
483 if (!pconverter_ || status(latex_snippet) != NotFound)
486 string const snippet = support::trim(latex_snippet);
490 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
492 pending_.push_back(snippet);
500 EraseSnippet(string const & s) : snippet_(s) {}
501 void operator()(InProgressProcess & process)
503 BitmapFile & snippets = process.second.snippets;
504 BitmapFile::iterator it = snippets.begin();
505 BitmapFile::iterator end = snippets.end();
507 it = find_if(it, end, FindFirst(snippet_));
509 snippets.erase(it, it+1);
513 string const & snippet_;
519 void PreviewLoader::Impl::remove(string const & latex_snippet)
521 Cache::iterator cit = cache_.find(latex_snippet);
522 if (cit != cache_.end())
525 PendingSnippets::iterator pit = pending_.begin();
526 PendingSnippets::iterator pend = pending_.end();
528 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
530 InProgressProcesses::iterator ipit = in_progress_.begin();
531 InProgressProcesses::iterator ipend = in_progress_.end();
533 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
535 while (ipit != ipend) {
536 InProgressProcesses::iterator curr = ipit++;
537 if (curr->second.snippets.empty())
538 in_progress_.erase(curr);
543 void PreviewLoader::Impl::startLoading()
545 if (pending_.empty() || !pconverter_)
548 // Only start the process off after the buffer is loaded from file.
549 if (!buffer_.isFullyLoaded())
552 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
554 // As used by the LaTeX file and by the resulting image files
555 string const directory = buffer_.temppath();
557 string const filename_base = unique_filename(directory);
559 // Create an InProgress instance to place in the map of all
560 // such processes if it starts correctly.
561 InProgress inprogress(filename_base, pending_, pconverter_->to);
563 // clear pending_, so we're ready to start afresh.
566 // Output the LaTeX file.
567 FileName const latexfile(filename_base + ".tex");
569 // we use the encoding of the buffer
570 Encoding const & enc = buffer_.params().encoding();
571 odocfstream of(enc.iconvName());
573 OutputParams runparams(&enc);
574 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
576 if (!openFileWrite(of, latexfile))
580 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
581 << "Unable to create LaTeX file\n" << latexfile);
584 of << "\\batchmode\n";
586 // handle inputenc etc.
587 buffer_.params().writeEncodingPreamble(of, features, texrow);
588 of << "\n\\begin{document}\n";
589 dumpData(of, inprogress.snippets);
590 of << "\n\\end{document}\n";
593 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
594 << "File was not closed properly.");
598 // The conversion command.
600 cs << pconverter_->command << ' ' << pconverter_->to << ' '
601 << support::quoteName(latexfile.toFilesystemEncoding()) << ' '
602 << int(font_scaling_factor_) << ' '
603 << theApp()->hexName(Color_preview) << ' '
604 << theApp()->hexName(Color_background);
606 string const command = support::libScriptSearch(cs.str());
608 // Initiate the conversion from LaTeX to bitmap images files.
609 support::ForkedCall::SignalTypePtr
610 convert_ptr(new support::ForkedCall::SignalType);
611 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
613 support::ForkedCall call;
614 int ret = call.startScript(command, convert_ptr);
617 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
618 << "Unable to start process\n" << command);
622 // Store the generation process in a list of all such processes
623 inprogress.pid = call.pid();
624 inprogress.command = command;
625 in_progress_[inprogress.pid] = inprogress;
629 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
632 InProgressProcesses::iterator git = in_progress_.find(pid);
633 if (git == in_progress_.end()) {
634 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
635 "data for PID " << pid << endl;
639 string const command = git->second.command;
640 string const status = retval > 0 ? "failed" : "succeeded";
641 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
642 << retval << "): processing " << status
643 << " for " << command);
647 // Read the metrics file, if it exists
648 vector<double> ascent_fractions(git->second.snippets.size());
649 setAscentFractions(ascent_fractions, git->second.metrics_file);
651 // Add these newly generated bitmap files to the cache and
652 // start loading them into LyX.
653 BitmapFile::const_iterator it = git->second.snippets.begin();
654 BitmapFile::const_iterator end = git->second.snippets.end();
656 std::list<PreviewImagePtr> newimages;
658 int metrics_counter = 0;
659 for (; it != end; ++it, ++metrics_counter) {
660 string const & snip = it->first;
661 FileName const & file = it->second;
662 double af = ascent_fractions[metrics_counter];
664 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
667 newimages.push_back(ptr);
670 // Remove the item from the list of still-executing processes.
671 in_progress_.erase(git);
673 // Tell the outside world
674 std::list<PreviewImagePtr>::const_reverse_iterator
675 nit = newimages.rbegin();
676 std::list<PreviewImagePtr>::const_reverse_iterator
677 nend = newimages.rend();
678 for (; nit != nend; ++nit) {
679 imageReady(*nit->get());
684 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
686 // Why on earth is Buffer::makeLaTeXFile a non-const method?
687 Buffer & tmp = const_cast<Buffer &>(buffer_);
688 // Dump the preamble only.
689 // We don't need an encoding for runparams since it is not used by
691 OutputParams runparams(0);
692 runparams.flavor = OutputParams::LATEX;
693 runparams.nice = true;
694 runparams.moving_arg = true;
695 runparams.free_spacing = true;
696 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
698 // FIXME! This is a HACK! The proper fix is to control the 'true'
699 // passed to WriteStream below:
700 // int InsetMathNest::latex(Buffer const &, odocstream & os,
701 // OutputParams const & runparams) const
703 // WriteStream wi(os, runparams.moving_arg, true);
708 << "\\def\\lyxlock{}\n"
711 // Loop over the insets in the buffer and dump all the math-macros.
712 Inset & inset = buffer_.inset();
713 InsetIterator it = inset_iterator_begin(inset);
714 InsetIterator const end = inset_iterator_end(inset);
716 for (; it != end; ++it)
717 if (it->lyxCode() == MATHMACRO_CODE)
718 it->latex(buffer_, os, runparams);
720 // All equation labels appear as "(#)" + preview.sty's rendering of
722 if (lyxrc.preview_hashed_labels)
723 os << "\\renewcommand{\\theequation}{\\#}\n";
725 // Use the preview style file to ensure that each snippet appears on a
728 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
733 void PreviewLoader::Impl::dumpData(odocstream & os,
734 BitmapFile const & vec) const
739 BitmapFile::const_iterator it = vec.begin();
740 BitmapFile::const_iterator end = vec.end();
742 for (; it != end; ++it) {
744 os << "\\begin{preview}\n"
745 << from_utf8(it->first)
746 << "\n\\end{preview}\n\n";
750 } // namespace graphics