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"
20 #include "latexrunparams.h"
24 #include "frontends/lyx_gui.h" // hexname
26 #include "insets/inset.h"
28 #include "support/filetools.h"
29 #include "support/forkedcall.h"
30 #include "support/forkedcontr.h"
31 #include "support/lstrings.h"
32 #include "support/lyxlib.h"
33 #include "support/tostr.h"
35 #include <boost/bind.hpp>
37 #include "support/std_sstream.h"
41 namespace support = lyx::support;
54 using std::ostringstream;
62 typedef pair<string, string> StrPair;
64 // A list of alll snippets to be converted to previews
65 typedef list<string> PendingSnippets;
67 // Each item in the vector is a pair<snippet, image file name>.
68 typedef vector<StrPair> BitmapFile;
70 string const unique_filename(string const bufferpath);
72 Converter const * setConverter();
74 void setAscentFractions(vector<double> & ascent_fractions,
75 string const & metrics_file);
78 FindFirst(string const & comp) : comp_(comp) {}
79 bool operator()(StrPair const & sp)
81 return sp.first == comp_;
88 /// Store info on a currently executing, forked process.
91 InProgress() : pid(0) {}
93 InProgress(string const & filename_base,
94 PendingSnippets const & pending,
95 string const & to_format);
96 /// Remove any files left lying around and kill the forked process.
109 typedef map<pid_t, InProgress> InProgressProcesses;
111 typedef InProgressProcesses::value_type InProgressProcess;
119 struct PreviewLoader::Impl : public boost::signals::trackable {
121 Impl(PreviewLoader & p, Buffer const & b);
122 /// Stop any InProgress items still executing.
125 PreviewImage const * preview(string const & latex_snippet) const;
127 PreviewLoader::Status status(string const & latex_snippet) const;
129 void add(string const & latex_snippet);
131 void remove(string const & latex_snippet);
135 /// Emit this signal when an image is ready for display.
136 boost::signal1<void, PreviewImage const &> imageReady;
138 Buffer const & buffer() const { return buffer_; }
141 /// Called by the Forkedcall process that generated the bitmap files.
142 void finishedGenerating(pid_t, int);
144 void dumpPreamble(ostream &) const;
146 void dumpData(ostream &, BitmapFile const &) const;
148 /** cache_ allows easy retrieval of already-generated images
149 * using the LaTeX snippet as the identifier.
151 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
153 typedef map<string, PreviewImagePtr> Cache;
157 /** pending_ stores the LaTeX snippets in anticipation of them being
158 * sent to the converter.
160 PendingSnippets pending_;
162 /** in_progress_ stores all forked processes so that we can proceed
164 The map uses the conversion commands as its identifiers.
166 InProgressProcesses in_progress_;
169 PreviewLoader & parent_;
171 Buffer const & buffer_;
173 double font_scaling_factor_;
175 /// We don't own this
176 static Converter const * pconverter_;
180 Converter const * PreviewLoader::Impl::pconverter_;
183 // The public interface, defined in PreviewLoader.h
184 // ================================================
185 PreviewLoader::PreviewLoader(Buffer const & b)
186 : pimpl_(new Impl(*this, b))
190 PreviewLoader::~PreviewLoader()
194 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
196 return pimpl_->preview(latex_snippet);
200 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
202 return pimpl_->status(latex_snippet);
206 void PreviewLoader::add(string const & latex_snippet) const
208 pimpl_->add(latex_snippet);
212 void PreviewLoader::remove(string const & latex_snippet) const
214 pimpl_->remove(latex_snippet);
218 void PreviewLoader::startLoading() const
220 pimpl_->startLoading();
224 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
226 return pimpl_->imageReady.connect(slot);
230 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
232 pimpl_->imageReady(pimage);
236 Buffer const & PreviewLoader::buffer() const
238 return pimpl_->buffer();
241 } // namespace graphics
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 = 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 support::ForkedcallsController::get().kill(pid, 0);
293 if (!metrics_file.empty())
294 support::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 support::unlink(vit->second);
310 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
311 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
313 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
314 lyxrc.preview_scale_factor;
316 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
317 << font_scaling_factor_ << endl;
320 pconverter_ = setConverter();
324 PreviewLoader::Impl::~Impl()
326 InProgressProcesses::iterator ipit = in_progress_.begin();
327 InProgressProcesses::iterator ipend = in_progress_.end();
329 for (; ipit != ipend; ++ipit) {
336 PreviewLoader::Impl::preview(string const & latex_snippet) const
338 Cache::const_iterator it = cache_.find(latex_snippet);
339 return (it == cache_.end()) ? 0 : it->second.get();
346 FindSnippet(string const & s) : snippet_(s) {}
347 bool operator()(InProgressProcess const & process)
349 BitmapFile const & snippets = process.second.snippets;
350 BitmapFile::const_iterator it = snippets.begin();
351 BitmapFile::const_iterator end = snippets.end();
352 it = find_if(it, end, FindFirst(snippet_));
357 string const & snippet_;
362 PreviewLoader::Status
363 PreviewLoader::Impl::status(string const & latex_snippet) const
365 Cache::const_iterator cit = cache_.find(latex_snippet);
366 if (cit != cache_.end())
369 PendingSnippets::const_iterator pit = pending_.begin();
370 PendingSnippets::const_iterator pend = pending_.end();
372 pit = find(pit, pend, latex_snippet);
376 InProgressProcesses::const_iterator ipit = in_progress_.begin();
377 InProgressProcesses::const_iterator ipend = in_progress_.end();
379 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
387 void PreviewLoader::Impl::add(string const & latex_snippet)
389 if (!pconverter_ || status(latex_snippet) != NotFound)
392 string const snippet = support::trim(latex_snippet);
396 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
398 pending_.push_back(snippet);
404 struct EraseSnippet {
405 EraseSnippet(string const & s) : snippet_(s) {}
406 void operator()(InProgressProcess & process)
408 BitmapFile & snippets = process.second.snippets;
409 BitmapFile::iterator it = snippets.begin();
410 BitmapFile::iterator end = snippets.end();
412 it = find_if(it, end, FindFirst(snippet_));
414 snippets.erase(it, it+1);
418 string const & snippet_;
424 void PreviewLoader::Impl::remove(string const & latex_snippet)
426 Cache::iterator cit = cache_.find(latex_snippet);
427 if (cit != cache_.end())
430 PendingSnippets::iterator pit = pending_.begin();
431 PendingSnippets::iterator pend = pending_.end();
433 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
435 InProgressProcesses::iterator ipit = in_progress_.begin();
436 InProgressProcesses::iterator ipend = in_progress_.end();
438 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
440 while (ipit != ipend) {
441 InProgressProcesses::iterator curr = ipit++;
442 if (curr->second.snippets.empty())
443 in_progress_.erase(curr);
448 void PreviewLoader::Impl::startLoading()
450 if (pending_.empty() || !pconverter_)
453 // Only start the process off after the buffer is loaded from file.
454 if (!buffer_.fully_loaded())
457 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
459 // As used by the LaTeX file and by the resulting image files
460 string const directory = buffer_.temppath().empty() ?
461 buffer_.filePath() : buffer_.temppath();
463 string const filename_base(unique_filename(directory));
465 // Create an InProgress instance to place in the map of all
466 // such processes if it starts correctly.
467 InProgress inprogress(filename_base, pending_, pconverter_->to);
469 // clear pending_, so we're ready to start afresh.
472 // Output the LaTeX file.
473 string const latexfile = filename_base + ".tex";
475 ofstream of(latexfile.c_str());
476 of << "\\batchmode\n";
478 of << "\n\\begin{document}\n";
479 dumpData(of, inprogress.snippets);
480 of << "\n\\end{document}\n";
483 // The conversion command.
485 cs << pconverter_->command << ' ' << latexfile << ' '
486 << int(font_scaling_factor_) << ' ' << pconverter_->to;
488 string const command = "sh " + support::LibScriptSearch(cs.str());
490 // Initiate the conversion from LaTeX to bitmap images files.
491 support::Forkedcall::SignalTypePtr
492 convert_ptr(new support::Forkedcall::SignalType);
493 convert_ptr->connect(
494 boost::bind(&Impl::finishedGenerating, this, _1, _2));
496 support::Forkedcall call;
497 int ret = call.startscript(command, convert_ptr);
500 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
501 << "Unable to start process \n"
506 // Store the generation process in a list of all such processes
507 inprogress.pid = call.pid();
508 inprogress.command = command;
509 in_progress_[inprogress.pid] = inprogress;
513 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
516 InProgressProcesses::iterator git = in_progress_.find(pid);
517 if (git == in_progress_.end()) {
518 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
519 "data for PID " << pid << endl;
523 string const command = git->second.command;
524 string const status = retval > 0 ? "failed" : "succeeded";
525 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
526 << retval << "): processing " << status
527 << " for " << command << endl;
531 // Read the metrics file, if it exists
532 vector<double> ascent_fractions(git->second.snippets.size());
533 setAscentFractions(ascent_fractions, git->second.metrics_file);
535 // Add these newly generated bitmap files to the cache and
536 // start loading them into LyX.
537 BitmapFile::const_iterator it = git->second.snippets.begin();
538 BitmapFile::const_iterator end = git->second.snippets.end();
540 std::list<PreviewImagePtr> newimages;
542 int metrics_counter = 0;
543 for (; it != end; ++it, ++metrics_counter) {
544 string const & snip = it->first;
545 string const & file = it->second;
546 double af = ascent_fractions[metrics_counter];
548 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
551 newimages.push_back(ptr);
554 // Remove the item from the list of still-executing processes.
555 in_progress_.erase(git);
557 // Tell the outside world
558 std::list<PreviewImagePtr>::const_reverse_iterator
559 nit = newimages.rbegin();
560 std::list<PreviewImagePtr>::const_reverse_iterator
561 nend = newimages.rend();
562 for (; nit != nend; ++nit) {
563 imageReady(*nit->get());
568 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
570 // Why on earth is Buffer::makeLaTeXFile a non-const method?
571 Buffer & tmp = const_cast<Buffer &>(buffer_);
572 // Dump the preamble only.
573 LatexRunParams runparams;
574 runparams.flavor = LatexRunParams::LATEX;
575 runparams.nice = true;
576 runparams.moving_arg = true;
577 runparams.free_spacing = true;
578 tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
580 // FIXME! This is a HACK! The proper fix is to control the 'true'
581 // passed to WriteStream below:
582 // int InsetFormula::latex(Buffer const &, ostream & os,
583 // LatexRunParams const & runparams) const
585 // WriteStream wi(os, runparams.moving_arg, true);
590 << "\\def\\lyxlock{}\n"
593 // Loop over the insets in the buffer and dump all the math-macros.
594 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
595 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
597 for (; it != end; ++it)
598 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
599 it->latex(buffer_, os, runparams);
601 // All equation lables appear as "(#)" + preview.sty's rendering of
603 if (lyxrc.preview_hashed_labels)
604 os << "\\renewcommand{\\theequation}{\\#}\n";
606 // Use the preview style file to ensure that each snippet appears on a
609 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
612 // This piece of PostScript magic ensures that the foreground and
613 // background colors are the same as the LyX screen.
614 string fg = lyx_gui::hexname(LColor::preview);
615 if (fg.empty()) fg = "000000";
617 string bg = lyx_gui::hexname(LColor::background);
618 if (bg.empty()) bg = "ffffff";
620 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
621 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
622 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
623 << "clippath fill setrgbcolor}bind def end}}}\n";
627 void PreviewLoader::Impl::dumpData(ostream & os,
628 BitmapFile const & vec) const
633 BitmapFile::const_iterator it = vec.begin();
634 BitmapFile::const_iterator end = vec.end();
636 for (; it != end; ++it) {
637 os << "\\begin{preview}\n"
639 << "\n\\end{preview}\n\n";
643 } // namespace graphics
648 string const unique_filename(string const bufferpath)
650 static int theCounter = 0;
651 string const filename = tostr(theCounter++) + "lyxpreview";
652 return support::AddName(bufferpath, filename);
656 Converter const * setConverter()
658 string const from = "lyxpreview";
660 Formats::FormatList::const_iterator it = formats.begin();
661 Formats::FormatList::const_iterator end = formats.end();
663 for (; it != end; ++it) {
664 string const to = it->name();
668 Converter const * ptr = converters.getConverter(from, to);
673 static bool first = true;
676 lyxerr << "PreviewLoader::startLoading()\n"
677 << "No converter from \"lyxpreview\" format has been "
686 void setAscentFractions(vector<double> & ascent_fractions,
687 string const & metrics_file)
689 // If all else fails, then the images will have equal ascents and
691 vector<double>::iterator it = ascent_fractions.begin();
692 vector<double>::iterator end = ascent_fractions.end();
695 ifstream in(metrics_file.c_str());
697 lyxerr[Debug::GRAPHICS]
698 << "setAscentFractions(" << metrics_file << ")\n"
699 << "Unable to open file!" << endl;
705 // Tightpage dimensions affect all subsequent dimensions
709 int snippet_counter = 0;
711 // Expecting lines of the form
712 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
713 // Preview: Snippet id ascent descent width
716 in >> preview >> type;
722 error = preview != "Preview:"
723 || (type != "Tightpage" && type != "Snippet");
727 if (type == "Tightpage") {
729 in >> dummy >> tp_descent >> dummy >> tp_ascent;
740 in >> snippet_id >> ascent >> descent >> dummy;
742 error = !in.good() || ++snippet_counter != snippet_id;
746 double const a = ascent + tp_ascent;
747 double const d = descent - tp_descent;
749 if (!support::float_equal(a + d, 0, 0.1))
758 lyxerr[Debug::GRAPHICS]
759 << "setAscentFractions(" << metrics_file << ")\n"
760 << "Error reading file!\n" << endl;