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. This is thread-safe.
96 static nullptr_t no_conv = [&]{
97 LYXERR0("PreviewLoader::startLoading()\n"
98 << "No converter from \"" << from
99 << "\" format has been defined.");
107 void setAscentFractions(vector<double> & ascent_fractions,
108 FileName const & metrics_file)
110 // If all else fails, then the images will have equal ascents and
112 vector<double>::iterator it = ascent_fractions.begin();
113 vector<double>::iterator end = ascent_fractions.end();
116 ifstream in(metrics_file.toFilesystemEncoding().c_str());
118 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
119 << "Unable to open file!");
125 int snippet_counter = 1;
126 while (!in.eof() && it != end) {
129 double ascent_fraction;
131 in >> snippet >> id >> ascent_fraction;
137 error = snippet != "Snippet";
141 error = id != snippet_counter;
145 *it = ascent_fraction;
152 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
153 << "Error reading file!\n");
161 FindFirst(string const & comp) : comp_(comp) {}
162 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
168 /// Store info on a currently executing, forked process.
172 InProgress() : pid(0) {}
174 InProgress(string const & filename_base,
175 PendingSnippets const & pending,
176 string const & to_format);
177 /// Remove any files left lying around and kill the forked process.
185 FileName metrics_file;
190 typedef map<pid_t, InProgress> InProgressProcesses;
192 typedef InProgressProcesses::value_type InProgressProcess;
201 class PreviewLoader::Impl : public boost::signals2::trackable {
204 Impl(PreviewLoader & p, Buffer const & b);
205 /// Stop any InProgress items still executing.
208 PreviewImage const * preview(string const & latex_snippet) const;
210 PreviewLoader::Status status(string const & latex_snippet) const;
212 void add(string const & latex_snippet);
214 void remove(string const & latex_snippet);
215 /// \p wait whether to wait for the process to complete or, instead,
216 /// to do it in the background.
217 void startLoading(bool wait = false);
219 void refreshPreviews();
221 /// Emit this signal when an image is ready for display.
222 boost::signals2::signal<void(PreviewImage const &)> imageReady;
224 Buffer const & buffer() const { return buffer_; }
227 /// Called by the ForkedCall process that generated the bitmap files.
228 void finishedGenerating(pid_t, int);
230 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
232 void dumpData(odocstream &, BitmapFile const &) const;
234 /** cache_ allows easy retrieval of already-generated images
235 * using the LaTeX snippet as the identifier.
237 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
239 typedef map<string, PreviewImagePtr> Cache;
243 /** pending_ stores the LaTeX snippets in anticipation of them being
244 * sent to the converter.
246 PendingSnippets pending_;
248 /** in_progress_ stores all forked processes so that we can proceed
250 The map uses the conversion commands as its identifiers.
252 InProgressProcesses in_progress_;
255 PreviewLoader & parent_;
257 Buffer const & buffer_;
259 mutable int font_scaling_factor_;
261 mutable int fg_color_;
263 mutable int bg_color_;
265 QTimer * delay_refresh_;
267 bool finished_generating_;
269 /// We don't own this
270 static lyx::Converter const * pconverter_;
274 lyx::Converter const * PreviewLoader::Impl::pconverter_;
278 // The public interface, defined in PreviewLoader.h
281 PreviewLoader::PreviewLoader(Buffer const & b)
282 : pimpl_(new Impl(*this, b))
286 PreviewLoader::~PreviewLoader()
292 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
294 return pimpl_->preview(latex_snippet);
298 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
300 return pimpl_->status(latex_snippet);
304 void PreviewLoader::add(string const & latex_snippet) const
306 pimpl_->add(latex_snippet);
310 void PreviewLoader::remove(string const & latex_snippet) const
312 pimpl_->remove(latex_snippet);
316 void PreviewLoader::startLoading(bool wait) const
318 pimpl_->startLoading(wait);
322 void PreviewLoader::refreshPreviews()
324 pimpl_->refreshPreviews();
328 boost::signals2::connection PreviewLoader::connect(slot_type const & slot) const
330 return pimpl_->imageReady.connect(slot);
334 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
336 pimpl_->imageReady(pimage);
340 Buffer const & PreviewLoader::buffer() const
342 return pimpl_->buffer();
345 } // namespace graphics
349 // The details of the Impl
350 // =======================
354 class IncrementedFileName {
356 IncrementedFileName(string const & to_format,
357 string const & filename_base)
358 : to_format_(to_format), base_(filename_base), counter_(1)
361 SnippetPair const operator()(string const & snippet)
364 os << base_ << counter_++ << '.' << to_format_;
365 string const file = os.str();
367 return make_pair(snippet, FileName(file));
371 string const & to_format_;
372 string const & base_;
377 InProgress::InProgress(string const & filename_base,
378 PendingSnippets const & pending,
379 string const & to_format)
381 metrics_file(filename_base + ".metrics"),
382 snippets(pending.size())
384 PendingSnippets::const_iterator pit = pending.begin();
385 PendingSnippets::const_iterator pend = pending.end();
386 BitmapFile::iterator sit = snippets.begin();
388 transform(pit, pend, sit,
389 IncrementedFileName(to_format, filename_base));
393 void InProgress::stop() const
396 ForkedCallsController::kill(pid, 0);
398 if (!metrics_file.empty())
399 metrics_file.removeFile();
401 BitmapFile::const_iterator vit = snippets.begin();
402 BitmapFile::const_iterator vend = snippets.end();
403 for (; vit != vend; ++vit) {
404 if (!vit->second.empty())
405 vit->second.removeFile();
415 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
416 : parent_(p), buffer_(b), finished_generating_(true)
418 font_scaling_factor_ = int(buffer_.fontScalingFactor());
420 fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
421 bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
424 bg_color_ = 0xffffff;
427 pconverter_ = setConverter("lyxpreview");
429 delay_refresh_ = new QTimer(&parent_);
430 delay_refresh_->setSingleShot(true);
431 QObject::connect(delay_refresh_, SIGNAL(timeout()),
432 &parent_, SLOT(refreshPreviews()));
436 PreviewLoader::Impl::~Impl()
438 delete delay_refresh_;
440 InProgressProcesses::iterator ipit = in_progress_.begin();
441 InProgressProcesses::iterator ipend = in_progress_.end();
443 for (; ipit != ipend; ++ipit)
449 PreviewLoader::Impl::preview(string const & latex_snippet) const
451 int fs = int(buffer_.fontScalingFactor());
455 fg = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
456 bg = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
458 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
459 // Schedule refresh of all previews on zoom or color changes.
460 // The previews are regenerated only after the zoom factor
461 // has not been changed for about 1 second.
464 delay_refresh_->start(1000);
466 // Don't try to access the cache until we are done.
467 if (delay_refresh_->isActive() || !finished_generating_)
469 Cache::const_iterator it = cache_.find(latex_snippet);
470 return (it == cache_.end()) ? 0 : it->second.get();
474 void PreviewLoader::Impl::refreshPreviews()
476 font_scaling_factor_ = int(buffer_.fontScalingFactor());
477 // Reschedule refresh until the previous process completed.
478 if (!finished_generating_) {
479 delay_refresh_->start(1000);
482 Cache::const_iterator cit = cache_.begin();
483 Cache::const_iterator cend = cache_.end();
485 parent_.remove((cit++)->first);
486 finished_generating_ = false;
487 buffer_.updatePreviews();
495 FindSnippet(string const & s) : snippet_(s) {}
496 bool operator()(InProgressProcess const & process) const
498 BitmapFile const & snippets = process.second.snippets;
499 BitmapFile::const_iterator beg = snippets.begin();
500 BitmapFile::const_iterator end = snippets.end();
501 return find_if(beg, end, FindFirst(snippet_)) != end;
505 string const snippet_;
510 PreviewLoader::Status
511 PreviewLoader::Impl::status(string const & latex_snippet) const
513 Cache::const_iterator cit = cache_.find(latex_snippet);
514 if (cit != cache_.end())
517 PendingSnippets::const_iterator pit = pending_.begin();
518 PendingSnippets::const_iterator pend = pending_.end();
520 pit = find(pit, pend, latex_snippet);
524 InProgressProcesses::const_iterator ipit = in_progress_.begin();
525 InProgressProcesses::const_iterator ipend = in_progress_.end();
527 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
535 void PreviewLoader::Impl::add(string const & latex_snippet)
537 if (!pconverter_ || status(latex_snippet) != NotFound)
540 string const snippet = trim(latex_snippet);
544 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
546 pending_.push_back(snippet);
554 EraseSnippet(string const & s) : snippet_(s) {}
555 void operator()(InProgressProcess & process)
557 BitmapFile & snippets = process.second.snippets;
558 BitmapFile::iterator it = snippets.begin();
559 BitmapFile::iterator end = snippets.end();
561 it = find_if(it, end, FindFirst(snippet_));
563 snippets.erase(it, it+1);
567 string const & snippet_;
573 void PreviewLoader::Impl::remove(string const & latex_snippet)
575 Cache::iterator cit = cache_.find(latex_snippet);
576 if (cit != cache_.end())
579 PendingSnippets::iterator pit = pending_.begin();
580 PendingSnippets::iterator pend = pending_.end();
582 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
584 InProgressProcesses::iterator ipit = in_progress_.begin();
585 InProgressProcesses::iterator ipend = in_progress_.end();
587 for_each(ipit, ipend, EraseSnippet(latex_snippet));
589 while (ipit != ipend) {
590 InProgressProcesses::iterator curr = ipit++;
591 if (curr->second.snippets.empty())
592 in_progress_.erase(curr);
597 void PreviewLoader::Impl::startLoading(bool wait)
599 if (pending_.empty() || !pconverter_)
602 // Only start the process off after the buffer is loaded from file.
603 if (!buffer_.isFullyLoaded())
606 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
608 // As used by the LaTeX file and by the resulting image files
609 FileName const directory(buffer_.temppath());
611 FileName const latexfile = unique_tex_filename(directory);
612 string const filename_base = removeExtension(latexfile.absFileName());
614 // Create an InProgress instance to place in the map of all
615 // such processes if it starts correctly.
616 InProgress inprogress(filename_base, pending_, pconverter_->to());
618 // clear pending_, so we're ready to start afresh.
621 // Output the LaTeX file.
622 // we use the encoding of the buffer
623 Encoding const & enc = buffer_.params().encoding();
625 try { of.reset(enc.iconvName()); }
626 catch (iconv_codecvt_facet_exception const & e) {
627 LYXERR0("Caught iconv exception: " << e.what()
628 << "\nUnable to create LaTeX file: " << latexfile);
633 OutputParams runparams(&enc);
634 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
636 if (!openFileWrite(of, latexfile))
640 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
641 << "Unable to create LaTeX file\n" << latexfile);
644 of << "\\batchmode\n";
646 // Set \jobname of previews to the document name (see bug 9627)
647 of << "\\def\\jobname{"
648 << from_utf8(changeExtension(buffer_.latexName(true), ""))
651 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
652 string latexparam = "";
653 bool docformat = !buffer_.params().default_output_format.empty()
654 && buffer_.params().default_output_format != "default";
655 // Use LATEX flavor if the document does not specify a specific
656 // output format (see bug 9371).
657 OutputParams::FLAVOR flavor = docformat
658 ? buffer_.params().getOutputFlavor()
659 : OutputParams::LATEX;
660 if (buffer_.params().encoding().package() == Encoding::japanese) {
661 latexparam = " --latex=platex";
662 flavor = OutputParams::LATEX;
664 else if (buffer_.params().useNonTeXFonts) {
665 if (flavor == OutputParams::LUATEX)
666 latexparam = " --latex=lualatex";
668 flavor = OutputParams::XETEX;
669 latexparam = " --latex=xelatex";
674 case OutputParams::PDFLATEX:
675 latexparam = " --latex=pdflatex";
677 case OutputParams::XETEX:
678 latexparam = " --latex=xelatex";
680 case OutputParams::LUATEX:
681 latexparam = " --latex=lualatex";
683 case OutputParams::DVILUATEX:
684 latexparam = " --latex=dvilualatex";
687 flavor = OutputParams::LATEX;
690 dumpPreamble(os, flavor);
691 // handle inputenc etc.
692 // I think, this is already hadled by dumpPreamble(): Kornel
693 // buffer_.params().writeEncodingPreamble(os, features);
694 of << "\n\\begin{document}\n";
695 dumpData(of, inprogress.snippets);
696 of << "\n\\end{document}\n";
699 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
700 << "File was not closed properly.");
704 // The conversion command.
706 cs << pconverter_->command()
707 << " " << quoteName(latexfile.toFilesystemEncoding())
708 << " --dpi " << font_scaling_factor_;
711 // The colors should be customizable.
712 if (!buffer_.isExporting()) {
713 ColorCode const fg = PreviewLoader::foregroundColor();
714 ColorCode const bg = PreviewLoader::backgroundColor();
715 cs << " --fg " << theApp()->hexName(fg)
716 << " --bg " << theApp()->hexName(bg);
720 if (buffer_.params().bibtex_command != "default")
721 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
722 else if (buffer_.params().encoding().package() == Encoding::japanese)
723 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
725 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
726 if (buffer_.params().bufferFormat() == "lilypond-book")
729 string const command = cs.str();
732 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
733 int ret = call.startScript(ForkedProcess::Wait, command);
734 static atomic_int fake((2^20) + 1);
736 inprogress.pid = pid;
737 inprogress.command = command;
738 in_progress_[pid] = inprogress;
739 finishedGenerating(pid, ret);
743 // Initiate the conversion from LaTeX to bitmap images files.
744 ForkedCall::SignalTypePtr
745 convert_ptr(new ForkedCall::SignalType);
746 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
748 ForkedCall call(buffer_.filePath());
749 int ret = call.startScript(command, convert_ptr);
752 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
753 << "Unable to start process\n" << command);
757 // Store the generation process in a list of all such processes
758 inprogress.pid = call.pid();
759 inprogress.command = command;
760 in_progress_[inprogress.pid] = inprogress;
764 double PreviewLoader::displayPixelRatio() const
766 return buffer().params().display_pixel_ratio;
769 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
772 InProgressProcesses::iterator git = in_progress_.find(pid);
773 if (git == in_progress_.end()) {
774 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
775 "data for PID " << pid << endl;
776 finished_generating_ = true;
780 string const command = git->second.command;
781 string const status = retval > 0 ? "failed" : "succeeded";
782 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
783 << retval << "): processing " << status
784 << " for " << command);
786 in_progress_.erase(git);
787 finished_generating_ = true;
791 // Read the metrics file, if it exists
792 vector<double> ascent_fractions(git->second.snippets.size());
793 setAscentFractions(ascent_fractions, git->second.metrics_file);
795 // Add these newly generated bitmap files to the cache and
796 // start loading them into LyX.
797 BitmapFile::const_iterator it = git->second.snippets.begin();
798 BitmapFile::const_iterator end = git->second.snippets.end();
800 list<PreviewImagePtr> newimages;
802 int metrics_counter = 0;
803 for (; it != end; ++it, ++metrics_counter) {
804 string const & snip = it->first;
805 FileName const & file = it->second;
806 double af = ascent_fractions[metrics_counter];
808 // Add the image to the cache only if it's actually present
809 // and not empty (an empty image is signaled by af < 0)
810 if (af >= 0 && file.isReadableFile()) {
811 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
814 newimages.push_back(ptr);
819 // Remove the item from the list of still-executing processes.
820 in_progress_.erase(git);
822 // Tell the outside world
823 list<PreviewImagePtr>::const_reverse_iterator
824 nit = newimages.rbegin();
825 list<PreviewImagePtr>::const_reverse_iterator
826 nend = newimages.rend();
827 for (; nit != nend; ++nit) {
828 imageReady(*nit->get());
830 finished_generating_ = true;
834 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
836 // Dump the preamble only.
837 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
838 OutputParams runparams(&buffer_.params().encoding());
839 runparams.flavor = flavor;
840 runparams.nice = true;
841 runparams.moving_arg = true;
842 runparams.free_spacing = true;
843 runparams.is_child = buffer_.parent();
844 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
846 // FIXME! This is a HACK! The proper fix is to control the 'true'
847 // passed to WriteStream below:
848 // int InsetMathNest::latex(Buffer const &, odocstream & os,
849 // OutputParams const & runparams) const
851 // WriteStream wi(os, runparams.moving_arg, true);
856 << "\\def\\lyxlock{}\n"
859 // All equation labels appear as "(#)" + preview.sty's rendering of
861 if (lyxrc.preview_hashed_labels)
862 os << "\\renewcommand{\\theequation}{\\#}\n";
864 // Use the preview style file to ensure that each snippet appears on a
866 // Also support PDF output (automatically generated e.g. when
867 // \usepackage[pdftex]{hyperref} is used and XeTeX.
869 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
874 void PreviewLoader::Impl::dumpData(odocstream & os,
875 BitmapFile const & vec) const
880 BitmapFile::const_iterator it = vec.begin();
881 BitmapFile::const_iterator end = vec.end();
883 for (; it != end; ++it) {
885 os << "\\begin{preview}\n"
886 << from_utf8(it->first)
887 << "\n\\end{preview}\n\n";
891 } // namespace graphics
894 #include "moc_PreviewLoader.cpp"