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"
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 lyx::Converter const * setConverter(string const & from)
78 typedef vector<string> FmtList;
79 typedef lyx::graphics::Cache GCache;
80 FmtList const & loadableFormats = GCache::get().loadableFormats();
81 FmtList::const_iterator it = loadableFormats.begin();
82 FmtList::const_iterator const end = loadableFormats.end();
84 for (; it != end; ++it) {
85 string const to = *it;
89 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
95 static bool first = true;
98 LYXERR0("PreviewLoader::startLoading()\n"
99 << "No converter from \"" << from << "\" format has been defined.");
105 void setAscentFractions(vector<double> & ascent_fractions,
106 FileName const & metrics_file)
108 // If all else fails, then the images will have equal ascents and
110 vector<double>::iterator it = ascent_fractions.begin();
111 vector<double>::iterator end = ascent_fractions.end();
114 ifstream in(metrics_file.toFilesystemEncoding().c_str());
116 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
117 << "Unable to open file!");
123 int snippet_counter = 1;
124 while (!in.eof() && it != end) {
127 double ascent_fraction;
129 in >> snippet >> id >> ascent_fraction;
135 error = snippet != "Snippet";
139 error = id != snippet_counter;
143 *it = ascent_fraction;
150 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
151 << "Error reading file!\n");
159 FindFirst(string const & comp) : comp_(comp) {}
160 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
166 /// Store info on a currently executing, forked process.
170 InProgress() : pid(0) {}
172 InProgress(string const & filename_base,
173 PendingSnippets const & pending,
174 string const & to_format);
175 /// Remove any files left lying around and kill the forked process.
183 FileName metrics_file;
188 typedef map<pid_t, InProgress> InProgressProcesses;
190 typedef InProgressProcesses::value_type InProgressProcess;
199 class PreviewLoader::Impl : public boost::signals2::trackable {
202 Impl(PreviewLoader & p, Buffer const & b);
203 /// Stop any InProgress items still executing.
206 PreviewImage const * preview(string const & latex_snippet) const;
208 PreviewLoader::Status status(string const & latex_snippet) const;
210 void add(string const & latex_snippet);
212 void remove(string const & latex_snippet);
213 /// \p wait whether to wait for the process to complete or, instead,
214 /// to do it in the background.
215 void startLoading(bool wait = false);
217 void refreshPreviews();
219 /// Emit this signal when an image is ready for display.
220 boost::signals2::signal<void(PreviewImage const &)> imageReady;
222 Buffer const & buffer() const { return buffer_; }
225 /// Called by the ForkedCall process that generated the bitmap files.
226 void finishedGenerating(pid_t, int);
228 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
230 void dumpData(odocstream &, BitmapFile const &) const;
232 /** cache_ allows easy retrieval of already-generated images
233 * using the LaTeX snippet as the identifier.
235 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
237 typedef map<string, PreviewImagePtr> Cache;
241 /** pending_ stores the LaTeX snippets in anticipation of them being
242 * sent to the converter.
244 PendingSnippets pending_;
246 /** in_progress_ stores all forked processes so that we can proceed
248 The map uses the conversion commands as its identifiers.
250 InProgressProcesses in_progress_;
253 PreviewLoader & parent_;
255 Buffer const & buffer_;
257 mutable int font_scaling_factor_;
259 mutable int fg_color_;
261 mutable int bg_color_;
263 QTimer * delay_refresh_;
265 bool finished_generating_;
267 /// We don't own this
268 static lyx::Converter const * pconverter_;
272 lyx::Converter const * PreviewLoader::Impl::pconverter_;
276 // The public interface, defined in PreviewLoader.h
279 PreviewLoader::PreviewLoader(Buffer const & b)
280 : pimpl_(new Impl(*this, b))
284 PreviewLoader::~PreviewLoader()
290 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
292 return pimpl_->preview(latex_snippet);
296 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
298 return pimpl_->status(latex_snippet);
302 void PreviewLoader::add(string const & latex_snippet) const
304 pimpl_->add(latex_snippet);
308 void PreviewLoader::remove(string const & latex_snippet) const
310 pimpl_->remove(latex_snippet);
314 void PreviewLoader::startLoading(bool wait) const
316 pimpl_->startLoading(wait);
320 void PreviewLoader::refreshPreviews()
322 pimpl_->refreshPreviews();
326 boost::signals2::connection PreviewLoader::connect(slot_type const & slot) const
328 return pimpl_->imageReady.connect(slot);
332 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
334 pimpl_->imageReady(pimage);
338 Buffer const & PreviewLoader::buffer() const
340 return pimpl_->buffer();
343 } // namespace graphics
347 // The details of the Impl
348 // =======================
352 class IncrementedFileName {
354 IncrementedFileName(string const & to_format,
355 string const & filename_base)
356 : to_format_(to_format), base_(filename_base), counter_(1)
359 SnippetPair const operator()(string const & snippet)
362 os << base_ << counter_++ << '.' << to_format_;
363 string const file = os.str();
365 return make_pair(snippet, FileName(file));
369 string const & to_format_;
370 string const & base_;
375 InProgress::InProgress(string const & filename_base,
376 PendingSnippets const & pending,
377 string const & to_format)
379 metrics_file(filename_base + ".metrics"),
380 snippets(pending.size())
382 PendingSnippets::const_iterator pit = pending.begin();
383 PendingSnippets::const_iterator pend = pending.end();
384 BitmapFile::iterator sit = snippets.begin();
386 transform(pit, pend, sit,
387 IncrementedFileName(to_format, filename_base));
391 void InProgress::stop() const
394 ForkedCallsController::kill(pid, 0);
396 if (!metrics_file.empty())
397 metrics_file.removeFile();
399 BitmapFile::const_iterator vit = snippets.begin();
400 BitmapFile::const_iterator vend = snippets.end();
401 for (; vit != vend; ++vit) {
402 if (!vit->second.empty())
403 vit->second.removeFile();
413 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
414 : parent_(p), buffer_(b), finished_generating_(true)
416 font_scaling_factor_ = int(buffer_.fontScalingFactor());
418 fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
419 bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
422 bg_color_ = 0xffffff;
425 pconverter_ = setConverter("lyxpreview");
427 delay_refresh_ = new QTimer(&parent_);
428 delay_refresh_->setSingleShot(true);
429 QObject::connect(delay_refresh_, SIGNAL(timeout()),
430 &parent_, SLOT(refreshPreviews()));
434 PreviewLoader::Impl::~Impl()
436 delete delay_refresh_;
438 InProgressProcesses::iterator ipit = in_progress_.begin();
439 InProgressProcesses::iterator ipend = in_progress_.end();
441 for (; ipit != ipend; ++ipit)
447 PreviewLoader::Impl::preview(string const & latex_snippet) const
449 int fs = int(buffer_.fontScalingFactor());
453 fg = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
454 bg = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
456 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
457 // Schedule refresh of all previews on zoom or color changes.
458 // The previews are regenerated only after the zoom factor
459 // has not been changed for about 1 second.
462 delay_refresh_->start(1000);
464 // Don't try to access the cache until we are done.
465 if (delay_refresh_->isActive() || !finished_generating_)
467 Cache::const_iterator it = cache_.find(latex_snippet);
468 return (it == cache_.end()) ? 0 : it->second.get();
472 void PreviewLoader::Impl::refreshPreviews()
474 font_scaling_factor_ = int(buffer_.fontScalingFactor());
475 // Reschedule refresh until the previous process completed.
476 if (!finished_generating_) {
477 delay_refresh_->start(1000);
480 Cache::const_iterator cit = cache_.begin();
481 Cache::const_iterator cend = cache_.end();
483 parent_.remove((cit++)->first);
484 finished_generating_ = false;
485 buffer_.updatePreviews();
493 FindSnippet(string const & s) : snippet_(s) {}
494 bool operator()(InProgressProcess const & process) const
496 BitmapFile const & snippets = process.second.snippets;
497 BitmapFile::const_iterator beg = snippets.begin();
498 BitmapFile::const_iterator end = snippets.end();
499 return find_if(beg, end, FindFirst(snippet_)) != end;
503 string const snippet_;
508 PreviewLoader::Status
509 PreviewLoader::Impl::status(string const & latex_snippet) const
511 Cache::const_iterator cit = cache_.find(latex_snippet);
512 if (cit != cache_.end())
515 PendingSnippets::const_iterator pit = pending_.begin();
516 PendingSnippets::const_iterator pend = pending_.end();
518 pit = find(pit, pend, latex_snippet);
522 InProgressProcesses::const_iterator ipit = in_progress_.begin();
523 InProgressProcesses::const_iterator ipend = in_progress_.end();
525 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
533 void PreviewLoader::Impl::add(string const & latex_snippet)
535 if (!pconverter_ || status(latex_snippet) != NotFound)
538 string const snippet = trim(latex_snippet);
542 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
544 pending_.push_back(snippet);
552 EraseSnippet(string const & s) : snippet_(s) {}
553 void operator()(InProgressProcess & process)
555 BitmapFile & snippets = process.second.snippets;
556 BitmapFile::iterator it = snippets.begin();
557 BitmapFile::iterator end = snippets.end();
559 it = find_if(it, end, FindFirst(snippet_));
561 snippets.erase(it, it+1);
565 string const & snippet_;
571 void PreviewLoader::Impl::remove(string const & latex_snippet)
573 Cache::iterator cit = cache_.find(latex_snippet);
574 if (cit != cache_.end())
577 PendingSnippets::iterator pit = pending_.begin();
578 PendingSnippets::iterator pend = pending_.end();
580 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
582 InProgressProcesses::iterator ipit = in_progress_.begin();
583 InProgressProcesses::iterator ipend = in_progress_.end();
585 for_each(ipit, ipend, EraseSnippet(latex_snippet));
587 while (ipit != ipend) {
588 InProgressProcesses::iterator curr = ipit++;
589 if (curr->second.snippets.empty())
590 in_progress_.erase(curr);
595 void PreviewLoader::Impl::startLoading(bool wait)
597 if (pending_.empty() || !pconverter_)
600 // Only start the process off after the buffer is loaded from file.
601 if (!buffer_.isFullyLoaded())
604 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
606 // As used by the LaTeX file and by the resulting image files
607 FileName const directory(buffer_.temppath());
609 FileName const latexfile = unique_tex_filename(directory);
610 string const filename_base = removeExtension(latexfile.absFileName());
612 // Create an InProgress instance to place in the map of all
613 // such processes if it starts correctly.
614 InProgress inprogress(filename_base, pending_, pconverter_->to());
616 // clear pending_, so we're ready to start afresh.
619 // Output the LaTeX file.
620 // we use the encoding of the buffer
621 Encoding const & enc = buffer_.params().encoding();
623 try { of.reset(enc.iconvName()); }
624 catch (iconv_codecvt_facet_exception const & e) {
625 LYXERR0("Caught iconv exception: " << e.what()
626 << "\nUnable to create LaTeX file: " << latexfile);
631 OutputParams runparams(&enc);
632 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
634 if (!openFileWrite(of, latexfile))
638 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
639 << "Unable to create LaTeX file\n" << latexfile);
642 of << "\\batchmode\n";
644 // Set \jobname of previews to the document name (see bug 9627)
645 of << "\\def\\jobname{"
646 << from_utf8(changeExtension(buffer_.latexName(true), ""))
649 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
650 string latexparam = "";
651 bool docformat = !buffer_.params().default_output_format.empty()
652 && buffer_.params().default_output_format != "default";
653 // Use LATEX flavor if the document does not specify a specific
654 // output format (see bug 9371).
655 OutputParams::FLAVOR flavor = docformat
656 ? buffer_.params().getOutputFlavor()
657 : OutputParams::LATEX;
658 if (buffer_.params().encoding().package() == Encoding::japanese) {
659 latexparam = " --latex=platex";
660 flavor = OutputParams::LATEX;
662 else if (buffer_.params().useNonTeXFonts) {
663 if (flavor == OutputParams::LUATEX)
664 latexparam = " --latex=lualatex";
666 flavor = OutputParams::XETEX;
667 latexparam = " --latex=xelatex";
672 case OutputParams::PDFLATEX:
673 latexparam = " --latex=pdflatex";
675 case OutputParams::XETEX:
676 latexparam = " --latex=xelatex";
678 case OutputParams::LUATEX:
679 latexparam = " --latex=lualatex";
681 case OutputParams::DVILUATEX:
682 latexparam = " --latex=dvilualatex";
685 flavor = OutputParams::LATEX;
688 dumpPreamble(os, flavor);
689 // handle inputenc etc.
690 // I think, this is already hadled by dumpPreamble(): Kornel
691 // buffer_.params().writeEncodingPreamble(os, features);
692 of << "\n\\begin{document}\n";
693 dumpData(of, inprogress.snippets);
694 of << "\n\\end{document}\n";
697 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
698 << "File was not closed properly.");
702 // The conversion command.
704 cs << pconverter_->command()
705 << " " << quoteName(latexfile.toFilesystemEncoding())
706 << " --dpi " << font_scaling_factor_;
709 // The colors should be customizable.
710 if (!buffer_.isExporting()) {
711 ColorCode const fg = PreviewLoader::foregroundColor();
712 ColorCode const bg = PreviewLoader::backgroundColor();
713 cs << " --fg " << theApp()->hexName(fg)
714 << " --bg " << theApp()->hexName(bg);
718 if (buffer_.params().bibtex_command != "default")
719 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
720 else if (buffer_.params().encoding().package() == Encoding::japanese)
721 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
723 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
724 if (buffer_.params().bufferFormat() == "lilypond-book")
727 string const command = cs.str();
730 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
731 int ret = call.startScript(ForkedProcess::Wait, command);
732 static atomic_int fake((2^20) + 1);
734 inprogress.pid = pid;
735 inprogress.command = command;
736 in_progress_[pid] = inprogress;
737 finishedGenerating(pid, ret);
741 // Initiate the conversion from LaTeX to bitmap images files.
742 ForkedCall::SignalTypePtr
743 convert_ptr(new ForkedCall::SignalType);
744 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
746 ForkedCall call(buffer_.filePath());
747 int ret = call.startScript(command, convert_ptr);
750 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
751 << "Unable to start process\n" << command);
755 // Store the generation process in a list of all such processes
756 inprogress.pid = call.pid();
757 inprogress.command = command;
758 in_progress_[inprogress.pid] = inprogress;
762 double PreviewLoader::displayPixelRatio() const
764 return buffer().params().display_pixel_ratio;
767 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
770 InProgressProcesses::iterator git = in_progress_.find(pid);
771 if (git == in_progress_.end()) {
772 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
773 "data for PID " << pid << endl;
774 finished_generating_ = true;
778 string const command = git->second.command;
779 string const status = retval > 0 ? "failed" : "succeeded";
780 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
781 << retval << "): processing " << status
782 << " for " << command);
784 in_progress_.erase(git);
785 finished_generating_ = true;
789 // Read the metrics file, if it exists
790 vector<double> ascent_fractions(git->second.snippets.size());
791 setAscentFractions(ascent_fractions, git->second.metrics_file);
793 // Add these newly generated bitmap files to the cache and
794 // start loading them into LyX.
795 BitmapFile::const_iterator it = git->second.snippets.begin();
796 BitmapFile::const_iterator end = git->second.snippets.end();
798 list<PreviewImagePtr> newimages;
800 int metrics_counter = 0;
801 for (; it != end; ++it, ++metrics_counter) {
802 string const & snip = it->first;
803 FileName const & file = it->second;
804 double af = ascent_fractions[metrics_counter];
806 // Add the image to the cache only if it's actually present
807 // and not empty (an empty image is signaled by af < 0)
808 if (af >= 0 && file.isReadableFile()) {
809 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
812 newimages.push_back(ptr);
817 // Remove the item from the list of still-executing processes.
818 in_progress_.erase(git);
820 // Tell the outside world
821 list<PreviewImagePtr>::const_reverse_iterator
822 nit = newimages.rbegin();
823 list<PreviewImagePtr>::const_reverse_iterator
824 nend = newimages.rend();
825 for (; nit != nend; ++nit) {
826 imageReady(*nit->get());
828 finished_generating_ = true;
832 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
834 // Dump the preamble only.
835 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
836 OutputParams runparams(&buffer_.params().encoding());
837 runparams.flavor = flavor;
838 runparams.nice = true;
839 runparams.moving_arg = true;
840 runparams.free_spacing = true;
841 runparams.is_child = buffer_.parent();
842 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
844 // FIXME! This is a HACK! The proper fix is to control the 'true'
845 // passed to WriteStream below:
846 // int InsetMathNest::latex(Buffer const &, odocstream & os,
847 // OutputParams const & runparams) const
849 // WriteStream wi(os, runparams.moving_arg, true);
854 << "\\def\\lyxlock{}\n"
857 // All equation labels appear as "(#)" + preview.sty's rendering of
859 if (lyxrc.preview_hashed_labels)
860 os << "\\renewcommand{\\theequation}{\\#}\n";
862 // Use the preview style file to ensure that each snippet appears on a
864 // Also support PDF output (automatically generated e.g. when
865 // \usepackage[pdftex]{hyperref} is used and XeTeX.
867 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
872 void PreviewLoader::Impl::dumpData(odocstream & os,
873 BitmapFile const & vec) const
878 BitmapFile::const_iterator it = vec.begin();
879 BitmapFile::const_iterator end = vec.end();
881 for (; it != end; ++it) {
883 os << "\\begin{preview}\n"
884 << from_utf8(it->first)
885 << "\n\\end{preview}\n\n";
889 } // namespace graphics
892 #include "moc_PreviewLoader.cpp"