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 "latexrunparams.h"
23 #include "frontends/lyx_gui.h" // hexname
25 #include "support/filetools.h"
26 #include "support/forkedcall.h"
27 #include "support/forkedcontr.h"
28 #include "support/lstrings.h"
29 #include "support/lyxlib.h"
30 #include "support/tostr.h"
32 #include <boost/bind.hpp>
34 #include "support/std_sstream.h"
38 namespace support = lyx::support;
51 using std::ostringstream;
58 typedef pair<string, string> StrPair;
60 // A list of alll snippets to be converted to previews
61 typedef list<string> PendingSnippets;
63 // Each item in the vector is a pair<snippet, image file name>.
64 typedef vector<StrPair> BitmapFile;
66 string const unique_filename(string const bufferpath);
68 Converter const * setConverter();
70 void setAscentFractions(vector<double> & ascent_fractions,
71 string const & metrics_file);
74 FindFirst(string const & comp) : comp_(comp) {}
75 bool operator()(StrPair const & sp)
77 return sp.first == comp_;
84 /// Store info on a currently executing, forked process.
87 InProgress() : pid(0) {}
89 InProgress(string const & filename_base,
90 PendingSnippets const & pending,
91 string const & to_format);
92 /// Remove any files left lying around and kill the forked process.
105 typedef map<pid_t, InProgress> InProgressProcesses;
107 typedef InProgressProcesses::value_type InProgressProcess;
115 struct PreviewLoader::Impl : public boost::signals::trackable {
117 Impl(PreviewLoader & p, Buffer const & b);
118 /// Stop any InProgress items still executing.
121 PreviewImage const * preview(string const & latex_snippet) const;
123 PreviewLoader::Status status(string const & latex_snippet) const;
125 void add(string const & latex_snippet);
127 void remove(string const & latex_snippet);
131 /// Emit this signal when an image is ready for display.
132 boost::signal1<void, PreviewImage const &> imageReady;
134 Buffer const & buffer() const { return buffer_; }
137 /// Called by the Forkedcall process that generated the bitmap files.
138 void finishedGenerating(pid_t, int);
140 void dumpPreamble(ostream &) const;
142 void dumpData(ostream &, BitmapFile const &) const;
144 /** cache_ allows easy retrieval of already-generated images
145 * using the LaTeX snippet as the identifier.
147 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
149 typedef map<string, PreviewImagePtr> Cache;
153 /** pending_ stores the LaTeX snippets in anticipation of them being
154 * sent to the converter.
156 PendingSnippets pending_;
158 /** in_progress_ stores all forked processes so that we can proceed
160 The map uses the conversion commands as its identifiers.
162 InProgressProcesses in_progress_;
165 PreviewLoader & parent_;
167 Buffer const & buffer_;
169 double font_scaling_factor_;
171 /// We don't own this
172 static Converter const * pconverter_;
176 Converter const * PreviewLoader::Impl::pconverter_;
179 // The public interface, defined in PreviewLoader.h
180 // ================================================
181 PreviewLoader::PreviewLoader(Buffer const & b)
182 : pimpl_(new Impl(*this, b))
186 PreviewLoader::~PreviewLoader()
190 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
192 return pimpl_->preview(latex_snippet);
196 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
198 return pimpl_->status(latex_snippet);
202 void PreviewLoader::add(string const & latex_snippet) const
204 pimpl_->add(latex_snippet);
208 void PreviewLoader::remove(string const & latex_snippet) const
210 pimpl_->remove(latex_snippet);
214 void PreviewLoader::startLoading() const
216 pimpl_->startLoading();
220 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
222 return pimpl_->imageReady.connect(slot);
226 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
228 pimpl_->imageReady(pimage);
232 Buffer const & PreviewLoader::buffer() const
234 return pimpl_->buffer();
237 } // namespace graphics
241 // The details of the Impl
242 // =======================
246 struct IncrementedFileName {
247 IncrementedFileName(string const & to_format,
248 string const & filename_base)
249 : to_format_(to_format), base_(filename_base), counter_(1)
252 StrPair const operator()(string const & snippet)
255 os << base_ << counter_++ << '.' << to_format_;
256 string const file = STRCONV(os.str());
258 return make_pair(snippet, file);
262 string const & to_format_;
263 string const & base_;
268 InProgress::InProgress(string const & filename_base,
269 PendingSnippets const & pending,
270 string const & to_format)
272 metrics_file(filename_base + ".metrics"),
273 snippets(pending.size())
275 PendingSnippets::const_iterator pit = pending.begin();
276 PendingSnippets::const_iterator pend = pending.end();
277 BitmapFile::iterator sit = snippets.begin();
279 std::transform(pit, pend, sit,
280 IncrementedFileName(to_format, filename_base));
284 void InProgress::stop() const
287 support::ForkedcallsController::get().kill(pid, 0);
289 if (!metrics_file.empty())
290 support::unlink(metrics_file);
292 BitmapFile::const_iterator vit = snippets.begin();
293 BitmapFile::const_iterator vend = snippets.end();
294 for (; vit != vend; ++vit) {
295 if (!vit->second.empty())
296 support::unlink(vit->second);
306 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
307 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
309 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
310 lyxrc.preview_scale_factor;
312 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
313 << font_scaling_factor_ << endl;
316 pconverter_ = setConverter();
320 PreviewLoader::Impl::~Impl()
322 InProgressProcesses::iterator ipit = in_progress_.begin();
323 InProgressProcesses::iterator ipend = in_progress_.end();
325 for (; ipit != ipend; ++ipit) {
332 PreviewLoader::Impl::preview(string const & latex_snippet) const
334 Cache::const_iterator it = cache_.find(latex_snippet);
335 return (it == cache_.end()) ? 0 : it->second.get();
342 FindSnippet(string const & s) : snippet_(s) {}
343 bool operator()(InProgressProcess const & process)
345 BitmapFile const & snippets = process.second.snippets;
346 BitmapFile::const_iterator it = snippets.begin();
347 BitmapFile::const_iterator end = snippets.end();
348 it = find_if(it, end, FindFirst(snippet_));
353 string const & snippet_;
358 PreviewLoader::Status
359 PreviewLoader::Impl::status(string const & latex_snippet) const
361 Cache::const_iterator cit = cache_.find(latex_snippet);
362 if (cit != cache_.end())
365 PendingSnippets::const_iterator pit = pending_.begin();
366 PendingSnippets::const_iterator pend = pending_.end();
368 pit = find(pit, pend, latex_snippet);
372 InProgressProcesses::const_iterator ipit = in_progress_.begin();
373 InProgressProcesses::const_iterator ipend = in_progress_.end();
375 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
383 void PreviewLoader::Impl::add(string const & latex_snippet)
385 if (!pconverter_ || status(latex_snippet) != NotFound)
388 string const snippet = support::trim(latex_snippet);
392 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
394 pending_.push_back(snippet);
400 struct EraseSnippet {
401 EraseSnippet(string const & s) : snippet_(s) {}
402 void operator()(InProgressProcess & process)
404 BitmapFile & snippets = process.second.snippets;
405 BitmapFile::iterator it = snippets.begin();
406 BitmapFile::iterator end = snippets.end();
408 it = find_if(it, end, FindFirst(snippet_));
410 snippets.erase(it, it+1);
414 string const & snippet_;
420 void PreviewLoader::Impl::remove(string const & latex_snippet)
422 Cache::iterator cit = cache_.find(latex_snippet);
423 if (cit != cache_.end())
426 PendingSnippets::iterator pit = pending_.begin();
427 PendingSnippets::iterator pend = pending_.end();
429 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
431 InProgressProcesses::iterator ipit = in_progress_.begin();
432 InProgressProcesses::iterator ipend = in_progress_.end();
434 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
436 for (; ipit != ipend; ++ipit) {
437 InProgressProcesses::iterator curr = ipit++;
438 if (curr->second.snippets.empty())
439 in_progress_.erase(curr);
444 void PreviewLoader::Impl::startLoading()
446 if (pending_.empty() || !pconverter_)
449 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
451 // As used by the LaTeX file and by the resulting image files
452 string directory = buffer_.temppath();
453 if (directory.empty())
454 directory = buffer_.filePath();
456 string const filename_base(unique_filename(directory));
458 // Create an InProgress instance to place in the map of all
459 // such processes if it starts correctly.
460 InProgress inprogress(filename_base, pending_, pconverter_->to);
462 // clear pending_, so we're ready to start afresh.
465 // Output the LaTeX file.
466 string const latexfile = filename_base + ".tex";
468 ofstream of(latexfile.c_str());
469 of << "\\batchmode\n";
471 of << "\n\\begin{document}\n";
472 dumpData(of, inprogress.snippets);
473 of << "\n\\end{document}\n";
476 // The conversion command.
478 cs << pconverter_->command << ' ' << latexfile << ' '
479 << int(font_scaling_factor_) << ' ' << pconverter_->to;
481 string const command = "sh " + support::LibScriptSearch(STRCONV(cs.str()));
483 // Initiate the conversion from LaTeX to bitmap images files.
484 support::Forkedcall::SignalTypePtr
485 convert_ptr(new support::Forkedcall::SignalType);
486 convert_ptr->connect(
487 boost::bind(&Impl::finishedGenerating, this, _1, _2));
489 support::Forkedcall call;
490 int ret = call.startscript(command, convert_ptr);
493 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
494 << "Unable to start process \n"
499 // Store the generation process in a list of all such processes
500 inprogress.pid = call.pid();
501 inprogress.command = command;
502 in_progress_[inprogress.pid] = inprogress;
506 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
509 InProgressProcesses::iterator git = in_progress_.find(pid);
510 if (git == in_progress_.end()) {
511 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
512 "data for PID " << pid << endl;
516 string const command = git->second.command;
517 string const status = retval > 0 ? "failed" : "succeeded";
518 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
519 << retval << "): processing " << status
520 << " for " << command << endl;
524 // Read the metrics file, if it exists
525 vector<double> ascent_fractions(git->second.snippets.size());
526 setAscentFractions(ascent_fractions, git->second.metrics_file);
528 // Add these newly generated bitmap files to the cache and
529 // start loading them into LyX.
530 BitmapFile::const_iterator it = git->second.snippets.begin();
531 BitmapFile::const_iterator end = git->second.snippets.end();
533 std::list<PreviewImagePtr> newimages;
535 int metrics_counter = 0;
536 for (; it != end; ++it, ++metrics_counter) {
537 string const & snip = it->first;
538 string const & file = it->second;
539 double af = ascent_fractions[metrics_counter];
541 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
544 newimages.push_back(ptr);
547 // Remove the item from the list of still-executing processes.
548 in_progress_.erase(git);
550 // Tell the outside world
551 std::list<PreviewImagePtr>::const_reverse_iterator
552 nit = newimages.rbegin();
553 std::list<PreviewImagePtr>::const_reverse_iterator
554 nend = newimages.rend();
555 for (; nit != nend; ++nit) {
556 imageReady(*nit->get());
561 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
563 // Why on earth is Buffer::makeLaTeXFile a non-const method?
564 Buffer & tmp = const_cast<Buffer &>(buffer_);
565 // Dump the preamble only.
566 LatexRunParams runparams;
567 runparams.flavor = LatexRunParams::LATEX;
568 runparams.nice = true;
569 runparams.moving_arg = true;
570 runparams.free_spacing = true;
571 tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
573 // FIXME! This is a HACK! The proper fix is to control the 'true'
574 // passed to WriteStream below:
575 // int InsetFormula::latex(Buffer const &, ostream & os,
576 // LatexRunParams const & runparams) const
578 // WriteStream wi(os, runparams.moving_arg, true);
583 << "\\def\\lyxlock{}\n"
586 // Loop over the insets in the buffer and dump all the math-macros.
587 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
588 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
590 for (; it != end; ++it)
591 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
592 it->latex(buffer_, os, runparams);
594 // All equation lables appear as "(#)" + preview.sty's rendering of
596 if (lyxrc.preview_hashed_labels)
597 os << "\\renewcommand{\\theequation}{\\#}\n";
599 // Use the preview style file to ensure that each snippet appears on a
602 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
605 // This piece of PostScript magic ensures that the foreground and
606 // background colors are the same as the LyX screen.
607 string fg = lyx_gui::hexname(LColor::preview);
608 if (fg.empty()) fg = "000000";
610 string bg = lyx_gui::hexname(LColor::background);
611 if (bg.empty()) bg = "ffffff";
613 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
614 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
615 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
616 << "clippath fill setrgbcolor}bind def end}}}\n";
620 void PreviewLoader::Impl::dumpData(ostream & os,
621 BitmapFile const & vec) const
626 BitmapFile::const_iterator it = vec.begin();
627 BitmapFile::const_iterator end = vec.end();
629 for (; it != end; ++it) {
630 os << "\\begin{preview}\n"
632 << "\n\\end{preview}\n\n";
636 } // namespace graphics
641 string const unique_filename(string const bufferpath)
643 static int theCounter = 0;
644 string const filename = tostr(theCounter++) + "lyxpreview";
645 return support::AddName(bufferpath, filename);
649 Converter const * setConverter()
651 string const from = "lyxpreview";
653 Formats::FormatList::const_iterator it = formats.begin();
654 Formats::FormatList::const_iterator end = formats.end();
656 for (; it != end; ++it) {
657 string const to = it->name();
661 Converter const * ptr = converters.getConverter(from, to);
666 static bool first = true;
669 lyxerr << "PreviewLoader::startLoading()\n"
670 << "No converter from \"lyxpreview\" format has been "
679 void setAscentFractions(vector<double> & ascent_fractions,
680 string const & metrics_file)
682 // If all else fails, then the images will have equal ascents and
684 vector<double>::iterator it = ascent_fractions.begin();
685 vector<double>::iterator end = ascent_fractions.end();
688 ifstream in(metrics_file.c_str());
690 lyxerr[Debug::GRAPHICS]
691 << "setAscentFractions(" << metrics_file << ")\n"
692 << "Unable to open file!" << endl;
698 // Tightpage dimensions affect all subsequent dimensions
702 int snippet_counter = 0;
704 // Expecting lines of the form
705 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
706 // Preview: Snippet id ascent descent width
709 in >> preview >> type;
715 error = preview != "Preview:"
716 || (type != "Tightpage" && type != "Snippet");
720 if (type == "Tightpage") {
722 in >> dummy >> tp_descent >> dummy >> tp_ascent;
733 in >> snippet_id >> ascent >> descent >> dummy;
735 error = !in.good() || ++snippet_counter != snippet_id;
739 double const a = ascent + tp_ascent;
740 double const d = descent - tp_descent;
742 if (!support::float_equal(a + d, 0, 0.1))
751 lyxerr[Debug::GRAPHICS]
752 << "setAscentFractions(" << metrics_file << ")\n"
753 << "Error reading file!\n" << endl;