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"
24 #include "frontends/lyx_gui.h" // hexname
26 #include "insets/inset.h"
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"
33 #include "support/tostr.h"
35 #include <boost/bind.hpp>
37 #include "support/std_sstream.h"
41 namespace support = lyx::support;
54 using std::ostringstream;
61 typedef pair<string, string> StrPair;
63 // A list of alll snippets to be converted to previews
64 typedef list<string> PendingSnippets;
66 // Each item in the vector is a pair<snippet, image file name>.
67 typedef vector<StrPair> BitmapFile;
69 string const unique_filename(string const bufferpath);
71 Converter const * setConverter();
73 void setAscentFractions(vector<double> & ascent_fractions,
74 string const & metrics_file);
77 FindFirst(string const & comp) : comp_(comp) {}
78 bool operator()(StrPair const & sp)
80 return sp.first == comp_;
87 /// Store info on a currently executing, forked process.
90 InProgress() : pid(0) {}
92 InProgress(string const & filename_base,
93 PendingSnippets const & pending,
94 string const & to_format);
95 /// Remove any files left lying around and kill the forked process.
108 typedef map<pid_t, InProgress> InProgressProcesses;
110 typedef InProgressProcesses::value_type InProgressProcess;
118 struct PreviewLoader::Impl : public boost::signals::trackable {
120 Impl(PreviewLoader & p, Buffer const & b);
121 /// Stop any InProgress items still executing.
124 PreviewImage const * preview(string const & latex_snippet) const;
126 PreviewLoader::Status status(string const & latex_snippet) const;
128 void add(string const & latex_snippet);
130 void remove(string const & latex_snippet);
134 /// Emit this signal when an image is ready for display.
135 boost::signal1<void, PreviewImage const &> imageReady;
137 Buffer const & buffer() const { return buffer_; }
140 /// Called by the Forkedcall process that generated the bitmap files.
141 void finishedGenerating(pid_t, int);
143 void dumpPreamble(ostream &) const;
145 void dumpData(ostream &, BitmapFile const &) const;
147 /** cache_ allows easy retrieval of already-generated images
148 * using the LaTeX snippet as the identifier.
150 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
152 typedef map<string, PreviewImagePtr> Cache;
156 /** pending_ stores the LaTeX snippets in anticipation of them being
157 * sent to the converter.
159 PendingSnippets pending_;
161 /** in_progress_ stores all forked processes so that we can proceed
163 The map uses the conversion commands as its identifiers.
165 InProgressProcesses in_progress_;
168 PreviewLoader & parent_;
170 Buffer const & buffer_;
172 double font_scaling_factor_;
174 /// We don't own this
175 static Converter const * pconverter_;
179 Converter const * PreviewLoader::Impl::pconverter_;
182 // The public interface, defined in PreviewLoader.h
183 // ================================================
184 PreviewLoader::PreviewLoader(Buffer const & b)
185 : pimpl_(new Impl(*this, b))
189 PreviewLoader::~PreviewLoader()
193 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
195 return pimpl_->preview(latex_snippet);
199 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
201 return pimpl_->status(latex_snippet);
205 void PreviewLoader::add(string const & latex_snippet) const
207 pimpl_->add(latex_snippet);
211 void PreviewLoader::remove(string const & latex_snippet) const
213 pimpl_->remove(latex_snippet);
217 void PreviewLoader::startLoading() const
219 pimpl_->startLoading();
223 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
225 return pimpl_->imageReady.connect(slot);
229 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
231 pimpl_->imageReady(pimage);
235 Buffer const & PreviewLoader::buffer() const
237 return pimpl_->buffer();
240 } // namespace graphics
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();
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 support::ForkedcallsController::get().kill(pid, 0);
292 if (!metrics_file.empty())
293 support::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 support::unlink(vit->second);
309 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
310 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
312 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
313 lyxrc.preview_scale_factor;
315 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
316 << font_scaling_factor_ << endl;
319 pconverter_ = setConverter();
323 PreviewLoader::Impl::~Impl()
325 InProgressProcesses::iterator ipit = in_progress_.begin();
326 InProgressProcesses::iterator ipend = in_progress_.end();
328 for (; ipit != ipend; ++ipit) {
335 PreviewLoader::Impl::preview(string const & latex_snippet) const
337 Cache::const_iterator it = cache_.find(latex_snippet);
338 return (it == cache_.end()) ? 0 : it->second.get();
345 FindSnippet(string const & s) : snippet_(s) {}
346 bool operator()(InProgressProcess const & process)
348 BitmapFile const & snippets = process.second.snippets;
349 BitmapFile::const_iterator it = snippets.begin();
350 BitmapFile::const_iterator end = snippets.end();
351 it = find_if(it, end, FindFirst(snippet_));
356 string const & snippet_;
361 PreviewLoader::Status
362 PreviewLoader::Impl::status(string const & latex_snippet) const
364 Cache::const_iterator cit = cache_.find(latex_snippet);
365 if (cit != cache_.end())
368 PendingSnippets::const_iterator pit = pending_.begin();
369 PendingSnippets::const_iterator pend = pending_.end();
371 pit = find(pit, pend, latex_snippet);
375 InProgressProcesses::const_iterator ipit = in_progress_.begin();
376 InProgressProcesses::const_iterator ipend = in_progress_.end();
378 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
386 void PreviewLoader::Impl::add(string const & latex_snippet)
388 if (!pconverter_ || status(latex_snippet) != NotFound)
391 string const snippet = support::trim(latex_snippet);
395 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
397 pending_.push_back(snippet);
403 struct EraseSnippet {
404 EraseSnippet(string const & s) : snippet_(s) {}
405 void operator()(InProgressProcess & process)
407 BitmapFile & snippets = process.second.snippets;
408 BitmapFile::iterator it = snippets.begin();
409 BitmapFile::iterator end = snippets.end();
411 it = find_if(it, end, FindFirst(snippet_));
413 snippets.erase(it, it+1);
417 string const & snippet_;
423 void PreviewLoader::Impl::remove(string const & latex_snippet)
425 Cache::iterator cit = cache_.find(latex_snippet);
426 if (cit != cache_.end())
429 PendingSnippets::iterator pit = pending_.begin();
430 PendingSnippets::iterator pend = pending_.end();
432 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
434 InProgressProcesses::iterator ipit = in_progress_.begin();
435 InProgressProcesses::iterator ipend = in_progress_.end();
437 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
439 while (ipit != ipend) {
440 InProgressProcesses::iterator curr = ipit++;
441 if (curr->second.snippets.empty())
442 in_progress_.erase(curr);
447 void PreviewLoader::Impl::startLoading()
449 if (pending_.empty() || !pconverter_)
452 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
454 // As used by the LaTeX file and by the resulting image files
455 string directory = buffer_.temppath();
456 if (directory.empty())
457 directory = buffer_.filePath();
459 string const filename_base(unique_filename(directory));
461 // Create an InProgress instance to place in the map of all
462 // such processes if it starts correctly.
463 InProgress inprogress(filename_base, pending_, pconverter_->to);
465 // clear pending_, so we're ready to start afresh.
468 // Output the LaTeX file.
469 string const latexfile = filename_base + ".tex";
471 ofstream of(latexfile.c_str());
472 of << "\\batchmode\n";
474 of << "\n\\begin{document}\n";
475 dumpData(of, inprogress.snippets);
476 of << "\n\\end{document}\n";
479 // The conversion command.
481 cs << pconverter_->command << ' ' << latexfile << ' '
482 << int(font_scaling_factor_) << ' ' << pconverter_->to;
484 string const command = "sh " + support::LibScriptSearch(cs.str());
486 // Initiate the conversion from LaTeX to bitmap images files.
487 support::Forkedcall::SignalTypePtr
488 convert_ptr(new support::Forkedcall::SignalType);
489 convert_ptr->connect(
490 boost::bind(&Impl::finishedGenerating, this, _1, _2));
492 support::Forkedcall call;
493 int ret = call.startscript(command, convert_ptr);
496 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
497 << "Unable to start process \n"
502 // Store the generation process in a list of all such processes
503 inprogress.pid = call.pid();
504 inprogress.command = command;
505 in_progress_[inprogress.pid] = inprogress;
509 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
512 InProgressProcesses::iterator git = in_progress_.find(pid);
513 if (git == in_progress_.end()) {
514 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
515 "data for PID " << pid << endl;
519 string const command = git->second.command;
520 string const status = retval > 0 ? "failed" : "succeeded";
521 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
522 << retval << "): processing " << status
523 << " for " << command << endl;
527 // Read the metrics file, if it exists
528 vector<double> ascent_fractions(git->second.snippets.size());
529 setAscentFractions(ascent_fractions, git->second.metrics_file);
531 // Add these newly generated bitmap files to the cache and
532 // start loading them into LyX.
533 BitmapFile::const_iterator it = git->second.snippets.begin();
534 BitmapFile::const_iterator end = git->second.snippets.end();
536 std::list<PreviewImagePtr> newimages;
538 int metrics_counter = 0;
539 for (; it != end; ++it, ++metrics_counter) {
540 string const & snip = it->first;
541 string const & file = it->second;
542 double af = ascent_fractions[metrics_counter];
544 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
547 newimages.push_back(ptr);
550 // Remove the item from the list of still-executing processes.
551 in_progress_.erase(git);
553 // Tell the outside world
554 std::list<PreviewImagePtr>::const_reverse_iterator
555 nit = newimages.rbegin();
556 std::list<PreviewImagePtr>::const_reverse_iterator
557 nend = newimages.rend();
558 for (; nit != nend; ++nit) {
559 imageReady(*nit->get());
564 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
566 // Why on earth is Buffer::makeLaTeXFile a non-const method?
567 Buffer & tmp = const_cast<Buffer &>(buffer_);
568 // Dump the preamble only.
569 LatexRunParams runparams;
570 runparams.flavor = LatexRunParams::LATEX;
571 runparams.nice = true;
572 runparams.moving_arg = true;
573 runparams.free_spacing = true;
574 tmp.makeLaTeXFile(os, buffer_.filePath(), runparams, true, false);
576 // FIXME! This is a HACK! The proper fix is to control the 'true'
577 // passed to WriteStream below:
578 // int InsetFormula::latex(Buffer const &, ostream & os,
579 // LatexRunParams const & runparams) const
581 // WriteStream wi(os, runparams.moving_arg, true);
586 << "\\def\\lyxlock{}\n"
589 // Loop over the insets in the buffer and dump all the math-macros.
590 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
591 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
593 for (; it != end; ++it)
594 if (it->lyxCode() == InsetOld::MATHMACRO_CODE)
595 it->latex(buffer_, os, runparams);
597 // All equation lables appear as "(#)" + preview.sty's rendering of
599 if (lyxrc.preview_hashed_labels)
600 os << "\\renewcommand{\\theequation}{\\#}\n";
602 // Use the preview style file to ensure that each snippet appears on a
605 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
608 // This piece of PostScript magic ensures that the foreground and
609 // background colors are the same as the LyX screen.
610 string fg = lyx_gui::hexname(LColor::preview);
611 if (fg.empty()) fg = "000000";
613 string bg = lyx_gui::hexname(LColor::background);
614 if (bg.empty()) bg = "ffffff";
616 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
617 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
618 << '<' << fg << bg << ">{255 div}forall setrgbcolor\n"
619 << "clippath fill setrgbcolor}bind def end}}}\n";
623 void PreviewLoader::Impl::dumpData(ostream & os,
624 BitmapFile const & vec) const
629 BitmapFile::const_iterator it = vec.begin();
630 BitmapFile::const_iterator end = vec.end();
632 for (; it != end; ++it) {
633 os << "\\begin{preview}\n"
635 << "\n\\end{preview}\n\n";
639 } // namespace graphics
644 string const unique_filename(string const bufferpath)
646 static int theCounter = 0;
647 string const filename = tostr(theCounter++) + "lyxpreview";
648 return support::AddName(bufferpath, filename);
652 Converter const * setConverter()
654 string const from = "lyxpreview";
656 Formats::FormatList::const_iterator it = formats.begin();
657 Formats::FormatList::const_iterator end = formats.end();
659 for (; it != end; ++it) {
660 string const to = it->name();
664 Converter const * ptr = converters.getConverter(from, to);
669 static bool first = true;
672 lyxerr << "PreviewLoader::startLoading()\n"
673 << "No converter from \"lyxpreview\" format has been "
682 void setAscentFractions(vector<double> & ascent_fractions,
683 string const & metrics_file)
685 // If all else fails, then the images will have equal ascents and
687 vector<double>::iterator it = ascent_fractions.begin();
688 vector<double>::iterator end = ascent_fractions.end();
691 ifstream in(metrics_file.c_str());
693 lyxerr[Debug::GRAPHICS]
694 << "setAscentFractions(" << metrics_file << ")\n"
695 << "Unable to open file!" << endl;
701 // Tightpage dimensions affect all subsequent dimensions
705 int snippet_counter = 0;
707 // Expecting lines of the form
708 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
709 // Preview: Snippet id ascent descent width
712 in >> preview >> type;
718 error = preview != "Preview:"
719 || (type != "Tightpage" && type != "Snippet");
723 if (type == "Tightpage") {
725 in >> dummy >> tp_descent >> dummy >> tp_ascent;
736 in >> snippet_id >> ascent >> descent >> dummy;
738 error = !in.good() || ++snippet_counter != snippet_id;
742 double const a = ascent + tp_ascent;
743 double const d = descent - tp_descent;
745 if (!support::float_equal(a + d, 0, 0.1))
754 lyxerr[Debug::GRAPHICS]
755 << "setAscentFractions(" << metrics_file << ")\n"
756 << "Error reading file!\n" << endl;