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 LYXERR(Debug::OUTFILE, "Format = " << buffer_.params().getDefaultOutputFormat());
623 string latexparam = "";
624 bool docformat = !buffer_.params().default_output_format.empty()
625 && buffer_.params().default_output_format != "default";
626 // Use LATEX flavor if the document does not specify a specific
627 // output format (see bug 9371).
628 Flavor flavor = docformat
629 ? buffer_.params().getOutputFlavor()
631 if (buffer_.params().encoding().package() == Encoding::japanese) {
632 latexparam = " --latex=platex";
633 flavor = Flavor::LaTeX;
635 else if (buffer_.params().useNonTeXFonts) {
636 if (flavor == Flavor::LuaTeX)
637 latexparam = " --latex=lualatex";
639 flavor = Flavor::XeTeX;
640 latexparam = " --latex=xelatex";
645 case Flavor::PdfLaTeX:
646 latexparam = " --latex=pdflatex";
649 latexparam = " --latex=xelatex";
652 latexparam = " --latex=lualatex";
654 case Flavor::DviLuaTeX:
655 latexparam = " --latex=dvilualatex";
658 flavor = Flavor::LaTeX;
661 dumpPreamble(os, flavor);
662 // handle inputenc etc.
663 // I think this is already handled by dumpPreamble(): Kornel
664 // buffer_.params().writeEncodingPreamble(os, features);
665 of << "\n\\begin{document}\n";
666 dumpData(of, inprogress.snippets);
667 of << "\n\\end{document}\n";
670 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
671 << "File was not closed properly.");
675 // The conversion command.
677 cs << subst(pconverter_->command(), "$${python}", os::python())
678 << " " << quoteName(latexfile.toFilesystemEncoding())
679 << " --dpi " << font_scaling_factor_;
682 // The colors should be customizable.
683 if (!buffer_.isExporting()) {
684 ColorCode const fg = PreviewLoader::foregroundColor();
685 ColorCode const bg = PreviewLoader::backgroundColor();
686 cs << " --fg " << theApp()->hexName(fg)
687 << " --bg " << theApp()->hexName(bg);
691 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
692 if (buffer_.params().bufferFormat() == "lilypond-book")
695 string const command = cs.str();
698 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
699 int ret = call.startScript(ForkedProcess::Wait, command);
700 // PID_MAX_LIMIT is 2^22 so we start one after that
701 static atomic_int fake((1 << 22) + 1);
703 inprogress.pid = pid;
704 inprogress.command = command;
705 in_progress_[pid] = inprogress;
706 finishedGenerating(pid, ret);
710 // Initiate the conversion from LaTeX to bitmap images files.
711 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
712 weak_ptr<PreviewLoader::Impl> this_ = parent_.pimpl_;
713 convert_ptr->connect([this_](pid_t pid, int retval){
714 if (auto p = this_.lock()) {
715 p->finishedGenerating(pid, retval);
719 ForkedCall call(buffer_.filePath());
720 int ret = call.startScript(command, convert_ptr);
723 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
724 << "Unable to start process\n" << command);
728 // Store the generation process in a list of all such processes
729 inprogress.pid = call.pid();
730 inprogress.command = command;
731 in_progress_[inprogress.pid] = inprogress;
735 double PreviewLoader::displayPixelRatio() const
737 return buffer().params().display_pixel_ratio;
740 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
743 InProgressProcesses::iterator git = in_progress_.find(pid);
744 if (git == in_progress_.end()) {
745 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
746 "data for PID " << pid << endl;
747 finished_generating_ = true;
751 string const command = git->second.command;
752 string const status = retval > 0 ? "failed" : "succeeded";
753 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
754 << retval << "): processing " << status
755 << " for " << command);
757 in_progress_.erase(git);
758 finished_generating_ = true;
762 // Read the metrics file, if it exists
763 vector<double> ascent_fractions(git->second.snippets.size());
764 setAscentFractions(ascent_fractions, git->second.metrics_file);
766 // Add these newly generated bitmap files to the cache and
767 // start loading them into LyX.
768 BitmapFile::const_iterator it = git->second.snippets.begin();
769 BitmapFile::const_iterator end = git->second.snippets.end();
771 list<PreviewImagePtr> newimages;
773 size_t metrics_counter = 0;
774 for (; it != end; ++it, ++metrics_counter) {
775 string const & snip = it->first;
776 FileName const & file = it->second;
777 double af = ascent_fractions[metrics_counter];
779 // Add the image to the cache only if it's actually present
780 // and not empty (an empty image is signaled by af < 0)
781 if (af >= 0 && file.isReadableFile()) {
782 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
785 newimages.push_back(ptr);
790 // Remove the item from the list of still-executing processes.
791 in_progress_.erase(git);
793 // Tell the outside world
794 list<PreviewImagePtr>::const_reverse_iterator
795 nit = newimages.rbegin();
796 list<PreviewImagePtr>::const_reverse_iterator
797 nend = newimages.rend();
798 for (; nit != nend; ++nit) {
799 imageReady(*nit->get());
801 finished_generating_ = true;
805 void PreviewLoader::Impl::dumpPreamble(otexstream & os, Flavor flavor) const
807 // Dump the preamble only.
808 LYXERR(Debug::OUTFILE, "dumpPreamble, flavor == " << static_cast<int>(flavor));
809 OutputParams runparams(&buffer_.params().encoding());
810 runparams.flavor = flavor;
811 runparams.nice = true;
812 runparams.moving_arg = true;
813 runparams.free_spacing = true;
814 runparams.is_child = buffer_.parent();
815 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
817 // FIXME! This is a HACK! The proper fix is to control the 'true'
818 // passed to TeXMathStream below:
819 // int InsetMathNest::latex(Buffer const &, odocstream & os,
820 // OutputParams const & runparams) const
822 // TeXMathStream wi(os, runparams.moving_arg, true);
827 << "\\def\\lyxlock{}\n"
830 // All equation labels appear as "(#)" + preview.sty's rendering of
832 if (lyxrc.preview_hashed_labels)
833 os << "\\renewcommand{\\theequation}{\\#}\n";
835 // Use the preview style file to ensure that each snippet appears on a
837 // Also support PDF output (automatically generated e.g. when
838 // \usepackage[pdftex]{hyperref} is used and XeTeX.
840 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
845 void PreviewLoader::Impl::dumpData(odocstream & os,
846 BitmapFile const & vec) const
851 BitmapFile::const_iterator it = vec.begin();
852 BitmapFile::const_iterator end = vec.end();
854 for (; it != end; ++it) {
856 os << "\\begin{preview}\n"
857 << from_utf8(it->first)
858 << "\n\\end{preview}\n\n";
862 } // namespace graphics
865 #include "moc_PreviewLoader.cpp"