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 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 bool finished_generating_;
231 /// We don't own this
232 static lyx::Converter const * pconverter_;
237 lyx::Converter const * PreviewLoader::Impl::pconverter_;
241 // The public interface, defined in PreviewLoader.h
244 PreviewLoader::PreviewLoader(Buffer const & b)
245 : pimpl_(make_shared<Impl>(*this, b))
249 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
251 return pimpl_->preview(latex_snippet);
255 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
257 return pimpl_->status(latex_snippet);
261 void PreviewLoader::add(string const & latex_snippet) const
263 pimpl_->add(latex_snippet);
267 void PreviewLoader::remove(string const & latex_snippet) const
269 pimpl_->remove(latex_snippet);
273 void PreviewLoader::startLoading(bool wait) const
275 pimpl_->startLoading(wait);
279 void PreviewLoader::refreshPreviews()
281 pimpl_->refreshPreviews();
285 connection PreviewLoader::connect(slot const & slot) const
287 return pimpl_->imageReady.connect(slot);
291 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
293 pimpl_->imageReady(pimage);
297 Buffer const & PreviewLoader::buffer() const
299 return pimpl_->buffer();
302 } // namespace graphics
306 // The details of the Impl
307 // =======================
311 class IncrementedFileName {
313 IncrementedFileName(string const & to_format,
314 string const & filename_base)
315 : to_format_(to_format), base_(filename_base), counter_(1)
318 SnippetPair const operator()(string const & snippet)
321 os << base_ << counter_++ << '.' << to_format_;
322 string const file_name = os.str();
323 return make_pair(snippet, FileName(file_name));
327 string const & to_format_;
328 string const & base_;
333 InProgress::InProgress(string const & filename_base,
334 PendingSnippets const & pending,
335 string const & to_format)
336 : metrics_file(filename_base + ".metrics"),
337 snippets(pending.size()), pid(0)
339 PendingSnippets::const_iterator pit = pending.begin();
340 PendingSnippets::const_iterator pend = pending.end();
341 BitmapFile::iterator sit = snippets.begin();
343 transform(pit, pend, sit,
344 IncrementedFileName(to_format, filename_base));
348 void InProgress::stop() const
351 ForkedCallsController::kill(pid, 0);
353 if (!metrics_file.empty())
354 metrics_file.removeFile();
356 BitmapFile::const_iterator vit = snippets.begin();
357 BitmapFile::const_iterator vend = snippets.end();
358 for (; vit != vend; ++vit) {
359 if (!vit->second.empty())
360 vit->second.removeFile();
370 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
371 : parent_(p), buffer_(b), finished_generating_(true)
373 font_scaling_factor_ = int(buffer_.fontScalingFactor());
375 fg_color_ = convert(theApp()->hexName(foregroundColor()), 16);
376 bg_color_ = convert(theApp()->hexName(backgroundColor()), 16);
379 bg_color_ = 0xffffff;
382 pconverter_ = setConverter("lyxpreview");
384 delay_refresh_ = new QTimer(&parent_);
385 delay_refresh_->setSingleShot(true);
386 QObject::connect(delay_refresh_, SIGNAL(timeout()),
387 &parent_, SLOT(refreshPreviews()));
391 lyx::Converter const * PreviewLoader::Impl::setConverter(string const & from)
393 typedef vector<string> FmtList;
394 FmtList const & loadableFormats = graphics::Cache::get().loadableFormats();
395 FmtList::const_iterator it = loadableFormats.begin();
396 FmtList::const_iterator const end = loadableFormats.end();
398 for (; it != end; ++it) {
399 string const to = *it;
403 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
408 // Show the error only once. This is thread-safe.
409 static nullptr_t no_conv = [&]{
410 LYXERR0("PreviewLoader::startLoading()\n"
411 << "No converter from \"" << from
412 << "\" format has been defined.");
420 PreviewLoader::Impl::~Impl()
422 delete delay_refresh_;
424 InProgressProcesses::iterator ipit = in_progress_.begin();
425 InProgressProcesses::iterator ipend = in_progress_.end();
427 for (; ipit != ipend; ++ipit)
433 PreviewLoader::Impl::preview(string const & latex_snippet) const
435 int fs = int(buffer_.fontScalingFactor());
439 fg = convert(theApp()->hexName(foregroundColor()), 16);
440 bg = convert(theApp()->hexName(backgroundColor()), 16);
442 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
443 // Schedule refresh of all previews on zoom or color changes.
444 // The previews are regenerated only after the zoom factor
445 // has not been changed for about 1 second.
448 delay_refresh_->start(1000);
450 // Don't try to access the cache until we are done.
451 if (delay_refresh_->isActive() || !finished_generating_)
454 Cache::const_iterator it = cache_.find(latex_snippet);
455 return (it == cache_.end()) ? nullptr : it->second.get();
459 void PreviewLoader::Impl::refreshPreviews()
461 font_scaling_factor_ = int(buffer_.fontScalingFactor());
462 // Reschedule refresh until the previous process completed.
463 if (!finished_generating_) {
464 delay_refresh_->start(1000);
467 Cache::const_iterator cit = cache_.begin();
468 Cache::const_iterator cend = cache_.end();
470 parent_.remove((cit++)->first);
471 finished_generating_ = false;
472 buffer_.updatePreviews();
478 std::function<bool (InProgressProcess const &)> FindSnippet(string const & s)
480 return [&s](InProgressProcess const & process) {
481 BitmapFile const & snippets = process.second.snippets;
482 BitmapFile::const_iterator beg = snippets.begin();
483 BitmapFile::const_iterator end = snippets.end();
484 return find_if(beg, end, FindFirst(s)) != end;
490 PreviewLoader::Status
491 PreviewLoader::Impl::status(string const & latex_snippet) const
493 Cache::const_iterator cit = cache_.find(latex_snippet);
494 if (cit != cache_.end())
497 PendingSnippets::const_iterator pit = pending_.begin();
498 PendingSnippets::const_iterator pend = pending_.end();
500 pit = find(pit, pend, latex_snippet);
504 InProgressProcesses::const_iterator ipit = in_progress_.begin();
505 InProgressProcesses::const_iterator ipend = in_progress_.end();
507 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
515 void PreviewLoader::Impl::add(string const & latex_snippet)
517 if (!pconverter_ || status(latex_snippet) != NotFound)
520 string const snippet = trim(latex_snippet);
524 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
526 pending_.push_back(snippet);
532 std::function<void (InProgressProcess &)> EraseSnippet(string const & s)
534 return [&s](InProgressProcess & process) {
535 BitmapFile & snippets = process.second.snippets;
536 BitmapFile::iterator it = snippets.begin();
537 BitmapFile::iterator end = snippets.end();
539 it = find_if(it, end, FindFirst(s));
541 snippets.erase(it, it+1);
548 void PreviewLoader::Impl::remove(string const & latex_snippet)
550 Cache::iterator cit = cache_.find(latex_snippet);
551 if (cit != cache_.end())
554 PendingSnippets::iterator pit = pending_.begin();
555 PendingSnippets::iterator pend = pending_.end();
557 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
559 InProgressProcesses::iterator ipit = in_progress_.begin();
560 InProgressProcesses::iterator ipend = in_progress_.end();
562 for_each(ipit, ipend, EraseSnippet(latex_snippet));
564 while (ipit != ipend) {
565 InProgressProcesses::iterator curr = ipit++;
566 if (curr->second.snippets.empty())
567 in_progress_.erase(curr);
572 void PreviewLoader::Impl::startLoading(bool wait)
574 if (pending_.empty() || !pconverter_)
577 // Only start the process off after the buffer is loaded from file.
578 if (!buffer_.isFullyLoaded())
581 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
583 // As used by the LaTeX file and by the resulting image files
584 FileName const directory(buffer_.temppath());
586 FileName const latexfile = unique_tex_filename(directory);
587 string const filename_base = removeExtension(latexfile.absFileName());
589 // Create an InProgress instance to place in the map of all
590 // such processes if it starts correctly.
591 InProgress inprogress(filename_base, pending_, pconverter_->to());
593 // clear pending_, so we're ready to start afresh.
596 // Output the LaTeX file.
597 // we use the encoding of the buffer
598 Encoding const & enc = buffer_.params().encoding();
600 try { of.reset(enc.iconvName()); }
601 catch (iconv_codecvt_facet_exception const & e) {
602 LYXERR0("Caught iconv exception: " << e.what()
603 << "\nUnable to create LaTeX file: " << latexfile);
608 OutputParams runparams(&enc);
609 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
611 if (!openFileWrite(of, latexfile))
615 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
616 << "Unable to create LaTeX file\n" << latexfile);
619 of << "\\batchmode\n";
621 // Set \jobname of previews to the document name (see bug 9627)
622 of << "\\def\\jobname{"
623 << from_utf8(changeExtension(buffer_.latexName(), ""))
626 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
627 string latexparam = "";
628 bool docformat = !buffer_.params().default_output_format.empty()
629 && buffer_.params().default_output_format != "default";
630 // Use LATEX flavor if the document does not specify a specific
631 // output format (see bug 9371).
632 Flavor flavor = docformat
633 ? buffer_.params().getOutputFlavor()
635 if (buffer_.params().encoding().package() == Encoding::japanese) {
636 latexparam = " --latex=platex";
637 flavor = Flavor::LaTeX;
639 else if (buffer_.params().useNonTeXFonts) {
640 if (flavor == Flavor::LuaTeX)
641 latexparam = " --latex=lualatex";
643 flavor = Flavor::XeTeX;
644 latexparam = " --latex=xelatex";
649 case Flavor::PdfLaTeX:
650 latexparam = " --latex=pdflatex";
653 latexparam = " --latex=xelatex";
656 latexparam = " --latex=lualatex";
658 case Flavor::DviLuaTeX:
659 latexparam = " --latex=dvilualatex";
662 flavor = Flavor::LaTeX;
665 dumpPreamble(os, flavor);
666 // handle inputenc etc.
667 // I think this is already handled by dumpPreamble(): Kornel
668 // buffer_.params().writeEncodingPreamble(os, features);
669 of << "\n\\begin{document}\n";
670 dumpData(of, inprogress.snippets);
671 of << "\n\\end{document}\n";
674 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
675 << "File was not closed properly.");
679 // The conversion command.
681 cs << pconverter_->command()
682 << " " << quoteName(latexfile.toFilesystemEncoding())
683 << " --dpi " << font_scaling_factor_;
686 // The colors should be customizable.
687 if (!buffer_.isExporting()) {
688 ColorCode const fg = PreviewLoader::foregroundColor();
689 ColorCode const bg = PreviewLoader::backgroundColor();
690 cs << " --fg " << theApp()->hexName(fg)
691 << " --bg " << theApp()->hexName(bg);
695 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
696 if (buffer_.params().bufferFormat() == "lilypond-book")
699 string const command = cs.str();
702 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
703 int ret = call.startScript(ForkedProcess::Wait, command);
704 // PID_MAX_LIMIT is 2^22 so we start one after that
705 static atomic_int fake((1 << 22) + 1);
707 inprogress.pid = pid;
708 inprogress.command = command;
709 in_progress_[pid] = inprogress;
710 finishedGenerating(pid, ret);
714 // Initiate the conversion from LaTeX to bitmap images files.
715 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
716 weak_ptr<PreviewLoader::Impl> this_ = parent_.pimpl_;
717 convert_ptr->connect([this_](pid_t pid, int retval){
718 if (auto p = this_.lock()) {
719 p->finishedGenerating(pid, retval);
723 ForkedCall call(buffer_.filePath());
724 int ret = call.startScript(command, convert_ptr);
727 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
728 << "Unable to start process\n" << command);
732 // Store the generation process in a list of all such processes
733 inprogress.pid = call.pid();
734 inprogress.command = command;
735 in_progress_[inprogress.pid] = inprogress;
739 double PreviewLoader::displayPixelRatio() const
741 return buffer().params().display_pixel_ratio;
744 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
747 InProgressProcesses::iterator git = in_progress_.find(pid);
748 if (git == in_progress_.end()) {
749 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
750 "data for PID " << pid << endl;
751 finished_generating_ = true;
755 string const command = git->second.command;
756 string const status = retval > 0 ? "failed" : "succeeded";
757 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
758 << retval << "): processing " << status
759 << " for " << command);
761 in_progress_.erase(git);
762 finished_generating_ = true;
766 // Read the metrics file, if it exists
767 vector<double> ascent_fractions(git->second.snippets.size());
768 setAscentFractions(ascent_fractions, git->second.metrics_file);
770 // Add these newly generated bitmap files to the cache and
771 // start loading them into LyX.
772 BitmapFile::const_iterator it = git->second.snippets.begin();
773 BitmapFile::const_iterator end = git->second.snippets.end();
775 list<PreviewImagePtr> newimages;
777 size_t metrics_counter = 0;
778 for (; it != end; ++it, ++metrics_counter) {
779 string const & snip = it->first;
780 FileName const & file = it->second;
781 double af = ascent_fractions[metrics_counter];
783 // Add the image to the cache only if it's actually present
784 // and not empty (an empty image is signaled by af < 0)
785 if (af >= 0 && file.isReadableFile()) {
786 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
789 newimages.push_back(ptr);
794 // Remove the item from the list of still-executing processes.
795 in_progress_.erase(git);
797 // Tell the outside world
798 list<PreviewImagePtr>::const_reverse_iterator
799 nit = newimages.rbegin();
800 list<PreviewImagePtr>::const_reverse_iterator
801 nend = newimages.rend();
802 for (; nit != nend; ++nit) {
803 imageReady(*nit->get());
805 finished_generating_ = true;
809 void PreviewLoader::Impl::dumpPreamble(otexstream & os, Flavor flavor) const
811 // Dump the preamble only.
812 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << static_cast<int>(flavor));
813 OutputParams runparams(&buffer_.params().encoding());
814 runparams.flavor = flavor;
815 runparams.nice = true;
816 runparams.moving_arg = true;
817 runparams.free_spacing = true;
818 runparams.is_child = buffer_.parent();
819 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
821 // FIXME! This is a HACK! The proper fix is to control the 'true'
822 // passed to TeXMathStream below:
823 // int InsetMathNest::latex(Buffer const &, odocstream & os,
824 // OutputParams const & runparams) const
826 // TeXMathStream wi(os, runparams.moving_arg, true);
831 << "\\def\\lyxlock{}\n"
834 // All equation labels appear as "(#)" + preview.sty's rendering of
836 if (lyxrc.preview_hashed_labels)
837 os << "\\renewcommand{\\theequation}{\\#}\n";
839 // Use the preview style file to ensure that each snippet appears on a
841 // Also support PDF output (automatically generated e.g. when
842 // \usepackage[pdftex]{hyperref} is used and XeTeX.
844 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
849 void PreviewLoader::Impl::dumpData(odocstream & os,
850 BitmapFile const & vec) const
855 BitmapFile::const_iterator it = vec.begin();
856 BitmapFile::const_iterator end = vec.end();
858 for (; it != end; ++it) {
860 os << "\\begin{preview}\n"
861 << from_utf8(it->first)
862 << "\n\\end{preview}\n\n";
866 } // namespace graphics
869 #include "moc_PreviewLoader.cpp"