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");
130 FindFirst(string const & comp) : comp_(comp) {}
131 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
137 /// Store info on a currently executing, forked process.
141 InProgress() : pid(0) {}
143 InProgress(string const & filename_base,
144 PendingSnippets const & pending,
145 string const & to_format);
146 /// Remove any files left lying around and kill the forked process.
154 FileName metrics_file;
159 typedef map<pid_t, InProgress> InProgressProcesses;
161 typedef InProgressProcesses::value_type InProgressProcess;
169 class PreviewLoader::Impl {
172 Impl(PreviewLoader & p, Buffer const & b);
173 /// Stop any InProgress items still executing.
176 PreviewImage const * preview(string const & latex_snippet) const;
178 PreviewLoader::Status status(string const & latex_snippet) const;
180 void add(string const & latex_snippet);
182 void remove(string const & latex_snippet);
183 /// \p wait whether to wait for the process to complete or, instead,
184 /// to do it in the background.
185 void startLoading(bool wait = false);
187 void refreshPreviews();
189 /// Emit this signal when an image is ready for display.
190 signals2::signal<void(PreviewImage const &)> imageReady;
192 Buffer const & buffer() const { return buffer_; }
194 lyx::Converter const * setConverter(string const & from);
197 /// Called by the ForkedCall process that generated the bitmap files.
198 void finishedGenerating(pid_t, int);
200 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
202 void dumpData(odocstream &, BitmapFile const &) const;
204 /** cache_ allows easy retrieval of already-generated images
205 * using the LaTeX snippet as the identifier.
207 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
209 typedef map<string, PreviewImagePtr> Cache;
213 /** pending_ stores the LaTeX snippets in anticipation of them being
214 * sent to the converter.
216 PendingSnippets pending_;
218 /** in_progress_ stores all forked processes so that we can proceed
221 InProgressProcesses in_progress_;
224 PreviewLoader & parent_;
226 Buffer const & buffer_;
228 mutable int font_scaling_factor_;
230 mutable int fg_color_;
232 mutable int bg_color_;
234 QTimer * delay_refresh_;
236 bool finished_generating_;
238 /// We don't own this
239 static lyx::Converter const * pconverter_;
241 Trackable trackable_;
245 lyx::Converter const * PreviewLoader::Impl::pconverter_;
249 // The public interface, defined in PreviewLoader.h
252 PreviewLoader::PreviewLoader(Buffer const & b)
253 : pimpl_(new Impl(*this, b))
257 PreviewLoader::~PreviewLoader()
263 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
265 return pimpl_->preview(latex_snippet);
269 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
271 return pimpl_->status(latex_snippet);
275 void PreviewLoader::add(string const & latex_snippet) const
277 pimpl_->add(latex_snippet);
281 void PreviewLoader::remove(string const & latex_snippet) const
283 pimpl_->remove(latex_snippet);
287 void PreviewLoader::startLoading(bool wait) const
289 pimpl_->startLoading(wait);
293 void PreviewLoader::refreshPreviews()
295 pimpl_->refreshPreviews();
299 signals2::connection PreviewLoader::connect(slot const & slot) const
301 return pimpl_->imageReady.connect(slot);
305 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
307 pimpl_->imageReady(pimage);
311 Buffer const & PreviewLoader::buffer() const
313 return pimpl_->buffer();
316 } // namespace graphics
320 // The details of the Impl
321 // =======================
325 class IncrementedFileName {
327 IncrementedFileName(string const & to_format,
328 string const & filename_base)
329 : to_format_(to_format), base_(filename_base), counter_(1)
332 SnippetPair const operator()(string const & snippet)
335 os << base_ << counter_++ << '.' << to_format_;
336 string const file = os.str();
338 return make_pair(snippet, FileName(file));
342 string const & to_format_;
343 string const & base_;
348 InProgress::InProgress(string const & filename_base,
349 PendingSnippets const & pending,
350 string const & to_format)
352 metrics_file(filename_base + ".metrics"),
353 snippets(pending.size())
355 PendingSnippets::const_iterator pit = pending.begin();
356 PendingSnippets::const_iterator pend = pending.end();
357 BitmapFile::iterator sit = snippets.begin();
359 transform(pit, pend, sit,
360 IncrementedFileName(to_format, filename_base));
364 void InProgress::stop() const
367 ForkedCallsController::kill(pid, 0);
369 if (!metrics_file.empty())
370 metrics_file.removeFile();
372 BitmapFile::const_iterator vit = snippets.begin();
373 BitmapFile::const_iterator vend = snippets.end();
374 for (; vit != vend; ++vit) {
375 if (!vit->second.empty())
376 vit->second.removeFile();
386 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
387 : parent_(p), buffer_(b), finished_generating_(true)
389 font_scaling_factor_ = int(buffer_.fontScalingFactor());
391 fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
392 bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
395 bg_color_ = 0xffffff;
398 pconverter_ = setConverter("lyxpreview");
400 delay_refresh_ = new QTimer(&parent_);
401 delay_refresh_->setSingleShot(true);
402 QObject::connect(delay_refresh_, SIGNAL(timeout()),
403 &parent_, SLOT(refreshPreviews()));
407 lyx::Converter const * PreviewLoader::Impl::setConverter(string const & from)
409 typedef vector<string> FmtList;
410 FmtList const & loadableFormats = graphics::Cache::get().loadableFormats();
411 FmtList::const_iterator it = loadableFormats.begin();
412 FmtList::const_iterator const end = loadableFormats.end();
414 for (; it != end; ++it) {
415 string const to = *it;
419 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
424 // Show the error only once. This is thread-safe.
425 static nullptr_t no_conv = [&]{
426 LYXERR0("PreviewLoader::startLoading()\n"
427 << "No converter from \"" << from
428 << "\" format has been defined.");
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 handled 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 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
721 if (buffer_.params().bufferFormat() == "lilypond-book")
724 string const command = cs.str();
727 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
728 int ret = call.startScript(ForkedProcess::Wait, command);
729 // PID_MAX_LIMIT is 2^22 so we start one after that
730 static atomic_int fake((1 << 22) + 1);
732 inprogress.pid = pid;
733 inprogress.command = command;
734 in_progress_[pid] = inprogress;
735 finishedGenerating(pid, ret);
739 // Initiate the conversion from LaTeX to bitmap images files.
740 ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
741 convert_ptr->connect(ForkedProcess::slot([this](pid_t pid, int retval){
742 finishedGenerating(pid, retval);
743 }).track_foreign(trackable_.p()));
745 ForkedCall call(buffer_.filePath());
746 int ret = call.startScript(command, convert_ptr);
749 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
750 << "Unable to start process\n" << command);
754 // Store the generation process in a list of all such processes
755 inprogress.pid = call.pid();
756 inprogress.command = command;
757 in_progress_[inprogress.pid] = inprogress;
761 double PreviewLoader::displayPixelRatio() const
763 return buffer().params().display_pixel_ratio;
766 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
769 InProgressProcesses::iterator git = in_progress_.find(pid);
770 if (git == in_progress_.end()) {
771 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
772 "data for PID " << pid << endl;
773 finished_generating_ = true;
777 string const command = git->second.command;
778 string const status = retval > 0 ? "failed" : "succeeded";
779 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
780 << retval << "): processing " << status
781 << " for " << command);
783 in_progress_.erase(git);
784 finished_generating_ = true;
788 // Read the metrics file, if it exists
789 vector<double> ascent_fractions(git->second.snippets.size());
790 setAscentFractions(ascent_fractions, git->second.metrics_file);
792 // Add these newly generated bitmap files to the cache and
793 // start loading them into LyX.
794 BitmapFile::const_iterator it = git->second.snippets.begin();
795 BitmapFile::const_iterator end = git->second.snippets.end();
797 list<PreviewImagePtr> newimages;
799 int metrics_counter = 0;
800 for (; it != end; ++it, ++metrics_counter) {
801 string const & snip = it->first;
802 FileName const & file = it->second;
803 double af = ascent_fractions[metrics_counter];
805 // Add the image to the cache only if it's actually present
806 // and not empty (an empty image is signaled by af < 0)
807 if (af >= 0 && file.isReadableFile()) {
808 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
811 newimages.push_back(ptr);
816 // Remove the item from the list of still-executing processes.
817 in_progress_.erase(git);
819 // Tell the outside world
820 list<PreviewImagePtr>::const_reverse_iterator
821 nit = newimages.rbegin();
822 list<PreviewImagePtr>::const_reverse_iterator
823 nend = newimages.rend();
824 for (; nit != nend; ++nit) {
825 imageReady(*nit->get());
827 finished_generating_ = true;
831 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
833 // Dump the preamble only.
834 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
835 OutputParams runparams(&buffer_.params().encoding());
836 runparams.flavor = flavor;
837 runparams.nice = true;
838 runparams.moving_arg = true;
839 runparams.free_spacing = true;
840 runparams.is_child = buffer_.parent();
841 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
843 // FIXME! This is a HACK! The proper fix is to control the 'true'
844 // passed to WriteStream below:
845 // int InsetMathNest::latex(Buffer const &, odocstream & os,
846 // OutputParams const & runparams) const
848 // WriteStream wi(os, runparams.moving_arg, true);
853 << "\\def\\lyxlock{}\n"
856 // All equation labels appear as "(#)" + preview.sty's rendering of
858 if (lyxrc.preview_hashed_labels)
859 os << "\\renewcommand{\\theequation}{\\#}\n";
861 // Use the preview style file to ensure that each snippet appears on a
863 // Also support PDF output (automatically generated e.g. when
864 // \usepackage[pdftex]{hyperref} is used and XeTeX.
866 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
871 void PreviewLoader::Impl::dumpData(odocstream & os,
872 BitmapFile const & vec) const
877 BitmapFile::const_iterator it = vec.begin();
878 BitmapFile::const_iterator end = vec.end();
880 for (; it != end; ++it) {
882 os << "\\begin{preview}\n"
883 << from_utf8(it->first)
884 << "\n\\end{preview}\n\n";
888 } // namespace graphics
891 #include "moc_PreviewLoader.cpp"