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;
57 using std::ostringstream;
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);
80 class FindFirst : public std::unary_function<StrPair, bool> {
82 FindFirst(string const & comp) : comp_(comp) {}
83 bool operator()(StrPair const & sp) const
85 return sp.first == comp_;
92 /// Store info on a currently executing, forked process.
95 InProgress() : pid(0) {}
97 InProgress(string const & filename_base,
98 PendingSnippets const & pending,
99 string const & to_format);
100 /// Remove any files left lying around and kill the forked process.
113 typedef map<pid_t, InProgress> InProgressProcesses;
115 typedef InProgressProcesses::value_type InProgressProcess;
123 struct PreviewLoader::Impl : public boost::signals::trackable {
125 Impl(PreviewLoader & p, Buffer const & b);
126 /// Stop any InProgress items still executing.
129 PreviewImage const * preview(string const & latex_snippet) const;
131 PreviewLoader::Status status(string const & latex_snippet) const;
133 void add(string const & latex_snippet);
135 void remove(string const & latex_snippet);
139 /// Emit this signal when an image is ready for display.
140 boost::signal1<void, PreviewImage const &> imageReady;
142 Buffer const & buffer() const { return buffer_; }
145 /// Called by the Forkedcall process that generated the bitmap files.
146 void finishedGenerating(pid_t, int);
148 void dumpPreamble(ostream &) const;
150 void dumpData(ostream &, BitmapFile const &) const;
152 /** cache_ allows easy retrieval of already-generated images
153 * using the LaTeX snippet as the identifier.
155 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
157 typedef map<string, PreviewImagePtr> Cache;
161 /** pending_ stores the LaTeX snippets in anticipation of them being
162 * sent to the converter.
164 PendingSnippets pending_;
166 /** in_progress_ stores all forked processes so that we can proceed
168 The map uses the conversion commands as its identifiers.
170 InProgressProcesses in_progress_;
173 PreviewLoader & parent_;
175 Buffer const & buffer_;
177 double font_scaling_factor_;
179 /// We don't own this
180 static Converter const * pconverter_;
184 Converter const * PreviewLoader::Impl::pconverter_;
187 // The public interface, defined in PreviewLoader.h
188 // ================================================
189 PreviewLoader::PreviewLoader(Buffer const & b)
190 : pimpl_(new Impl(*this, b))
194 PreviewLoader::~PreviewLoader()
198 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
200 return pimpl_->preview(latex_snippet);
204 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
206 return pimpl_->status(latex_snippet);
210 void PreviewLoader::add(string const & latex_snippet) const
212 pimpl_->add(latex_snippet);
216 void PreviewLoader::remove(string const & latex_snippet) const
218 pimpl_->remove(latex_snippet);
222 void PreviewLoader::startLoading() const
224 pimpl_->startLoading();
228 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
230 return pimpl_->imageReady.connect(slot);
234 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
236 pimpl_->imageReady(pimage);
240 Buffer const & PreviewLoader::buffer() const
242 return pimpl_->buffer();
245 } // namespace graphics
249 // The details of the Impl
250 // =======================
254 struct IncrementedFileName {
255 IncrementedFileName(string const & to_format,
256 string const & filename_base)
257 : to_format_(to_format), base_(filename_base), counter_(1)
260 StrPair const operator()(string const & snippet)
263 os << base_ << counter_++ << '.' << to_format_;
264 string const file = os.str();
266 return make_pair(snippet, file);
270 string const & to_format_;
271 string const & base_;
276 InProgress::InProgress(string const & filename_base,
277 PendingSnippets const & pending,
278 string const & to_format)
280 metrics_file(filename_base + ".metrics"),
281 snippets(pending.size())
283 PendingSnippets::const_iterator pit = pending.begin();
284 PendingSnippets::const_iterator pend = pending.end();
285 BitmapFile::iterator sit = snippets.begin();
287 std::transform(pit, pend, sit,
288 IncrementedFileName(to_format, filename_base));
292 void InProgress::stop() const
295 support::ForkedcallsController::get().kill(pid, 0);
297 if (!metrics_file.empty())
298 support::unlink(metrics_file);
300 BitmapFile::const_iterator vit = snippets.begin();
301 BitmapFile::const_iterator vend = snippets.end();
302 for (; vit != vend; ++vit) {
303 if (!vit->second.empty())
304 support::unlink(vit->second);
314 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
315 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
317 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
318 lyxrc.preview_scale_factor;
320 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
321 << font_scaling_factor_ << endl;
324 pconverter_ = setConverter();
328 PreviewLoader::Impl::~Impl()
330 InProgressProcesses::iterator ipit = in_progress_.begin();
331 InProgressProcesses::iterator ipend = in_progress_.end();
333 for (; ipit != ipend; ++ipit) {
340 PreviewLoader::Impl::preview(string const & latex_snippet) const
342 Cache::const_iterator it = cache_.find(latex_snippet);
343 return (it == cache_.end()) ? 0 : it->second.get();
349 class FindSnippet : public std::unary_function<InProgressProcess, bool> {
351 FindSnippet(string const & s) : snippet_(s) {}
352 bool operator()(InProgressProcess const & process) const
354 BitmapFile const & snippets = process.second.snippets;
355 BitmapFile::const_iterator beg = snippets.begin();
356 BitmapFile::const_iterator end = snippets.end();
357 return find_if(beg, end, FindFirst(snippet_)) != end;
361 string const snippet_;
366 PreviewLoader::Status
367 PreviewLoader::Impl::status(string const & latex_snippet) const
369 Cache::const_iterator cit = cache_.find(latex_snippet);
370 if (cit != cache_.end())
373 PendingSnippets::const_iterator pit = pending_.begin();
374 PendingSnippets::const_iterator pend = pending_.end();
376 pit = find(pit, pend, latex_snippet);
380 InProgressProcesses::const_iterator ipit = in_progress_.begin();
381 InProgressProcesses::const_iterator ipend = in_progress_.end();
383 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
391 void PreviewLoader::Impl::add(string const & latex_snippet)
393 if (!pconverter_ || status(latex_snippet) != NotFound)
396 string const snippet = support::trim(latex_snippet);
400 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
402 pending_.push_back(snippet);
408 struct EraseSnippet {
409 EraseSnippet(string const & s) : snippet_(s) {}
410 void operator()(InProgressProcess & process)
412 BitmapFile & snippets = process.second.snippets;
413 BitmapFile::iterator it = snippets.begin();
414 BitmapFile::iterator end = snippets.end();
416 it = find_if(it, end, FindFirst(snippet_));
418 snippets.erase(it, it+1);
422 string const & snippet_;
428 void PreviewLoader::Impl::remove(string const & latex_snippet)
430 Cache::iterator cit = cache_.find(latex_snippet);
431 if (cit != cache_.end())
434 PendingSnippets::iterator pit = pending_.begin();
435 PendingSnippets::iterator pend = pending_.end();
437 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
439 InProgressProcesses::iterator ipit = in_progress_.begin();
440 InProgressProcesses::iterator ipend = in_progress_.end();
442 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
444 while (ipit != ipend) {
445 InProgressProcesses::iterator curr = ipit++;
446 if (curr->second.snippets.empty())
447 in_progress_.erase(curr);
452 void PreviewLoader::Impl::startLoading()
454 if (pending_.empty() || !pconverter_)
457 // Only start the process off after the buffer is loaded from file.
458 if (!buffer_.fully_loaded())
461 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
463 // As used by the LaTeX file and by the resulting image files
464 string const directory = buffer_.temppath().empty() ?
465 buffer_.filePath() : buffer_.temppath();
467 string const filename_base(unique_filename(directory));
469 // Create an InProgress instance to place in the map of all
470 // such processes if it starts correctly.
471 InProgress inprogress(filename_base, pending_, pconverter_->to);
473 // clear pending_, so we're ready to start afresh.
476 // Output the LaTeX file.
477 string const latexfile = filename_base + ".tex";
479 ofstream of(latexfile.c_str());
480 of << "\\batchmode\n";
482 of << "\n\\begin{document}\n";
483 dumpData(of, inprogress.snippets);
484 of << "\n\\end{document}\n";
487 // The conversion command.
489 cs << pconverter_->command << ' ' << latexfile << ' '
490 << int(font_scaling_factor_) << ' ' << pconverter_->to;
492 string const command = "sh " + support::LibScriptSearch(cs.str());
494 // Initiate the conversion from LaTeX to bitmap images files.
495 support::Forkedcall::SignalTypePtr
496 convert_ptr(new support::Forkedcall::SignalType);
497 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
499 support::Forkedcall call;
500 int ret = call.startscript(command, convert_ptr);
503 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
504 << "Unable to start process \n"
509 // Store the generation process in a list of all such processes
510 inprogress.pid = call.pid();
511 inprogress.command = command;
512 in_progress_[inprogress.pid] = inprogress;
516 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
519 InProgressProcesses::iterator git = in_progress_.find(pid);
520 if (git == in_progress_.end()) {
521 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
522 "data for PID " << pid << endl;
526 string const command = git->second.command;
527 string const status = retval > 0 ? "failed" : "succeeded";
528 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
529 << retval << "): processing " << status
530 << " for " << command << endl;
534 // Read the metrics file, if it exists
535 vector<double> ascent_fractions(git->second.snippets.size());
536 setAscentFractions(ascent_fractions, git->second.metrics_file);
538 // Add these newly generated bitmap files to the cache and
539 // start loading them into LyX.
540 BitmapFile::const_iterator it = git->second.snippets.begin();
541 BitmapFile::const_iterator end = git->second.snippets.end();
543 std::list<PreviewImagePtr> newimages;
545 int metrics_counter = 0;
546 for (; it != end; ++it, ++metrics_counter) {
547 string const & snip = it->first;
548 string const & file = it->second;
549 double af = ascent_fractions[metrics_counter];
551 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
554 newimages.push_back(ptr);
557 // Remove the item from the list of still-executing processes.
558 in_progress_.erase(git);
560 // Tell the outside world
561 std::list<PreviewImagePtr>::const_reverse_iterator
562 nit = newimages.rbegin();
563 std::list<PreviewImagePtr>::const_reverse_iterator
564 nend = newimages.rend();
565 for (; nit != nend; ++nit) {
566 imageReady(*nit->get());
571 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
573 // Why on earth is Buffer::makeLaTeXFile a non-const method?
574 Buffer & tmp = const_cast<Buffer &>(buffer_);
575 // Dump the preamble only.
576 OutputParams runparams;
577 runparams.flavor = OutputParams::LATEX;
578 runparams.nice = true;
579 runparams.moving_arg = true;
580 runparams.free_spacing = true;
581 tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
583 // FIXME! This is a HACK! The proper fix is to control the 'true'
584 // passed to WriteStream below:
585 // int InsetFormula::latex(Buffer const &, ostream & os,
586 // OutputParams const & runparams) const
588 // WriteStream wi(os, runparams.moving_arg, true);
593 << "\\def\\lyxlock{}\n"
596 // Loop over the insets in the buffer and dump all the math-macros.
597 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
598 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
600 for (; it != end; ++it)
601 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
602 it->latex(buffer_, os, runparams);
604 // All equation lables appear as "(#)" + preview.sty's rendering of
606 if (lyxrc.preview_hashed_labels)
607 os << "\\renewcommand{\\theequation}{\\#}\n";
609 // Use the preview style file to ensure that each snippet appears on a
612 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
615 // This piece of PostScript magic ensures that the foreground and
616 // background colors are the same as the LyX screen.
617 string fg = lyx_gui::hexname(LColor::preview);
618 if (fg.empty()) fg = "000000";
620 string bg = lyx_gui::hexname(LColor::background);
621 if (bg.empty()) bg = "ffffff";
623 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
624 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
625 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
626 << "clippath fill setrgbcolor}bind def end}}}\n";
630 void PreviewLoader::Impl::dumpData(ostream & os,
631 BitmapFile const & vec) const
636 BitmapFile::const_iterator it = vec.begin();
637 BitmapFile::const_iterator end = vec.end();
639 for (; it != end; ++it) {
640 os << "\\begin{preview}\n"
642 << "\n\\end{preview}\n\n";
646 } // namespace graphics
651 string const unique_filename(string const bufferpath)
653 static int theCounter = 0;
654 string const filename = tostr(theCounter++) + "lyxpreview";
655 return support::AddName(bufferpath, filename);
659 Converter const * setConverter()
661 string const from = "lyxpreview";
663 Formats::FormatList::const_iterator it = formats.begin();
664 Formats::FormatList::const_iterator end = formats.end();
666 for (; it != end; ++it) {
667 string const to = it->name();
671 Converter const * ptr = converters.getConverter(from, to);
676 static bool first = true;
679 lyxerr << "PreviewLoader::startLoading()\n"
680 << "No converter from \"lyxpreview\" format has been "
689 void setAscentFractions(vector<double> & ascent_fractions,
690 string const & metrics_file)
692 // If all else fails, then the images will have equal ascents and
694 vector<double>::iterator it = ascent_fractions.begin();
695 vector<double>::iterator end = ascent_fractions.end();
698 ifstream in(metrics_file.c_str());
700 lyxerr[Debug::GRAPHICS]
701 << "setAscentFractions(" << metrics_file << ")\n"
702 << "Unable to open file!" << endl;
708 // Tightpage dimensions affect all subsequent dimensions
712 int snippet_counter = 0;
714 // Expecting lines of the form
715 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
716 // Preview: Snippet id ascent descent width
719 in >> preview >> type;
725 error = preview != "Preview:"
726 || (type != "Tightpage" && type != "Snippet");
730 if (type == "Tightpage") {
732 in >> dummy >> tp_descent >> dummy >> tp_ascent;
743 in >> snippet_id >> ascent >> descent >> dummy;
745 error = !in.good() || ++snippet_counter != snippet_id;
749 double const a = ascent + tp_ascent;
750 double const d = descent - tp_descent;
752 if (!support::float_equal(a + d, 0, 0.1))
761 lyxerr[Debug::GRAPHICS]
762 << "setAscentFractions(" << metrics_file << ")\n"
763 << "Error reading file!\n" << endl;