2 * \file PreviewLoader.C
3 * Copyright 2002 the LyX Team
4 * Read the file COPYING
6 * \author Angus Leeming <a.leeming@ic.ac.uk>
12 #pragma implementation
15 #include "PreviewLoader.h"
16 #include "PreviewImage.h"
17 #include "PreviewMetrics.h"
20 #include "bufferparams.h"
21 #include "converter.h"
26 #include "insets/inset.h"
28 #include "frontends/lyx_gui.h" // hexname
30 #include "support/filetools.h"
31 #include "support/forkedcall.h"
32 #include "support/forkedcontr.h"
33 #include "support/lstrings.h"
34 #include "support/lyxlib.h"
36 #include <boost/bind.hpp>
37 #include <boost/signals/trackable.hpp>
59 typedef pair<string, string> StrPair;
62 bool operator()(StrPair const & lhs, StrPair const & rhs)
64 return lhs.second < rhs.second;
69 FindFirst(string const & comp) : comp_(comp) {}
70 bool operator()(StrPair const & sp)
72 return sp.first < comp_;
79 string const unique_filename(string const bufferpath)
81 static int theCounter = 0;
82 string const filename = tostr(theCounter++) + "lyxpreview";
83 return AddName(bufferpath, filename);
87 /// Store info on a currently executing, forked process.
90 InProgress() : pid(0) {}
92 InProgress(string const & f, vector<StrPair> const & s)
93 : pid(0), metrics_file(f), snippets(s)
95 /// Remove any files left lying around and kill the forked process.
102 /// Each item in the vector is a pair<snippet, image file name>.
103 vector<StrPair> snippets;
112 struct PreviewLoader::Impl : public boost::signals::trackable {
114 Impl(PreviewLoader & p, Buffer const & b);
115 /// Stop any InProgress items still executing.
118 PreviewImage const * preview(string const & latex_snippet) const;
120 PreviewLoader::Status status(string const & latex_snippet) const;
122 void add(string const & latex_snippet);
124 void remove(string const & latex_snippet);
130 static bool haveConverter();
131 /// We don't own this
132 static Converter const * pconverter_;
134 /// Called by the Forkedcall process that generated the bitmap files.
135 void finishedGenerating(string const &, pid_t, int);
137 void dumpPreamble(ostream &) const;
139 void dumpData(ostream &, vector<StrPair> const &) const;
141 /** cache_ allows easy retrieval of already-generated images
142 * using the LaTeX snippet as the identifier.
144 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
146 typedef map<string, PreviewImagePtr> Cache;
150 /** pending_ stores the LaTeX snippets in anticipation of them being
151 * sent to the converter.
153 vector<string> pending_;
155 /** in_progress_ stores all forked processes so that we can proceed
157 The map uses the conversion commands as its identifiers.
159 typedef map<string, InProgress> InProgressMap;
161 InProgressMap in_progress_;
164 PreviewLoader & parent_;
166 Buffer const & buffer_;
170 Converter const * PreviewLoader::Impl::pconverter_;
173 // The public interface, defined in PreviewLoader.h
174 // ================================================
175 PreviewLoader::PreviewLoader(Buffer const & b)
176 : pimpl_(new Impl(*this, b))
180 PreviewLoader::~PreviewLoader()
184 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
186 return pimpl_->preview(latex_snippet);
190 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
192 return pimpl_->status(latex_snippet);
196 void PreviewLoader::add(string const & latex_snippet)
198 pimpl_->add(latex_snippet);
202 void PreviewLoader::remove(string const & latex_snippet)
204 pimpl_->remove(latex_snippet);
208 void PreviewLoader::startLoading()
210 pimpl_->startLoading();
216 // The details of the Impl
217 // =======================
221 void InProgress::stop() const
224 ForkedcallsController::get().kill(pid, 0);
226 if (!metrics_file.empty())
227 lyx::unlink(metrics_file);
229 vector<StrPair>::const_iterator vit = snippets.begin();
230 vector<StrPair>::const_iterator vend = snippets.end();
231 for (; vit != vend; ++vit) {
232 if (!vit->second.empty())
233 lyx::unlink(vit->second);
242 bool PreviewLoader::Impl::haveConverter()
247 string const from = "lyxpreview";
249 Formats::FormatList::const_iterator it = formats.begin();
250 Formats::FormatList::const_iterator end = formats.end();
252 for (; it != end; ++it) {
253 string const to = it->name();
256 Converter const * ptr = converters.getConverter(from, to);
266 static bool first = true;
269 lyxerr << "PreviewLoader::startLoading()\n"
270 << "No converter from \"lyxpreview\" format has been "
279 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
280 : parent_(p), buffer_(b)
284 PreviewLoader::Impl::~Impl()
286 InProgressMap::iterator ipit = in_progress_.begin();
287 InProgressMap::iterator ipend = in_progress_.end();
289 for (; ipit != ipend; ++ipit) {
296 PreviewLoader::Impl::preview(string const & latex_snippet) const
298 Cache::const_iterator it = cache_.find(latex_snippet);
299 return (it == cache_.end()) ? 0 : it->second.get();
303 PreviewLoader::Status
304 PreviewLoader::Impl::status(string const & latex_snippet) const
306 Cache::const_iterator cit = cache_.find(latex_snippet);
307 if (cit != cache_.end())
310 vector<string>::const_iterator vit = pending_.begin();
311 vector<string>::const_iterator vend = pending_.end();
312 vit = find(vit, vend, latex_snippet);
317 InProgressMap::const_iterator ipit = in_progress_.begin();
318 InProgressMap::const_iterator ipend = in_progress_.end();
320 for (; ipit != ipend; ++ipit) {
321 vector<StrPair> const & snippets = ipit->second.snippets;
322 vector<StrPair>::const_iterator vit = snippets.begin();
323 vector<StrPair>::const_iterator vend = snippets.end();
324 vit = find_if(vit, vend, FindFirst(latex_snippet));
334 void PreviewLoader::Impl::add(string const & latex_snippet)
336 if (!haveConverter())
339 if (status(latex_snippet) != NotFound)
342 pending_.push_back(latex_snippet);
343 sort(pending_.begin(), pending_.end());
347 void PreviewLoader::Impl::remove(string const & latex_snippet)
349 Cache::iterator cit = cache_.find(latex_snippet);
350 if (cit != cache_.end())
353 vector<string>::iterator vit = pending_.begin();
354 vector<string>::iterator vend = pending_.end();
355 vit = find(vit, vend, latex_snippet);
358 pending_.erase(vit, vit+1);
360 InProgressMap::iterator ipit = in_progress_.begin();
361 InProgressMap::iterator ipend = in_progress_.end();
363 while (ipit != ipend) {
364 InProgressMap::iterator curr = ipit;
367 vector<StrPair> & snippets = curr->second.snippets;
368 vector<StrPair>::iterator vit = snippets.begin();
369 vector<StrPair>::iterator vend = snippets.end();
370 vit = find_if(vit, vend, FindFirst(latex_snippet));
373 snippets.erase(vit, vit+1);
375 if (snippets.empty())
376 in_progress_.erase(curr);
381 void PreviewLoader::Impl::startLoading()
383 if (pending_.empty())
386 if (!haveConverter())
389 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
391 // As used by the LaTeX file and by the resulting image files
392 string const filename_base(unique_filename(buffer_.tmppath));
394 // Create an InProgress instance to place in the map of all
395 // such processes if it starts correctly.
396 vector<StrPair> snippets(pending_.size());
397 vector<StrPair>::iterator sit = snippets.begin();
398 vector<string>::const_iterator pit = pending_.begin();
399 vector<string>::const_iterator pend = pending_.end();
401 int counter = 1; // file numbers start at 1
402 for (; pit != pend; ++pit, ++sit, ++counter) {
405 << setfill('0') << setw(3) << counter
406 << "." << pconverter_->to;
407 string const file = os.str().c_str();
409 *sit = make_pair(*pit, file);
412 string const metrics_file = filename_base + ".metrics";
413 InProgress inprogress(metrics_file, snippets);
415 // clear pending_, so we're ready to start afresh.
418 // Output the LaTeX file.
419 string const latexfile = filename_base + ".tex";
421 ofstream of(latexfile.c_str());
423 of << "\n\\begin{document}\n";
424 dumpData(of, inprogress.snippets);
425 of << "\n\\end{document}\n";
428 // The conversion command.
430 cs << pconverter_->command << " " << latexfile << " "
431 << tostr(0.01 * lyxrc.dpi * lyxrc.zoom);
433 string const command = cs.str().c_str();
435 // Initiate the conversion from LaTeX to bitmap images files.
436 Forkedcall::SignalTypePtr convert_ptr;
437 convert_ptr.reset(new Forkedcall::SignalType);
439 convert_ptr->connect(
440 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
443 int ret = call.startscript(command, convert_ptr);
446 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
447 << "Unable to start process \n"
452 // Store the generation process in a list of all such processes
453 inprogress.pid = call.pid();
454 in_progress_[command] = inprogress;
458 void PreviewLoader::Impl::finishedGenerating(string const & command,
459 pid_t /* pid */, int retval)
461 string const status = retval > 0 ? "failed" : "succeeded";
462 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
463 << retval << "): processing " << status
464 << " for " << command << endl;
468 InProgressMap::iterator git = in_progress_.find(command);
469 if (git == in_progress_.end()) {
470 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
472 << command << "!" << endl;
476 // Read the metrics file, if it exists
477 PreviewMetrics metrics_file(git->second.metrics_file);
479 // Add these newly generated bitmap files to the cache and
480 // start loading them into LyX.
481 vector<StrPair>::const_iterator it = git->second.snippets.begin();
482 vector<StrPair>::const_iterator end = git->second.snippets.end();
484 int metrics_counter = 0;
485 for (; it != end; ++it) {
486 string const & snip = it->first;
489 Cache::const_iterator chk = cache_.find(snip);
490 if (chk != cache_.end())
493 // Mental note (Angus, 4 July 2002, having just found out the
495 // We /must/ first add to the cache and then start the
496 // image loading process.
497 // If not, then outside functions can be called before by the
498 // image loader before the PreviewImage/map is properly
500 // This can lead to all sorts of horribleness if such a
501 // function attempts to access the cache's internals.
502 string const & file = it->second;
503 double af = metrics_file.ascent_fraction(metrics_counter++);
504 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
511 // Remove the item from the list of still-executing processes.
512 in_progress_.erase(git);
516 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
518 // Why on earth is Buffer::makeLaTeXFile a non-const method?
519 Buffer & tmp = const_cast<Buffer &>(buffer_);
520 // Dump the preamble only.
521 tmp.makeLaTeXFile(os, string(), true, false, true);
523 // Loop over the insets in the buffer and dump all the math-macros.
524 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
525 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
527 for (; it != end; ++it) {
528 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
529 (*it)->latex(&buffer_, os, true, true);
533 // Use the preview style file to ensure that each snippet appears on a
536 << "\\usepackage[active,delayed,dvips,tightpage,showlabels]{preview}\n"
539 // This piece of PostScript magic ensures that the foreground and
540 // background colors are the same as the LyX screen.
541 string fg = lyx_gui::hexname(LColor::preview);
542 if (fg.empty()) fg = "000000";
544 string bg = lyx_gui::hexname(LColor::background);
545 if (bg.empty()) bg = "ffffff";
547 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
548 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
549 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
550 << "clippath fill setrgbcolor}bind def end}}}\n";
554 void PreviewLoader::Impl::dumpData(ostream & os,
555 vector<StrPair> const & vec) const
560 vector<StrPair>::const_iterator it = vec.begin();
561 vector<StrPair>::const_iterator end = vec.end();
563 for (; it != end; ++it) {
564 os << "\\begin{preview}\n"
566 << "\n\\end{preview}\n\n";