2 * \file PreviewLoader.C
3 * Copyright 2002 the LyX Team
4 * Read the file COPYING
6 * \author Angus Leeming <a.leeming@ic.ac.uk>
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 typedef list<string> PendingStore;
69 typedef vector<StrPair> InProgressStore;
72 double setFontScalingFactor(Buffer &);
74 string const unique_filename(string const bufferpath);
76 Converter const * setConverter();
78 void setAscentFractions(vector<double> & ascent_fractions,
79 string const & metrics_file);
82 FindFirst(string const & comp) : comp_(comp) {}
83 bool operator()(StrPair const & sp)
85 return sp.first < comp_;
92 /// Store info on a currently executing, forked process.
95 InProgress() : pid(0) {}
97 InProgress(string const & filename_base,
98 PendingStore const & pending,
99 string const & to_format);
100 /// Remove any files left lying around and kill the forked process.
107 /// Each item in the vector is a pair<snippet, image file name>.
108 InProgressStore snippets;
117 struct PreviewLoader::Impl : public boost::signals::trackable {
119 Impl(PreviewLoader & p, Buffer const & b);
120 /// Stop any InProgress items still executing.
123 PreviewImage const * preview(string const & latex_snippet) const;
125 PreviewLoader::Status status(string const & latex_snippet) const;
127 void add(string const & latex_snippet);
129 void remove(string const & latex_snippet);
134 /// Called by the Forkedcall process that generated the bitmap files.
135 void finishedGenerating(string const &, pid_t, int);
137 void dumpPreamble(ostream &) const;
139 void dumpData(ostream &, InProgressStore const &) const;
141 /** cache_ allows easy retrieval of already-generated images
142 * using the LaTeX snippet as the identifier.
144 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
146 typedef map<string, PreviewImagePtr> Cache;
150 /** pending_ stores the LaTeX snippets in anticipation of them being
151 * sent to the converter.
153 PendingStore pending_;
155 /** in_progress_ stores all forked processes so that we can proceed
157 The map uses the conversion commands as its identifiers.
159 typedef map<string, InProgress> InProgressMap;
161 InProgressMap in_progress_;
164 PreviewLoader & parent_;
166 Buffer const & buffer_;
168 double font_scaling_factor_;
170 /// We don't own this
171 static Converter const * pconverter_;
175 Converter const * PreviewLoader::Impl::pconverter_;
178 // The public interface, defined in PreviewLoader.h
179 // ================================================
180 PreviewLoader::PreviewLoader(Buffer const & b)
181 : pimpl_(new Impl(*this, b))
185 PreviewLoader::~PreviewLoader()
189 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
191 return pimpl_->preview(latex_snippet);
195 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
197 return pimpl_->status(latex_snippet);
201 void PreviewLoader::add(string const & latex_snippet)
203 pimpl_->add(latex_snippet);
207 void PreviewLoader::remove(string const & latex_snippet)
209 pimpl_->remove(latex_snippet);
213 void PreviewLoader::startLoading()
215 pimpl_->startLoading();
221 // The details of the Impl
222 // =======================
226 InProgress::InProgress(string const & filename_base,
227 PendingStore const & pending,
228 string const & to_format)
230 metrics_file(filename_base + ".metrics"),
231 snippets(pending.size())
233 InProgressStore::iterator sit = snippets.begin();
234 PendingStore::const_iterator pit = pending.begin();
235 PendingStore::const_iterator pend = pending.end();
237 int counter = 1; // file numbers start at 1
238 for (; pit != pend; ++pit, ++sit, ++counter) {
241 << setfill('0') << setw(3) << counter
243 string const file = os.str().c_str();
245 *sit = make_pair(*pit, file);
250 void InProgress::stop() const
253 ForkedcallsController::get().kill(pid, 0);
255 if (!metrics_file.empty())
256 lyx::unlink(metrics_file);
258 InProgressStore::const_iterator vit = snippets.begin();
259 InProgressStore::const_iterator vend = snippets.end();
260 for (; vit != vend; ++vit) {
261 if (!vit->second.empty())
262 lyx::unlink(vit->second);
271 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
272 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
274 font_scaling_factor_ = setFontScalingFactor(const_cast<Buffer &>(b));
276 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
277 << font_scaling_factor_ << endl;
280 pconverter_ = setConverter();
284 PreviewLoader::Impl::~Impl()
286 InProgressMap::iterator ipit = in_progress_.begin();
287 InProgressMap::iterator ipend = in_progress_.end();
289 for (; ipit != ipend; ++ipit) {
296 PreviewLoader::Impl::preview(string const & latex_snippet) const
298 Cache::const_iterator it = cache_.find(latex_snippet);
299 return (it == cache_.end()) ? 0 : it->second.get();
303 PreviewLoader::Status
304 PreviewLoader::Impl::status(string const & latex_snippet) const
306 Cache::const_iterator cit = cache_.find(latex_snippet);
307 if (cit != cache_.end())
310 PendingStore::const_iterator pit = pending_.begin();
311 PendingStore::const_iterator pend = pending_.end();
312 pit = find(pit, pend, latex_snippet);
317 InProgressMap::const_iterator ipit = in_progress_.begin();
318 InProgressMap::const_iterator ipend = in_progress_.end();
320 for (; ipit != ipend; ++ipit) {
321 InProgressStore const & snippets = ipit->second.snippets;
322 InProgressStore::const_iterator sit = snippets.begin();
323 InProgressStore::const_iterator send = snippets.end();
324 sit = find_if(sit, send, FindFirst(latex_snippet));
334 void PreviewLoader::Impl::add(string const & latex_snippet)
336 if (!pconverter_ || status(latex_snippet) != NotFound)
339 pending_.push_back(latex_snippet);
343 void PreviewLoader::Impl::remove(string const & latex_snippet)
345 Cache::iterator cit = cache_.find(latex_snippet);
346 if (cit != cache_.end())
349 PendingStore::iterator pit = pending_.begin();
350 PendingStore::iterator pend = pending_.end();
351 pit = find(pit, pend, latex_snippet);
354 PendingStore::iterator first = pit++;
355 pending_.erase(first, pit);
358 InProgressMap::iterator ipit = in_progress_.begin();
359 InProgressMap::iterator ipend = in_progress_.end();
361 while (ipit != ipend) {
362 InProgressMap::iterator curr = ipit;
365 InProgressStore & snippets = curr->second.snippets;
366 InProgressStore::iterator sit = snippets.begin();
367 InProgressStore::iterator send = snippets.end();
368 sit = find_if(sit, send, FindFirst(latex_snippet));
371 snippets.erase(sit, sit+1);
373 if (snippets.empty())
374 in_progress_.erase(curr);
379 void PreviewLoader::Impl::startLoading()
381 if (pending_.empty() || !pconverter_)
384 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
386 // As used by the LaTeX file and by the resulting image files
387 string const filename_base(unique_filename(buffer_.tmppath));
389 // Create an InProgress instance to place in the map of all
390 // such processes if it starts correctly.
391 InProgress inprogress(filename_base, pending_, pconverter_->to);
393 // clear pending_, so we're ready to start afresh.
396 // Output the LaTeX file.
397 string const latexfile = filename_base + ".tex";
399 ofstream of(latexfile.c_str());
401 of << "\n\\begin{document}\n";
402 dumpData(of, inprogress.snippets);
403 of << "\n\\end{document}\n";
406 // The conversion command.
408 cs << pconverter_->command << " " << latexfile << " "
409 << font_scaling_factor_;
411 string const command = cs.str().c_str();
413 // Initiate the conversion from LaTeX to bitmap images files.
414 Forkedcall::SignalTypePtr convert_ptr;
415 convert_ptr.reset(new Forkedcall::SignalType);
417 convert_ptr->connect(
418 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
421 int ret = call.startscript(command, convert_ptr);
424 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
425 << "Unable to start process \n"
430 // Store the generation process in a list of all such processes
431 inprogress.pid = call.pid();
432 in_progress_[command] = inprogress;
436 void PreviewLoader::Impl::finishedGenerating(string const & command,
437 pid_t /* pid */, int retval)
439 string const status = retval > 0 ? "failed" : "succeeded";
440 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
441 << retval << "): processing " << status
442 << " for " << command << endl;
446 InProgressMap::iterator git = in_progress_.find(command);
447 if (git == in_progress_.end()) {
448 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
450 << command << "!" << endl;
454 // Read the metrics file, if it exists
455 vector<double> ascent_fractions(git->second.snippets.size());
456 setAscentFractions(ascent_fractions, git->second.metrics_file);
458 // Add these newly generated bitmap files to the cache and
459 // start loading them into LyX.
460 InProgressStore::const_iterator it = git->second.snippets.begin();
461 InProgressStore::const_iterator end = git->second.snippets.end();
463 int metrics_counter = 0;
464 for (; it != end; ++it, ++metrics_counter) {
465 string const & snip = it->first;
466 string const & file = it->second;
467 double af = ascent_fractions[metrics_counter];
469 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
475 // Remove the item from the list of still-executing processes.
476 in_progress_.erase(git);
480 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
482 // Why on earth is Buffer::makeLaTeXFile a non-const method?
483 Buffer & tmp = const_cast<Buffer &>(buffer_);
484 // Dump the preamble only.
485 tmp.makeLaTeXFile(os, string(), true, false, true);
487 // Loop over the insets in the buffer and dump all the math-macros.
488 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
489 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
491 for (; it != end; ++it) {
492 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
493 (*it)->latex(&buffer_, os, true, true);
497 // Use the preview style file to ensure that each snippet appears on a
500 << "\\usepackage[active,delayed,dvips,tightpage,showlabels]{preview}\n"
503 // This piece of PostScript magic ensures that the foreground and
504 // background colors are the same as the LyX screen.
505 string fg = lyx_gui::hexname(LColor::preview);
506 if (fg.empty()) fg = "000000";
508 string bg = lyx_gui::hexname(LColor::background);
509 if (bg.empty()) bg = "ffffff";
511 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
512 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
513 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
514 << "clippath fill setrgbcolor}bind def end}}}\n";
518 void PreviewLoader::Impl::dumpData(ostream & os,
519 InProgressStore const & vec) const
524 InProgressStore::const_iterator it = vec.begin();
525 InProgressStore::const_iterator end = vec.end();
527 for (; it != end; ++it) {
528 os << "\\begin{preview}\n"
530 << "\n\\end{preview}\n\n";
539 string const unique_filename(string const bufferpath)
541 static int theCounter = 0;
542 string const filename = tostr(theCounter++) + "lyxpreview";
543 return AddName(bufferpath, filename);
547 Converter const * setConverter()
549 Converter const * converter = 0;
551 string const from = "lyxpreview";
553 Formats::FormatList::const_iterator it = formats.begin();
554 Formats::FormatList::const_iterator end = formats.end();
556 for (; it != end; ++it) {
557 string const to = it->name();
561 Converter const * ptr = converters.getConverter(from, to);
566 static bool first = true;
569 lyxerr << "PreviewLoader::startLoading()\n"
570 << "No converter from \"lyxpreview\" format has been "
579 double setFontScalingFactor(Buffer & buffer)
581 static double const lyxrc_preview_scale_factor = 0.9;
582 double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
583 lyxrc_preview_scale_factor;
585 // Has the font size been set explicitly?
586 string const & fontsize = buffer.params.fontsize;
587 lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
588 << "font size is " << fontsize << endl;
590 if (isStrUnsignedInt(fontsize))
591 return 10.0 * scale_factor / strToDbl(fontsize);
593 // No. We must extract it from the LaTeX class file.
594 LyXTextClass const & tclass = textclasslist[buffer.params.textclass];
595 string const textclass(tclass.latexname() + ".cls");
596 string const classfile(findtexfile(textclass, "cls"));
598 lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
599 << "class file is " << classfile << endl;
601 ifstream ifs(classfile.c_str());
603 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
608 double scaling = scale_factor;
612 // To get the default font size, look for a line like
613 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
614 if (!prefixIs(frontStrip(str), "\\ExecuteOptions"))
617 str = split(str, '{');
619 string tok = token(str, ',', count++);
620 while (!isValidLength(tok) && !tok.empty())
621 tok = token(str, ',', count++);
624 lyxerr[Debug::GRAPHICS]
625 << "Extracted default font size from "
626 "LaTeX class file successfully!" << endl;
627 LyXLength fsize(tok);
628 scaling *= 10.0 / fsize.value();
637 void setAscentFractions(vector<double> & ascent_fractions,
638 string const & metrics_file)
640 // If all else fails, then the images will have equal ascents and
642 vector<double>::iterator it = ascent_fractions.begin();
643 vector<double>::iterator end = ascent_fractions.end();
646 ifstream ifs(metrics_file.c_str());
648 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
649 << metrics_file << ")\n"
650 << "Unable to open file!"
655 for (; it != end; ++it) {
662 ifs >> page >> page_id >> dummy >> dummy >> dummy >> dummy
663 >> ascent >> descent >> dummy;
667 !isStrUnsignedInt(strip(page_id, ':'))) {
668 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
669 << metrics_file << ")\n"
670 << "Error reading file!"
675 *it = ascent / (ascent + descent);