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 static once_flag flag;
97 call_once(flag, [&](){
98 LYXERR0("PreviewLoader::startLoading()\n"
99 << "No converter from \"" << from
100 << "\" format has been defined.");
106 void setAscentFractions(vector<double> & ascent_fractions,
107 FileName const & metrics_file)
109 // If all else fails, then the images will have equal ascents and
111 vector<double>::iterator it = ascent_fractions.begin();
112 vector<double>::iterator end = ascent_fractions.end();
115 ifstream in(metrics_file.toFilesystemEncoding().c_str());
117 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
118 << "Unable to open file!");
124 int snippet_counter = 1;
125 while (!in.eof() && it != end) {
128 double ascent_fraction;
130 in >> snippet >> id >> ascent_fraction;
136 error = snippet != "Snippet";
140 error = id != snippet_counter;
144 *it = ascent_fraction;
151 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
152 << "Error reading file!\n");
160 FindFirst(string const & comp) : comp_(comp) {}
161 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
167 /// Store info on a currently executing, forked process.
171 InProgress() : pid(0) {}
173 InProgress(string const & filename_base,
174 PendingSnippets const & pending,
175 string const & to_format);
176 /// Remove any files left lying around and kill the forked process.
184 FileName metrics_file;
189 typedef map<pid_t, InProgress> InProgressProcesses;
191 typedef InProgressProcesses::value_type InProgressProcess;
200 class PreviewLoader::Impl : public boost::signals2::trackable {
203 Impl(PreviewLoader & p, Buffer const & b);
204 /// Stop any InProgress items still executing.
207 PreviewImage const * preview(string const & latex_snippet) const;
209 PreviewLoader::Status status(string const & latex_snippet) const;
211 void add(string const & latex_snippet);
213 void remove(string const & latex_snippet);
214 /// \p wait whether to wait for the process to complete or, instead,
215 /// to do it in the background.
216 void startLoading(bool wait = false);
218 void refreshPreviews();
220 /// Emit this signal when an image is ready for display.
221 boost::signals2::signal<void(PreviewImage const &)> imageReady;
223 Buffer const & buffer() const { return buffer_; }
226 /// Called by the ForkedCall process that generated the bitmap files.
227 void finishedGenerating(pid_t, int);
229 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
231 void dumpData(odocstream &, BitmapFile const &) const;
233 /** cache_ allows easy retrieval of already-generated images
234 * using the LaTeX snippet as the identifier.
236 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
238 typedef map<string, PreviewImagePtr> Cache;
242 /** pending_ stores the LaTeX snippets in anticipation of them being
243 * sent to the converter.
245 PendingSnippets pending_;
247 /** in_progress_ stores all forked processes so that we can proceed
249 The map uses the conversion commands as its identifiers.
251 InProgressProcesses in_progress_;
254 PreviewLoader & parent_;
256 Buffer const & buffer_;
258 mutable int font_scaling_factor_;
260 mutable int fg_color_;
262 mutable int bg_color_;
264 QTimer * delay_refresh_;
266 bool finished_generating_;
268 /// We don't own this
269 static lyx::Converter const * pconverter_;
273 lyx::Converter const * PreviewLoader::Impl::pconverter_;
277 // The public interface, defined in PreviewLoader.h
280 PreviewLoader::PreviewLoader(Buffer const & b)
281 : pimpl_(new Impl(*this, b))
285 PreviewLoader::~PreviewLoader()
291 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
293 return pimpl_->preview(latex_snippet);
297 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
299 return pimpl_->status(latex_snippet);
303 void PreviewLoader::add(string const & latex_snippet) const
305 pimpl_->add(latex_snippet);
309 void PreviewLoader::remove(string const & latex_snippet) const
311 pimpl_->remove(latex_snippet);
315 void PreviewLoader::startLoading(bool wait) const
317 pimpl_->startLoading(wait);
321 void PreviewLoader::refreshPreviews()
323 pimpl_->refreshPreviews();
327 boost::signals2::connection PreviewLoader::connect(slot_type const & slot) const
329 return pimpl_->imageReady.connect(slot);
333 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
335 pimpl_->imageReady(pimage);
339 Buffer const & PreviewLoader::buffer() const
341 return pimpl_->buffer();
344 } // namespace graphics
348 // The details of the Impl
349 // =======================
353 class IncrementedFileName {
355 IncrementedFileName(string const & to_format,
356 string const & filename_base)
357 : to_format_(to_format), base_(filename_base), counter_(1)
360 SnippetPair const operator()(string const & snippet)
363 os << base_ << counter_++ << '.' << to_format_;
364 string const file = os.str();
366 return make_pair(snippet, FileName(file));
370 string const & to_format_;
371 string const & base_;
376 InProgress::InProgress(string const & filename_base,
377 PendingSnippets const & pending,
378 string const & to_format)
380 metrics_file(filename_base + ".metrics"),
381 snippets(pending.size())
383 PendingSnippets::const_iterator pit = pending.begin();
384 PendingSnippets::const_iterator pend = pending.end();
385 BitmapFile::iterator sit = snippets.begin();
387 transform(pit, pend, sit,
388 IncrementedFileName(to_format, filename_base));
392 void InProgress::stop() const
395 ForkedCallsController::kill(pid, 0);
397 if (!metrics_file.empty())
398 metrics_file.removeFile();
400 BitmapFile::const_iterator vit = snippets.begin();
401 BitmapFile::const_iterator vend = snippets.end();
402 for (; vit != vend; ++vit) {
403 if (!vit->second.empty())
404 vit->second.removeFile();
414 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
415 : parent_(p), buffer_(b), finished_generating_(true)
417 font_scaling_factor_ = int(buffer_.fontScalingFactor());
419 fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
420 bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
423 bg_color_ = 0xffffff;
426 pconverter_ = setConverter("lyxpreview");
428 delay_refresh_ = new QTimer(&parent_);
429 delay_refresh_->setSingleShot(true);
430 QObject::connect(delay_refresh_, SIGNAL(timeout()),
431 &parent_, SLOT(refreshPreviews()));
435 PreviewLoader::Impl::~Impl()
437 delete delay_refresh_;
439 InProgressProcesses::iterator ipit = in_progress_.begin();
440 InProgressProcesses::iterator ipend = in_progress_.end();
442 for (; ipit != ipend; ++ipit)
448 PreviewLoader::Impl::preview(string const & latex_snippet) const
450 int fs = int(buffer_.fontScalingFactor());
454 fg = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
455 bg = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
457 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
458 // Schedule refresh of all previews on zoom or color changes.
459 // The previews are regenerated only after the zoom factor
460 // has not been changed for about 1 second.
463 delay_refresh_->start(1000);
465 // Don't try to access the cache until we are done.
466 if (delay_refresh_->isActive() || !finished_generating_)
468 Cache::const_iterator it = cache_.find(latex_snippet);
469 return (it == cache_.end()) ? 0 : it->second.get();
473 void PreviewLoader::Impl::refreshPreviews()
475 font_scaling_factor_ = int(buffer_.fontScalingFactor());
476 // Reschedule refresh until the previous process completed.
477 if (!finished_generating_) {
478 delay_refresh_->start(1000);
481 Cache::const_iterator cit = cache_.begin();
482 Cache::const_iterator cend = cache_.end();
484 parent_.remove((cit++)->first);
485 finished_generating_ = false;
486 buffer_.updatePreviews();
494 FindSnippet(string const & s) : snippet_(s) {}
495 bool operator()(InProgressProcess const & process) const
497 BitmapFile const & snippets = process.second.snippets;
498 BitmapFile::const_iterator beg = snippets.begin();
499 BitmapFile::const_iterator end = snippets.end();
500 return find_if(beg, end, FindFirst(snippet_)) != end;
504 string const snippet_;
509 PreviewLoader::Status
510 PreviewLoader::Impl::status(string const & latex_snippet) const
512 Cache::const_iterator cit = cache_.find(latex_snippet);
513 if (cit != cache_.end())
516 PendingSnippets::const_iterator pit = pending_.begin();
517 PendingSnippets::const_iterator pend = pending_.end();
519 pit = find(pit, pend, latex_snippet);
523 InProgressProcesses::const_iterator ipit = in_progress_.begin();
524 InProgressProcesses::const_iterator ipend = in_progress_.end();
526 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
534 void PreviewLoader::Impl::add(string const & latex_snippet)
536 if (!pconverter_ || status(latex_snippet) != NotFound)
539 string const snippet = trim(latex_snippet);
543 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
545 pending_.push_back(snippet);
553 EraseSnippet(string const & s) : snippet_(s) {}
554 void operator()(InProgressProcess & process)
556 BitmapFile & snippets = process.second.snippets;
557 BitmapFile::iterator it = snippets.begin();
558 BitmapFile::iterator end = snippets.end();
560 it = find_if(it, end, FindFirst(snippet_));
562 snippets.erase(it, it+1);
566 string const & snippet_;
572 void PreviewLoader::Impl::remove(string const & latex_snippet)
574 Cache::iterator cit = cache_.find(latex_snippet);
575 if (cit != cache_.end())
578 PendingSnippets::iterator pit = pending_.begin();
579 PendingSnippets::iterator pend = pending_.end();
581 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
583 InProgressProcesses::iterator ipit = in_progress_.begin();
584 InProgressProcesses::iterator ipend = in_progress_.end();
586 for_each(ipit, ipend, EraseSnippet(latex_snippet));
588 while (ipit != ipend) {
589 InProgressProcesses::iterator curr = ipit++;
590 if (curr->second.snippets.empty())
591 in_progress_.erase(curr);
596 void PreviewLoader::Impl::startLoading(bool wait)
598 if (pending_.empty() || !pconverter_)
601 // Only start the process off after the buffer is loaded from file.
602 if (!buffer_.isFullyLoaded())
605 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
607 // As used by the LaTeX file and by the resulting image files
608 FileName const directory(buffer_.temppath());
610 FileName const latexfile = unique_tex_filename(directory);
611 string const filename_base = removeExtension(latexfile.absFileName());
613 // Create an InProgress instance to place in the map of all
614 // such processes if it starts correctly.
615 InProgress inprogress(filename_base, pending_, pconverter_->to());
617 // clear pending_, so we're ready to start afresh.
620 // Output the LaTeX file.
621 // we use the encoding of the buffer
622 Encoding const & enc = buffer_.params().encoding();
624 try { of.reset(enc.iconvName()); }
625 catch (iconv_codecvt_facet_exception const & e) {
626 LYXERR0("Caught iconv exception: " << e.what()
627 << "\nUnable to create LaTeX file: " << latexfile);
632 OutputParams runparams(&enc);
633 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
635 if (!openFileWrite(of, latexfile))
639 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
640 << "Unable to create LaTeX file\n" << latexfile);
643 of << "\\batchmode\n";
645 // Set \jobname of previews to the document name (see bug 9627)
646 of << "\\def\\jobname{"
647 << from_utf8(changeExtension(buffer_.latexName(true), ""))
650 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
651 string latexparam = "";
652 bool docformat = !buffer_.params().default_output_format.empty()
653 && buffer_.params().default_output_format != "default";
654 // Use LATEX flavor if the document does not specify a specific
655 // output format (see bug 9371).
656 OutputParams::FLAVOR flavor = docformat
657 ? buffer_.params().getOutputFlavor()
658 : OutputParams::LATEX;
659 if (buffer_.params().encoding().package() == Encoding::japanese) {
660 latexparam = " --latex=platex";
661 flavor = OutputParams::LATEX;
663 else if (buffer_.params().useNonTeXFonts) {
664 if (flavor == OutputParams::LUATEX)
665 latexparam = " --latex=lualatex";
667 flavor = OutputParams::XETEX;
668 latexparam = " --latex=xelatex";
673 case OutputParams::PDFLATEX:
674 latexparam = " --latex=pdflatex";
676 case OutputParams::XETEX:
677 latexparam = " --latex=xelatex";
679 case OutputParams::LUATEX:
680 latexparam = " --latex=lualatex";
682 case OutputParams::DVILUATEX:
683 latexparam = " --latex=dvilualatex";
686 flavor = OutputParams::LATEX;
689 dumpPreamble(os, flavor);
690 // handle inputenc etc.
691 // I think, this is already hadled by dumpPreamble(): Kornel
692 // buffer_.params().writeEncodingPreamble(os, features);
693 of << "\n\\begin{document}\n";
694 dumpData(of, inprogress.snippets);
695 of << "\n\\end{document}\n";
698 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
699 << "File was not closed properly.");
703 // The conversion command.
705 cs << pconverter_->command()
706 << " " << quoteName(latexfile.toFilesystemEncoding())
707 << " --dpi " << font_scaling_factor_;
710 // The colors should be customizable.
711 if (!buffer_.isExporting()) {
712 ColorCode const fg = PreviewLoader::foregroundColor();
713 ColorCode const bg = PreviewLoader::backgroundColor();
714 cs << " --fg " << theApp()->hexName(fg)
715 << " --bg " << theApp()->hexName(bg);
719 if (buffer_.params().bibtex_command != "default")
720 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
721 else if (buffer_.params().encoding().package() == Encoding::japanese)
722 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
724 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
725 if (buffer_.params().bufferFormat() == "lilypond-book")
728 string const command = cs.str();
731 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
732 int ret = call.startScript(ForkedProcess::Wait, command);
733 static atomic_int fake((2^20) + 1);
735 inprogress.pid = pid;
736 inprogress.command = command;
737 in_progress_[pid] = inprogress;
738 finishedGenerating(pid, ret);
742 // Initiate the conversion from LaTeX to bitmap images files.
743 ForkedCall::SignalTypePtr
744 convert_ptr(new ForkedCall::SignalType);
745 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
747 ForkedCall call(buffer_.filePath());
748 int ret = call.startScript(command, convert_ptr);
751 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
752 << "Unable to start process\n" << command);
756 // Store the generation process in a list of all such processes
757 inprogress.pid = call.pid();
758 inprogress.command = command;
759 in_progress_[inprogress.pid] = inprogress;
763 double PreviewLoader::displayPixelRatio() const
765 return buffer().params().display_pixel_ratio;
768 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
771 InProgressProcesses::iterator git = in_progress_.find(pid);
772 if (git == in_progress_.end()) {
773 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
774 "data for PID " << pid << endl;
775 finished_generating_ = true;
779 string const command = git->second.command;
780 string const status = retval > 0 ? "failed" : "succeeded";
781 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
782 << retval << "): processing " << status
783 << " for " << command);
785 in_progress_.erase(git);
786 finished_generating_ = true;
790 // Read the metrics file, if it exists
791 vector<double> ascent_fractions(git->second.snippets.size());
792 setAscentFractions(ascent_fractions, git->second.metrics_file);
794 // Add these newly generated bitmap files to the cache and
795 // start loading them into LyX.
796 BitmapFile::const_iterator it = git->second.snippets.begin();
797 BitmapFile::const_iterator end = git->second.snippets.end();
799 list<PreviewImagePtr> newimages;
801 int metrics_counter = 0;
802 for (; it != end; ++it, ++metrics_counter) {
803 string const & snip = it->first;
804 FileName const & file = it->second;
805 double af = ascent_fractions[metrics_counter];
807 // Add the image to the cache only if it's actually present
808 // and not empty (an empty image is signaled by af < 0)
809 if (af >= 0 && file.isReadableFile()) {
810 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
813 newimages.push_back(ptr);
818 // Remove the item from the list of still-executing processes.
819 in_progress_.erase(git);
821 // Tell the outside world
822 list<PreviewImagePtr>::const_reverse_iterator
823 nit = newimages.rbegin();
824 list<PreviewImagePtr>::const_reverse_iterator
825 nend = newimages.rend();
826 for (; nit != nend; ++nit) {
827 imageReady(*nit->get());
829 finished_generating_ = true;
833 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
835 // Dump the preamble only.
836 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
837 OutputParams runparams(&buffer_.params().encoding());
838 runparams.flavor = flavor;
839 runparams.nice = true;
840 runparams.moving_arg = true;
841 runparams.free_spacing = true;
842 runparams.is_child = buffer_.parent();
843 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
845 // FIXME! This is a HACK! The proper fix is to control the 'true'
846 // passed to WriteStream below:
847 // int InsetMathNest::latex(Buffer const &, odocstream & os,
848 // OutputParams const & runparams) const
850 // WriteStream wi(os, runparams.moving_arg, true);
855 << "\\def\\lyxlock{}\n"
858 // All equation labels appear as "(#)" + preview.sty's rendering of
860 if (lyxrc.preview_hashed_labels)
861 os << "\\renewcommand{\\theequation}{\\#}\n";
863 // Use the preview style file to ensure that each snippet appears on a
865 // Also support PDF output (automatically generated e.g. when
866 // \usepackage[pdftex]{hyperref} is used and XeTeX.
868 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
873 void PreviewLoader::Impl::dumpData(odocstream & os,
874 BitmapFile const & vec) const
879 BitmapFile::const_iterator it = vec.begin();
880 BitmapFile::const_iterator end = vec.end();
882 for (; it != end; ++it) {
884 os << "\\begin{preview}\n"
885 << from_utf8(it->first)
886 << "\n\\end{preview}\n\n";
890 } // namespace graphics
893 #include "moc_PreviewLoader.cpp"