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 std::function<SnippetPair (string const &)> IncrementedFileName
323 (string const & to_format, string const & filename_base)
325 return [&to_format, &filename_base](string const & snippet)
327 static int counter_ = 1;
329 os << filename_base << counter_++ << '.' << to_format;
330 string const file = os.str();
331 return make_pair(snippet, FileName(file));
336 InProgress::InProgress(string const & filename_base,
337 PendingSnippets const & pending,
338 string const & to_format)
339 : metrics_file(filename_base + ".metrics"),
340 snippets(pending.size()), pid(0)
342 PendingSnippets::const_iterator pit = pending.begin();
343 PendingSnippets::const_iterator pend = pending.end();
344 BitmapFile::iterator sit = snippets.begin();
346 transform(pit, pend, sit,
347 IncrementedFileName(to_format, filename_base));
351 void InProgress::stop() const
354 ForkedCallsController::kill(pid, 0);
356 if (!metrics_file.empty())
357 metrics_file.removeFile();
359 BitmapFile::const_iterator vit = snippets.begin();
360 BitmapFile::const_iterator vend = snippets.end();
361 for (; vit != vend; ++vit) {
362 if (!vit->second.empty())
363 vit->second.removeFile();
373 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
374 : parent_(p), buffer_(b), finished_generating_(true)
376 font_scaling_factor_ = int(buffer_.fontScalingFactor());
378 fg_color_ = convert(theApp()->hexName(foregroundColor()).c_str(), 16);
379 bg_color_ = convert(theApp()->hexName(backgroundColor()).c_str(), 16);
382 bg_color_ = 0xffffff;
385 pconverter_ = setConverter("lyxpreview");
387 delay_refresh_ = new QTimer(&parent_);
388 delay_refresh_->setSingleShot(true);
389 QObject::connect(delay_refresh_, SIGNAL(timeout()),
390 &parent_, SLOT(refreshPreviews()));
394 lyx::Converter const * PreviewLoader::Impl::setConverter(string const & from)
396 typedef vector<string> FmtList;
397 FmtList const & loadableFormats = graphics::Cache::get().loadableFormats();
398 FmtList::const_iterator it = loadableFormats.begin();
399 FmtList::const_iterator const end = loadableFormats.end();
401 for (; it != end; ++it) {
402 string const to = *it;
406 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
411 // Show the error only once. This is thread-safe.
412 static nullptr_t no_conv = [&]{
413 LYXERR0("PreviewLoader::startLoading()\n"
414 << "No converter from \"" << from
415 << "\" format has been defined.");
423 PreviewLoader::Impl::~Impl()
425 delete delay_refresh_;
427 InProgressProcesses::iterator ipit = in_progress_.begin();
428 InProgressProcesses::iterator ipend = in_progress_.end();
430 for (; ipit != ipend; ++ipit)
436 PreviewLoader::Impl::preview(string const & latex_snippet) const
438 int fs = int(buffer_.fontScalingFactor());
442 fg = convert(theApp()->hexName(foregroundColor()).c_str(), 16);
443 bg = convert(theApp()->hexName(backgroundColor()).c_str(), 16);
445 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
446 // Schedule refresh of all previews on zoom or color changes.
447 // The previews are regenerated only after the zoom factor
448 // has not been changed for about 1 second.
451 delay_refresh_->start(1000);
453 // Don't try to access the cache until we are done.
454 if (delay_refresh_->isActive() || !finished_generating_)
457 Cache::const_iterator it = cache_.find(latex_snippet);
458 return (it == cache_.end()) ? nullptr : it->second.get();
462 void PreviewLoader::Impl::refreshPreviews()
464 font_scaling_factor_ = int(buffer_.fontScalingFactor());
465 // Reschedule refresh until the previous process completed.
466 if (!finished_generating_) {
467 delay_refresh_->start(1000);
470 Cache::const_iterator cit = cache_.begin();
471 Cache::const_iterator cend = cache_.end();
473 parent_.remove((cit++)->first);
474 finished_generating_ = false;
475 buffer_.updatePreviews();
481 std::function<bool (InProgressProcess const &)> FindSnippet(string const & s)
483 return [&s](InProgressProcess const & process) {
484 BitmapFile const & snippets = process.second.snippets;
485 BitmapFile::const_iterator beg = snippets.begin();
486 BitmapFile::const_iterator end = snippets.end();
487 return find_if(beg, end, FindFirst(s)) != end;
493 PreviewLoader::Status
494 PreviewLoader::Impl::status(string const & latex_snippet) const
496 Cache::const_iterator cit = cache_.find(latex_snippet);
497 if (cit != cache_.end())
500 PendingSnippets::const_iterator pit = pending_.begin();
501 PendingSnippets::const_iterator pend = pending_.end();
503 pit = find(pit, pend, latex_snippet);
507 InProgressProcesses::const_iterator ipit = in_progress_.begin();
508 InProgressProcesses::const_iterator ipend = in_progress_.end();
510 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
518 void PreviewLoader::Impl::add(string const & latex_snippet)
520 if (!pconverter_ || status(latex_snippet) != NotFound)
523 string const snippet = trim(latex_snippet);
527 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
529 pending_.push_back(snippet);
535 std::function<void (InProgressProcess &)> EraseSnippet(string const & s) {
536 return [&s](InProgressProcess & process) {
537 BitmapFile & snippets = process.second.snippets;
538 BitmapFile::iterator it = snippets.begin();
539 BitmapFile::iterator end = snippets.end();
541 it = find_if(it, end, FindFirst(s));
543 snippets.erase(it, it+1);
550 void PreviewLoader::Impl::remove(string const & latex_snippet)
552 Cache::iterator cit = cache_.find(latex_snippet);
553 if (cit != cache_.end())
556 PendingSnippets::iterator pit = pending_.begin();
557 PendingSnippets::iterator pend = pending_.end();
559 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
561 InProgressProcesses::iterator ipit = in_progress_.begin();
562 InProgressProcesses::iterator ipend = in_progress_.end();
564 for_each(ipit, ipend, EraseSnippet(latex_snippet));
566 while (ipit != ipend) {
567 InProgressProcesses::iterator curr = ipit++;
568 if (curr->second.snippets.empty())
569 in_progress_.erase(curr);
574 void PreviewLoader::Impl::startLoading(bool wait)
576 if (pending_.empty() || !pconverter_)
579 // Only start the process off after the buffer is loaded from file.
580 if (!buffer_.isFullyLoaded())
583 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
585 // As used by the LaTeX file and by the resulting image files
586 FileName const directory(buffer_.temppath());
588 FileName const latexfile = unique_tex_filename(directory);
589 string const filename_base = removeExtension(latexfile.absFileName());
591 // Create an InProgress instance to place in the map of all
592 // such processes if it starts correctly.
593 InProgress inprogress(filename_base, pending_, pconverter_->to());
595 // clear pending_, so we're ready to start afresh.
598 // Output the LaTeX file.
599 // we use the encoding of the buffer
600 Encoding const & enc = buffer_.params().encoding();
602 try { of.reset(enc.iconvName()); }
603 catch (iconv_codecvt_facet_exception const & e) {
604 LYXERR0("Caught iconv exception: " << e.what()
605 << "\nUnable to create LaTeX file: " << latexfile);
610 OutputParams runparams(&enc);
611 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
613 if (!openFileWrite(of, latexfile))
617 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
618 << "Unable to create LaTeX file\n" << latexfile);
621 of << "\\batchmode\n";
623 // Set \jobname of previews to the document name (see bug 9627)
624 of << "\\def\\jobname{"
625 << from_utf8(changeExtension(buffer_.latexName(true), ""))
628 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
629 string latexparam = "";
630 bool docformat = !buffer_.params().default_output_format.empty()
631 && buffer_.params().default_output_format != "default";
632 // Use LATEX flavor if the document does not specify a specific
633 // output format (see bug 9371).
634 OutputParams::FLAVOR flavor = docformat
635 ? buffer_.params().getOutputFlavor()
636 : OutputParams::LATEX;
637 if (buffer_.params().encoding().package() == Encoding::japanese) {
638 latexparam = " --latex=platex";
639 flavor = OutputParams::LATEX;
641 else if (buffer_.params().useNonTeXFonts) {
642 if (flavor == OutputParams::LUATEX)
643 latexparam = " --latex=lualatex";
645 flavor = OutputParams::XETEX;
646 latexparam = " --latex=xelatex";
651 case OutputParams::PDFLATEX:
652 latexparam = " --latex=pdflatex";
654 case OutputParams::XETEX:
655 latexparam = " --latex=xelatex";
657 case OutputParams::LUATEX:
658 latexparam = " --latex=lualatex";
660 case OutputParams::DVILUATEX:
661 latexparam = " --latex=dvilualatex";
664 flavor = OutputParams::LATEX;
667 dumpPreamble(os, flavor);
668 // handle inputenc etc.
669 // I think this is already handled by dumpPreamble(): Kornel
670 // buffer_.params().writeEncodingPreamble(os, features);
671 of << "\n\\begin{document}\n";
672 dumpData(of, inprogress.snippets);
673 of << "\n\\end{document}\n";
676 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
677 << "File was not closed properly.");
681 // The conversion command.
683 cs << pconverter_->command()
684 << " " << quoteName(latexfile.toFilesystemEncoding())
685 << " --dpi " << font_scaling_factor_;
688 // The colors should be customizable.
689 if (!buffer_.isExporting()) {
690 ColorCode const fg = PreviewLoader::foregroundColor();
691 ColorCode const bg = PreviewLoader::backgroundColor();
692 cs << " --fg " << theApp()->hexName(fg)
693 << " --bg " << theApp()->hexName(bg);
697 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
698 if (buffer_.params().bufferFormat() == "lilypond-book")
701 string const command = cs.str();
704 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
705 int ret = call.startScript(ForkedProcess::Wait, command);
706 // PID_MAX_LIMIT is 2^22 so we start one after that
707 static atomic_int fake((1 << 22) + 1);
709 inprogress.pid = pid;
710 inprogress.command = command;
711 in_progress_[pid] = inprogress;
712 finishedGenerating(pid, ret);
716 // Initiate the conversion from LaTeX to bitmap images files.
717 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
718 convert_ptr->connect(ForkedProcess::slot([this](pid_t pid, int retval){
719 finishedGenerating(pid, retval);
720 }).track_foreign(trackable_.p()));
722 ForkedCall call(buffer_.filePath());
723 int ret = call.startScript(command, convert_ptr);
726 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
727 << "Unable to start process\n" << command);
731 // Store the generation process in a list of all such processes
732 inprogress.pid = call.pid();
733 inprogress.command = command;
734 in_progress_[inprogress.pid] = inprogress;
738 double PreviewLoader::displayPixelRatio() const
740 return buffer().params().display_pixel_ratio;
743 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
746 InProgressProcesses::iterator git = in_progress_.find(pid);
747 if (git == in_progress_.end()) {
748 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
749 "data for PID " << pid << endl;
750 finished_generating_ = true;
754 string const command = git->second.command;
755 string const status = retval > 0 ? "failed" : "succeeded";
756 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
757 << retval << "): processing " << status
758 << " for " << command);
760 in_progress_.erase(git);
761 finished_generating_ = true;
765 // Read the metrics file, if it exists
766 vector<double> ascent_fractions(git->second.snippets.size());
767 setAscentFractions(ascent_fractions, git->second.metrics_file);
769 // Add these newly generated bitmap files to the cache and
770 // start loading them into LyX.
771 BitmapFile::const_iterator it = git->second.snippets.begin();
772 BitmapFile::const_iterator end = git->second.snippets.end();
774 list<PreviewImagePtr> newimages;
776 size_t metrics_counter = 0;
777 for (; it != end; ++it, ++metrics_counter) {
778 string const & snip = it->first;
779 FileName const & file = it->second;
780 double af = ascent_fractions[metrics_counter];
782 // Add the image to the cache only if it's actually present
783 // and not empty (an empty image is signaled by af < 0)
784 if (af >= 0 && file.isReadableFile()) {
785 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
788 newimages.push_back(ptr);
793 // Remove the item from the list of still-executing processes.
794 in_progress_.erase(git);
796 // Tell the outside world
797 list<PreviewImagePtr>::const_reverse_iterator
798 nit = newimages.rbegin();
799 list<PreviewImagePtr>::const_reverse_iterator
800 nend = newimages.rend();
801 for (; nit != nend; ++nit) {
802 imageReady(*nit->get());
804 finished_generating_ = true;
808 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
810 // Dump the preamble only.
811 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
812 OutputParams runparams(&buffer_.params().encoding());
813 runparams.flavor = flavor;
814 runparams.nice = true;
815 runparams.moving_arg = true;
816 runparams.free_spacing = true;
817 runparams.is_child = buffer_.parent();
818 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
820 // FIXME! This is a HACK! The proper fix is to control the 'true'
821 // passed to WriteStream below:
822 // int InsetMathNest::latex(Buffer const &, odocstream & os,
823 // OutputParams const & runparams) const
825 // WriteStream wi(os, runparams.moving_arg, true);
830 << "\\def\\lyxlock{}\n"
833 // All equation labels appear as "(#)" + preview.sty's rendering of
835 if (lyxrc.preview_hashed_labels)
836 os << "\\renewcommand{\\theequation}{\\#}\n";
838 // Use the preview style file to ensure that each snippet appears on a
840 // Also support PDF output (automatically generated e.g. when
841 // \usepackage[pdftex]{hyperref} is used and XeTeX.
843 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
848 void PreviewLoader::Impl::dumpData(odocstream & os,
849 BitmapFile const & vec) const
854 BitmapFile::const_iterator it = vec.begin();
855 BitmapFile::const_iterator end = vec.end();
857 for (; it != end; ++it) {
859 os << "\\begin{preview}\n"
860 << from_utf8(it->first)
861 << "\n\\end{preview}\n\n";
865 } // namespace graphics
868 #include "moc_PreviewLoader.cpp"