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"
50 using namespace lyx::support;
56 typedef pair<string, FileName> SnippetPair;
58 // A list of all snippets to be converted to previews
59 typedef list<string> PendingSnippets;
61 // Each item in the vector is a pair<snippet, image file name>.
62 typedef vector<SnippetPair> BitmapFile;
65 FileName const unique_tex_filename(FileName const & bufferpath)
67 TempFile tempfile(bufferpath, "lyxpreviewXXXXXX.tex");
68 tempfile.setAutoRemove(false);
69 return tempfile.name();
73 lyx::Converter const * setConverter(string const & from)
75 typedef vector<string> FmtList;
76 typedef lyx::graphics::Cache GCache;
77 FmtList const & loadableFormats = GCache::get().loadableFormats();
78 FmtList::const_iterator it = loadableFormats.begin();
79 FmtList::const_iterator const end = loadableFormats.end();
81 for (; it != end; ++it) {
82 string const to = *it;
86 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
92 static bool first = true;
95 LYXERR0("PreviewLoader::startLoading()\n"
96 << "No converter from \"" << from << "\" format has been defined.");
102 void setAscentFractions(vector<double> & ascent_fractions,
103 FileName const & metrics_file)
105 // If all else fails, then the images will have equal ascents and
107 vector<double>::iterator it = ascent_fractions.begin();
108 vector<double>::iterator end = ascent_fractions.end();
111 ifstream in(metrics_file.toFilesystemEncoding().c_str());
113 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
114 << "Unable to open file!");
120 int snippet_counter = 1;
121 while (!in.eof() && it != end) {
124 double ascent_fraction;
126 in >> snippet >> id >> ascent_fraction;
132 error = snippet != "Snippet";
136 error = id != snippet_counter;
140 *it = ascent_fraction;
147 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
148 << "Error reading file!\n");
156 FindFirst(string const & comp) : comp_(comp) {}
157 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
163 /// Store info on a currently executing, forked process.
167 InProgress() : pid(0) {}
169 InProgress(string const & filename_base,
170 PendingSnippets const & pending,
171 string const & to_format);
172 /// Remove any files left lying around and kill the forked process.
180 FileName metrics_file;
185 typedef map<pid_t, InProgress> InProgressProcesses;
187 typedef InProgressProcesses::value_type InProgressProcess;
196 class PreviewLoader::Impl : public boost::signals::trackable {
199 Impl(PreviewLoader & p, Buffer const & b);
200 /// Stop any InProgress items still executing.
203 PreviewImage const * preview(string const & latex_snippet) const;
205 PreviewLoader::Status status(string const & latex_snippet) const;
207 void add(string const & latex_snippet);
209 void remove(string const & latex_snippet);
210 /// Record math macro definitions added to the loader
211 void addMacroDef(docstring const & latex_snippet);
212 /// Has a math macro definition already been added to the loader?
213 bool hasMacroDef(docstring const & latex_snippet) const;
214 /// \p wait whether to wait for the process to complete or, instead,
215 /// to do it in the background.
216 void startLoading(bool wait = false);
218 void refreshPreviews();
220 /// Emit this signal when an image is ready for display.
221 boost::signal<void(PreviewImage const &)> imageReady;
223 Buffer const & buffer() const { return buffer_; }
226 /// Called by the ForkedCall process that generated the bitmap files.
227 void finishedGenerating(pid_t, int);
229 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
231 void dumpData(odocstream &, BitmapFile const &) const;
233 /** cache_ allows easy retrieval of already-generated images
234 * using the LaTeX snippet as the identifier.
236 typedef shared_ptr<PreviewImage> PreviewImagePtr;
238 typedef map<string, PreviewImagePtr> Cache;
242 /** pending_ stores the LaTeX snippets in anticipation of them being
243 * sent to the converter.
245 PendingSnippets pending_;
247 /** in_progress_ stores all forked processes so that we can proceed
249 The map uses the conversion commands as its identifiers.
251 InProgressProcesses in_progress_;
254 set<docstring> macrodefs_;
257 PreviewLoader & parent_;
259 Buffer const & buffer_;
261 mutable int font_scaling_factor_;
263 QTimer * delay_refresh_;
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::addMacroDef(docstring const & latex_snippet) const
314 pimpl_->addMacroDef(latex_snippet);
318 bool PreviewLoader::hasMacroDef(docstring const & latex_snippet) const
320 return pimpl_->hasMacroDef(latex_snippet);
324 void PreviewLoader::startLoading(bool wait) const
326 pimpl_->startLoading(wait);
330 void PreviewLoader::refreshPreviews()
332 pimpl_->refreshPreviews();
336 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
338 return pimpl_->imageReady.connect(slot);
342 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
344 pimpl_->imageReady(pimage);
348 Buffer const & PreviewLoader::buffer() const
350 return pimpl_->buffer();
353 } // namespace graphics
357 // The details of the Impl
358 // =======================
362 class IncrementedFileName {
364 IncrementedFileName(string const & to_format,
365 string const & filename_base)
366 : to_format_(to_format), base_(filename_base), counter_(1)
369 SnippetPair const operator()(string const & snippet)
372 os << base_ << counter_++ << '.' << to_format_;
373 string const file = os.str();
375 return make_pair(snippet, FileName(file));
379 string const & to_format_;
380 string const & base_;
385 InProgress::InProgress(string const & filename_base,
386 PendingSnippets const & pending,
387 string const & to_format)
389 metrics_file(filename_base + ".metrics"),
390 snippets(pending.size())
392 PendingSnippets::const_iterator pit = pending.begin();
393 PendingSnippets::const_iterator pend = pending.end();
394 BitmapFile::iterator sit = snippets.begin();
396 transform(pit, pend, sit,
397 IncrementedFileName(to_format, filename_base));
401 void InProgress::stop() const
404 ForkedCallsController::kill(pid, 0);
406 if (!metrics_file.empty())
407 metrics_file.removeFile();
409 BitmapFile::const_iterator vit = snippets.begin();
410 BitmapFile::const_iterator vend = snippets.end();
411 for (; vit != vend; ++vit) {
412 if (!vit->second.empty())
413 vit->second.removeFile();
423 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
424 : parent_(p), buffer_(b)
426 font_scaling_factor_ = int(buffer_.fontScalingFactor());
428 pconverter_ = setConverter("lyxpreview");
430 delay_refresh_ = new QTimer(&parent_);
431 delay_refresh_->setSingleShot(true);
432 QObject::connect(delay_refresh_, SIGNAL(timeout()),
433 &parent_, SLOT(refreshPreviews()));
437 PreviewLoader::Impl::~Impl()
439 InProgressProcesses::iterator ipit = in_progress_.begin();
440 InProgressProcesses::iterator ipend = in_progress_.end();
442 for (; ipit != ipend; ++ipit)
448 PreviewLoader::Impl::preview(string const & latex_snippet) const
450 int fs = int(buffer_.fontScalingFactor());
451 if (font_scaling_factor_ != fs) {
452 // Schedule refresh of all previews on zoom changes.
453 // The previews are regenerated only after the zoom factor
454 // has not been changed for about 1 second.
455 delay_refresh_->start(1000);
457 // Don't try to access the cache until we are finished.
458 if (delay_refresh_->isActive())
460 Cache::const_iterator it = cache_.find(latex_snippet);
461 return (it == cache_.end()) ? 0 : it->second.get();
465 void PreviewLoader::Impl::refreshPreviews()
467 font_scaling_factor_ = int(buffer_.fontScalingFactor());
468 Cache::const_iterator cit = cache_.begin();
469 Cache::const_iterator cend = cache_.end();
471 parent_.remove((cit++)->first);
472 buffer_.updatePreviews();
480 FindSnippet(string const & s) : snippet_(s) {}
481 bool operator()(InProgressProcess const & process) const
483 BitmapFile const & snippets = process.second.snippets;
484 BitmapFile::const_iterator beg = snippets.begin();
485 BitmapFile::const_iterator end = snippets.end();
486 return find_if(beg, end, FindFirst(snippet_)) != end;
490 string const snippet_;
495 PreviewLoader::Status
496 PreviewLoader::Impl::status(string const & latex_snippet) const
498 Cache::const_iterator cit = cache_.find(latex_snippet);
499 if (cit != cache_.end())
502 PendingSnippets::const_iterator pit = pending_.begin();
503 PendingSnippets::const_iterator pend = pending_.end();
505 pit = find(pit, pend, latex_snippet);
509 InProgressProcesses::const_iterator ipit = in_progress_.begin();
510 InProgressProcesses::const_iterator ipend = in_progress_.end();
512 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
520 void PreviewLoader::Impl::add(string const & latex_snippet)
522 if (!pconverter_ || status(latex_snippet) != NotFound)
525 string const snippet = trim(latex_snippet);
529 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
531 pending_.push_back(snippet);
539 EraseSnippet(string const & s) : snippet_(s) {}
540 void operator()(InProgressProcess & process)
542 BitmapFile & snippets = process.second.snippets;
543 BitmapFile::iterator it = snippets.begin();
544 BitmapFile::iterator end = snippets.end();
546 it = find_if(it, end, FindFirst(snippet_));
548 snippets.erase(it, it+1);
552 string const & snippet_;
558 void PreviewLoader::Impl::remove(string const & latex_snippet)
560 Cache::iterator cit = cache_.find(latex_snippet);
561 if (cit != cache_.end())
564 PendingSnippets::iterator pit = pending_.begin();
565 PendingSnippets::iterator pend = pending_.end();
567 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
569 InProgressProcesses::iterator ipit = in_progress_.begin();
570 InProgressProcesses::iterator ipend = in_progress_.end();
572 for_each(ipit, ipend, EraseSnippet(latex_snippet));
574 while (ipit != ipend) {
575 InProgressProcesses::iterator curr = ipit++;
576 if (curr->second.snippets.empty())
577 in_progress_.erase(curr);
582 void PreviewLoader::Impl::addMacroDef(docstring const & latex_snippet)
584 macrodefs_.insert(latex_snippet);
588 bool PreviewLoader::Impl::hasMacroDef(docstring const & latex_snippet) const
590 return macrodefs_.find(latex_snippet) != macrodefs_.end();
594 void PreviewLoader::Impl::startLoading(bool wait)
596 if (pending_.empty() || !pconverter_)
599 // Only start the process off after the buffer is loaded from file.
600 if (!buffer_.isFullyLoaded())
603 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
605 // As used by the LaTeX file and by the resulting image files
606 FileName const directory(buffer_.temppath());
608 FileName const latexfile = unique_tex_filename(directory);
609 string const filename_base = removeExtension(latexfile.absFileName());
611 // Create an InProgress instance to place in the map of all
612 // such processes if it starts correctly.
613 InProgress inprogress(filename_base, pending_, pconverter_->to());
615 // clear pending_, so we're ready to start afresh.
618 // Output the LaTeX file.
619 // we use the encoding of the buffer
620 Encoding const & enc = buffer_.params().encoding();
622 try { of.reset(enc.iconvName()); }
623 catch (iconv_codecvt_facet_exception const & e) {
624 LYXERR0("Caught iconv exception: " << e.what()
625 << "\nUnable to create LaTeX file: " << latexfile);
630 otexstream os(of, texrow);
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 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
645 string latexparam = "";
646 bool docformat = !buffer_.params().default_output_format.empty()
647 && buffer_.params().default_output_format != "default";
648 // Use LATEX flavor if the document does not specify a specific
649 // output format (see bug 9371).
650 OutputParams::FLAVOR flavor = docformat
651 ? buffer_.params().getOutputFlavor()
652 : OutputParams::LATEX;
653 if (buffer_.params().encoding().package() == Encoding::japanese) {
654 latexparam = " --latex=platex";
655 flavor = OutputParams::LATEX;
657 else if (buffer_.params().useNonTeXFonts) {
658 if (flavor == OutputParams::LUATEX)
659 latexparam = " --latex=lualatex";
661 flavor = OutputParams::XETEX;
662 latexparam = " --latex=xelatex";
667 case OutputParams::PDFLATEX:
668 latexparam = " --latex=pdflatex";
670 case OutputParams::XETEX:
671 latexparam = " --latex=xelatex";
673 case OutputParams::LUATEX:
674 latexparam = " --latex=lualatex";
676 case OutputParams::DVILUATEX:
677 latexparam = " --latex=dvilualatex";
680 flavor = OutputParams::LATEX;
683 dumpPreamble(os, flavor);
684 // handle inputenc etc.
685 // I think, this is already hadled by dumpPreamble(): Kornel
686 // buffer_.params().writeEncodingPreamble(os, features);
687 of << "\n\\begin{document}\n";
688 dumpData(of, inprogress.snippets);
689 of << "\n\\end{document}\n";
692 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
693 << "File was not closed properly.");
697 // The conversion command.
699 cs << pconverter_->command()
700 << " " << quoteName(latexfile.toFilesystemEncoding())
701 << " --dpi " << font_scaling_factor_;
704 // The colors should be customizable.
705 if (!buffer_.isExporting()) {
706 ColorCode const fg = PreviewLoader::foregroundColor();
707 ColorCode const bg = PreviewLoader::backgroundColor();
708 cs << " --fg " << theApp()->hexName(fg)
709 << " --bg " << theApp()->hexName(bg);
713 if (buffer_.params().bibtex_command != "default")
714 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
715 else if (buffer_.params().encoding().package() == Encoding::japanese)
716 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
718 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
719 if (buffer_.params().bufferFormat() == "lilypond-book")
722 string const command = cs.str();
725 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
726 int ret = call.startScript(ForkedProcess::Wait, command);
728 static int fake = (2^20) + 1;
730 inprogress.pid = pid;
731 inprogress.command = command;
732 in_progress_[pid] = inprogress;
733 finishedGenerating(pid, ret);
737 // Initiate the conversion from LaTeX to bitmap images files.
738 ForkedCall::SignalTypePtr
739 convert_ptr(new ForkedCall::SignalType);
740 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
742 ForkedCall call(buffer_.filePath());
743 int ret = call.startScript(command, convert_ptr);
746 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
747 << "Unable to start process\n" << command);
751 // Store the generation process in a list of all such processes
752 inprogress.pid = call.pid();
753 inprogress.command = command;
754 in_progress_[inprogress.pid] = inprogress;
758 double PreviewLoader::displayPixelRatio() const
760 return buffer().params().display_pixel_ratio;
763 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
766 InProgressProcesses::iterator git = in_progress_.find(pid);
767 if (git == in_progress_.end()) {
768 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
769 "data for PID " << pid << endl;
773 string const command = git->second.command;
774 string const status = retval > 0 ? "failed" : "succeeded";
775 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
776 << retval << "): processing " << status
777 << " for " << command);
781 // Read the metrics file, if it exists
782 vector<double> ascent_fractions(git->second.snippets.size());
783 setAscentFractions(ascent_fractions, git->second.metrics_file);
785 // Add these newly generated bitmap files to the cache and
786 // start loading them into LyX.
787 BitmapFile::const_iterator it = git->second.snippets.begin();
788 BitmapFile::const_iterator end = git->second.snippets.end();
790 list<PreviewImagePtr> newimages;
792 int metrics_counter = 0;
793 for (; it != end; ++it, ++metrics_counter) {
794 string const & snip = it->first;
795 FileName const & file = it->second;
796 double af = ascent_fractions[metrics_counter];
798 // Add the image to the cache only if it's actually present
799 // and not empty (an empty image is signaled by af < 0)
800 if (af >= 0 && file.isReadableFile()) {
801 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
804 newimages.push_back(ptr);
809 // Remove the item from the list of still-executing processes.
810 in_progress_.erase(git);
812 // Tell the outside world
813 list<PreviewImagePtr>::const_reverse_iterator
814 nit = newimages.rbegin();
815 list<PreviewImagePtr>::const_reverse_iterator
816 nend = newimages.rend();
817 for (; nit != nend; ++nit) {
818 imageReady(*nit->get());
823 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
825 // Dump the preamble only.
826 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
827 OutputParams runparams(&buffer_.params().encoding());
828 runparams.flavor = flavor;
829 runparams.nice = true;
830 runparams.moving_arg = true;
831 runparams.free_spacing = true;
832 runparams.is_child = buffer_.parent();
833 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
835 // FIXME! This is a HACK! The proper fix is to control the 'true'
836 // passed to WriteStream below:
837 // int InsetMathNest::latex(Buffer const &, odocstream & os,
838 // OutputParams const & runparams) const
840 // WriteStream wi(os, runparams.moving_arg, true);
845 << "\\def\\lyxlock{}\n"
848 // All equation labels appear as "(#)" + preview.sty's rendering of
850 if (lyxrc.preview_hashed_labels)
851 os << "\\renewcommand{\\theequation}{\\#}\n";
853 // Use the preview style file to ensure that each snippet appears on a
855 // Also support PDF output (automatically generated e.g. when
856 // \usepackage[pdftex]{hyperref} is used and XeTeX.
858 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
863 void PreviewLoader::Impl::dumpData(odocstream & os,
864 BitmapFile const & vec) const
869 BitmapFile::const_iterator it = vec.begin();
870 BitmapFile::const_iterator end = vec.end();
872 for (; it != end; ++it) {
874 os << "\\begin{preview}\n"
875 << from_utf8(it->first)
876 << "\n\\end{preview}\n\n";
880 } // namespace graphics
883 #include "moc_PreviewLoader.cpp"