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, buffer_.filePath(), 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);
590 // All equation lables appear as "(#)" + preview.sty's rendering of
592 if (lyxrc.preview_hashed_labels)
593 os << "\\renewcommand{\\theequation}{\\#}\n";
595 // Use the preview style file to ensure that each snippet appears on a
598 << "\\usepackage[active,delayed,dvips,tightpage,showlabels,lyx]{preview}\n"
601 // This piece of PostScript magic ensures that the foreground and
602 // background colors are the same as the LyX screen.
603 string fg = lyx_gui::hexname(LColor::preview);
604 if (fg.empty()) fg = "000000";
606 string bg = lyx_gui::hexname(LColor::background);
607 if (bg.empty()) bg = "ffffff";
609 os << "\\AtBeginDocument{\\AtBeginDvi{%\n"
610 << "\\special{!userdict begin/bop-hook{//bop-hook exec\n"
611 << "<" << fg << bg << ">{255 div}forall setrgbcolor\n"
612 << "clippath fill setrgbcolor}bind def end}}}\n";
616 void PreviewLoader::Impl::dumpData(ostream & os,
617 BitmapFile const & vec) const
622 BitmapFile::const_iterator it = vec.begin();
623 BitmapFile::const_iterator end = vec.end();
625 for (; it != end; ++it) {
626 os << "\\begin{preview}\n"
628 << "\n\\end{preview}\n\n";
637 string const unique_filename(string const bufferpath)
639 static int theCounter = 0;
640 string const filename = tostr(theCounter++) + "lyxpreview";
641 return AddName(bufferpath, filename);
645 Converter const * setConverter()
647 string const from = "lyxpreview";
649 Formats::FormatList::const_iterator it = formats.begin();
650 Formats::FormatList::const_iterator end = formats.end();
652 for (; it != end; ++it) {
653 string const to = it->name();
657 Converter const * ptr = converters.getConverter(from, to);
662 static bool first = true;
665 lyxerr << "PreviewLoader::startLoading()\n"
666 << "No converter from \"lyxpreview\" format has been "
675 #if !USING_NEW_PREVIEW_STY
676 double setFontScalingFactor(Buffer & buffer)
678 double scale_factor = 0.01 * lyxrc.dpi * lyxrc.zoom *
679 lyxrc.preview_scale_factor;
681 // Has the font size been set explicitly?
682 string const & fontsize = buffer.params.fontsize;
683 lyxerr[Debug::GRAPHICS] << "PreviewLoader::scaleToFitLyXView()\n"
684 << "font size is " << fontsize << endl;
686 if (isStrUnsignedInt(fontsize))
687 return 10.0 * scale_factor / strToDbl(fontsize);
689 // No. We must extract it from the LaTeX class file.
690 LyXTextClass const & tclass = buffer.params.getLyXTextClass();
691 string const textclass(tclass.latexname() + ".cls");
692 string const classfile(findtexfile(textclass, "cls"));
694 lyxerr[Debug::GRAPHICS] << "text class is " << textclass << '\n'
695 << "class file is " << classfile << endl;
697 ifstream ifs(classfile.c_str());
699 lyxerr[Debug::GRAPHICS] << "Unable to open class file!" << endl;
704 double scaling = scale_factor;
708 // To get the default font size, look for a line like
709 // "\ExecuteOptions{letterpaper,10pt,oneside,onecolumn,final}"
710 if (!prefixIs(ltrim(str), "\\ExecuteOptions"))
713 // str contains just the options of \ExecuteOptions
714 string const tmp = split(str, '{');
715 split(tmp, str, '}');
718 string tok = token(str, ',', count++);
719 while (!isValidLength(tok) && !tok.empty())
720 tok = token(str, ',', count++);
723 lyxerr[Debug::GRAPHICS]
724 << "Extracted default font size from "
725 "LaTeX class file successfully!" << endl;
726 LyXLength fsize(tok);
727 scaling *= 10.0 / fsize.value();
737 void setAscentFractions(vector<double> & ascent_fractions,
738 string const & metrics_file)
740 // If all else fails, then the images will have equal ascents and
742 vector<double>::iterator it = ascent_fractions.begin();
743 vector<double>::iterator end = ascent_fractions.end();
746 ifstream in(metrics_file.c_str());
748 lyxerr[Debug::GRAPHICS]
749 << "setAscentFractions(" << metrics_file << ")\n"
750 << "Unable to open file!" << endl;
756 #if USING_NEW_PREVIEW_STY
757 // Tightpage dimensions affect all subsequent dimensions
761 int snippet_counter = 0;
763 // Expecting lines of the form
764 // Preview: Tightpage tp_bl_x tp_bl_y tp_tr_x tp_tr_y
765 // Preview: Snippet id ascent descent width
768 in >> preview >> type;
774 error = preview != "Preview:"
775 || (type != "Tightpage" && type != "Snippet");
779 if (type == "Tightpage") {
781 in >> dummy >> tp_descent >> dummy >> tp_ascent;
792 in >> snippet_id >> ascent >> descent >> dummy;
794 error = !in.good() || ++snippet_counter != snippet_id;
798 double const a = ascent + tp_ascent;
799 double const d = descent - tp_descent;
801 if (!lyx::float_equal(a + d, 0, 0.1))
810 int snippet_counter = 0;
811 for (; it != end; ++it) {
812 // Extracting lines of the form
813 // %%Page id: tp_bl_x tp_bl_y tp_tr_x tp_tr_y asc desc width
821 in >> page >> page_id
822 >> dummy >> tp_descent >> dummy >> tp_ascent
823 >> ascent >> descent >> dummy;
825 page_id = rtrim(page_id, ":");
828 || !isStrUnsignedInt(page_id);
832 int const snippet_id = strToInt(page_id);
833 error = page != "%%Page"
834 || ++snippet_counter != snippet_id;
838 double const a = ascent + tp_ascent;
839 double const d = descent - tp_descent;
841 if (!lyx::float_equal(a + d, 0, 0.1))
847 lyxerr[Debug::GRAPHICS]
848 << "setAscentFractions(" << metrics_file << ")\n"
849 << "Error reading file!\n" << endl;