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 /// \p wait whether to wait for the process to complete or, instead,
211 /// to do it in the background.
212 void startLoading(bool wait = false);
214 void refreshPreviews();
216 /// Emit this signal when an image is ready for display.
217 boost::signal<void(PreviewImage const &)> imageReady;
219 Buffer const & buffer() const { return buffer_; }
222 /// Called by the ForkedCall process that generated the bitmap files.
223 void finishedGenerating(pid_t, int);
225 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
227 void dumpData(odocstream &, BitmapFile const &) const;
229 /** cache_ allows easy retrieval of already-generated images
230 * using the LaTeX snippet as the identifier.
232 typedef shared_ptr<PreviewImage> PreviewImagePtr;
234 typedef map<string, PreviewImagePtr> Cache;
238 /** pending_ stores the LaTeX snippets in anticipation of them being
239 * sent to the converter.
241 PendingSnippets pending_;
243 /** in_progress_ stores all forked processes so that we can proceed
245 The map uses the conversion commands as its identifiers.
247 InProgressProcesses in_progress_;
250 PreviewLoader & parent_;
252 Buffer const & buffer_;
254 mutable int font_scaling_factor_;
256 mutable int fg_color_;
258 mutable int bg_color_;
260 QTimer * delay_refresh_;
262 bool finished_generating_;
264 /// We don't own this
265 static lyx::Converter const * pconverter_;
269 lyx::Converter const * PreviewLoader::Impl::pconverter_;
273 // The public interface, defined in PreviewLoader.h
276 PreviewLoader::PreviewLoader(Buffer const & b)
277 : pimpl_(new Impl(*this, b))
281 PreviewLoader::~PreviewLoader()
287 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
289 return pimpl_->preview(latex_snippet);
293 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
295 return pimpl_->status(latex_snippet);
299 void PreviewLoader::add(string const & latex_snippet) const
301 pimpl_->add(latex_snippet);
305 void PreviewLoader::remove(string const & latex_snippet) const
307 pimpl_->remove(latex_snippet);
311 void PreviewLoader::startLoading(bool wait) const
313 pimpl_->startLoading(wait);
317 void PreviewLoader::refreshPreviews()
319 pimpl_->refreshPreviews();
323 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
325 return pimpl_->imageReady.connect(slot);
329 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
331 pimpl_->imageReady(pimage);
335 Buffer const & PreviewLoader::buffer() const
337 return pimpl_->buffer();
340 } // namespace graphics
344 // The details of the Impl
345 // =======================
349 class IncrementedFileName {
351 IncrementedFileName(string const & to_format,
352 string const & filename_base)
353 : to_format_(to_format), base_(filename_base), counter_(1)
356 SnippetPair const operator()(string const & snippet)
359 os << base_ << counter_++ << '.' << to_format_;
360 string const file = os.str();
362 return make_pair(snippet, FileName(file));
366 string const & to_format_;
367 string const & base_;
372 InProgress::InProgress(string const & filename_base,
373 PendingSnippets const & pending,
374 string const & to_format)
376 metrics_file(filename_base + ".metrics"),
377 snippets(pending.size())
379 PendingSnippets::const_iterator pit = pending.begin();
380 PendingSnippets::const_iterator pend = pending.end();
381 BitmapFile::iterator sit = snippets.begin();
383 transform(pit, pend, sit,
384 IncrementedFileName(to_format, filename_base));
388 void InProgress::stop() const
391 ForkedCallsController::kill(pid, 0);
393 if (!metrics_file.empty())
394 metrics_file.removeFile();
396 BitmapFile::const_iterator vit = snippets.begin();
397 BitmapFile::const_iterator vend = snippets.end();
398 for (; vit != vend; ++vit) {
399 if (!vit->second.empty())
400 vit->second.removeFile();
410 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
411 : parent_(p), buffer_(b), finished_generating_(true)
413 font_scaling_factor_ = int(buffer_.fontScalingFactor());
415 fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
416 bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
419 bg_color_ = 0xffffff;
422 pconverter_ = setConverter("lyxpreview");
424 delay_refresh_ = new QTimer(&parent_);
425 delay_refresh_->setSingleShot(true);
426 QObject::connect(delay_refresh_, SIGNAL(timeout()),
427 &parent_, SLOT(refreshPreviews()));
431 PreviewLoader::Impl::~Impl()
433 delete delay_refresh_;
435 InProgressProcesses::iterator ipit = in_progress_.begin();
436 InProgressProcesses::iterator ipend = in_progress_.end();
438 for (; ipit != ipend; ++ipit)
444 PreviewLoader::Impl::preview(string const & latex_snippet) const
446 int fs = int(buffer_.fontScalingFactor());
450 fg = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
451 bg = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
453 if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
454 // Schedule refresh of all previews on zoom or color changes.
455 // The previews are regenerated only after the zoom factor
456 // has not been changed for about 1 second.
459 delay_refresh_->start(1000);
461 // Don't try to access the cache until we are done.
462 if (delay_refresh_->isActive() || !finished_generating_)
464 Cache::const_iterator it = cache_.find(latex_snippet);
465 return (it == cache_.end()) ? 0 : it->second.get();
469 void PreviewLoader::Impl::refreshPreviews()
471 font_scaling_factor_ = int(buffer_.fontScalingFactor());
472 // Reschedule refresh until the previous process completed.
473 if (!finished_generating_) {
474 delay_refresh_->start(1000);
477 Cache::const_iterator cit = cache_.begin();
478 Cache::const_iterator cend = cache_.end();
480 parent_.remove((cit++)->first);
481 finished_generating_ = false;
482 buffer_.updatePreviews();
490 FindSnippet(string const & s) : snippet_(s) {}
491 bool operator()(InProgressProcess const & process) const
493 BitmapFile const & snippets = process.second.snippets;
494 BitmapFile::const_iterator beg = snippets.begin();
495 BitmapFile::const_iterator end = snippets.end();
496 return find_if(beg, end, FindFirst(snippet_)) != end;
500 string const snippet_;
505 PreviewLoader::Status
506 PreviewLoader::Impl::status(string const & latex_snippet) const
508 Cache::const_iterator cit = cache_.find(latex_snippet);
509 if (cit != cache_.end())
512 PendingSnippets::const_iterator pit = pending_.begin();
513 PendingSnippets::const_iterator pend = pending_.end();
515 pit = find(pit, pend, latex_snippet);
519 InProgressProcesses::const_iterator ipit = in_progress_.begin();
520 InProgressProcesses::const_iterator ipend = in_progress_.end();
522 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
530 void PreviewLoader::Impl::add(string const & latex_snippet)
532 if (!pconverter_ || status(latex_snippet) != NotFound)
535 string const snippet = trim(latex_snippet);
539 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
541 pending_.push_back(snippet);
549 EraseSnippet(string const & s) : snippet_(s) {}
550 void operator()(InProgressProcess & process)
552 BitmapFile & snippets = process.second.snippets;
553 BitmapFile::iterator it = snippets.begin();
554 BitmapFile::iterator end = snippets.end();
556 it = find_if(it, end, FindFirst(snippet_));
558 snippets.erase(it, it+1);
562 string const & snippet_;
568 void PreviewLoader::Impl::remove(string const & latex_snippet)
570 Cache::iterator cit = cache_.find(latex_snippet);
571 if (cit != cache_.end())
574 PendingSnippets::iterator pit = pending_.begin();
575 PendingSnippets::iterator pend = pending_.end();
577 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
579 InProgressProcesses::iterator ipit = in_progress_.begin();
580 InProgressProcesses::iterator ipend = in_progress_.end();
582 for_each(ipit, ipend, EraseSnippet(latex_snippet));
584 while (ipit != ipend) {
585 InProgressProcesses::iterator curr = ipit++;
586 if (curr->second.snippets.empty())
587 in_progress_.erase(curr);
592 void PreviewLoader::Impl::startLoading(bool wait)
594 if (pending_.empty() || !pconverter_)
597 // Only start the process off after the buffer is loaded from file.
598 if (!buffer_.isFullyLoaded())
601 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
603 // As used by the LaTeX file and by the resulting image files
604 FileName const directory(buffer_.temppath());
606 FileName const latexfile = unique_tex_filename(directory);
607 string const filename_base = removeExtension(latexfile.absFileName());
609 // Create an InProgress instance to place in the map of all
610 // such processes if it starts correctly.
611 InProgress inprogress(filename_base, pending_, pconverter_->to());
613 // clear pending_, so we're ready to start afresh.
616 // Output the LaTeX file.
617 // we use the encoding of the buffer
618 Encoding const & enc = buffer_.params().encoding();
620 try { of.reset(enc.iconvName()); }
621 catch (iconv_codecvt_facet_exception const & e) {
622 LYXERR0("Caught iconv exception: " << e.what()
623 << "\nUnable to create LaTeX file: " << latexfile);
628 otexstream os(of, texrow);
629 OutputParams runparams(&enc);
630 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
632 if (!openFileWrite(of, latexfile))
636 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
637 << "Unable to create LaTeX file\n" << latexfile);
640 of << "\\batchmode\n";
642 // Set \jobname of previews to the document name (see bug 9627)
643 of << "\\def\\jobname{"
644 << from_utf8(changeExtension(buffer_.latexName(true), ""))
647 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
648 string latexparam = "";
649 bool docformat = !buffer_.params().default_output_format.empty()
650 && buffer_.params().default_output_format != "default";
651 // Use LATEX flavor if the document does not specify a specific
652 // output format (see bug 9371).
653 OutputParams::FLAVOR flavor = docformat
654 ? buffer_.params().getOutputFlavor()
655 : OutputParams::LATEX;
656 if (buffer_.params().encoding().package() == Encoding::japanese) {
657 latexparam = " --latex=platex";
658 flavor = OutputParams::LATEX;
660 else if (buffer_.params().useNonTeXFonts) {
661 if (flavor == OutputParams::LUATEX)
662 latexparam = " --latex=lualatex";
664 flavor = OutputParams::XETEX;
665 latexparam = " --latex=xelatex";
670 case OutputParams::PDFLATEX:
671 latexparam = " --latex=pdflatex";
673 case OutputParams::XETEX:
674 latexparam = " --latex=xelatex";
676 case OutputParams::LUATEX:
677 latexparam = " --latex=lualatex";
679 case OutputParams::DVILUATEX:
680 latexparam = " --latex=dvilualatex";
683 flavor = OutputParams::LATEX;
686 dumpPreamble(os, flavor);
687 // handle inputenc etc.
688 // I think, this is already hadled by dumpPreamble(): Kornel
689 // buffer_.params().writeEncodingPreamble(os, features);
690 of << "\n\\begin{document}\n";
691 dumpData(of, inprogress.snippets);
692 of << "\n\\end{document}\n";
695 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
696 << "File was not closed properly.");
700 // The conversion command.
702 cs << pconverter_->command()
703 << " " << quoteName(latexfile.toFilesystemEncoding())
704 << " --dpi " << font_scaling_factor_;
707 // The colors should be customizable.
708 if (!buffer_.isExporting()) {
709 ColorCode const fg = PreviewLoader::foregroundColor();
710 ColorCode const bg = PreviewLoader::backgroundColor();
711 cs << " --fg " << theApp()->hexName(fg)
712 << " --bg " << theApp()->hexName(bg);
716 if (buffer_.params().bibtex_command != "default")
717 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
718 else if (buffer_.params().encoding().package() == Encoding::japanese)
719 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
721 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
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);
731 static int fake = (2^20) + 1;
733 inprogress.pid = pid;
734 inprogress.command = command;
735 in_progress_[pid] = inprogress;
736 finishedGenerating(pid, ret);
740 // Initiate the conversion from LaTeX to bitmap images files.
741 ForkedCall::SignalTypePtr
742 convert_ptr(new ForkedCall::SignalType);
743 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
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"