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;
141 /// Called by the Forkedcall process that generated the bitmap files.
142 void finishedGenerating(string const &, pid_t, int);
144 void dumpPreamble(ostream &) const;
146 void dumpData(ostream &, BitmapFile const &) const;
148 /** cache_ allows easy retrieval of already-generated images
149 * using the LaTeX snippet as the identifier.
151 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
153 typedef map<string, PreviewImagePtr> Cache;
157 /** pending_ stores the LaTeX snippets in anticipation of them being
158 * sent to the converter.
160 PendingSnippets pending_;
162 /** in_progress_ stores all forked processes so that we can proceed
164 The map uses the conversion commands as its identifiers.
166 InProgressProcesses in_progress_;
169 PreviewLoader & parent_;
171 Buffer const & buffer_;
173 double font_scaling_factor_;
175 /// We don't own this
176 static Converter const * pconverter_;
180 Converter const * PreviewLoader::Impl::pconverter_;
183 // The public interface, defined in PreviewLoader.h
184 // ================================================
185 PreviewLoader::PreviewLoader(Buffer const & b)
186 : pimpl_(new Impl(*this, b))
190 PreviewLoader::~PreviewLoader()
194 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
196 return pimpl_->preview(latex_snippet);
200 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
202 return pimpl_->status(latex_snippet);
206 void PreviewLoader::add(string const & latex_snippet) const
208 pimpl_->add(latex_snippet);
212 void PreviewLoader::remove(string const & latex_snippet) const
214 pimpl_->remove(latex_snippet);
218 void PreviewLoader::startLoading() const
220 pimpl_->startLoading();
224 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
226 return pimpl_->imageReady.connect(slot);
230 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
232 pimpl_->imageReady(pimage);
238 // The details of the Impl
239 // =======================
243 struct IncrementedFileName {
244 IncrementedFileName(string const & to_format,
245 string const & filename_base)
246 : to_format_(to_format), base_(filename_base), counter_(1)
249 StrPair const operator()(string const & snippet)
253 << setfill('0') << setw(3) << counter_++
254 << "." << to_format_;
256 string const file = os.str().c_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 ForkedcallsController::get().kill(pid, 0);
289 if (!metrics_file.empty())
290 lyx::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 lyx::unlink(vit->second);
305 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
306 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
308 font_scaling_factor_ = setFontScalingFactor(const_cast<Buffer &>(b));
310 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
311 << font_scaling_factor_ << endl;
314 pconverter_ = setConverter();
318 PreviewLoader::Impl::~Impl()
320 InProgressProcesses::iterator ipit = in_progress_.begin();
321 InProgressProcesses::iterator ipend = in_progress_.end();
323 for (; ipit != ipend; ++ipit) {
330 PreviewLoader::Impl::preview(string const & latex_snippet) const
332 Cache::const_iterator it = cache_.find(latex_snippet);
333 return (it == cache_.end()) ? 0 : it->second.get();
340 FindSnippet(string const & s) : snippet_(s) {}
341 bool operator()(InProgressProcess const & process)
343 BitmapFile const & snippets = process.second.snippets;
344 BitmapFile::const_iterator it = snippets.begin();
345 BitmapFile::const_iterator end = snippets.end();
346 it = find_if(it, end, FindFirst(snippet_));
351 string const & snippet_;
356 PreviewLoader::Status
357 PreviewLoader::Impl::status(string const & latex_snippet) const
359 Cache::const_iterator cit = cache_.find(latex_snippet);
360 if (cit != cache_.end())
363 PendingSnippets::const_iterator pit = pending_.begin();
364 PendingSnippets::const_iterator pend = pending_.end();
366 pit = find(pit, pend, latex_snippet);
370 InProgressProcesses::const_iterator ipit = in_progress_.begin();
371 InProgressProcesses::const_iterator ipend = in_progress_.end();
373 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
381 void PreviewLoader::Impl::add(string const & latex_snippet)
383 if (!pconverter_ || status(latex_snippet) != NotFound)
386 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << latex_snippet << endl;
388 pending_.push_back(latex_snippet);
394 struct EraseSnippet {
395 EraseSnippet(string const & s) : snippet_(s) {}
396 void operator()(InProgressProcess & process)
398 BitmapFile & snippets = process.second.snippets;
399 BitmapFile::iterator it = snippets.begin();
400 BitmapFile::iterator end = snippets.end();
402 it = find_if(it, end, FindFirst(snippet_));
404 snippets.erase(it, it+1);
408 string const & snippet_;
414 void PreviewLoader::Impl::remove(string const & latex_snippet)
416 Cache::iterator cit = cache_.find(latex_snippet);
417 if (cit != cache_.end())
420 PendingSnippets::iterator pit = pending_.begin();
421 PendingSnippets::iterator pend = pending_.end();
423 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
425 InProgressProcesses::iterator ipit = in_progress_.begin();
426 InProgressProcesses::iterator ipend = in_progress_.end();
428 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
430 for (; ipit != ipend; ++ipit) {
431 InProgressProcesses::iterator curr = ipit++;
432 if (curr->second.snippets.empty())
433 in_progress_.erase(curr);
438 void PreviewLoader::Impl::startLoading()
440 if (pending_.empty() || !pconverter_)
443 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
445 // As used by the LaTeX file and by the resulting image files
446 string const filename_base(unique_filename(buffer_.tmppath));
448 // Create an InProgress instance to place in the map of all
449 // such processes if it starts correctly.
450 InProgress inprogress(filename_base, pending_, pconverter_->to);
452 // clear pending_, so we're ready to start afresh.
455 // Output the LaTeX file.
456 string const latexfile = filename_base + ".tex";
458 ofstream of(latexfile.c_str());
459 of << "\\batchmode\n";
461 of << "\n\\begin{document}\n";
462 dumpData(of, inprogress.snippets);
463 of << "\n\\end{document}\n";
466 // The conversion command.
468 cs << pconverter_->command << " " << latexfile << " "
469 << int(font_scaling_factor_);
471 string const command = LibScriptSearch(cs.str().c_str());
473 // Initiate the conversion from LaTeX to bitmap images files.
474 Forkedcall::SignalTypePtr convert_ptr;
475 convert_ptr.reset(new Forkedcall::SignalType);
477 convert_ptr->connect(
478 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
481 int ret = call.startscript(command, convert_ptr);
484 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
485 << "Unable to start process \n"
490 // Store the generation process in a list of all such processes
491 inprogress.pid = call.pid();
492 in_progress_[command] = inprogress;
496 void PreviewLoader::Impl::finishedGenerating(string const & command,
497 pid_t /* pid */, int retval)
499 string const status = retval > 0 ? "failed" : "succeeded";
500 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
501 << retval << "): processing " << status
502 << " for " << command << endl;
507 InProgressProcesses::iterator git = in_progress_.find(command);
508 if (git == in_progress_.end()) {
509 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
511 << command << "!" << endl;
515 // Read the metrics file, if it exists
516 vector<double> ascent_fractions(git->second.snippets.size());
517 setAscentFractions(ascent_fractions, git->second.metrics_file);
519 // Add these newly generated bitmap files to the cache and
520 // start loading them into LyX.
521 BitmapFile::const_iterator it = git->second.snippets.begin();
522 BitmapFile::const_iterator end = git->second.snippets.end();
524 std::list<PreviewImagePtr> newimages;
526 int metrics_counter = 0;
527 for (; it != end; ++it, ++metrics_counter) {
528 string const & snip = it->first;
529 string const & file = it->second;
530 double af = ascent_fractions[metrics_counter];
532 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
535 newimages.push_back(ptr);
538 // Remove the item from the list of still-executing processes.
539 in_progress_.erase(git);
541 // Tell the outside world
542 std::list<PreviewImagePtr>::const_iterator nit = newimages.begin();
543 std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
544 for (; nit != nend; ++nit) {
545 imageReady(*nit->get());
550 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
552 // Why on earth is Buffer::makeLaTeXFile a non-const method?
553 Buffer & tmp = const_cast<Buffer &>(buffer_);
554 // Dump the preamble only.
555 tmp.makeLaTeXFile(os, string(), true, false, true);
557 // Loop over the insets in the buffer and dump all the math-macros.
558 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
559 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
561 for (; it != end; ++it) {
562 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
563 (*it)->latex(&buffer_, os, true, true);
567 // All equation lables appear as "(#)" + preview.sty's rendering of
569 if (lyxrc.preview_hashed_labels)
570 os << "\\renewcommand{\\theequation}{\\#}\n";
572 // Use the preview style file to ensure that each snippet appears on a
575 << "\\usepackage[active,delayed,dvips,tightpage,showlabels]{preview}\n"
578 // This piece of PostScript magic ensures that the foreground and
579 // background colors are the same as the LyX screen.
580 string fg = lyx_gui::hexname(LColor::preview);
581 if (fg.empty()) fg = "000000";
583 string bg = lyx_gui::hexname(LColor::background);
584 if (bg.empty()) bg = "ffffff";
586 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
587 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
588 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
589 << "clippath fill setrgbcolor}bind def end}}}\n";
593 void PreviewLoader::Impl::dumpData(ostream & os,
594 BitmapFile const & vec) const
599 BitmapFile::const_iterator it = vec.begin();
600 BitmapFile::const_iterator end = vec.end();
602 for (; it != end; ++it) {
603 os << "\\begin{preview}\n"
605 << "\n\\end{preview}\n\n";
614 string const unique_filename(string const bufferpath)
616 static int theCounter = 0;
617 string const filename = tostr(theCounter++) + "lyxpreview";
618 return AddName(bufferpath, filename);
622 Converter const * setConverter()
624 string const from = "lyxpreview";
626 Formats::FormatList::const_iterator it = formats.begin();
627 Formats::FormatList::const_iterator end = formats.end();
629 for (; it != end; ++it) {
630 string const to = it->name();
634 Converter const * ptr = converters.getConverter(from, to);
639 static bool first = true;
642 lyxerr << "PreviewLoader::startLoading()\n"
643 << "No converter from \"lyxpreview\" format has been "
652 double setFontScalingFactor(Buffer & buffer)
654 double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
655 lyxrc.preview_scale_factor;
657 // Has the font size been set explicitly?
658 string const & fontsize = buffer.params.fontsize;
659 lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
660 << "font size is " << fontsize << endl;
662 if (isStrUnsignedInt(fontsize))
663 return 10.0 * scale_factor / strToDbl(fontsize);
665 // No. We must extract it from the LaTeX class file.
666 LyXTextClass const & tclass = buffer.params.getLyXTextClass();
667 string const textclass(tclass.latexname() + ".cls");
668 string const classfile(findtexfile(textclass, "cls"));
670 lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
671 << "class file is " << classfile << endl;
673 ifstream ifs(classfile.c_str());
675 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
680 double scaling = scale_factor;
684 // To get the default font size, look for a line like
685 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
686 if (!prefixIs(ltrim(str), "\\ExecuteOptions"))
689 // str contains just the options of \ExecuteOptions
690 string const tmp = split(str, '{');
691 split(tmp, str, '}');
694 string tok = token(str, ',', count++);
695 while (!isValidLength(tok) && !tok.empty())
696 tok = token(str, ',', count++);
699 lyxerr[Debug::GRAPHICS]
700 << "Extracted default font size from "
701 "LaTeX class file successfully!" << endl;
702 LyXLength fsize(tok);
703 scaling *= 10.0 / fsize.value();
712 void setAscentFractions(vector<double> & ascent_fractions,
713 string const & metrics_file)
715 // If all else fails, then the images will have equal ascents and
717 vector<double>::iterator it = ascent_fractions.begin();
718 vector<double>::iterator end = ascent_fractions.end();
721 ifstream ifs(metrics_file.c_str());
723 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
724 << metrics_file << ")\n"
725 << "Unable to open file!"
730 for (; it != end; ++it) {
737 ifs >> page >> page_id >> dummy >> dummy >> dummy >> dummy
738 >> ascent >> descent >> dummy;
742 !isStrUnsignedInt(rtrim(page_id, ":"))) {
743 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
744 << metrics_file << ")\n"
745 << "Error reading file!"
750 if (ascent + descent != 0)
751 *it = ascent / (ascent + descent);