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 bool finished_generating_;
234 /// We don't own this
235 static lyx::Converter const * pconverter_;
237 Trackable trackable_;
241 lyx::Converter const * PreviewLoader::Impl::pconverter_;
245 // The public interface, defined in PreviewLoader.h
248 PreviewLoader::PreviewLoader(Buffer const & b)
249 : pimpl_(new Impl(*this, b))
253 PreviewLoader::~PreviewLoader()
259 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
261 return pimpl_->preview(latex_snippet);
265 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
267 return pimpl_->status(latex_snippet);
271 void PreviewLoader::add(string const & latex_snippet) const
273 pimpl_->add(latex_snippet);
277 void PreviewLoader::remove(string const & latex_snippet) const
279 pimpl_->remove(latex_snippet);
283 void PreviewLoader::startLoading(bool wait) const
285 pimpl_->startLoading(wait);
289 void PreviewLoader::refreshPreviews()
291 pimpl_->refreshPreviews();
295 signals2::connection PreviewLoader::connect(slot const & slot) const
297 return pimpl_->imageReady.connect(slot);
301 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
303 pimpl_->imageReady(pimage);
307 Buffer const & PreviewLoader::buffer() const
309 return pimpl_->buffer();
312 } // namespace graphics
316 // The details of the Impl
317 // =======================
321 std::function<SnippetPair (string const &)> IncrementedFileName
322 (string const & to_format, string const & filename_base)
324 return [&to_format, &filename_base](string const & snippet)
326 static int counter_ = 1;
328 os << filename_base << counter_++ << '.' << to_format;
329 string const file = os.str();
330 return make_pair(snippet, FileName(file));
335 InProgress::InProgress(string const & filename_base,
336 PendingSnippets const & pending,
337 string const & to_format)
338 : metrics_file(filename_base + ".metrics"),
339 snippets(pending.size()), pid(0)
341 PendingSnippets::const_iterator pit = pending.begin();
342 PendingSnippets::const_iterator pend = pending.end();
343 BitmapFile::iterator sit = snippets.begin();
345 transform(pit, pend, sit,
346 IncrementedFileName(to_format, filename_base));
350 void InProgress::stop() const
353 ForkedCallsController::kill(pid, 0);
355 if (!metrics_file.empty())
356 metrics_file.removeFile();
358 BitmapFile::const_iterator vit = snippets.begin();
359 BitmapFile::const_iterator vend = snippets.end();
360 for (; vit != vend; ++vit) {
361 if (!vit->second.empty())
362 vit->second.removeFile();
372 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
373 : parent_(p), buffer_(b), finished_generating_(true)
375 font_scaling_factor_ = int(buffer_.fontScalingFactor());
377 fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), nullptr, 16);
378 bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), nullptr, 16);
381 bg_color_ = 0xffffff;
384 pconverter_ = setConverter("lyxpreview");
386 delay_refresh_ = new QTimer(&parent_);
387 delay_refresh_->setSingleShot(true);
388 QObject::connect(delay_refresh_, SIGNAL(timeout()),
389 &parent_, SLOT(refreshPreviews()));
393 lyx::Converter const * PreviewLoader::Impl::setConverter(string const & from)
395 typedef vector<string> FmtList;
396 FmtList const & loadableFormats = graphics::Cache::get().loadableFormats();
397 FmtList::const_iterator it = loadableFormats.begin();
398 FmtList::const_iterator const end = loadableFormats.end();
400 for (; it != end; ++it) {
401 string const to = *it;
405 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
410 // Show the error only once. This is thread-safe.
411 static nullptr_t no_conv = [&]{
412 LYXERR0("PreviewLoader::startLoading()\n"
413 << "No converter from \"" << from
414 << "\" format has been defined.");
422 PreviewLoader::Impl::~Impl()
424 delete delay_refresh_;
426 InProgressProcesses::iterator ipit = in_progress_.begin();
427 InProgressProcesses::iterator ipend = in_progress_.end();
429 for (; ipit != ipend; ++ipit)
435 PreviewLoader::Impl::preview(string const & latex_snippet) const
437 int fs = int(buffer_.fontScalingFactor());
441 fg = strtol(theApp()->hexName(foregroundColor()).c_str(), nullptr, 16);
442 bg = strtol(theApp()->hexName(backgroundColor()).c_str(), nullptr, 16);
444 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
445 // Schedule refresh of all previews on zoom or color changes.
446 // The previews are regenerated only after the zoom factor
447 // has not been changed for about 1 second.
450 delay_refresh_->start(1000);
452 // Don't try to access the cache until we are done.
453 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) {
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 OutputParams runparams(&enc);
609 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
611 if (!openFileWrite(of, latexfile))
615 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
616 << "Unable to create LaTeX file\n" << latexfile);
619 of << "\\batchmode\n";
621 // Set \jobname of previews to the document name (see bug 9627)
622 of << "\\def\\jobname{"
623 << from_utf8(changeExtension(buffer_.latexName(true), ""))
626 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
627 string latexparam = "";
628 bool docformat = !buffer_.params().default_output_format.empty()
629 && buffer_.params().default_output_format != "default";
630 // Use LATEX flavor if the document does not specify a specific
631 // output format (see bug 9371).
632 OutputParams::FLAVOR flavor = docformat
633 ? buffer_.params().getOutputFlavor()
634 : OutputParams::LATEX;
635 if (buffer_.params().encoding().package() == Encoding::japanese) {
636 latexparam = " --latex=platex";
637 flavor = OutputParams::LATEX;
639 else if (buffer_.params().useNonTeXFonts) {
640 if (flavor == OutputParams::LUATEX)
641 latexparam = " --latex=lualatex";
643 flavor = OutputParams::XETEX;
644 latexparam = " --latex=xelatex";
649 case OutputParams::PDFLATEX:
650 latexparam = " --latex=pdflatex";
652 case OutputParams::XETEX:
653 latexparam = " --latex=xelatex";
655 case OutputParams::LUATEX:
656 latexparam = " --latex=lualatex";
658 case OutputParams::DVILUATEX:
659 latexparam = " --latex=dvilualatex";
662 flavor = OutputParams::LATEX;
665 dumpPreamble(os, flavor);
666 // handle inputenc etc.
667 // I think this is already handled by dumpPreamble(): Kornel
668 // buffer_.params().writeEncodingPreamble(os, features);
669 of << "\n\\begin{document}\n";
670 dumpData(of, inprogress.snippets);
671 of << "\n\\end{document}\n";
674 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
675 << "File was not closed properly.");
679 // The conversion command.
681 cs << pconverter_->command()
682 << " " << quoteName(latexfile.toFilesystemEncoding())
683 << " --dpi " << font_scaling_factor_;
686 // The colors should be customizable.
687 if (!buffer_.isExporting()) {
688 ColorCode const fg = PreviewLoader::foregroundColor();
689 ColorCode const bg = PreviewLoader::backgroundColor();
690 cs << " --fg " << theApp()->hexName(fg)
691 << " --bg " << theApp()->hexName(bg);
695 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
696 if (buffer_.params().bufferFormat() == "lilypond-book")
699 string const command = cs.str();
702 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
703 int ret = call.startScript(ForkedProcess::Wait, command);
704 // PID_MAX_LIMIT is 2^22 so we start one after that
705 static atomic_int fake((1 << 22) + 1);
707 inprogress.pid = pid;
708 inprogress.command = command;
709 in_progress_[pid] = inprogress;
710 finishedGenerating(pid, ret);
714 // Initiate the conversion from LaTeX to bitmap images files.
715 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
716 convert_ptr->connect(ForkedProcess::slot([this](pid_t pid, int retval){
717 finishedGenerating(pid, retval);
718 }).track_foreign(trackable_.p()));
720 ForkedCall call(buffer_.filePath());
721 int ret = call.startScript(command, convert_ptr);
724 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
725 << "Unable to start process\n" << command);
729 // Store the generation process in a list of all such processes
730 inprogress.pid = call.pid();
731 inprogress.command = command;
732 in_progress_[inprogress.pid] = inprogress;
736 double PreviewLoader::displayPixelRatio() const
738 return buffer().params().display_pixel_ratio;
741 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
744 InProgressProcesses::iterator git = in_progress_.find(pid);
745 if (git == in_progress_.end()) {
746 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
747 "data for PID " << pid << endl;
748 finished_generating_ = true;
752 string const command = git->second.command;
753 string const status = retval > 0 ? "failed" : "succeeded";
754 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
755 << retval << "): processing " << status
756 << " for " << command);
758 in_progress_.erase(git);
759 finished_generating_ = true;
763 // Read the metrics file, if it exists
764 vector<double> ascent_fractions(git->second.snippets.size());
765 setAscentFractions(ascent_fractions, git->second.metrics_file);
767 // Add these newly generated bitmap files to the cache and
768 // start loading them into LyX.
769 BitmapFile::const_iterator it = git->second.snippets.begin();
770 BitmapFile::const_iterator end = git->second.snippets.end();
772 list<PreviewImagePtr> newimages;
774 size_t metrics_counter = 0;
775 for (; it != end; ++it, ++metrics_counter) {
776 string const & snip = it->first;
777 FileName const & file = it->second;
778 double af = ascent_fractions[metrics_counter];
780 // Add the image to the cache only if it's actually present
781 // and not empty (an empty image is signaled by af < 0)
782 if (af >= 0 && file.isReadableFile()) {
783 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
786 newimages.push_back(ptr);
791 // Remove the item from the list of still-executing processes.
792 in_progress_.erase(git);
794 // Tell the outside world
795 list<PreviewImagePtr>::const_reverse_iterator
796 nit = newimages.rbegin();
797 list<PreviewImagePtr>::const_reverse_iterator
798 nend = newimages.rend();
799 for (; nit != nend; ++nit) {
800 imageReady(*nit->get());
802 finished_generating_ = true;
806 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
808 // Dump the preamble only.
809 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
810 OutputParams runparams(&buffer_.params().encoding());
811 runparams.flavor = flavor;
812 runparams.nice = true;
813 runparams.moving_arg = true;
814 runparams.free_spacing = true;
815 runparams.is_child = buffer_.parent();
816 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
818 // FIXME! This is a HACK! The proper fix is to control the 'true'
819 // passed to WriteStream below:
820 // int InsetMathNest::latex(Buffer const &, odocstream & os,
821 // OutputParams const & runparams) const
823 // WriteStream wi(os, runparams.moving_arg, true);
828 << "\\def\\lyxlock{}\n"
831 // All equation labels appear as "(#)" + preview.sty's rendering of
833 if (lyxrc.preview_hashed_labels)
834 os << "\\renewcommand{\\theequation}{\\#}\n";
836 // Use the preview style file to ensure that each snippet appears on a
838 // Also support PDF output (automatically generated e.g. when
839 // \usepackage[pdftex]{hyperref} is used and XeTeX.
841 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
846 void PreviewLoader::Impl::dumpData(odocstream & os,
847 BitmapFile const & vec) const
852 BitmapFile::const_iterator it = vec.begin();
853 BitmapFile::const_iterator end = vec.end();
855 for (; it != end; ++it) {
857 os << "\\begin{preview}\n"
858 << from_utf8(it->first)
859 << "\n\\end{preview}\n\n";
863 } // namespace graphics
866 #include "moc_PreviewLoader.cpp"