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 pending_.push_back(latex_snippet);
392 struct EraseSnippet {
393 EraseSnippet(string const & s) : snippet_(s) {}
394 void operator()(InProgressProcess & process)
396 BitmapFile & snippets = process.second.snippets;
397 BitmapFile::iterator it = snippets.begin();
398 BitmapFile::iterator end = snippets.end();
400 it = find_if(it, end, FindFirst(snippet_));
402 snippets.erase(it, it+1);
406 string const & snippet_;
412 void PreviewLoader::Impl::remove(string const & latex_snippet)
414 Cache::iterator cit = cache_.find(latex_snippet);
415 if (cit != cache_.end())
418 PendingSnippets::iterator pit = pending_.begin();
419 PendingSnippets::iterator pend = pending_.end();
421 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
423 InProgressProcesses::iterator ipit = in_progress_.begin();
424 InProgressProcesses::iterator ipend = in_progress_.end();
426 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
428 for (; ipit != ipend; ++ipit) {
429 InProgressProcesses::iterator curr = ipit++;
430 if (curr->second.snippets.empty())
431 in_progress_.erase(curr);
436 void PreviewLoader::Impl::startLoading()
438 if (pending_.empty() || !pconverter_)
441 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
443 // As used by the LaTeX file and by the resulting image files
444 string const filename_base(unique_filename(buffer_.tmppath));
446 // Create an InProgress instance to place in the map of all
447 // such processes if it starts correctly.
448 InProgress inprogress(filename_base, pending_, pconverter_->to);
450 // clear pending_, so we're ready to start afresh.
453 // Output the LaTeX file.
454 string const latexfile = filename_base + ".tex";
456 ofstream of(latexfile.c_str());
457 of << "\\batchmode\n";
459 of << "\n\\begin{document}\n";
460 dumpData(of, inprogress.snippets);
461 of << "\n\\end{document}\n";
464 // The conversion command.
466 cs << pconverter_->command << " " << latexfile << " "
467 << int(font_scaling_factor_);
469 string const command = LibScriptSearch(cs.str().c_str());
471 // Initiate the conversion from LaTeX to bitmap images files.
472 Forkedcall::SignalTypePtr convert_ptr;
473 convert_ptr.reset(new Forkedcall::SignalType);
475 convert_ptr->connect(
476 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
479 int ret = call.startscript(command, convert_ptr);
482 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
483 << "Unable to start process \n"
488 // Store the generation process in a list of all such processes
489 inprogress.pid = call.pid();
490 in_progress_[command] = inprogress;
494 void PreviewLoader::Impl::finishedGenerating(string const & command,
495 pid_t /* pid */, int retval)
497 string const status = retval > 0 ? "failed" : "succeeded";
498 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
499 << retval << "): processing " << status
500 << " for " << command << endl;
505 InProgressProcesses::iterator git = in_progress_.find(command);
506 if (git == in_progress_.end()) {
507 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
509 << command << "!" << endl;
513 // Read the metrics file, if it exists
514 vector<double> ascent_fractions(git->second.snippets.size());
515 setAscentFractions(ascent_fractions, git->second.metrics_file);
517 // Add these newly generated bitmap files to the cache and
518 // start loading them into LyX.
519 BitmapFile::const_iterator it = git->second.snippets.begin();
520 BitmapFile::const_iterator end = git->second.snippets.end();
522 std::list<PreviewImagePtr> newimages;
524 int metrics_counter = 0;
525 for (; it != end; ++it, ++metrics_counter) {
526 string const & snip = it->first;
527 string const & file = it->second;
528 double af = ascent_fractions[metrics_counter];
530 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
533 newimages.push_back(ptr);
536 // Remove the item from the list of still-executing processes.
537 in_progress_.erase(git);
539 // Tell the outside world
540 std::list<PreviewImagePtr>::const_iterator nit = newimages.begin();
541 std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
542 for (; nit != nend; ++nit) {
543 imageReady(*nit->get());
548 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
550 // Why on earth is Buffer::makeLaTeXFile a non-const method?
551 Buffer & tmp = const_cast<Buffer &>(buffer_);
552 // Dump the preamble only.
553 tmp.makeLaTeXFile(os, string(), true, false, true);
555 // Loop over the insets in the buffer and dump all the math-macros.
556 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
557 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
559 for (; it != end; ++it) {
560 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
561 (*it)->latex(&buffer_, os, true, true);
565 // All equation lables appear as "(#)" + preview.sty's rendering of
567 if (lyxrc.preview_hashed_labels)
568 os << "\\renewcommand{\\theequation}{\\#}\n";
570 // Use the preview style file to ensure that each snippet appears on a
573 << "\\usepackage[active,delayed,dvips,tightpage,showlabels]{preview}\n"
576 // This piece of PostScript magic ensures that the foreground and
577 // background colors are the same as the LyX screen.
578 string fg = lyx_gui::hexname(LColor::preview);
579 if (fg.empty()) fg = "000000";
581 string bg = lyx_gui::hexname(LColor::background);
582 if (bg.empty()) bg = "ffffff";
584 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
585 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
586 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
587 << "clippath fill setrgbcolor}bind def end}}}\n";
591 void PreviewLoader::Impl::dumpData(ostream & os,
592 BitmapFile const & vec) const
597 BitmapFile::const_iterator it = vec.begin();
598 BitmapFile::const_iterator end = vec.end();
600 for (; it != end; ++it) {
601 os << "\\begin{preview}\n"
603 << "\n\\end{preview}\n\n";
612 string const unique_filename(string const bufferpath)
614 static int theCounter = 0;
615 string const filename = tostr(theCounter++) + "lyxpreview";
616 return AddName(bufferpath, filename);
620 Converter const * setConverter()
622 string const from = "lyxpreview";
624 Formats::FormatList::const_iterator it = formats.begin();
625 Formats::FormatList::const_iterator end = formats.end();
627 for (; it != end; ++it) {
628 string const to = it->name();
632 Converter const * ptr = converters.getConverter(from, to);
637 static bool first = true;
640 lyxerr << "PreviewLoader::startLoading()\n"
641 << "No converter from \"lyxpreview\" format has been "
650 double setFontScalingFactor(Buffer & buffer)
652 double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
653 lyxrc.preview_scale_factor;
655 // Has the font size been set explicitly?
656 string const & fontsize = buffer.params.fontsize;
657 lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
658 << "font size is " << fontsize << endl;
660 if (isStrUnsignedInt(fontsize))
661 return 10.0 * scale_factor / strToDbl(fontsize);
663 // No. We must extract it from the LaTeX class file.
664 LyXTextClass const & tclass = buffer.params.getLyXTextClass();
665 string const textclass(tclass.latexname() + ".cls");
666 string const classfile(findtexfile(textclass, "cls"));
668 lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
669 << "class file is " << classfile << endl;
671 ifstream ifs(classfile.c_str());
673 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
678 double scaling = scale_factor;
682 // To get the default font size, look for a line like
683 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
684 if (!prefixIs(frontStrip(str), "\\ExecuteOptions"))
687 // str contains just the options of \ExecuteOptions
688 string const tmp = split(str, '{');
689 split(tmp, str, '}');
692 string tok = token(str, ',', count++);
693 while (!isValidLength(tok) && !tok.empty())
694 tok = token(str, ',', count++);
697 lyxerr[Debug::GRAPHICS]
698 << "Extracted default font size from "
699 "LaTeX class file successfully!" << endl;
700 LyXLength fsize(tok);
701 scaling *= 10.0 / fsize.value();
710 void setAscentFractions(vector<double> & ascent_fractions,
711 string const & metrics_file)
713 // If all else fails, then the images will have equal ascents and
715 vector<double>::iterator it = ascent_fractions.begin();
716 vector<double>::iterator end = ascent_fractions.end();
719 ifstream ifs(metrics_file.c_str());
721 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
722 << metrics_file << ")\n"
723 << "Unable to open file!"
728 for (; it != end; ++it) {
735 ifs >> page >> page_id >> dummy >> dummy >> dummy >> dummy
736 >> ascent >> descent >> dummy;
740 !isStrUnsignedInt(strip(page_id, ":"))) {
741 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
742 << metrics_file << ")\n"
743 << "Error reading file!"
748 if (ascent + descent != 0)
749 *it = ascent / (ascent + descent);