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(string const bufferpath)
79 static int theCounter = 0;
80 string const filename = tostr(theCounter++) + "lyxpreview";
81 return AddName(bufferpath, filename);ostringstream os;
89 struct PreviewLoader::Impl : public boost::signals::trackable {
91 Impl(PreviewLoader & p, Buffer const & b);
95 PreviewImage const * preview(string const & latex_snippet) const;
97 PreviewLoader::Status status(string const & latex_snippet) const;
99 void add(string const & latex_snippet);
101 void remove(string const & latex_snippet);
106 typedef pair<string, string> StrPair;
108 typedef map<string, string> PendingMap;
111 /// Called by the Forkedcall process that generated the bitmap files.
112 void finishedGenerating(string const &, pid_t, int);
114 void dumpPreamble(ostream &) const;
116 void dumpData(ostream &, vector<StrPair> const &) const;
119 static void setConverter();
120 /// We don't own this
121 static Converter const * pconverter_;
123 /** cache_ allows easy retrieval of already-generated images
124 * using the LaTeX snippet as the identifier.
126 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
128 typedef map<string, PreviewImagePtr> Cache;
132 /** pending_ stores the LaTeX snippet and the name of the generated
133 * bitmap image file in anticipation of them being sent to the
138 /// Store info on a currently executing, forked process.
143 InProgress(string const & f, PendingMap const & m)
144 : pid(0), metrics_file(f), snippets(m.begin(), m.end())
146 sort(snippets.begin(), snippets.end(), CompSecond());
154 /** Store the info in the PendingMap as a vector.
155 Ensures that the data is output in the order
156 file001, file002 etc, as we expect, which is /not/ what
157 happens when we iterate through the map.
159 vector<StrPair> snippets;
162 /// Store all forked processes so that we can proceed thereafter.
163 typedef map<string, InProgress> InProgressMap;
165 InProgressMap in_progress_;
168 string filename_base_;
170 PreviewLoader & parent_;
172 Buffer const & buffer_;
175 Converter const * PreviewLoader::Impl::pconverter_;
178 PreviewLoader::PreviewLoader(Buffer const & b)
179 : pimpl_(new Impl(*this, b))
183 PreviewLoader::~PreviewLoader()
187 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
189 return pimpl_->preview(latex_snippet);
193 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
195 return pimpl_->status(latex_snippet);
199 void PreviewLoader::add(string const & latex_snippet)
201 pimpl_->add(latex_snippet);
205 void PreviewLoader::remove(string const & latex_snippet)
207 pimpl_->remove(latex_snippet);
211 void PreviewLoader::startLoading()
213 pimpl_->startLoading();
217 void PreviewLoader::Impl::setConverter()
222 string const from = "lyxpreview";
224 Formats::FormatList::const_iterator it = formats.begin();
225 Formats::FormatList::const_iterator end = formats.end();
227 for (; it != end; ++it) {
228 string const to = it->name();
231 Converter const * ptr = converters.getConverter(from, to);
241 static bool first = true;
246 lyxerr << "PreviewLoader::startLoading()\n"
247 << "No converter from \"lyxpreview\" format has been defined."
252 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
253 : filename_base_(unique_filename(b.tmppath)), parent_(p), buffer_(b)
258 PreviewLoader::Impl::preview(string const & latex_snippet) const
260 Cache::const_iterator it = cache_.find(latex_snippet);
261 return (it == cache_.end()) ? 0 : it->second.get();
265 PreviewLoader::Impl::~Impl()
267 InProgressMap::const_iterator ipit = in_progress_.begin();
268 InProgressMap::const_iterator ipend = in_progress_.end();
270 for (; ipit != ipend; ++ipit) {
271 pid_t pid = ipit->second.pid;
273 ForkedcallsController::get().kill(pid, 0);
275 lyx::unlink(ipit->second.metrics_file);
277 vector<StrPair> const & snippets = ipit->second.snippets;
278 vector<StrPair>::const_iterator vit = snippets.begin();
279 vector<StrPair>::const_iterator vend = snippets.end();
280 for (; vit != vend; ++vit) {
281 lyx::unlink(vit->second);
287 PreviewLoader::Status
288 PreviewLoader::Impl::status(string const & latex_snippet) const
290 Cache::const_iterator cit = cache_.find(latex_snippet);
291 if (cit != cache_.end())
292 return PreviewLoader::Ready;
294 PendingMap::const_iterator pit = pending_.find(latex_snippet);
295 if (pit != pending_.end())
296 return PreviewLoader::InQueue;
298 InProgressMap::const_iterator ipit = in_progress_.begin();
299 InProgressMap::const_iterator ipend = in_progress_.end();
301 for (; ipit != ipend; ++ipit) {
302 vector<StrPair> const & snippets = ipit->second.snippets;
303 vector<StrPair>::const_iterator vit = snippets.begin();
304 vector<StrPair>::const_iterator vend = snippets.end();
305 vit = find_if(vit, vend, FindFirst(latex_snippet));
308 return PreviewLoader::Processing;
311 return PreviewLoader::NotFound;
315 void PreviewLoader::Impl::add(string const & latex_snippet)
323 Cache::const_iterator cit = cache_.find(latex_snippet);
324 if (cit != cache_.end())
327 PendingMap::const_iterator pit = pending_.find(latex_snippet);
328 if (pit != pending_.end())
331 int const snippet_counter = int(pending_.size()) + 1;
334 << setfill('0') << setw(3) << snippet_counter
335 << "." << pconverter_->to;
336 string const image_filename = os.str().c_str();
338 pending_[latex_snippet] = image_filename;
342 void PreviewLoader::Impl::remove(string const & latex_snippet)
344 Cache::iterator cit = cache_.find(latex_snippet);
345 if (cit != cache_.end())
348 PendingMap::iterator pit = pending_.find(latex_snippet);
349 if (pit != pending_.end())
352 InProgressMap::iterator ipit = in_progress_.begin();
353 InProgressMap::iterator ipend = in_progress_.end();
355 while (ipit != ipend) {
356 InProgressMap::iterator curr = ipit;
359 vector<StrPair> & snippets = curr->second.snippets;
360 vector<StrPair>::iterator vit = snippets.begin();
361 vector<StrPair>::iterator vend = snippets.end();
362 vit = find_if(vit, vend, FindFirst(latex_snippet));
365 snippets.erase(vit, vit+1);
367 if (snippets.empty())
368 in_progress_.erase(curr);
373 void PreviewLoader::Impl::startLoading()
375 if (pending_.empty())
384 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
386 // Create an InProgress instance to place in the map of all
387 // such processes if it starts correctly.
388 string const metrics_file = filename_base_ + ".metrics";
389 InProgress inprogress(metrics_file, pending_);
391 // Output the LaTeX file.
392 string const latexfile = filename_base_ + ".tex";
394 ofstream of(latexfile.c_str());
396 of << "\n\\begin{document}\n";
397 dumpData(of, inprogress.snippets);
398 of << "\n\\end{document}\n";
401 // Reset the filename and clear pending_, so we're ready to
404 filename_base_ = unique_filename(buffer_.tmppath);
406 // The conversion command.
408 cs << pconverter_->command << " " << latexfile << " "
409 << tostr(0.01 * lyxrc.dpi * lyxrc.zoom);
411 string const command = cs.str().c_str();
413 // Initiate the conversion from LaTeX to bitmap images files.
414 Forkedcall::SignalTypePtr convert_ptr;
415 convert_ptr.reset(new Forkedcall::SignalType);
417 convert_ptr->connect(
418 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
421 int ret = call.startscript(command, convert_ptr);
424 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
425 << "Unable to start process \n"
430 // Store the generation process in a list of all such processes
431 inprogress.pid = call.pid();
432 in_progress_[command] = inprogress;
436 void PreviewLoader::Impl::finishedGenerating(string const & command,
437 pid_t /* pid */, int retval)
439 string const status = retval > 0 ? "failed" : "succeeded";
440 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
441 << retval << "): processing " << status
442 << " for " << command << endl;
446 InProgressMap::iterator git = in_progress_.find(command);
447 if (git == in_progress_.end()) {
448 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
450 << command << "!" << endl;
454 // Reset the pid to 0 as the process has finished.
457 // Read the metrics file, if it exists
458 PreviewMetrics metrics_file(git->second.metrics_file);
460 // Add these newly generated bitmap files to the cache and
461 // start loading them into LyX.
462 vector<StrPair>::const_iterator it = git->second.snippets.begin();
463 vector<StrPair>::const_iterator end = git->second.snippets.end();
465 int metrics_counter = 0;
466 for (; it != end; ++it) {
467 string const & snip = it->first;
470 Cache::const_iterator chk = cache_.find(snip);
471 if (chk != cache_.end())
474 // Mental note (Angus, 4 July 2002, having just found out the
476 // We /must/ first add to the cache and then start the
477 // image loading process.
478 // If not, then outside functions can be called before by the
479 // image loader before the PreviewImage is properly constucted.
480 // This can lead to all sorts of horribleness if such a
481 // function attempts to access its internals.
482 string const & file = it->second;
483 double af = metrics_file.ascent_fraction(metrics_counter++);
484 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
491 in_progress_.erase(git);
495 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
497 // Why on earth is Buffer::makeLaTeXFile a non-const method?
498 Buffer & tmp = const_cast<Buffer &>(buffer_);
499 // Dump the preamble only.
500 tmp.makeLaTeXFile(os, string(), true, false, true);
502 // Loop over the insets in the buffer and dump all the math-macros.
503 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
504 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
506 for (; it != end; ++it) {
507 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
508 (*it)->latex(&buffer_, os, true, true);
512 // Use the preview style file to ensure that each snippet appears on a
515 << "\\usepackage[active,dvips,tightpage]{preview}\n"
518 // This piece of PostScript magic ensures that the foreground and
519 // background colors are the same as the LyX screen.
520 string fg = lyx_gui::hexname(LColor::preview);
521 if (fg.empty()) fg = "000000";
523 string bg = lyx_gui::hexname(LColor::background);
524 if (bg.empty()) bg = "ffffff";
526 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
527 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
528 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
529 << "clippath fill setrgbcolor}bind def end}}}\n";
533 void PreviewLoader::Impl::dumpData(ostream & os,
534 vector<StrPair> const & vec) const
539 vector<StrPair>::const_iterator it = vec.begin();
540 vector<StrPair>::const_iterator end = vec.end();
542 for (; it != end; ++it) {
543 os << "\\begin{preview}\n"
545 << "\n\\end{preview}\n\n";