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"
24 #include "insets/inset.h"
26 #include "frontends/lyx_gui.h" // hexname
28 #include "support/filetools.h"
29 #include "support/forkedcall.h"
30 #include "support/forkedcontr.h"
31 #include "support/tostr.h"
32 #include "support/lstrings.h"
33 #include "support/lyxlib.h"
35 #include <boost/bind.hpp>
36 #include <boost/signals/trackable.hpp>
45 using namespace lyx::support;
66 typedef pair<string, string> StrPair;
68 // A list of alll snippets to be converted to previews
69 typedef list<string> PendingSnippets;
71 // Each item in the vector is a pair<snippet, image file name>.
72 typedef vector<StrPair> BitmapFile;
74 string const unique_filename(string const bufferpath);
76 Converter const * setConverter();
78 void setAscentFractions(vector<double> & ascent_fractions,
79 string const & metrics_file);
82 FindFirst(string const & comp) : comp_(comp) {}
83 bool operator()(StrPair const & sp)
85 return sp.first == comp_;
92 /// Store info on a currently executing, forked process.
95 InProgress() : pid(0) {}
97 InProgress(string const & filename_base,
98 PendingSnippets const & pending,
99 string const & to_format);
100 /// Remove any files left lying around and kill the forked process.
113 typedef map<pid_t, InProgress> InProgressProcesses;
115 typedef InProgressProcesses::value_type InProgressProcess;
122 struct PreviewLoader::Impl : public boost::signals::trackable {
124 Impl(PreviewLoader & p, Buffer const & b);
125 /// Stop any InProgress items still executing.
128 PreviewImage const * preview(string const & latex_snippet) const;
130 PreviewLoader::Status status(string const & latex_snippet) const;
132 void add(string const & latex_snippet);
134 void remove(string const & latex_snippet);
138 /// Emit this signal when an image is ready for display.
139 boost::signal1<void, PreviewImage const &> imageReady;
141 Buffer const & buffer() const { return buffer_; }
144 /// Called by the Forkedcall process that generated the bitmap files.
145 void finishedGenerating(pid_t, int);
147 void dumpPreamble(ostream &) const;
149 void dumpData(ostream &, BitmapFile const &) const;
151 /** cache_ allows easy retrieval of already-generated images
152 * using the LaTeX snippet as the identifier.
154 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
156 typedef map<string, PreviewImagePtr> Cache;
160 /** pending_ stores the LaTeX snippets in anticipation of them being
161 * sent to the converter.
163 PendingSnippets pending_;
165 /** in_progress_ stores all forked processes so that we can proceed
167 The map uses the conversion commands as its identifiers.
169 InProgressProcesses in_progress_;
172 PreviewLoader & parent_;
174 Buffer const & buffer_;
176 double font_scaling_factor_;
178 /// We don't own this
179 static Converter const * pconverter_;
183 Converter const * PreviewLoader::Impl::pconverter_;
186 // The public interface, defined in PreviewLoader.h
187 // ================================================
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) const
211 pimpl_->add(latex_snippet);
215 void PreviewLoader::remove(string const & latex_snippet) const
217 pimpl_->remove(latex_snippet);
221 void PreviewLoader::startLoading() const
223 pimpl_->startLoading();
227 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
229 return pimpl_->imageReady.connect(slot);
233 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
235 pimpl_->imageReady(pimage);
239 Buffer const & PreviewLoader::buffer() const
241 return pimpl_->buffer();
247 // The details of the Impl
248 // =======================
252 struct IncrementedFileName {
253 IncrementedFileName(string const & to_format,
254 string const & filename_base)
255 : to_format_(to_format), base_(filename_base), counter_(1)
258 StrPair const operator()(string const & snippet)
261 os << base_ << counter_++ << '.' << to_format_;
262 string const file = STRCONV(os.str());
264 return make_pair(snippet, file);
268 string const & to_format_;
269 string const & base_;
274 InProgress::InProgress(string const & filename_base,
275 PendingSnippets const & pending,
276 string const & to_format)
278 metrics_file(filename_base + ".metrics"),
279 snippets(pending.size())
281 PendingSnippets::const_iterator pit = pending.begin();
282 PendingSnippets::const_iterator pend = pending.end();
283 BitmapFile::iterator sit = snippets.begin();
285 std::transform(pit, pend, sit,
286 IncrementedFileName(to_format, filename_base));
290 void InProgress::stop() const
293 ForkedcallsController::get().kill(pid, 0);
295 if (!metrics_file.empty())
296 unlink(metrics_file);
298 BitmapFile::const_iterator vit = snippets.begin();
299 BitmapFile::const_iterator vend = snippets.end();
300 for (; vit != vend; ++vit) {
301 if (!vit->second.empty())
311 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
312 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
314 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
315 lyxrc.preview_scale_factor;
317 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
318 << font_scaling_factor_ << endl;
321 pconverter_ = setConverter();
325 PreviewLoader::Impl::~Impl()
327 InProgressProcesses::iterator ipit = in_progress_.begin();
328 InProgressProcesses::iterator ipend = in_progress_.end();
330 for (; ipit != ipend; ++ipit) {
337 PreviewLoader::Impl::preview(string const & latex_snippet) const
339 Cache::const_iterator it = cache_.find(latex_snippet);
340 return (it == cache_.end()) ? 0 : it->second.get();
347 FindSnippet(string const & s) : snippet_(s) {}
348 bool operator()(InProgressProcess const & process)
350 BitmapFile const & snippets = process.second.snippets;
351 BitmapFile::const_iterator it = snippets.begin();
352 BitmapFile::const_iterator end = snippets.end();
353 it = find_if(it, end, FindFirst(snippet_));
358 string const & snippet_;
363 PreviewLoader::Status
364 PreviewLoader::Impl::status(string const & latex_snippet) const
366 Cache::const_iterator cit = cache_.find(latex_snippet);
367 if (cit != cache_.end())
370 PendingSnippets::const_iterator pit = pending_.begin();
371 PendingSnippets::const_iterator pend = pending_.end();
373 pit = find(pit, pend, latex_snippet);
377 InProgressProcesses::const_iterator ipit = in_progress_.begin();
378 InProgressProcesses::const_iterator ipend = in_progress_.end();
380 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
388 void PreviewLoader::Impl::add(string const & latex_snippet)
390 if (!pconverter_ || status(latex_snippet) != NotFound)
393 string const snippet = trim(latex_snippet);
397 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
399 pending_.push_back(snippet);
405 struct EraseSnippet {
406 EraseSnippet(string const & s) : snippet_(s) {}
407 void operator()(InProgressProcess & process)
409 BitmapFile & snippets = process.second.snippets;
410 BitmapFile::iterator it = snippets.begin();
411 BitmapFile::iterator end = snippets.end();
413 it = find_if(it, end, FindFirst(snippet_));
415 snippets.erase(it, it+1);
419 string const & snippet_;
425 void PreviewLoader::Impl::remove(string const & latex_snippet)
427 Cache::iterator cit = cache_.find(latex_snippet);
428 if (cit != cache_.end())
431 PendingSnippets::iterator pit = pending_.begin();
432 PendingSnippets::iterator pend = pending_.end();
434 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
436 InProgressProcesses::iterator ipit = in_progress_.begin();
437 InProgressProcesses::iterator ipend = in_progress_.end();
439 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
441 for (; ipit != ipend; ++ipit) {
442 InProgressProcesses::iterator curr = ipit++;
443 if (curr->second.snippets.empty())
444 in_progress_.erase(curr);
449 void PreviewLoader::Impl::startLoading()
451 if (pending_.empty() || !pconverter_)
454 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
456 // As used by the LaTeX file and by the resulting image files
457 string directory = buffer_.tmppath;
458 if (directory.empty())
459 directory = buffer_.filePath();
461 string const filename_base(unique_filename(directory));
463 // Create an InProgress instance to place in the map of all
464 // such processes if it starts correctly.
465 InProgress inprogress(filename_base, pending_, pconverter_->to);
467 // clear pending_, so we're ready to start afresh.
470 // Output the LaTeX file.
471 string const latexfile = filename_base + ".tex";
473 ofstream of(latexfile.c_str());
474 of << "\\batchmode\n";
476 of << "\n\\begin{document}\n";
477 dumpData(of, inprogress.snippets);
478 of << "\n\\end{document}\n";
481 // The conversion command.
483 cs << pconverter_->command << ' ' << latexfile << ' '
484 << int(font_scaling_factor_) << ' ' << pconverter_->to;
486 string const command = "sh " + LibScriptSearch(STRCONV(cs.str()));
488 // Initiate the conversion from LaTeX to bitmap images files.
489 Forkedcall::SignalTypePtr convert_ptr(new Forkedcall::SignalType);
490 convert_ptr->connect(
491 boost::bind(&Impl::finishedGenerating, this, _1, _2));
494 int ret = call.startscript(command, convert_ptr);
497 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
498 << "Unable to start process \n"
503 // Store the generation process in a list of all such processes
504 inprogress.pid = call.pid();
505 inprogress.command = command;
506 in_progress_[inprogress.pid] = inprogress;
510 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
513 InProgressProcesses::iterator git = in_progress_.find(pid);
514 if (git == in_progress_.end()) {
515 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
516 "data for PID " << pid << endl;
520 string const command = git->second.command;
521 string const status = retval > 0 ? "failed" : "succeeded";
522 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
523 << retval << "): processing " << status
524 << " for " << command << endl;
528 // Read the metrics file, if it exists
529 vector<double> ascent_fractions(git->second.snippets.size());
530 setAscentFractions(ascent_fractions, git->second.metrics_file);
532 // Add these newly generated bitmap files to the cache and
533 // start loading them into LyX.
534 BitmapFile::const_iterator it = git->second.snippets.begin();
535 BitmapFile::const_iterator end = git->second.snippets.end();
537 std::list<PreviewImagePtr> newimages;
539 int metrics_counter = 0;
540 for (; it != end; ++it, ++metrics_counter) {
541 string const & snip = it->first;
542 string const & file = it->second;
543 double af = ascent_fractions[metrics_counter];
545 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
548 newimages.push_back(ptr);
551 // Remove the item from the list of still-executing processes.
552 in_progress_.erase(git);
554 // Tell the outside world
555 std::list<PreviewImagePtr>::const_reverse_iterator
556 nit = newimages.rbegin();
557 std::list<PreviewImagePtr>::const_reverse_iterator
558 nend = newimages.rend();
559 for (; nit != nend; ++nit) {
560 imageReady(*nit->get());
565 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
567 // Why on earth is Buffer::makeLaTeXFile a non-const method?
568 Buffer & tmp = const_cast<Buffer &>(buffer_);
569 // Dump the preamble only.
570 LatexRunParams runparams;
571 runparams.flavor = LatexRunParams::LATEX;
572 runparams.nice = true;
573 runparams.moving_arg = true;
574 runparams.free_spacing = true;
575 tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, false, true);
577 // FIXME! This is a HACK! The proper fix is to control the 'true'
578 // passed to WriteStream below:
579 // int InsetFormula::latex(Buffer const *, ostream & os,
580 // LatexRunParams const & runparams) const
582 // WriteStream wi(os, runparams.moving_arg, true);
587 << "\\def\\lyxlock{}\n"
590 // Loop over the insets in the buffer and dump all the math-macros.
591 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
592 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
594 for (; it != end; ++it)
595 if (it->lyxCode() == Inset::MATHMACRO_CODE)
596 it->latex(&buffer_, os, runparams);
598 // All equation lables appear as "(#)" + preview.sty's rendering of
600 if (lyxrc.preview_hashed_labels)
601 os << "\\renewcommand{\\theequation}{\\#}\n";
603 // Use the preview style file to ensure that each snippet appears on a
606 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
609 // This piece of PostScript magic ensures that the foreground and
610 // background colors are the same as the LyX screen.
611 string fg = lyx_gui::hexname(LColor::preview);
612 if (fg.empty()) fg = "000000";
614 string bg = lyx_gui::hexname(LColor::background);
615 if (bg.empty()) bg = "ffffff";
617 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
618 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
619 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
620 << "clippath fill setrgbcolor}bind def end}}}\n";
624 void PreviewLoader::Impl::dumpData(ostream & os,
625 BitmapFile const & vec) const
630 BitmapFile::const_iterator it = vec.begin();
631 BitmapFile::const_iterator end = vec.end();
633 for (; it != end; ++it) {
634 os << "\\begin{preview}\n"
636 << "\n\\end{preview}\n\n";
645 string const unique_filename(string const bufferpath)
647 static int theCounter = 0;
648 string const filename = tostr(theCounter++) + "lyxpreview";
649 return AddName(bufferpath, filename);
653 Converter const * setConverter()
655 string const from = "lyxpreview";
657 Formats::FormatList::const_iterator it = formats.begin();
658 Formats::FormatList::const_iterator end = formats.end();
660 for (; it != end; ++it) {
661 string const to = it->name();
665 Converter const * ptr = converters.getConverter(from, to);
670 static bool first = true;
673 lyxerr << "PreviewLoader::startLoading()\n"
674 << "No converter from \"lyxpreview\" format has been "
683 void setAscentFractions(vector<double> & ascent_fractions,
684 string const & metrics_file)
686 // If all else fails, then the images will have equal ascents and
688 vector<double>::iterator it = ascent_fractions.begin();
689 vector<double>::iterator end = ascent_fractions.end();
692 ifstream in(metrics_file.c_str());
694 lyxerr[Debug::GRAPHICS]
695 << "setAscentFractions(" << metrics_file << ")\n"
696 << "Unable to open file!" << endl;
702 // Tightpage dimensions affect all subsequent dimensions
706 int snippet_counter = 0;
708 // Expecting lines of the form
709 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
710 // Preview: Snippet id ascent descent width
713 in >> preview >> type;
719 error = preview != "Preview:"
720 || (type != "Tightpage" && type != "Snippet");
724 if (type == "Tightpage") {
726 in >> dummy >> tp_descent >> dummy >> tp_ascent;
737 in >> snippet_id >> ascent >> descent >> dummy;
739 error = !in.good() || ++snippet_counter != snippet_id;
743 double const a = ascent + tp_ascent;
744 double const d = descent - tp_descent;
746 if (!float_equal(a + d, 0, 0.1))
755 lyxerr[Debug::GRAPHICS]
756 << "setAscentFractions(" << metrics_file << ")\n"
757 << "Error reading file!\n" << endl;