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 "insetiterator.h"
23 #include "outputparams.h"
24 #include "paragraph.h"
26 #include "frontends/lyx_gui.h" // hexname
28 #include "insets/inset.h"
30 #include "support/filetools.h"
31 #include "support/forkedcall.h"
32 #include "support/forkedcontr.h"
33 #include "support/lstrings.h"
34 #include "support/lyxlib.h"
35 #include "support/tostr.h"
37 #include <boost/bind.hpp>
39 #include "support/std_sstream.h"
43 namespace support = lyx::support;
58 using std::ostringstream;
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);
81 class FindFirst : public std::unary_function<StrPair, bool> {
83 FindFirst(string const & comp) : comp_(comp) {}
84 bool operator()(StrPair const & sp) const
86 return sp.first == comp_;
93 /// Store info on a currently executing, forked process.
96 InProgress() : pid(0) {}
98 InProgress(string const & filename_base,
99 PendingSnippets const & pending,
100 string const & to_format);
101 /// Remove any files left lying around and kill the forked process.
114 typedef map<pid_t, InProgress> InProgressProcesses;
116 typedef InProgressProcesses::value_type InProgressProcess;
124 struct PreviewLoader::Impl : public boost::signals::trackable {
126 Impl(PreviewLoader & p, Buffer const & b);
127 /// Stop any InProgress items still executing.
130 PreviewImage const * preview(string const & latex_snippet) const;
132 PreviewLoader::Status status(string const & latex_snippet) const;
134 void add(string const & latex_snippet);
136 void remove(string const & latex_snippet);
140 /// Emit this signal when an image is ready for display.
141 boost::signal1<void, PreviewImage const &> imageReady;
143 Buffer const & buffer() const { return buffer_; }
146 /// Called by the Forkedcall process that generated the bitmap files.
147 void finishedGenerating(pid_t, int);
149 void dumpPreamble(ostream &) const;
151 void dumpData(ostream &, BitmapFile const &) const;
153 /** cache_ allows easy retrieval of already-generated images
154 * using the LaTeX snippet as the identifier.
156 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
158 typedef map<string, PreviewImagePtr> Cache;
162 /** pending_ stores the LaTeX snippets in anticipation of them being
163 * sent to the converter.
165 PendingSnippets pending_;
167 /** in_progress_ stores all forked processes so that we can proceed
169 The map uses the conversion commands as its identifiers.
171 InProgressProcesses in_progress_;
174 PreviewLoader & parent_;
176 Buffer const & buffer_;
178 double font_scaling_factor_;
180 /// We don't own this
181 static Converter const * pconverter_;
185 Converter const * PreviewLoader::Impl::pconverter_;
188 // The public interface, defined in PreviewLoader.h
189 // ================================================
190 PreviewLoader::PreviewLoader(Buffer const & b)
191 : pimpl_(new Impl(*this, b))
195 PreviewLoader::~PreviewLoader()
199 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
201 return pimpl_->preview(latex_snippet);
205 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
207 return pimpl_->status(latex_snippet);
211 void PreviewLoader::add(string const & latex_snippet) const
213 pimpl_->add(latex_snippet);
217 void PreviewLoader::remove(string const & latex_snippet) const
219 pimpl_->remove(latex_snippet);
223 void PreviewLoader::startLoading() const
225 pimpl_->startLoading();
229 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
231 return pimpl_->imageReady.connect(slot);
235 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
237 pimpl_->imageReady(pimage);
241 Buffer const & PreviewLoader::buffer() const
243 return pimpl_->buffer();
246 } // namespace graphics
250 // The details of the Impl
251 // =======================
255 struct IncrementedFileName {
256 IncrementedFileName(string const & to_format,
257 string const & filename_base)
258 : to_format_(to_format), base_(filename_base), counter_(1)
261 StrPair const operator()(string const & snippet)
264 os << base_ << counter_++ << '.' << to_format_;
265 string const file = os.str();
267 return make_pair(snippet, file);
271 string const & to_format_;
272 string const & base_;
277 InProgress::InProgress(string const & filename_base,
278 PendingSnippets const & pending,
279 string const & to_format)
281 metrics_file(filename_base + ".metrics"),
282 snippets(pending.size())
284 PendingSnippets::const_iterator pit = pending.begin();
285 PendingSnippets::const_iterator pend = pending.end();
286 BitmapFile::iterator sit = snippets.begin();
288 std::transform(pit, pend, sit,
289 IncrementedFileName(to_format, filename_base));
293 void InProgress::stop() const
296 support::ForkedcallsController::get().kill(pid, 0);
298 if (!metrics_file.empty())
299 support::unlink(metrics_file);
301 BitmapFile::const_iterator vit = snippets.begin();
302 BitmapFile::const_iterator vend = snippets.end();
303 for (; vit != vend; ++vit) {
304 if (!vit->second.empty())
305 support::unlink(vit->second);
315 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
316 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
318 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
319 lyxrc.preview_scale_factor;
321 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
322 << font_scaling_factor_ << endl;
325 pconverter_ = setConverter();
329 PreviewLoader::Impl::~Impl()
331 InProgressProcesses::iterator ipit = in_progress_.begin();
332 InProgressProcesses::iterator ipend = in_progress_.end();
334 for (; ipit != ipend; ++ipit) {
341 PreviewLoader::Impl::preview(string const & latex_snippet) const
343 Cache::const_iterator it = cache_.find(latex_snippet);
344 return (it == cache_.end()) ? 0 : it->second.get();
350 class FindSnippet : public std::unary_function<InProgressProcess, bool> {
352 FindSnippet(string const & s) : snippet_(s) {}
353 bool operator()(InProgressProcess const & process) const
355 BitmapFile const & snippets = process.second.snippets;
356 BitmapFile::const_iterator beg = snippets.begin();
357 BitmapFile::const_iterator end = snippets.end();
358 return find_if(beg, end, FindFirst(snippet_)) != end;
362 string const snippet_;
367 PreviewLoader::Status
368 PreviewLoader::Impl::status(string const & latex_snippet) const
370 Cache::const_iterator cit = cache_.find(latex_snippet);
371 if (cit != cache_.end())
374 PendingSnippets::const_iterator pit = pending_.begin();
375 PendingSnippets::const_iterator pend = pending_.end();
377 pit = find(pit, pend, latex_snippet);
381 InProgressProcesses::const_iterator ipit = in_progress_.begin();
382 InProgressProcesses::const_iterator ipend = in_progress_.end();
384 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
392 void PreviewLoader::Impl::add(string const & latex_snippet)
394 if (!pconverter_ || status(latex_snippet) != NotFound)
397 string const snippet = support::trim(latex_snippet);
401 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
403 pending_.push_back(snippet);
409 struct EraseSnippet {
410 EraseSnippet(string const & s) : snippet_(s) {}
411 void operator()(InProgressProcess & process)
413 BitmapFile & snippets = process.second.snippets;
414 BitmapFile::iterator it = snippets.begin();
415 BitmapFile::iterator end = snippets.end();
417 it = find_if(it, end, FindFirst(snippet_));
419 snippets.erase(it, it+1);
423 string const & snippet_;
429 void PreviewLoader::Impl::remove(string const & latex_snippet)
431 Cache::iterator cit = cache_.find(latex_snippet);
432 if (cit != cache_.end())
435 PendingSnippets::iterator pit = pending_.begin();
436 PendingSnippets::iterator pend = pending_.end();
438 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
440 InProgressProcesses::iterator ipit = in_progress_.begin();
441 InProgressProcesses::iterator ipend = in_progress_.end();
443 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
445 while (ipit != ipend) {
446 InProgressProcesses::iterator curr = ipit++;
447 if (curr->second.snippets.empty())
448 in_progress_.erase(curr);
453 void PreviewLoader::Impl::startLoading()
455 if (pending_.empty() || !pconverter_)
458 // Only start the process off after the buffer is loaded from file.
459 if (!buffer_.fully_loaded())
462 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
464 // As used by the LaTeX file and by the resulting image files
465 string const directory = buffer_.temppath();
467 string const filename_base(unique_filename(directory));
469 // Create an InProgress instance to place in the map of all
470 // such processes if it starts correctly.
471 InProgress inprogress(filename_base, pending_, pconverter_->to);
473 // clear pending_, so we're ready to start afresh.
476 // Output the LaTeX file.
477 string const latexfile = filename_base + ".tex";
479 ofstream of(latexfile.c_str());
481 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
482 << "Unable to create LaTeX file\n"
483 << latexfile << endl;
486 of << "\\batchmode\n";
488 of << "\n\\begin{document}\n";
489 dumpData(of, inprogress.snippets);
490 of << "\n\\end{document}\n";
493 // The conversion command.
495 cs << pconverter_->command << ' ' << latexfile << ' '
496 << int(font_scaling_factor_) << ' ' << pconverter_->to;
498 string const command = "sh " + support::LibScriptSearch(cs.str());
500 // Initiate the conversion from LaTeX to bitmap images files.
501 support::Forkedcall::SignalTypePtr
502 convert_ptr(new support::Forkedcall::SignalType);
503 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
505 support::Forkedcall call;
506 int ret = call.startscript(command, convert_ptr);
509 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
510 << "Unable to start process \n"
515 // Store the generation process in a list of all such processes
516 inprogress.pid = call.pid();
517 inprogress.command = command;
518 in_progress_[inprogress.pid] = inprogress;
522 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
525 InProgressProcesses::iterator git = in_progress_.find(pid);
526 if (git == in_progress_.end()) {
527 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
528 "data for PID " << pid << endl;
532 string const command = git->second.command;
533 string const status = retval > 0 ? "failed" : "succeeded";
534 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
535 << retval << "): processing " << status
536 << " for " << command << endl;
540 // Read the metrics file, if it exists
541 vector<double> ascent_fractions(git->second.snippets.size());
542 setAscentFractions(ascent_fractions, git->second.metrics_file);
544 // Add these newly generated bitmap files to the cache and
545 // start loading them into LyX.
546 BitmapFile::const_iterator it = git->second.snippets.begin();
547 BitmapFile::const_iterator end = git->second.snippets.end();
549 std::list<PreviewImagePtr> newimages;
551 int metrics_counter = 0;
552 for (; it != end; ++it, ++metrics_counter) {
553 string const & snip = it->first;
554 string const & file = it->second;
555 double af = ascent_fractions[metrics_counter];
557 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
560 newimages.push_back(ptr);
563 // Remove the item from the list of still-executing processes.
564 in_progress_.erase(git);
566 // Tell the outside world
567 std::list<PreviewImagePtr>::const_reverse_iterator
568 nit = newimages.rbegin();
569 std::list<PreviewImagePtr>::const_reverse_iterator
570 nend = newimages.rend();
571 for (; nit != nend; ++nit) {
572 imageReady(*nit->get());
577 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
579 // Why on earth is Buffer::makeLaTeXFile a non-const method?
580 Buffer & tmp = const_cast<Buffer &>(buffer_);
581 // Dump the preamble only.
582 OutputParams runparams;
583 runparams.flavor = OutputParams::LATEX;
584 runparams.nice = true;
585 runparams.moving_arg = true;
586 runparams.free_spacing = true;
587 tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
589 // FIXME! This is a HACK! The proper fix is to control the 'true'
590 // passed to WriteStream below:
591 // int InsetFormula::latex(Buffer const &, ostream & os,
592 // OutputParams const & runparams) const
594 // WriteStream wi(os, runparams.moving_arg, true);
599 << "\\def\\lyxlock{}\n"
602 // Loop over the insets in the buffer and dump all the math-macros.
603 for (InsetIterator it(buffer_.inset()); it; ++it)
604 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
605 it->latex(buffer_, os, runparams);
607 // All equation lables appear as "(#)" + preview.sty's rendering of
609 if (lyxrc.preview_hashed_labels)
610 os << "\\renewcommand{\\theequation}{\\#}\n";
612 // Use the preview style file to ensure that each snippet appears on a
615 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
618 // This piece of PostScript magic ensures that the foreground and
619 // background colors are the same as the LyX screen.
620 string fg = lyx_gui::hexname(LColor::preview);
621 if (fg.empty()) fg = "000000";
623 string bg = lyx_gui::hexname(LColor::background);
624 if (bg.empty()) bg = "ffffff";
626 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
627 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
628 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
629 << "clippath fill setrgbcolor}bind def end}}}\n";
633 void PreviewLoader::Impl::dumpData(ostream & os,
634 BitmapFile const & vec) const
639 BitmapFile::const_iterator it = vec.begin();
640 BitmapFile::const_iterator end = vec.end();
642 for (; it != end; ++it) {
643 os << "\\begin{preview}\n"
645 << "\n\\end{preview}\n\n";
649 } // namespace graphics
654 string const unique_filename(string const bufferpath)
656 static int theCounter = 0;
657 string const filename = tostr(theCounter++) + "lyxpreview";
658 return support::AddName(bufferpath, filename);
662 Converter const * setConverter()
664 string const from = "lyxpreview";
666 Formats::FormatList::const_iterator it = formats.begin();
667 Formats::FormatList::const_iterator end = formats.end();
669 for (; it != end; ++it) {
670 string const to = it->name();
674 Converter const * ptr = converters.getConverter(from, to);
679 static bool first = true;
682 lyxerr << "PreviewLoader::startLoading()\n"
683 << "No converter from \"lyxpreview\" format has been "
692 void setAscentFractions(vector<double> & ascent_fractions,
693 string const & metrics_file)
695 // If all else fails, then the images will have equal ascents and
697 vector<double>::iterator it = ascent_fractions.begin();
698 vector<double>::iterator end = ascent_fractions.end();
701 ifstream in(metrics_file.c_str());
703 lyxerr[Debug::GRAPHICS]
704 << "setAscentFractions(" << metrics_file << ")\n"
705 << "Unable to open file!" << endl;
711 // Tightpage dimensions affect all subsequent dimensions
715 int snippet_counter = 0;
717 // Expecting lines of the form
718 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
719 // Preview: Snippet id ascent descent width
722 in >> preview >> type;
728 error = preview != "Preview:"
729 || (type != "Tightpage" && type != "Snippet");
733 if (type == "Tightpage") {
735 in >> dummy >> tp_descent >> dummy >> tp_ascent;
746 in >> snippet_id >> ascent >> descent >> dummy;
748 error = !in.good() || ++snippet_counter != snippet_id;
752 double const a = ascent + tp_ascent;
753 double const d = descent - tp_descent;
755 if (!support::float_equal(a + d, 0, 0.1))
764 lyxerr[Debug::GRAPHICS]
765 << "setAscentFractions(" << metrics_file << ")\n"
766 << "Error reading file!\n" << endl;