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"
48 using namespace lyx::support;
54 typedef pair<string, FileName> SnippetPair;
56 // A list of all snippets to be converted to previews
57 typedef list<string> PendingSnippets;
59 // Each item in the vector is a pair<snippet, image file name>.
60 typedef vector<SnippetPair> BitmapFile;
63 FileName const unique_tex_filename(FileName const & bufferpath)
65 TempFile tempfile(bufferpath, "lyxpreviewXXXXXX.tex");
66 tempfile.setAutoRemove(false);
67 return tempfile.name();
71 lyx::Converter const * setConverter(string const & from)
73 typedef vector<string> FmtList;
74 typedef lyx::graphics::Cache GCache;
75 FmtList const & loadableFormats = GCache::get().loadableFormats();
76 FmtList::const_iterator it = loadableFormats.begin();
77 FmtList::const_iterator const end = loadableFormats.end();
79 for (; it != end; ++it) {
80 string const to = *it;
84 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
90 static bool first = true;
93 LYXERR0("PreviewLoader::startLoading()\n"
94 << "No converter from \"" << from << "\" format has been defined.");
100 void setAscentFractions(vector<double> & ascent_fractions,
101 FileName const & metrics_file)
103 // If all else fails, then the images will have equal ascents and
105 vector<double>::iterator it = ascent_fractions.begin();
106 vector<double>::iterator end = ascent_fractions.end();
109 ifstream in(metrics_file.toFilesystemEncoding().c_str());
111 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
112 << "Unable to open file!");
118 int snippet_counter = 1;
119 while (!in.eof() && it != end) {
122 double ascent_fraction;
124 in >> snippet >> id >> ascent_fraction;
130 error = snippet != "Snippet";
134 error = id != snippet_counter;
138 *it = ascent_fraction;
145 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
146 << "Error reading file!\n");
154 FindFirst(string const & comp) : comp_(comp) {}
155 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
161 /// Store info on a currently executing, forked process.
165 InProgress() : pid(0) {}
167 InProgress(string const & filename_base,
168 PendingSnippets const & pending,
169 string const & to_format);
170 /// Remove any files left lying around and kill the forked process.
178 FileName metrics_file;
183 typedef map<pid_t, InProgress> InProgressProcesses;
185 typedef InProgressProcesses::value_type InProgressProcess;
194 class PreviewLoader::Impl : public boost::signals::trackable {
197 Impl(PreviewLoader & p, Buffer const & b);
198 /// Stop any InProgress items still executing.
201 PreviewImage const * preview(string const & latex_snippet) const;
203 PreviewLoader::Status status(string const & latex_snippet) const;
205 void add(string const & latex_snippet);
207 void remove(string const & latex_snippet);
208 /// Record math macro definitions added to the loader
209 void addMacroDef(docstring const & latex_snippet);
210 /// Has a math macro definition already been added to the loader?
211 bool hasMacroDef(docstring const & latex_snippet) const;
212 /// \p wait whether to wait for the process to complete or, instead,
213 /// to do it in the background.
214 void startLoading(bool wait = false);
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 set<docstring> macrodefs_;
253 PreviewLoader & parent_;
255 Buffer const & buffer_;
257 mutable int font_scaling_factor_;
259 /// We don't own this
260 static lyx::Converter const * pconverter_;
264 lyx::Converter const * PreviewLoader::Impl::pconverter_;
268 // The public interface, defined in PreviewLoader.h
271 PreviewLoader::PreviewLoader(Buffer const & b)
272 : pimpl_(new Impl(*this, b))
276 PreviewLoader::~PreviewLoader()
282 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
284 return pimpl_->preview(latex_snippet);
288 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
290 return pimpl_->status(latex_snippet);
294 void PreviewLoader::add(string const & latex_snippet) const
296 pimpl_->add(latex_snippet);
300 void PreviewLoader::remove(string const & latex_snippet) const
302 pimpl_->remove(latex_snippet);
306 void PreviewLoader::addMacroDef(docstring const & latex_snippet) const
308 pimpl_->addMacroDef(latex_snippet);
312 bool PreviewLoader::hasMacroDef(docstring const & latex_snippet) const
314 return pimpl_->hasMacroDef(latex_snippet);
318 void PreviewLoader::startLoading(bool wait) const
320 pimpl_->startLoading(wait);
324 boost::signals::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)
414 font_scaling_factor_ = int(buffer_.fontScalingFactor());
416 pconverter_ = setConverter("lyxpreview");
420 PreviewLoader::Impl::~Impl()
422 InProgressProcesses::iterator ipit = in_progress_.begin();
423 InProgressProcesses::iterator ipend = in_progress_.end();
425 for (; ipit != ipend; ++ipit)
431 PreviewLoader::Impl::preview(string const & latex_snippet) const
433 int fs = int(buffer_.fontScalingFactor());
434 if (font_scaling_factor_ != fs) {
435 // Refresh all previews on zoom changes
436 font_scaling_factor_ = fs;
437 Cache::const_iterator cit = cache_.begin();
438 Cache::const_iterator cend = cache_.end();
440 parent_.remove((cit++)->first);
441 buffer_.updatePreviews();
443 Cache::const_iterator it = cache_.find(latex_snippet);
444 return (it == cache_.end()) ? 0 : it->second.get();
452 FindSnippet(string const & s) : snippet_(s) {}
453 bool operator()(InProgressProcess const & process) const
455 BitmapFile const & snippets = process.second.snippets;
456 BitmapFile::const_iterator beg = snippets.begin();
457 BitmapFile::const_iterator end = snippets.end();
458 return find_if(beg, end, FindFirst(snippet_)) != end;
462 string const snippet_;
467 PreviewLoader::Status
468 PreviewLoader::Impl::status(string const & latex_snippet) const
470 Cache::const_iterator cit = cache_.find(latex_snippet);
471 if (cit != cache_.end())
474 PendingSnippets::const_iterator pit = pending_.begin();
475 PendingSnippets::const_iterator pend = pending_.end();
477 pit = find(pit, pend, latex_snippet);
481 InProgressProcesses::const_iterator ipit = in_progress_.begin();
482 InProgressProcesses::const_iterator ipend = in_progress_.end();
484 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
492 void PreviewLoader::Impl::add(string const & latex_snippet)
494 if (!pconverter_ || status(latex_snippet) != NotFound)
497 string const snippet = trim(latex_snippet);
501 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
503 pending_.push_back(snippet);
511 EraseSnippet(string const & s) : snippet_(s) {}
512 void operator()(InProgressProcess & process)
514 BitmapFile & snippets = process.second.snippets;
515 BitmapFile::iterator it = snippets.begin();
516 BitmapFile::iterator end = snippets.end();
518 it = find_if(it, end, FindFirst(snippet_));
520 snippets.erase(it, it+1);
524 string const & snippet_;
530 void PreviewLoader::Impl::remove(string const & latex_snippet)
532 Cache::iterator cit = cache_.find(latex_snippet);
533 if (cit != cache_.end())
536 PendingSnippets::iterator pit = pending_.begin();
537 PendingSnippets::iterator pend = pending_.end();
539 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
541 InProgressProcesses::iterator ipit = in_progress_.begin();
542 InProgressProcesses::iterator ipend = in_progress_.end();
544 for_each(ipit, ipend, EraseSnippet(latex_snippet));
546 while (ipit != ipend) {
547 InProgressProcesses::iterator curr = ipit++;
548 if (curr->second.snippets.empty())
549 in_progress_.erase(curr);
554 void PreviewLoader::Impl::addMacroDef(docstring const & latex_snippet)
556 macrodefs_.insert(latex_snippet);
560 bool PreviewLoader::Impl::hasMacroDef(docstring const & latex_snippet) const
562 return macrodefs_.find(latex_snippet) != macrodefs_.end();
566 void PreviewLoader::Impl::startLoading(bool wait)
568 if (pending_.empty() || !pconverter_)
571 // Only start the process off after the buffer is loaded from file.
572 if (!buffer_.isFullyLoaded())
575 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
577 // As used by the LaTeX file and by the resulting image files
578 FileName const directory(buffer_.temppath());
580 FileName const latexfile = unique_tex_filename(directory);
581 string const filename_base = removeExtension(latexfile.absFileName());
583 // Create an InProgress instance to place in the map of all
584 // such processes if it starts correctly.
585 InProgress inprogress(filename_base, pending_, pconverter_->to());
587 // clear pending_, so we're ready to start afresh.
590 // Output the LaTeX file.
591 // we use the encoding of the buffer
592 Encoding const & enc = buffer_.params().encoding();
594 try { of.reset(enc.iconvName()); }
595 catch (iconv_codecvt_facet_exception const & e) {
596 LYXERR0("Caught iconv exception: " << e.what()
597 << "\nUnable to create LaTeX file: " << latexfile);
602 otexstream os(of, texrow);
603 OutputParams runparams(&enc);
604 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
606 if (!openFileWrite(of, latexfile))
610 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
611 << "Unable to create LaTeX file\n" << latexfile);
614 of << "\\batchmode\n";
616 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
617 string latexparam = "";
618 bool docformat = !buffer_.params().default_output_format.empty()
619 && buffer_.params().default_output_format != "default";
620 // Use LATEX flavor if the document does not specify a specific
621 // output format (see bug 9371).
622 OutputParams::FLAVOR flavor = docformat
623 ? buffer_.params().getOutputFlavor()
624 : OutputParams::LATEX;
625 if (buffer_.params().encoding().package() == Encoding::japanese) {
626 latexparam = " --latex=platex";
627 flavor = OutputParams::LATEX;
629 else if (buffer_.params().useNonTeXFonts) {
630 if (flavor == OutputParams::LUATEX)
631 latexparam = " --latex=lualatex";
633 flavor = OutputParams::XETEX;
634 latexparam = " --latex=xelatex";
639 case OutputParams::PDFLATEX:
640 latexparam = " --latex=pdflatex";
642 case OutputParams::XETEX:
643 latexparam = " --latex=xelatex";
645 case OutputParams::LUATEX:
646 latexparam = " --latex=lualatex";
648 case OutputParams::DVILUATEX:
649 latexparam = " --latex=dvilualatex";
652 flavor = OutputParams::LATEX;
655 dumpPreamble(os, flavor);
656 // handle inputenc etc.
657 // I think, this is already hadled by dumpPreamble(): Kornel
658 // buffer_.params().writeEncodingPreamble(os, features);
659 of << "\n\\begin{document}\n";
660 dumpData(of, inprogress.snippets);
661 of << "\n\\end{document}\n";
664 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
665 << "File was not closed properly.");
669 // The conversion command.
671 cs << pconverter_->command()
672 << " " << quoteName(latexfile.toFilesystemEncoding())
673 << " --dpi " << font_scaling_factor_;
676 // The colors should be customizable.
677 if (!buffer_.isExporting()) {
678 ColorCode const fg = PreviewLoader::foregroundColor();
679 ColorCode const bg = PreviewLoader::backgroundColor();
680 cs << " --fg " << theApp()->hexName(fg)
681 << " --bg " << theApp()->hexName(bg);
685 if (buffer_.params().bibtex_command != "default")
686 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
687 else if (buffer_.params().encoding().package() == Encoding::japanese)
688 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
690 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
691 if (buffer_.params().bufferFormat() == "lilypond-book")
694 string const command = cs.str();
697 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
698 int ret = call.startScript(ForkedProcess::Wait, command);
700 static int fake = (2^20) + 1;
702 inprogress.pid = pid;
703 inprogress.command = command;
704 in_progress_[pid] = inprogress;
705 finishedGenerating(pid, ret);
709 // Initiate the conversion from LaTeX to bitmap images files.
710 ForkedCall::SignalTypePtr
711 convert_ptr(new ForkedCall::SignalType);
712 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
714 ForkedCall call(buffer_.filePath());
715 int ret = call.startScript(command, convert_ptr);
718 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
719 << "Unable to start process\n" << command);
723 // Store the generation process in a list of all such processes
724 inprogress.pid = call.pid();
725 inprogress.command = command;
726 in_progress_[inprogress.pid] = inprogress;
730 double PreviewLoader::displayPixelRatio() const
732 return buffer().params().display_pixel_ratio;
735 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
738 InProgressProcesses::iterator git = in_progress_.find(pid);
739 if (git == in_progress_.end()) {
740 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
741 "data for PID " << pid << endl;
745 string const command = git->second.command;
746 string const status = retval > 0 ? "failed" : "succeeded";
747 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
748 << retval << "): processing " << status
749 << " for " << command);
753 // Read the metrics file, if it exists
754 vector<double> ascent_fractions(git->second.snippets.size());
755 setAscentFractions(ascent_fractions, git->second.metrics_file);
757 // Add these newly generated bitmap files to the cache and
758 // start loading them into LyX.
759 BitmapFile::const_iterator it = git->second.snippets.begin();
760 BitmapFile::const_iterator end = git->second.snippets.end();
762 list<PreviewImagePtr> newimages;
764 int metrics_counter = 0;
765 for (; it != end; ++it, ++metrics_counter) {
766 string const & snip = it->first;
767 FileName const & file = it->second;
768 double af = ascent_fractions[metrics_counter];
770 // Add the image to the cache only if it's actually present
771 // and not empty (an empty image is signaled by af < 0)
772 if (af >= 0 && file.isReadableFile()) {
773 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
776 newimages.push_back(ptr);
781 // Remove the item from the list of still-executing processes.
782 in_progress_.erase(git);
784 // Tell the outside world
785 list<PreviewImagePtr>::const_reverse_iterator
786 nit = newimages.rbegin();
787 list<PreviewImagePtr>::const_reverse_iterator
788 nend = newimages.rend();
789 for (; nit != nend; ++nit) {
790 imageReady(*nit->get());
795 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
797 // Dump the preamble only.
798 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
799 OutputParams runparams(&buffer_.params().encoding());
800 runparams.flavor = flavor;
801 runparams.nice = true;
802 runparams.moving_arg = true;
803 runparams.free_spacing = true;
804 runparams.is_child = buffer_.parent();
805 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
807 // FIXME! This is a HACK! The proper fix is to control the 'true'
808 // passed to WriteStream below:
809 // int InsetMathNest::latex(Buffer const &, odocstream & os,
810 // OutputParams const & runparams) const
812 // WriteStream wi(os, runparams.moving_arg, true);
817 << "\\def\\lyxlock{}\n"
820 // All equation labels appear as "(#)" + preview.sty's rendering of
822 if (lyxrc.preview_hashed_labels)
823 os << "\\renewcommand{\\theequation}{\\#}\n";
825 // Use the preview style file to ensure that each snippet appears on a
827 // Also support PDF output (automatically generated e.g. when
828 // \usepackage[pdftex]{hyperref} is used and XeTeX.
830 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
835 void PreviewLoader::Impl::dumpData(odocstream & os,
836 BitmapFile const & vec) const
841 BitmapFile::const_iterator it = vec.begin();
842 BitmapFile::const_iterator end = vec.end();
844 for (; it != end; ++it) {
846 os << "\\begin{preview}\n"
847 << from_utf8(it->first)
848 << "\n\\end{preview}\n\n";
852 } // namespace graphics