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"
24 #include "OutputParams.h"
26 #include "texstream.h"
28 #include "frontends/Application.h" // hexName
30 #include "support/convert.h"
31 #include "support/debug.h"
32 #include "support/FileName.h"
33 #include "support/filetools.h"
34 #include "support/ForkedCalls.h"
35 #include "support/lstrings.h"
36 #include "support/os.h"
38 #include "support/TempFile.h"
51 using namespace lyx::support;
57 typedef pair<docstring, FileName> SnippetPair;
59 // A list of all snippets to be converted to previews
60 typedef list<docstring> PendingSnippets;
62 // Each item in the vector is a pair<snippet, image file name>.
63 typedef vector<SnippetPair> BitmapFile;
66 FileName const unique_tex_filename(FileName const & bufferpath)
68 TempFile tempfile(bufferpath, "lyxpreviewXXXXXX.tex");
69 tempfile.setAutoRemove(false);
70 return tempfile.name();
74 void setAscentFractions(vector<double> & ascent_fractions,
75 FileName const & metrics_file)
77 // If all else fails, then the images will have equal ascents and
79 vector<double>::iterator it = ascent_fractions.begin();
80 vector<double>::iterator end = ascent_fractions.end();
83 ifstream in(metrics_file.toFilesystemEncoding().c_str());
85 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
86 << "Unable to open file!");
92 int snippet_counter = 1;
93 while (!in.eof() && it != end) {
96 double ascent_fraction;
98 in >> snippet >> id >> ascent_fraction;
104 error = snippet != "Snippet";
108 error = id != snippet_counter;
112 *it = ascent_fraction;
119 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
120 << "Error reading file!\n");
125 std::function <bool (SnippetPair const &)> FindFirst(docstring const & comp)
127 return [&comp](SnippetPair const & sp) { return sp.first == comp; };
131 /// Store info on a currently executing, forked process.
135 InProgress() : pid(0) {}
137 InProgress(string const & filename_base,
138 PendingSnippets const & pending,
139 string const & to_format);
140 /// Remove any files left lying around and kill the forked process.
146 FileName metrics_file;
153 typedef map<pid_t, InProgress> InProgressProcesses;
155 typedef InProgressProcesses::value_type InProgressProcess;
163 class PreviewLoader::Impl {
166 Impl(PreviewLoader & p, Buffer const & b);
167 /// Stop any InProgress items still executing.
170 PreviewImage const * preview(docstring const & latex_snippet) const;
172 PreviewLoader::Status status(docstring const & latex_snippet) const;
174 void add(docstring const & latex_snippet);
176 void remove(docstring const & latex_snippet);
177 /// \p wait whether to wait for the process to complete or, instead,
178 /// to do it in the background.
179 void startLoading(bool wait = false);
181 void refreshPreviews();
183 /// Emit this signal when an image is ready for display.
184 signal<void(PreviewImage const &)> imageReady;
186 Buffer const & buffer() const { return buffer_; }
188 lyx::Converter const * setConverter(string const & from);
191 /// Called by the ForkedCall process that generated the bitmap files.
192 void finishedGenerating(pid_t, int);
194 void dumpPreamble(otexstream &, Flavor) const;
196 void dumpData(odocstream &, BitmapFile const &) const;
198 /** cache_ allows easy retrieval of already-generated images
199 * using the LaTeX snippet as the identifier.
201 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
203 typedef map<docstring, PreviewImagePtr> Cache;
207 /** pending_ stores the LaTeX snippets in anticipation of them being
208 * sent to the converter.
210 PendingSnippets pending_;
212 /** in_progress_ stores all forked processes so that we can proceed
215 InProgressProcesses in_progress_;
218 PreviewLoader & parent_;
220 Buffer const & buffer_;
222 mutable int font_scaling_factor_;
224 mutable int fg_color_;
226 mutable int bg_color_;
228 QTimer * delay_refresh_;
230 bool finished_generating_;
232 /// We don't own this
233 static lyx::Converter const * pconverter_;
238 lyx::Converter const * PreviewLoader::Impl::pconverter_;
242 // The public interface, defined in PreviewLoader.h
245 PreviewLoader::PreviewLoader(Buffer const & b)
246 : pimpl_(make_shared<Impl>(*this, b))
250 PreviewImage const * PreviewLoader::preview(docstring const & latex_snippet) const
252 return pimpl_->preview(latex_snippet);
256 PreviewLoader::Status PreviewLoader::status(docstring const & latex_snippet) const
258 return pimpl_->status(latex_snippet);
262 void PreviewLoader::add(docstring const & latex_snippet) const
264 pimpl_->add(latex_snippet);
268 void PreviewLoader::remove(docstring const & latex_snippet) const
270 pimpl_->remove(latex_snippet);
274 void PreviewLoader::startLoading(bool wait) const
276 pimpl_->startLoading(wait);
280 void PreviewLoader::refreshPreviews()
282 pimpl_->refreshPreviews();
286 connection PreviewLoader::connect(slot const & slot) const
288 return pimpl_->imageReady.connect(slot);
292 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
294 pimpl_->imageReady(pimage);
298 Buffer const & PreviewLoader::buffer() const
300 return pimpl_->buffer();
303 } // namespace graphics
307 // The details of the Impl
308 // =======================
312 class IncrementedFileName {
314 IncrementedFileName(string const & to_format,
315 string const & filename_base)
316 : to_format_(to_format), base_(filename_base), counter_(1)
319 SnippetPair const operator()(docstring const & snippet)
322 os << base_ << counter_++ << '.' << to_format_;
323 string const file_name = os.str();
324 return make_pair(snippet, FileName(file_name));
328 string const & to_format_;
329 string const & base_;
334 InProgress::InProgress(string const & filename_base,
335 PendingSnippets const & pending,
336 string const & to_format)
337 : metrics_file(filename_base + ".metrics"),
338 snippets(pending.size()), pid(0)
340 PendingSnippets::const_iterator pit = pending.begin();
341 PendingSnippets::const_iterator pend = pending.end();
342 BitmapFile::iterator sit = snippets.begin();
344 transform(pit, pend, sit,
345 IncrementedFileName(to_format, filename_base));
349 void InProgress::stop() const
352 ForkedCallsController::kill(pid, 0);
354 if (!metrics_file.empty())
355 metrics_file.removeFile();
357 BitmapFile::const_iterator vit = snippets.begin();
358 BitmapFile::const_iterator vend = snippets.end();
359 for (; vit != vend; ++vit) {
360 if (!vit->second.empty())
361 vit->second.removeFile();
371 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
372 : parent_(p), buffer_(b), finished_generating_(true)
374 font_scaling_factor_ = int(buffer_.fontScalingFactor());
376 fg_color_ = convert(theApp()->hexName(foregroundColor()), 16);
377 bg_color_ = convert(theApp()->hexName(backgroundColor()), 16);
380 bg_color_ = 0xffffff;
383 pconverter_ = setConverter("lyxpreview");
385 delay_refresh_ = new QTimer(&parent_);
386 delay_refresh_->setSingleShot(true);
387 QObject::connect(delay_refresh_, SIGNAL(timeout()),
388 &parent_, SLOT(refreshPreviews()));
392 lyx::Converter const * PreviewLoader::Impl::setConverter(string const & from)
394 typedef vector<string> FmtList;
395 FmtList const & loadableFormats = graphics::Cache::get().loadableFormats();
396 FmtList::const_iterator it = loadableFormats.begin();
397 FmtList::const_iterator const end = loadableFormats.end();
399 for (; it != end; ++it) {
400 string const to = *it;
404 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
409 // Show the error only once. This is thread-safe.
410 static nullptr_t no_conv = [&]{
411 LYXERR0("PreviewLoader::startLoading()\n"
412 << "No converter from \"" << from
413 << "\" format has been defined.");
421 PreviewLoader::Impl::~Impl()
423 delete delay_refresh_;
425 InProgressProcesses::iterator ipit = in_progress_.begin();
426 InProgressProcesses::iterator ipend = in_progress_.end();
428 for (; ipit != ipend; ++ipit)
434 PreviewLoader::Impl::preview(docstring const & latex_snippet) const
436 int fs = int(buffer_.fontScalingFactor());
440 fg = convert(theApp()->hexName(foregroundColor()), 16);
441 bg = convert(theApp()->hexName(backgroundColor()), 16);
443 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
444 // Schedule refresh of all previews on zoom or color changes.
445 // The previews are regenerated only after the zoom factor
446 // has not been changed for about 1 second.
449 delay_refresh_->start(1000);
451 // Don't try to access the cache until we are done.
452 if (delay_refresh_->isActive() || !finished_generating_)
455 Cache::const_iterator it = cache_.find(latex_snippet);
456 return (it == cache_.end()) ? nullptr : it->second.get();
460 void PreviewLoader::Impl::refreshPreviews()
462 font_scaling_factor_ = int(buffer_.fontScalingFactor());
463 // Reschedule refresh until the previous process completed.
464 if (!finished_generating_) {
465 delay_refresh_->start(1000);
468 Cache::const_iterator cit = cache_.begin();
469 Cache::const_iterator cend = cache_.end();
471 parent_.remove((cit++)->first);
472 finished_generating_ = false;
473 buffer_.updatePreviews();
479 std::function<bool (InProgressProcess const &)> FindSnippet(docstring const & s)
481 return [&s](InProgressProcess const & process) {
482 BitmapFile const & snippets = process.second.snippets;
483 BitmapFile::const_iterator beg = snippets.begin();
484 BitmapFile::const_iterator end = snippets.end();
485 return find_if(beg, end, FindFirst(s)) != end;
491 PreviewLoader::Status
492 PreviewLoader::Impl::status(docstring const & latex_snippet) const
494 Cache::const_iterator cit = cache_.find(latex_snippet);
495 if (cit != cache_.end())
498 PendingSnippets::const_iterator pit = pending_.begin();
499 PendingSnippets::const_iterator pend = pending_.end();
501 pit = find(pit, pend, latex_snippet);
505 InProgressProcesses::const_iterator ipit = in_progress_.begin();
506 InProgressProcesses::const_iterator ipend = in_progress_.end();
508 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
516 void PreviewLoader::Impl::add(docstring const & latex_snippet)
518 if (!pconverter_ || status(latex_snippet) != NotFound)
521 docstring const snippet = trim(latex_snippet);
525 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
527 pending_.push_back(snippet);
533 std::function<void (InProgressProcess &)> EraseSnippet(docstring const & s)
535 return [&s](InProgressProcess & process) {
536 BitmapFile & snippets = process.second.snippets;
537 BitmapFile::iterator it = snippets.begin();
538 BitmapFile::iterator end = snippets.end();
540 it = find_if(it, end, FindFirst(s));
542 snippets.erase(it, it+1);
549 void PreviewLoader::Impl::remove(docstring const & latex_snippet)
551 Cache::iterator cit = cache_.find(latex_snippet);
552 if (cit != cache_.end())
555 PendingSnippets::iterator pit = pending_.begin();
556 PendingSnippets::iterator pend = pending_.end();
558 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
560 InProgressProcesses::iterator ipit = in_progress_.begin();
561 InProgressProcesses::iterator ipend = in_progress_.end();
563 for_each(ipit, ipend, EraseSnippet(latex_snippet));
565 while (ipit != ipend) {
566 InProgressProcesses::iterator curr = ipit++;
567 if (curr->second.snippets.empty())
568 in_progress_.erase(curr);
573 void PreviewLoader::Impl::startLoading(bool wait)
575 if (pending_.empty() || !pconverter_)
578 // Only start the process off after the buffer is loaded from file.
579 if (!buffer_.isFullyLoaded())
582 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
584 // As used by the LaTeX file and by the resulting image files
585 FileName const directory(buffer_.temppath());
587 FileName const latexfile = unique_tex_filename(directory);
588 string const filename_base = removeExtension(latexfile.absFileName());
590 // Create an InProgress instance to place in the map of all
591 // such processes if it starts correctly.
592 InProgress inprogress(filename_base, pending_, pconverter_->to());
594 // clear pending_, so we're ready to start afresh.
597 // Output the LaTeX file.
598 // we use the encoding of the buffer
599 Encoding const & enc = buffer_.params().encoding();
601 try { of.reset(enc.iconvName()); }
602 catch (iconv_codecvt_facet_exception const & e) {
603 LYXERR0("Caught iconv exception: " << e.what()
604 << "\nUnable to create LaTeX file: " << latexfile);
609 if (!openFileWrite(of, latexfile))
613 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
614 << "Unable to create LaTeX file\n" << latexfile);
617 of << "\\batchmode\n";
619 LYXERR(Debug::OUTFILE, "Format = " << buffer_.params().getDefaultOutputFormat());
620 string latexparam = "";
621 bool docformat = !buffer_.params().default_output_format.empty()
622 && buffer_.params().default_output_format != "default";
623 // Use LATEX flavor if the document does not specify a specific
624 // output format (see bug 9371).
625 Flavor flavor = docformat
626 ? buffer_.params().getOutputFlavor()
628 if (buffer_.params().encoding().package() == Encoding::japanese) {
629 latexparam = " --latex=platex";
630 flavor = Flavor::LaTeX;
632 else if (buffer_.params().useNonTeXFonts) {
633 if (flavor == Flavor::LuaTeX)
634 latexparam = " --latex=lualatex";
636 flavor = Flavor::XeTeX;
637 latexparam = " --latex=xelatex";
642 case Flavor::PdfLaTeX:
643 latexparam = " --latex=pdflatex";
646 latexparam = " --latex=xelatex";
649 latexparam = " --latex=lualatex";
651 case Flavor::DviLuaTeX:
652 latexparam = " --latex=dvilualatex";
655 flavor = Flavor::LaTeX;
658 dumpPreamble(os, flavor);
659 // handle inputenc etc.
660 // I think this is already handled by dumpPreamble(): Kornel
661 // buffer_.params().writeEncodingPreamble(os, features);
662 of << "\n\\begin{document}\n";
663 dumpData(of, inprogress.snippets);
664 of << "\n\\end{document}\n";
667 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
668 << "File was not closed properly.");
672 // The conversion command.
674 cs << subst(pconverter_->command(), "$${python}", os::python())
675 << " " << quoteName(latexfile.toFilesystemEncoding())
676 << " --dpi " << font_scaling_factor_;
679 // The colors should be customizable.
680 if (!buffer_.isExporting()) {
681 ColorCode const fg = PreviewLoader::foregroundColor();
682 ColorCode const bg = PreviewLoader::backgroundColor();
683 cs << " --fg " << theApp()->hexName(fg)
684 << " --bg " << theApp()->hexName(bg);
688 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
689 if (buffer_.params().bufferFormat() == "lilypond-book")
692 string const command = cs.str();
695 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
696 int ret = call.startScript(ForkedProcess::Wait, command);
697 // PID_MAX_LIMIT is 2^22 so we start one after that
698 static atomic_int fake((1 << 22) + 1);
700 inprogress.pid = pid;
701 inprogress.command = command;
702 in_progress_[pid] = inprogress;
703 finishedGenerating(pid, ret);
707 // Initiate the conversion from LaTeX to bitmap images files.
708 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
709 weak_ptr<PreviewLoader::Impl> this_ = parent_.pimpl_;
710 convert_ptr->connect([this_](pid_t pid, int retval){
711 if (auto p = this_.lock()) {
712 p->finishedGenerating(pid, retval);
716 ForkedCall call(buffer_.filePath());
717 int ret = call.startScript(command, convert_ptr);
720 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
721 << "Unable to start process\n" << command);
725 // Store the generation process in a list of all such processes
726 inprogress.pid = call.pid();
727 inprogress.command = command;
728 in_progress_[inprogress.pid] = inprogress;
732 double PreviewLoader::displayPixelRatio() const
734 return buffer().params().display_pixel_ratio;
737 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
740 InProgressProcesses::iterator git = in_progress_.find(pid);
741 if (git == in_progress_.end()) {
742 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
743 "data for PID " << pid << endl;
744 finished_generating_ = true;
748 string const command = git->second.command;
749 string const status = retval > 0 ? "failed" : "succeeded";
750 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
751 << retval << "): processing " << status
752 << " for " << command);
754 in_progress_.erase(git);
755 finished_generating_ = true;
759 // Read the metrics file, if it exists
760 vector<double> ascent_fractions(git->second.snippets.size());
761 setAscentFractions(ascent_fractions, git->second.metrics_file);
763 // Add these newly generated bitmap files to the cache and
764 // start loading them into LyX.
765 BitmapFile::const_iterator it = git->second.snippets.begin();
766 BitmapFile::const_iterator end = git->second.snippets.end();
768 list<PreviewImagePtr> newimages;
770 size_t metrics_counter = 0;
771 for (; it != end; ++it, ++metrics_counter) {
772 docstring const & snip = it->first;
773 FileName const & file = it->second;
774 double af = ascent_fractions[metrics_counter];
776 // Add the image to the cache only if it's actually present
777 // and not empty (an empty image is signaled by af < 0)
778 if (af >= 0 && file.isReadableFile()) {
779 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
782 newimages.push_back(ptr);
787 // Remove the item from the list of still-executing processes.
788 in_progress_.erase(git);
791 /* FIXME : there is no need for all these calls, which recompute
792 * all metrics for each and every preview. The single call at the
793 * end of this method is sufficient.
795 * It seems that this whole imageReady mechanism is actually not
796 * needed. If it is the case, the whole updateFrontend/updateInset
800 // Tell the outside world
801 list<PreviewImagePtr>::const_reverse_iterator
802 nit = newimages.rbegin();
803 list<PreviewImagePtr>::const_reverse_iterator
804 nend = newimages.rend();
805 for (; nit != nend; ++nit) {
806 imageReady(*nit->get());
810 finished_generating_ = true;
811 buffer_.scheduleRedrawWorkAreas();
815 void PreviewLoader::Impl::dumpPreamble(otexstream & os, Flavor flavor) const
817 // Dump the preamble only.
818 LYXERR(Debug::OUTFILE, "dumpPreamble, flavor == " << static_cast<int>(flavor));
819 OutputParams runparams(&buffer_.params().encoding());
820 runparams.flavor = flavor;
821 runparams.nice = true;
822 runparams.moving_arg = true;
823 runparams.free_spacing = true;
824 runparams.is_child = buffer_.parent();
825 runparams.for_preview = true;
826 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
828 // FIXME! This is a HACK! The proper fix is to control the 'true'
829 // passed to TeXMathStream below:
830 // int InsetMathNest::latex(Buffer const &, odocstream & os,
831 // OutputParams const & runparams) const
833 // TeXMathStream wi(os, runparams.moving_arg, true);
838 << "\\def\\lyxlock{}\n"
841 // All equation labels appear as "(#)" + preview.sty's rendering of
843 if (lyxrc.preview_hashed_labels)
844 os << "\\renewcommand{\\theequation}{\\#}\n";
846 // Use the preview style file to ensure that each snippet appears on a
848 // Also support PDF output (automatically generated e.g. when
849 // \usepackage[pdftex]{hyperref} is used and XeTeX.
851 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
856 void PreviewLoader::Impl::dumpData(odocstream & os,
857 BitmapFile const & vec) const
862 BitmapFile::const_iterator it = vec.begin();
863 BitmapFile::const_iterator end = vec.end();
865 Encoding const & enc = buffer_.params().encoding();
867 for (; it != end; ++it) {
868 bool uncodable_content = false;
869 // check whether the content is encodable
870 // FIXME: the preview loader should be able
871 // to handle multiple encodings
872 // or we should generally use utf8
873 for (char_type n : it->first) {
874 if (!enc.encodable(n)) {
875 LYXERR0("Uncodable character '"
877 << "' in preview snippet!");
878 uncodable_content = true;
882 os << "\\begin{preview}\n";
883 // do not show incomplete preview
884 if (!uncodable_content)
886 os << "\n\\end{preview}\n\n";
890 } // namespace graphics
893 #include "moc_PreviewLoader.cpp"