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) {
544 return [&s](InProgressProcess & process) {
545 BitmapFile & snippets = process.second.snippets;
546 BitmapFile::iterator it = snippets.begin();
547 BitmapFile::iterator end = snippets.end();
549 it = find_if(it, end, FindFirst(s));
551 snippets.erase(it, it+1);
558 void PreviewLoader::Impl::remove(string const & latex_snippet)
560 Cache::iterator cit = cache_.find(latex_snippet);
561 if (cit != cache_.end())
564 PendingSnippets::iterator pit = pending_.begin();
565 PendingSnippets::iterator pend = pending_.end();
567 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
569 InProgressProcesses::iterator ipit = in_progress_.begin();
570 InProgressProcesses::iterator ipend = in_progress_.end();
572 for_each(ipit, ipend, EraseSnippet(latex_snippet));
574 while (ipit != ipend) {
575 InProgressProcesses::iterator curr = ipit++;
576 if (curr->second.snippets.empty())
577 in_progress_.erase(curr);
582 void PreviewLoader::Impl::startLoading(bool wait)
584 if (pending_.empty() || !pconverter_)
587 // Only start the process off after the buffer is loaded from file.
588 if (!buffer_.isFullyLoaded())
591 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
593 // As used by the LaTeX file and by the resulting image files
594 FileName const directory(buffer_.temppath());
596 FileName const latexfile = unique_tex_filename(directory);
597 string const filename_base = removeExtension(latexfile.absFileName());
599 // Create an InProgress instance to place in the map of all
600 // such processes if it starts correctly.
601 InProgress inprogress(filename_base, pending_, pconverter_->to());
603 // clear pending_, so we're ready to start afresh.
606 // Output the LaTeX file.
607 // we use the encoding of the buffer
608 Encoding const & enc = buffer_.params().encoding();
610 try { of.reset(enc.iconvName()); }
611 catch (iconv_codecvt_facet_exception const & e) {
612 LYXERR0("Caught iconv exception: " << e.what()
613 << "\nUnable to create LaTeX file: " << latexfile);
618 OutputParams runparams(&enc);
619 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
621 if (!openFileWrite(of, latexfile))
625 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
626 << "Unable to create LaTeX file\n" << latexfile);
629 of << "\\batchmode\n";
631 // Set \jobname of previews to the document name (see bug 9627)
632 of << "\\def\\jobname{"
633 << from_utf8(changeExtension(buffer_.latexName(true), ""))
636 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
637 string latexparam = "";
638 bool docformat = !buffer_.params().default_output_format.empty()
639 && buffer_.params().default_output_format != "default";
640 // Use LATEX flavor if the document does not specify a specific
641 // output format (see bug 9371).
642 OutputParams::FLAVOR flavor = docformat
643 ? buffer_.params().getOutputFlavor()
644 : OutputParams::LATEX;
645 if (buffer_.params().encoding().package() == Encoding::japanese) {
646 latexparam = " --latex=platex";
647 flavor = OutputParams::LATEX;
649 else if (buffer_.params().useNonTeXFonts) {
650 if (flavor == OutputParams::LUATEX)
651 latexparam = " --latex=lualatex";
653 flavor = OutputParams::XETEX;
654 latexparam = " --latex=xelatex";
659 case OutputParams::PDFLATEX:
660 latexparam = " --latex=pdflatex";
662 case OutputParams::XETEX:
663 latexparam = " --latex=xelatex";
665 case OutputParams::LUATEX:
666 latexparam = " --latex=lualatex";
668 case OutputParams::DVILUATEX:
669 latexparam = " --latex=dvilualatex";
672 flavor = OutputParams::LATEX;
675 dumpPreamble(os, flavor);
676 // handle inputenc etc.
677 // I think this is already handled by dumpPreamble(): Kornel
678 // buffer_.params().writeEncodingPreamble(os, features);
679 of << "\n\\begin{document}\n";
680 dumpData(of, inprogress.snippets);
681 of << "\n\\end{document}\n";
684 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
685 << "File was not closed properly.");
689 // The conversion command.
691 cs << pconverter_->command()
692 << " " << quoteName(latexfile.toFilesystemEncoding())
693 << " --dpi " << font_scaling_factor_;
696 // The colors should be customizable.
697 if (!buffer_.isExporting()) {
698 ColorCode const fg = PreviewLoader::foregroundColor();
699 ColorCode const bg = PreviewLoader::backgroundColor();
700 cs << " --fg " << theApp()->hexName(fg)
701 << " --bg " << theApp()->hexName(bg);
705 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
706 if (buffer_.params().bufferFormat() == "lilypond-book")
709 string const command = cs.str();
712 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
713 int ret = call.startScript(ForkedProcess::Wait, command);
714 // PID_MAX_LIMIT is 2^22 so we start one after that
715 static atomic_int fake((1 << 22) + 1);
717 inprogress.pid = pid;
718 inprogress.command = command;
719 in_progress_[pid] = inprogress;
720 finishedGenerating(pid, ret);
724 // Initiate the conversion from LaTeX to bitmap images files.
725 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
726 convert_ptr->connect(ForkedProcess::slot([this](pid_t pid, int retval){
727 finishedGenerating(pid, retval);
728 }).track_foreign(trackable_.p()));
730 ForkedCall call(buffer_.filePath());
731 int ret = call.startScript(command, convert_ptr);
734 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
735 << "Unable to start process\n" << command);
739 // Store the generation process in a list of all such processes
740 inprogress.pid = call.pid();
741 inprogress.command = command;
742 in_progress_[inprogress.pid] = inprogress;
746 double PreviewLoader::displayPixelRatio() const
748 return buffer().params().display_pixel_ratio;
751 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
754 InProgressProcesses::iterator git = in_progress_.find(pid);
755 if (git == in_progress_.end()) {
756 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
757 "data for PID " << pid << endl;
758 finished_generating_ = true;
762 string const command = git->second.command;
763 string const status = retval > 0 ? "failed" : "succeeded";
764 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
765 << retval << "): processing " << status
766 << " for " << command);
768 in_progress_.erase(git);
769 finished_generating_ = true;
773 // Read the metrics file, if it exists
774 vector<double> ascent_fractions(git->second.snippets.size());
775 setAscentFractions(ascent_fractions, git->second.metrics_file);
777 // Add these newly generated bitmap files to the cache and
778 // start loading them into LyX.
779 BitmapFile::const_iterator it = git->second.snippets.begin();
780 BitmapFile::const_iterator end = git->second.snippets.end();
782 list<PreviewImagePtr> newimages;
784 size_t metrics_counter = 0;
785 for (; it != end; ++it, ++metrics_counter) {
786 string const & snip = it->first;
787 FileName const & file = it->second;
788 double af = ascent_fractions[metrics_counter];
790 // Add the image to the cache only if it's actually present
791 // and not empty (an empty image is signaled by af < 0)
792 if (af >= 0 && file.isReadableFile()) {
793 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
796 newimages.push_back(ptr);
801 // Remove the item from the list of still-executing processes.
802 in_progress_.erase(git);
804 // Tell the outside world
805 list<PreviewImagePtr>::const_reverse_iterator
806 nit = newimages.rbegin();
807 list<PreviewImagePtr>::const_reverse_iterator
808 nend = newimages.rend();
809 for (; nit != nend; ++nit) {
810 imageReady(*nit->get());
812 finished_generating_ = true;
816 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
818 // Dump the preamble only.
819 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
820 OutputParams runparams(&buffer_.params().encoding());
821 runparams.flavor = flavor;
822 runparams.nice = true;
823 runparams.moving_arg = true;
824 runparams.free_spacing = true;
825 runparams.is_child = buffer_.parent();
826 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
828 // FIXME! This is a HACK! The proper fix is to control the 'true'
829 // passed to WriteStream below:
830 // int InsetMathNest::latex(Buffer const &, odocstream & os,
831 // OutputParams const & runparams) const
833 // WriteStream wi(os, runparams.moving_arg, true);
838 << "\\def\\lyxlock{}\n"
841 // All equation labels appear as "(#)" + preview.sty's rendering of
843 if (lyxrc.preview_hashed_labels)
844 os << "\\renewcommand{\\theequation}{\\#}\n";
846 // Use the preview style file to ensure that each snippet appears on a
848 // Also support PDF output (automatically generated e.g. when
849 // \usepackage[pdftex]{hyperref} is used and XeTeX.
851 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
856 void PreviewLoader::Impl::dumpData(odocstream & os,
857 BitmapFile const & vec) const
862 BitmapFile::const_iterator it = vec.begin();
863 BitmapFile::const_iterator end = vec.end();
865 for (; it != end; ++it) {
867 os << "\\begin{preview}\n"
868 << from_utf8(it->first)
869 << "\n\\end{preview}\n\n";
873 } // namespace graphics
876 #include "moc_PreviewLoader.cpp"