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 /// \p wait whether to wait for the process to complete or, instead,
209 /// to do it in the background.
210 void startLoading(bool wait = false);
212 /// Emit this signal when an image is ready for display.
213 boost::signal<void(PreviewImage const &)> imageReady;
215 Buffer const & buffer() const { return buffer_; }
218 /// Called by the ForkedCall process that generated the bitmap files.
219 void finishedGenerating(pid_t, int);
221 void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
223 void dumpData(odocstream &, BitmapFile const &) const;
225 /** cache_ allows easy retrieval of already-generated images
226 * using the LaTeX snippet as the identifier.
228 typedef shared_ptr<PreviewImage> PreviewImagePtr;
230 typedef map<string, PreviewImagePtr> Cache;
234 /** pending_ stores the LaTeX snippets in anticipation of them being
235 * sent to the converter.
237 PendingSnippets pending_;
239 /** in_progress_ stores all forked processes so that we can proceed
241 The map uses the conversion commands as its identifiers.
243 InProgressProcesses in_progress_;
246 PreviewLoader & parent_;
248 Buffer const & buffer_;
250 mutable int font_scaling_factor_;
252 /// We don't own this
253 static lyx::Converter const * pconverter_;
257 lyx::Converter const * PreviewLoader::Impl::pconverter_;
261 // The public interface, defined in PreviewLoader.h
264 PreviewLoader::PreviewLoader(Buffer const & b)
265 : pimpl_(new Impl(*this, b))
269 PreviewLoader::~PreviewLoader()
275 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
277 return pimpl_->preview(latex_snippet);
281 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
283 return pimpl_->status(latex_snippet);
287 void PreviewLoader::add(string const & latex_snippet) const
289 pimpl_->add(latex_snippet);
293 void PreviewLoader::remove(string const & latex_snippet) const
295 pimpl_->remove(latex_snippet);
299 void PreviewLoader::startLoading(bool wait) const
301 pimpl_->startLoading(wait);
305 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
307 return pimpl_->imageReady.connect(slot);
311 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
313 pimpl_->imageReady(pimage);
317 Buffer const & PreviewLoader::buffer() const
319 return pimpl_->buffer();
322 } // namespace graphics
326 // The details of the Impl
327 // =======================
331 class IncrementedFileName {
333 IncrementedFileName(string const & to_format,
334 string const & filename_base)
335 : to_format_(to_format), base_(filename_base), counter_(1)
338 SnippetPair const operator()(string const & snippet)
341 os << base_ << counter_++ << '.' << to_format_;
342 string const file = os.str();
344 return make_pair(snippet, FileName(file));
348 string const & to_format_;
349 string const & base_;
354 InProgress::InProgress(string const & filename_base,
355 PendingSnippets const & pending,
356 string const & to_format)
358 metrics_file(filename_base + ".metrics"),
359 snippets(pending.size())
361 PendingSnippets::const_iterator pit = pending.begin();
362 PendingSnippets::const_iterator pend = pending.end();
363 BitmapFile::iterator sit = snippets.begin();
365 transform(pit, pend, sit,
366 IncrementedFileName(to_format, filename_base));
370 void InProgress::stop() const
373 ForkedCallsController::kill(pid, 0);
375 if (!metrics_file.empty())
376 metrics_file.removeFile();
378 BitmapFile::const_iterator vit = snippets.begin();
379 BitmapFile::const_iterator vend = snippets.end();
380 for (; vit != vend; ++vit) {
381 if (!vit->second.empty())
382 vit->second.removeFile();
392 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
393 : parent_(p), buffer_(b)
395 font_scaling_factor_ = int(buffer_.fontScalingFactor());
397 pconverter_ = setConverter("lyxpreview");
401 PreviewLoader::Impl::~Impl()
403 InProgressProcesses::iterator ipit = in_progress_.begin();
404 InProgressProcesses::iterator ipend = in_progress_.end();
406 for (; ipit != ipend; ++ipit)
412 PreviewLoader::Impl::preview(string const & latex_snippet) const
414 int fs = int(buffer_.fontScalingFactor());
415 if (font_scaling_factor_ != fs) {
416 // Refresh all previews on zoom changes
417 font_scaling_factor_ = fs;
418 Cache::const_iterator cit = cache_.begin();
419 Cache::const_iterator cend = cache_.end();
420 while (cit != cend) {
421 string const snippet = (cit++)->first;
422 parent_.remove(snippet);
423 parent_.add(snippet);
425 parent_.startLoading(false);
427 Cache::const_iterator it = cache_.find(latex_snippet);
428 return (it == cache_.end()) ? 0 : it->second.get();
436 FindSnippet(string const & s) : snippet_(s) {}
437 bool operator()(InProgressProcess const & process) const
439 BitmapFile const & snippets = process.second.snippets;
440 BitmapFile::const_iterator beg = snippets.begin();
441 BitmapFile::const_iterator end = snippets.end();
442 return find_if(beg, end, FindFirst(snippet_)) != end;
446 string const snippet_;
451 PreviewLoader::Status
452 PreviewLoader::Impl::status(string const & latex_snippet) const
454 Cache::const_iterator cit = cache_.find(latex_snippet);
455 if (cit != cache_.end())
458 PendingSnippets::const_iterator pit = pending_.begin();
459 PendingSnippets::const_iterator pend = pending_.end();
461 pit = find(pit, pend, latex_snippet);
465 InProgressProcesses::const_iterator ipit = in_progress_.begin();
466 InProgressProcesses::const_iterator ipend = in_progress_.end();
468 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
476 void PreviewLoader::Impl::add(string const & latex_snippet)
478 if (!pconverter_ || status(latex_snippet) != NotFound)
481 string const snippet = trim(latex_snippet);
485 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
487 pending_.push_back(snippet);
495 EraseSnippet(string const & s) : snippet_(s) {}
496 void operator()(InProgressProcess & process)
498 BitmapFile & snippets = process.second.snippets;
499 BitmapFile::iterator it = snippets.begin();
500 BitmapFile::iterator end = snippets.end();
502 it = find_if(it, end, FindFirst(snippet_));
504 snippets.erase(it, it+1);
508 string const & snippet_;
514 void PreviewLoader::Impl::remove(string const & latex_snippet)
516 Cache::iterator cit = cache_.find(latex_snippet);
517 if (cit != cache_.end())
520 PendingSnippets::iterator pit = pending_.begin();
521 PendingSnippets::iterator pend = pending_.end();
523 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
525 InProgressProcesses::iterator ipit = in_progress_.begin();
526 InProgressProcesses::iterator ipend = in_progress_.end();
528 for_each(ipit, ipend, EraseSnippet(latex_snippet));
530 while (ipit != ipend) {
531 InProgressProcesses::iterator curr = ipit++;
532 if (curr->second.snippets.empty())
533 in_progress_.erase(curr);
538 void PreviewLoader::Impl::startLoading(bool wait)
540 if (pending_.empty() || !pconverter_)
543 // Only start the process off after the buffer is loaded from file.
544 if (!buffer_.isFullyLoaded())
547 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
549 // As used by the LaTeX file and by the resulting image files
550 FileName const directory(buffer_.temppath());
552 FileName const latexfile = unique_tex_filename(directory);
553 string const filename_base = removeExtension(latexfile.absFileName());
555 // Create an InProgress instance to place in the map of all
556 // such processes if it starts correctly.
557 InProgress inprogress(filename_base, pending_, pconverter_->to());
559 // clear pending_, so we're ready to start afresh.
562 // Output the LaTeX file.
563 // we use the encoding of the buffer
564 Encoding const & enc = buffer_.params().encoding();
566 try { of.reset(enc.iconvName()); }
567 catch (iconv_codecvt_facet_exception const & e) {
568 LYXERR0("Caught iconv exception: " << e.what()
569 << "\nUnable to create LaTeX file: " << latexfile);
574 otexstream os(of, texrow);
575 OutputParams runparams(&enc);
576 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
578 if (!openFileWrite(of, latexfile))
582 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
583 << "Unable to create LaTeX file\n" << latexfile);
586 of << "\\batchmode\n";
588 LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
589 string latexparam = "";
590 bool docformat = !buffer_.params().default_output_format.empty()
591 && buffer_.params().default_output_format != "default";
592 // Use LATEX flavor if the document does not specify a specific
593 // output format (see bug 9371).
594 OutputParams::FLAVOR flavor = docformat
595 ? buffer_.params().getOutputFlavor()
596 : OutputParams::LATEX;
597 if (buffer_.params().encoding().package() == Encoding::japanese) {
598 latexparam = " --latex=platex";
599 flavor = OutputParams::LATEX;
601 else if (buffer_.params().useNonTeXFonts) {
602 if (flavor == OutputParams::LUATEX)
603 latexparam = " --latex=lualatex";
605 flavor = OutputParams::XETEX;
606 latexparam = " --latex=xelatex";
611 case OutputParams::PDFLATEX:
612 latexparam = " --latex=pdflatex";
614 case OutputParams::XETEX:
615 latexparam = " --latex=xelatex";
617 case OutputParams::LUATEX:
618 latexparam = " --latex=lualatex";
620 case OutputParams::DVILUATEX:
621 latexparam = " --latex=dvilualatex";
624 flavor = OutputParams::LATEX;
627 dumpPreamble(os, flavor);
628 // handle inputenc etc.
629 // I think, this is already hadled by dumpPreamble(): Kornel
630 // buffer_.params().writeEncodingPreamble(os, features);
631 of << "\n\\begin{document}\n";
632 dumpData(of, inprogress.snippets);
633 of << "\n\\end{document}\n";
636 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
637 << "File was not closed properly.");
641 // The conversion command.
643 cs << pconverter_->command()
644 << " " << quoteName(latexfile.toFilesystemEncoding())
645 << " --dpi " << font_scaling_factor_;
648 // The colors should be customizable.
649 if (!buffer_.isExporting()) {
650 ColorCode const fg = PreviewLoader::foregroundColor();
651 ColorCode const bg = PreviewLoader::backgroundColor();
652 cs << " --fg " << theApp()->hexName(fg)
653 << " --bg " << theApp()->hexName(bg);
657 if (buffer_.params().bibtex_command != "default")
658 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
659 else if (buffer_.params().encoding().package() == Encoding::japanese)
660 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
662 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
663 if (buffer_.params().bufferFormat() == "lilypond-book")
666 string const command = cs.str();
669 ForkedCall call(buffer_.filePath());
670 int ret = call.startScript(ForkedProcess::Wait, command);
672 static int fake = (2^20) + 1;
674 inprogress.pid = pid;
675 inprogress.command = command;
676 in_progress_[pid] = inprogress;
677 finishedGenerating(pid, ret);
681 // Initiate the conversion from LaTeX to bitmap images files.
682 ForkedCall::SignalTypePtr
683 convert_ptr(new ForkedCall::SignalType);
684 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
686 ForkedCall call(buffer_.filePath());
687 int ret = call.startScript(command, convert_ptr);
690 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
691 << "Unable to start process\n" << command);
695 // Store the generation process in a list of all such processes
696 inprogress.pid = call.pid();
697 inprogress.command = command;
698 in_progress_[inprogress.pid] = inprogress;
702 double PreviewLoader::displayPixelRatio() const
704 return buffer().params().display_pixel_ratio;
707 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
710 InProgressProcesses::iterator git = in_progress_.find(pid);
711 if (git == in_progress_.end()) {
712 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
713 "data for PID " << pid << endl;
717 string const command = git->second.command;
718 string const status = retval > 0 ? "failed" : "succeeded";
719 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
720 << retval << "): processing " << status
721 << " for " << command);
725 // Read the metrics file, if it exists
726 vector<double> ascent_fractions(git->second.snippets.size());
727 setAscentFractions(ascent_fractions, git->second.metrics_file);
729 // Add these newly generated bitmap files to the cache and
730 // start loading them into LyX.
731 BitmapFile::const_iterator it = git->second.snippets.begin();
732 BitmapFile::const_iterator end = git->second.snippets.end();
734 list<PreviewImagePtr> newimages;
736 int metrics_counter = 0;
737 for (; it != end; ++it, ++metrics_counter) {
738 string const & snip = it->first;
739 FileName const & file = it->second;
740 double af = ascent_fractions[metrics_counter];
742 // Add the image to the cache only if it's actually present
743 // and not empty (an empty image is signaled by af < 0)
744 if (af >= 0 && file.isReadableFile()) {
745 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
748 newimages.push_back(ptr);
753 // Remove the item from the list of still-executing processes.
754 in_progress_.erase(git);
756 // Tell the outside world
757 list<PreviewImagePtr>::const_reverse_iterator
758 nit = newimages.rbegin();
759 list<PreviewImagePtr>::const_reverse_iterator
760 nend = newimages.rend();
761 for (; nit != nend; ++nit) {
762 imageReady(*nit->get());
767 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
769 // Dump the preamble only.
770 LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
771 OutputParams runparams(&buffer_.params().encoding());
772 runparams.flavor = flavor;
773 runparams.nice = true;
774 runparams.moving_arg = true;
775 runparams.free_spacing = true;
776 runparams.is_child = buffer_.parent();
777 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
779 // FIXME! This is a HACK! The proper fix is to control the 'true'
780 // passed to WriteStream below:
781 // int InsetMathNest::latex(Buffer const &, odocstream & os,
782 // OutputParams const & runparams) const
784 // WriteStream wi(os, runparams.moving_arg, true);
789 << "\\def\\lyxlock{}\n"
792 // All equation labels appear as "(#)" + preview.sty's rendering of
794 if (lyxrc.preview_hashed_labels)
795 os << "\\renewcommand{\\theequation}{\\#}\n";
797 // Use the preview style file to ensure that each snippet appears on a
799 // Also support PDF output (automatically generated e.g. when
800 // \usepackage[pdftex]{hyperref} is used and XeTeX.
802 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
807 void PreviewLoader::Impl::dumpData(odocstream & os,
808 BitmapFile const & vec) const
813 BitmapFile::const_iterator it = vec.begin();
814 BitmapFile::const_iterator end = vec.end();
816 for (; it != end; ++it) {
818 os << "\\begin{preview}\n"
819 << from_utf8(it->first)
820 << "\n\\end{preview}\n\n";
824 } // namespace graphics