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"
39 #include <boost/bind.hpp>
46 using namespace lyx::support;
52 typedef pair<string, FileName> SnippetPair;
54 // A list of all snippets to be converted to previews
55 typedef list<string> PendingSnippets;
57 // Each item in the vector is a pair<snippet, image file name>.
58 typedef vector<SnippetPair> BitmapFile;
61 string const unique_filename(string const & bufferpath)
63 static int theCounter = 0;
64 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
65 return addName(bufferpath, filename);
69 lyx::Converter const * setConverter()
71 string const from = "lyxpreview";
73 typedef vector<string> FmtList;
74 typedef lyx::graphics::Cache GCache;
75 FmtList const loadableFormats = GCache::get().loadableFormats();
76 FmtList::const_iterator it = loadableFormats.begin();
77 FmtList::const_iterator const end = loadableFormats.end();
79 for (; it != end; ++it) {
80 string const to = *it;
84 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
89 static bool first = true;
92 LYXERR0("PreviewLoader::startLoading()\n"
93 << "No converter from \"lyxpreview\" format has been defined.");
99 void setAscentFractions(vector<double> & ascent_fractions,
100 FileName const & metrics_file)
102 // If all else fails, then the images will have equal ascents and
104 vector<double>::iterator it = ascent_fractions.begin();
105 vector<double>::iterator end = ascent_fractions.end();
108 ifstream in(metrics_file.toFilesystemEncoding().c_str());
110 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
111 << "Unable to open file!");
117 int snippet_counter = 1;
118 while (!in.eof() && it != end) {
121 double ascent_fraction;
123 in >> snippet >> id >> ascent_fraction;
129 error = snippet != "Snippet";
133 error = id != snippet_counter;
137 *it = ascent_fraction;
144 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
145 << "Error reading file!\n");
153 FindFirst(string const & comp) : comp_(comp) {}
154 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
160 /// Store info on a currently executing, forked process.
164 InProgress() : pid(0) {}
166 InProgress(string const & filename_base,
167 PendingSnippets const & pending,
168 string const & to_format);
169 /// Remove any files left lying around and kill the forked process.
177 FileName metrics_file;
182 typedef map<pid_t, InProgress> InProgressProcesses;
184 typedef InProgressProcesses::value_type InProgressProcess;
193 class PreviewLoader::Impl : public boost::signals::trackable {
196 Impl(PreviewLoader & p, Buffer const & b);
197 /// Stop any InProgress items still executing.
200 PreviewImage const * preview(string const & latex_snippet) const;
202 PreviewLoader::Status status(string const & latex_snippet) const;
204 void add(string const & latex_snippet);
206 void remove(string const & latex_snippet);
210 /// Emit this signal when an image is ready for display.
211 boost::signal<void(PreviewImage const &)> imageReady;
213 Buffer const & buffer() const { return buffer_; }
216 /// Called by the ForkedCall process that generated the bitmap files.
217 void finishedGenerating(pid_t, int);
219 void dumpPreamble(odocstream &) const;
221 void dumpData(odocstream &, BitmapFile const &) const;
223 /** cache_ allows easy retrieval of already-generated images
224 * using the LaTeX snippet as the identifier.
226 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
228 typedef map<string, PreviewImagePtr> Cache;
232 /** pending_ stores the LaTeX snippets in anticipation of them being
233 * sent to the converter.
235 PendingSnippets pending_;
237 /** in_progress_ stores all forked processes so that we can proceed
239 The map uses the conversion commands as its identifiers.
241 InProgressProcesses in_progress_;
244 PreviewLoader & parent_;
246 Buffer const & buffer_;
248 double font_scaling_factor_;
250 /// We don't own this
251 static lyx::Converter const * pconverter_;
255 lyx::Converter const * PreviewLoader::Impl::pconverter_;
259 // The public interface, defined in PreviewLoader.h
262 PreviewLoader::PreviewLoader(Buffer const & b)
263 : pimpl_(new Impl(*this, b))
267 PreviewLoader::~PreviewLoader()
273 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
275 return pimpl_->preview(latex_snippet);
279 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
281 return pimpl_->status(latex_snippet);
285 void PreviewLoader::add(string const & latex_snippet) const
287 pimpl_->add(latex_snippet);
291 void PreviewLoader::remove(string const & latex_snippet) const
293 pimpl_->remove(latex_snippet);
297 void PreviewLoader::startLoading() const
299 pimpl_->startLoading();
303 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
305 return pimpl_->imageReady.connect(slot);
309 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
311 pimpl_->imageReady(pimage);
315 Buffer const & PreviewLoader::buffer() const
317 return pimpl_->buffer();
320 } // namespace graphics
324 // The details of the Impl
325 // =======================
329 class IncrementedFileName {
331 IncrementedFileName(string const & to_format,
332 string const & filename_base)
333 : to_format_(to_format), base_(filename_base), counter_(1)
336 SnippetPair const operator()(string const & snippet)
339 os << base_ << counter_++ << '.' << to_format_;
340 string const file = os.str();
342 return make_pair(snippet, FileName(file));
346 string const & to_format_;
347 string const & base_;
352 InProgress::InProgress(string const & filename_base,
353 PendingSnippets const & pending,
354 string const & to_format)
356 metrics_file(FileName(filename_base + ".metrics")),
357 snippets(pending.size())
359 PendingSnippets::const_iterator pit = pending.begin();
360 PendingSnippets::const_iterator pend = pending.end();
361 BitmapFile::iterator sit = snippets.begin();
363 transform(pit, pend, sit,
364 IncrementedFileName(to_format, filename_base));
368 void InProgress::stop() const
371 ForkedCallsController::kill(pid, 0);
373 if (!metrics_file.empty())
374 metrics_file.removeFile();
376 BitmapFile::const_iterator vit = snippets.begin();
377 BitmapFile::const_iterator vend = snippets.end();
378 for (; vit != vend; ++vit) {
379 if (!vit->second.empty())
380 vit->second.removeFile();
390 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
391 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
393 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
394 convert<double>(lyxrc.preview_scale_factor);
396 LYXERR(Debug::GRAPHICS, "The font scaling factor is "
397 << font_scaling_factor_);
400 pconverter_ = setConverter();
404 PreviewLoader::Impl::~Impl()
406 InProgressProcesses::iterator ipit = in_progress_.begin();
407 InProgressProcesses::iterator ipend = in_progress_.end();
409 for (; ipit != ipend; ++ipit)
415 PreviewLoader::Impl::preview(string const & latex_snippet) const
417 Cache::const_iterator it = cache_.find(latex_snippet);
418 return (it == cache_.end()) ? 0 : it->second.get();
426 FindSnippet(string const & s) : snippet_(s) {}
427 bool operator()(InProgressProcess const & process) const
429 BitmapFile const & snippets = process.second.snippets;
430 BitmapFile::const_iterator beg = snippets.begin();
431 BitmapFile::const_iterator end = snippets.end();
432 return find_if(beg, end, FindFirst(snippet_)) != end;
436 string const snippet_;
441 PreviewLoader::Status
442 PreviewLoader::Impl::status(string const & latex_snippet) const
444 Cache::const_iterator cit = cache_.find(latex_snippet);
445 if (cit != cache_.end())
448 PendingSnippets::const_iterator pit = pending_.begin();
449 PendingSnippets::const_iterator pend = pending_.end();
451 pit = find(pit, pend, latex_snippet);
455 InProgressProcesses::const_iterator ipit = in_progress_.begin();
456 InProgressProcesses::const_iterator ipend = in_progress_.end();
458 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
466 void PreviewLoader::Impl::add(string const & latex_snippet)
468 if (!pconverter_ || status(latex_snippet) != NotFound)
471 string const snippet = trim(latex_snippet);
475 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
477 pending_.push_back(snippet);
485 EraseSnippet(string const & s) : snippet_(s) {}
486 void operator()(InProgressProcess & process)
488 BitmapFile & snippets = process.second.snippets;
489 BitmapFile::iterator it = snippets.begin();
490 BitmapFile::iterator end = snippets.end();
492 it = find_if(it, end, FindFirst(snippet_));
494 snippets.erase(it, it+1);
498 string const & snippet_;
504 void PreviewLoader::Impl::remove(string const & latex_snippet)
506 Cache::iterator cit = cache_.find(latex_snippet);
507 if (cit != cache_.end())
510 PendingSnippets::iterator pit = pending_.begin();
511 PendingSnippets::iterator pend = pending_.end();
513 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
515 InProgressProcesses::iterator ipit = in_progress_.begin();
516 InProgressProcesses::iterator ipend = in_progress_.end();
518 for_each(ipit, ipend, EraseSnippet(latex_snippet));
520 while (ipit != ipend) {
521 InProgressProcesses::iterator curr = ipit++;
522 if (curr->second.snippets.empty())
523 in_progress_.erase(curr);
528 void PreviewLoader::Impl::startLoading()
530 if (pending_.empty() || !pconverter_)
533 // Only start the process off after the buffer is loaded from file.
534 if (!buffer_.isFullyLoaded())
537 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
539 // As used by the LaTeX file and by the resulting image files
540 string const directory = buffer_.temppath();
542 string const filename_base = unique_filename(directory);
544 // Create an InProgress instance to place in the map of all
545 // such processes if it starts correctly.
546 InProgress inprogress(filename_base, pending_, pconverter_->to);
548 // clear pending_, so we're ready to start afresh.
551 // Output the LaTeX file.
552 FileName const latexfile(filename_base + ".tex");
554 // we use the encoding of the buffer
555 Encoding const & enc = buffer_.params().encoding();
556 odocfstream of(enc.iconvName());
558 OutputParams runparams(&enc);
559 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
561 if (!openFileWrite(of, latexfile))
565 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
566 << "Unable to create LaTeX file\n" << latexfile);
569 of << "\\batchmode\n";
571 // handle inputenc etc.
572 buffer_.params().writeEncodingPreamble(of, features, texrow);
573 of << "\n\\begin{document}\n";
574 dumpData(of, inprogress.snippets);
575 of << "\n\\end{document}\n";
578 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
579 << "File was not closed properly.");
583 // The conversion command.
585 cs << pconverter_->command << ' ' << pconverter_->to << ' '
586 << quoteName(latexfile.toFilesystemEncoding()) << ' '
587 << int(font_scaling_factor_) << ' '
588 << theApp()->hexName(Color_preview) << ' '
589 << theApp()->hexName(Color_background);
591 string const command = libScriptSearch(cs.str());
593 // Initiate the conversion from LaTeX to bitmap images files.
594 ForkedCall::SignalTypePtr
595 convert_ptr(new ForkedCall::SignalType);
596 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
599 int ret = call.startScript(command, convert_ptr);
602 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
603 << "Unable to start process\n" << command);
607 // Store the generation process in a list of all such processes
608 inprogress.pid = call.pid();
609 inprogress.command = command;
610 in_progress_[inprogress.pid] = inprogress;
614 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
617 InProgressProcesses::iterator git = in_progress_.find(pid);
618 if (git == in_progress_.end()) {
619 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
620 "data for PID " << pid << endl;
624 string const command = git->second.command;
625 string const status = retval > 0 ? "failed" : "succeeded";
626 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
627 << retval << "): processing " << status
628 << " for " << command);
632 // Read the metrics file, if it exists
633 vector<double> ascent_fractions(git->second.snippets.size());
634 setAscentFractions(ascent_fractions, git->second.metrics_file);
636 // Add these newly generated bitmap files to the cache and
637 // start loading them into LyX.
638 BitmapFile::const_iterator it = git->second.snippets.begin();
639 BitmapFile::const_iterator end = git->second.snippets.end();
641 list<PreviewImagePtr> newimages;
643 int metrics_counter = 0;
644 for (; it != end; ++it, ++metrics_counter) {
645 string const & snip = it->first;
646 FileName const & file = it->second;
647 double af = ascent_fractions[metrics_counter];
649 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
652 newimages.push_back(ptr);
655 // Remove the item from the list of still-executing processes.
656 in_progress_.erase(git);
658 // Tell the outside world
659 list<PreviewImagePtr>::const_reverse_iterator
660 nit = newimages.rbegin();
661 list<PreviewImagePtr>::const_reverse_iterator
662 nend = newimages.rend();
663 for (; nit != nend; ++nit) {
664 imageReady(*nit->get());
669 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
671 // Why on earth is Buffer::makeLaTeXFile a non-const method?
672 Buffer & tmp = const_cast<Buffer &>(buffer_);
673 // Dump the preamble only.
674 // We don't need an encoding for runparams since it is not used by
676 OutputParams runparams(0);
677 runparams.flavor = OutputParams::LATEX;
678 runparams.nice = true;
679 runparams.moving_arg = true;
680 runparams.free_spacing = true;
681 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
683 // FIXME! This is a HACK! The proper fix is to control the 'true'
684 // passed to WriteStream below:
685 // int InsetMathNest::latex(Buffer const &, odocstream & os,
686 // OutputParams const & runparams) const
688 // WriteStream wi(os, runparams.moving_arg, true);
693 << "\\def\\lyxlock{}\n"
696 // Loop over the insets in the buffer and dump all the math-macros.
697 Inset & inset = buffer_.inset();
698 InsetIterator it = inset_iterator_begin(inset);
699 InsetIterator const end = inset_iterator_end(inset);
701 for (; it != end; ++it)
702 if (it->lyxCode() == MATHMACRO_CODE)
703 it->latex(buffer_, os, runparams);
705 // All equation labels appear as "(#)" + preview.sty's rendering of
707 if (lyxrc.preview_hashed_labels)
708 os << "\\renewcommand{\\theequation}{\\#}\n";
710 // Use the preview style file to ensure that each snippet appears on a
713 << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
718 void PreviewLoader::Impl::dumpData(odocstream & os,
719 BitmapFile const & vec) const
724 BitmapFile::const_iterator it = vec.begin();
725 BitmapFile::const_iterator end = vec.end();
727 for (; it != end; ++it) {
729 os << "\\begin{preview}\n"
730 << from_utf8(it->first)
731 << "\n\\end{preview}\n\n";
735 } // namespace graphics