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/bind.h"
42 #include "support/TempFile.h"
54 using namespace lyx::support;
60 typedef pair<string, FileName> SnippetPair;
62 // A list of all snippets to be converted to previews
63 typedef list<string> PendingSnippets;
65 // Each item in the vector is a pair<snippet, image file name>.
66 typedef vector<SnippetPair> BitmapFile;
69 FileName const unique_tex_filename(FileName const & bufferpath)
71 TempFile tempfile(bufferpath, "lyxpreviewXXXXXX.tex");
72 tempfile.setAutoRemove(false);
73 return tempfile.name();
77 lyx::Converter const * setConverter(string const & from)
79 typedef vector<string> FmtList;
80 typedef lyx::graphics::Cache GCache;
81 FmtList const & loadableFormats = GCache::get().loadableFormats();
82 FmtList::const_iterator it = loadableFormats.begin();
83 FmtList::const_iterator const end = loadableFormats.end();
85 for (; it != end; ++it) {
86 string const to = *it;
90 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
95 // Show the error only once
96 #ifdef LYX_USE_STD_CALL_ONCE
97 // This is thread-safe.
98 static once_flag flag;
99 call_once(flag, [&](){
100 LYXERR0("PreviewLoader::startLoading()\n"
101 << "No converter from \"" << from
102 << "\" format has been defined.");
105 // This is also thread-safe according to ยง6.7.4 of the C++11 standard.
106 static bool first = true;
109 LYXERR0("PreviewLoader::startLoading()\n"
110 << "No converter from \"" << from
111 << "\" format has been defined.");
118 void setAscentFractions(vector<double> & ascent_fractions,
119 FileName const & metrics_file)
121 // If all else fails, then the images will have equal ascents and
123 vector<double>::iterator it = ascent_fractions.begin();
124 vector<double>::iterator end = ascent_fractions.end();
127 ifstream in(metrics_file.toFilesystemEncoding().c_str());
129 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
130 << "Unable to open file!");
136 int snippet_counter = 1;
137 while (!in.eof() && it != end) {
140 double ascent_fraction;
142 in >> snippet >> id >> ascent_fraction;
148 error = snippet != "Snippet";
152 error = id != snippet_counter;
156 *it = ascent_fraction;
163 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
164 << "Error reading file!\n");
172 FindFirst(string const & comp) : comp_(comp) {}
173 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
179 /// Store info on a currently executing, forked process.
183 InProgress() : pid(0) {}
185 InProgress(string const & filename_base,
186 PendingSnippets const & pending,
187 string const & to_format);
188 /// Remove any files left lying around and kill the forked process.
196 FileName metrics_file;
201 typedef map<pid_t, InProgress> InProgressProcesses;
203 typedef InProgressProcesses::value_type InProgressProcess;
212 class PreviewLoader::Impl : public boost::signals2::trackable {
215 Impl(PreviewLoader & p, Buffer const & b);
216 /// Stop any InProgress items still executing.
219 PreviewImage const * preview(string const & latex_snippet) const;
221 PreviewLoader::Status status(string const & latex_snippet) const;
223 void add(string const & latex_snippet);
225 void remove(string const & latex_snippet);
226 /// \p wait whether to wait for the process to complete or, instead,
227 /// to do it in the background.
228 void startLoading(bool wait = false);
230 void refreshPreviews();
232 /// Emit this signal when an image is ready for display.
233 boost::signals2::signal<void(PreviewImage const &)> imageReady;
235 Buffer const & buffer() const { return buffer_; }
238 /// Called by the ForkedCall process that generated the bitmap files.
239 void finishedGenerating(pid_t, int);
241 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
243 void dumpData(odocstream &, BitmapFile const &) const;
245 /** cache_ allows easy retrieval of already-generated images
246 * using the LaTeX snippet as the identifier.
248 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
250 typedef map<string, PreviewImagePtr> Cache;
254 /** pending_ stores the LaTeX snippets in anticipation of them being
255 * sent to the converter.
257 PendingSnippets pending_;
259 /** in_progress_ stores all forked processes so that we can proceed
261 The map uses the conversion commands as its identifiers.
263 InProgressProcesses in_progress_;
266 PreviewLoader & parent_;
268 Buffer const & buffer_;
270 mutable int font_scaling_factor_;
272 mutable int fg_color_;
274 mutable int bg_color_;
276 QTimer * delay_refresh_;
278 bool finished_generating_;
280 /// We don't own this
281 static lyx::Converter const * pconverter_;
285 lyx::Converter const * PreviewLoader::Impl::pconverter_;
289 // The public interface, defined in PreviewLoader.h
292 PreviewLoader::PreviewLoader(Buffer const & b)
293 : pimpl_(new Impl(*this, b))
297 PreviewLoader::~PreviewLoader()
303 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
305 return pimpl_->preview(latex_snippet);
309 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
311 return pimpl_->status(latex_snippet);
315 void PreviewLoader::add(string const & latex_snippet) const
317 pimpl_->add(latex_snippet);
321 void PreviewLoader::remove(string const & latex_snippet) const
323 pimpl_->remove(latex_snippet);
327 void PreviewLoader::startLoading(bool wait) const
329 pimpl_->startLoading(wait);
333 void PreviewLoader::refreshPreviews()
335 pimpl_->refreshPreviews();
339 boost::signals2::connection PreviewLoader::connect(slot_type const & slot) const
341 return pimpl_->imageReady.connect(slot);
345 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
347 pimpl_->imageReady(pimage);
351 Buffer const & PreviewLoader::buffer() const
353 return pimpl_->buffer();
356 } // namespace graphics
360 // The details of the Impl
361 // =======================
365 class IncrementedFileName {
367 IncrementedFileName(string const & to_format,
368 string const & filename_base)
369 : to_format_(to_format), base_(filename_base), counter_(1)
372 SnippetPair const operator()(string const & snippet)
375 os << base_ << counter_++ << '.' << to_format_;
376 string const file = os.str();
378 return make_pair(snippet, FileName(file));
382 string const & to_format_;
383 string const & base_;
388 InProgress::InProgress(string const & filename_base,
389 PendingSnippets const & pending,
390 string const & to_format)
392 metrics_file(filename_base + ".metrics"),
393 snippets(pending.size())
395 PendingSnippets::const_iterator pit = pending.begin();
396 PendingSnippets::const_iterator pend = pending.end();
397 BitmapFile::iterator sit = snippets.begin();
399 transform(pit, pend, sit,
400 IncrementedFileName(to_format, filename_base));
404 void InProgress::stop() const
407 ForkedCallsController::kill(pid, 0);
409 if (!metrics_file.empty())
410 metrics_file.removeFile();
412 BitmapFile::const_iterator vit = snippets.begin();
413 BitmapFile::const_iterator vend = snippets.end();
414 for (; vit != vend; ++vit) {
415 if (!vit->second.empty())
416 vit->second.removeFile();
426 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
427 : parent_(p), buffer_(b), finished_generating_(true)
429 font_scaling_factor_ = int(buffer_.fontScalingFactor());
431 fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
432 bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
435 bg_color_ = 0xffffff;
438 pconverter_ = setConverter("lyxpreview");
440 delay_refresh_ = new QTimer(&parent_);
441 delay_refresh_->setSingleShot(true);
442 QObject::connect(delay_refresh_, SIGNAL(timeout()),
443 &parent_, SLOT(refreshPreviews()));
447 PreviewLoader::Impl::~Impl()
449 delete delay_refresh_;
451 InProgressProcesses::iterator ipit = in_progress_.begin();
452 InProgressProcesses::iterator ipend = in_progress_.end();
454 for (; ipit != ipend; ++ipit)
460 PreviewLoader::Impl::preview(string const & latex_snippet) const
462 int fs = int(buffer_.fontScalingFactor());
466 fg = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
467 bg = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
469 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
470 // Schedule refresh of all previews on zoom or color changes.
471 // The previews are regenerated only after the zoom factor
472 // has not been changed for about 1 second.
475 delay_refresh_->start(1000);
477 // Don't try to access the cache until we are done.
478 if (delay_refresh_->isActive() || !finished_generating_)
480 Cache::const_iterator it = cache_.find(latex_snippet);
481 return (it == cache_.end()) ? 0 : it->second.get();
485 void PreviewLoader::Impl::refreshPreviews()
487 font_scaling_factor_ = int(buffer_.fontScalingFactor());
488 // Reschedule refresh until the previous process completed.
489 if (!finished_generating_) {
490 delay_refresh_->start(1000);
493 Cache::const_iterator cit = cache_.begin();
494 Cache::const_iterator cend = cache_.end();
496 parent_.remove((cit++)->first);
497 finished_generating_ = false;
498 buffer_.updatePreviews();
506 FindSnippet(string const & s) : snippet_(s) {}
507 bool operator()(InProgressProcess const & process) const
509 BitmapFile const & snippets = process.second.snippets;
510 BitmapFile::const_iterator beg = snippets.begin();
511 BitmapFile::const_iterator end = snippets.end();
512 return find_if(beg, end, FindFirst(snippet_)) != end;
516 string const snippet_;
521 PreviewLoader::Status
522 PreviewLoader::Impl::status(string const & latex_snippet) const
524 Cache::const_iterator cit = cache_.find(latex_snippet);
525 if (cit != cache_.end())
528 PendingSnippets::const_iterator pit = pending_.begin();
529 PendingSnippets::const_iterator pend = pending_.end();
531 pit = find(pit, pend, latex_snippet);
535 InProgressProcesses::const_iterator ipit = in_progress_.begin();
536 InProgressProcesses::const_iterator ipend = in_progress_.end();
538 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
546 void PreviewLoader::Impl::add(string const & latex_snippet)
548 if (!pconverter_ || status(latex_snippet) != NotFound)
551 string const snippet = trim(latex_snippet);
555 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
557 pending_.push_back(snippet);
565 EraseSnippet(string const & s) : snippet_(s) {}
566 void operator()(InProgressProcess & process)
568 BitmapFile & snippets = process.second.snippets;
569 BitmapFile::iterator it = snippets.begin();
570 BitmapFile::iterator end = snippets.end();
572 it = find_if(it, end, FindFirst(snippet_));
574 snippets.erase(it, it+1);
578 string const & snippet_;
584 void PreviewLoader::Impl::remove(string const & latex_snippet)
586 Cache::iterator cit = cache_.find(latex_snippet);
587 if (cit != cache_.end())
590 PendingSnippets::iterator pit = pending_.begin();
591 PendingSnippets::iterator pend = pending_.end();
593 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
595 InProgressProcesses::iterator ipit = in_progress_.begin();
596 InProgressProcesses::iterator ipend = in_progress_.end();
598 for_each(ipit, ipend, EraseSnippet(latex_snippet));
600 while (ipit != ipend) {
601 InProgressProcesses::iterator curr = ipit++;
602 if (curr->second.snippets.empty())
603 in_progress_.erase(curr);
608 void PreviewLoader::Impl::startLoading(bool wait)
610 if (pending_.empty() || !pconverter_)
613 // Only start the process off after the buffer is loaded from file.
614 if (!buffer_.isFullyLoaded())
617 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
619 // As used by the LaTeX file and by the resulting image files
620 FileName const directory(buffer_.temppath());
622 FileName const latexfile = unique_tex_filename(directory);
623 string const filename_base = removeExtension(latexfile.absFileName());
625 // Create an InProgress instance to place in the map of all
626 // such processes if it starts correctly.
627 InProgress inprogress(filename_base, pending_, pconverter_->to());
629 // clear pending_, so we're ready to start afresh.
632 // Output the LaTeX file.
633 // we use the encoding of the buffer
634 Encoding const & enc = buffer_.params().encoding();
636 try { of.reset(enc.iconvName()); }
637 catch (iconv_codecvt_facet_exception const & e) {
638 LYXERR0("Caught iconv exception: " << e.what()
639 << "\nUnable to create LaTeX file: " << latexfile);
644 OutputParams runparams(&enc);
645 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
647 if (!openFileWrite(of, latexfile))
651 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
652 << "Unable to create LaTeX file\n" << latexfile);
655 of << "\\batchmode\n";
657 // Set \jobname of previews to the document name (see bug 9627)
658 of << "\\def\\jobname{"
659 << from_utf8(changeExtension(buffer_.latexName(true), ""))
662 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
663 string latexparam = "";
664 bool docformat = !buffer_.params().default_output_format.empty()
665 && buffer_.params().default_output_format != "default";
666 // Use LATEX flavor if the document does not specify a specific
667 // output format (see bug 9371).
668 OutputParams::FLAVOR flavor = docformat
669 ? buffer_.params().getOutputFlavor()
670 : OutputParams::LATEX;
671 if (buffer_.params().encoding().package() == Encoding::japanese) {
672 latexparam = " --latex=platex";
673 flavor = OutputParams::LATEX;
675 else if (buffer_.params().useNonTeXFonts) {
676 if (flavor == OutputParams::LUATEX)
677 latexparam = " --latex=lualatex";
679 flavor = OutputParams::XETEX;
680 latexparam = " --latex=xelatex";
685 case OutputParams::PDFLATEX:
686 latexparam = " --latex=pdflatex";
688 case OutputParams::XETEX:
689 latexparam = " --latex=xelatex";
691 case OutputParams::LUATEX:
692 latexparam = " --latex=lualatex";
694 case OutputParams::DVILUATEX:
695 latexparam = " --latex=dvilualatex";
698 flavor = OutputParams::LATEX;
701 dumpPreamble(os, flavor);
702 // handle inputenc etc.
703 // I think, this is already hadled by dumpPreamble(): Kornel
704 // buffer_.params().writeEncodingPreamble(os, features);
705 of << "\n\\begin{document}\n";
706 dumpData(of, inprogress.snippets);
707 of << "\n\\end{document}\n";
710 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
711 << "File was not closed properly.");
715 // The conversion command.
717 cs << pconverter_->command()
718 << " " << quoteName(latexfile.toFilesystemEncoding())
719 << " --dpi " << font_scaling_factor_;
722 // The colors should be customizable.
723 if (!buffer_.isExporting()) {
724 ColorCode const fg = PreviewLoader::foregroundColor();
725 ColorCode const bg = PreviewLoader::backgroundColor();
726 cs << " --fg " << theApp()->hexName(fg)
727 << " --bg " << theApp()->hexName(bg);
731 if (buffer_.params().bibtex_command != "default")
732 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
733 else if (buffer_.params().encoding().package() == Encoding::japanese)
734 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
736 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
737 if (buffer_.params().bufferFormat() == "lilypond-book")
740 string const command = cs.str();
743 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
744 int ret = call.startScript(ForkedProcess::Wait, command);
745 static atomic_int fake((2^20) + 1);
747 inprogress.pid = pid;
748 inprogress.command = command;
749 in_progress_[pid] = inprogress;
750 finishedGenerating(pid, ret);
754 // Initiate the conversion from LaTeX to bitmap images files.
755 ForkedCall::SignalTypePtr
756 convert_ptr(new ForkedCall::SignalType);
757 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
759 ForkedCall call(buffer_.filePath());
760 int ret = call.startScript(command, convert_ptr);
763 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
764 << "Unable to start process\n" << command);
768 // Store the generation process in a list of all such processes
769 inprogress.pid = call.pid();
770 inprogress.command = command;
771 in_progress_[inprogress.pid] = inprogress;
775 double PreviewLoader::displayPixelRatio() const
777 return buffer().params().display_pixel_ratio;
780 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
783 InProgressProcesses::iterator git = in_progress_.find(pid);
784 if (git == in_progress_.end()) {
785 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
786 "data for PID " << pid << endl;
787 finished_generating_ = true;
791 string const command = git->second.command;
792 string const status = retval > 0 ? "failed" : "succeeded";
793 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
794 << retval << "): processing " << status
795 << " for " << command);
797 in_progress_.erase(git);
798 finished_generating_ = true;
802 // Read the metrics file, if it exists
803 vector<double> ascent_fractions(git->second.snippets.size());
804 setAscentFractions(ascent_fractions, git->second.metrics_file);
806 // Add these newly generated bitmap files to the cache and
807 // start loading them into LyX.
808 BitmapFile::const_iterator it = git->second.snippets.begin();
809 BitmapFile::const_iterator end = git->second.snippets.end();
811 list<PreviewImagePtr> newimages;
813 int metrics_counter = 0;
814 for (; it != end; ++it, ++metrics_counter) {
815 string const & snip = it->first;
816 FileName const & file = it->second;
817 double af = ascent_fractions[metrics_counter];
819 // Add the image to the cache only if it's actually present
820 // and not empty (an empty image is signaled by af < 0)
821 if (af >= 0 && file.isReadableFile()) {
822 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
825 newimages.push_back(ptr);
830 // Remove the item from the list of still-executing processes.
831 in_progress_.erase(git);
833 // Tell the outside world
834 list<PreviewImagePtr>::const_reverse_iterator
835 nit = newimages.rbegin();
836 list<PreviewImagePtr>::const_reverse_iterator
837 nend = newimages.rend();
838 for (; nit != nend; ++nit) {
839 imageReady(*nit->get());
841 finished_generating_ = true;
845 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
847 // Dump the preamble only.
848 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
849 OutputParams runparams(&buffer_.params().encoding());
850 runparams.flavor = flavor;
851 runparams.nice = true;
852 runparams.moving_arg = true;
853 runparams.free_spacing = true;
854 runparams.is_child = buffer_.parent();
855 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
857 // FIXME! This is a HACK! The proper fix is to control the 'true'
858 // passed to WriteStream below:
859 // int InsetMathNest::latex(Buffer const &, odocstream & os,
860 // OutputParams const & runparams) const
862 // WriteStream wi(os, runparams.moving_arg, true);
867 << "\\def\\lyxlock{}\n"
870 // All equation labels appear as "(#)" + preview.sty's rendering of
872 if (lyxrc.preview_hashed_labels)
873 os << "\\renewcommand{\\theequation}{\\#}\n";
875 // Use the preview style file to ensure that each snippet appears on a
877 // Also support PDF output (automatically generated e.g. when
878 // \usepackage[pdftex]{hyperref} is used and XeTeX.
880 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
885 void PreviewLoader::Impl::dumpData(odocstream & os,
886 BitmapFile const & vec) const
891 BitmapFile::const_iterator it = vec.begin();
892 BitmapFile::const_iterator end = vec.end();
894 for (; it != end; ++it) {
896 os << "\\begin{preview}\n"
897 << from_utf8(it->first)
898 << "\n\\end{preview}\n\n";
902 } // namespace graphics
905 #include "moc_PreviewLoader.cpp"