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 "InsetIterator.h"
23 #include "LaTeXFeatures.h"
26 #include "OutputParams.h"
28 #include "texstream.h"
30 #include "frontends/Application.h" // hexName
32 #include "insets/Inset.h"
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/FileName.h"
37 #include "support/filetools.h"
38 #include "support/ForkedCalls.h"
39 #include "support/lstrings.h"
41 #include "support/TempFile.h"
53 using namespace lyx::support;
59 typedef pair<string, FileName> SnippetPair;
61 // A list of all snippets to be converted to previews
62 typedef list<string> PendingSnippets;
64 // Each item in the vector is a pair<snippet, image file name>.
65 typedef vector<SnippetPair> BitmapFile;
68 FileName const unique_tex_filename(FileName const & bufferpath)
70 TempFile tempfile(bufferpath, "lyxpreviewXXXXXX.tex");
71 tempfile.setAutoRemove(false);
72 return tempfile.name();
76 void setAscentFractions(vector<double> & ascent_fractions,
77 FileName const & metrics_file)
79 // If all else fails, then the images will have equal ascents and
81 vector<double>::iterator it = ascent_fractions.begin();
82 vector<double>::iterator end = ascent_fractions.end();
85 ifstream in(metrics_file.toFilesystemEncoding().c_str());
87 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
88 << "Unable to open file!");
94 int snippet_counter = 1;
95 while (!in.eof() && it != end) {
98 double ascent_fraction;
100 in >> snippet >> id >> ascent_fraction;
106 error = snippet != "Snippet";
110 error = id != snippet_counter;
114 *it = ascent_fraction;
121 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
122 << "Error reading file!\n");
127 std::function <bool (SnippetPair const &)> FindFirst(string const & comp)
129 return [&comp](SnippetPair const & sp) { return sp.first == comp; };
133 /// Store info on a currently executing, forked process.
137 InProgress() : pid(0) {}
139 InProgress(string const & filename_base,
140 PendingSnippets const & pending,
141 string const & to_format);
142 /// Remove any files left lying around and kill the forked process.
148 FileName metrics_file;
155 typedef map<pid_t, InProgress> InProgressProcesses;
157 typedef InProgressProcesses::value_type InProgressProcess;
165 class PreviewLoader::Impl {
168 Impl(PreviewLoader & p, Buffer const & b);
169 /// Stop any InProgress items still executing.
172 PreviewImage const * preview(string const & latex_snippet) const;
174 PreviewLoader::Status status(string const & latex_snippet) const;
176 void add(string const & latex_snippet);
178 void remove(string const & latex_snippet);
179 /// \p wait whether to wait for the process to complete or, instead,
180 /// to do it in the background.
181 void startLoading(bool wait = false);
183 void refreshPreviews();
185 /// Emit this signal when an image is ready for display.
186 signals2::signal<void(PreviewImage const &)> imageReady;
188 Buffer const & buffer() const { return buffer_; }
190 lyx::Converter const * setConverter(string const & from);
193 /// Called by the ForkedCall process that generated the bitmap files.
194 void finishedGenerating(pid_t, int);
196 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
198 void dumpData(odocstream &, BitmapFile const &) const;
200 /** cache_ allows easy retrieval of already-generated images
201 * using the LaTeX snippet as the identifier.
203 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
205 typedef map<string, PreviewImagePtr> Cache;
209 /** pending_ stores the LaTeX snippets in anticipation of them being
210 * sent to the converter.
212 PendingSnippets pending_;
214 /** in_progress_ stores all forked processes so that we can proceed
217 InProgressProcesses in_progress_;
220 PreviewLoader & parent_;
222 Buffer const & buffer_;
224 mutable int font_scaling_factor_;
226 mutable int fg_color_;
228 mutable int bg_color_;
230 QTimer * delay_refresh_;
232 Trackable trackable_;
234 bool finished_generating_;
236 /// We don't own this
237 static lyx::Converter const * pconverter_;
242 lyx::Converter const * PreviewLoader::Impl::pconverter_;
246 // The public interface, defined in PreviewLoader.h
249 PreviewLoader::PreviewLoader(Buffer const & b)
250 : pimpl_(new Impl(*this, b))
254 PreviewLoader::~PreviewLoader()
260 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
262 return pimpl_->preview(latex_snippet);
266 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
268 return pimpl_->status(latex_snippet);
272 void PreviewLoader::add(string const & latex_snippet) const
274 pimpl_->add(latex_snippet);
278 void PreviewLoader::remove(string const & latex_snippet) const
280 pimpl_->remove(latex_snippet);
284 void PreviewLoader::startLoading(bool wait) const
286 pimpl_->startLoading(wait);
290 void PreviewLoader::refreshPreviews()
292 pimpl_->refreshPreviews();
296 signals2::connection PreviewLoader::connect(slot const & slot) const
298 return pimpl_->imageReady.connect(slot);
302 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
304 pimpl_->imageReady(pimage);
308 Buffer const & PreviewLoader::buffer() const
310 return pimpl_->buffer();
313 } // namespace graphics
317 // The details of the Impl
318 // =======================
322 class IncrementedFileName {
324 IncrementedFileName(string const & to_format,
325 string const & filename_base)
326 : to_format_(to_format), base_(filename_base), counter_(1)
329 SnippetPair const operator()(string const & snippet)
332 os << base_ << counter_++ << '.' << to_format_;
333 string const file_name = os.str();
334 return make_pair(snippet, FileName(file_name));
338 string const & to_format_;
339 string const & base_;
344 InProgress::InProgress(string const & filename_base,
345 PendingSnippets const & pending,
346 string const & to_format)
347 : metrics_file(filename_base + ".metrics"),
348 snippets(pending.size()), pid(0)
350 PendingSnippets::const_iterator pit = pending.begin();
351 PendingSnippets::const_iterator pend = pending.end();
352 BitmapFile::iterator sit = snippets.begin();
354 transform(pit, pend, sit,
355 IncrementedFileName(to_format, filename_base));
359 void InProgress::stop() const
362 ForkedCallsController::kill(pid, 0);
364 if (!metrics_file.empty())
365 metrics_file.removeFile();
367 BitmapFile::const_iterator vit = snippets.begin();
368 BitmapFile::const_iterator vend = snippets.end();
369 for (; vit != vend; ++vit) {
370 if (!vit->second.empty())
371 vit->second.removeFile();
381 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
382 : parent_(p), buffer_(b), finished_generating_(true)
384 font_scaling_factor_ = int(buffer_.fontScalingFactor());
386 fg_color_ = convert(theApp()->hexName(foregroundColor()).c_str(), 16);
387 bg_color_ = convert(theApp()->hexName(backgroundColor()).c_str(), 16);
390 bg_color_ = 0xffffff;
393 pconverter_ = setConverter("lyxpreview");
395 delay_refresh_ = new QTimer(&parent_);
396 delay_refresh_->setSingleShot(true);
397 QObject::connect(delay_refresh_, SIGNAL(timeout()),
398 &parent_, SLOT(refreshPreviews()));
402 lyx::Converter const * PreviewLoader::Impl::setConverter(string const & from)
404 typedef vector<string> FmtList;
405 FmtList const & loadableFormats = graphics::Cache::get().loadableFormats();
406 FmtList::const_iterator it = loadableFormats.begin();
407 FmtList::const_iterator const end = loadableFormats.end();
409 for (; it != end; ++it) {
410 string const to = *it;
414 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
419 // Show the error only once. This is thread-safe.
420 static nullptr_t no_conv = [&]{
421 LYXERR0("PreviewLoader::startLoading()\n"
422 << "No converter from \"" << from
423 << "\" format has been defined.");
431 PreviewLoader::Impl::~Impl()
433 delete delay_refresh_;
435 InProgressProcesses::iterator ipit = in_progress_.begin();
436 InProgressProcesses::iterator ipend = in_progress_.end();
438 for (; ipit != ipend; ++ipit)
444 PreviewLoader::Impl::preview(string const & latex_snippet) const
446 int fs = int(buffer_.fontScalingFactor());
450 fg = convert(theApp()->hexName(foregroundColor()).c_str(), 16);
451 bg = convert(theApp()->hexName(backgroundColor()).c_str(), 16);
453 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
454 // Schedule refresh of all previews on zoom or color changes.
455 // The previews are regenerated only after the zoom factor
456 // has not been changed for about 1 second.
459 delay_refresh_->start(1000);
461 // Don't try to access the cache until we are done.
462 if (delay_refresh_->isActive() || !finished_generating_)
465 Cache::const_iterator it = cache_.find(latex_snippet);
466 return (it == cache_.end()) ? nullptr : it->second.get();
470 void PreviewLoader::Impl::refreshPreviews()
472 font_scaling_factor_ = int(buffer_.fontScalingFactor());
473 // Reschedule refresh until the previous process completed.
474 if (!finished_generating_) {
475 delay_refresh_->start(1000);
478 Cache::const_iterator cit = cache_.begin();
479 Cache::const_iterator cend = cache_.end();
481 parent_.remove((cit++)->first);
482 finished_generating_ = false;
483 buffer_.updatePreviews();
489 std::function<bool (InProgressProcess const &)> FindSnippet(string const & s)
491 return [&s](InProgressProcess const & process) {
492 BitmapFile const & snippets = process.second.snippets;
493 BitmapFile::const_iterator beg = snippets.begin();
494 BitmapFile::const_iterator end = snippets.end();
495 return find_if(beg, end, FindFirst(s)) != end;
501 PreviewLoader::Status
502 PreviewLoader::Impl::status(string const & latex_snippet) const
504 Cache::const_iterator cit = cache_.find(latex_snippet);
505 if (cit != cache_.end())
508 PendingSnippets::const_iterator pit = pending_.begin();
509 PendingSnippets::const_iterator pend = pending_.end();
511 pit = find(pit, pend, latex_snippet);
515 InProgressProcesses::const_iterator ipit = in_progress_.begin();
516 InProgressProcesses::const_iterator ipend = in_progress_.end();
518 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
526 void PreviewLoader::Impl::add(string const & latex_snippet)
528 if (!pconverter_ || status(latex_snippet) != NotFound)
531 string const snippet = trim(latex_snippet);
535 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
537 pending_.push_back(snippet);
543 std::function<void (InProgressProcess &)> EraseSnippet(string const & s)
545 return [&s](InProgressProcess & process) {
546 BitmapFile & snippets = process.second.snippets;
547 BitmapFile::iterator it = snippets.begin();
548 BitmapFile::iterator end = snippets.end();
550 it = find_if(it, end, FindFirst(s));
552 snippets.erase(it, it+1);
559 void PreviewLoader::Impl::remove(string const & latex_snippet)
561 Cache::iterator cit = cache_.find(latex_snippet);
562 if (cit != cache_.end())
565 PendingSnippets::iterator pit = pending_.begin();
566 PendingSnippets::iterator pend = pending_.end();
568 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
570 InProgressProcesses::iterator ipit = in_progress_.begin();
571 InProgressProcesses::iterator ipend = in_progress_.end();
573 for_each(ipit, ipend, EraseSnippet(latex_snippet));
575 while (ipit != ipend) {
576 InProgressProcesses::iterator curr = ipit++;
577 if (curr->second.snippets.empty())
578 in_progress_.erase(curr);
583 void PreviewLoader::Impl::startLoading(bool wait)
585 if (pending_.empty() || !pconverter_)
588 // Only start the process off after the buffer is loaded from file.
589 if (!buffer_.isFullyLoaded())
592 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
594 // As used by the LaTeX file and by the resulting image files
595 FileName const directory(buffer_.temppath());
597 FileName const latexfile = unique_tex_filename(directory);
598 string const filename_base = removeExtension(latexfile.absFileName());
600 // Create an InProgress instance to place in the map of all
601 // such processes if it starts correctly.
602 InProgress inprogress(filename_base, pending_, pconverter_->to());
604 // clear pending_, so we're ready to start afresh.
607 // Output the LaTeX file.
608 // we use the encoding of the buffer
609 Encoding const & enc = buffer_.params().encoding();
611 try { of.reset(enc.iconvName()); }
612 catch (iconv_codecvt_facet_exception const & e) {
613 LYXERR0("Caught iconv exception: " << e.what()
614 << "\nUnable to create LaTeX file: " << latexfile);
619 OutputParams runparams(&enc);
620 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
622 if (!openFileWrite(of, latexfile))
626 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
627 << "Unable to create LaTeX file\n" << latexfile);
630 of << "\\batchmode\n";
632 // Set \jobname of previews to the document name (see bug 9627)
633 of << "\\def\\jobname{"
634 << from_utf8(changeExtension(buffer_.latexName(true), ""))
637 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
638 string latexparam = "";
639 bool docformat = !buffer_.params().default_output_format.empty()
640 && buffer_.params().default_output_format != "default";
641 // Use LATEX flavor if the document does not specify a specific
642 // output format (see bug 9371).
643 OutputParams::FLAVOR flavor = docformat
644 ? buffer_.params().getOutputFlavor()
645 : OutputParams::LATEX;
646 if (buffer_.params().encoding().package() == Encoding::japanese) {
647 latexparam = " --latex=platex";
648 flavor = OutputParams::LATEX;
650 else if (buffer_.params().useNonTeXFonts) {
651 if (flavor == OutputParams::LUATEX)
652 latexparam = " --latex=lualatex";
654 flavor = OutputParams::XETEX;
655 latexparam = " --latex=xelatex";
660 case OutputParams::PDFLATEX:
661 latexparam = " --latex=pdflatex";
663 case OutputParams::XETEX:
664 latexparam = " --latex=xelatex";
666 case OutputParams::LUATEX:
667 latexparam = " --latex=lualatex";
669 case OutputParams::DVILUATEX:
670 latexparam = " --latex=dvilualatex";
673 flavor = OutputParams::LATEX;
676 dumpPreamble(os, flavor);
677 // handle inputenc etc.
678 // I think this is already handled by dumpPreamble(): Kornel
679 // buffer_.params().writeEncodingPreamble(os, features);
680 of << "\n\\begin{document}\n";
681 dumpData(of, inprogress.snippets);
682 of << "\n\\end{document}\n";
685 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
686 << "File was not closed properly.");
690 // The conversion command.
692 cs << pconverter_->command()
693 << " " << quoteName(latexfile.toFilesystemEncoding())
694 << " --dpi " << font_scaling_factor_;
697 // The colors should be customizable.
698 if (!buffer_.isExporting()) {
699 ColorCode const fg = PreviewLoader::foregroundColor();
700 ColorCode const bg = PreviewLoader::backgroundColor();
701 cs << " --fg " << theApp()->hexName(fg)
702 << " --bg " << theApp()->hexName(bg);
706 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
707 if (buffer_.params().bufferFormat() == "lilypond-book")
710 string const command = cs.str();
713 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
714 int ret = call.startScript(ForkedProcess::Wait, command);
715 // PID_MAX_LIMIT is 2^22 so we start one after that
716 static atomic_int fake((1 << 22) + 1);
718 inprogress.pid = pid;
719 inprogress.command = command;
720 in_progress_[pid] = inprogress;
721 finishedGenerating(pid, ret);
725 // Initiate the conversion from LaTeX to bitmap images files.
726 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
727 convert_ptr->connect(ForkedProcess::slot([this](pid_t pid, int retval){
728 finishedGenerating(pid, retval);
729 }).track_foreign(trackable_.p()));
731 ForkedCall call(buffer_.filePath());
732 int ret = call.startScript(command, convert_ptr);
735 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
736 << "Unable to start process\n" << command);
740 // Store the generation process in a list of all such processes
741 inprogress.pid = call.pid();
742 inprogress.command = command;
743 in_progress_[inprogress.pid] = inprogress;
747 double PreviewLoader::displayPixelRatio() const
749 return buffer().params().display_pixel_ratio;
752 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
755 InProgressProcesses::iterator git = in_progress_.find(pid);
756 if (git == in_progress_.end()) {
757 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
758 "data for PID " << pid << endl;
759 finished_generating_ = true;
763 string const command = git->second.command;
764 string const status = retval > 0 ? "failed" : "succeeded";
765 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
766 << retval << "): processing " << status
767 << " for " << command);
769 in_progress_.erase(git);
770 finished_generating_ = true;
774 // Read the metrics file, if it exists
775 vector<double> ascent_fractions(git->second.snippets.size());
776 setAscentFractions(ascent_fractions, git->second.metrics_file);
778 // Add these newly generated bitmap files to the cache and
779 // start loading them into LyX.
780 BitmapFile::const_iterator it = git->second.snippets.begin();
781 BitmapFile::const_iterator end = git->second.snippets.end();
783 list<PreviewImagePtr> newimages;
785 size_t metrics_counter = 0;
786 for (; it != end; ++it, ++metrics_counter) {
787 string const & snip = it->first;
788 FileName const & file = it->second;
789 double af = ascent_fractions[metrics_counter];
791 // Add the image to the cache only if it's actually present
792 // and not empty (an empty image is signaled by af < 0)
793 if (af >= 0 && file.isReadableFile()) {
794 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
797 newimages.push_back(ptr);
802 // Remove the item from the list of still-executing processes.
803 in_progress_.erase(git);
805 // Tell the outside world
806 list<PreviewImagePtr>::const_reverse_iterator
807 nit = newimages.rbegin();
808 list<PreviewImagePtr>::const_reverse_iterator
809 nend = newimages.rend();
810 for (; nit != nend; ++nit) {
811 imageReady(*nit->get());
813 finished_generating_ = true;
817 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
819 // Dump the preamble only.
820 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
821 OutputParams runparams(&buffer_.params().encoding());
822 runparams.flavor = flavor;
823 runparams.nice = true;
824 runparams.moving_arg = true;
825 runparams.free_spacing = true;
826 runparams.is_child = buffer_.parent();
827 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
829 // FIXME! This is a HACK! The proper fix is to control the 'true'
830 // passed to WriteStream below:
831 // int InsetMathNest::latex(Buffer const &, odocstream & os,
832 // OutputParams const & runparams) const
834 // WriteStream wi(os, runparams.moving_arg, true);
839 << "\\def\\lyxlock{}\n"
842 // All equation labels appear as "(#)" + preview.sty's rendering of
844 if (lyxrc.preview_hashed_labels)
845 os << "\\renewcommand{\\theequation}{\\#}\n";
847 // Use the preview style file to ensure that each snippet appears on a
849 // Also support PDF output (automatically generated e.g. when
850 // \usepackage[pdftex]{hyperref} is used and XeTeX.
852 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
857 void PreviewLoader::Impl::dumpData(odocstream & os,
858 BitmapFile const & vec) const
863 BitmapFile::const_iterator it = vec.begin();
864 BitmapFile::const_iterator end = vec.end();
866 for (; it != end; ++it) {
868 os << "\\begin{preview}\n"
869 << from_utf8(it->first)
870 << "\n\\end{preview}\n\n";
874 } // namespace graphics
877 #include "moc_PreviewLoader.cpp"