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"
27 #include "PDFOptions.h"
30 #include "frontends/Application.h" // hexName
32 #include "insets/Inset.h"
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/FileName.h"
37 #include "support/filetools.h"
38 #include "support/ForkedCalls.h"
39 #include "support/lstrings.h"
41 #include "support/bind.h"
48 using namespace lyx::support;
54 typedef pair<string, FileName> SnippetPair;
56 // A list of all snippets to be converted to previews
57 typedef list<string> PendingSnippets;
59 // Each item in the vector is a pair<snippet, image file name>.
60 typedef vector<SnippetPair> BitmapFile;
63 string const unique_filename(string const & bufferpath)
65 static int theCounter = 0;
66 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
67 return addName(bufferpath, filename);
71 lyx::Converter const * setConverter(string const from)
73 typedef vector<string> FmtList;
74 typedef lyx::graphics::Cache GCache;
75 FmtList const & loadableFormats = GCache::get().loadableFormats();
76 FmtList::const_iterator it = loadableFormats.begin();
77 FmtList::const_iterator const end = loadableFormats.end();
79 for (; it != end; ++it) {
80 string const to = *it;
84 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
89 static bool first = true;
92 LYXERR0("PreviewLoader::startLoading()\n"
93 << "No converter from \"" << from << "\" format has been defined.");
99 void setAscentFractions(vector<double> & ascent_fractions,
100 FileName const & metrics_file)
102 // If all else fails, then the images will have equal ascents and
104 vector<double>::iterator it = ascent_fractions.begin();
105 vector<double>::iterator end = ascent_fractions.end();
108 ifstream in(metrics_file.toFilesystemEncoding().c_str());
110 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
111 << "Unable to open file!");
117 int snippet_counter = 1;
118 while (!in.eof() && it != end) {
121 double ascent_fraction;
123 in >> snippet >> id >> ascent_fraction;
129 error = snippet != "Snippet";
133 error = id != snippet_counter;
137 *it = ascent_fraction;
144 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
145 << "Error reading file!\n");
153 FindFirst(string const & comp) : comp_(comp) {}
154 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
160 /// Store info on a currently executing, forked process.
164 InProgress() : pid(0) {}
166 InProgress(string const & filename_base,
167 PendingSnippets const & pending,
168 string const & to_format);
169 /// Remove any files left lying around and kill the forked process.
177 FileName metrics_file;
182 typedef map<pid_t, InProgress> InProgressProcesses;
184 typedef InProgressProcesses::value_type InProgressProcess;
193 class PreviewLoader::Impl : public boost::signals::trackable {
196 Impl(PreviewLoader & p, Buffer const & b);
197 /// Stop any InProgress items still executing.
200 PreviewImage const * preview(string const & latex_snippet) const;
202 PreviewLoader::Status status(string const & latex_snippet) const;
204 void add(string const & latex_snippet);
206 void remove(string const & latex_snippet);
207 /// \p wait whether to wait for the process to complete or, instead,
208 /// to do it in the background.
209 void startLoading(bool wait = false);
211 /// Emit this signal when an image is ready for display.
212 boost::signal<void(PreviewImage const &)> imageReady;
214 Buffer const & buffer() const { return buffer_; }
217 /// Called by the ForkedCall process that generated the bitmap files.
218 void finishedGenerating(pid_t, int);
220 void dumpPreamble(otexstream &) const;
222 void dumpData(odocstream &, BitmapFile const &) const;
224 /** cache_ allows easy retrieval of already-generated images
225 * using the LaTeX snippet as the identifier.
227 typedef shared_ptr<PreviewImage> PreviewImagePtr;
229 typedef map<string, PreviewImagePtr> Cache;
233 /** pending_ stores the LaTeX snippets in anticipation of them being
234 * sent to the converter.
236 PendingSnippets pending_;
238 /** in_progress_ stores all forked processes so that we can proceed
240 The map uses the conversion commands as its identifiers.
242 InProgressProcesses in_progress_;
245 PreviewLoader & parent_;
247 Buffer const & buffer_;
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(bool wait) const
298 pimpl_->startLoading(wait);
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)
392 if (b.bufferFormat() == "lilypond-book")
393 pconverter_ = setConverter("lyxpreview-lytex");
394 else if (b.params().encoding().package() == Encoding::japanese)
395 pconverter_ = setConverter("lyxpreview-platex");
397 pconverter_ = setConverter("lyxpreview");
401 PreviewLoader::Impl::~Impl()
403 InProgressProcesses::iterator ipit = in_progress_.begin();
404 InProgressProcesses::iterator ipend = in_progress_.end();
406 for (; ipit != ipend; ++ipit)
412 PreviewLoader::Impl::preview(string const & latex_snippet) const
414 Cache::const_iterator it = cache_.find(latex_snippet);
415 return (it == cache_.end()) ? 0 : it->second.get();
423 FindSnippet(string const & s) : snippet_(s) {}
424 bool operator()(InProgressProcess const & process) const
426 BitmapFile const & snippets = process.second.snippets;
427 BitmapFile::const_iterator beg = snippets.begin();
428 BitmapFile::const_iterator end = snippets.end();
429 return find_if(beg, end, FindFirst(snippet_)) != end;
433 string const snippet_;
438 PreviewLoader::Status
439 PreviewLoader::Impl::status(string const & latex_snippet) const
441 Cache::const_iterator cit = cache_.find(latex_snippet);
442 if (cit != cache_.end())
445 PendingSnippets::const_iterator pit = pending_.begin();
446 PendingSnippets::const_iterator pend = pending_.end();
448 pit = find(pit, pend, latex_snippet);
452 InProgressProcesses::const_iterator ipit = in_progress_.begin();
453 InProgressProcesses::const_iterator ipend = in_progress_.end();
455 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
463 void PreviewLoader::Impl::add(string const & latex_snippet)
465 if (!pconverter_ || status(latex_snippet) != NotFound)
468 string const snippet = trim(latex_snippet);
472 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
474 pending_.push_back(snippet);
482 EraseSnippet(string const & s) : snippet_(s) {}
483 void operator()(InProgressProcess & process)
485 BitmapFile & snippets = process.second.snippets;
486 BitmapFile::iterator it = snippets.begin();
487 BitmapFile::iterator end = snippets.end();
489 it = find_if(it, end, FindFirst(snippet_));
491 snippets.erase(it, it+1);
495 string const & snippet_;
501 void PreviewLoader::Impl::remove(string const & latex_snippet)
503 Cache::iterator cit = cache_.find(latex_snippet);
504 if (cit != cache_.end())
507 PendingSnippets::iterator pit = pending_.begin();
508 PendingSnippets::iterator pend = pending_.end();
510 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
512 InProgressProcesses::iterator ipit = in_progress_.begin();
513 InProgressProcesses::iterator ipend = in_progress_.end();
515 for_each(ipit, ipend, EraseSnippet(latex_snippet));
517 while (ipit != ipend) {
518 InProgressProcesses::iterator curr = ipit++;
519 if (curr->second.snippets.empty())
520 in_progress_.erase(curr);
525 void PreviewLoader::Impl::startLoading(bool wait)
527 if (pending_.empty() || !pconverter_)
530 // Only start the process off after the buffer is loaded from file.
531 if (!buffer_.isFullyLoaded())
534 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
536 // As used by the LaTeX file and by the resulting image files
537 string const directory = buffer_.temppath();
539 string const filename_base = unique_filename(directory);
541 // Create an InProgress instance to place in the map of all
542 // such processes if it starts correctly.
543 InProgress inprogress(filename_base, pending_, pconverter_->to);
545 // clear pending_, so we're ready to start afresh.
548 // Output the LaTeX file.
549 FileName const latexfile(filename_base + ".tex");
551 // we use the encoding of the buffer
552 Encoding const & enc = buffer_.params().encoding();
554 try { of.reset(enc.iconvName()); }
555 catch (iconv_codecvt_facet_exception & e) {
556 LYXERR0("Caught iconv exception: " << e.what()
557 << "\nUnable to create LaTeX file: " << latexfile);
562 otexstream os(of, texrow);
563 OutputParams runparams(&enc);
564 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
566 if (!openFileWrite(of, latexfile))
570 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
571 << "Unable to create LaTeX file\n" << latexfile);
574 of << "\\batchmode\n";
576 // handle inputenc etc.
577 buffer_.params().writeEncodingPreamble(os, features);
578 of << "\n\\begin{document}\n";
579 dumpData(of, inprogress.snippets);
580 of << "\n\\end{document}\n";
583 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
584 << "File was not closed properly.");
588 double const font_scaling_factor =
589 buffer_.isExporting() ? 75.0 * buffer_.params().html_math_img_scale
590 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor;
593 // The colors should be customizable.
594 ColorCode const bg = buffer_.isExporting()
595 ? Color_white : PreviewLoader::backgroundColor();
596 ColorCode const fg = buffer_.isExporting()
597 ? Color_black : PreviewLoader::foregroundColor();
598 // The conversion command.
600 cs << pconverter_->command << ' ' << pconverter_->to << ' '
601 << quoteName(latexfile.toFilesystemEncoding()) << ' '
602 << int(font_scaling_factor) << ' '
603 << theApp()->hexName(fg) << ' '
604 << theApp()->hexName(bg);
605 // FIXME what about LuaTeX?
606 if (buffer_.bufferFormat() == "xetex")
608 // DVI output fails sometimes with hyperref
609 // (probably a preview-latex/hyperref bug)
610 else if (buffer_.params().pdfoptions().use_hyperref)
613 string const command = libScriptSearch(cs.str());
617 int ret = call.startScript(ForkedProcess::Wait, command);
618 static int fake = (2^20) + 1;
620 inprogress.pid = pid;
621 inprogress.command = command;
622 in_progress_[pid] = inprogress;
623 finishedGenerating(pid, ret);
627 // Initiate the conversion from LaTeX to bitmap images files.
628 ForkedCall::SignalTypePtr
629 convert_ptr(new ForkedCall::SignalType);
630 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
633 int ret = call.startScript(command, convert_ptr);
636 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
637 << "Unable to start process\n" << command);
641 // Store the generation process in a list of all such processes
642 inprogress.pid = call.pid();
643 inprogress.command = command;
644 in_progress_[inprogress.pid] = inprogress;
648 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
651 InProgressProcesses::iterator git = in_progress_.find(pid);
652 if (git == in_progress_.end()) {
653 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
654 "data for PID " << pid << endl;
658 string const command = git->second.command;
659 string const status = retval > 0 ? "failed" : "succeeded";
660 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
661 << retval << "): processing " << status
662 << " for " << command);
666 // Read the metrics file, if it exists
667 vector<double> ascent_fractions(git->second.snippets.size());
668 setAscentFractions(ascent_fractions, git->second.metrics_file);
670 // Add these newly generated bitmap files to the cache and
671 // start loading them into LyX.
672 BitmapFile::const_iterator it = git->second.snippets.begin();
673 BitmapFile::const_iterator end = git->second.snippets.end();
675 list<PreviewImagePtr> newimages;
677 int metrics_counter = 0;
678 for (; it != end; ++it, ++metrics_counter) {
679 string const & snip = it->first;
680 FileName const & file = it->second;
681 double af = ascent_fractions[metrics_counter];
683 // Add the image to the cache only if it's actually present
684 if (file.isReadableFile()) {
685 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
688 newimages.push_back(ptr);
693 // Remove the item from the list of still-executing processes.
694 in_progress_.erase(git);
696 // Tell the outside world
697 list<PreviewImagePtr>::const_reverse_iterator
698 nit = newimages.rbegin();
699 list<PreviewImagePtr>::const_reverse_iterator
700 nend = newimages.rend();
701 for (; nit != nend; ++nit) {
702 imageReady(*nit->get());
707 void PreviewLoader::Impl::dumpPreamble(otexstream & os) const
709 // Dump the preamble only.
710 OutputParams runparams(&buffer_.params().encoding());
711 runparams.flavor = OutputParams::LATEX;
712 runparams.nice = true;
713 runparams.moving_arg = true;
714 runparams.free_spacing = true;
715 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
717 // FIXME! This is a HACK! The proper fix is to control the 'true'
718 // passed to WriteStream below:
719 // int InsetMathNest::latex(Buffer const &, odocstream & os,
720 // OutputParams const & runparams) const
722 // WriteStream wi(os, runparams.moving_arg, true);
727 << "\\def\\lyxlock{}\n"
730 // All equation labels appear as "(#)" + preview.sty's rendering of
732 if (lyxrc.preview_hashed_labels)
733 os << "\\renewcommand{\\theequation}{\\#}\n";
735 // Use the preview style file to ensure that each snippet appears on a
737 // Also support PDF output (automatically generated e.g. when
738 // \usepackage[pdftex]{hyperref} is used and XeTeX.
740 << "\\newif\\ifxetex\n"
741 << "\\expandafter\\ifx\\csname XeTeXrevision\\endcsname\\relax\n"
746 << "\\newif\\ifpdf\n"
747 << "\\ifx\\pdfoutput\\undefined\n"
748 << "\\else\\ifx\\pdfoutput\\relax\n"
749 << "\\else\\ifnum0=\\pdfoutput\n"
750 << "\\else\\pdftrue\\fi\\fi\\fi\n"
752 << " \\usepackage[active,delayed,tightpage,showlabels,lyx,xetex]{preview}\n"
755 << " \\usepackage[active,delayed,tightpage,showlabels,lyx,pdftex]{preview}\n"
757 << " \\usepackage[active,delayed,showlabels,lyx,dvips]{preview}\n"
764 void PreviewLoader::Impl::dumpData(odocstream & os,
765 BitmapFile const & vec) const
770 BitmapFile::const_iterator it = vec.begin();
771 BitmapFile::const_iterator end = vec.end();
773 for (; it != end; ++it) {
775 os << "\\begin{preview}\n"
776 << from_utf8(it->first)
777 << "\n\\end{preview}\n\n";
781 } // namespace graphics