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 "support/bind.h"
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 \"" << from << "\" 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);
206 /// \p wait whether to wait for the process to complete or, instead,
207 /// to do it in the background.
208 void startLoading(bool wait = false);
210 /// Emit this signal when an image is ready for display.
211 boost::signal<void(PreviewImage const &)> imageReady;
213 Buffer const & buffer() const { return buffer_; }
216 /// Called by the ForkedCall process that generated the bitmap files.
217 void finishedGenerating(pid_t, int);
219 void dumpPreamble(otexstream &) const;
221 void dumpData(odocstream &, BitmapFile const &) const;
223 /** cache_ allows easy retrieval of already-generated images
224 * using the LaTeX snippet as the identifier.
226 typedef shared_ptr<PreviewImage> PreviewImagePtr;
228 typedef map<string, PreviewImagePtr> Cache;
232 /** pending_ stores the LaTeX snippets in anticipation of them being
233 * sent to the converter.
235 PendingSnippets pending_;
237 /** in_progress_ stores all forked processes so that we can proceed
239 The map uses the conversion commands as its identifiers.
241 InProgressProcesses in_progress_;
244 PreviewLoader & parent_;
246 Buffer const & buffer_;
248 /// We don't own this
249 static lyx::Converter const * pconverter_;
253 lyx::Converter const * PreviewLoader::Impl::pconverter_;
257 // The public interface, defined in PreviewLoader.h
260 PreviewLoader::PreviewLoader(Buffer const & b)
261 : pimpl_(new Impl(*this, b))
265 PreviewLoader::~PreviewLoader()
271 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
273 return pimpl_->preview(latex_snippet);
277 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
279 return pimpl_->status(latex_snippet);
283 void PreviewLoader::add(string const & latex_snippet) const
285 pimpl_->add(latex_snippet);
289 void PreviewLoader::remove(string const & latex_snippet) const
291 pimpl_->remove(latex_snippet);
295 void PreviewLoader::startLoading(bool wait) const
297 pimpl_->startLoading(wait);
301 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
303 return pimpl_->imageReady.connect(slot);
307 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
309 pimpl_->imageReady(pimage);
313 Buffer const & PreviewLoader::buffer() const
315 return pimpl_->buffer();
318 } // namespace graphics
322 // The details of the Impl
323 // =======================
327 class IncrementedFileName {
329 IncrementedFileName(string const & to_format,
330 string const & filename_base)
331 : to_format_(to_format), base_(filename_base), counter_(1)
334 SnippetPair const operator()(string const & snippet)
337 os << base_ << counter_++ << '.' << to_format_;
338 string const file = os.str();
340 return make_pair(snippet, FileName(file));
344 string const & to_format_;
345 string const & base_;
350 InProgress::InProgress(string const & filename_base,
351 PendingSnippets const & pending,
352 string const & to_format)
354 metrics_file(filename_base + ".metrics"),
355 snippets(pending.size())
357 PendingSnippets::const_iterator pit = pending.begin();
358 PendingSnippets::const_iterator pend = pending.end();
359 BitmapFile::iterator sit = snippets.begin();
361 transform(pit, pend, sit,
362 IncrementedFileName(to_format, filename_base));
366 void InProgress::stop() const
369 ForkedCallsController::kill(pid, 0);
371 if (!metrics_file.empty())
372 metrics_file.removeFile();
374 BitmapFile::const_iterator vit = snippets.begin();
375 BitmapFile::const_iterator vend = snippets.end();
376 for (; vit != vend; ++vit) {
377 if (!vit->second.empty())
378 vit->second.removeFile();
388 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
389 : parent_(p), buffer_(b)
392 pconverter_ = setConverter("lyxpreview");
396 PreviewLoader::Impl::~Impl()
398 InProgressProcesses::iterator ipit = in_progress_.begin();
399 InProgressProcesses::iterator ipend = in_progress_.end();
401 for (; ipit != ipend; ++ipit)
407 PreviewLoader::Impl::preview(string const & latex_snippet) const
409 Cache::const_iterator it = cache_.find(latex_snippet);
410 return (it == cache_.end()) ? 0 : it->second.get();
418 FindSnippet(string const & s) : snippet_(s) {}
419 bool operator()(InProgressProcess const & process) const
421 BitmapFile const & snippets = process.second.snippets;
422 BitmapFile::const_iterator beg = snippets.begin();
423 BitmapFile::const_iterator end = snippets.end();
424 return find_if(beg, end, FindFirst(snippet_)) != end;
428 string const snippet_;
433 PreviewLoader::Status
434 PreviewLoader::Impl::status(string const & latex_snippet) const
436 Cache::const_iterator cit = cache_.find(latex_snippet);
437 if (cit != cache_.end())
440 PendingSnippets::const_iterator pit = pending_.begin();
441 PendingSnippets::const_iterator pend = pending_.end();
443 pit = find(pit, pend, latex_snippet);
447 InProgressProcesses::const_iterator ipit = in_progress_.begin();
448 InProgressProcesses::const_iterator ipend = in_progress_.end();
450 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
458 void PreviewLoader::Impl::add(string const & latex_snippet)
460 if (!pconverter_ || status(latex_snippet) != NotFound)
463 string const snippet = trim(latex_snippet);
467 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
469 pending_.push_back(snippet);
477 EraseSnippet(string const & s) : snippet_(s) {}
478 void operator()(InProgressProcess & process)
480 BitmapFile & snippets = process.second.snippets;
481 BitmapFile::iterator it = snippets.begin();
482 BitmapFile::iterator end = snippets.end();
484 it = find_if(it, end, FindFirst(snippet_));
486 snippets.erase(it, it+1);
490 string const & snippet_;
496 void PreviewLoader::Impl::remove(string const & latex_snippet)
498 Cache::iterator cit = cache_.find(latex_snippet);
499 if (cit != cache_.end())
502 PendingSnippets::iterator pit = pending_.begin();
503 PendingSnippets::iterator pend = pending_.end();
505 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
507 InProgressProcesses::iterator ipit = in_progress_.begin();
508 InProgressProcesses::iterator ipend = in_progress_.end();
510 for_each(ipit, ipend, EraseSnippet(latex_snippet));
512 while (ipit != ipend) {
513 InProgressProcesses::iterator curr = ipit++;
514 if (curr->second.snippets.empty())
515 in_progress_.erase(curr);
520 void PreviewLoader::Impl::startLoading(bool wait)
522 if (pending_.empty() || !pconverter_)
525 // Only start the process off after the buffer is loaded from file.
526 if (!buffer_.isFullyLoaded())
529 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
531 // As used by the LaTeX file and by the resulting image files
532 string const directory = buffer_.temppath();
534 string const filename_base = unique_filename(directory);
536 // Create an InProgress instance to place in the map of all
537 // such processes if it starts correctly.
538 InProgress inprogress(filename_base, pending_, pconverter_->to);
540 // clear pending_, so we're ready to start afresh.
543 // Output the LaTeX file.
544 FileName const latexfile(filename_base + ".tex");
546 // we use the encoding of the buffer
547 Encoding const & enc = buffer_.params().encoding();
549 try { of.reset(enc.iconvName()); }
550 catch (iconv_codecvt_facet_exception const & e) {
551 LYXERR0("Caught iconv exception: " << e.what()
552 << "\nUnable to create LaTeX file: " << latexfile);
557 otexstream os(of, texrow);
558 OutputParams runparams(&enc);
559 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
561 if (!openFileWrite(of, latexfile))
565 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
566 << "Unable to create LaTeX file\n" << latexfile);
569 of << "\\batchmode\n";
571 // handle inputenc etc.
572 buffer_.params().writeEncodingPreamble(os, features);
573 of << "\n\\begin{document}\n";
574 dumpData(of, inprogress.snippets);
575 of << "\n\\end{document}\n";
578 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
579 << "File was not closed properly.");
583 double const font_scaling_factor =
584 buffer_.isExporting() ? 75.0 * buffer_.params().html_math_img_scale
585 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor;
588 // The colors should be customizable.
589 ColorCode const bg = buffer_.isExporting()
590 ? Color_white : PreviewLoader::backgroundColor();
591 ColorCode const fg = buffer_.isExporting()
592 ? Color_black : PreviewLoader::foregroundColor();
593 // The conversion command.
595 cs << pconverter_->command
596 << " " << quoteName(latexfile.toFilesystemEncoding())
597 << " --dpi " << int(font_scaling_factor)
598 << " --fg " << theApp()->hexName(fg)
599 << " --bg " << theApp()->hexName(bg);
600 // FIXME what about LuaTeX?
601 if (buffer_.params().useNonTeXFonts)
602 cs << " --latex=xelatex";
603 if (buffer_.params().encoding().package() == Encoding::japanese)
604 cs << " --latex=platex";
605 if (buffer_.params().bibtex_command != "default")
606 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
607 else if (buffer_.params().encoding().package() == Encoding::japanese)
608 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
610 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
611 if (buffer_.params().bufferFormat() == "lilypond-book")
614 string const command = libScriptSearch(cs.str());
617 ForkedCall call(buffer_.filePath());
618 int ret = call.startScript(ForkedProcess::Wait, command);
619 static int fake = (2^20) + 1;
621 inprogress.pid = pid;
622 inprogress.command = command;
623 in_progress_[pid] = inprogress;
624 finishedGenerating(pid, ret);
628 // Initiate the conversion from LaTeX to bitmap images files.
629 ForkedCall::SignalTypePtr
630 convert_ptr(new ForkedCall::SignalType);
631 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
633 ForkedCall call(buffer_.filePath());
634 int ret = call.startScript(command, convert_ptr);
637 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
638 << "Unable to start process\n" << command);
642 // Store the generation process in a list of all such processes
643 inprogress.pid = call.pid();
644 inprogress.command = command;
645 in_progress_[inprogress.pid] = inprogress;
649 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
652 InProgressProcesses::iterator git = in_progress_.find(pid);
653 if (git == in_progress_.end()) {
654 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
655 "data for PID " << pid << endl;
659 string const command = git->second.command;
660 string const status = retval > 0 ? "failed" : "succeeded";
661 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
662 << retval << "): processing " << status
663 << " for " << command);
667 // Read the metrics file, if it exists
668 vector<double> ascent_fractions(git->second.snippets.size());
669 setAscentFractions(ascent_fractions, git->second.metrics_file);
671 // Add these newly generated bitmap files to the cache and
672 // start loading them into LyX.
673 BitmapFile::const_iterator it = git->second.snippets.begin();
674 BitmapFile::const_iterator end = git->second.snippets.end();
676 list<PreviewImagePtr> newimages;
678 int metrics_counter = 0;
679 for (; it != end; ++it, ++metrics_counter) {
680 string const & snip = it->first;
681 FileName const & file = it->second;
682 double af = ascent_fractions[metrics_counter];
684 // Add the image to the cache only if it's actually present
685 if (file.isReadableFile()) {
686 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
689 newimages.push_back(ptr);
694 // Remove the item from the list of still-executing processes.
695 in_progress_.erase(git);
697 // Tell the outside world
698 list<PreviewImagePtr>::const_reverse_iterator
699 nit = newimages.rbegin();
700 list<PreviewImagePtr>::const_reverse_iterator
701 nend = newimages.rend();
702 for (; nit != nend; ++nit) {
703 imageReady(*nit->get());
708 void PreviewLoader::Impl::dumpPreamble(otexstream & os) const
710 // Dump the preamble only.
711 OutputParams runparams(&buffer_.params().encoding());
712 if (buffer_.params().useNonTeXFonts)
713 runparams.flavor = OutputParams::XETEX;
715 runparams.flavor = OutputParams::LATEX;
716 runparams.nice = true;
717 runparams.moving_arg = true;
718 runparams.free_spacing = true;
719 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
721 // FIXME! This is a HACK! The proper fix is to control the 'true'
722 // passed to WriteStream below:
723 // int InsetMathNest::latex(Buffer const &, odocstream & os,
724 // OutputParams const & runparams) const
726 // WriteStream wi(os, runparams.moving_arg, true);
731 << "\\def\\lyxlock{}\n"
734 // All equation labels appear as "(#)" + preview.sty's rendering of
736 if (lyxrc.preview_hashed_labels)
737 os << "\\renewcommand{\\theequation}{\\#}\n";
739 // Use the preview style file to ensure that each snippet appears on a
741 // Also support PDF output (automatically generated e.g. when
742 // \usepackage[pdftex]{hyperref} is used and XeTeX.
744 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
749 void PreviewLoader::Impl::dumpData(odocstream & os,
750 BitmapFile const & vec) const
755 BitmapFile::const_iterator it = vec.begin();
756 BitmapFile::const_iterator end = vec.end();
758 for (; it != end; ++it) {
760 os << "\\begin{preview}\n"
761 << from_utf8(it->first)
762 << "\n\\end{preview}\n\n";
766 } // namespace graphics