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);
138 /// Emit this signal when an image is ready for display.
139 boost::signal1<void, PreviewImage const &> imageReady;
142 /// Called by the Forkedcall process that generated the bitmap files.
143 void finishedGenerating(string const &, pid_t, int);
145 void dumpPreamble(ostream &) const;
147 void dumpData(ostream &, BitmapFile const &) const;
149 /** cache_ allows easy retrieval of already-generated images
150 * using the LaTeX snippet as the identifier.
152 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
154 typedef map<string, PreviewImagePtr> Cache;
158 /** pending_ stores the LaTeX snippets in anticipation of them being
159 * sent to the converter.
161 PendingSnippets pending_;
163 /** in_progress_ stores all forked processes so that we can proceed
165 The map uses the conversion commands as its identifiers.
167 InProgressProcesses in_progress_;
170 PreviewLoader & parent_;
172 Buffer const & buffer_;
174 double font_scaling_factor_;
176 /// We don't own this
177 static Converter const * pconverter_;
181 Converter const * PreviewLoader::Impl::pconverter_;
184 // The public interface, defined in PreviewLoader.h
185 // ================================================
186 PreviewLoader::PreviewLoader(Buffer const & b)
187 : pimpl_(new Impl(*this, b))
191 PreviewLoader::~PreviewLoader()
195 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
197 return pimpl_->preview(latex_snippet);
201 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
203 return pimpl_->status(latex_snippet);
207 void PreviewLoader::add(string const & latex_snippet) const
209 pimpl_->add(latex_snippet);
213 void PreviewLoader::remove(string const & latex_snippet) const
215 pimpl_->remove(latex_snippet);
219 void PreviewLoader::startLoading() const
221 pimpl_->startLoading();
225 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
227 return pimpl_->imageReady.connect(slot);
231 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
233 pimpl_->imageReady(pimage);
239 // The details of the Impl
240 // =======================
244 struct IncrementedFileName {
245 IncrementedFileName(string const & to_format,
246 string const & filename_base)
247 : to_format_(to_format), base_(filename_base), counter_(1)
250 StrPair const operator()(string const & snippet)
254 << setfill('0') << setw(3) << counter_++
255 << "." << to_format_;
257 string const file = os.str().c_str();
259 return make_pair(snippet, file);
263 string const & to_format_;
264 string const & base_;
269 InProgress::InProgress(string const & filename_base,
270 PendingSnippets const & pending,
271 string const & to_format)
273 metrics_file(filename_base + ".metrics"),
274 snippets(pending.size())
276 PendingSnippets::const_iterator pit = pending.begin();
277 PendingSnippets::const_iterator pend = pending.end();
278 BitmapFile::iterator sit = snippets.begin();
280 std::transform(pit, pend, sit,
281 IncrementedFileName(to_format, filename_base));
285 void InProgress::stop() const
288 ForkedcallsController::get().kill(pid, 0);
290 if (!metrics_file.empty())
291 lyx::unlink(metrics_file);
293 BitmapFile::const_iterator vit = snippets.begin();
294 BitmapFile::const_iterator vend = snippets.end();
295 for (; vit != vend; ++vit) {
296 if (!vit->second.empty())
297 lyx::unlink(vit->second);
306 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
307 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
309 font_scaling_factor_ = setFontScalingFactor(const_cast<Buffer &>(b));
311 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
312 << font_scaling_factor_ << endl;
315 pconverter_ = setConverter();
319 PreviewLoader::Impl::~Impl()
321 InProgressProcesses::iterator ipit = in_progress_.begin();
322 InProgressProcesses::iterator ipend = in_progress_.end();
324 for (; ipit != ipend; ++ipit) {
331 PreviewLoader::Impl::preview(string const & latex_snippet) const
333 Cache::const_iterator it = cache_.find(latex_snippet);
334 return (it == cache_.end()) ? 0 : it->second.get();
341 FindSnippet(string const & s) : snippet_(s) {}
342 bool operator()(InProgressProcess const & process)
344 BitmapFile const & snippets = process.second.snippets;
345 BitmapFile::const_iterator it = snippets.begin();
346 BitmapFile::const_iterator end = snippets.end();
347 it = find_if(it, end, FindFirst(snippet_));
352 string const & snippet_;
357 PreviewLoader::Status
358 PreviewLoader::Impl::status(string const & latex_snippet) const
360 Cache::const_iterator cit = cache_.find(latex_snippet);
361 if (cit != cache_.end())
364 PendingSnippets::const_iterator pit = pending_.begin();
365 PendingSnippets::const_iterator pend = pending_.end();
367 pit = find(pit, pend, latex_snippet);
371 InProgressProcesses::const_iterator ipit = in_progress_.begin();
372 InProgressProcesses::const_iterator ipend = in_progress_.end();
374 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
382 void PreviewLoader::Impl::add(string const & latex_snippet)
384 if (!pconverter_ || status(latex_snippet) != NotFound)
387 pending_.push_back(latex_snippet);
393 struct EraseSnippet {
394 EraseSnippet(string const & s) : snippet_(s) {}
395 void operator()(InProgressProcess & process)
397 BitmapFile & snippets = process.second.snippets;
398 BitmapFile::iterator it = snippets.begin();
399 BitmapFile::iterator end = snippets.end();
401 it = find_if(it, end, FindFirst(snippet_));
403 snippets.erase(it, it+1);
407 string const & snippet_;
413 void PreviewLoader::Impl::remove(string const & latex_snippet)
415 Cache::iterator cit = cache_.find(latex_snippet);
416 if (cit != cache_.end())
419 PendingSnippets::iterator pit = pending_.begin();
420 PendingSnippets::iterator pend = pending_.end();
422 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
424 InProgressProcesses::iterator ipit = in_progress_.begin();
425 InProgressProcesses::iterator ipend = in_progress_.end();
427 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
429 for (; ipit != ipend; ++ipit) {
430 InProgressProcesses::iterator curr = ipit++;
431 if (curr->second.snippets.empty())
432 in_progress_.erase(curr);
437 void PreviewLoader::Impl::startLoading()
439 if (pending_.empty() || !pconverter_)
442 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
444 // As used by the LaTeX file and by the resulting image files
445 string const filename_base(unique_filename(buffer_.tmppath));
447 // Create an InProgress instance to place in the map of all
448 // such processes if it starts correctly.
449 InProgress inprogress(filename_base, pending_, pconverter_->to);
451 // clear pending_, so we're ready to start afresh.
454 // Output the LaTeX file.
455 string const latexfile = filename_base + ".tex";
457 ofstream of(latexfile.c_str());
458 of << "\\batchmode\n";
460 of << "\n\\begin{document}\n";
461 dumpData(of, inprogress.snippets);
462 of << "\n\\end{document}\n";
465 // The conversion command.
467 cs << pconverter_->command << " " << latexfile << " "
468 << font_scaling_factor_;
470 string const command = LibScriptSearch(cs.str().c_str());
472 // Initiate the conversion from LaTeX to bitmap images files.
473 Forkedcall::SignalTypePtr convert_ptr;
474 convert_ptr.reset(new Forkedcall::SignalType);
476 convert_ptr->connect(
477 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
480 int ret = call.startscript(command, convert_ptr);
483 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
484 << "Unable to start process \n"
489 // Store the generation process in a list of all such processes
490 inprogress.pid = call.pid();
491 in_progress_[command] = inprogress;
495 void PreviewLoader::Impl::finishedGenerating(string const & command,
496 pid_t /* pid */, int retval)
498 string const status = retval > 0 ? "failed" : "succeeded";
499 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
500 << retval << "): processing " << status
501 << " for " << command << endl;
506 InProgressProcesses::iterator git = in_progress_.find(command);
507 if (git == in_progress_.end()) {
508 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
510 << command << "!" << endl;
514 // Read the metrics file, if it exists
515 vector<double> ascent_fractions(git->second.snippets.size());
516 setAscentFractions(ascent_fractions, git->second.metrics_file);
518 // Add these newly generated bitmap files to the cache and
519 // start loading them into LyX.
520 BitmapFile::const_iterator it = git->second.snippets.begin();
521 BitmapFile::const_iterator end = git->second.snippets.end();
523 std::list<PreviewImagePtr> newimages;
525 int metrics_counter = 0;
526 for (; it != end; ++it, ++metrics_counter) {
527 string const & snip = it->first;
528 string const & file = it->second;
529 double af = ascent_fractions[metrics_counter];
531 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
534 newimages.push_back(ptr);
537 // Remove the item from the list of still-executing processes.
538 in_progress_.erase(git);
540 // Tell the outside world
541 std::list<PreviewImagePtr>::const_iterator nit = newimages.begin();
542 std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
543 for (; nit != nend; ++nit) {
544 imageReady(*nit->get());
549 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
551 // Why on earth is Buffer::makeLaTeXFile a non-const method?
552 Buffer & tmp = const_cast<Buffer &>(buffer_);
553 // Dump the preamble only.
554 tmp.makeLaTeXFile(os, string(), true, false, true);
556 // Loop over the insets in the buffer and dump all the math-macros.
557 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
558 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
560 for (; it != end; ++it) {
561 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
562 (*it)->latex(&buffer_, os, true, true);
566 // All equation lables appear as "(#)" + preview.sty's rendering of
568 if (lyxrc.preview_hashed_labels)
569 os << "\\renewcommand{\\theequation}{\\#}\n";
571 // Use the preview style file to ensure that each snippet appears on a
574 << "\\usepackage[active,delayed,dvips,tightpage,showlabels]{preview}\n"
577 // This piece of PostScript magic ensures that the foreground and
578 // background colors are the same as the LyX screen.
579 string fg = lyx_gui::hexname(LColor::preview);
580 if (fg.empty()) fg = "000000";
582 string bg = lyx_gui::hexname(LColor::background);
583 if (bg.empty()) bg = "ffffff";
585 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
586 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
587 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
588 << "clippath fill setrgbcolor}bind def end}}}\n";
592 void PreviewLoader::Impl::dumpData(ostream & os,
593 BitmapFile const & vec) const
598 BitmapFile::const_iterator it = vec.begin();
599 BitmapFile::const_iterator end = vec.end();
601 for (; it != end; ++it) {
602 os << "\\begin{preview}\n"
604 << "\n\\end{preview}\n\n";
613 string const unique_filename(string const bufferpath)
615 static int theCounter = 0;
616 string const filename = tostr(theCounter++) + "lyxpreview";
617 return AddName(bufferpath, filename);
621 Converter const * setConverter()
623 string const from = "lyxpreview";
625 Formats::FormatList::const_iterator it = formats.begin();
626 Formats::FormatList::const_iterator end = formats.end();
628 for (; it != end; ++it) {
629 string const to = it->name();
633 Converter const * ptr = converters.getConverter(from, to);
638 static bool first = true;
641 lyxerr << "PreviewLoader::startLoading()\n"
642 << "No converter from \"lyxpreview\" format has been "
651 double setFontScalingFactor(Buffer & buffer)
653 double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
654 lyxrc.preview_scale_factor;
656 // Has the font size been set explicitly?
657 string const & fontsize = buffer.params.fontsize;
658 lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
659 << "font size is " << fontsize << endl;
661 if (isStrUnsignedInt(fontsize))
662 return 10.0 * scale_factor / strToDbl(fontsize);
664 // No. We must extract it from the LaTeX class file.
665 LyXTextClass const & tclass = textclasslist[buffer.params.textclass];
666 string const textclass(tclass.latexname() + ".cls");
667 string const classfile(findtexfile(textclass, "cls"));
669 lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
670 << "class file is " << classfile << endl;
672 ifstream ifs(classfile.c_str());
674 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
679 double scaling = scale_factor;
683 // To get the default font size, look for a line like
684 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
685 if (!prefixIs(frontStrip(str), "\\ExecuteOptions"))
688 // str contains just the options of \ExecuteOptions
689 string const tmp = split(str, '{');
690 split(tmp, str, '}');
693 string tok = token(str, ',', count++);
694 while (!isValidLength(tok) && !tok.empty())
695 tok = token(str, ',', count++);
698 lyxerr[Debug::GRAPHICS]
699 << "Extracted default font size from "
700 "LaTeX class file successfully!" << endl;
701 LyXLength fsize(tok);
702 scaling *= 10.0 / fsize.value();
711 void setAscentFractions(vector<double> & ascent_fractions,
712 string const & metrics_file)
714 // If all else fails, then the images will have equal ascents and
716 vector<double>::iterator it = ascent_fractions.begin();
717 vector<double>::iterator end = ascent_fractions.end();
720 ifstream ifs(metrics_file.c_str());
722 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
723 << metrics_file << ")\n"
724 << "Unable to open file!"
729 for (; it != end; ++it) {
736 ifs >> page >> page_id >> dummy >> dummy >> dummy >> dummy
737 >> ascent >> descent >> dummy;
741 !isStrUnsignedInt(strip(page_id, ':'))) {
742 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
743 << metrics_file << ")\n"
744 << "Error reading file!"
749 if (ascent + descent != 0)
750 *it = ascent / (ascent + descent);