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 &) 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 /// We don't own this
251 static lyx::Converter const * pconverter_;
255 lyx::Converter const * PreviewLoader::Impl::pconverter_;
259 // The public interface, defined in PreviewLoader.h
262 PreviewLoader::PreviewLoader(Buffer const & b)
263 : pimpl_(new Impl(*this, b))
267 PreviewLoader::~PreviewLoader()
273 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
275 return pimpl_->preview(latex_snippet);
279 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
281 return pimpl_->status(latex_snippet);
285 void PreviewLoader::add(string const & latex_snippet) const
287 pimpl_->add(latex_snippet);
291 void PreviewLoader::remove(string const & latex_snippet) const
293 pimpl_->remove(latex_snippet);
297 void PreviewLoader::startLoading(bool wait) const
299 pimpl_->startLoading(wait);
303 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
305 return pimpl_->imageReady.connect(slot);
309 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
311 pimpl_->imageReady(pimage);
315 Buffer const & PreviewLoader::buffer() const
317 return pimpl_->buffer();
320 } // namespace graphics
324 // The details of the Impl
325 // =======================
329 class IncrementedFileName {
331 IncrementedFileName(string const & to_format,
332 string const & filename_base)
333 : to_format_(to_format), base_(filename_base), counter_(1)
336 SnippetPair const operator()(string const & snippet)
339 os << base_ << counter_++ << '.' << to_format_;
340 string const file = os.str();
342 return make_pair(snippet, FileName(file));
346 string const & to_format_;
347 string const & base_;
352 InProgress::InProgress(string const & filename_base,
353 PendingSnippets const & pending,
354 string const & to_format)
356 metrics_file(filename_base + ".metrics"),
357 snippets(pending.size())
359 PendingSnippets::const_iterator pit = pending.begin();
360 PendingSnippets::const_iterator pend = pending.end();
361 BitmapFile::iterator sit = snippets.begin();
363 transform(pit, pend, sit,
364 IncrementedFileName(to_format, filename_base));
368 void InProgress::stop() const
371 ForkedCallsController::kill(pid, 0);
373 if (!metrics_file.empty())
374 metrics_file.removeFile();
376 BitmapFile::const_iterator vit = snippets.begin();
377 BitmapFile::const_iterator vend = snippets.end();
378 for (; vit != vend; ++vit) {
379 if (!vit->second.empty())
380 vit->second.removeFile();
390 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
391 : parent_(p), buffer_(b)
394 pconverter_ = setConverter("lyxpreview");
398 PreviewLoader::Impl::~Impl()
400 InProgressProcesses::iterator ipit = in_progress_.begin();
401 InProgressProcesses::iterator ipend = in_progress_.end();
403 for (; ipit != ipend; ++ipit)
409 PreviewLoader::Impl::preview(string const & latex_snippet) const
411 Cache::const_iterator it = cache_.find(latex_snippet);
412 return (it == cache_.end()) ? 0 : it->second.get();
420 FindSnippet(string const & s) : snippet_(s) {}
421 bool operator()(InProgressProcess const & process) const
423 BitmapFile const & snippets = process.second.snippets;
424 BitmapFile::const_iterator beg = snippets.begin();
425 BitmapFile::const_iterator end = snippets.end();
426 return find_if(beg, end, FindFirst(snippet_)) != end;
430 string const snippet_;
435 PreviewLoader::Status
436 PreviewLoader::Impl::status(string const & latex_snippet) const
438 Cache::const_iterator cit = cache_.find(latex_snippet);
439 if (cit != cache_.end())
442 PendingSnippets::const_iterator pit = pending_.begin();
443 PendingSnippets::const_iterator pend = pending_.end();
445 pit = find(pit, pend, latex_snippet);
449 InProgressProcesses::const_iterator ipit = in_progress_.begin();
450 InProgressProcesses::const_iterator ipend = in_progress_.end();
452 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
460 void PreviewLoader::Impl::add(string const & latex_snippet)
462 if (!pconverter_ || status(latex_snippet) != NotFound)
465 string const snippet = trim(latex_snippet);
469 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
471 pending_.push_back(snippet);
479 EraseSnippet(string const & s) : snippet_(s) {}
480 void operator()(InProgressProcess & process)
482 BitmapFile & snippets = process.second.snippets;
483 BitmapFile::iterator it = snippets.begin();
484 BitmapFile::iterator end = snippets.end();
486 it = find_if(it, end, FindFirst(snippet_));
488 snippets.erase(it, it+1);
492 string const & snippet_;
498 void PreviewLoader::Impl::remove(string const & latex_snippet)
500 Cache::iterator cit = cache_.find(latex_snippet);
501 if (cit != cache_.end())
504 PendingSnippets::iterator pit = pending_.begin();
505 PendingSnippets::iterator pend = pending_.end();
507 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
509 InProgressProcesses::iterator ipit = in_progress_.begin();
510 InProgressProcesses::iterator ipend = in_progress_.end();
512 for_each(ipit, ipend, EraseSnippet(latex_snippet));
514 while (ipit != ipend) {
515 InProgressProcesses::iterator curr = ipit++;
516 if (curr->second.snippets.empty())
517 in_progress_.erase(curr);
522 void PreviewLoader::Impl::startLoading(bool wait)
524 if (pending_.empty() || !pconverter_)
527 // Only start the process off after the buffer is loaded from file.
528 if (!buffer_.isFullyLoaded())
531 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
533 // As used by the LaTeX file and by the resulting image files
534 FileName const directory(buffer_.temppath());
536 FileName const latexfile = unique_tex_filename(directory);
537 string const filename_base = removeExtension(latexfile.absFileName());
539 // Create an InProgress instance to place in the map of all
540 // such processes if it starts correctly.
541 InProgress inprogress(filename_base, pending_, pconverter_->to);
543 // clear pending_, so we're ready to start afresh.
546 // Output the LaTeX file.
547 // we use the encoding of the buffer
548 Encoding const & enc = buffer_.params().encoding();
550 try { of.reset(enc.iconvName()); }
551 catch (iconv_codecvt_facet_exception const & e) {
552 LYXERR0("Caught iconv exception: " << e.what()
553 << "\nUnable to create LaTeX file: " << latexfile);
558 otexstream os(of, texrow);
559 OutputParams runparams(&enc);
560 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
562 if (!openFileWrite(of, latexfile))
566 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
567 << "Unable to create LaTeX file\n" << latexfile);
570 of << "\\batchmode\n";
572 // handle inputenc etc.
573 buffer_.params().writeEncodingPreamble(os, features);
574 of << "\n\\begin{document}\n";
575 dumpData(of, inprogress.snippets);
576 of << "\n\\end{document}\n";
579 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
580 << "File was not closed properly.");
584 double const font_scaling_factor =
585 buffer_.isExporting() ? 75.0 * buffer_.params().html_math_img_scale
586 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor;
588 // The conversion command.
590 cs << pconverter_->command
591 << " " << quoteName(latexfile.toFilesystemEncoding())
592 << " --dpi " << int(font_scaling_factor);
595 // The colors should be customizable.
596 if (!buffer_.isExporting()) {
597 ColorCode const fg = PreviewLoader::foregroundColor();
598 ColorCode const bg = PreviewLoader::backgroundColor();
599 cs << " --fg " << theApp()->hexName(fg)
600 << " --bg " << theApp()->hexName(bg);
603 // FIXME what about LuaTeX?
604 if (buffer_.params().useNonTeXFonts)
605 cs << " --latex=xelatex";
606 if (buffer_.params().encoding().package() == Encoding::japanese)
607 cs << " --latex=platex";
608 if (buffer_.params().bibtex_command != "default")
609 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
610 else if (buffer_.params().encoding().package() == Encoding::japanese)
611 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
613 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
614 if (buffer_.params().bufferFormat() == "lilypond-book")
617 string const command = cs.str();
620 ForkedCall call(buffer_.filePath());
621 int ret = call.startScript(ForkedProcess::Wait, command);
623 static int fake = (2^20) + 1;
625 inprogress.pid = pid;
626 inprogress.command = command;
627 in_progress_[pid] = inprogress;
628 finishedGenerating(pid, ret);
632 // Initiate the conversion from LaTeX to bitmap images files.
633 ForkedCall::SignalTypePtr
634 convert_ptr(new ForkedCall::SignalType);
635 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
637 ForkedCall call(buffer_.filePath());
638 int ret = call.startScript(command, convert_ptr);
641 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
642 << "Unable to start process\n" << command);
646 // Store the generation process in a list of all such processes
647 inprogress.pid = call.pid();
648 inprogress.command = command;
649 in_progress_[inprogress.pid] = inprogress;
653 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
656 InProgressProcesses::iterator git = in_progress_.find(pid);
657 if (git == in_progress_.end()) {
658 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
659 "data for PID " << pid << endl;
663 string const command = git->second.command;
664 string const status = retval > 0 ? "failed" : "succeeded";
665 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
666 << retval << "): processing " << status
667 << " for " << command);
671 // Read the metrics file, if it exists
672 vector<double> ascent_fractions(git->second.snippets.size());
673 setAscentFractions(ascent_fractions, git->second.metrics_file);
675 // Add these newly generated bitmap files to the cache and
676 // start loading them into LyX.
677 BitmapFile::const_iterator it = git->second.snippets.begin();
678 BitmapFile::const_iterator end = git->second.snippets.end();
680 list<PreviewImagePtr> newimages;
682 int metrics_counter = 0;
683 for (; it != end; ++it, ++metrics_counter) {
684 string const & snip = it->first;
685 FileName const & file = it->second;
686 double af = ascent_fractions[metrics_counter];
688 // Add the image to the cache only if it's actually present
689 if (file.isReadableFile()) {
690 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
693 newimages.push_back(ptr);
698 // Remove the item from the list of still-executing processes.
699 in_progress_.erase(git);
701 // Tell the outside world
702 list<PreviewImagePtr>::const_reverse_iterator
703 nit = newimages.rbegin();
704 list<PreviewImagePtr>::const_reverse_iterator
705 nend = newimages.rend();
706 for (; nit != nend; ++nit) {
707 imageReady(*nit->get());
712 void PreviewLoader::Impl::dumpPreamble(otexstream & os) const
714 // Dump the preamble only.
715 OutputParams runparams(&buffer_.params().encoding());
716 if (buffer_.params().useNonTeXFonts)
717 runparams.flavor = OutputParams::XETEX;
719 runparams.flavor = OutputParams::LATEX;
720 runparams.nice = true;
721 runparams.moving_arg = true;
722 runparams.free_spacing = true;
723 runparams.is_child = buffer_.parent();
724 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
726 // FIXME! This is a HACK! The proper fix is to control the 'true'
727 // passed to WriteStream below:
728 // int InsetMathNest::latex(Buffer const &, odocstream & os,
729 // OutputParams const & runparams) const
731 // WriteStream wi(os, runparams.moving_arg, true);
736 << "\\def\\lyxlock{}\n"
739 // All equation labels appear as "(#)" + preview.sty's rendering of
741 if (lyxrc.preview_hashed_labels)
742 os << "\\renewcommand{\\theequation}{\\#}\n";
744 // Use the preview style file to ensure that each snippet appears on a
746 // Also support PDF output (automatically generated e.g. when
747 // \usepackage[pdftex]{hyperref} is used and XeTeX.
749 << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
754 void PreviewLoader::Impl::dumpData(odocstream & os,
755 BitmapFile const & vec) const
760 BitmapFile::const_iterator it = vec.begin();
761 BitmapFile::const_iterator end = vec.end();
763 for (; it != end; ++it) {
765 os << "\\begin{preview}\n"
766 << from_utf8(it->first)
767 << "\n\\end{preview}\n\n";
771 } // namespace graphics