2 * \file PreviewLoader.C
3 * Copyright 2002 the LyX Team
4 * Read the file COPYING
6 * \author Angus Leeming <leeming@lyx.org>
12 #pragma implementation
15 #include "PreviewLoader.h"
16 #include "PreviewImage.h"
19 #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/lstrings.h"
32 #include "support/lyxlib.h"
34 #include <boost/bind.hpp>
35 #include <boost/signals/trackable.hpp>
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 // Given a base-10 number return the number of digits needed to store it.
90 // Eg 2 requires 1 digit, 22 requires 2 digits and 999 requires 3 digits.
91 // Note that André suggests just returning '12' here...
92 int ndigits(int /*num*/)
94 //return 1 + int(std::log10(double(num)));
99 /// Store info on a currently executing, forked process.
102 InProgress() : pid(0) {}
104 InProgress(string const & filename_base,
105 PendingSnippets const & pending,
106 string const & to_format);
107 /// Remove any files left lying around and kill the forked process.
118 typedef map<string, InProgress> InProgressProcesses;
120 typedef InProgressProcesses::value_type InProgressProcess;
127 struct PreviewLoader::Impl : public boost::signals::trackable {
129 Impl(PreviewLoader & p, Buffer const & b);
130 /// Stop any InProgress items still executing.
133 PreviewImage const * preview(string const & latex_snippet) const;
135 PreviewLoader::Status status(string const & latex_snippet) const;
137 void add(string const & latex_snippet);
139 void remove(string const & latex_snippet);
143 /// Emit this signal when an image is ready for display.
144 boost::signal1<void, PreviewImage const &> imageReady;
146 Buffer const & buffer() const { return buffer_; }
149 /// Called by the Forkedcall process that generated the bitmap files.
150 void finishedGenerating(string const &, pid_t, int);
152 void dumpPreamble(ostream &) const;
154 void dumpData(ostream &, BitmapFile const &) const;
156 /** cache_ allows easy retrieval of already-generated images
157 * using the LaTeX snippet as the identifier.
159 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
161 typedef map<string, PreviewImagePtr> Cache;
165 /** pending_ stores the LaTeX snippets in anticipation of them being
166 * sent to the converter.
168 PendingSnippets pending_;
170 /** in_progress_ stores all forked processes so that we can proceed
172 The map uses the conversion commands as its identifiers.
174 InProgressProcesses in_progress_;
177 PreviewLoader & parent_;
179 Buffer const & buffer_;
181 double font_scaling_factor_;
183 /// We don't own this
184 static Converter const * pconverter_;
188 Converter const * PreviewLoader::Impl::pconverter_;
191 // The public interface, defined in PreviewLoader.h
192 // ================================================
193 PreviewLoader::PreviewLoader(Buffer const & b)
194 : pimpl_(new Impl(*this, b))
198 PreviewLoader::~PreviewLoader()
202 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
204 return pimpl_->preview(latex_snippet);
208 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
210 return pimpl_->status(latex_snippet);
214 void PreviewLoader::add(string const & latex_snippet) const
216 pimpl_->add(latex_snippet);
220 void PreviewLoader::remove(string const & latex_snippet) const
222 pimpl_->remove(latex_snippet);
226 void PreviewLoader::startLoading() const
228 pimpl_->startLoading();
232 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
234 return pimpl_->imageReady.connect(slot);
238 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
240 pimpl_->imageReady(pimage);
244 Buffer const & PreviewLoader::buffer() const
246 return pimpl_->buffer();
252 // The details of the Impl
253 // =======================
257 struct IncrementedFileName {
258 IncrementedFileName(string const & to_format,
259 string const & filename_base, int nd)
260 : to_format_(to_format), base_(filename_base),
261 ndigits_(nd), counter_(1)
264 StrPair const operator()(string const & snippet)
268 << setfill('0') << setw(ndigits_) << counter_++
269 << "." << to_format_;
271 string const file = os.str().c_str();
273 return make_pair(snippet, file);
277 string const & to_format_;
278 string const & base_;
284 InProgress::InProgress(string const & filename_base,
285 PendingSnippets const & pending,
286 string const & to_format)
288 metrics_file(filename_base + ".metrics"),
289 snippets(pending.size())
291 PendingSnippets::const_iterator pit = pending.begin();
292 PendingSnippets::const_iterator pend = pending.end();
293 BitmapFile::iterator sit = snippets.begin();
295 std::transform(pit, pend, sit,
296 IncrementedFileName(to_format, filename_base,
297 ndigits(int(snippets.size()))));
301 void InProgress::stop() const
304 ForkedcallsController::get().kill(pid, 0);
306 if (!metrics_file.empty())
307 lyx::unlink(metrics_file);
309 BitmapFile::const_iterator vit = snippets.begin();
310 BitmapFile::const_iterator vend = snippets.end();
311 for (; vit != vend; ++vit) {
312 if (!vit->second.empty())
313 lyx::unlink(vit->second);
322 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
323 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
325 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
326 lyxrc.preview_scale_factor;
328 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
329 << font_scaling_factor_ << endl;
332 pconverter_ = setConverter();
336 PreviewLoader::Impl::~Impl()
338 InProgressProcesses::iterator ipit = in_progress_.begin();
339 InProgressProcesses::iterator ipend = in_progress_.end();
341 for (; ipit != ipend; ++ipit) {
348 PreviewLoader::Impl::preview(string const & latex_snippet) const
350 Cache::const_iterator it = cache_.find(latex_snippet);
351 return (it == cache_.end()) ? 0 : it->second.get();
358 FindSnippet(string const & s) : snippet_(s) {}
359 bool operator()(InProgressProcess const & process)
361 BitmapFile const & snippets = process.second.snippets;
362 BitmapFile::const_iterator it = snippets.begin();
363 BitmapFile::const_iterator end = snippets.end();
364 it = find_if(it, end, FindFirst(snippet_));
369 string const & snippet_;
374 PreviewLoader::Status
375 PreviewLoader::Impl::status(string const & latex_snippet) const
377 Cache::const_iterator cit = cache_.find(latex_snippet);
378 if (cit != cache_.end())
381 PendingSnippets::const_iterator pit = pending_.begin();
382 PendingSnippets::const_iterator pend = pending_.end();
384 pit = find(pit, pend, latex_snippet);
388 InProgressProcesses::const_iterator ipit = in_progress_.begin();
389 InProgressProcesses::const_iterator ipend = in_progress_.end();
391 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
399 void PreviewLoader::Impl::add(string const & latex_snippet)
401 if (!pconverter_ || status(latex_snippet) != NotFound)
404 string const snippet = trim(latex_snippet);
408 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
410 pending_.push_back(snippet);
416 struct EraseSnippet {
417 EraseSnippet(string const & s) : snippet_(s) {}
418 void operator()(InProgressProcess & process)
420 BitmapFile & snippets = process.second.snippets;
421 BitmapFile::iterator it = snippets.begin();
422 BitmapFile::iterator end = snippets.end();
424 it = find_if(it, end, FindFirst(snippet_));
426 snippets.erase(it, it+1);
430 string const & snippet_;
436 void PreviewLoader::Impl::remove(string const & latex_snippet)
438 Cache::iterator cit = cache_.find(latex_snippet);
439 if (cit != cache_.end())
442 PendingSnippets::iterator pit = pending_.begin();
443 PendingSnippets::iterator pend = pending_.end();
445 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
447 InProgressProcesses::iterator ipit = in_progress_.begin();
448 InProgressProcesses::iterator ipend = in_progress_.end();
450 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
452 for (; ipit != ipend; ++ipit) {
453 InProgressProcesses::iterator curr = ipit++;
454 if (curr->second.snippets.empty())
455 in_progress_.erase(curr);
460 void PreviewLoader::Impl::startLoading()
462 if (pending_.empty() || !pconverter_)
465 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
467 // As used by the LaTeX file and by the resulting image files
468 string const filename_base(unique_filename(buffer_.tmppath));
470 // Create an InProgress instance to place in the map of all
471 // such processes if it starts correctly.
472 InProgress inprogress(filename_base, pending_, pconverter_->to);
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_) << " "
489 << ndigits(int(pending_.size()));
491 string const command = LibScriptSearch(cs.str().c_str());
493 // clear pending_, so we're ready to start afresh.
496 // Initiate the conversion from LaTeX to bitmap images files.
497 Forkedcall::SignalTypePtr convert_ptr;
498 convert_ptr.reset(new Forkedcall::SignalType);
500 convert_ptr->connect(
501 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
504 int ret = call.startscript(command, convert_ptr);
507 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
508 << "Unable to start process \n"
513 // Store the generation process in a list of all such processes
514 inprogress.pid = call.pid();
515 in_progress_[command] = inprogress;
519 void PreviewLoader::Impl::finishedGenerating(string const & command,
520 pid_t /* pid */, int retval)
522 string const status = retval > 0 ? "failed" : "succeeded";
523 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
524 << retval << "): processing " << status
525 << " for " << command << endl;
530 InProgressProcesses::iterator git = in_progress_.find(command);
531 if (git == in_progress_.end()) {
532 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
534 << command << "!" << endl;
538 // Read the metrics file, if it exists
539 vector<double> ascent_fractions(git->second.snippets.size());
540 setAscentFractions(ascent_fractions, git->second.metrics_file);
542 // Add these newly generated bitmap files to the cache and
543 // start loading them into LyX.
544 BitmapFile::const_iterator it = git->second.snippets.begin();
545 BitmapFile::const_iterator end = git->second.snippets.end();
547 std::list<PreviewImagePtr> newimages;
549 int metrics_counter = 0;
550 for (; it != end; ++it, ++metrics_counter) {
551 string const & snip = it->first;
552 string const & file = it->second;
553 double af = ascent_fractions[metrics_counter];
555 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
558 newimages.push_back(ptr);
561 // Remove the item from the list of still-executing processes.
562 in_progress_.erase(git);
564 // Tell the outside world
565 std::list<PreviewImagePtr>::const_iterator nit = newimages.begin();
566 std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
567 for (; nit != nend; ++nit) {
568 imageReady(*nit->get());
573 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
575 // Why on earth is Buffer::makeLaTeXFile a non-const method?
576 Buffer & tmp = const_cast<Buffer &>(buffer_);
577 // Dump the preamble only.
578 tmp.makeLaTeXFile(os, buffer_.filePath(), true, false, true);
580 // Loop over the insets in the buffer and dump all the math-macros.
581 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
582 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
584 for (; it != end; ++it)
585 if (it->lyxCode() == Inset::MATHMACRO_CODE)
586 it->latex(&buffer_, os, true, true);
588 // All equation lables appear as "(#)" + preview.sty's rendering of
590 if (lyxrc.preview_hashed_labels)
591 os << "\\renewcommand{\\theequation}{\\#}\n";
593 // Use the preview style file to ensure that each snippet appears on a
596 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
599 // This piece of PostScript magic ensures that the foreground and
600 // background colors are the same as the LyX screen.
601 string fg = lyx_gui::hexname(LColor::preview);
602 if (fg.empty()) fg = "000000";
604 string bg = lyx_gui::hexname(LColor::background);
605 if (bg.empty()) bg = "ffffff";
607 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
608 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
609 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
610 << "clippath fill setrgbcolor}bind def end}}}\n";
614 void PreviewLoader::Impl::dumpData(ostream & os,
615 BitmapFile const & vec) const
620 BitmapFile::const_iterator it = vec.begin();
621 BitmapFile::const_iterator end = vec.end();
623 for (; it != end; ++it) {
624 os << "\\begin{preview}\n"
626 << "\n\\end{preview}\n\n";
635 string const unique_filename(string const bufferpath)
637 static int theCounter = 0;
638 string const filename = tostr(theCounter++) + "lyxpreview";
639 return AddName(bufferpath, filename);
643 Converter const * setConverter()
645 string const from = "lyxpreview";
647 Formats::FormatList::const_iterator it = formats.begin();
648 Formats::FormatList::const_iterator end = formats.end();
650 for (; it != end; ++it) {
651 string const to = it->name();
655 Converter const * ptr = converters.getConverter(from, to);
660 static bool first = true;
663 lyxerr << "PreviewLoader::startLoading()\n"
664 << "No converter from \"lyxpreview\" format has been "
673 void setAscentFractions(vector<double> & ascent_fractions,
674 string const & metrics_file)
676 // If all else fails, then the images will have equal ascents and
678 vector<double>::iterator it = ascent_fractions.begin();
679 vector<double>::iterator end = ascent_fractions.end();
682 ifstream in(metrics_file.c_str());
684 lyxerr[Debug::GRAPHICS]
685 << "setAscentFractions(" << metrics_file << ")\n"
686 << "Unable to open file!" << endl;
692 // Tightpage dimensions affect all subsequent dimensions
696 int snippet_counter = 0;
698 // Expecting lines of the form
699 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
700 // Preview: Snippet id ascent descent width
703 in >> preview >> type;
709 error = preview != "Preview:"
710 || (type != "Tightpage" && type != "Snippet");
714 if (type == "Tightpage") {
716 in >> dummy >> tp_descent >> dummy >> tp_ascent;
727 in >> snippet_id >> ascent >> descent >> dummy;
729 error = !in.good() || ++snippet_counter != snippet_id;
733 double const a = ascent + tp_ascent;
734 double const d = descent - tp_descent;
736 if (!lyx::float_equal(a + d, 0, 0.1))
745 lyxerr[Debug::GRAPHICS]
746 << "setAscentFractions(" << metrics_file << ")\n"
747 << "Error reading file!\n" << endl;