2 * \file PreviewLoader.C
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"
17 #include "converter.h"
22 #include "insets/inset.h"
24 #include "frontends/lyx_gui.h" // hexname
26 #include "support/filetools.h"
27 #include "support/forkedcall.h"
28 #include "support/forkedcontr.h"
29 #include "support/lstrings.h"
30 #include "support/lyxlib.h"
32 #include <boost/bind.hpp>
33 #include <boost/signals/trackable.hpp>
61 typedef pair<string, string> StrPair;
63 // A list of alll snippets to be converted to previews
64 typedef list<string> PendingSnippets;
66 // Each item in the vector is a pair<snippet, image file name>.
67 typedef vector<StrPair> BitmapFile;
69 string const unique_filename(string const bufferpath);
71 Converter const * setConverter();
73 void setAscentFractions(vector<double> & ascent_fractions,
74 string const & metrics_file);
77 FindFirst(string const & comp) : comp_(comp) {}
78 bool operator()(StrPair const & sp)
80 return sp.first == comp_;
87 /// Store info on a currently executing, forked process.
90 InProgress() : pid(0) {}
92 InProgress(string const & filename_base,
93 PendingSnippets const & pending,
94 string const & to_format);
95 /// Remove any files left lying around and kill the forked process.
108 typedef map<pid_t, InProgress> InProgressProcesses;
110 typedef InProgressProcesses::value_type InProgressProcess;
117 struct PreviewLoader::Impl : public boost::signals::trackable {
119 Impl(PreviewLoader & p, Buffer const & b);
120 /// Stop any InProgress items still executing.
123 PreviewImage const * preview(string const & latex_snippet) const;
125 PreviewLoader::Status status(string const & latex_snippet) const;
127 void add(string const & latex_snippet);
129 void remove(string const & latex_snippet);
133 /// Emit this signal when an image is ready for display.
134 boost::signal1<void, PreviewImage const &> imageReady;
136 Buffer const & buffer() const { return buffer_; }
139 /// Called by the Forkedcall process that generated the bitmap files.
140 void finishedGenerating(pid_t, int);
142 void dumpPreamble(ostream &) const;
144 void dumpData(ostream &, BitmapFile const &) const;
146 /** cache_ allows easy retrieval of already-generated images
147 * using the LaTeX snippet as the identifier.
149 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
151 typedef map<string, PreviewImagePtr> Cache;
155 /** pending_ stores the LaTeX snippets in anticipation of them being
156 * sent to the converter.
158 PendingSnippets pending_;
160 /** in_progress_ stores all forked processes so that we can proceed
162 The map uses the conversion commands as its identifiers.
164 InProgressProcesses in_progress_;
167 PreviewLoader & parent_;
169 Buffer const & buffer_;
171 double font_scaling_factor_;
173 /// We don't own this
174 static Converter const * pconverter_;
178 Converter const * PreviewLoader::Impl::pconverter_;
181 // The public interface, defined in PreviewLoader.h
182 // ================================================
183 PreviewLoader::PreviewLoader(Buffer const & b)
184 : pimpl_(new Impl(*this, b))
188 PreviewLoader::~PreviewLoader()
192 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
194 return pimpl_->preview(latex_snippet);
198 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
200 return pimpl_->status(latex_snippet);
204 void PreviewLoader::add(string const & latex_snippet) const
206 pimpl_->add(latex_snippet);
210 void PreviewLoader::remove(string const & latex_snippet) const
212 pimpl_->remove(latex_snippet);
216 void PreviewLoader::startLoading() const
218 pimpl_->startLoading();
222 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
224 return pimpl_->imageReady.connect(slot);
228 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
230 pimpl_->imageReady(pimage);
234 Buffer const & PreviewLoader::buffer() const
236 return pimpl_->buffer();
242 // The details of the Impl
243 // =======================
247 struct IncrementedFileName {
248 IncrementedFileName(string const & to_format,
249 string const & filename_base)
250 : to_format_(to_format), base_(filename_base), counter_(1)
253 StrPair const operator()(string const & snippet)
256 os << base_ << counter_++ << '.' << to_format_;
257 string const file = STRCONV(os.str());
259 return make_pair(snippet, file);
263 string const & to_format_;
264 string const & base_;
269 InProgress::InProgress(string const & filename_base,
270 PendingSnippets const & pending,
271 string const & to_format)
273 metrics_file(filename_base + ".metrics"),
274 snippets(pending.size())
276 PendingSnippets::const_iterator pit = pending.begin();
277 PendingSnippets::const_iterator pend = pending.end();
278 BitmapFile::iterator sit = snippets.begin();
280 std::transform(pit, pend, sit,
281 IncrementedFileName(to_format, filename_base));
285 void InProgress::stop() const
288 ForkedcallsController::get().kill(pid, 0);
290 if (!metrics_file.empty())
291 lyx::unlink(metrics_file);
293 BitmapFile::const_iterator vit = snippets.begin();
294 BitmapFile::const_iterator vend = snippets.end();
295 for (; vit != vend; ++vit) {
296 if (!vit->second.empty())
297 lyx::unlink(vit->second);
306 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
307 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
309 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
310 lyxrc.preview_scale_factor;
312 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
313 << font_scaling_factor_ << endl;
316 pconverter_ = setConverter();
320 PreviewLoader::Impl::~Impl()
322 InProgressProcesses::iterator ipit = in_progress_.begin();
323 InProgressProcesses::iterator ipend = in_progress_.end();
325 for (; ipit != ipend; ++ipit) {
332 PreviewLoader::Impl::preview(string const & latex_snippet) const
334 Cache::const_iterator it = cache_.find(latex_snippet);
335 return (it == cache_.end()) ? 0 : it->second.get();
342 FindSnippet(string const & s) : snippet_(s) {}
343 bool operator()(InProgressProcess const & process)
345 BitmapFile const & snippets = process.second.snippets;
346 BitmapFile::const_iterator it = snippets.begin();
347 BitmapFile::const_iterator end = snippets.end();
348 it = find_if(it, end, FindFirst(snippet_));
353 string const & snippet_;
358 PreviewLoader::Status
359 PreviewLoader::Impl::status(string const & latex_snippet) const
361 Cache::const_iterator cit = cache_.find(latex_snippet);
362 if (cit != cache_.end())
365 PendingSnippets::const_iterator pit = pending_.begin();
366 PendingSnippets::const_iterator pend = pending_.end();
368 pit = find(pit, pend, latex_snippet);
372 InProgressProcesses::const_iterator ipit = in_progress_.begin();
373 InProgressProcesses::const_iterator ipend = in_progress_.end();
375 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
383 void PreviewLoader::Impl::add(string const & latex_snippet)
385 if (!pconverter_ || status(latex_snippet) != NotFound)
388 string const snippet = trim(latex_snippet);
392 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
394 pending_.push_back(snippet);
400 struct EraseSnippet {
401 EraseSnippet(string const & s) : snippet_(s) {}
402 void operator()(InProgressProcess & process)
404 BitmapFile & snippets = process.second.snippets;
405 BitmapFile::iterator it = snippets.begin();
406 BitmapFile::iterator end = snippets.end();
408 it = find_if(it, end, FindFirst(snippet_));
410 snippets.erase(it, it+1);
414 string const & snippet_;
420 void PreviewLoader::Impl::remove(string const & latex_snippet)
422 Cache::iterator cit = cache_.find(latex_snippet);
423 if (cit != cache_.end())
426 PendingSnippets::iterator pit = pending_.begin();
427 PendingSnippets::iterator pend = pending_.end();
429 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
431 InProgressProcesses::iterator ipit = in_progress_.begin();
432 InProgressProcesses::iterator ipend = in_progress_.end();
434 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
436 for (; ipit != ipend; ++ipit) {
437 InProgressProcesses::iterator curr = ipit++;
438 if (curr->second.snippets.empty())
439 in_progress_.erase(curr);
444 void PreviewLoader::Impl::startLoading()
446 if (pending_.empty() || !pconverter_)
449 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
451 // As used by the LaTeX file and by the resulting image files
452 string const filename_base(unique_filename(buffer_.tmppath));
454 // Create an InProgress instance to place in the map of all
455 // such processes if it starts correctly.
456 InProgress inprogress(filename_base, pending_, pconverter_->to);
458 // clear pending_, so we're ready to start afresh.
461 // Output the LaTeX file.
462 string const latexfile = filename_base + ".tex";
464 ofstream of(latexfile.c_str());
465 of << "\\batchmode\n";
467 of << "\n\\begin{document}\n";
468 dumpData(of, inprogress.snippets);
469 of << "\n\\end{document}\n";
472 // The conversion command.
474 cs << pconverter_->command << ' ' << latexfile << ' '
475 << int(font_scaling_factor_) << ' ' << pconverter_->to;
477 string const command = "sh " + LibScriptSearch(STRCONV(cs.str()));
479 // Initiate the conversion from LaTeX to bitmap images files.
480 Forkedcall::SignalTypePtr convert_ptr(new Forkedcall::SignalType);
481 convert_ptr->connect(
482 boost::bind(&Impl::finishedGenerating, this, _1, _2));
485 int ret = call.startscript(command, convert_ptr);
488 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
489 << "Unable to start process \n"
494 // Store the generation process in a list of all such processes
495 inprogress.pid = call.pid();
496 inprogress.command = command;
497 in_progress_[inprogress.pid] = inprogress;
501 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
504 InProgressProcesses::iterator git = in_progress_.find(pid);
505 if (git == in_progress_.end()) {
506 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
507 "data for PID " << pid << endl;
511 string const command = git->second.command;
512 string const status = retval > 0 ? "failed" : "succeeded";
513 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
514 << retval << "): processing " << status
515 << " for " << command << endl;
519 // Read the metrics file, if it exists
520 vector<double> ascent_fractions(git->second.snippets.size());
521 setAscentFractions(ascent_fractions, git->second.metrics_file);
523 // Add these newly generated bitmap files to the cache and
524 // start loading them into LyX.
525 BitmapFile::const_iterator it = git->second.snippets.begin();
526 BitmapFile::const_iterator end = git->second.snippets.end();
528 std::list<PreviewImagePtr> newimages;
530 int metrics_counter = 0;
531 for (; it != end; ++it, ++metrics_counter) {
532 string const & snip = it->first;
533 string const & file = it->second;
534 double af = ascent_fractions[metrics_counter];
536 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
539 newimages.push_back(ptr);
542 // Remove the item from the list of still-executing processes.
543 in_progress_.erase(git);
545 // Tell the outside world
546 std::list<PreviewImagePtr>::const_reverse_iterator
547 nit = newimages.rbegin();
548 std::list<PreviewImagePtr>::const_reverse_iterator
549 nend = newimages.rend();
550 for (; nit != nend; ++nit) {
551 imageReady(*nit->get());
556 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
558 // Why on earth is Buffer::makeLaTeXFile a non-const method?
559 Buffer & tmp = const_cast<Buffer &>(buffer_);
560 // Dump the preamble only.
561 tmp.makeLaTeXFile(os, buffer_.filePath(), true, false, true);
563 // FIXME! This is a HACK! The proper fix is to control the 'true'
564 // passed to WriteStream below:
565 // int InsetFormula::latex(Buffer const *, ostream & os,
566 // bool fragile, bool) const
568 // WriteStream wi(os, fragile, true);
573 << "\\def\\lyxlock{}\n"
576 // Loop over the insets in the buffer and dump all the math-macros.
577 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
578 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
580 for (; it != end; ++it)
581 if (it->lyxCode() == Inset::MATHMACRO_CODE)
582 it->latex(&buffer_, os, true, true);
584 // All equation lables appear as "(#)" + preview.sty's rendering of
586 if (lyxrc.preview_hashed_labels)
587 os << "\\renewcommand{\\theequation}{\\#}\n";
589 // Use the preview style file to ensure that each snippet appears on a
592 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
595 // This piece of PostScript magic ensures that the foreground and
596 // background colors are the same as the LyX screen.
597 string fg = lyx_gui::hexname(LColor::preview);
598 if (fg.empty()) fg = "000000";
600 string bg = lyx_gui::hexname(LColor::background);
601 if (bg.empty()) bg = "ffffff";
603 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
604 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
605 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
606 << "clippath fill setrgbcolor}bind def end}}}\n";
610 void PreviewLoader::Impl::dumpData(ostream & os,
611 BitmapFile const & vec) const
616 BitmapFile::const_iterator it = vec.begin();
617 BitmapFile::const_iterator end = vec.end();
619 for (; it != end; ++it) {
620 os << "\\begin{preview}\n"
622 << "\n\\end{preview}\n\n";
631 string const unique_filename(string const bufferpath)
633 static int theCounter = 0;
634 string const filename = tostr(theCounter++) + "lyxpreview";
635 return AddName(bufferpath, filename);
639 Converter const * setConverter()
641 string const from = "lyxpreview";
643 Formats::FormatList::const_iterator it = formats.begin();
644 Formats::FormatList::const_iterator end = formats.end();
646 for (; it != end; ++it) {
647 string const to = it->name();
651 Converter const * ptr = converters.getConverter(from, to);
656 static bool first = true;
659 lyxerr << "PreviewLoader::startLoading()\n"
660 << "No converter from \"lyxpreview\" format has been "
669 void setAscentFractions(vector<double> & ascent_fractions,
670 string const & metrics_file)
672 // If all else fails, then the images will have equal ascents and
674 vector<double>::iterator it = ascent_fractions.begin();
675 vector<double>::iterator end = ascent_fractions.end();
678 ifstream in(metrics_file.c_str());
680 lyxerr[Debug::GRAPHICS]
681 << "setAscentFractions(" << metrics_file << ")\n"
682 << "Unable to open file!" << endl;
688 // Tightpage dimensions affect all subsequent dimensions
692 int snippet_counter = 0;
694 // Expecting lines of the form
695 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
696 // Preview: Snippet id ascent descent width
699 in >> preview >> type;
705 error = preview != "Preview:"
706 || (type != "Tightpage" && type != "Snippet");
710 if (type == "Tightpage") {
712 in >> dummy >> tp_descent >> dummy >> tp_ascent;
723 in >> snippet_id >> ascent >> descent >> dummy;
725 error = !in.good() || ++snippet_counter != snippet_id;
729 double const a = ascent + tp_ascent;
730 double const d = descent - tp_descent;
732 if (!lyx::float_equal(a + d, 0, 0.1))
741 lyxerr[Debug::GRAPHICS]
742 << "setAscentFractions(" << metrics_file << ")\n"
743 << "Error reading file!\n" << endl;