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 "LaTeXFeatures.h"
25 #include "OutputParams.h"
27 #include "texstream.h"
29 #include "frontends/Application.h" // hexName
31 #include "support/convert.h"
32 #include "support/debug.h"
33 #include "support/FileName.h"
34 #include "support/filetools.h"
35 #include "support/ForkedCalls.h"
36 #include "support/lstrings.h"
38 #include "support/TempFile.h"
50 using namespace lyx::support;
56 typedef pair<string, FileName> SnippetPair;
58 // A list of all snippets to be converted to previews
59 typedef list<string> PendingSnippets;
61 // Each item in the vector is a pair<snippet, image file name>.
62 typedef vector<SnippetPair> BitmapFile;
65 FileName const unique_tex_filename(FileName const & bufferpath)
67 TempFile tempfile(bufferpath, "lyxpreviewXXXXXX.tex");
68 tempfile.setAutoRemove(false);
69 return tempfile.name();
73 void setAscentFractions(vector<double> & ascent_fractions,
74 FileName const & metrics_file)
76 // If all else fails, then the images will have equal ascents and
78 vector<double>::iterator it = ascent_fractions.begin();
79 vector<double>::iterator end = ascent_fractions.end();
82 ifstream in(metrics_file.toFilesystemEncoding().c_str());
84 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
85 << "Unable to open file!");
91 int snippet_counter = 1;
92 while (!in.eof() && it != end) {
95 double ascent_fraction;
97 in >> snippet >> id >> ascent_fraction;
103 error = snippet != "Snippet";
107 error = id != snippet_counter;
111 *it = ascent_fraction;
118 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
119 << "Error reading file!\n");
124 std::function <bool (SnippetPair const &)> FindFirst(string const & comp)
126 return [&comp](SnippetPair const & sp) { return sp.first == comp; };
130 /// Store info on a currently executing, forked process.
134 InProgress() : pid(0) {}
136 InProgress(string const & filename_base,
137 PendingSnippets const & pending,
138 string const & to_format);
139 /// Remove any files left lying around and kill the forked process.
145 FileName metrics_file;
152 typedef map<pid_t, InProgress> InProgressProcesses;
154 typedef InProgressProcesses::value_type InProgressProcess;
162 class PreviewLoader::Impl {
165 Impl(PreviewLoader & p, Buffer const & b);
166 /// Stop any InProgress items still executing.
169 PreviewImage const * preview(string const & latex_snippet) const;
171 PreviewLoader::Status status(string const & latex_snippet) const;
173 void add(string const & latex_snippet);
175 void remove(string const & latex_snippet);
176 /// \p wait whether to wait for the process to complete or, instead,
177 /// to do it in the background.
178 void startLoading(bool wait = false);
180 void refreshPreviews();
182 /// Emit this signal when an image is ready for display.
183 signals2::signal<void(PreviewImage const &)> imageReady;
185 Buffer const & buffer() const { return buffer_; }
187 lyx::Converter const * setConverter(string const & from);
190 /// Called by the ForkedCall process that generated the bitmap files.
191 void finishedGenerating(pid_t, int);
193 void dumpPreamble(otexstream &, Flavor) const;
195 void dumpData(odocstream &, BitmapFile const &) const;
197 /** cache_ allows easy retrieval of already-generated images
198 * using the LaTeX snippet as the identifier.
200 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
202 typedef map<string, PreviewImagePtr> Cache;
206 /** pending_ stores the LaTeX snippets in anticipation of them being
207 * sent to the converter.
209 PendingSnippets pending_;
211 /** in_progress_ stores all forked processes so that we can proceed
214 InProgressProcesses in_progress_;
217 PreviewLoader & parent_;
219 Buffer const & buffer_;
221 mutable int font_scaling_factor_;
223 mutable int fg_color_;
225 mutable int bg_color_;
227 QTimer * delay_refresh_;
229 Trackable trackable_;
231 bool finished_generating_;
233 /// We don't own this
234 static lyx::Converter const * pconverter_;
239 lyx::Converter const * PreviewLoader::Impl::pconverter_;
243 // The public interface, defined in PreviewLoader.h
246 PreviewLoader::PreviewLoader(Buffer const & b)
247 : pimpl_(new Impl(*this, b))
251 PreviewLoader::~PreviewLoader()
257 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
259 return pimpl_->preview(latex_snippet);
263 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
265 return pimpl_->status(latex_snippet);
269 void PreviewLoader::add(string const & latex_snippet) const
271 pimpl_->add(latex_snippet);
275 void PreviewLoader::remove(string const & latex_snippet) const
277 pimpl_->remove(latex_snippet);
281 void PreviewLoader::startLoading(bool wait) const
283 pimpl_->startLoading(wait);
287 void PreviewLoader::refreshPreviews()
289 pimpl_->refreshPreviews();
293 signals2::connection PreviewLoader::connect(slot const & slot) const
295 return pimpl_->imageReady.connect(slot);
299 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
301 pimpl_->imageReady(pimage);
305 Buffer const & PreviewLoader::buffer() const
307 return pimpl_->buffer();
310 } // namespace graphics
314 // The details of the Impl
315 // =======================
319 class IncrementedFileName {
321 IncrementedFileName(string const & to_format,
322 string const & filename_base)
323 : to_format_(to_format), base_(filename_base), counter_(1)
326 SnippetPair const operator()(string const & snippet)
329 os << base_ << counter_++ << '.' << to_format_;
330 string const file_name = os.str();
331 return make_pair(snippet, FileName(file_name));
335 string const & to_format_;
336 string const & base_;
341 InProgress::InProgress(string const & filename_base,
342 PendingSnippets const & pending,
343 string const & to_format)
344 : metrics_file(filename_base + ".metrics"),
345 snippets(pending.size()), pid(0)
347 PendingSnippets::const_iterator pit = pending.begin();
348 PendingSnippets::const_iterator pend = pending.end();
349 BitmapFile::iterator sit = snippets.begin();
351 transform(pit, pend, sit,
352 IncrementedFileName(to_format, filename_base));
356 void InProgress::stop() const
359 ForkedCallsController::kill(pid, 0);
361 if (!metrics_file.empty())
362 metrics_file.removeFile();
364 BitmapFile::const_iterator vit = snippets.begin();
365 BitmapFile::const_iterator vend = snippets.end();
366 for (; vit != vend; ++vit) {
367 if (!vit->second.empty())
368 vit->second.removeFile();
378 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
379 : parent_(p), buffer_(b), finished_generating_(true)
381 font_scaling_factor_ = int(buffer_.fontScalingFactor());
383 fg_color_ = convert(theApp()->hexName(foregroundColor()), 16);
384 bg_color_ = convert(theApp()->hexName(backgroundColor()), 16);
387 bg_color_ = 0xffffff;
390 pconverter_ = setConverter("lyxpreview");
392 delay_refresh_ = new QTimer(&parent_);
393 delay_refresh_->setSingleShot(true);
394 QObject::connect(delay_refresh_, SIGNAL(timeout()),
395 &parent_, SLOT(refreshPreviews()));
399 lyx::Converter const * PreviewLoader::Impl::setConverter(string const & from)
401 typedef vector<string> FmtList;
402 FmtList const & loadableFormats = graphics::Cache::get().loadableFormats();
403 FmtList::const_iterator it = loadableFormats.begin();
404 FmtList::const_iterator const end = loadableFormats.end();
406 for (; it != end; ++it) {
407 string const to = *it;
411 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
416 // Show the error only once. This is thread-safe.
417 static nullptr_t no_conv = [&]{
418 LYXERR0("PreviewLoader::startLoading()\n"
419 << "No converter from \"" << from
420 << "\" format has been defined.");
428 PreviewLoader::Impl::~Impl()
430 delete delay_refresh_;
432 InProgressProcesses::iterator ipit = in_progress_.begin();
433 InProgressProcesses::iterator ipend = in_progress_.end();
435 for (; ipit != ipend; ++ipit)
441 PreviewLoader::Impl::preview(string const & latex_snippet) const
443 int fs = int(buffer_.fontScalingFactor());
447 fg = convert(theApp()->hexName(foregroundColor()), 16);
448 bg = convert(theApp()->hexName(backgroundColor()), 16);
450 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
451 // Schedule refresh of all previews on zoom or color changes.
452 // The previews are regenerated only after the zoom factor
453 // has not been changed for about 1 second.
456 delay_refresh_->start(1000);
458 // Don't try to access the cache until we are done.
459 if (delay_refresh_->isActive() || !finished_generating_)
462 Cache::const_iterator it = cache_.find(latex_snippet);
463 return (it == cache_.end()) ? nullptr : it->second.get();
467 void PreviewLoader::Impl::refreshPreviews()
469 font_scaling_factor_ = int(buffer_.fontScalingFactor());
470 // Reschedule refresh until the previous process completed.
471 if (!finished_generating_) {
472 delay_refresh_->start(1000);
475 Cache::const_iterator cit = cache_.begin();
476 Cache::const_iterator cend = cache_.end();
478 parent_.remove((cit++)->first);
479 finished_generating_ = false;
480 buffer_.updatePreviews();
486 std::function<bool (InProgressProcess const &)> FindSnippet(string const & s)
488 return [&s](InProgressProcess const & process) {
489 BitmapFile const & snippets = process.second.snippets;
490 BitmapFile::const_iterator beg = snippets.begin();
491 BitmapFile::const_iterator end = snippets.end();
492 return find_if(beg, end, FindFirst(s)) != end;
498 PreviewLoader::Status
499 PreviewLoader::Impl::status(string const & latex_snippet) const
501 Cache::const_iterator cit = cache_.find(latex_snippet);
502 if (cit != cache_.end())
505 PendingSnippets::const_iterator pit = pending_.begin();
506 PendingSnippets::const_iterator pend = pending_.end();
508 pit = find(pit, pend, latex_snippet);
512 InProgressProcesses::const_iterator ipit = in_progress_.begin();
513 InProgressProcesses::const_iterator ipend = in_progress_.end();
515 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
523 void PreviewLoader::Impl::add(string const & latex_snippet)
525 if (!pconverter_ || status(latex_snippet) != NotFound)
528 string const snippet = trim(latex_snippet);
532 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
534 pending_.push_back(snippet);
540 std::function<void (InProgressProcess &)> EraseSnippet(string const & s)
542 return [&s](InProgressProcess & process) {
543 BitmapFile & snippets = process.second.snippets;
544 BitmapFile::iterator it = snippets.begin();
545 BitmapFile::iterator end = snippets.end();
547 it = find_if(it, end, FindFirst(s));
549 snippets.erase(it, it+1);
556 void PreviewLoader::Impl::remove(string const & latex_snippet)
558 Cache::iterator cit = cache_.find(latex_snippet);
559 if (cit != cache_.end())
562 PendingSnippets::iterator pit = pending_.begin();
563 PendingSnippets::iterator pend = pending_.end();
565 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
567 InProgressProcesses::iterator ipit = in_progress_.begin();
568 InProgressProcesses::iterator ipend = in_progress_.end();
570 for_each(ipit, ipend, EraseSnippet(latex_snippet));
572 while (ipit != ipend) {
573 InProgressProcesses::iterator curr = ipit++;
574 if (curr->second.snippets.empty())
575 in_progress_.erase(curr);
580 void PreviewLoader::Impl::startLoading(bool wait)
582 if (pending_.empty() || !pconverter_)
585 // Only start the process off after the buffer is loaded from file.
586 if (!buffer_.isFullyLoaded())
589 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
591 // As used by the LaTeX file and by the resulting image files
592 FileName const directory(buffer_.temppath());
594 FileName const latexfile = unique_tex_filename(directory);
595 string const filename_base = removeExtension(latexfile.absFileName());
597 // Create an InProgress instance to place in the map of all
598 // such processes if it starts correctly.
599 InProgress inprogress(filename_base, pending_, pconverter_->to());
601 // clear pending_, so we're ready to start afresh.
604 // Output the LaTeX file.
605 // we use the encoding of the buffer
606 Encoding const & enc = buffer_.params().encoding();
608 try { of.reset(enc.iconvName()); }
609 catch (iconv_codecvt_facet_exception const & e) {
610 LYXERR0("Caught iconv exception: " << e.what()
611 << "\nUnable to create LaTeX file: " << latexfile);
616 OutputParams runparams(&enc);
617 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
619 if (!openFileWrite(of, latexfile))
623 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
624 << "Unable to create LaTeX file\n" << latexfile);
627 of << "\\batchmode\n";
629 // Set \jobname of previews to the document name (see bug 9627)
630 of << "\\def\\jobname{"
631 << from_utf8(changeExtension(buffer_.latexName(), ""))
634 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
635 string latexparam = "";
636 bool docformat = !buffer_.params().default_output_format.empty()
637 && buffer_.params().default_output_format != "default";
638 // Use LATEX flavor if the document does not specify a specific
639 // output format (see bug 9371).
640 Flavor flavor = docformat
641 ? buffer_.params().getOutputFlavor()
643 if (buffer_.params().encoding().package() == Encoding::japanese) {
644 latexparam = " --latex=platex";
645 flavor = Flavor::LaTeX;
647 else if (buffer_.params().useNonTeXFonts) {
648 if (flavor == Flavor::LuaTeX)
649 latexparam = " --latex=lualatex";
651 flavor = Flavor::XeTeX;
652 latexparam = " --latex=xelatex";
657 case Flavor::PdfLaTeX:
658 latexparam = " --latex=pdflatex";
661 latexparam = " --latex=xelatex";
664 latexparam = " --latex=lualatex";
666 case Flavor::DviLuaTeX:
667 latexparam = " --latex=dvilualatex";
670 flavor = Flavor::LaTeX;
673 dumpPreamble(os, flavor);
674 // handle inputenc etc.
675 // I think this is already handled by dumpPreamble(): Kornel
676 // buffer_.params().writeEncodingPreamble(os, features);
677 of << "\n\\begin{document}\n";
678 dumpData(of, inprogress.snippets);
679 of << "\n\\end{document}\n";
682 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
683 << "File was not closed properly.");
687 // The conversion command.
689 cs << pconverter_->command()
690 << " " << quoteName(latexfile.toFilesystemEncoding())
691 << " --dpi " << font_scaling_factor_;
694 // The colors should be customizable.
695 if (!buffer_.isExporting()) {
696 ColorCode const fg = PreviewLoader::foregroundColor();
697 ColorCode const bg = PreviewLoader::backgroundColor();
698 cs << " --fg " << theApp()->hexName(fg)
699 << " --bg " << theApp()->hexName(bg);
703 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
704 if (buffer_.params().bufferFormat() == "lilypond-book")
707 string const command = cs.str();
710 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
711 int ret = call.startScript(ForkedProcess::Wait, command);
712 // PID_MAX_LIMIT is 2^22 so we start one after that
713 static atomic_int fake((1 << 22) + 1);
715 inprogress.pid = pid;
716 inprogress.command = command;
717 in_progress_[pid] = inprogress;
718 finishedGenerating(pid, ret);
722 // Initiate the conversion from LaTeX to bitmap images files.
723 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
724 convert_ptr->connect(ForkedProcess::slot([this](pid_t pid, int retval){
725 finishedGenerating(pid, retval);
726 }).track_foreign(trackable_.p()));
728 ForkedCall call(buffer_.filePath());
729 int ret = call.startScript(command, convert_ptr);
732 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
733 << "Unable to start process\n" << command);
737 // Store the generation process in a list of all such processes
738 inprogress.pid = call.pid();
739 inprogress.command = command;
740 in_progress_[inprogress.pid] = inprogress;
744 double PreviewLoader::displayPixelRatio() const
746 return buffer().params().display_pixel_ratio;
749 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
752 InProgressProcesses::iterator git = in_progress_.find(pid);
753 if (git == in_progress_.end()) {
754 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
755 "data for PID " << pid << endl;
756 finished_generating_ = true;
760 string const command = git->second.command;
761 string const status = retval > 0 ? "failed" : "succeeded";
762 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
763 << retval << "): processing " << status
764 << " for " << command);
766 in_progress_.erase(git);
767 finished_generating_ = true;
771 // Read the metrics file, if it exists
772 vector<double> ascent_fractions(git->second.snippets.size());
773 setAscentFractions(ascent_fractions, git->second.metrics_file);
775 // Add these newly generated bitmap files to the cache and
776 // start loading them into LyX.
777 BitmapFile::const_iterator it = git->second.snippets.begin();
778 BitmapFile::const_iterator end = git->second.snippets.end();
780 list<PreviewImagePtr> newimages;
782 size_t metrics_counter = 0;
783 for (; it != end; ++it, ++metrics_counter) {
784 string const & snip = it->first;
785 FileName const & file = it->second;
786 double af = ascent_fractions[metrics_counter];
788 // Add the image to the cache only if it's actually present
789 // and not empty (an empty image is signaled by af < 0)
790 if (af >= 0 && file.isReadableFile()) {
791 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
794 newimages.push_back(ptr);
799 // Remove the item from the list of still-executing processes.
800 in_progress_.erase(git);
802 // Tell the outside world
803 list<PreviewImagePtr>::const_reverse_iterator
804 nit = newimages.rbegin();
805 list<PreviewImagePtr>::const_reverse_iterator
806 nend = newimages.rend();
807 for (; nit != nend; ++nit) {
808 imageReady(*nit->get());
810 finished_generating_ = true;
814 void PreviewLoader::Impl::dumpPreamble(otexstream & os, Flavor flavor) const
816 // Dump the preamble only.
817 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << static_cast<int>(flavor));
818 OutputParams runparams(&buffer_.params().encoding());
819 runparams.flavor = flavor;
820 runparams.nice = true;
821 runparams.moving_arg = true;
822 runparams.free_spacing = true;
823 runparams.is_child = buffer_.parent();
824 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
826 // FIXME! This is a HACK! The proper fix is to control the 'true'
827 // passed to WriteStream below:
828 // int InsetMathNest::latex(Buffer const &, odocstream & os,
829 // OutputParams const & runparams) const
831 // WriteStream wi(os, runparams.moving_arg, true);
836 << "\\def\\lyxlock{}\n"
839 // All equation labels appear as "(#)" + preview.sty's rendering of
841 if (lyxrc.preview_hashed_labels)
842 os << "\\renewcommand{\\theequation}{\\#}\n";
844 // Use the preview style file to ensure that each snippet appears on a
846 // Also support PDF output (automatically generated e.g. when
847 // \usepackage[pdftex]{hyperref} is used and XeTeX.
849 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
854 void PreviewLoader::Impl::dumpData(odocstream & os,
855 BitmapFile const & vec) const
860 BitmapFile::const_iterator it = vec.begin();
861 BitmapFile::const_iterator end = vec.end();
863 for (; it != end; ++it) {
865 os << "\\begin{preview}\n"
866 << from_utf8(it->first)
867 << "\n\\end{preview}\n\n";
871 } // namespace graphics
874 #include "moc_PreviewLoader.cpp"