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"
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 if (!openFileWrite(of, latexfile))
612 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
613 << "Unable to create LaTeX file\n" << latexfile);
616 of << "\\batchmode\n";
618 LYXERR(Debug::OUTFILE, "Format = " << buffer_.params().getDefaultOutputFormat());
619 string latexparam = "";
620 bool docformat = !buffer_.params().default_output_format.empty()
621 && buffer_.params().default_output_format != "default";
622 // Use LATEX flavor if the document does not specify a specific
623 // output format (see bug 9371).
624 Flavor flavor = docformat
625 ? buffer_.params().getOutputFlavor()
627 if (buffer_.params().encoding().package() == Encoding::japanese) {
628 latexparam = " --latex=platex";
629 flavor = Flavor::LaTeX;
631 else if (buffer_.params().useNonTeXFonts) {
632 if (flavor == Flavor::LuaTeX)
633 latexparam = " --latex=lualatex";
635 flavor = Flavor::XeTeX;
636 latexparam = " --latex=xelatex";
641 case Flavor::PdfLaTeX:
642 latexparam = " --latex=pdflatex";
645 latexparam = " --latex=xelatex";
648 latexparam = " --latex=lualatex";
650 case Flavor::DviLuaTeX:
651 latexparam = " --latex=dvilualatex";
654 flavor = Flavor::LaTeX;
657 dumpPreamble(os, flavor);
658 // handle inputenc etc.
659 // I think this is already handled by dumpPreamble(): Kornel
660 // buffer_.params().writeEncodingPreamble(os, features);
661 of << "\n\\begin{document}\n";
662 dumpData(of, inprogress.snippets);
663 of << "\n\\end{document}\n";
666 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
667 << "File was not closed properly.");
671 // The conversion command.
673 cs << subst(pconverter_->command(), "$${python}", os::python())
674 << " " << quoteName(latexfile.toFilesystemEncoding())
675 << " --dpi " << font_scaling_factor_;
678 // The colors should be customizable.
679 if (!buffer_.isExporting()) {
680 ColorCode const fg = PreviewLoader::foregroundColor();
681 ColorCode const bg = PreviewLoader::backgroundColor();
682 cs << " --fg " << theApp()->hexName(fg)
683 << " --bg " << theApp()->hexName(bg);
687 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
688 if (buffer_.params().bufferFormat() == "lilypond-book")
691 string const command = cs.str();
694 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
695 int ret = call.startScript(ForkedProcess::Wait, command);
696 // PID_MAX_LIMIT is 2^22 so we start one after that
697 static atomic_int fake((1 << 22) + 1);
699 inprogress.pid = pid;
700 inprogress.command = command;
701 in_progress_[pid] = inprogress;
702 finishedGenerating(pid, ret);
706 // Initiate the conversion from LaTeX to bitmap images files.
707 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
708 weak_ptr<PreviewLoader::Impl> this_ = parent_.pimpl_;
709 convert_ptr->connect([this_](pid_t pid, int retval){
710 if (auto p = this_.lock()) {
711 p->finishedGenerating(pid, retval);
715 ForkedCall call(buffer_.filePath());
716 int ret = call.startScript(command, convert_ptr);
719 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
720 << "Unable to start process\n" << command);
724 // Store the generation process in a list of all such processes
725 inprogress.pid = call.pid();
726 inprogress.command = command;
727 in_progress_[inprogress.pid] = inprogress;
731 double PreviewLoader::displayPixelRatio() const
733 return buffer().params().display_pixel_ratio;
736 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
739 InProgressProcesses::iterator git = in_progress_.find(pid);
740 if (git == in_progress_.end()) {
741 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
742 "data for PID " << pid << endl;
743 finished_generating_ = true;
747 string const command = git->second.command;
748 string const status = retval > 0 ? "failed" : "succeeded";
749 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
750 << retval << "): processing " << status
751 << " for " << command);
753 in_progress_.erase(git);
754 finished_generating_ = true;
758 // Read the metrics file, if it exists
759 vector<double> ascent_fractions(git->second.snippets.size());
760 setAscentFractions(ascent_fractions, git->second.metrics_file);
762 // Add these newly generated bitmap files to the cache and
763 // start loading them into LyX.
764 BitmapFile::const_iterator it = git->second.snippets.begin();
765 BitmapFile::const_iterator end = git->second.snippets.end();
767 list<PreviewImagePtr> newimages;
769 size_t metrics_counter = 0;
770 for (; it != end; ++it, ++metrics_counter) {
771 string const & snip = it->first;
772 FileName const & file = it->second;
773 double af = ascent_fractions[metrics_counter];
775 // Add the image to the cache only if it's actually present
776 // and not empty (an empty image is signaled by af < 0)
777 if (af >= 0 && file.isReadableFile()) {
778 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
781 newimages.push_back(ptr);
786 // Remove the item from the list of still-executing processes.
787 in_progress_.erase(git);
789 // Tell the outside world
790 list<PreviewImagePtr>::const_reverse_iterator
791 nit = newimages.rbegin();
792 list<PreviewImagePtr>::const_reverse_iterator
793 nend = newimages.rend();
794 for (; nit != nend; ++nit) {
795 imageReady(*nit->get());
797 finished_generating_ = true;
798 buffer_.scheduleRedrawWorkAreas();
802 void PreviewLoader::Impl::dumpPreamble(otexstream & os, Flavor flavor) const
804 // Dump the preamble only.
805 LYXERR(Debug::OUTFILE, "dumpPreamble, flavor == " << static_cast<int>(flavor));
806 OutputParams runparams(&buffer_.params().encoding());
807 runparams.flavor = flavor;
808 runparams.nice = true;
809 runparams.moving_arg = true;
810 runparams.free_spacing = true;
811 runparams.is_child = buffer_.parent();
812 runparams.for_preview = true;
813 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
815 // FIXME! This is a HACK! The proper fix is to control the 'true'
816 // passed to TeXMathStream below:
817 // int InsetMathNest::latex(Buffer const &, odocstream & os,
818 // OutputParams const & runparams) const
820 // TeXMathStream wi(os, runparams.moving_arg, true);
825 << "\\def\\lyxlock{}\n"
828 // All equation labels appear as "(#)" + preview.sty's rendering of
830 if (lyxrc.preview_hashed_labels)
831 os << "\\renewcommand{\\theequation}{\\#}\n";
833 // Use the preview style file to ensure that each snippet appears on a
835 // Also support PDF output (automatically generated e.g. when
836 // \usepackage[pdftex]{hyperref} is used and XeTeX.
838 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
843 void PreviewLoader::Impl::dumpData(odocstream & os,
844 BitmapFile const & vec) const
849 BitmapFile::const_iterator it = vec.begin();
850 BitmapFile::const_iterator end = vec.end();
852 Encoding const & enc = buffer_.params().encoding();
854 for (; it != end; ++it) {
855 bool uncodable_content = false;
856 // check whether the content is encodable
857 // FIXME: the preview loader should be able
858 // to handle multiple encodings
859 // or we should generally use utf8
860 for (char_type n : from_utf8(it->first)) {
861 if (!enc.encodable(n)) {
862 LYXERR0("Uncodable character '"
864 << "' in preview snippet!");
865 uncodable_content = true;
869 os << "\\begin{preview}\n";
870 // do not show incomplete preview
871 if (!uncodable_content)
872 os << from_utf8(it->first);
873 os << "\n\\end{preview}\n\n";
877 } // namespace graphics
880 #include "moc_PreviewLoader.cpp"