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 "bufferparams.h"
20 #include "converter.h"
25 #include "insets/inset.h"
27 #include "frontends/lyx_gui.h" // hexname
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"
35 #include <boost/bind.hpp>
36 #include <boost/signals/trackable.hpp>
64 typedef pair<string, string> StrPair;
66 // A list of alll snippets to be converted to previews
67 typedef list<string> PendingSnippets;
69 // Each item in the vector is a pair<snippet, image file name>.
70 typedef vector<StrPair> BitmapFile;
73 double setFontScalingFactor(Buffer &);
75 string const unique_filename(string const bufferpath);
77 Converter const * setConverter();
79 void setAscentFractions(vector<double> & ascent_fractions,
80 string const & metrics_file);
83 FindFirst(string const & comp) : comp_(comp) {}
84 bool operator()(StrPair const & sp)
86 return sp.first < comp_;
93 /// Store info on a currently executing, forked process.
96 InProgress() : pid(0) {}
98 InProgress(string const & filename_base,
99 PendingSnippets const & pending,
100 string const & to_format);
101 /// Remove any files left lying around and kill the forked process.
112 typedef map<string, InProgress> InProgressProcesses;
114 typedef InProgressProcesses::value_type InProgressProcess;
121 struct PreviewLoader::Impl : public boost::signals::trackable {
123 Impl(PreviewLoader & p, Buffer const & b);
124 /// Stop any InProgress items still executing.
127 PreviewImage const * preview(string const & latex_snippet) const;
129 PreviewLoader::Status status(string const & latex_snippet) const;
131 void add(string const & latex_snippet);
133 void remove(string const & latex_snippet);
137 /// Emit this signal when an image is ready for display.
138 boost::signal1<void, PreviewImage const &> imageReady;
140 Buffer const & buffer() const { return buffer_; }
143 /// Called by the Forkedcall process that generated the bitmap files.
144 void finishedGenerating(string const &, pid_t, int);
146 void dumpPreamble(ostream &) const;
148 void dumpData(ostream &, BitmapFile const &) const;
150 /** cache_ allows easy retrieval of already-generated images
151 * using the LaTeX snippet as the identifier.
153 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
155 typedef map<string, PreviewImagePtr> Cache;
159 /** pending_ stores the LaTeX snippets in anticipation of them being
160 * sent to the converter.
162 PendingSnippets pending_;
164 /** in_progress_ stores all forked processes so that we can proceed
166 The map uses the conversion commands as its identifiers.
168 InProgressProcesses in_progress_;
171 PreviewLoader & parent_;
173 Buffer const & buffer_;
175 double font_scaling_factor_;
177 /// We don't own this
178 static Converter const * pconverter_;
182 Converter const * PreviewLoader::Impl::pconverter_;
185 // The public interface, defined in PreviewLoader.h
186 // ================================================
187 PreviewLoader::PreviewLoader(Buffer const & b)
188 : pimpl_(new Impl(*this, b))
192 PreviewLoader::~PreviewLoader()
196 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
198 return pimpl_->preview(latex_snippet);
202 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
204 return pimpl_->status(latex_snippet);
208 void PreviewLoader::add(string const & latex_snippet) const
210 pimpl_->add(latex_snippet);
214 void PreviewLoader::remove(string const & latex_snippet) const
216 pimpl_->remove(latex_snippet);
220 void PreviewLoader::startLoading() const
222 pimpl_->startLoading();
226 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
228 return pimpl_->imageReady.connect(slot);
232 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
234 pimpl_->imageReady(pimage);
238 Buffer const & PreviewLoader::buffer() const
240 return pimpl_->buffer();
246 // The details of the Impl
247 // =======================
251 struct IncrementedFileName {
252 IncrementedFileName(string const & to_format,
253 string const & filename_base)
254 : to_format_(to_format), base_(filename_base), counter_(1)
257 StrPair const operator()(string const & snippet)
261 << setfill('0') << setw(3) << counter_++
262 << "." << to_format_;
264 string const file = os.str().c_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 ForkedcallsController::get().kill(pid, 0);
297 if (!metrics_file.empty())
298 lyx::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 lyx::unlink(vit->second);
313 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
314 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
316 font_scaling_factor_ = setFontScalingFactor(const_cast<Buffer &>(b));
318 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
319 << font_scaling_factor_ << endl;
322 pconverter_ = setConverter();
326 PreviewLoader::Impl::~Impl()
328 InProgressProcesses::iterator ipit = in_progress_.begin();
329 InProgressProcesses::iterator ipend = in_progress_.end();
331 for (; ipit != ipend; ++ipit) {
338 PreviewLoader::Impl::preview(string const & latex_snippet) const
340 Cache::const_iterator it = cache_.find(latex_snippet);
341 return (it == cache_.end()) ? 0 : it->second.get();
348 FindSnippet(string const & s) : snippet_(s) {}
349 bool operator()(InProgressProcess const & process)
351 BitmapFile const & snippets = process.second.snippets;
352 BitmapFile::const_iterator it = snippets.begin();
353 BitmapFile::const_iterator end = snippets.end();
354 it = find_if(it, end, FindFirst(snippet_));
359 string const & snippet_;
364 PreviewLoader::Status
365 PreviewLoader::Impl::status(string const & latex_snippet) const
367 Cache::const_iterator cit = cache_.find(latex_snippet);
368 if (cit != cache_.end())
371 PendingSnippets::const_iterator pit = pending_.begin();
372 PendingSnippets::const_iterator pend = pending_.end();
374 pit = find(pit, pend, latex_snippet);
378 InProgressProcesses::const_iterator ipit = in_progress_.begin();
379 InProgressProcesses::const_iterator ipend = in_progress_.end();
381 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
389 void PreviewLoader::Impl::add(string const & latex_snippet)
391 if (!pconverter_ || status(latex_snippet) != NotFound)
394 string const snippet = trim(latex_snippet);
398 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
400 pending_.push_back(snippet);
406 struct EraseSnippet {
407 EraseSnippet(string const & s) : snippet_(s) {}
408 void operator()(InProgressProcess & process)
410 BitmapFile & snippets = process.second.snippets;
411 BitmapFile::iterator it = snippets.begin();
412 BitmapFile::iterator end = snippets.end();
414 it = find_if(it, end, FindFirst(snippet_));
416 snippets.erase(it, it+1);
420 string const & snippet_;
426 void PreviewLoader::Impl::remove(string const & latex_snippet)
428 Cache::iterator cit = cache_.find(latex_snippet);
429 if (cit != cache_.end())
432 PendingSnippets::iterator pit = pending_.begin();
433 PendingSnippets::iterator pend = pending_.end();
435 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
437 InProgressProcesses::iterator ipit = in_progress_.begin();
438 InProgressProcesses::iterator ipend = in_progress_.end();
440 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
442 for (; ipit != ipend; ++ipit) {
443 InProgressProcesses::iterator curr = ipit++;
444 if (curr->second.snippets.empty())
445 in_progress_.erase(curr);
450 void PreviewLoader::Impl::startLoading()
452 if (pending_.empty() || !pconverter_)
455 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
457 // As used by the LaTeX file and by the resulting image files
458 string const filename_base(unique_filename(buffer_.tmppath));
460 // Create an InProgress instance to place in the map of all
461 // such processes if it starts correctly.
462 InProgress inprogress(filename_base, pending_, pconverter_->to);
464 // clear pending_, so we're ready to start afresh.
467 // Output the LaTeX file.
468 string const latexfile = filename_base + ".tex";
470 ofstream of(latexfile.c_str());
471 of << "\\batchmode\n";
473 of << "\n\\begin{document}\n";
474 dumpData(of, inprogress.snippets);
475 of << "\n\\end{document}\n";
478 // The conversion command.
480 cs << pconverter_->command << " " << latexfile << " "
481 << int(font_scaling_factor_);
483 string const command = LibScriptSearch(cs.str().c_str());
485 // Initiate the conversion from LaTeX to bitmap images files.
486 Forkedcall::SignalTypePtr convert_ptr;
487 convert_ptr.reset(new Forkedcall::SignalType);
489 convert_ptr->connect(
490 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
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 in_progress_[command] = inprogress;
508 void PreviewLoader::Impl::finishedGenerating(string const & command,
509 pid_t /* pid */, int retval)
511 string const status = retval > 0 ? "failed" : "succeeded";
512 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
513 << retval << "): processing " << status
514 << " for " << command << endl;
519 InProgressProcesses::iterator git = in_progress_.find(command);
520 if (git == in_progress_.end()) {
521 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
523 << 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_iterator nit = newimages.begin();
555 std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
556 for (; nit != nend; ++nit) {
557 imageReady(*nit->get());
562 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
564 // Why on earth is Buffer::makeLaTeXFile a non-const method?
565 Buffer & tmp = const_cast<Buffer &>(buffer_);
566 // Dump the preamble only.
567 tmp.makeLaTeXFile(os, string(), true, false, true);
569 // Loop over the insets in the buffer and dump all the math-macros.
570 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
571 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
573 for (; it != end; ++it) {
574 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
575 (*it)->latex(&buffer_, os, true, true);
579 // All equation lables appear as "(#)" + preview.sty's rendering of
581 if (lyxrc.preview_hashed_labels)
582 os << "\\renewcommand{\\theequation}{\\#}\n";
584 // Use the preview style file to ensure that each snippet appears on a
587 << "\\usepackage[active,delayed,dvips,tightpage,showlabels]{preview}\n"
590 // This piece of PostScript magic ensures that the foreground and
591 // background colors are the same as the LyX screen.
592 string fg = lyx_gui::hexname(LColor::preview);
593 if (fg.empty()) fg = "000000";
595 string bg = lyx_gui::hexname(LColor::background);
596 if (bg.empty()) bg = "ffffff";
598 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
599 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
600 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
601 << "clippath fill setrgbcolor}bind def end}}}\n";
605 void PreviewLoader::Impl::dumpData(ostream & os,
606 BitmapFile const & vec) const
611 BitmapFile::const_iterator it = vec.begin();
612 BitmapFile::const_iterator end = vec.end();
614 for (; it != end; ++it) {
615 os << "\\begin{preview}\n"
617 << "\n\\end{preview}\n\n";
626 string const unique_filename(string const bufferpath)
628 static int theCounter = 0;
629 string const filename = tostr(theCounter++) + "lyxpreview";
630 return AddName(bufferpath, filename);
634 Converter const * setConverter()
636 string const from = "lyxpreview";
638 Formats::FormatList::const_iterator it = formats.begin();
639 Formats::FormatList::const_iterator end = formats.end();
641 for (; it != end; ++it) {
642 string const to = it->name();
646 Converter const * ptr = converters.getConverter(from, to);
651 static bool first = true;
654 lyxerr << "PreviewLoader::startLoading()\n"
655 << "No converter from \"lyxpreview\" format has been "
664 double setFontScalingFactor(Buffer & buffer)
666 double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
667 lyxrc.preview_scale_factor;
669 // Has the font size been set explicitly?
670 string const & fontsize = buffer.params.fontsize;
671 lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
672 << "font size is " << fontsize << endl;
674 if (isStrUnsignedInt(fontsize))
675 return 10.0 * scale_factor / strToDbl(fontsize);
677 // No. We must extract it from the LaTeX class file.
678 LyXTextClass const & tclass = buffer.params.getLyXTextClass();
679 string const textclass(tclass.latexname() + ".cls");
680 string const classfile(findtexfile(textclass, "cls"));
682 lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
683 << "class file is " << classfile << endl;
685 ifstream ifs(classfile.c_str());
687 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
692 double scaling = scale_factor;
696 // To get the default font size, look for a line like
697 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
698 if (!prefixIs(ltrim(str), "\\ExecuteOptions"))
701 // str contains just the options of \ExecuteOptions
702 string const tmp = split(str, '{');
703 split(tmp, str, '}');
706 string tok = token(str, ',', count++);
707 while (!isValidLength(tok) && !tok.empty())
708 tok = token(str, ',', count++);
711 lyxerr[Debug::GRAPHICS]
712 << "Extracted default font size from "
713 "LaTeX class file successfully!" << endl;
714 LyXLength fsize(tok);
715 scaling *= 10.0 / fsize.value();
724 void setAscentFractions(vector<double> & ascent_fractions,
725 string const & metrics_file)
727 // If all else fails, then the images will have equal ascents and
729 vector<double>::iterator it = ascent_fractions.begin();
730 vector<double>::iterator end = ascent_fractions.end();
733 ifstream ifs(metrics_file.c_str());
735 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
736 << metrics_file << ")\n"
737 << "Unable to open file!"
742 for (; it != end; ++it) {
749 ifs >> page >> page_id >> dummy >> dummy >> dummy >> dummy
750 >> ascent >> descent >> dummy;
754 !isStrUnsignedInt(rtrim(page_id, ":"))) {
755 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
756 << metrics_file << ")\n"
757 << "Error reading file!"
762 if (ascent + descent != 0)
763 *it = ascent / (ascent + descent);