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());
400 of << "\\batchmode\n";
402 of << "\n\\begin{document}\n";
403 dumpData(of, inprogress.snippets);
404 of << "\n\\end{document}\n";
407 // The conversion command.
409 cs << pconverter_->command << " " << latexfile << " "
410 << font_scaling_factor_;
412 string const command = cs.str().c_str();
414 // Initiate the conversion from LaTeX to bitmap images files.
415 Forkedcall::SignalTypePtr convert_ptr;
416 convert_ptr.reset(new Forkedcall::SignalType);
418 convert_ptr->connect(
419 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
422 int ret = call.startscript(command, convert_ptr);
425 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
426 << "Unable to start process \n"
431 // Store the generation process in a list of all such processes
432 inprogress.pid = call.pid();
433 in_progress_[command] = inprogress;
437 void PreviewLoader::Impl::finishedGenerating(string const & command,
438 pid_t /* pid */, int retval)
440 string const status = retval > 0 ? "failed" : "succeeded";
441 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
442 << retval << "): processing " << status
443 << " for " << command << endl;
447 InProgressMap::iterator git = in_progress_.find(command);
448 if (git == in_progress_.end()) {
449 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
451 << command << "!" << endl;
455 // Read the metrics file, if it exists
456 vector<double> ascent_fractions(git->second.snippets.size());
457 setAscentFractions(ascent_fractions, git->second.metrics_file);
459 // Add these newly generated bitmap files to the cache and
460 // start loading them into LyX.
461 InProgressStore::const_iterator it = git->second.snippets.begin();
462 InProgressStore::const_iterator end = git->second.snippets.end();
464 int metrics_counter = 0;
465 for (; it != end; ++it, ++metrics_counter) {
466 string const & snip = it->first;
467 string const & file = it->second;
468 double af = ascent_fractions[metrics_counter];
470 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
476 // Remove the item from the list of still-executing processes.
477 in_progress_.erase(git);
481 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
483 // Why on earth is Buffer::makeLaTeXFile a non-const method?
484 Buffer & tmp = const_cast<Buffer &>(buffer_);
485 // Dump the preamble only.
486 tmp.makeLaTeXFile(os, string(), true, false, true);
488 // Loop over the insets in the buffer and dump all the math-macros.
489 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
490 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
492 for (; it != end; ++it) {
493 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
494 (*it)->latex(&buffer_, os, true, true);
498 // All equation lables appear as "(#)" + preview.sty's rendering of
500 if (lyxrc.preview_hashed_labels)
501 os << "\\renewcommand{\\theequation}{\\#}\n";
503 // Use the preview style file to ensure that each snippet appears on a
506 << "\\usepackage[active,delayed,dvips,tightpage,showlabels]{preview}\n"
509 // This piece of PostScript magic ensures that the foreground and
510 // background colors are the same as the LyX screen.
511 string fg = lyx_gui::hexname(LColor::preview);
512 if (fg.empty()) fg = "000000";
514 string bg = lyx_gui::hexname(LColor::background);
515 if (bg.empty()) bg = "ffffff";
517 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
518 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
519 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
520 << "clippath fill setrgbcolor}bind def end}}}\n";
524 void PreviewLoader::Impl::dumpData(ostream & os,
525 InProgressStore const & vec) const
530 InProgressStore::const_iterator it = vec.begin();
531 InProgressStore::const_iterator end = vec.end();
533 for (; it != end; ++it) {
534 os << "\\begin{preview}\n"
536 << "\n\\end{preview}\n\n";
545 string const unique_filename(string const bufferpath)
547 static int theCounter = 0;
548 string const filename = tostr(theCounter++) + "lyxpreview";
549 return AddName(bufferpath, filename);
553 Converter const * setConverter()
555 Converter const * converter = 0;
557 string const from = "lyxpreview";
559 Formats::FormatList::const_iterator it = formats.begin();
560 Formats::FormatList::const_iterator end = formats.end();
562 for (; it != end; ++it) {
563 string const to = it->name();
567 Converter const * ptr = converters.getConverter(from, to);
572 static bool first = true;
575 lyxerr << "PreviewLoader::startLoading()\n"
576 << "No converter from \"lyxpreview\" format has been "
585 double setFontScalingFactor(Buffer & buffer)
587 double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
588 lyxrc.preview_scale_factor;
590 // Has the font size been set explicitly?
591 string const & fontsize = buffer.params.fontsize;
592 lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
593 << "font size is " << fontsize << endl;
595 if (isStrUnsignedInt(fontsize))
596 return 10.0 * scale_factor / strToDbl(fontsize);
598 // No. We must extract it from the LaTeX class file.
599 LyXTextClass const & tclass = textclasslist[buffer.params.textclass];
600 string const textclass(tclass.latexname() + ".cls");
601 string const classfile(findtexfile(textclass, "cls"));
603 lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
604 << "class file is " << classfile << endl;
606 ifstream ifs(classfile.c_str());
608 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
613 double scaling = scale_factor;
617 // To get the default font size, look for a line like
618 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
619 if (!prefixIs(frontStrip(str), "\\ExecuteOptions"))
622 // str contains just the options of \ExecuteOptions
623 string const tmp = split(str, '{');
624 split(tmp, str, '}');
627 string tok = token(str, ',', count++);
628 while (!isValidLength(tok) && !tok.empty())
629 tok = token(str, ',', count++);
632 lyxerr[Debug::GRAPHICS]
633 << "Extracted default font size from "
634 "LaTeX class file successfully!" << endl;
635 LyXLength fsize(tok);
636 scaling *= 10.0 / fsize.value();
645 void setAscentFractions(vector<double> & ascent_fractions,
646 string const & metrics_file)
648 // If all else fails, then the images will have equal ascents and
650 vector<double>::iterator it = ascent_fractions.begin();
651 vector<double>::iterator end = ascent_fractions.end();
654 ifstream ifs(metrics_file.c_str());
656 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
657 << metrics_file << ")\n"
658 << "Unable to open file!"
663 for (; it != end; ++it) {
670 ifs >> page >> page_id >> dummy >> dummy >> dummy >> dummy
671 >> ascent >> descent >> dummy;
675 !isStrUnsignedInt(strip(page_id, ':'))) {
676 lyxerr[Debug::GRAPHICS] << "setAscentFractions("
677 << metrics_file << ")\n"
678 << "Error reading file!"
683 if (ascent + descent != 0)
684 *it = ascent / (ascent + descent);