2 * \file PreviewLoader.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
8 * Full author contact details are available in file CREDITS.
13 #include "PreviewLoader.h"
14 #include "PreviewImage.h"
15 #include "GraphicsCache.h"
18 #include "BufferParams.h"
19 #include "Converter.h"
22 #include "InsetIterator.h"
23 #include "LaTeXFeatures.h"
26 #include "OutputParams.h"
29 #include "frontends/Application.h" // hexName
31 #include "insets/Inset.h"
33 #include "support/convert.h"
34 #include "support/debug.h"
35 #include "support/FileName.h"
36 #include "support/filetools.h"
37 #include "support/ForkedCalls.h"
38 #include "support/lstrings.h"
40 #include <boost/bind.hpp>
47 using namespace lyx::support;
53 typedef pair<string, FileName> SnippetPair;
55 // A list of all snippets to be converted to previews
56 typedef list<string> PendingSnippets;
58 // Each item in the vector is a pair<snippet, image file name>.
59 typedef vector<SnippetPair> BitmapFile;
62 string const unique_filename(string const & bufferpath)
64 static int theCounter = 0;
65 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
66 return addName(bufferpath, filename);
70 lyx::Converter const * setConverter(string const from)
72 typedef vector<string> FmtList;
73 typedef lyx::graphics::Cache GCache;
74 FmtList const & loadableFormats = GCache::get().loadableFormats();
75 FmtList::const_iterator it = loadableFormats.begin();
76 FmtList::const_iterator const end = loadableFormats.end();
78 for (; it != end; ++it) {
79 string const to = *it;
83 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
88 static bool first = true;
91 LYXERR0("PreviewLoader::startLoading()\n"
92 << "No converter from \"lyxpreview\" format has been defined.");
98 void setAscentFractions(vector<double> & ascent_fractions,
99 FileName const & metrics_file)
101 // If all else fails, then the images will have equal ascents and
103 vector<double>::iterator it = ascent_fractions.begin();
104 vector<double>::iterator end = ascent_fractions.end();
107 ifstream in(metrics_file.toFilesystemEncoding().c_str());
109 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
110 << "Unable to open file!");
116 int snippet_counter = 1;
117 while (!in.eof() && it != end) {
120 double ascent_fraction;
122 in >> snippet >> id >> ascent_fraction;
128 error = snippet != "Snippet";
132 error = id != snippet_counter;
136 *it = ascent_fraction;
143 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
144 << "Error reading file!\n");
152 FindFirst(string const & comp) : comp_(comp) {}
153 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
159 /// Store info on a currently executing, forked process.
163 InProgress() : pid(0) {}
165 InProgress(string const & filename_base,
166 PendingSnippets const & pending,
167 string const & to_format);
168 /// Remove any files left lying around and kill the forked process.
176 FileName metrics_file;
181 typedef map<pid_t, InProgress> InProgressProcesses;
183 typedef InProgressProcesses::value_type InProgressProcess;
192 class PreviewLoader::Impl : public boost::signals::trackable {
195 Impl(PreviewLoader & p, Buffer const & b);
196 /// Stop any InProgress items still executing.
199 PreviewImage const * preview(string const & latex_snippet) const;
201 PreviewLoader::Status status(string const & latex_snippet) const;
203 void add(string const & latex_snippet);
205 void remove(string const & latex_snippet);
209 /// Emit this signal when an image is ready for display.
210 boost::signal<void(PreviewImage const &)> imageReady;
212 Buffer const & buffer() const { return buffer_; }
215 /// Called by the ForkedCall process that generated the bitmap files.
216 void finishedGenerating(pid_t, int);
218 void dumpPreamble(odocstream &) const;
220 void dumpData(odocstream &, BitmapFile const &) const;
222 /** cache_ allows easy retrieval of already-generated images
223 * using the LaTeX snippet as the identifier.
225 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
227 typedef map<string, PreviewImagePtr> Cache;
231 /** pending_ stores the LaTeX snippets in anticipation of them being
232 * sent to the converter.
234 PendingSnippets pending_;
236 /** in_progress_ stores all forked processes so that we can proceed
238 The map uses the conversion commands as its identifiers.
240 InProgressProcesses in_progress_;
243 PreviewLoader & parent_;
245 Buffer const & buffer_;
247 double font_scaling_factor_;
249 /// We don't own this
250 static lyx::Converter const * pconverter_;
254 lyx::Converter const * PreviewLoader::Impl::pconverter_;
258 // The public interface, defined in PreviewLoader.h
261 PreviewLoader::PreviewLoader(Buffer const & b)
262 : pimpl_(new Impl(*this, b))
266 PreviewLoader::~PreviewLoader()
272 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
274 return pimpl_->preview(latex_snippet);
278 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
280 return pimpl_->status(latex_snippet);
284 void PreviewLoader::add(string const & latex_snippet) const
286 pimpl_->add(latex_snippet);
290 void PreviewLoader::remove(string const & latex_snippet) const
292 pimpl_->remove(latex_snippet);
296 void PreviewLoader::startLoading() const
298 pimpl_->startLoading();
302 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
304 return pimpl_->imageReady.connect(slot);
308 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
310 pimpl_->imageReady(pimage);
314 Buffer const & PreviewLoader::buffer() const
316 return pimpl_->buffer();
319 } // namespace graphics
323 // The details of the Impl
324 // =======================
328 class IncrementedFileName {
330 IncrementedFileName(string const & to_format,
331 string const & filename_base)
332 : to_format_(to_format), base_(filename_base), counter_(1)
335 SnippetPair const operator()(string const & snippet)
338 os << base_ << counter_++ << '.' << to_format_;
339 string const file = os.str();
341 return make_pair(snippet, FileName(file));
345 string const & to_format_;
346 string const & base_;
351 InProgress::InProgress(string const & filename_base,
352 PendingSnippets const & pending,
353 string const & to_format)
355 metrics_file(filename_base + ".metrics"),
356 snippets(pending.size())
358 PendingSnippets::const_iterator pit = pending.begin();
359 PendingSnippets::const_iterator pend = pending.end();
360 BitmapFile::iterator sit = snippets.begin();
362 transform(pit, pend, sit,
363 IncrementedFileName(to_format, filename_base));
367 void InProgress::stop() const
370 ForkedCallsController::kill(pid, 0);
372 if (!metrics_file.empty())
373 metrics_file.removeFile();
375 BitmapFile::const_iterator vit = snippets.begin();
376 BitmapFile::const_iterator vend = snippets.end();
377 for (; vit != vend; ++vit) {
378 if (!vit->second.empty())
379 vit->second.removeFile();
389 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
390 : parent_(p), buffer_(b), font_scaling_factor_(0.0)
392 font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
393 convert<double>(lyxrc.preview_scale_factor);
395 LYXERR(Debug::GRAPHICS, "The font scaling factor is "
396 << font_scaling_factor_);
399 if (b.params().encoding().package() == Encoding::japanese)
400 pconverter_ = setConverter("lyxpreview-platex");
402 pconverter_ = setConverter("lyxpreview");
407 PreviewLoader::Impl::~Impl()
409 InProgressProcesses::iterator ipit = in_progress_.begin();
410 InProgressProcesses::iterator ipend = in_progress_.end();
412 for (; ipit != ipend; ++ipit)
418 PreviewLoader::Impl::preview(string const & latex_snippet) const
420 Cache::const_iterator it = cache_.find(latex_snippet);
421 return (it == cache_.end()) ? 0 : it->second.get();
429 FindSnippet(string const & s) : snippet_(s) {}
430 bool operator()(InProgressProcess const & process) const
432 BitmapFile const & snippets = process.second.snippets;
433 BitmapFile::const_iterator beg = snippets.begin();
434 BitmapFile::const_iterator end = snippets.end();
435 return find_if(beg, end, FindFirst(snippet_)) != end;
439 string const snippet_;
444 PreviewLoader::Status
445 PreviewLoader::Impl::status(string const & latex_snippet) const
447 Cache::const_iterator cit = cache_.find(latex_snippet);
448 if (cit != cache_.end())
451 PendingSnippets::const_iterator pit = pending_.begin();
452 PendingSnippets::const_iterator pend = pending_.end();
454 pit = find(pit, pend, latex_snippet);
458 InProgressProcesses::const_iterator ipit = in_progress_.begin();
459 InProgressProcesses::const_iterator ipend = in_progress_.end();
461 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
469 void PreviewLoader::Impl::add(string const & latex_snippet)
471 if (!pconverter_ || status(latex_snippet) != NotFound)
474 string const snippet = trim(latex_snippet);
478 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
480 pending_.push_back(snippet);
488 EraseSnippet(string const & s) : snippet_(s) {}
489 void operator()(InProgressProcess & process)
491 BitmapFile & snippets = process.second.snippets;
492 BitmapFile::iterator it = snippets.begin();
493 BitmapFile::iterator end = snippets.end();
495 it = find_if(it, end, FindFirst(snippet_));
497 snippets.erase(it, it+1);
501 string const & snippet_;
507 void PreviewLoader::Impl::remove(string const & latex_snippet)
509 Cache::iterator cit = cache_.find(latex_snippet);
510 if (cit != cache_.end())
513 PendingSnippets::iterator pit = pending_.begin();
514 PendingSnippets::iterator pend = pending_.end();
516 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
518 InProgressProcesses::iterator ipit = in_progress_.begin();
519 InProgressProcesses::iterator ipend = in_progress_.end();
521 for_each(ipit, ipend, EraseSnippet(latex_snippet));
523 while (ipit != ipend) {
524 InProgressProcesses::iterator curr = ipit++;
525 if (curr->second.snippets.empty())
526 in_progress_.erase(curr);
531 void PreviewLoader::Impl::startLoading()
533 if (pending_.empty() || !pconverter_)
536 // Only start the process off after the buffer is loaded from file.
537 if (!buffer_.isFullyLoaded())
540 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
542 // As used by the LaTeX file and by the resulting image files
543 string const directory = buffer_.temppath();
545 string const filename_base = unique_filename(directory);
547 // Create an InProgress instance to place in the map of all
548 // such processes if it starts correctly.
549 InProgress inprogress(filename_base, pending_, pconverter_->to);
551 // clear pending_, so we're ready to start afresh.
554 // Output the LaTeX file.
555 FileName const latexfile(filename_base + ".tex");
557 // we use the encoding of the buffer
558 Encoding const & enc = buffer_.params().encoding();
560 try { of.reset(enc.iconvName()); }
561 catch (iconv_codecvt_facet_exception & e) {
562 LYXERR0("Caught iconv exception: " << e.what()
563 << "\nUnable to create LaTeX file: " << latexfile);
568 OutputParams runparams(&enc);
569 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
571 if (!openFileWrite(of, latexfile))
575 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
576 << "Unable to create LaTeX file\n" << latexfile);
579 of << "\\batchmode\n";
581 // handle inputenc etc.
582 buffer_.params().writeEncodingPreamble(of, features, texrow);
583 of << "\n\\begin{document}\n";
584 dumpData(of, inprogress.snippets);
585 of << "\n\\end{document}\n";
588 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
589 << "File was not closed properly.");
593 // The conversion command.
595 cs << pconverter_->command << ' ' << pconverter_->to << ' '
596 << quoteName(latexfile.toFilesystemEncoding()) << ' '
597 << int(font_scaling_factor_) << ' '
598 << theApp()->hexName(Color_preview) << ' '
599 << theApp()->hexName(Color_background);
601 string const command = libScriptSearch(cs.str());
603 // Initiate the conversion from LaTeX to bitmap images files.
604 ForkedCall::SignalTypePtr
605 convert_ptr(new ForkedCall::SignalType);
606 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
609 int ret = call.startScript(command, convert_ptr);
612 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
613 << "Unable to start process\n" << command);
617 // Store the generation process in a list of all such processes
618 inprogress.pid = call.pid();
619 inprogress.command = command;
620 in_progress_[inprogress.pid] = inprogress;
624 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
627 InProgressProcesses::iterator git = in_progress_.find(pid);
628 if (git == in_progress_.end()) {
629 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
630 "data for PID " << pid << endl;
634 string const command = git->second.command;
635 string const status = retval > 0 ? "failed" : "succeeded";
636 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
637 << retval << "): processing " << status
638 << " for " << command);
642 // Read the metrics file, if it exists
643 vector<double> ascent_fractions(git->second.snippets.size());
644 setAscentFractions(ascent_fractions, git->second.metrics_file);
646 // Add these newly generated bitmap files to the cache and
647 // start loading them into LyX.
648 BitmapFile::const_iterator it = git->second.snippets.begin();
649 BitmapFile::const_iterator end = git->second.snippets.end();
651 list<PreviewImagePtr> newimages;
653 int metrics_counter = 0;
654 for (; it != end; ++it, ++metrics_counter) {
655 string const & snip = it->first;
656 FileName const & file = it->second;
657 double af = ascent_fractions[metrics_counter];
659 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
662 newimages.push_back(ptr);
665 // Remove the item from the list of still-executing processes.
666 in_progress_.erase(git);
668 // Tell the outside world
669 list<PreviewImagePtr>::const_reverse_iterator
670 nit = newimages.rbegin();
671 list<PreviewImagePtr>::const_reverse_iterator
672 nend = newimages.rend();
673 for (; nit != nend; ++nit) {
674 imageReady(*nit->get());
679 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
681 // Why on earth is Buffer::makeLaTeXFile a non-const method?
682 Buffer & tmp = const_cast<Buffer &>(buffer_);
683 // Dump the preamble only.
684 // We don't need an encoding for runparams since it is not used by
686 OutputParams runparams(0);
687 runparams.flavor = OutputParams::LATEX;
688 runparams.nice = true;
689 runparams.moving_arg = true;
690 runparams.free_spacing = true;
691 tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
693 // FIXME! This is a HACK! The proper fix is to control the 'true'
694 // passed to WriteStream below:
695 // int InsetMathNest::latex(Buffer const &, odocstream & os,
696 // OutputParams const & runparams) const
698 // WriteStream wi(os, runparams.moving_arg, true);
703 << "\\def\\lyxlock{}\n"
706 // Loop over the insets in the buffer and dump all the math-macros.
707 Inset & inset = buffer_.inset();
708 InsetIterator it = inset_iterator_begin(inset);
709 InsetIterator const end = inset_iterator_end(inset);
711 for (; it != end; ++it)
712 if (it->lyxCode() == MATHMACRO_CODE)
713 it->latex(os, runparams);
715 // All equation labels appear as "(#)" + preview.sty's rendering of
717 if (lyxrc.preview_hashed_labels)
718 os << "\\renewcommand{\\theequation}{\\#}\n";
720 // Use the preview style file to ensure that each snippet appears on a
722 // Also support PDF output (automatically generated e.g. when
723 // \usepackage[pdftex]{hyperref} is used.
725 << "\\newif\\ifpdf\n"
726 << "\\ifx\\pdfoutput\\undefined\n"
727 << "\\else\\ifx\\pdfoutput\\relax\n"
728 << "\\else\\ifnum0=\\pdfoutput\n"
729 << "\\else\\pdftrue\\fi\\fi\\fi\n"
731 << " \\usepackage[active,delayed,tightpage,showlabels,lyx,pdftex]{preview}\n"
733 << " \\usepackage[active,delayed,showlabels,lyx,dvips]{preview}\n"
739 void PreviewLoader::Impl::dumpData(odocstream & os,
740 BitmapFile const & vec) const
745 BitmapFile::const_iterator it = vec.begin();
746 BitmapFile::const_iterator end = vec.end();
748 for (; it != end; ++it) {
750 os << "\\begin{preview}\n"
751 << from_utf8(it->first)
752 << "\n\\end{preview}\n\n";
756 } // namespace graphics