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
14 #pragma implementation
17 #include "PreviewLoader.h"
18 #include "PreviewImage.h"
21 #include "converter.h"
26 #include "insets/inset.h"
28 #include "frontends/lyx_gui.h" // hexname
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"
36 #include <boost/bind.hpp>
37 #include <boost/signals/trackable.hpp>
65 typedef pair<string, string> StrPair;
67 // A list of alll snippets to be converted to previews
68 typedef list<string> PendingSnippets;
70 // Each item in the vector is a pair<snippet, image file name>.
71 typedef vector<StrPair> BitmapFile;
73 string const unique_filename(string const bufferpath);
75 Converter const * setConverter();
77 void setAscentFractions(vector<double> & ascent_fractions,
78 string const & metrics_file);
81 FindFirst(string const & comp) : comp_(comp) {}
82 bool operator()(StrPair const & sp)
84 return sp.first < comp_;
91 /// Store info on a currently executing, forked process.
94 InProgress() : pid(0) {}
96 InProgress(string const & filename_base,
97 PendingSnippets const & pending,
98 string const & to_format);
99 /// Remove any files left lying around and kill the forked process.
110 typedef map<string, InProgress> InProgressProcesses;
112 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(string const &, 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();
244 // The details of the Impl
245 // =======================
249 struct IncrementedFileName {
250 IncrementedFileName(string const & to_format,
251 string const & filename_base)
252 : to_format_(to_format), base_(filename_base), counter_(1)
255 StrPair const operator()(string const & snippet)
258 os << base_ << counter_++ << "." << to_format_;
259 string const file = os.str().c_str();
261 return make_pair(snippet, file);
265 string const & to_format_;
266 string const & base_;
271 InProgress::InProgress(string const & filename_base,
272 PendingSnippets const & pending,
273 string const & to_format)
275 metrics_file(filename_base + ".metrics"),
276 snippets(pending.size())
278 PendingSnippets::const_iterator pit = pending.begin();
279 PendingSnippets::const_iterator pend = pending.end();
280 BitmapFile::iterator sit = snippets.begin();
282 std::transform(pit, pend, sit,
283 IncrementedFileName(to_format, filename_base));
287 void InProgress::stop() const
290 ForkedcallsController::get().kill(pid, 0);
292 if (!metrics_file.empty())
293 lyx::unlink(metrics_file);
295 BitmapFile::const_iterator vit = snippets.begin();
296 BitmapFile::const_iterator vend = snippets.end();
297 for (; vit != vend; ++vit) {
298 if (!vit->second.empty())
299 lyx::unlink(vit->second);
308 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
309 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
311 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
312 lyxrc.preview_scale_factor;
314 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
315 << font_scaling_factor_ << endl;
318 pconverter_ = setConverter();
322 PreviewLoader::Impl::~Impl()
324 InProgressProcesses::iterator ipit = in_progress_.begin();
325 InProgressProcesses::iterator ipend = in_progress_.end();
327 for (; ipit != ipend; ++ipit) {
334 PreviewLoader::Impl::preview(string const & latex_snippet) const
336 Cache::const_iterator it = cache_.find(latex_snippet);
337 return (it == cache_.end()) ? 0 : it->second.get();
344 FindSnippet(string const & s) : snippet_(s) {}
345 bool operator()(InProgressProcess const & process)
347 BitmapFile const & snippets = process.second.snippets;
348 BitmapFile::const_iterator it = snippets.begin();
349 BitmapFile::const_iterator end = snippets.end();
350 it = find_if(it, end, FindFirst(snippet_));
355 string const & snippet_;
360 PreviewLoader::Status
361 PreviewLoader::Impl::status(string const & latex_snippet) const
363 Cache::const_iterator cit = cache_.find(latex_snippet);
364 if (cit != cache_.end())
367 PendingSnippets::const_iterator pit = pending_.begin();
368 PendingSnippets::const_iterator pend = pending_.end();
370 pit = find(pit, pend, latex_snippet);
374 InProgressProcesses::const_iterator ipit = in_progress_.begin();
375 InProgressProcesses::const_iterator ipend = in_progress_.end();
377 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
385 void PreviewLoader::Impl::add(string const & latex_snippet)
387 if (!pconverter_ || status(latex_snippet) != NotFound)
390 string const snippet = trim(latex_snippet);
394 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
396 pending_.push_back(snippet);
402 struct EraseSnippet {
403 EraseSnippet(string const & s) : snippet_(s) {}
404 void operator()(InProgressProcess & process)
406 BitmapFile & snippets = process.second.snippets;
407 BitmapFile::iterator it = snippets.begin();
408 BitmapFile::iterator end = snippets.end();
410 it = find_if(it, end, FindFirst(snippet_));
412 snippets.erase(it, it+1);
416 string const & snippet_;
422 void PreviewLoader::Impl::remove(string const & latex_snippet)
424 Cache::iterator cit = cache_.find(latex_snippet);
425 if (cit != cache_.end())
428 PendingSnippets::iterator pit = pending_.begin();
429 PendingSnippets::iterator pend = pending_.end();
431 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
433 InProgressProcesses::iterator ipit = in_progress_.begin();
434 InProgressProcesses::iterator ipend = in_progress_.end();
436 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
438 for (; ipit != ipend; ++ipit) {
439 InProgressProcesses::iterator curr = ipit++;
440 if (curr->second.snippets.empty())
441 in_progress_.erase(curr);
446 void PreviewLoader::Impl::startLoading()
448 if (pending_.empty() || !pconverter_)
451 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
453 // As used by the LaTeX file and by the resulting image files
454 string const filename_base(unique_filename(buffer_.tmppath));
456 // Create an InProgress instance to place in the map of all
457 // such processes if it starts correctly.
458 InProgress inprogress(filename_base, pending_, pconverter_->to);
460 // clear pending_, so we're ready to start afresh.
463 // Output the LaTeX file.
464 string const latexfile = filename_base + ".tex";
466 ofstream of(latexfile.c_str());
467 of << "\\batchmode\n";
469 of << "\n\\begin{document}\n";
470 dumpData(of, inprogress.snippets);
471 of << "\n\\end{document}\n";
474 // The conversion command.
476 cs << pconverter_->command << " " << latexfile << " "
477 << int(font_scaling_factor_) << " " << pconverter_->to;
479 string const command = "sh " + LibScriptSearch(cs.str().c_str());
481 // Initiate the conversion from LaTeX to bitmap images files.
482 Forkedcall::SignalTypePtr convert_ptr(new Forkedcall::SignalType);
483 convert_ptr->connect(
484 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
487 int ret = call.startscript(command, convert_ptr);
490 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
491 << "Unable to start process \n"
496 // Store the generation process in a list of all such processes
497 inprogress.pid = call.pid();
498 in_progress_[command] = inprogress;
502 void PreviewLoader::Impl::finishedGenerating(string const & command,
503 pid_t /* pid */, int retval)
505 string const status = retval > 0 ? "failed" : "succeeded";
506 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
507 << retval << "): processing " << status
508 << " for " << command << endl;
513 InProgressProcesses::iterator git = in_progress_.find(command);
514 if (git == in_progress_.end()) {
515 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
517 << command << "!" << endl;
521 // Read the metrics file, if it exists
522 vector<double> ascent_fractions(git->second.snippets.size());
523 setAscentFractions(ascent_fractions, git->second.metrics_file);
525 // Add these newly generated bitmap files to the cache and
526 // start loading them into LyX.
527 BitmapFile::const_iterator it = git->second.snippets.begin();
528 BitmapFile::const_iterator end = git->second.snippets.end();
530 std::list<PreviewImagePtr> newimages;
532 int metrics_counter = 0;
533 for (; it != end; ++it, ++metrics_counter) {
534 string const & snip = it->first;
535 string const & file = it->second;
536 double af = ascent_fractions[metrics_counter];
538 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
541 newimages.push_back(ptr);
544 // Remove the item from the list of still-executing processes.
545 in_progress_.erase(git);
547 // Tell the outside world
548 std::list<PreviewImagePtr>::const_iterator nit = newimages.begin();
549 std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
550 for (; nit != nend; ++nit) {
551 imageReady(*nit->get());
556 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
558 // Why on earth is Buffer::makeLaTeXFile a non-const method?
559 Buffer & tmp = const_cast<Buffer &>(buffer_);
560 // Dump the preamble only.
561 tmp.makeLaTeXFile(os, buffer_.filePath(), true, false, true);
563 // Loop over the insets in the buffer and dump all the math-macros.
564 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
565 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
567 for (; it != end; ++it)
568 if (it->lyxCode() == Inset::MATHMACRO_CODE)
569 it->latex(&buffer_, os, true, true);
571 // All equation lables appear as "(#)" + preview.sty's rendering of
573 if (lyxrc.preview_hashed_labels)
574 os << "\\renewcommand{\\theequation}{\\#}\n";
576 // Use the preview style file to ensure that each snippet appears on a
579 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
582 // This piece of PostScript magic ensures that the foreground and
583 // background colors are the same as the LyX screen.
584 string fg = lyx_gui::hexname(LColor::preview);
585 if (fg.empty()) fg = "000000";
587 string bg = lyx_gui::hexname(LColor::background);
588 if (bg.empty()) bg = "ffffff";
590 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
591 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
592 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
593 << "clippath fill setrgbcolor}bind def end}}}\n";
597 void PreviewLoader::Impl::dumpData(ostream & os,
598 BitmapFile const & vec) const
603 BitmapFile::const_iterator it = vec.begin();
604 BitmapFile::const_iterator end = vec.end();
606 for (; it != end; ++it) {
607 os << "\\begin{preview}\n"
609 << "\n\\end{preview}\n\n";
618 string const unique_filename(string const bufferpath)
620 static int theCounter = 0;
621 string const filename = tostr(theCounter++) + "lyxpreview";
622 return AddName(bufferpath, filename);
626 Converter const * setConverter()
628 string const from = "lyxpreview";
630 Formats::FormatList::const_iterator it = formats.begin();
631 Formats::FormatList::const_iterator end = formats.end();
633 for (; it != end; ++it) {
634 string const to = it->name();
638 Converter const * ptr = converters.getConverter(from, to);
643 static bool first = true;
646 lyxerr << "PreviewLoader::startLoading()\n"
647 << "No converter from \"lyxpreview\" format has been "
656 void setAscentFractions(vector<double> & ascent_fractions,
657 string const & metrics_file)
659 // If all else fails, then the images will have equal ascents and
661 vector<double>::iterator it = ascent_fractions.begin();
662 vector<double>::iterator end = ascent_fractions.end();
665 ifstream in(metrics_file.c_str());
667 lyxerr[Debug::GRAPHICS]
668 << "setAscentFractions(" << metrics_file << ")\n"
669 << "Unable to open file!" << endl;
675 // Tightpage dimensions affect all subsequent dimensions
679 int snippet_counter = 0;
681 // Expecting lines of the form
682 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
683 // Preview: Snippet id ascent descent width
686 in >> preview >> type;
692 error = preview != "Preview:"
693 || (type != "Tightpage" && type != "Snippet");
697 if (type == "Tightpage") {
699 in >> dummy >> tp_descent >> dummy >> tp_ascent;
710 in >> snippet_id >> ascent >> descent >> dummy;
712 error = !in.good() || ++snippet_counter != snippet_id;
716 double const a = ascent + tp_ascent;
717 double const d = descent - tp_descent;
719 if (!lyx::float_equal(a + d, 0, 0.1))
728 lyxerr[Debug::GRAPHICS]
729 << "setAscentFractions(" << metrics_file << ")\n"
730 << "Error reading file!\n" << endl;