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"
23 #include "lyxtextclasslist.h"
26 #include "insets/inset.h"
28 #include "frontends/lyx_gui.h" // hexname
30 #include "support/filetools.h"
31 #include "support/forkedcall.h"
32 #include "support/forkedcontr.h"
33 #include "support/lstrings.h"
34 #include "support/lyxlib.h"
36 #include <boost/bind.hpp>
37 #include <boost/signals/trackable.hpp>
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;
74 double setFontScalingFactor(Buffer &);
76 string const unique_filename(string const bufferpath);
78 Converter const * setConverter();
80 void setAscentFractions(vector<double> & ascent_fractions,
81 string const & metrics_file);
84 FindFirst(string const & comp) : comp_(comp) {}
85 bool operator()(StrPair const & sp)
87 return sp.first < comp_;
94 /// Store info on a currently executing, forked process.
97 InProgress() : pid(0) {}
99 InProgress(string const & filename_base,
100 PendingSnippets const & pending,
101 string const & to_format);
102 /// Remove any files left lying around and kill the forked process.
113 typedef map<string, InProgress> InProgressProcesses;
115 typedef InProgressProcesses::value_type InProgressProcess;
122 struct PreviewLoader::Impl : public boost::signals::trackable {
124 Impl(PreviewLoader & p, Buffer const & b);
125 /// Stop any InProgress items still executing.
128 PreviewImage const * preview(string const & latex_snippet) const;
130 PreviewLoader::Status status(string const & latex_snippet) const;
132 void add(string const & latex_snippet);
134 void remove(string const & latex_snippet);
139 /// Called by the Forkedcall process that generated the bitmap files.
140 void finishedGenerating(string const &, pid_t, int);
142 void dumpPreamble(ostream &) const;
144 void dumpData(ostream &, BitmapFile const &) const;
146 /** cache_ allows easy retrieval of already-generated images
147 * using the LaTeX snippet as the identifier.
149 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
151 typedef map<string, PreviewImagePtr> Cache;
155 /** pending_ stores the LaTeX snippets in anticipation of them being
156 * sent to the converter.
158 PendingSnippets pending_;
160 /** in_progress_ stores all forked processes so that we can proceed
162 The map uses the conversion commands as its identifiers.
164 InProgressProcesses in_progress_;
167 PreviewLoader & parent_;
169 Buffer const & buffer_;
171 double font_scaling_factor_;
173 /// We don't own this
174 static Converter const * pconverter_;
178 Converter const * PreviewLoader::Impl::pconverter_;
181 // The public interface, defined in PreviewLoader.h
182 // ================================================
183 PreviewLoader::PreviewLoader(Buffer const & b)
184 : pimpl_(new Impl(*this, b))
188 PreviewLoader::~PreviewLoader()
192 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
194 return pimpl_->preview(latex_snippet);
198 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
200 return pimpl_->status(latex_snippet);
204 void PreviewLoader::add(string const & latex_snippet)
206 pimpl_->add(latex_snippet);
210 void PreviewLoader::remove(string const & latex_snippet)
212 pimpl_->remove(latex_snippet);
216 void PreviewLoader::startLoading()
218 pimpl_->startLoading();
224 // The details of the Impl
225 // =======================
229 struct IncrementedFileName {
230 IncrementedFileName(string const & to_format,
231 string const & filename_base)
232 : to_format_(to_format), base_(filename_base), counter_(1)
235 StrPair const operator()(string const & snippet)
239 << setfill('0') << setw(3) << counter_++
240 << "." << to_format_;
242 string const file = os.str().c_str();
244 return make_pair(snippet, file);
248 string const & to_format_;
249 string const & base_;
254 InProgress::InProgress(string const & filename_base,
255 PendingSnippets const & pending,
256 string const & to_format)
258 metrics_file(filename_base + ".metrics"),
259 snippets(pending.size())
261 PendingSnippets::const_iterator pit = pending.begin();
262 PendingSnippets::const_iterator pend = pending.end();
263 BitmapFile::iterator sit = snippets.begin();
265 std::transform(pit, pend, sit,
266 IncrementedFileName(to_format, filename_base));
270 void InProgress::stop() const
273 ForkedcallsController::get().kill(pid, 0);
275 if (!metrics_file.empty())
276 lyx::unlink(metrics_file);
278 BitmapFile::const_iterator vit = snippets.begin();
279 BitmapFile::const_iterator vend = snippets.end();
280 for (; vit != vend; ++vit) {
281 if (!vit->second.empty())
282 lyx::unlink(vit->second);
291 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
292 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
294 font_scaling_factor_ = setFontScalingFactor(const_cast<Buffer &>(b));
296 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
297 << font_scaling_factor_ << endl;
300 pconverter_ = setConverter();
304 PreviewLoader::Impl::~Impl()
306 InProgressProcesses::iterator ipit = in_progress_.begin();
307 InProgressProcesses::iterator ipend = in_progress_.end();
309 for (; ipit != ipend; ++ipit) {
316 PreviewLoader::Impl::preview(string const & latex_snippet) const
318 Cache::const_iterator it = cache_.find(latex_snippet);
319 return (it == cache_.end()) ? 0 : it->second.get();
326 FindSnippet(string const & s) : snippet_(s) {}
327 bool operator()(InProgressProcess const & process)
329 BitmapFile const & snippets = process.second.snippets;
330 BitmapFile::const_iterator it = snippets.begin();
331 BitmapFile::const_iterator end = snippets.end();
332 it = find_if(it, end, FindFirst(snippet_));
337 string const & snippet_;
342 PreviewLoader::Status
343 PreviewLoader::Impl::status(string const & latex_snippet) const
345 Cache::const_iterator cit = cache_.find(latex_snippet);
346 if (cit != cache_.end())
349 PendingSnippets::const_iterator pit = pending_.begin();
350 PendingSnippets::const_iterator pend = pending_.end();
352 pit = find(pit, pend, latex_snippet);
356 InProgressProcesses::const_iterator ipit = in_progress_.begin();
357 InProgressProcesses::const_iterator ipend = in_progress_.end();
359 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
367 void PreviewLoader::Impl::add(string const & latex_snippet)
369 if (!pconverter_ || status(latex_snippet) != NotFound)
372 pending_.push_back(latex_snippet);
378 struct EraseSnippet {
379 EraseSnippet(string const & s) : snippet_(s) {}
380 void operator()(InProgressProcess & process)
382 BitmapFile & snippets = process.second.snippets;
383 BitmapFile::iterator it = snippets.begin();
384 BitmapFile::iterator end = snippets.end();
386 it = find_if(it, end, FindFirst(snippet_));
388 snippets.erase(it, it+1);
392 string const & snippet_;
398 void PreviewLoader::Impl::remove(string const & latex_snippet)
400 Cache::iterator cit = cache_.find(latex_snippet);
401 if (cit != cache_.end())
404 PendingSnippets::iterator pit = pending_.begin();
405 PendingSnippets::iterator pend = pending_.end();
407 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
409 InProgressProcesses::iterator ipit = in_progress_.begin();
410 InProgressProcesses::iterator ipend = in_progress_.end();
412 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
414 for (; ipit != ipend; ++ipit) {
415 InProgressProcesses::iterator curr = ipit++;
416 if (curr->second.snippets.empty())
417 in_progress_.erase(curr);
422 void PreviewLoader::Impl::startLoading()
424 if (pending_.empty() || !pconverter_)
427 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
429 // As used by the LaTeX file and by the resulting image files
430 string const filename_base(unique_filename(buffer_.tmppath));
432 // Create an InProgress instance to place in the map of all
433 // such processes if it starts correctly.
434 InProgress inprogress(filename_base, pending_, pconverter_->to);
436 // clear pending_, so we're ready to start afresh.
439 // Output the LaTeX file.
440 string const latexfile = filename_base + ".tex";
442 ofstream of(latexfile.c_str());
443 of << "\\batchmode\n";
445 of << "\n\\begin{document}\n";
446 dumpData(of, inprogress.snippets);
447 of << "\n\\end{document}\n";
450 // The conversion command.
452 cs << pconverter_->command << " " << latexfile << " "
453 << font_scaling_factor_;
455 string const command = cs.str().c_str();
457 // Initiate the conversion from LaTeX to bitmap images files.
458 Forkedcall::SignalTypePtr convert_ptr;
459 convert_ptr.reset(new Forkedcall::SignalType);
461 convert_ptr->connect(
462 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
465 int ret = call.startscript(command, convert_ptr);
468 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
469 << "Unable to start process \n"
474 // Store the generation process in a list of all such processes
475 inprogress.pid = call.pid();
476 in_progress_[command] = inprogress;
480 void PreviewLoader::Impl::finishedGenerating(string const & command,
481 pid_t /* pid */, int retval)
483 string const status = retval > 0 ? "failed" : "succeeded";
484 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
485 << retval << "): processing " << status
486 << " for " << command << endl;
491 InProgressProcesses::iterator git = in_progress_.find(command);
492 if (git == in_progress_.end()) {
493 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
495 << command << "!" << endl;
499 // Read the metrics file, if it exists
500 vector<double> ascent_fractions(git->second.snippets.size());
501 setAscentFractions(ascent_fractions, git->second.metrics_file);
503 // Add these newly generated bitmap files to the cache and
504 // start loading them into LyX.
505 BitmapFile::const_iterator it = git->second.snippets.begin();
506 BitmapFile::const_iterator end = git->second.snippets.end();
508 std::list<PreviewImagePtr> newimages;
510 int metrics_counter = 0;
511 for (; it != end; ++it, ++metrics_counter) {
512 string const & snip = it->first;
513 string const & file = it->second;
514 double af = ascent_fractions[metrics_counter];
516 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
519 newimages.push_back(ptr);
522 // Remove the item from the list of still-executing processes.
523 in_progress_.erase(git);
525 // Tell the outside world
526 std::list<PreviewImagePtr>::const_iterator nit = newimages.begin();
527 std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
528 for (; nit != nend; ++nit) {
529 parent_.imageReady(*nit->get());
534 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
536 // Why on earth is Buffer::makeLaTeXFile a non-const method?
537 Buffer & tmp = const_cast<Buffer &>(buffer_);
538 // Dump the preamble only.
539 tmp.makeLaTeXFile(os, string(), true, false, true);
541 // Loop over the insets in the buffer and dump all the math-macros.
542 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
543 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
545 for (; it != end; ++it) {
546 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
547 (*it)->latex(&buffer_, os, true, true);
551 // All equation lables appear as "(#)" + preview.sty's rendering of
553 if (lyxrc.preview_hashed_labels)
554 os << "\\renewcommand{\\theequation}{\\#}\n";
556 // Use the preview style file to ensure that each snippet appears on a
559 << "\\usepackage[active,delayed,dvips,tightpage,showlabels]{preview}\n"
562 // This piece of PostScript magic ensures that the foreground and
563 // background colors are the same as the LyX screen.
564 string fg = lyx_gui::hexname(LColor::preview);
565 if (fg.empty()) fg = "000000";
567 string bg = lyx_gui::hexname(LColor::background);
568 if (bg.empty()) bg = "ffffff";
570 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
571 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
572 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
573 << "clippath fill setrgbcolor}bind def end}}}\n";
577 void PreviewLoader::Impl::dumpData(ostream & os,
578 BitmapFile const & vec) const
583 BitmapFile::const_iterator it = vec.begin();
584 BitmapFile::const_iterator end = vec.end();
586 for (; it != end; ++it) {
587 os << "\\begin{preview}\n"
589 << "\n\\end{preview}\n\n";
598 string const unique_filename(string const bufferpath)
600 static int theCounter = 0;
601 string const filename = tostr(theCounter++) + "lyxpreview";
602 return AddName(bufferpath, filename);
606 Converter const * setConverter()
608 string const from = "lyxpreview";
610 Formats::FormatList::const_iterator it = formats.begin();
611 Formats::FormatList::const_iterator end = formats.end();
613 for (; it != end; ++it) {
614 string const to = it->name();
618 Converter const * ptr = converters.getConverter(from, to);
623 static bool first = true;
626 lyxerr << "PreviewLoader::startLoading()\n"
627 << "No converter from \"lyxpreview\" format has been "
636 double setFontScalingFactor(Buffer & buffer)
638 double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
639 lyxrc.preview_scale_factor;
641 // Has the font size been set explicitly?
642 string const & fontsize = buffer.params.fontsize;
643 lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
644 << "font size is " << fontsize << endl;
646 if (isStrUnsignedInt(fontsize))
647 return 10.0 * scale_factor / strToDbl(fontsize);
649 // No. We must extract it from the LaTeX class file.
650 LyXTextClass const & tclass = textclasslist[buffer.params.textclass];
651 string const textclass(tclass.latexname() + ".cls");
652 string const classfile(findtexfile(textclass, "cls"));
654 lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
655 << "class file is " << classfile << endl;
657 ifstream ifs(classfile.c_str());
659 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
664 double scaling = scale_factor;
668 // To get the default font size, look for a line like
669 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
670 if (!prefixIs(frontStrip(str), "\\ExecuteOptions"))
673 // str contains just the options of \ExecuteOptions
674 string const tmp = split(str, '{');
675 split(tmp, str, '}');
678 string tok = token(str, ',', count++);
679 while (!isValidLength(tok) && !tok.empty())
680 tok = token(str, ',', count++);
683 lyxerr[Debug::GRAPHICS]
684 << "Extracted default font size from "
685 "LaTeX class file successfully!" << endl;
686 LyXLength fsize(tok);
687 scaling *= 10.0 / fsize.value();
696 void setAscentFractions(vector<double> & ascent_fractions,
697 string const & metrics_file)
699 // If all else fails, then the images will have equal ascents and
701 vector<double>::iterator it = ascent_fractions.begin();
702 vector<double>::iterator end = ascent_fractions.end();
705 ifstream ifs(metrics_file.c_str());
707 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
708 << metrics_file << ")\n"
709 << "Unable to open file!"
714 for (; it != end; ++it) {
721 ifs >> page >> page_id >> dummy >> dummy >> dummy >> dummy
722 >> ascent >> descent >> dummy;
726 !isStrUnsignedInt(strip(page_id, ':'))) {
727 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
728 << metrics_file << ")\n"
729 << "Error reading file!"
734 if (ascent + descent != 0)
735 *it = ascent / (ascent + descent);