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>
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.
111 typedef map<pid_t, InProgress> InProgressProcesses;
113 typedef InProgressProcesses::value_type InProgressProcess;
120 struct PreviewLoader::Impl : public boost::signals::trackable {
122 Impl(PreviewLoader & p, Buffer const & b);
123 /// Stop any InProgress items still executing.
126 PreviewImage const * preview(string const & latex_snippet) const;
128 PreviewLoader::Status status(string const & latex_snippet) const;
130 void add(string const & latex_snippet);
132 void remove(string const & latex_snippet);
136 /// Emit this signal when an image is ready for display.
137 boost::signal1<void, PreviewImage const &> imageReady;
139 Buffer const & buffer() const { return buffer_; }
142 /// Called by the Forkedcall process that generated the bitmap files.
143 void finishedGenerating(pid_t, int);
145 void dumpPreamble(ostream &) const;
147 void dumpData(ostream &, BitmapFile const &) const;
149 /** cache_ allows easy retrieval of already-generated images
150 * using the LaTeX snippet as the identifier.
152 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
154 typedef map<string, PreviewImagePtr> Cache;
158 /** pending_ stores the LaTeX snippets in anticipation of them being
159 * sent to the converter.
161 PendingSnippets pending_;
163 /** in_progress_ stores all forked processes so that we can proceed
165 The map uses the conversion commands as its identifiers.
167 InProgressProcesses in_progress_;
170 PreviewLoader & parent_;
172 Buffer const & buffer_;
174 double font_scaling_factor_;
176 /// We don't own this
177 static Converter const * pconverter_;
181 Converter const * PreviewLoader::Impl::pconverter_;
184 // The public interface, defined in PreviewLoader.h
185 // ================================================
186 PreviewLoader::PreviewLoader(Buffer const & b)
187 : pimpl_(new Impl(*this, b))
191 PreviewLoader::~PreviewLoader()
195 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
197 return pimpl_->preview(latex_snippet);
201 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
203 return pimpl_->status(latex_snippet);
207 void PreviewLoader::add(string const & latex_snippet) const
209 pimpl_->add(latex_snippet);
213 void PreviewLoader::remove(string const & latex_snippet) const
215 pimpl_->remove(latex_snippet);
219 void PreviewLoader::startLoading() const
221 pimpl_->startLoading();
225 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
227 return pimpl_->imageReady.connect(slot);
231 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
233 pimpl_->imageReady(pimage);
237 Buffer const & PreviewLoader::buffer() const
239 return pimpl_->buffer();
245 // The details of the Impl
246 // =======================
250 struct IncrementedFileName {
251 IncrementedFileName(string const & to_format,
252 string const & filename_base)
253 : to_format_(to_format), base_(filename_base), counter_(1)
256 StrPair const operator()(string const & snippet)
259 os << base_ << counter_++ << '.' << to_format_;
260 string const file = STRCONV(os.str());
262 return make_pair(snippet, file);
266 string const & to_format_;
267 string const & base_;
272 InProgress::InProgress(string const & filename_base,
273 PendingSnippets const & pending,
274 string const & to_format)
276 metrics_file(filename_base + ".metrics"),
277 snippets(pending.size())
279 PendingSnippets::const_iterator pit = pending.begin();
280 PendingSnippets::const_iterator pend = pending.end();
281 BitmapFile::iterator sit = snippets.begin();
283 std::transform(pit, pend, sit,
284 IncrementedFileName(to_format, filename_base));
288 void InProgress::stop() const
291 ForkedcallsController::get().kill(pid, 0);
293 if (!metrics_file.empty())
294 lyx::unlink(metrics_file);
296 BitmapFile::const_iterator vit = snippets.begin();
297 BitmapFile::const_iterator vend = snippets.end();
298 for (; vit != vend; ++vit) {
299 if (!vit->second.empty())
300 lyx::unlink(vit->second);
309 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
310 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
312 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
313 lyxrc.preview_scale_factor;
315 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
316 << font_scaling_factor_ << endl;
319 pconverter_ = setConverter();
323 PreviewLoader::Impl::~Impl()
325 InProgressProcesses::iterator ipit = in_progress_.begin();
326 InProgressProcesses::iterator ipend = in_progress_.end();
328 for (; ipit != ipend; ++ipit) {
335 PreviewLoader::Impl::preview(string const & latex_snippet) const
337 Cache::const_iterator it = cache_.find(latex_snippet);
338 return (it == cache_.end()) ? 0 : it->second.get();
345 FindSnippet(string const & s) : snippet_(s) {}
346 bool operator()(InProgressProcess const & process)
348 BitmapFile const & snippets = process.second.snippets;
349 BitmapFile::const_iterator it = snippets.begin();
350 BitmapFile::const_iterator end = snippets.end();
351 it = find_if(it, end, FindFirst(snippet_));
356 string const & snippet_;
361 PreviewLoader::Status
362 PreviewLoader::Impl::status(string const & latex_snippet) const
364 Cache::const_iterator cit = cache_.find(latex_snippet);
365 if (cit != cache_.end())
368 PendingSnippets::const_iterator pit = pending_.begin();
369 PendingSnippets::const_iterator pend = pending_.end();
371 pit = find(pit, pend, latex_snippet);
375 InProgressProcesses::const_iterator ipit = in_progress_.begin();
376 InProgressProcesses::const_iterator ipend = in_progress_.end();
378 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
386 void PreviewLoader::Impl::add(string const & latex_snippet)
388 if (!pconverter_ || status(latex_snippet) != NotFound)
391 string const snippet = trim(latex_snippet);
395 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
397 pending_.push_back(snippet);
403 struct EraseSnippet {
404 EraseSnippet(string const & s) : snippet_(s) {}
405 void operator()(InProgressProcess & process)
407 BitmapFile & snippets = process.second.snippets;
408 BitmapFile::iterator it = snippets.begin();
409 BitmapFile::iterator end = snippets.end();
411 it = find_if(it, end, FindFirst(snippet_));
413 snippets.erase(it, it+1);
417 string const & snippet_;
423 void PreviewLoader::Impl::remove(string const & latex_snippet)
425 Cache::iterator cit = cache_.find(latex_snippet);
426 if (cit != cache_.end())
429 PendingSnippets::iterator pit = pending_.begin();
430 PendingSnippets::iterator pend = pending_.end();
432 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
434 InProgressProcesses::iterator ipit = in_progress_.begin();
435 InProgressProcesses::iterator ipend = in_progress_.end();
437 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
439 for (; ipit != ipend; ++ipit) {
440 InProgressProcesses::iterator curr = ipit++;
441 if (curr->second.snippets.empty())
442 in_progress_.erase(curr);
447 void PreviewLoader::Impl::startLoading()
449 if (pending_.empty() || !pconverter_)
452 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
454 // As used by the LaTeX file and by the resulting image files
455 string directory = buffer_.tmppath;
456 if (directory.empty())
457 directory = buffer_.filePath();
459 string const filename_base(unique_filename(directory));
461 // Create an InProgress instance to place in the map of all
462 // such processes if it starts correctly.
463 InProgress inprogress(filename_base, pending_, pconverter_->to);
465 // clear pending_, so we're ready to start afresh.
468 // Output the LaTeX file.
469 string const latexfile = filename_base + ".tex";
471 ofstream of(latexfile.c_str());
472 of << "\\batchmode\n";
474 of << "\n\\begin{document}\n";
475 dumpData(of, inprogress.snippets);
476 of << "\n\\end{document}\n";
479 // The conversion command.
481 cs << pconverter_->command << ' ' << latexfile << ' '
482 << int(font_scaling_factor_) << ' ' << pconverter_->to;
484 string const command = "sh " + LibScriptSearch(STRCONV(cs.str()));
486 // Initiate the conversion from LaTeX to bitmap images files.
487 Forkedcall::SignalTypePtr convert_ptr(new Forkedcall::SignalType);
488 convert_ptr->connect(
489 boost::bind(&Impl::finishedGenerating, this, _1, _2));
492 int ret = call.startscript(command, convert_ptr);
495 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
496 << "Unable to start process \n"
501 // Store the generation process in a list of all such processes
502 inprogress.pid = call.pid();
503 inprogress.command = command;
504 in_progress_[inprogress.pid] = inprogress;
508 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
511 InProgressProcesses::iterator git = in_progress_.find(pid);
512 if (git == in_progress_.end()) {
513 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
514 "data for PID " << pid << endl;
518 string const command = git->second.command;
519 string const status = retval > 0 ? "failed" : "succeeded";
520 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
521 << retval << "): processing " << status
522 << " for " << command << endl;
526 // Read the metrics file, if it exists
527 vector<double> ascent_fractions(git->second.snippets.size());
528 setAscentFractions(ascent_fractions, git->second.metrics_file);
530 // Add these newly generated bitmap files to the cache and
531 // start loading them into LyX.
532 BitmapFile::const_iterator it = git->second.snippets.begin();
533 BitmapFile::const_iterator end = git->second.snippets.end();
535 std::list<PreviewImagePtr> newimages;
537 int metrics_counter = 0;
538 for (; it != end; ++it, ++metrics_counter) {
539 string const & snip = it->first;
540 string const & file = it->second;
541 double af = ascent_fractions[metrics_counter];
543 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
546 newimages.push_back(ptr);
549 // Remove the item from the list of still-executing processes.
550 in_progress_.erase(git);
552 // Tell the outside world
553 std::list<PreviewImagePtr>::const_reverse_iterator
554 nit = newimages.rbegin();
555 std::list<PreviewImagePtr>::const_reverse_iterator
556 nend = newimages.rend();
557 for (; nit != nend; ++nit) {
558 imageReady(*nit->get());
563 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
565 // Why on earth is Buffer::makeLaTeXFile a non-const method?
566 Buffer & tmp = const_cast<Buffer &>(buffer_);
567 // Dump the preamble only.
568 LatexRunParams runparams;
569 runparams.flavor = LatexRunParams::LATEX;
570 runparams.nice = true;
571 runparams.moving_arg = true;
572 runparams.free_spacing = true;
573 tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, false, true);
575 // FIXME! This is a HACK! The proper fix is to control the 'true'
576 // passed to WriteStream below:
577 // int InsetFormula::latex(Buffer const *, ostream & os,
578 // LatexRunParams const & runparams) const
580 // WriteStream wi(os, runparams.moving_arg, true);
585 << "\\def\\lyxlock{}\n"
588 // Loop over the insets in the buffer and dump all the math-macros.
589 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
590 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
592 for (; it != end; ++it)
593 if (it->lyxCode() == Inset::MATHMACRO_CODE)
594 it->latex(&buffer_, os, runparams);
596 // All equation lables appear as "(#)" + preview.sty's rendering of
598 if (lyxrc.preview_hashed_labels)
599 os << "\\renewcommand{\\theequation}{\\#}\n";
601 // Use the preview style file to ensure that each snippet appears on a
604 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
607 // This piece of PostScript magic ensures that the foreground and
608 // background colors are the same as the LyX screen.
609 string fg = lyx_gui::hexname(LColor::preview);
610 if (fg.empty()) fg = "000000";
612 string bg = lyx_gui::hexname(LColor::background);
613 if (bg.empty()) bg = "ffffff";
615 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
616 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
617 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
618 << "clippath fill setrgbcolor}bind def end}}}\n";
622 void PreviewLoader::Impl::dumpData(ostream & os,
623 BitmapFile const & vec) const
628 BitmapFile::const_iterator it = vec.begin();
629 BitmapFile::const_iterator end = vec.end();
631 for (; it != end; ++it) {
632 os << "\\begin{preview}\n"
634 << "\n\\end{preview}\n\n";
643 string const unique_filename(string const bufferpath)
645 static int theCounter = 0;
646 string const filename = tostr(theCounter++) + "lyxpreview";
647 return AddName(bufferpath, filename);
651 Converter const * setConverter()
653 string const from = "lyxpreview";
655 Formats::FormatList::const_iterator it = formats.begin();
656 Formats::FormatList::const_iterator end = formats.end();
658 for (; it != end; ++it) {
659 string const to = it->name();
663 Converter const * ptr = converters.getConverter(from, to);
668 static bool first = true;
671 lyxerr << "PreviewLoader::startLoading()\n"
672 << "No converter from \"lyxpreview\" format has been "
681 void setAscentFractions(vector<double> & ascent_fractions,
682 string const & metrics_file)
684 // If all else fails, then the images will have equal ascents and
686 vector<double>::iterator it = ascent_fractions.begin();
687 vector<double>::iterator end = ascent_fractions.end();
690 ifstream in(metrics_file.c_str());
692 lyxerr[Debug::GRAPHICS]
693 << "setAscentFractions(" << metrics_file << ")\n"
694 << "Unable to open file!" << endl;
700 // Tightpage dimensions affect all subsequent dimensions
704 int snippet_counter = 0;
706 // Expecting lines of the form
707 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
708 // Preview: Snippet id ascent descent width
711 in >> preview >> type;
717 error = preview != "Preview:"
718 || (type != "Tightpage" && type != "Snippet");
722 if (type == "Tightpage") {
724 in >> dummy >> tp_descent >> dummy >> tp_ascent;
735 in >> snippet_id >> ascent >> descent >> dummy;
737 error = !in.good() || ++snippet_counter != snippet_id;
741 double const a = ascent + tp_ascent;
742 double const d = descent - tp_descent;
744 if (!lyx::float_equal(a + d, 0, 0.1))
753 lyxerr[Debug::GRAPHICS]
754 << "setAscentFractions(" << metrics_file << ")\n"
755 << "Error reading file!\n" << endl;