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"
37 #include "support/os.h"
39 #include "support/TempFile.h"
51 using namespace lyx::support;
57 typedef pair<string, FileName> SnippetPair;
59 // A list of all snippets to be converted to previews
60 typedef list<string> 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(string 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(string const & latex_snippet) const;
172 PreviewLoader::Status status(string const & latex_snippet) const;
174 void add(string const & latex_snippet);
176 void remove(string 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<string, 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(string const & latex_snippet) const
252 return pimpl_->preview(latex_snippet);
256 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
258 return pimpl_->status(latex_snippet);
262 void PreviewLoader::add(string const & latex_snippet) const
264 pimpl_->add(latex_snippet);
268 void PreviewLoader::remove(string 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()(string 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(string 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(string 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(string 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(string const & latex_snippet)
518 if (!pconverter_ || status(latex_snippet) != NotFound)
521 string const snippet = trim(latex_snippet);
525 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
527 pending_.push_back(snippet);
533 std::function<void (InProgressProcess &)> EraseSnippet(string 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(string 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 OutputParams runparams(&enc);
610 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
612 if (!openFileWrite(of, latexfile))
616 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
617 << "Unable to create LaTeX file\n" << latexfile);
620 of << "\\batchmode\n";
622 // Set \jobname of previews to the document name (see bug 9627)
623 of << "\\def\\jobname{"
624 << from_utf8(changeExtension(buffer_.latexName(), ""))
627 LYXERR(Debug::OUTFILE, "Format = " << buffer_.params().getDefaultOutputFormat());
628 string latexparam = "";
629 bool docformat = !buffer_.params().default_output_format.empty()
630 && buffer_.params().default_output_format != "default";
631 // Use LATEX flavor if the document does not specify a specific
632 // output format (see bug 9371).
633 Flavor flavor = docformat
634 ? buffer_.params().getOutputFlavor()
636 if (buffer_.params().encoding().package() == Encoding::japanese) {
637 latexparam = " --latex=platex";
638 flavor = Flavor::LaTeX;
640 else if (buffer_.params().useNonTeXFonts) {
641 if (flavor == Flavor::LuaTeX)
642 latexparam = " --latex=lualatex";
644 flavor = Flavor::XeTeX;
645 latexparam = " --latex=xelatex";
650 case Flavor::PdfLaTeX:
651 latexparam = " --latex=pdflatex";
654 latexparam = " --latex=xelatex";
657 latexparam = " --latex=lualatex";
659 case Flavor::DviLuaTeX:
660 latexparam = " --latex=dvilualatex";
663 flavor = Flavor::LaTeX;
666 dumpPreamble(os, flavor);
667 // handle inputenc etc.
668 // I think this is already handled by dumpPreamble(): Kornel
669 // buffer_.params().writeEncodingPreamble(os, features);
670 of << "\n\\begin{document}\n";
671 dumpData(of, inprogress.snippets);
672 of << "\n\\end{document}\n";
675 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
676 << "File was not closed properly.");
680 // The conversion command.
682 cs << subst(pconverter_->command(), "$${python}", os::python())
683 << " " << quoteName(latexfile.toFilesystemEncoding())
684 << " --dpi " << font_scaling_factor_;
687 // The colors should be customizable.
688 if (!buffer_.isExporting()) {
689 ColorCode const fg = PreviewLoader::foregroundColor();
690 ColorCode const bg = PreviewLoader::backgroundColor();
691 cs << " --fg " << theApp()->hexName(fg)
692 << " --bg " << theApp()->hexName(bg);
696 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
697 if (buffer_.params().bufferFormat() == "lilypond-book")
700 string const command = cs.str();
703 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
704 int ret = call.startScript(ForkedProcess::Wait, command);
705 // PID_MAX_LIMIT is 2^22 so we start one after that
706 static atomic_int fake((1 << 22) + 1);
708 inprogress.pid = pid;
709 inprogress.command = command;
710 in_progress_[pid] = inprogress;
711 finishedGenerating(pid, ret);
715 // Initiate the conversion from LaTeX to bitmap images files.
716 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
717 weak_ptr<PreviewLoader::Impl> this_ = parent_.pimpl_;
718 convert_ptr->connect([this_](pid_t pid, int retval){
719 if (auto p = this_.lock()) {
720 p->finishedGenerating(pid, retval);
724 ForkedCall call(buffer_.filePath());
725 int ret = call.startScript(command, convert_ptr);
728 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
729 << "Unable to start process\n" << command);
733 // Store the generation process in a list of all such processes
734 inprogress.pid = call.pid();
735 inprogress.command = command;
736 in_progress_[inprogress.pid] = inprogress;
740 double PreviewLoader::displayPixelRatio() const
742 return buffer().params().display_pixel_ratio;
745 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
748 InProgressProcesses::iterator git = in_progress_.find(pid);
749 if (git == in_progress_.end()) {
750 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
751 "data for PID " << pid << endl;
752 finished_generating_ = true;
756 string const command = git->second.command;
757 string const status = retval > 0 ? "failed" : "succeeded";
758 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
759 << retval << "): processing " << status
760 << " for " << command);
762 in_progress_.erase(git);
763 finished_generating_ = true;
767 // Read the metrics file, if it exists
768 vector<double> ascent_fractions(git->second.snippets.size());
769 setAscentFractions(ascent_fractions, git->second.metrics_file);
771 // Add these newly generated bitmap files to the cache and
772 // start loading them into LyX.
773 BitmapFile::const_iterator it = git->second.snippets.begin();
774 BitmapFile::const_iterator end = git->second.snippets.end();
776 list<PreviewImagePtr> newimages;
778 size_t metrics_counter = 0;
779 for (; it != end; ++it, ++metrics_counter) {
780 string const & snip = it->first;
781 FileName const & file = it->second;
782 double af = ascent_fractions[metrics_counter];
784 // Add the image to the cache only if it's actually present
785 // and not empty (an empty image is signaled by af < 0)
786 if (af >= 0 && file.isReadableFile()) {
787 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
790 newimages.push_back(ptr);
795 // Remove the item from the list of still-executing processes.
796 in_progress_.erase(git);
798 // Tell the outside world
799 list<PreviewImagePtr>::const_reverse_iterator
800 nit = newimages.rbegin();
801 list<PreviewImagePtr>::const_reverse_iterator
802 nend = newimages.rend();
803 for (; nit != nend; ++nit) {
804 imageReady(*nit->get());
806 finished_generating_ = true;
810 void PreviewLoader::Impl::dumpPreamble(otexstream & os, Flavor flavor) const
812 // Dump the preamble only.
813 LYXERR(Debug::OUTFILE, "dumpPreamble, flavor == " << static_cast<int>(flavor));
814 OutputParams runparams(&buffer_.params().encoding());
815 runparams.flavor = flavor;
816 runparams.nice = true;
817 runparams.moving_arg = true;
818 runparams.free_spacing = true;
819 runparams.is_child = buffer_.parent();
820 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
822 // FIXME! This is a HACK! The proper fix is to control the 'true'
823 // passed to TeXMathStream below:
824 // int InsetMathNest::latex(Buffer const &, odocstream & os,
825 // OutputParams const & runparams) const
827 // TeXMathStream wi(os, runparams.moving_arg, true);
832 << "\\def\\lyxlock{}\n"
835 // All equation labels appear as "(#)" + preview.sty's rendering of
837 if (lyxrc.preview_hashed_labels)
838 os << "\\renewcommand{\\theequation}{\\#}\n";
840 // Use the preview style file to ensure that each snippet appears on a
842 // Also support PDF output (automatically generated e.g. when
843 // \usepackage[pdftex]{hyperref} is used and XeTeX.
845 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
850 void PreviewLoader::Impl::dumpData(odocstream & os,
851 BitmapFile const & vec) const
856 BitmapFile::const_iterator it = vec.begin();
857 BitmapFile::const_iterator end = vec.end();
859 for (; it != end; ++it) {
861 os << "\\begin{preview}\n"
862 << from_utf8(it->first)
863 << "\n\\end{preview}\n\n";
867 } // namespace graphics
870 #include "moc_PreviewLoader.cpp"