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 // Set to 1 if using preview.sty >= 0.73 and a version of lyxpreview2ppm.sh
16 // that extracts the metrics info from the latex log file.
17 #define USING_NEW_PREVIEW_STY 0
19 #include "PreviewLoader.h"
20 #include "PreviewImage.h"
23 #if !USING_NEW_PREVIEW_STY
24 #include "bufferparams.h"
26 #include "converter.h"
31 #include "insets/inset.h"
33 #include "frontends/lyx_gui.h" // hexname
35 #include "support/filetools.h"
36 #include "support/forkedcall.h"
37 #include "support/forkedcontr.h"
38 #include "support/lstrings.h"
39 #include "support/lyxlib.h"
41 #include <boost/bind.hpp>
42 #include <boost/signals/trackable.hpp>
70 typedef pair<string, string> StrPair;
72 // A list of alll snippets to be converted to previews
73 typedef list<string> PendingSnippets;
75 // Each item in the vector is a pair<snippet, image file name>.
76 typedef vector<StrPair> BitmapFile;
79 #if !USING_NEW_PREVIEW_STY
80 double setFontScalingFactor(Buffer &);
83 string const unique_filename(string const bufferpath);
85 Converter const * setConverter();
87 void setAscentFractions(vector<double> & ascent_fractions,
88 string const & metrics_file);
91 FindFirst(string const & comp) : comp_(comp) {}
92 bool operator()(StrPair const & sp)
94 return sp.first < comp_;
101 /// Store info on a currently executing, forked process.
104 InProgress() : pid(0) {}
106 InProgress(string const & filename_base,
107 PendingSnippets const & pending,
108 string const & to_format);
109 /// Remove any files left lying around and kill the forked process.
120 typedef map<string, InProgress> InProgressProcesses;
122 typedef InProgressProcesses::value_type InProgressProcess;
129 struct PreviewLoader::Impl : public boost::signals::trackable {
131 Impl(PreviewLoader & p, Buffer const & b);
132 /// Stop any InProgress items still executing.
135 PreviewImage const * preview(string const & latex_snippet) const;
137 PreviewLoader::Status status(string const & latex_snippet) const;
139 void add(string const & latex_snippet);
141 void remove(string const & latex_snippet);
145 /// Emit this signal when an image is ready for display.
146 boost::signal1<void, PreviewImage const &> imageReady;
148 Buffer const & buffer() const { return buffer_; }
151 /// Called by the Forkedcall process that generated the bitmap files.
152 void finishedGenerating(string const &, pid_t, int);
154 void dumpPreamble(ostream &) const;
156 void dumpData(ostream &, BitmapFile const &) const;
158 /** cache_ allows easy retrieval of already-generated images
159 * using the LaTeX snippet as the identifier.
161 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
163 typedef map<string, PreviewImagePtr> Cache;
167 /** pending_ stores the LaTeX snippets in anticipation of them being
168 * sent to the converter.
170 PendingSnippets pending_;
172 /** in_progress_ stores all forked processes so that we can proceed
174 The map uses the conversion commands as its identifiers.
176 InProgressProcesses in_progress_;
179 PreviewLoader & parent_;
181 Buffer const & buffer_;
183 double font_scaling_factor_;
185 /// We don't own this
186 static Converter const * pconverter_;
190 Converter const * PreviewLoader::Impl::pconverter_;
193 // The public interface, defined in PreviewLoader.h
194 // ================================================
195 PreviewLoader::PreviewLoader(Buffer const & b)
196 : pimpl_(new Impl(*this, b))
200 PreviewLoader::~PreviewLoader()
204 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
206 return pimpl_->preview(latex_snippet);
210 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
212 return pimpl_->status(latex_snippet);
216 void PreviewLoader::add(string const & latex_snippet) const
218 pimpl_->add(latex_snippet);
222 void PreviewLoader::remove(string const & latex_snippet) const
224 pimpl_->remove(latex_snippet);
228 void PreviewLoader::startLoading() const
230 pimpl_->startLoading();
234 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
236 return pimpl_->imageReady.connect(slot);
240 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
242 pimpl_->imageReady(pimage);
246 Buffer const & PreviewLoader::buffer() const
248 return pimpl_->buffer();
254 // The details of the Impl
255 // =======================
259 struct IncrementedFileName {
260 IncrementedFileName(string const & to_format,
261 string const & filename_base)
262 : to_format_(to_format), base_(filename_base), counter_(1)
265 StrPair const operator()(string const & snippet)
269 << setfill('0') << setw(3) << counter_++
270 << "." << to_format_;
272 string const file = os.str().c_str();
274 return make_pair(snippet, file);
278 string const & to_format_;
279 string const & base_;
284 InProgress::InProgress(string const & filename_base,
285 PendingSnippets const & pending,
286 string const & to_format)
288 metrics_file(filename_base + ".metrics"),
289 snippets(pending.size())
291 PendingSnippets::const_iterator pit = pending.begin();
292 PendingSnippets::const_iterator pend = pending.end();
293 BitmapFile::iterator sit = snippets.begin();
295 std::transform(pit, pend, sit,
296 IncrementedFileName(to_format, filename_base));
300 void InProgress::stop() const
303 ForkedcallsController::get().kill(pid, 0);
305 if (!metrics_file.empty())
306 lyx::unlink(metrics_file);
308 BitmapFile::const_iterator vit = snippets.begin();
309 BitmapFile::const_iterator vend = snippets.end();
310 for (; vit != vend; ++vit) {
311 if (!vit->second.empty())
312 lyx::unlink(vit->second);
321 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
322 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
324 #if USING_NEW_PREVIEW_STY
325 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
326 lyxrc.preview_scale_factor;
328 font_scaling_factor_ = setFontScalingFactor(const_cast<Buffer &>(b));
331 lyxerr[Debug::GRAPHICS] << "The font scaling factor is "
332 << font_scaling_factor_ << endl;
335 pconverter_ = setConverter();
339 PreviewLoader::Impl::~Impl()
341 InProgressProcesses::iterator ipit = in_progress_.begin();
342 InProgressProcesses::iterator ipend = in_progress_.end();
344 for (; ipit != ipend; ++ipit) {
351 PreviewLoader::Impl::preview(string const & latex_snippet) const
353 Cache::const_iterator it = cache_.find(latex_snippet);
354 return (it == cache_.end()) ? 0 : it->second.get();
361 FindSnippet(string const & s) : snippet_(s) {}
362 bool operator()(InProgressProcess const & process)
364 BitmapFile const & snippets = process.second.snippets;
365 BitmapFile::const_iterator it = snippets.begin();
366 BitmapFile::const_iterator end = snippets.end();
367 it = find_if(it, end, FindFirst(snippet_));
372 string const & snippet_;
377 PreviewLoader::Status
378 PreviewLoader::Impl::status(string const & latex_snippet) const
380 Cache::const_iterator cit = cache_.find(latex_snippet);
381 if (cit != cache_.end())
384 PendingSnippets::const_iterator pit = pending_.begin();
385 PendingSnippets::const_iterator pend = pending_.end();
387 pit = find(pit, pend, latex_snippet);
391 InProgressProcesses::const_iterator ipit = in_progress_.begin();
392 InProgressProcesses::const_iterator ipend = in_progress_.end();
394 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
402 void PreviewLoader::Impl::add(string const & latex_snippet)
404 if (!pconverter_ || status(latex_snippet) != NotFound)
407 string const snippet = trim(latex_snippet);
411 lyxerr[Debug::GRAPHICS] << "adding snippet:\n" << snippet << endl;
413 pending_.push_back(snippet);
419 struct EraseSnippet {
420 EraseSnippet(string const & s) : snippet_(s) {}
421 void operator()(InProgressProcess & process)
423 BitmapFile & snippets = process.second.snippets;
424 BitmapFile::iterator it = snippets.begin();
425 BitmapFile::iterator end = snippets.end();
427 it = find_if(it, end, FindFirst(snippet_));
429 snippets.erase(it, it+1);
433 string const & snippet_;
439 void PreviewLoader::Impl::remove(string const & latex_snippet)
441 Cache::iterator cit = cache_.find(latex_snippet);
442 if (cit != cache_.end())
445 PendingSnippets::iterator pit = pending_.begin();
446 PendingSnippets::iterator pend = pending_.end();
448 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
450 InProgressProcesses::iterator ipit = in_progress_.begin();
451 InProgressProcesses::iterator ipend = in_progress_.end();
453 std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
455 for (; ipit != ipend; ++ipit) {
456 InProgressProcesses::iterator curr = ipit++;
457 if (curr->second.snippets.empty())
458 in_progress_.erase(curr);
463 void PreviewLoader::Impl::startLoading()
465 if (pending_.empty() || !pconverter_)
468 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()" << endl;
470 // As used by the LaTeX file and by the resulting image files
471 string const filename_base(unique_filename(buffer_.tmppath));
473 // Create an InProgress instance to place in the map of all
474 // such processes if it starts correctly.
475 InProgress inprogress(filename_base, pending_, pconverter_->to);
477 // clear pending_, so we're ready to start afresh.
480 // Output the LaTeX file.
481 string const latexfile = filename_base + ".tex";
483 ofstream of(latexfile.c_str());
484 of << "\\batchmode\n";
486 of << "\n\\begin{document}\n";
487 dumpData(of, inprogress.snippets);
488 of << "\n\\end{document}\n";
491 // The conversion command.
493 cs << pconverter_->command << " " << latexfile << " "
494 << int(font_scaling_factor_);
496 string const command = LibScriptSearch(cs.str().c_str());
498 // Initiate the conversion from LaTeX to bitmap images files.
499 Forkedcall::SignalTypePtr convert_ptr;
500 convert_ptr.reset(new Forkedcall::SignalType);
502 convert_ptr->connect(
503 boost::bind(&Impl::finishedGenerating, this, _1, _2, _3));
506 int ret = call.startscript(command, convert_ptr);
509 lyxerr[Debug::GRAPHICS] << "PreviewLoader::startLoading()\n"
510 << "Unable to start process \n"
515 // Store the generation process in a list of all such processes
516 inprogress.pid = call.pid();
517 in_progress_[command] = inprogress;
521 void PreviewLoader::Impl::finishedGenerating(string const & command,
522 pid_t /* pid */, int retval)
524 string const status = retval > 0 ? "failed" : "succeeded";
525 lyxerr[Debug::GRAPHICS] << "PreviewLoader::finishedInProgress("
526 << retval << "): processing " << status
527 << " for " << command << endl;
532 InProgressProcesses::iterator git = in_progress_.find(command);
533 if (git == in_progress_.end()) {
534 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
536 << command << "!" << endl;
540 // Read the metrics file, if it exists
541 vector<double> ascent_fractions(git->second.snippets.size());
542 setAscentFractions(ascent_fractions, git->second.metrics_file);
544 // Add these newly generated bitmap files to the cache and
545 // start loading them into LyX.
546 BitmapFile::const_iterator it = git->second.snippets.begin();
547 BitmapFile::const_iterator end = git->second.snippets.end();
549 std::list<PreviewImagePtr> newimages;
551 int metrics_counter = 0;
552 for (; it != end; ++it, ++metrics_counter) {
553 string const & snip = it->first;
554 string const & file = it->second;
555 double af = ascent_fractions[metrics_counter];
557 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
560 newimages.push_back(ptr);
563 // Remove the item from the list of still-executing processes.
564 in_progress_.erase(git);
566 // Tell the outside world
567 std::list<PreviewImagePtr>::const_iterator nit = newimages.begin();
568 std::list<PreviewImagePtr>::const_iterator nend = newimages.end();
569 for (; nit != nend; ++nit) {
570 imageReady(*nit->get());
575 void PreviewLoader::Impl::dumpPreamble(ostream & os) const
577 // Why on earth is Buffer::makeLaTeXFile a non-const method?
578 Buffer & tmp = const_cast<Buffer &>(buffer_);
579 // Dump the preamble only.
580 tmp.makeLaTeXFile(os, string(), true, false, true);
582 // Loop over the insets in the buffer and dump all the math-macros.
583 Buffer::inset_iterator it = buffer_.inset_const_iterator_begin();
584 Buffer::inset_iterator end = buffer_.inset_const_iterator_end();
586 for (; it != end; ++it) {
587 if ((*it)->lyxCode() == Inset::MATHMACRO_CODE) {
588 (*it)->latex(&buffer_, os, true, true);
592 // All equation lables appear as "(#)" + preview.sty's rendering of
594 if (lyxrc.preview_hashed_labels)
595 os << "\\renewcommand{\\theequation}{\\#}\n";
597 // Use the preview style file to ensure that each snippet appears on a
600 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
603 // This piece of PostScript magic ensures that the foreground and
604 // background colors are the same as the LyX screen.
605 string fg = lyx_gui::hexname(LColor::preview);
606 if (fg.empty()) fg = "000000";
608 string bg = lyx_gui::hexname(LColor::background);
609 if (bg.empty()) bg = "ffffff";
611 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
612 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
613 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
614 << "clippath fill setrgbcolor}bind def end}}}\n";
618 void PreviewLoader::Impl::dumpData(ostream & os,
619 BitmapFile const & vec) const
624 BitmapFile::const_iterator it = vec.begin();
625 BitmapFile::const_iterator end = vec.end();
627 for (; it != end; ++it) {
628 os << "\\begin{preview}\n"
630 << "\n\\end{preview}\n\n";
639 string const unique_filename(string const bufferpath)
641 static int theCounter = 0;
642 string const filename = tostr(theCounter++) + "lyxpreview";
643 return AddName(bufferpath, filename);
647 Converter const * setConverter()
649 string const from = "lyxpreview";
651 Formats::FormatList::const_iterator it = formats.begin();
652 Formats::FormatList::const_iterator end = formats.end();
654 for (; it != end; ++it) {
655 string const to = it->name();
659 Converter const * ptr = converters.getConverter(from, to);
664 static bool first = true;
667 lyxerr << "PreviewLoader::startLoading()\n"
668 << "No converter from \"lyxpreview\" format has been "
677 #if !USING_NEW_PREVIEW_STY
678 double setFontScalingFactor(Buffer & buffer)
680 double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
681 lyxrc.preview_scale_factor;
683 // Has the font size been set explicitly?
684 string const & fontsize = buffer.params.fontsize;
685 lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
686 << "font size is " << fontsize << endl;
688 if (isStrUnsignedInt(fontsize))
689 return 10.0 * scale_factor / strToDbl(fontsize);
691 // No. We must extract it from the LaTeX class file.
692 LyXTextClass const & tclass = buffer.params.getLyXTextClass();
693 string const textclass(tclass.latexname() + ".cls");
694 string const classfile(findtexfile(textclass, "cls"));
696 lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
697 << "class file is " << classfile << endl;
699 ifstream ifs(classfile.c_str());
701 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
706 double scaling = scale_factor;
710 // To get the default font size, look for a line like
711 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
712 if (!prefixIs(ltrim(str), "\\ExecuteOptions"))
715 // str contains just the options of \ExecuteOptions
716 string const tmp = split(str, '{');
717 split(tmp, str, '}');
720 string tok = token(str, ',', count++);
721 while (!isValidLength(tok) && !tok.empty())
722 tok = token(str, ',', count++);
725 lyxerr[Debug::GRAPHICS]
726 << "Extracted default font size from "
727 "LaTeX class file successfully!" << endl;
728 LyXLength fsize(tok);
729 scaling *= 10.0 / fsize.value();
739 void setAscentFractions(vector<double> & ascent_fractions,
740 string const & metrics_file)
742 // If all else fails, then the images will have equal ascents and
744 vector<double>::iterator it = ascent_fractions.begin();
745 vector<double>::iterator end = ascent_fractions.end();
748 ifstream in(metrics_file.c_str());
750 lyxerr[Debug::GRAPHICS]
751 << "setAscentFractions(" << metrics_file << ")\n"
752 << "Unable to open file!" << endl;
758 #if USING_NEW_PREVIEW_STY
759 // Tightpage dimensions affect all subsequent dimensions
763 int snippet_counter = 0;
765 // Expecting lines of the form
766 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
767 // Preview: Snippet id ascent descent width
770 in >> preview >> type;
776 error = preview != "Preview:"
777 || (type != "Tightpage" && type != "Snippet");
781 if (type == "Tightpage") {
783 in >> dummy >> tp_descent >> dummy >> tp_ascent;
794 in >> snippet_id >> ascent >> descent >> dummy;
796 error = !in.good() || ++snippet_counter != snippet_id;
800 double const a = ascent + tp_ascent;
801 double const d = descent - tp_descent;
803 if (!lyx::float_equal(a + d, 0, 0.1))
812 int snippet_counter = 0;
813 for (; it != end; ++it) {
814 // Extracting lines of the form
815 // %%Page id: tp_bl_x tp_bl_y tp_tr_x tp_tr_y asc desc width
823 in >> page >> page_id
824 >> dummy >> tp_descent >> dummy >> tp_ascent
825 >> ascent >> descent >> dummy;
827 page_id = rtrim(page_id, ":");
830 || !isStrUnsignedInt(page_id);
834 int const snippet_id = strToInt(page_id);
835 error = page != "%%Page"
836 || ++snippet_counter != snippet_id;
840 double const a = ascent + tp_ascent;
841 double const d = descent - tp_descent;
843 if (!lyx::float_equal(a + d, 0, 0.1))
849 lyxerr[Debug::GRAPHICS]
850 << "setAscentFractions(" << metrics_file << ")\n"
851 << "Error reading file!\n" << endl;