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"
29 #include "frontends/Application.h" // hexName
31 #include "insets/Inset.h"
33 #include "support/convert.h"
34 #include "support/debug.h"
35 #include "support/FileName.h"
36 #include "support/filetools.h"
37 #include "support/ForkedCalls.h"
38 #include "support/lstrings.h"
40 #include "support/bind.h"
41 #include "support/TempFile.h"
51 using namespace lyx::support;
57 typedef pair<string, FileName> SnippetPair;
59 // A list of all snippets to be converted to previews
60 typedef list<string> PendingSnippets;
62 // Each item in the vector is a pair<snippet, image file name>.
63 typedef vector<SnippetPair> BitmapFile;
66 FileName const unique_tex_filename(FileName const & bufferpath)
68 TempFile tempfile(bufferpath, "lyxpreviewXXXXXX.tex");
69 tempfile.setAutoRemove(false);
70 return tempfile.name();
74 lyx::Converter const * setConverter(string const & from)
76 typedef vector<string> FmtList;
77 typedef lyx::graphics::Cache GCache;
78 FmtList const & loadableFormats = GCache::get().loadableFormats();
79 FmtList::const_iterator it = loadableFormats.begin();
80 FmtList::const_iterator const end = loadableFormats.end();
82 for (; it != end; ++it) {
83 string const to = *it;
87 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
93 static bool first = true;
96 LYXERR0("PreviewLoader::startLoading()\n"
97 << "No converter from \"" << from << "\" format has been defined.");
103 void setAscentFractions(vector<double> & ascent_fractions,
104 FileName const & metrics_file)
106 // If all else fails, then the images will have equal ascents and
108 vector<double>::iterator it = ascent_fractions.begin();
109 vector<double>::iterator end = ascent_fractions.end();
112 ifstream in(metrics_file.toFilesystemEncoding().c_str());
114 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
115 << "Unable to open file!");
121 int snippet_counter = 1;
122 while (!in.eof() && it != end) {
125 double ascent_fraction;
127 in >> snippet >> id >> ascent_fraction;
133 error = snippet != "Snippet";
137 error = id != snippet_counter;
141 *it = ascent_fraction;
148 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
149 << "Error reading file!\n");
157 FindFirst(string const & comp) : comp_(comp) {}
158 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
164 /// Store info on a currently executing, forked process.
168 InProgress() : pid(0) {}
170 InProgress(string const & filename_base,
171 PendingSnippets const & pending,
172 string const & to_format);
173 /// Remove any files left lying around and kill the forked process.
181 FileName metrics_file;
186 typedef map<pid_t, InProgress> InProgressProcesses;
188 typedef InProgressProcesses::value_type InProgressProcess;
197 class PreviewLoader::Impl : public boost::signals2::trackable {
200 Impl(PreviewLoader & p, Buffer const & b);
201 /// Stop any InProgress items still executing.
204 PreviewImage const * preview(string const & latex_snippet) const;
206 PreviewLoader::Status status(string const & latex_snippet) const;
208 void add(string const & latex_snippet);
210 void remove(string const & latex_snippet);
211 /// \p wait whether to wait for the process to complete or, instead,
212 /// to do it in the background.
213 void startLoading(bool wait = false);
215 void refreshPreviews();
217 /// Emit this signal when an image is ready for display.
218 boost::signals2::signal<void(PreviewImage const &)> imageReady;
220 Buffer const & buffer() const { return buffer_; }
223 /// Called by the ForkedCall process that generated the bitmap files.
224 void finishedGenerating(pid_t, int);
226 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
228 void dumpData(odocstream &, BitmapFile const &) const;
230 /** cache_ allows easy retrieval of already-generated images
231 * using the LaTeX snippet as the identifier.
233 typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
235 typedef map<string, PreviewImagePtr> Cache;
239 /** pending_ stores the LaTeX snippets in anticipation of them being
240 * sent to the converter.
242 PendingSnippets pending_;
244 /** in_progress_ stores all forked processes so that we can proceed
246 The map uses the conversion commands as its identifiers.
248 InProgressProcesses in_progress_;
251 PreviewLoader & parent_;
253 Buffer const & buffer_;
255 mutable int font_scaling_factor_;
257 mutable int fg_color_;
259 mutable int bg_color_;
261 QTimer * delay_refresh_;
263 bool finished_generating_;
265 /// We don't own this
266 static lyx::Converter const * pconverter_;
270 lyx::Converter const * PreviewLoader::Impl::pconverter_;
274 // The public interface, defined in PreviewLoader.h
277 PreviewLoader::PreviewLoader(Buffer const & b)
278 : pimpl_(new Impl(*this, b))
282 PreviewLoader::~PreviewLoader()
288 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
290 return pimpl_->preview(latex_snippet);
294 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
296 return pimpl_->status(latex_snippet);
300 void PreviewLoader::add(string const & latex_snippet) const
302 pimpl_->add(latex_snippet);
306 void PreviewLoader::remove(string const & latex_snippet) const
308 pimpl_->remove(latex_snippet);
312 void PreviewLoader::startLoading(bool wait) const
314 pimpl_->startLoading(wait);
318 void PreviewLoader::refreshPreviews()
320 pimpl_->refreshPreviews();
324 boost::signals2::connection PreviewLoader::connect(slot_type const & slot) const
326 return pimpl_->imageReady.connect(slot);
330 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
332 pimpl_->imageReady(pimage);
336 Buffer const & PreviewLoader::buffer() const
338 return pimpl_->buffer();
341 } // namespace graphics
345 // The details of the Impl
346 // =======================
350 class IncrementedFileName {
352 IncrementedFileName(string const & to_format,
353 string const & filename_base)
354 : to_format_(to_format), base_(filename_base), counter_(1)
357 SnippetPair const operator()(string const & snippet)
360 os << base_ << counter_++ << '.' << to_format_;
361 string const file = os.str();
363 return make_pair(snippet, FileName(file));
367 string const & to_format_;
368 string const & base_;
373 InProgress::InProgress(string const & filename_base,
374 PendingSnippets const & pending,
375 string const & to_format)
377 metrics_file(filename_base + ".metrics"),
378 snippets(pending.size())
380 PendingSnippets::const_iterator pit = pending.begin();
381 PendingSnippets::const_iterator pend = pending.end();
382 BitmapFile::iterator sit = snippets.begin();
384 transform(pit, pend, sit,
385 IncrementedFileName(to_format, filename_base));
389 void InProgress::stop() const
392 ForkedCallsController::kill(pid, 0);
394 if (!metrics_file.empty())
395 metrics_file.removeFile();
397 BitmapFile::const_iterator vit = snippets.begin();
398 BitmapFile::const_iterator vend = snippets.end();
399 for (; vit != vend; ++vit) {
400 if (!vit->second.empty())
401 vit->second.removeFile();
411 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
412 : parent_(p), buffer_(b), finished_generating_(true)
414 font_scaling_factor_ = int(buffer_.fontScalingFactor());
416 fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
417 bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
420 bg_color_ = 0xffffff;
423 pconverter_ = setConverter("lyxpreview");
425 delay_refresh_ = new QTimer(&parent_);
426 delay_refresh_->setSingleShot(true);
427 QObject::connect(delay_refresh_, SIGNAL(timeout()),
428 &parent_, SLOT(refreshPreviews()));
432 PreviewLoader::Impl::~Impl()
434 delete delay_refresh_;
436 InProgressProcesses::iterator ipit = in_progress_.begin();
437 InProgressProcesses::iterator ipend = in_progress_.end();
439 for (; ipit != ipend; ++ipit)
445 PreviewLoader::Impl::preview(string const & latex_snippet) const
447 int fs = int(buffer_.fontScalingFactor());
451 fg = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
452 bg = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
454 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
455 // Schedule refresh of all previews on zoom or color changes.
456 // The previews are regenerated only after the zoom factor
457 // has not been changed for about 1 second.
460 delay_refresh_->start(1000);
462 // Don't try to access the cache until we are done.
463 if (delay_refresh_->isActive() || !finished_generating_)
465 Cache::const_iterator it = cache_.find(latex_snippet);
466 return (it == cache_.end()) ? 0 : it->second.get();
470 void PreviewLoader::Impl::refreshPreviews()
472 font_scaling_factor_ = int(buffer_.fontScalingFactor());
473 // Reschedule refresh until the previous process completed.
474 if (!finished_generating_) {
475 delay_refresh_->start(1000);
478 Cache::const_iterator cit = cache_.begin();
479 Cache::const_iterator cend = cache_.end();
481 parent_.remove((cit++)->first);
482 finished_generating_ = false;
483 buffer_.updatePreviews();
491 FindSnippet(string const & s) : snippet_(s) {}
492 bool operator()(InProgressProcess const & process) const
494 BitmapFile const & snippets = process.second.snippets;
495 BitmapFile::const_iterator beg = snippets.begin();
496 BitmapFile::const_iterator end = snippets.end();
497 return find_if(beg, end, FindFirst(snippet_)) != end;
501 string const snippet_;
506 PreviewLoader::Status
507 PreviewLoader::Impl::status(string const & latex_snippet) const
509 Cache::const_iterator cit = cache_.find(latex_snippet);
510 if (cit != cache_.end())
513 PendingSnippets::const_iterator pit = pending_.begin();
514 PendingSnippets::const_iterator pend = pending_.end();
516 pit = find(pit, pend, latex_snippet);
520 InProgressProcesses::const_iterator ipit = in_progress_.begin();
521 InProgressProcesses::const_iterator ipend = in_progress_.end();
523 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
531 void PreviewLoader::Impl::add(string const & latex_snippet)
533 if (!pconverter_ || status(latex_snippet) != NotFound)
536 string const snippet = trim(latex_snippet);
540 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
542 pending_.push_back(snippet);
550 EraseSnippet(string const & s) : snippet_(s) {}
551 void operator()(InProgressProcess & process)
553 BitmapFile & snippets = process.second.snippets;
554 BitmapFile::iterator it = snippets.begin();
555 BitmapFile::iterator end = snippets.end();
557 it = find_if(it, end, FindFirst(snippet_));
559 snippets.erase(it, it+1);
563 string const & snippet_;
569 void PreviewLoader::Impl::remove(string const & latex_snippet)
571 Cache::iterator cit = cache_.find(latex_snippet);
572 if (cit != cache_.end())
575 PendingSnippets::iterator pit = pending_.begin();
576 PendingSnippets::iterator pend = pending_.end();
578 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
580 InProgressProcesses::iterator ipit = in_progress_.begin();
581 InProgressProcesses::iterator ipend = in_progress_.end();
583 for_each(ipit, ipend, EraseSnippet(latex_snippet));
585 while (ipit != ipend) {
586 InProgressProcesses::iterator curr = ipit++;
587 if (curr->second.snippets.empty())
588 in_progress_.erase(curr);
593 void PreviewLoader::Impl::startLoading(bool wait)
595 if (pending_.empty() || !pconverter_)
598 // Only start the process off after the buffer is loaded from file.
599 if (!buffer_.isFullyLoaded())
602 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
604 // As used by the LaTeX file and by the resulting image files
605 FileName const directory(buffer_.temppath());
607 FileName const latexfile = unique_tex_filename(directory);
608 string const filename_base = removeExtension(latexfile.absFileName());
610 // Create an InProgress instance to place in the map of all
611 // such processes if it starts correctly.
612 InProgress inprogress(filename_base, pending_, pconverter_->to());
614 // clear pending_, so we're ready to start afresh.
617 // Output the LaTeX file.
618 // we use the encoding of the buffer
619 Encoding const & enc = buffer_.params().encoding();
621 try { of.reset(enc.iconvName()); }
622 catch (iconv_codecvt_facet_exception const & e) {
623 LYXERR0("Caught iconv exception: " << e.what()
624 << "\nUnable to create LaTeX file: " << latexfile);
629 otexstream os(of, texrow);
630 OutputParams runparams(&enc);
631 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
633 if (!openFileWrite(of, latexfile))
637 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
638 << "Unable to create LaTeX file\n" << latexfile);
641 of << "\\batchmode\n";
643 // Set \jobname of previews to the document name (see bug 9627)
644 of << "\\def\\jobname{"
645 << from_utf8(changeExtension(buffer_.latexName(true), ""))
648 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
649 string latexparam = "";
650 bool docformat = !buffer_.params().default_output_format.empty()
651 && buffer_.params().default_output_format != "default";
652 // Use LATEX flavor if the document does not specify a specific
653 // output format (see bug 9371).
654 OutputParams::FLAVOR flavor = docformat
655 ? buffer_.params().getOutputFlavor()
656 : OutputParams::LATEX;
657 if (buffer_.params().encoding().package() == Encoding::japanese) {
658 latexparam = " --latex=platex";
659 flavor = OutputParams::LATEX;
661 else if (buffer_.params().useNonTeXFonts) {
662 if (flavor == OutputParams::LUATEX)
663 latexparam = " --latex=lualatex";
665 flavor = OutputParams::XETEX;
666 latexparam = " --latex=xelatex";
671 case OutputParams::PDFLATEX:
672 latexparam = " --latex=pdflatex";
674 case OutputParams::XETEX:
675 latexparam = " --latex=xelatex";
677 case OutputParams::LUATEX:
678 latexparam = " --latex=lualatex";
680 case OutputParams::DVILUATEX:
681 latexparam = " --latex=dvilualatex";
684 flavor = OutputParams::LATEX;
687 dumpPreamble(os, flavor);
688 // handle inputenc etc.
689 // I think, this is already hadled by dumpPreamble(): Kornel
690 // buffer_.params().writeEncodingPreamble(os, features);
691 of << "\n\\begin{document}\n";
692 dumpData(of, inprogress.snippets);
693 of << "\n\\end{document}\n";
696 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
697 << "File was not closed properly.");
701 // The conversion command.
703 cs << pconverter_->command()
704 << " " << quoteName(latexfile.toFilesystemEncoding())
705 << " --dpi " << font_scaling_factor_;
708 // The colors should be customizable.
709 if (!buffer_.isExporting()) {
710 ColorCode const fg = PreviewLoader::foregroundColor();
711 ColorCode const bg = PreviewLoader::backgroundColor();
712 cs << " --fg " << theApp()->hexName(fg)
713 << " --bg " << theApp()->hexName(bg);
717 if (buffer_.params().bibtex_command != "default")
718 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
719 else if (buffer_.params().encoding().package() == Encoding::japanese)
720 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
722 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
723 if (buffer_.params().bufferFormat() == "lilypond-book")
726 string const command = cs.str();
729 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
730 int ret = call.startScript(ForkedProcess::Wait, command);
732 static 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"