2 * \file PreviewLoader.C
3 * Read the file COPYING
5 * \author Angus Leeming
7 * Full author contact details available in file CREDITS
13 #pragma implementation
16 #include "PreviewLoader.h"
17 #include "PreviewImage.h"
20 #include "converter.h"
25 #include "insets/inset.h"
27 #include "frontends/lyx_gui.h" // hexname
29 #include "support/filetools.h"
30 #include "support/forkedcall.h"
31 #include "support/forkedcontr.h"
32 #include "support/lstrings.h"
33 #include "support/lyxlib.h"
35 #include <boost/bind.hpp>
36 #include <boost/signals/trackable.hpp>
64 typedef pair<string, string> StrPair;
66 // A list of alll snippets to be converted to previews
67 typedef list<string> PendingSnippets;
69 // Each item in the vector is a pair<snippet, image file name>.
70 typedef vector<StrPair> BitmapFile;
72 string const unique_filename(string const bufferpath);
74 Converter const * setConverter();
76 void setAscentFractions(vector<double> & ascent_fractions,
77 string const & metrics_file);
80 FindFirst(string const & comp) : comp_(comp) {}
81 bool operator()(StrPair const & sp)
83 return sp.first < comp_;
90 /// Store info on a currently executing, forked process.
93 InProgress() : pid(0) {}
95 InProgress(string const & filename_base,
96 PendingSnippets const & pending,
97 string const & to_format);
98 /// Remove any files left lying around and kill the forked process.
109 typedef map<string, InProgress> InProgressProcesses;
111 typedef InProgressProcesses::value_type InProgressProcess;
118 struct PreviewLoader::Impl : public boost::signals::trackable {
120 Impl(PreviewLoader & p, Buffer const & b);
121 /// Stop any InProgress items still executing.
124 PreviewImage const * preview(string const & latex_snippet) const;
126 PreviewLoader::Status status(string const & latex_snippet) const;
128 void add(string const & latex_snippet);
130 void remove(string const & latex_snippet);
134 /// Emit this signal when an image is ready for display.
135 boost::signal1<void, PreviewImage const &> imageReady;
137 Buffer const & buffer() const { return buffer_; }
140 /// Called by the Forkedcall process that generated the bitmap files.
141 void finishedGenerating(string const &, pid_t, int);
143 void dumpPreamble(ostream &) const;
145 void dumpData(ostream &, BitmapFile const &) const;
147 /** cache_ allows easy retrieval of already-generated images
148 * using the LaTeX snippet as the identifier.
150 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
152 typedef map<string, PreviewImagePtr> Cache;
156 /** pending_ stores the LaTeX snippets in anticipation of them being
157 * sent to the converter.
159 PendingSnippets pending_;
161 /** in_progress_ stores all forked processes so that we can proceed
163 The map uses the conversion commands as its identifiers.
165 InProgressProcesses in_progress_;
168 PreviewLoader & parent_;
170 Buffer const & buffer_;
172 double font_scaling_factor_;
174 /// We don't own this
175 static Converter const * pconverter_;
179 Converter const * PreviewLoader::Impl::pconverter_;
182 // The public interface, defined in PreviewLoader.h
183 // ================================================
184 PreviewLoader::PreviewLoader(Buffer const & b)
185 : pimpl_(new Impl(*this, b))
189 PreviewLoader::~PreviewLoader()
193 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
195 return pimpl_->preview(latex_snippet);
199 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
201 return pimpl_->status(latex_snippet);
205 void PreviewLoader::add(string const & latex_snippet) const
207 pimpl_->add(latex_snippet);
211 void PreviewLoader::remove(string const & latex_snippet) const
213 pimpl_->remove(latex_snippet);
217 void PreviewLoader::startLoading() const
219 pimpl_->startLoading();
223 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
225 return pimpl_->imageReady.connect(slot);
229 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
231 pimpl_->imageReady(pimage);
235 Buffer const & PreviewLoader::buffer() const
237 return pimpl_->buffer();
243 // The details of the Impl
244 // =======================
248 struct IncrementedFileName {
249 IncrementedFileName(string const & to_format,
250 string const & filename_base)
251 : to_format_(to_format), base_(filename_base), counter_(1)
254 StrPair const operator()(string const & snippet)
257 os << base_ << counter_++ << "." << to_format_;
258 string const file = os.str().c_str();
260 return make_pair(snippet, file);
264 string const & to_format_;
265 string const & base_;
270 InProgress::InProgress(string const & filename_base,
271 PendingSnippets const & pending,
272 string const & to_format)
274 metrics_file(filename_base + ".metrics"),
275 snippets(pending.size())
277 PendingSnippets::const_iterator pit = pending.begin();
278 PendingSnippets::const_iterator pend = pending.end();
279 BitmapFile::iterator sit = snippets.begin();
281 std::transform(pit, pend, sit,
282 IncrementedFileName(to_format, filename_base));
286 void InProgress::stop() const
289 ForkedcallsController::get().kill(pid, 0);
291 if (!metrics_file.empty())
292 lyx::unlink(metrics_file);
294 BitmapFile::const_iterator vit = snippets.begin();
295 BitmapFile::const_iterator vend = snippets.end();
296 for (; vit != vend; ++vit) {
297 if (!vit->second.empty())
298 lyx::unlink(vit->second);
307 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
308 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
310 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
311 lyxrc.preview_scale_factor;
313 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
314 << font_scaling_factor_ << endl;
317 pconverter_ = setConverter();
321 PreviewLoader::Impl::~Impl()
323 InProgressProcesses::iterator ipit = in_progress_.begin();
324 InProgressProcesses::iterator ipend = in_progress_.end();
326 for (; ipit != ipend; ++ipit) {
333 PreviewLoader::Impl::preview(string const & latex_snippet) const
335 Cache::const_iterator it = cache_.find(latex_snippet);
336 return (it == cache_.end()) ? 0 : it->second.get();
343 FindSnippet(string const & s) : snippet_(s) {}
344 bool operator()(InProgressProcess const & process)
346 BitmapFile const & snippets = process.second.snippets;
347 BitmapFile::const_iterator it = snippets.begin();
348 BitmapFile::const_iterator end = snippets.end();
349 it = find_if(it, end, FindFirst(snippet_));
354 string const & snippet_;
359 PreviewLoader::Status
360 PreviewLoader::Impl::status(string const & latex_snippet) const
362 Cache::const_iterator cit = cache_.find(latex_snippet);
363 if (cit != cache_.end())
366 PendingSnippets::const_iterator pit = pending_.begin();
367 PendingSnippets::const_iterator pend = pending_.end();
369 pit = find(pit, pend, latex_snippet);
373 InProgressProcesses::const_iterator ipit = in_progress_.begin();
374 InProgressProcesses::const_iterator ipend = in_progress_.end();
376 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
384 void PreviewLoader::Impl::add(string const & latex_snippet)
386 if (!pconverter_ || status(latex_snippet) != NotFound)
389 string const snippet = trim(latex_snippet);
393 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
395 pending_.push_back(snippet);
401 struct EraseSnippet {
402 EraseSnippet(string const & s) : snippet_(s) {}
403 void operator()(InProgressProcess & process)
405 BitmapFile & snippets = process.second.snippets;
406 BitmapFile::iterator it = snippets.begin();
407 BitmapFile::iterator end = snippets.end();
409 it = find_if(it, end, FindFirst(snippet_));
411 snippets.erase(it, it+1);
415 string const & snippet_;
421 void PreviewLoader::Impl::remove(string const & latex_snippet)
423 Cache::iterator cit = cache_.find(latex_snippet);
424 if (cit != cache_.end())
427 PendingSnippets::iterator pit = pending_.begin();
428 PendingSnippets::iterator pend = pending_.end();
430 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
432 InProgressProcesses::iterator ipit = in_progress_.begin();
433 InProgressProcesses::iterator ipend = in_progress_.end();
435 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
437 for (; ipit != ipend; ++ipit) {
438 InProgressProcesses::iterator curr = ipit++;
439 if (curr->second.snippets.empty())
440 in_progress_.erase(curr);
445 void PreviewLoader::Impl::startLoading()
447 if (pending_.empty() || !pconverter_)
450 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
452 // As used by the LaTeX file and by the resulting image files
453 string const filename_base(unique_filename(buffer_.tmppath));
455 // Create an InProgress instance to place in the map of all
456 // such processes if it starts correctly.
457 InProgress inprogress(filename_base, pending_, pconverter_->to);
459 // clear pending_, so we're ready to start afresh.
462 // Output the LaTeX file.
463 string const latexfile = filename_base + ".tex";
465 ofstream of(latexfile.c_str());
466 of << "\\batchmode\n";
468 of << "\n\\begin{document}\n";
469 dumpData(of, inprogress.snippets);
470 of << "\n\\end{document}\n";
473 // The conversion command.
475 cs << pconverter_->command << " " << latexfile << " "
476 << int(font_scaling_factor_) << " " << pconverter_->to;
478 string const command = "sh " + LibScriptSearch(cs.str().c_str());
480 // Initiate the conversion from LaTeX to bitmap images files.
481 Forkedcall::SignalTypePtr convert_ptr;
482 convert_ptr.reset(new Forkedcall::SignalType);
484 convert_ptr->connect(
485 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
488 int ret = call.startscript(command, convert_ptr);
491 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
492 << "Unable to start process \n"
497 // Store the generation process in a list of all such processes
498 inprogress.pid = call.pid();
499 in_progress_[command] = inprogress;
503 void PreviewLoader::Impl::finishedGenerating(string const & command,
504 pid_t /* pid */, int retval)
506 string const status = retval > 0 ? "failed" : "succeeded";
507 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
508 << retval << "): processing " << status
509 << " for " << command << endl;
514 InProgressProcesses::iterator git = in_progress_.find(command);
515 if (git == in_progress_.end()) {
516 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
518 << command << "!" << endl;
522 // Read the metrics file, if it exists
523 vector<double> ascent_fractions(git->second.snippets.size());
524 setAscentFractions(ascent_fractions, git->second.metrics_file);
526 // Add these newly generated bitmap files to the cache and
527 // start loading them into LyX.
528 BitmapFile::const_iterator it = git->second.snippets.begin();
529 BitmapFile::const_iterator end = git->second.snippets.end();
531 std::list<PreviewImagePtr> newimages;
533 int metrics_counter = 0;
534 for (; it != end; ++it, ++metrics_counter) {
535 string const & snip = it->first;
536 string const & file = it->second;
537 double af = ascent_fractions[metrics_counter];
539 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
542 newimages.push_back(ptr);
545 // Remove the item from the list of still-executing processes.
546 in_progress_.erase(git);
548 // Tell the outside world
549 std::list<PreviewImagePtr>::const_iterator nit = newimages.begin();
550 std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
551 for (; nit != nend; ++nit) {
552 imageReady(*nit->get());
557 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
559 // Why on earth is Buffer::makeLaTeXFile a non-const method?
560 Buffer & tmp = const_cast<Buffer &>(buffer_);
561 // Dump the preamble only.
562 tmp.makeLaTeXFile(os, buffer_.filePath(), true, false, true);
564 // Loop over the insets in the buffer and dump all the math-macros.
565 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
566 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
568 for (; it != end; ++it)
569 if (it->lyxCode() == Inset::MATHMACRO_CODE)
570 it->latex(&buffer_, os, true, true);
572 // All equation lables appear as "(#)" + preview.sty's rendering of
574 if (lyxrc.preview_hashed_labels)
575 os << "\\renewcommand{\\theequation}{\\#}\n";
577 // Use the preview style file to ensure that each snippet appears on a
580 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
583 // This piece of PostScript magic ensures that the foreground and
584 // background colors are the same as the LyX screen.
585 string fg = lyx_gui::hexname(LColor::preview);
586 if (fg.empty()) fg = "000000";
588 string bg = lyx_gui::hexname(LColor::background);
589 if (bg.empty()) bg = "ffffff";
591 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
592 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
593 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
594 << "clippath fill setrgbcolor}bind def end}}}\n";
598 void PreviewLoader::Impl::dumpData(ostream & os,
599 BitmapFile const & vec) const
604 BitmapFile::const_iterator it = vec.begin();
605 BitmapFile::const_iterator end = vec.end();
607 for (; it != end; ++it) {
608 os << "\\begin{preview}\n"
610 << "\n\\end{preview}\n\n";
619 string const unique_filename(string const bufferpath)
621 static int theCounter = 0;
622 string const filename = tostr(theCounter++) + "lyxpreview";
623 return AddName(bufferpath, filename);
627 Converter const * setConverter()
629 string const from = "lyxpreview";
631 Formats::FormatList::const_iterator it = formats.begin();
632 Formats::FormatList::const_iterator end = formats.end();
634 for (; it != end; ++it) {
635 string const to = it->name();
639 Converter const * ptr = converters.getConverter(from, to);
644 static bool first = true;
647 lyxerr << "PreviewLoader::startLoading()\n"
648 << "No converter from \"lyxpreview\" format has been "
657 void setAscentFractions(vector<double> & ascent_fractions,
658 string const & metrics_file)
660 // If all else fails, then the images will have equal ascents and
662 vector<double>::iterator it = ascent_fractions.begin();
663 vector<double>::iterator end = ascent_fractions.end();
666 ifstream in(metrics_file.c_str());
668 lyxerr[Debug::GRAPHICS]
669 << "setAscentFractions(" << metrics_file << ")\n"
670 << "Unable to open file!" << endl;
676 // Tightpage dimensions affect all subsequent dimensions
680 int snippet_counter = 0;
682 // Expecting lines of the form
683 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
684 // Preview: Snippet id ascent descent width
687 in >> preview >> type;
693 error = preview != "Preview:"
694 || (type != "Tightpage" && type != "Snippet");
698 if (type == "Tightpage") {
700 in >> dummy >> tp_descent >> dummy >> tp_ascent;
711 in >> snippet_id >> ascent >> descent >> dummy;
713 error = !in.good() || ++snippet_counter != snippet_id;
717 double const a = ascent + tp_ascent;
718 double const d = descent - tp_descent;
720 if (!lyx::float_equal(a + d, 0, 0.1))
729 lyxerr[Debug::GRAPHICS]
730 << "setAscentFractions(" << metrics_file << ")\n"
731 << "Error reading file!\n" << endl;