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 void setAscentFractions(vector<double> & ascent_fractions,
78 FileName const & metrics_file)
80 // If all else fails, then the images will have equal ascents and
82 vector<double>::iterator it = ascent_fractions.begin();
83 vector<double>::iterator end = ascent_fractions.end();
86 ifstream in(metrics_file.toFilesystemEncoding().c_str());
88 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
89 << "Unable to open file!");
95 int snippet_counter = 1;
96 while (!in.eof() && it != end) {
99 double ascent_fraction;
101 in >> snippet >> id >> ascent_fraction;
107 error = snippet != "Snippet";
111 error = id != snippet_counter;
115 *it = ascent_fraction;
122 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
123 << "Error reading file!\n");
131 FindFirst(string const & comp) : comp_(comp) {}
132 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
138 /// Store info on a currently executing, forked process.
142 InProgress() : pid(0) {}
144 InProgress(string const & filename_base,
145 PendingSnippets const & pending,
146 string const & to_format);
147 /// Remove any files left lying around and kill the forked process.
155 FileName metrics_file;
160 typedef map<pid_t, InProgress> InProgressProcesses;
162 typedef InProgressProcesses::value_type InProgressProcess;
171 class PreviewLoader::Impl : public boost::signals2::trackable {
174 Impl(PreviewLoader & p, Buffer const & b);
175 /// Stop any InProgress items still executing.
178 PreviewImage const * preview(string const & latex_snippet) const;
180 PreviewLoader::Status status(string const & latex_snippet) const;
182 void add(string const & latex_snippet);
184 void remove(string const & latex_snippet);
185 /// \p wait whether to wait for the process to complete or, instead,
186 /// to do it in the background.
187 void startLoading(bool wait = false);
189 void refreshPreviews();
191 /// Emit this signal when an image is ready for display.
192 boost::signals2::signal<void(PreviewImage const &)> imageReady;
194 Buffer const & buffer() const { return buffer_; }
196 lyx::Converter const * setConverter(string const & from);
199 /// Called by the ForkedCall process that generated the bitmap files.
200 void finishedGenerating(pid_t, int);
202 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
204 void dumpData(odocstream &, BitmapFile const &) const;
206 /** cache_ allows easy retrieval of already-generated images
207 * using the LaTeX snippet as the identifier.
209 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
211 typedef map<string, PreviewImagePtr> Cache;
215 /** pending_ stores the LaTeX snippets in anticipation of them being
216 * sent to the converter.
218 PendingSnippets pending_;
220 /** in_progress_ stores all forked processes so that we can proceed
222 The map uses the conversion commands as its identifiers.
224 InProgressProcesses in_progress_;
227 PreviewLoader & parent_;
229 Buffer const & buffer_;
231 mutable int font_scaling_factor_;
233 mutable int fg_color_;
235 mutable int bg_color_;
237 QTimer * delay_refresh_;
239 bool finished_generating_;
241 /// We don't own this
242 static lyx::Converter const * pconverter_;
246 lyx::Converter const * PreviewLoader::Impl::pconverter_;
250 // The public interface, defined in PreviewLoader.h
253 PreviewLoader::PreviewLoader(Buffer const & b)
254 : pimpl_(new Impl(*this, b))
258 PreviewLoader::~PreviewLoader()
264 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
266 return pimpl_->preview(latex_snippet);
270 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
272 return pimpl_->status(latex_snippet);
276 void PreviewLoader::add(string const & latex_snippet) const
278 pimpl_->add(latex_snippet);
282 void PreviewLoader::remove(string const & latex_snippet) const
284 pimpl_->remove(latex_snippet);
288 void PreviewLoader::startLoading(bool wait) const
290 pimpl_->startLoading(wait);
294 void PreviewLoader::refreshPreviews()
296 pimpl_->refreshPreviews();
300 boost::signals2::connection PreviewLoader::connect(slot_type const & slot) const
302 return pimpl_->imageReady.connect(slot);
306 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
308 pimpl_->imageReady(pimage);
312 Buffer const & PreviewLoader::buffer() const
314 return pimpl_->buffer();
317 } // namespace graphics
321 // The details of the Impl
322 // =======================
326 class IncrementedFileName {
328 IncrementedFileName(string const & to_format,
329 string const & filename_base)
330 : to_format_(to_format), base_(filename_base), counter_(1)
333 SnippetPair const operator()(string const & snippet)
336 os << base_ << counter_++ << '.' << to_format_;
337 string const file = os.str();
339 return make_pair(snippet, FileName(file));
343 string const & to_format_;
344 string const & base_;
349 InProgress::InProgress(string const & filename_base,
350 PendingSnippets const & pending,
351 string const & to_format)
353 metrics_file(filename_base + ".metrics"),
354 snippets(pending.size())
356 PendingSnippets::const_iterator pit = pending.begin();
357 PendingSnippets::const_iterator pend = pending.end();
358 BitmapFile::iterator sit = snippets.begin();
360 transform(pit, pend, sit,
361 IncrementedFileName(to_format, filename_base));
365 void InProgress::stop() const
368 ForkedCallsController::kill(pid, 0);
370 if (!metrics_file.empty())
371 metrics_file.removeFile();
373 BitmapFile::const_iterator vit = snippets.begin();
374 BitmapFile::const_iterator vend = snippets.end();
375 for (; vit != vend; ++vit) {
376 if (!vit->second.empty())
377 vit->second.removeFile();
387 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
388 : parent_(p), buffer_(b), finished_generating_(true)
390 font_scaling_factor_ = int(buffer_.fontScalingFactor());
392 fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
393 bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
396 bg_color_ = 0xffffff;
399 pconverter_ = setConverter("lyxpreview");
401 delay_refresh_ = new QTimer(&parent_);
402 delay_refresh_->setSingleShot(true);
403 QObject::connect(delay_refresh_, SIGNAL(timeout()),
404 &parent_, SLOT(refreshPreviews()));
408 lyx::Converter const * PreviewLoader::Impl::setConverter(string const & from)
410 typedef vector<string> FmtList;
411 FmtList const & loadableFormats = graphics::Cache::get().loadableFormats();
412 FmtList::const_iterator it = loadableFormats.begin();
413 FmtList::const_iterator const end = loadableFormats.end();
415 for (; it != end; ++it) {
416 string const to = *it;
420 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
425 // Show the error only once. This is thread-safe.
426 static nullptr_t no_conv = [&]{
427 LYXERR0("PreviewLoader::startLoading()\n"
428 << "No converter from \"" << from
429 << "\" format has been defined.");
437 PreviewLoader::Impl::~Impl()
439 delete delay_refresh_;
441 InProgressProcesses::iterator ipit = in_progress_.begin();
442 InProgressProcesses::iterator ipend = in_progress_.end();
444 for (; ipit != ipend; ++ipit)
450 PreviewLoader::Impl::preview(string const & latex_snippet) const
452 int fs = int(buffer_.fontScalingFactor());
456 fg = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
457 bg = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
459 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
460 // Schedule refresh of all previews on zoom or color changes.
461 // The previews are regenerated only after the zoom factor
462 // has not been changed for about 1 second.
465 delay_refresh_->start(1000);
467 // Don't try to access the cache until we are done.
468 if (delay_refresh_->isActive() || !finished_generating_)
470 Cache::const_iterator it = cache_.find(latex_snippet);
471 return (it == cache_.end()) ? 0 : it->second.get();
475 void PreviewLoader::Impl::refreshPreviews()
477 font_scaling_factor_ = int(buffer_.fontScalingFactor());
478 // Reschedule refresh until the previous process completed.
479 if (!finished_generating_) {
480 delay_refresh_->start(1000);
483 Cache::const_iterator cit = cache_.begin();
484 Cache::const_iterator cend = cache_.end();
486 parent_.remove((cit++)->first);
487 finished_generating_ = false;
488 buffer_.updatePreviews();
496 FindSnippet(string const & s) : snippet_(s) {}
497 bool operator()(InProgressProcess const & process) const
499 BitmapFile const & snippets = process.second.snippets;
500 BitmapFile::const_iterator beg = snippets.begin();
501 BitmapFile::const_iterator end = snippets.end();
502 return find_if(beg, end, FindFirst(snippet_)) != end;
506 string const snippet_;
511 PreviewLoader::Status
512 PreviewLoader::Impl::status(string const & latex_snippet) const
514 Cache::const_iterator cit = cache_.find(latex_snippet);
515 if (cit != cache_.end())
518 PendingSnippets::const_iterator pit = pending_.begin();
519 PendingSnippets::const_iterator pend = pending_.end();
521 pit = find(pit, pend, latex_snippet);
525 InProgressProcesses::const_iterator ipit = in_progress_.begin();
526 InProgressProcesses::const_iterator ipend = in_progress_.end();
528 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
536 void PreviewLoader::Impl::add(string const & latex_snippet)
538 if (!pconverter_ || status(latex_snippet) != NotFound)
541 string const snippet = trim(latex_snippet);
545 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
547 pending_.push_back(snippet);
555 EraseSnippet(string const & s) : snippet_(s) {}
556 void operator()(InProgressProcess & process)
558 BitmapFile & snippets = process.second.snippets;
559 BitmapFile::iterator it = snippets.begin();
560 BitmapFile::iterator end = snippets.end();
562 it = find_if(it, end, FindFirst(snippet_));
564 snippets.erase(it, it+1);
568 string const & snippet_;
574 void PreviewLoader::Impl::remove(string const & latex_snippet)
576 Cache::iterator cit = cache_.find(latex_snippet);
577 if (cit != cache_.end())
580 PendingSnippets::iterator pit = pending_.begin();
581 PendingSnippets::iterator pend = pending_.end();
583 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
585 InProgressProcesses::iterator ipit = in_progress_.begin();
586 InProgressProcesses::iterator ipend = in_progress_.end();
588 for_each(ipit, ipend, EraseSnippet(latex_snippet));
590 while (ipit != ipend) {
591 InProgressProcesses::iterator curr = ipit++;
592 if (curr->second.snippets.empty())
593 in_progress_.erase(curr);
598 void PreviewLoader::Impl::startLoading(bool wait)
600 if (pending_.empty() || !pconverter_)
603 // Only start the process off after the buffer is loaded from file.
604 if (!buffer_.isFullyLoaded())
607 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
609 // As used by the LaTeX file and by the resulting image files
610 FileName const directory(buffer_.temppath());
612 FileName const latexfile = unique_tex_filename(directory);
613 string const filename_base = removeExtension(latexfile.absFileName());
615 // Create an InProgress instance to place in the map of all
616 // such processes if it starts correctly.
617 InProgress inprogress(filename_base, pending_, pconverter_->to());
619 // clear pending_, so we're ready to start afresh.
622 // Output the LaTeX file.
623 // we use the encoding of the buffer
624 Encoding const & enc = buffer_.params().encoding();
626 try { of.reset(enc.iconvName()); }
627 catch (iconv_codecvt_facet_exception const & e) {
628 LYXERR0("Caught iconv exception: " << e.what()
629 << "\nUnable to create LaTeX file: " << latexfile);
634 OutputParams runparams(&enc);
635 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
637 if (!openFileWrite(of, latexfile))
641 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
642 << "Unable to create LaTeX file\n" << latexfile);
645 of << "\\batchmode\n";
647 // Set \jobname of previews to the document name (see bug 9627)
648 of << "\\def\\jobname{"
649 << from_utf8(changeExtension(buffer_.latexName(true), ""))
652 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
653 string latexparam = "";
654 bool docformat = !buffer_.params().default_output_format.empty()
655 && buffer_.params().default_output_format != "default";
656 // Use LATEX flavor if the document does not specify a specific
657 // output format (see bug 9371).
658 OutputParams::FLAVOR flavor = docformat
659 ? buffer_.params().getOutputFlavor()
660 : OutputParams::LATEX;
661 if (buffer_.params().encoding().package() == Encoding::japanese) {
662 latexparam = " --latex=platex";
663 flavor = OutputParams::LATEX;
665 else if (buffer_.params().useNonTeXFonts) {
666 if (flavor == OutputParams::LUATEX)
667 latexparam = " --latex=lualatex";
669 flavor = OutputParams::XETEX;
670 latexparam = " --latex=xelatex";
675 case OutputParams::PDFLATEX:
676 latexparam = " --latex=pdflatex";
678 case OutputParams::XETEX:
679 latexparam = " --latex=xelatex";
681 case OutputParams::LUATEX:
682 latexparam = " --latex=lualatex";
684 case OutputParams::DVILUATEX:
685 latexparam = " --latex=dvilualatex";
688 flavor = OutputParams::LATEX;
691 dumpPreamble(os, flavor);
692 // handle inputenc etc.
693 // I think, this is already hadled by dumpPreamble(): Kornel
694 // buffer_.params().writeEncodingPreamble(os, features);
695 of << "\n\\begin{document}\n";
696 dumpData(of, inprogress.snippets);
697 of << "\n\\end{document}\n";
700 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
701 << "File was not closed properly.");
705 // The conversion command.
707 cs << pconverter_->command()
708 << " " << quoteName(latexfile.toFilesystemEncoding())
709 << " --dpi " << font_scaling_factor_;
712 // The colors should be customizable.
713 if (!buffer_.isExporting()) {
714 ColorCode const fg = PreviewLoader::foregroundColor();
715 ColorCode const bg = PreviewLoader::backgroundColor();
716 cs << " --fg " << theApp()->hexName(fg)
717 << " --bg " << theApp()->hexName(bg);
721 cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
722 if (buffer_.params().bufferFormat() == "lilypond-book")
725 string const command = cs.str();
728 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
729 int ret = call.startScript(ForkedProcess::Wait, command);
730 static atomic_int fake((2^20) + 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::SignalTypePtr
741 convert_ptr(new ForkedCall::SignalType);
742 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
744 ForkedCall call(buffer_.filePath());
745 int ret = call.startScript(command, convert_ptr);
748 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
749 << "Unable to start process\n" << command);
753 // Store the generation process in a list of all such processes
754 inprogress.pid = call.pid();
755 inprogress.command = command;
756 in_progress_[inprogress.pid] = inprogress;
760 double PreviewLoader::displayPixelRatio() const
762 return buffer().params().display_pixel_ratio;
765 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
768 InProgressProcesses::iterator git = in_progress_.find(pid);
769 if (git == in_progress_.end()) {
770 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
771 "data for PID " << pid << endl;
772 finished_generating_ = true;
776 string const command = git->second.command;
777 string const status = retval > 0 ? "failed" : "succeeded";
778 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
779 << retval << "): processing " << status
780 << " for " << command);
782 in_progress_.erase(git);
783 finished_generating_ = true;
787 // Read the metrics file, if it exists
788 vector<double> ascent_fractions(git->second.snippets.size());
789 setAscentFractions(ascent_fractions, git->second.metrics_file);
791 // Add these newly generated bitmap files to the cache and
792 // start loading them into LyX.
793 BitmapFile::const_iterator it = git->second.snippets.begin();
794 BitmapFile::const_iterator end = git->second.snippets.end();
796 list<PreviewImagePtr> newimages;
798 int metrics_counter = 0;
799 for (; it != end; ++it, ++metrics_counter) {
800 string const & snip = it->first;
801 FileName const & file = it->second;
802 double af = ascent_fractions[metrics_counter];
804 // Add the image to the cache only if it's actually present
805 // and not empty (an empty image is signaled by af < 0)
806 if (af >= 0 && file.isReadableFile()) {
807 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
810 newimages.push_back(ptr);
815 // Remove the item from the list of still-executing processes.
816 in_progress_.erase(git);
818 // Tell the outside world
819 list<PreviewImagePtr>::const_reverse_iterator
820 nit = newimages.rbegin();
821 list<PreviewImagePtr>::const_reverse_iterator
822 nend = newimages.rend();
823 for (; nit != nend; ++nit) {
824 imageReady(*nit->get());
826 finished_generating_ = true;
830 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
832 // Dump the preamble only.
833 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
834 OutputParams runparams(&buffer_.params().encoding());
835 runparams.flavor = flavor;
836 runparams.nice = true;
837 runparams.moving_arg = true;
838 runparams.free_spacing = true;
839 runparams.is_child = buffer_.parent();
840 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
842 // FIXME! This is a HACK! The proper fix is to control the 'true'
843 // passed to WriteStream below:
844 // int InsetMathNest::latex(Buffer const &, odocstream & os,
845 // OutputParams const & runparams) const
847 // WriteStream wi(os, runparams.moving_arg, true);
852 << "\\def\\lyxlock{}\n"
855 // All equation labels appear as "(#)" + preview.sty's rendering of
857 if (lyxrc.preview_hashed_labels)
858 os << "\\renewcommand{\\theequation}{\\#}\n";
860 // Use the preview style file to ensure that each snippet appears on a
862 // Also support PDF output (automatically generated e.g. when
863 // \usepackage[pdftex]{hyperref} is used and XeTeX.
865 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
870 void PreviewLoader::Impl::dumpData(odocstream & os,
871 BitmapFile const & vec) const
876 BitmapFile::const_iterator it = vec.begin();
877 BitmapFile::const_iterator end = vec.end();
879 for (; it != end; ++it) {
881 os << "\\begin{preview}\n"
882 << from_utf8(it->first)
883 << "\n\\end{preview}\n\n";
887 } // namespace graphics
890 #include "moc_PreviewLoader.cpp"