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 namespace support = lyx::support;
67 typedef pair<string, string> StrPair;
69 // A list of alll snippets to be converted to previews
70 typedef list<string> PendingSnippets;
72 // Each item in the vector is a pair<snippet, image file name>.
73 typedef vector<StrPair> BitmapFile;
75 string const unique_filename(string const bufferpath);
77 Converter const * setConverter();
79 void setAscentFractions(vector<double> & ascent_fractions,
80 string const & metrics_file);
83 FindFirst(string const & comp) : comp_(comp) {}
84 bool operator()(StrPair const & sp)
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 = STRCONV(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();
351 FindSnippet(string const & s) : snippet_(s) {}
352 bool operator()(InProgressProcess const & process)
354 BitmapFile const & snippets = process.second.snippets;
355 BitmapFile::const_iterator it = snippets.begin();
356 BitmapFile::const_iterator end = snippets.end();
357 it = find_if(it, end, FindFirst(snippet_));
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 for (; ipit != ipend; ++ipit) {
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 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
460 // As used by the LaTeX file and by the resulting image files
461 string directory = buffer_.tmppath;
462 if (directory.empty())
463 directory = buffer_.filePath();
465 string const filename_base(unique_filename(directory));
467 // Create an InProgress instance to place in the map of all
468 // such processes if it starts correctly.
469 InProgress inprogress(filename_base, pending_, pconverter_->to);
471 // clear pending_, so we're ready to start afresh.
474 // Output the LaTeX file.
475 string const latexfile = filename_base + ".tex";
477 ofstream of(latexfile.c_str());
478 of << "\\batchmode\n";
480 of << "\n\\begin{document}\n";
481 dumpData(of, inprogress.snippets);
482 of << "\n\\end{document}\n";
485 // The conversion command.
487 cs << pconverter_->command << ' ' << latexfile << ' '
488 << int(font_scaling_factor_) << ' ' << pconverter_->to;
490 string const command = "sh " + support::LibScriptSearch(STRCONV(cs.str()));
492 // Initiate the conversion from LaTeX to bitmap images files.
493 support::Forkedcall::SignalTypePtr
494 convert_ptr(new support::Forkedcall::SignalType);
495 convert_ptr->connect(
496 boost::bind(&Impl::finishedGenerating, this, _1, _2));
498 support::Forkedcall call;
499 int ret = call.startscript(command, convert_ptr);
502 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
503 << "Unable to start process \n"
508 // Store the generation process in a list of all such processes
509 inprogress.pid = call.pid();
510 inprogress.command = command;
511 in_progress_[inprogress.pid] = inprogress;
515 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
518 InProgressProcesses::iterator git = in_progress_.find(pid);
519 if (git == in_progress_.end()) {
520 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
521 "data for PID " << pid << endl;
525 string const command = git->second.command;
526 string const status = retval > 0 ? "failed" : "succeeded";
527 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
528 << retval << "): processing " << status
529 << " for " << command << endl;
533 // Read the metrics file, if it exists
534 vector<double> ascent_fractions(git->second.snippets.size());
535 setAscentFractions(ascent_fractions, git->second.metrics_file);
537 // Add these newly generated bitmap files to the cache and
538 // start loading them into LyX.
539 BitmapFile::const_iterator it = git->second.snippets.begin();
540 BitmapFile::const_iterator end = git->second.snippets.end();
542 std::list<PreviewImagePtr> newimages;
544 int metrics_counter = 0;
545 for (; it != end; ++it, ++metrics_counter) {
546 string const & snip = it->first;
547 string const & file = it->second;
548 double af = ascent_fractions[metrics_counter];
550 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
553 newimages.push_back(ptr);
556 // Remove the item from the list of still-executing processes.
557 in_progress_.erase(git);
559 // Tell the outside world
560 std::list<PreviewImagePtr>::const_reverse_iterator
561 nit = newimages.rbegin();
562 std::list<PreviewImagePtr>::const_reverse_iterator
563 nend = newimages.rend();
564 for (; nit != nend; ++nit) {
565 imageReady(*nit->get());
570 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
572 // Why on earth is Buffer::makeLaTeXFile a non-const method?
573 Buffer & tmp = const_cast<Buffer &>(buffer_);
574 // Dump the preamble only.
575 LatexRunParams runparams;
576 runparams.flavor = LatexRunParams::LATEX;
577 runparams.nice = true;
578 runparams.moving_arg = true;
579 runparams.free_spacing = true;
580 tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
582 // FIXME! This is a HACK! The proper fix is to control the 'true'
583 // passed to WriteStream below:
584 // int InsetFormula::latex(Buffer const &, ostream & os,
585 // LatexRunParams const & runparams) const
587 // WriteStream wi(os, runparams.moving_arg, true);
592 << "\\def\\lyxlock{}\n"
595 // Loop over the insets in the buffer and dump all the math-macros.
596 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
597 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
599 for (; it != end; ++it)
600 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
601 it->latex(buffer_, os, runparams);
603 // All equation lables appear as "(#)" + preview.sty's rendering of
605 if (lyxrc.preview_hashed_labels)
606 os << "\\renewcommand{\\theequation}{\\#}\n";
608 // Use the preview style file to ensure that each snippet appears on a
611 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
614 // This piece of PostScript magic ensures that the foreground and
615 // background colors are the same as the LyX screen.
616 string fg = lyx_gui::hexname(LColor::preview);
617 if (fg.empty()) fg = "000000";
619 string bg = lyx_gui::hexname(LColor::background);
620 if (bg.empty()) bg = "ffffff";
622 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
623 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
624 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
625 << "clippath fill setrgbcolor}bind def end}}}\n";
629 void PreviewLoader::Impl::dumpData(ostream & os,
630 BitmapFile const & vec) const
635 BitmapFile::const_iterator it = vec.begin();
636 BitmapFile::const_iterator end = vec.end();
638 for (; it != end; ++it) {
639 os << "\\begin{preview}\n"
641 << "\n\\end{preview}\n\n";
645 } // namespace graphics
650 string const unique_filename(string const bufferpath)
652 static int theCounter = 0;
653 string const filename = tostr(theCounter++) + "lyxpreview";
654 return support::AddName(bufferpath, filename);
658 Converter const * setConverter()
660 string const from = "lyxpreview";
662 Formats::FormatList::const_iterator it = formats.begin();
663 Formats::FormatList::const_iterator end = formats.end();
665 for (; it != end; ++it) {
666 string const to = it->name();
670 Converter const * ptr = converters.getConverter(from, to);
675 static bool first = true;
678 lyxerr << "PreviewLoader::startLoading()\n"
679 << "No converter from \"lyxpreview\" format has been "
688 void setAscentFractions(vector<double> & ascent_fractions,
689 string const & metrics_file)
691 // If all else fails, then the images will have equal ascents and
693 vector<double>::iterator it = ascent_fractions.begin();
694 vector<double>::iterator end = ascent_fractions.end();
697 ifstream in(metrics_file.c_str());
699 lyxerr[Debug::GRAPHICS]
700 << "setAscentFractions(" << metrics_file << ")\n"
701 << "Unable to open file!" << endl;
707 // Tightpage dimensions affect all subsequent dimensions
711 int snippet_counter = 0;
713 // Expecting lines of the form
714 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
715 // Preview: Snippet id ascent descent width
718 in >> preview >> type;
724 error = preview != "Preview:"
725 || (type != "Tightpage" && type != "Snippet");
729 if (type == "Tightpage") {
731 in >> dummy >> tp_descent >> dummy >> tp_ascent;
742 in >> snippet_id >> ascent >> descent >> dummy;
744 error = !in.good() || ++snippet_counter != snippet_id;
748 double const a = ascent + tp_ascent;
749 double const d = descent - tp_descent;
751 if (!support::float_equal(a + d, 0, 0.1))
760 lyxerr[Debug::GRAPHICS]
761 << "setAscentFractions(" << metrics_file << ")\n"
762 << "Error reading file!\n" << endl;