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"
22 #include "outputparams.h"
23 #include "paragraph.h"
25 #include "frontends/lyx_gui.h" // hexname
27 #include "insets/inset.h"
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"
34 #include "support/tostr.h"
36 #include <boost/bind.hpp>
38 #include "support/std_sstream.h"
42 namespace support = lyx::support;
55 using std::ostringstream;
63 typedef pair<string, string> StrPair;
65 // A list of alll snippets to be converted to previews
66 typedef list<string> PendingSnippets;
68 // Each item in the vector is a pair<snippet, image file name>.
69 typedef vector<StrPair> BitmapFile;
71 string const unique_filename(string const bufferpath);
73 Converter const * setConverter();
75 void setAscentFractions(vector<double> & ascent_fractions,
76 string const & metrics_file);
79 FindFirst(string const & comp) : comp_(comp) {}
80 bool operator()(StrPair const & sp)
82 return sp.first == comp_;
89 /// Store info on a currently executing, forked process.
92 InProgress() : pid(0) {}
94 InProgress(string const & filename_base,
95 PendingSnippets const & pending,
96 string const & to_format);
97 /// Remove any files left lying around and kill the forked process.
110 typedef map<pid_t, InProgress> InProgressProcesses;
112 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();
242 } // namespace graphics
246 // The details of the Impl
247 // =======================
251 struct IncrementedFileName {
252 IncrementedFileName(string const & to_format,
253 string const & filename_base)
254 : to_format_(to_format), base_(filename_base), counter_(1)
257 StrPair const operator()(string const & snippet)
260 os << base_ << counter_++ << '.' << to_format_;
261 string const file = os.str();
263 return make_pair(snippet, file);
267 string const & to_format_;
268 string const & base_;
273 InProgress::InProgress(string const & filename_base,
274 PendingSnippets const & pending,
275 string const & to_format)
277 metrics_file(filename_base + ".metrics"),
278 snippets(pending.size())
280 PendingSnippets::const_iterator pit = pending.begin();
281 PendingSnippets::const_iterator pend = pending.end();
282 BitmapFile::iterator sit = snippets.begin();
284 std::transform(pit, pend, sit,
285 IncrementedFileName(to_format, filename_base));
289 void InProgress::stop() const
292 support::ForkedcallsController::get().kill(pid, 0);
294 if (!metrics_file.empty())
295 support::unlink(metrics_file);
297 BitmapFile::const_iterator vit = snippets.begin();
298 BitmapFile::const_iterator vend = snippets.end();
299 for (; vit != vend; ++vit) {
300 if (!vit->second.empty())
301 support::unlink(vit->second);
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 = support::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 while (ipit != ipend) {
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 // Only start the process off after the buffer is loaded from file.
455 if (!buffer_.fully_loaded())
458 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
460 // As used by the LaTeX file and by the resulting image files
461 string const directory = buffer_.temppath().empty() ?
462 buffer_.filePath() : buffer_.temppath();
464 string const filename_base(unique_filename(directory));
466 // Create an InProgress instance to place in the map of all
467 // such processes if it starts correctly.
468 InProgress inprogress(filename_base, pending_, pconverter_->to);
470 // clear pending_, so we're ready to start afresh.
473 // Output the LaTeX file.
474 string const latexfile = filename_base + ".tex";
476 ofstream of(latexfile.c_str());
477 of << "\\batchmode\n";
479 of << "\n\\begin{document}\n";
480 dumpData(of, inprogress.snippets);
481 of << "\n\\end{document}\n";
484 // The conversion command.
486 cs << pconverter_->command << ' ' << latexfile << ' '
487 << int(font_scaling_factor_) << ' ' << pconverter_->to;
489 string const command = "sh " + support::LibScriptSearch(cs.str());
491 // Initiate the conversion from LaTeX to bitmap images files.
492 support::Forkedcall::SignalTypePtr
493 convert_ptr(new support::Forkedcall::SignalType);
494 convert_ptr->connect(
495 boost::bind(&Impl::finishedGenerating, this, _1, _2));
497 support::Forkedcall call;
498 int ret = call.startscript(command, convert_ptr);
501 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
502 << "Unable to start process \n"
507 // Store the generation process in a list of all such processes
508 inprogress.pid = call.pid();
509 inprogress.command = command;
510 in_progress_[inprogress.pid] = inprogress;
514 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
517 InProgressProcesses::iterator git = in_progress_.find(pid);
518 if (git == in_progress_.end()) {
519 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
520 "data for PID " << pid << endl;
524 string const command = git->second.command;
525 string const status = retval > 0 ? "failed" : "succeeded";
526 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
527 << retval << "): processing " << status
528 << " for " << command << endl;
532 // Read the metrics file, if it exists
533 vector<double> ascent_fractions(git->second.snippets.size());
534 setAscentFractions(ascent_fractions, git->second.metrics_file);
536 // Add these newly generated bitmap files to the cache and
537 // start loading them into LyX.
538 BitmapFile::const_iterator it = git->second.snippets.begin();
539 BitmapFile::const_iterator end = git->second.snippets.end();
541 std::list<PreviewImagePtr> newimages;
543 int metrics_counter = 0;
544 for (; it != end; ++it, ++metrics_counter) {
545 string const & snip = it->first;
546 string const & file = it->second;
547 double af = ascent_fractions[metrics_counter];
549 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
552 newimages.push_back(ptr);
555 // Remove the item from the list of still-executing processes.
556 in_progress_.erase(git);
558 // Tell the outside world
559 std::list<PreviewImagePtr>::const_reverse_iterator
560 nit = newimages.rbegin();
561 std::list<PreviewImagePtr>::const_reverse_iterator
562 nend = newimages.rend();
563 for (; nit != nend; ++nit) {
564 imageReady(*nit->get());
569 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
571 // Why on earth is Buffer::makeLaTeXFile a non-const method?
572 Buffer & tmp = const_cast<Buffer &>(buffer_);
573 // Dump the preamble only.
574 OutputParams runparams;
575 runparams.flavor = OutputParams::LATEX;
576 runparams.nice = true;
577 runparams.moving_arg = true;
578 runparams.free_spacing = true;
579 tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
581 // FIXME! This is a HACK! The proper fix is to control the 'true'
582 // passed to WriteStream below:
583 // int InsetFormula::latex(Buffer const &, ostream & os,
584 // OutputParams const & runparams) const
586 // WriteStream wi(os, runparams.moving_arg, true);
591 << "\\def\\lyxlock{}\n"
594 // Loop over the insets in the buffer and dump all the math-macros.
595 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
596 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
598 for (; it != end; ++it)
599 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
600 it->latex(buffer_, os, runparams);
602 // All equation lables appear as "(#)" + preview.sty's rendering of
604 if (lyxrc.preview_hashed_labels)
605 os << "\\renewcommand{\\theequation}{\\#}\n";
607 // Use the preview style file to ensure that each snippet appears on a
610 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
613 // This piece of PostScript magic ensures that the foreground and
614 // background colors are the same as the LyX screen.
615 string fg = lyx_gui::hexname(LColor::preview);
616 if (fg.empty()) fg = "000000";
618 string bg = lyx_gui::hexname(LColor::background);
619 if (bg.empty()) bg = "ffffff";
621 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
622 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
623 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
624 << "clippath fill setrgbcolor}bind def end}}}\n";
628 void PreviewLoader::Impl::dumpData(ostream & os,
629 BitmapFile const & vec) const
634 BitmapFile::const_iterator it = vec.begin();
635 BitmapFile::const_iterator end = vec.end();
637 for (; it != end; ++it) {
638 os << "\\begin{preview}\n"
640 << "\n\\end{preview}\n\n";
644 } // namespace graphics
649 string const unique_filename(string const bufferpath)
651 static int theCounter = 0;
652 string const filename = tostr(theCounter++) + "lyxpreview";
653 return support::AddName(bufferpath, filename);
657 Converter const * setConverter()
659 string const from = "lyxpreview";
661 Formats::FormatList::const_iterator it = formats.begin();
662 Formats::FormatList::const_iterator end = formats.end();
664 for (; it != end; ++it) {
665 string const to = it->name();
669 Converter const * ptr = converters.getConverter(from, to);
674 static bool first = true;
677 lyxerr << "PreviewLoader::startLoading()\n"
678 << "No converter from \"lyxpreview\" format has been "
687 void setAscentFractions(vector<double> & ascent_fractions,
688 string const & metrics_file)
690 // If all else fails, then the images will have equal ascents and
692 vector<double>::iterator it = ascent_fractions.begin();
693 vector<double>::iterator end = ascent_fractions.end();
696 ifstream in(metrics_file.c_str());
698 lyxerr[Debug::GRAPHICS]
699 << "setAscentFractions(" << metrics_file << ")\n"
700 << "Unable to open file!" << endl;
706 // Tightpage dimensions affect all subsequent dimensions
710 int snippet_counter = 0;
712 // Expecting lines of the form
713 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
714 // Preview: Snippet id ascent descent width
717 in >> preview >> type;
723 error = preview != "Preview:"
724 || (type != "Tightpage" && type != "Snippet");
728 if (type == "Tightpage") {
730 in >> dummy >> tp_descent >> dummy >> tp_ascent;
741 in >> snippet_id >> ascent >> descent >> dummy;
743 error = !in.good() || ++snippet_counter != snippet_id;
747 double const a = ascent + tp_ascent;
748 double const d = descent - tp_descent;
750 if (!support::float_equal(a + d, 0, 0.1))
759 lyxerr[Debug::GRAPHICS]
760 << "setAscentFractions(" << metrics_file << ")\n"
761 << "Error reading file!\n" << endl;