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>
57 typedef pair<string, string> StrPair;
60 bool operator()(StrPair const & lhs, StrPair const & rhs)
62 return lhs.second < rhs.second;
67 FindFirst(string const & comp) : comp_(comp) {}
68 bool operator()(StrPair const & sp)
70 return sp.first < comp_;
77 string const unique_filename()
82 string const tmp = lyx::tempName();
87 static int theCounter = 0;
89 os << dir << theCounter++ << "lyxpreview";
91 return os.str().c_str();
99 struct PreviewLoader::Impl : public boost::signals::trackable {
101 Impl(PreviewLoader & p, Buffer const & b);
105 PreviewImage const * preview(string const & latex_snippet) const;
107 PreviewLoader::Status status(string const & latex_snippet) const;
109 void add(string const & latex_snippet);
111 void remove(string const & latex_snippet);
116 typedef pair<string, string> StrPair;
118 typedef map<string, string> PendingMap;
121 /// Called by the Forkedcall process that generated the bitmap files.
122 void finishedGenerating(string const &, pid_t, int);
124 void dumpPreamble(ostream &) const;
126 void dumpData(ostream &, vector<StrPair> const &) const;
129 static void setConverter();
130 /// We don't own this
131 static Converter const * pconverter_;
133 /** cache_ allows easy retrieval of already-generated images
134 * using the LaTeX snippet as the identifier.
136 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
138 typedef map<string, PreviewImagePtr> Cache;
142 /** pending_ stores the LaTeX snippet and the name of the generated
143 * bitmap image file in anticipation of them being sent to the
148 /// Store info on a currently executing, forked process.
153 InProgress(string const & f, PendingMap const & m)
154 : pid(0), metrics_file(f), snippets(m.begin(), m.end())
156 sort(snippets.begin(), snippets.end(), CompSecond());
164 /** Store the info in the PendingMap as a vector.
165 Ensures that the data is output in the order
166 file001, file002 etc, as we expect, which is /not/ what
167 happens when we iterate through the map.
169 vector<StrPair> snippets;
172 /// Store all forked processes so that we can proceed thereafter.
173 typedef map<string, InProgress> InProgressMap;
175 InProgressMap in_progress_;
178 string filename_base_;
180 PreviewLoader & parent_;
182 Buffer const & buffer_;
185 Converter const * PreviewLoader::Impl::pconverter_;
188 PreviewLoader::PreviewLoader(Buffer const & b)
189 : pimpl_(new Impl(*this, b))
193 PreviewLoader::~PreviewLoader()
197 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
199 return pimpl_->preview(latex_snippet);
203 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
205 return pimpl_->status(latex_snippet);
209 void PreviewLoader::add(string const & latex_snippet)
211 pimpl_->add(latex_snippet);
215 void PreviewLoader::remove(string const & latex_snippet)
217 pimpl_->remove(latex_snippet);
221 void PreviewLoader::startLoading()
223 pimpl_->startLoading();
227 void PreviewLoader::Impl::setConverter()
232 string const from = "lyxpreview";
234 Formats::FormatList::const_iterator it = formats.begin();
235 Formats::FormatList::const_iterator end = formats.end();
237 for (; it != end; ++it) {
238 string const to = it->name();
241 Converter const * ptr = converters.getConverter(from, to);
251 static bool first = true;
256 lyxerr << "PreviewLoader::startLoading()\n"
257 << "No converter from \"lyxpreview\" format has been defined."
262 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
263 : filename_base_(unique_filename()), parent_(p), buffer_(b)
268 PreviewLoader::Impl::preview(string const & latex_snippet) const
270 Cache::const_iterator it = cache_.find(latex_snippet);
271 return (it == cache_.end()) ? 0 : it->second.get();
275 PreviewLoader::Impl::~Impl()
277 InProgressMap::const_iterator ipit = in_progress_.begin();
278 InProgressMap::const_iterator ipend = in_progress_.end();
280 for (; ipit != ipend; ++ipit) {
281 pid_t pid = ipit->second.pid;
283 ForkedcallsController::get().kill(pid, 0);
285 lyx::unlink(ipit->second.metrics_file);
287 vector<StrPair> const & snippets = ipit->second.snippets;
288 vector<StrPair>::const_iterator vit = snippets.begin();
289 vector<StrPair>::const_iterator vend = snippets.end();
290 for (; vit != vend; ++vit) {
291 lyx::unlink(vit->second);
297 PreviewLoader::Status
298 PreviewLoader::Impl::status(string const & latex_snippet) const
300 Cache::const_iterator cit = cache_.find(latex_snippet);
301 if (cit != cache_.end())
302 return PreviewLoader::Ready;
304 PendingMap::const_iterator pit = pending_.find(latex_snippet);
305 if (pit != pending_.end())
306 return PreviewLoader::InQueue;
308 InProgressMap::const_iterator ipit = in_progress_.begin();
309 InProgressMap::const_iterator ipend = in_progress_.end();
311 for (; ipit != ipend; ++ipit) {
312 vector<StrPair> const & snippets = ipit->second.snippets;
313 vector<StrPair>::const_iterator vit = snippets.begin();
314 vector<StrPair>::const_iterator vend = snippets.end();
315 vit = find_if(vit, vend, FindFirst(latex_snippet));
318 return PreviewLoader::Processing;
321 return PreviewLoader::NotFound;
325 void PreviewLoader::Impl::add(string const & latex_snippet)
333 Cache::const_iterator cit = cache_.find(latex_snippet);
334 if (cit != cache_.end())
337 PendingMap::const_iterator pit = pending_.find(latex_snippet);
338 if (pit != pending_.end())
341 int const snippet_counter = int(pending_.size()) + 1;
344 << setfill('0') << setw(3) << snippet_counter
345 << "." << pconverter_->to;
346 string const image_filename = os.str().c_str();
348 pending_[latex_snippet] = image_filename;
352 void PreviewLoader::Impl::remove(string const & latex_snippet)
354 Cache::iterator cit = cache_.find(latex_snippet);
355 if (cit != cache_.end())
358 PendingMap::iterator pit = pending_.find(latex_snippet);
359 if (pit != pending_.end())
362 InProgressMap::iterator ipit = in_progress_.begin();
363 InProgressMap::iterator ipend = in_progress_.end();
365 while (ipit != ipend) {
366 InProgressMap::iterator curr = ipit;
369 vector<StrPair> & snippets = curr->second.snippets;
370 vector<StrPair>::iterator vit = snippets.begin();
371 vector<StrPair>::iterator vend = snippets.end();
372 vit = find_if(vit, vend, FindFirst(latex_snippet));
375 snippets.erase(vit, vit+1);
377 if (snippets.empty())
378 in_progress_.erase(curr);
383 void PreviewLoader::Impl::startLoading()
385 if (pending_.empty())
394 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
396 // Create an InProgress instance to place in the map of all
397 // such processes if it starts correctly.
398 string const metrics_file = filename_base_ + ".metrics";
399 InProgress inprogress(metrics_file, pending_);
401 // Output the LaTeX file.
402 string const latexfile = filename_base_ + ".tex";
404 ofstream of(latexfile.c_str());
406 of << "\n\\begin{document}\n";
407 dumpData(of, inprogress.snippets);
408 of << "\n\\end{document}\n";
411 // Reset the filename and clear pending_, so we're ready to
414 filename_base_ = unique_filename();
416 // The conversion command.
418 cs << pconverter_->command << " " << latexfile << " "
419 << tostr(0.01 * lyxrc.dpi * lyxrc.zoom);
421 string const command = cs.str().c_str();
423 // Initiate the conversion from LaTeX to bitmap images files.
424 Forkedcall::SignalTypePtr convert_ptr;
425 convert_ptr.reset(new Forkedcall::SignalType);
427 convert_ptr->connect(
428 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
431 int ret = call.startscript(command, convert_ptr);
434 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
435 << "Unable to start process \n"
440 // Store the generation process in a list of all generating processes
441 // (I anticipate that this will be small!)
442 inprogress.pid = call.pid();
443 in_progress_[command] = inprogress;
447 void PreviewLoader::Impl::finishedGenerating(string const & command,
448 pid_t /* pid */, int retval)
450 string const status = retval > 0 ? "failed" : "succeeded";
451 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
452 << retval << "): processing " << status
453 << " for " << command << endl;
457 InProgressMap::iterator git = in_progress_.find(command);
458 if (git == in_progress_.end()) {
459 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
461 << command << "!" << endl;
465 // Reset the pid to 0 as the process has finished.
468 // Read the metrics file, if it exists
469 PreviewMetrics metrics_file(git->second.metrics_file);
471 // Add these newly generated bitmap files to the cache and
472 // start loading them into LyX.
473 vector<StrPair>::const_iterator it = git->second.snippets.begin();
474 vector<StrPair>::const_iterator end = git->second.snippets.end();
476 int metrics_counter = 0;
477 for (; it != end; ++it) {
478 string const & snip = it->first;
481 Cache::const_iterator chk = cache_.find(snip);
482 if (chk != cache_.end())
485 // Mental note (Angus, 4 July 2002, having just found out the
487 // We /must/ first add to the cache and then start the
488 // image loading process.
489 // If not, then outside functions can be called before by the
490 // image loader before the PreviewImage is properly constucted.
491 // This can lead to all sorts of horribleness if such a
492 // function attempts to access its internals.
493 string const & file = it->second;
494 double af = metrics_file.ascent_fraction(metrics_counter++);
495 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
502 in_progress_.erase(git);
506 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
508 // Why on earth is Buffer::makeLaTeXFile a non-const method?
509 Buffer & tmp = const_cast<Buffer &>(buffer_);
510 // Dump the preamble only.
511 tmp.makeLaTeXFile(os, string(), true, false, true);
513 // Loop over the insets in the buffer and dump all the math-macros.
514 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
515 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
517 for (; it != end; ++it) {
518 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
519 (*it)->latex(&buffer_, os, true, true);
523 // Use the preview style file to ensure that each snippet appears on a
526 << "\\usepackage[active,dvips,tightpage]{preview}\n"
529 // This piece of PostScript magic ensures that the foreground and
530 // background colors are the same as the LyX screen.
531 string fg = lyx_gui::hexname(LColor::preview);
532 if (fg.empty()) fg = "000000";
534 string bg = lyx_gui::hexname(LColor::background);
535 if (bg.empty()) bg = "ffffff";
537 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
538 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
539 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
540 << "clippath fill setrgbcolor}bind def end}}}\n";
544 void PreviewLoader::Impl::dumpData(ostream & os,
545 vector<StrPair> const & vec) const
550 vector<StrPair>::const_iterator it = vec.begin();
551 vector<StrPair>::const_iterator end = vec.end();
553 for (; it != end; ++it) {
554 os << "\\begin{preview}\n"
556 << "\n\\end{preview}\n\n";