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 QTimer * delay_refresh_;
258 bool finished_generating_;
260 /// We don't own this
261 static lyx::Converter const * pconverter_;
265 lyx::Converter const * PreviewLoader::Impl::pconverter_;
269 // The public interface, defined in PreviewLoader.h
272 PreviewLoader::PreviewLoader(Buffer const & b)
273 : pimpl_(new Impl(*this, b))
277 PreviewLoader::~PreviewLoader()
283 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
285 return pimpl_->preview(latex_snippet);
289 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
291 return pimpl_->status(latex_snippet);
295 void PreviewLoader::add(string const & latex_snippet) const
297 pimpl_->add(latex_snippet);
301 void PreviewLoader::remove(string const & latex_snippet) const
303 pimpl_->remove(latex_snippet);
307 void PreviewLoader::startLoading(bool wait) const
309 pimpl_->startLoading(wait);
313 void PreviewLoader::refreshPreviews()
315 pimpl_->refreshPreviews();
319 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
321 return pimpl_->imageReady.connect(slot);
325 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
327 pimpl_->imageReady(pimage);
331 Buffer const & PreviewLoader::buffer() const
333 return pimpl_->buffer();
336 } // namespace graphics
340 // The details of the Impl
341 // =======================
345 class IncrementedFileName {
347 IncrementedFileName(string const & to_format,
348 string const & filename_base)
349 : to_format_(to_format), base_(filename_base), counter_(1)
352 SnippetPair const operator()(string const & snippet)
355 os << base_ << counter_++ << '.' << to_format_;
356 string const file = os.str();
358 return make_pair(snippet, FileName(file));
362 string const & to_format_;
363 string const & base_;
368 InProgress::InProgress(string const & filename_base,
369 PendingSnippets const & pending,
370 string const & to_format)
372 metrics_file(filename_base + ".metrics"),
373 snippets(pending.size())
375 PendingSnippets::const_iterator pit = pending.begin();
376 PendingSnippets::const_iterator pend = pending.end();
377 BitmapFile::iterator sit = snippets.begin();
379 transform(pit, pend, sit,
380 IncrementedFileName(to_format, filename_base));
384 void InProgress::stop() const
387 ForkedCallsController::kill(pid, 0);
389 if (!metrics_file.empty())
390 metrics_file.removeFile();
392 BitmapFile::const_iterator vit = snippets.begin();
393 BitmapFile::const_iterator vend = snippets.end();
394 for (; vit != vend; ++vit) {
395 if (!vit->second.empty())
396 vit->second.removeFile();
406 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
407 : parent_(p), buffer_(b), finished_generating_(true)
409 font_scaling_factor_ = int(buffer_.fontScalingFactor());
411 pconverter_ = setConverter("lyxpreview");
413 delay_refresh_ = new QTimer(&parent_);
414 delay_refresh_->setSingleShot(true);
415 QObject::connect(delay_refresh_, SIGNAL(timeout()),
416 &parent_, SLOT(refreshPreviews()));
420 PreviewLoader::Impl::~Impl()
422 delete delay_refresh_;
424 InProgressProcesses::iterator ipit = in_progress_.begin();
425 InProgressProcesses::iterator ipend = in_progress_.end();
427 for (; ipit != ipend; ++ipit)
433 PreviewLoader::Impl::preview(string const & latex_snippet) const
435 int fs = int(buffer_.fontScalingFactor());
436 if (font_scaling_factor_ != fs) {
437 // Schedule refresh of all previews on zoom changes.
438 // The previews are regenerated only after the zoom factor
439 // has not been changed for about 1 second.
440 delay_refresh_->start(1000);
442 // Don't try to access the cache until we are done.
443 if (delay_refresh_->isActive() || !finished_generating_)
445 Cache::const_iterator it = cache_.find(latex_snippet);
446 return (it == cache_.end()) ? 0 : it->second.get();
450 void PreviewLoader::Impl::refreshPreviews()
452 font_scaling_factor_ = int(buffer_.fontScalingFactor());
453 Cache::const_iterator cit = cache_.begin();
454 Cache::const_iterator cend = cache_.end();
456 parent_.remove((cit++)->first);
457 finished_generating_ = false;
458 buffer_.updatePreviews();
466 FindSnippet(string const & s) : snippet_(s) {}
467 bool operator()(InProgressProcess const & process) const
469 BitmapFile const & snippets = process.second.snippets;
470 BitmapFile::const_iterator beg = snippets.begin();
471 BitmapFile::const_iterator end = snippets.end();
472 return find_if(beg, end, FindFirst(snippet_)) != end;
476 string const snippet_;
481 PreviewLoader::Status
482 PreviewLoader::Impl::status(string const & latex_snippet) const
484 Cache::const_iterator cit = cache_.find(latex_snippet);
485 if (cit != cache_.end())
488 PendingSnippets::const_iterator pit = pending_.begin();
489 PendingSnippets::const_iterator pend = pending_.end();
491 pit = find(pit, pend, latex_snippet);
495 InProgressProcesses::const_iterator ipit = in_progress_.begin();
496 InProgressProcesses::const_iterator ipend = in_progress_.end();
498 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
506 void PreviewLoader::Impl::add(string const & latex_snippet)
508 if (!pconverter_ || status(latex_snippet) != NotFound)
511 string const snippet = trim(latex_snippet);
515 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
517 pending_.push_back(snippet);
525 EraseSnippet(string const & s) : snippet_(s) {}
526 void operator()(InProgressProcess & process)
528 BitmapFile & snippets = process.second.snippets;
529 BitmapFile::iterator it = snippets.begin();
530 BitmapFile::iterator end = snippets.end();
532 it = find_if(it, end, FindFirst(snippet_));
534 snippets.erase(it, it+1);
538 string const & snippet_;
544 void PreviewLoader::Impl::remove(string const & latex_snippet)
546 Cache::iterator cit = cache_.find(latex_snippet);
547 if (cit != cache_.end())
550 PendingSnippets::iterator pit = pending_.begin();
551 PendingSnippets::iterator pend = pending_.end();
553 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
555 InProgressProcesses::iterator ipit = in_progress_.begin();
556 InProgressProcesses::iterator ipend = in_progress_.end();
558 for_each(ipit, ipend, EraseSnippet(latex_snippet));
560 while (ipit != ipend) {
561 InProgressProcesses::iterator curr = ipit++;
562 if (curr->second.snippets.empty())
563 in_progress_.erase(curr);
568 void PreviewLoader::Impl::startLoading(bool wait)
570 if (pending_.empty() || !pconverter_)
573 // Only start the process off after the buffer is loaded from file.
574 if (!buffer_.isFullyLoaded())
577 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
579 // As used by the LaTeX file and by the resulting image files
580 FileName const directory(buffer_.temppath());
582 FileName const latexfile = unique_tex_filename(directory);
583 string const filename_base = removeExtension(latexfile.absFileName());
585 // Create an InProgress instance to place in the map of all
586 // such processes if it starts correctly.
587 InProgress inprogress(filename_base, pending_, pconverter_->to());
589 // clear pending_, so we're ready to start afresh.
592 // Output the LaTeX file.
593 // we use the encoding of the buffer
594 Encoding const & enc = buffer_.params().encoding();
596 try { of.reset(enc.iconvName()); }
597 catch (iconv_codecvt_facet_exception const & e) {
598 LYXERR0("Caught iconv exception: " << e.what()
599 << "\nUnable to create LaTeX file: " << latexfile);
604 otexstream os(of, texrow);
605 OutputParams runparams(&enc);
606 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
608 if (!openFileWrite(of, latexfile))
612 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
613 << "Unable to create LaTeX file\n" << latexfile);
616 of << "\\batchmode\n";
618 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
619 string latexparam = "";
620 bool docformat = !buffer_.params().default_output_format.empty()
621 && buffer_.params().default_output_format != "default";
622 // Use LATEX flavor if the document does not specify a specific
623 // output format (see bug 9371).
624 OutputParams::FLAVOR flavor = docformat
625 ? buffer_.params().getOutputFlavor()
626 : OutputParams::LATEX;
627 if (buffer_.params().encoding().package() == Encoding::japanese) {
628 latexparam = " --latex=platex";
629 flavor = OutputParams::LATEX;
631 else if (buffer_.params().useNonTeXFonts) {
632 if (flavor == OutputParams::LUATEX)
633 latexparam = " --latex=lualatex";
635 flavor = OutputParams::XETEX;
636 latexparam = " --latex=xelatex";
641 case OutputParams::PDFLATEX:
642 latexparam = " --latex=pdflatex";
644 case OutputParams::XETEX:
645 latexparam = " --latex=xelatex";
647 case OutputParams::LUATEX:
648 latexparam = " --latex=lualatex";
650 case OutputParams::DVILUATEX:
651 latexparam = " --latex=dvilualatex";
654 flavor = OutputParams::LATEX;
657 dumpPreamble(os, flavor);
658 // handle inputenc etc.
659 // I think, this is already hadled by dumpPreamble(): Kornel
660 // buffer_.params().writeEncodingPreamble(os, features);
661 of << "\n\\begin{document}\n";
662 dumpData(of, inprogress.snippets);
663 of << "\n\\end{document}\n";
666 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
667 << "File was not closed properly.");
671 // The conversion command.
673 cs << pconverter_->command()
674 << " " << quoteName(latexfile.toFilesystemEncoding())
675 << " --dpi " << font_scaling_factor_;
678 // The colors should be customizable.
679 if (!buffer_.isExporting()) {
680 ColorCode const fg = PreviewLoader::foregroundColor();
681 ColorCode const bg = PreviewLoader::backgroundColor();
682 cs << " --fg " << theApp()->hexName(fg)
683 << " --bg " << theApp()->hexName(bg);
687 if (buffer_.params().bibtex_command != "default")
688 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
689 else if (buffer_.params().encoding().package() == Encoding::japanese)
690 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
692 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
693 if (buffer_.params().bufferFormat() == "lilypond-book")
696 string const command = cs.str();
699 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
700 int ret = call.startScript(ForkedProcess::Wait, command);
702 static int fake = (2^20) + 1;
704 inprogress.pid = pid;
705 inprogress.command = command;
706 in_progress_[pid] = inprogress;
707 finishedGenerating(pid, ret);
711 // Initiate the conversion from LaTeX to bitmap images files.
712 ForkedCall::SignalTypePtr
713 convert_ptr(new ForkedCall::SignalType);
714 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
716 ForkedCall call(buffer_.filePath());
717 int ret = call.startScript(command, convert_ptr);
720 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
721 << "Unable to start process\n" << command);
725 // Store the generation process in a list of all such processes
726 inprogress.pid = call.pid();
727 inprogress.command = command;
728 in_progress_[inprogress.pid] = inprogress;
732 double PreviewLoader::displayPixelRatio() const
734 return buffer().params().display_pixel_ratio;
737 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
740 InProgressProcesses::iterator git = in_progress_.find(pid);
741 if (git == in_progress_.end()) {
742 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
743 "data for PID " << pid << endl;
747 string const command = git->second.command;
748 string const status = retval > 0 ? "failed" : "succeeded";
749 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
750 << retval << "): processing " << status
751 << " for " << command);
755 // Read the metrics file, if it exists
756 vector<double> ascent_fractions(git->second.snippets.size());
757 setAscentFractions(ascent_fractions, git->second.metrics_file);
759 // Add these newly generated bitmap files to the cache and
760 // start loading them into LyX.
761 BitmapFile::const_iterator it = git->second.snippets.begin();
762 BitmapFile::const_iterator end = git->second.snippets.end();
764 list<PreviewImagePtr> newimages;
766 int metrics_counter = 0;
767 for (; it != end; ++it, ++metrics_counter) {
768 string const & snip = it->first;
769 FileName const & file = it->second;
770 double af = ascent_fractions[metrics_counter];
772 // Add the image to the cache only if it's actually present
773 // and not empty (an empty image is signaled by af < 0)
774 if (af >= 0 && file.isReadableFile()) {
775 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
778 newimages.push_back(ptr);
783 // Remove the item from the list of still-executing processes.
784 in_progress_.erase(git);
786 // Tell the outside world
787 list<PreviewImagePtr>::const_reverse_iterator
788 nit = newimages.rbegin();
789 list<PreviewImagePtr>::const_reverse_iterator
790 nend = newimages.rend();
791 for (; nit != nend; ++nit) {
792 imageReady(*nit->get());
794 finished_generating_ = true;
798 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
800 // Dump the preamble only.
801 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
802 OutputParams runparams(&buffer_.params().encoding());
803 runparams.flavor = flavor;
804 runparams.nice = true;
805 runparams.moving_arg = true;
806 runparams.free_spacing = true;
807 runparams.is_child = buffer_.parent();
808 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
810 // FIXME! This is a HACK! The proper fix is to control the 'true'
811 // passed to WriteStream below:
812 // int InsetMathNest::latex(Buffer const &, odocstream & os,
813 // OutputParams const & runparams) const
815 // WriteStream wi(os, runparams.moving_arg, true);
820 << "\\def\\lyxlock{}\n"
823 // All equation labels appear as "(#)" + preview.sty's rendering of
825 if (lyxrc.preview_hashed_labels)
826 os << "\\renewcommand{\\theequation}{\\#}\n";
828 // Use the preview style file to ensure that each snippet appears on a
830 // Also support PDF output (automatically generated e.g. when
831 // \usepackage[pdftex]{hyperref} is used and XeTeX.
833 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
838 void PreviewLoader::Impl::dumpData(odocstream & os,
839 BitmapFile const & vec) const
844 BitmapFile::const_iterator it = vec.begin();
845 BitmapFile::const_iterator end = vec.end();
847 for (; it != end; ++it) {
849 os << "\\begin{preview}\n"
850 << from_utf8(it->first)
851 << "\n\\end{preview}\n\n";
855 } // namespace graphics
858 #include "moc_PreviewLoader.cpp"