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 <boost/bind.hpp>
47 using namespace lyx::support;
53 typedef pair<string, FileName> SnippetPair;
55 // A list of all snippets to be converted to previews
56 typedef list<string> PendingSnippets;
58 // Each item in the vector is a pair<snippet, image file name>.
59 typedef vector<SnippetPair> BitmapFile;
62 string const unique_filename(string const & bufferpath)
64 static int theCounter = 0;
65 string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
66 return addName(bufferpath, filename);
70 lyx::Converter const * setConverter(string const from)
72 typedef vector<string> FmtList;
73 typedef lyx::graphics::Cache GCache;
74 FmtList const & loadableFormats = GCache::get().loadableFormats();
75 FmtList::const_iterator it = loadableFormats.begin();
76 FmtList::const_iterator const end = loadableFormats.end();
78 for (; it != end; ++it) {
79 string const to = *it;
83 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
88 static bool first = true;
91 LYXERR0("PreviewLoader::startLoading()\n"
92 << "No converter from \"" << from << "\" format has been defined.");
98 void setAscentFractions(vector<double> & ascent_fractions,
99 FileName const & metrics_file)
101 // If all else fails, then the images will have equal ascents and
103 vector<double>::iterator it = ascent_fractions.begin();
104 vector<double>::iterator end = ascent_fractions.end();
107 ifstream in(metrics_file.toFilesystemEncoding().c_str());
109 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
110 << "Unable to open file!");
116 int snippet_counter = 1;
117 while (!in.eof() && it != end) {
120 double ascent_fraction;
122 in >> snippet >> id >> ascent_fraction;
128 error = snippet != "Snippet";
132 error = id != snippet_counter;
136 *it = ascent_fraction;
143 LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
144 << "Error reading file!\n");
152 FindFirst(string const & comp) : comp_(comp) {}
153 bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
159 /// Store info on a currently executing, forked process.
163 InProgress() : pid(0) {}
165 InProgress(string const & filename_base,
166 PendingSnippets const & pending,
167 string const & to_format);
168 /// Remove any files left lying around and kill the forked process.
176 FileName metrics_file;
181 typedef map<pid_t, InProgress> InProgressProcesses;
183 typedef InProgressProcesses::value_type InProgressProcess;
192 class PreviewLoader::Impl : public boost::signals::trackable {
195 Impl(PreviewLoader & p, Buffer const & b);
196 /// Stop any InProgress items still executing.
199 PreviewImage const * preview(string const & latex_snippet) const;
201 PreviewLoader::Status status(string const & latex_snippet) const;
203 void add(string const & latex_snippet);
205 void remove(string const & latex_snippet);
209 /// Emit this signal when an image is ready for display.
210 boost::signal<void(PreviewImage const &)> imageReady;
212 Buffer const & buffer() const { return buffer_; }
215 /// Called by the ForkedCall process that generated the bitmap files.
216 void finishedGenerating(pid_t, int);
218 void dumpPreamble(odocstream &) const;
220 void dumpData(odocstream &, BitmapFile const &) const;
222 /** cache_ allows easy retrieval of already-generated images
223 * using the LaTeX snippet as the identifier.
225 typedef boost::shared_ptr<PreviewImage> PreviewImagePtr;
227 typedef map<string, PreviewImagePtr> Cache;
231 /** pending_ stores the LaTeX snippets in anticipation of them being
232 * sent to the converter.
234 PendingSnippets pending_;
236 /** in_progress_ stores all forked processes so that we can proceed
238 The map uses the conversion commands as its identifiers.
240 InProgressProcesses in_progress_;
243 PreviewLoader & parent_;
245 Buffer const & buffer_;
247 /// We don't own this
248 static lyx::Converter const * pconverter_;
252 lyx::Converter const * PreviewLoader::Impl::pconverter_;
256 // The public interface, defined in PreviewLoader.h
259 PreviewLoader::PreviewLoader(Buffer const & b)
260 : pimpl_(new Impl(*this, b))
264 PreviewLoader::~PreviewLoader()
270 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
272 return pimpl_->preview(latex_snippet);
276 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
278 return pimpl_->status(latex_snippet);
282 void PreviewLoader::add(string const & latex_snippet) const
284 pimpl_->add(latex_snippet);
288 void PreviewLoader::remove(string const & latex_snippet) const
290 pimpl_->remove(latex_snippet);
294 void PreviewLoader::startLoading() const
296 pimpl_->startLoading();
300 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
302 return pimpl_->imageReady.connect(slot);
306 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
308 pimpl_->imageReady(pimage);
312 Buffer const & PreviewLoader::buffer() const
314 return pimpl_->buffer();
317 } // namespace graphics
321 // The details of the Impl
322 // =======================
326 class IncrementedFileName {
328 IncrementedFileName(string const & to_format,
329 string const & filename_base)
330 : to_format_(to_format), base_(filename_base), counter_(1)
333 SnippetPair const operator()(string const & snippet)
336 os << base_ << counter_++ << '.' << to_format_;
337 string const file = os.str();
339 return make_pair(snippet, FileName(file));
343 string const & to_format_;
344 string const & base_;
349 InProgress::InProgress(string const & filename_base,
350 PendingSnippets const & pending,
351 string const & to_format)
353 metrics_file(filename_base + ".metrics"),
354 snippets(pending.size())
356 PendingSnippets::const_iterator pit = pending.begin();
357 PendingSnippets::const_iterator pend = pending.end();
358 BitmapFile::iterator sit = snippets.begin();
360 transform(pit, pend, sit,
361 IncrementedFileName(to_format, filename_base));
365 void InProgress::stop() const
368 ForkedCallsController::kill(pid, 0);
370 if (!metrics_file.empty())
371 metrics_file.removeFile();
373 BitmapFile::const_iterator vit = snippets.begin();
374 BitmapFile::const_iterator vend = snippets.end();
375 for (; vit != vend; ++vit) {
376 if (!vit->second.empty())
377 vit->second.removeFile();
387 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
388 : parent_(p), buffer_(b)
391 if (b.params().encoding().package() == Encoding::japanese)
392 pconverter_ = setConverter("lyxpreview-platex");
394 pconverter_ = setConverter("lyxpreview");
399 PreviewLoader::Impl::~Impl()
401 InProgressProcesses::iterator ipit = in_progress_.begin();
402 InProgressProcesses::iterator ipend = in_progress_.end();
404 for (; ipit != ipend; ++ipit)
410 PreviewLoader::Impl::preview(string const & latex_snippet) const
412 Cache::const_iterator it = cache_.find(latex_snippet);
413 return (it == cache_.end()) ? 0 : it->second.get();
421 FindSnippet(string const & s) : snippet_(s) {}
422 bool operator()(InProgressProcess const & process) const
424 BitmapFile const & snippets = process.second.snippets;
425 BitmapFile::const_iterator beg = snippets.begin();
426 BitmapFile::const_iterator end = snippets.end();
427 return find_if(beg, end, FindFirst(snippet_)) != end;
431 string const snippet_;
436 PreviewLoader::Status
437 PreviewLoader::Impl::status(string const & latex_snippet) const
439 Cache::const_iterator cit = cache_.find(latex_snippet);
440 if (cit != cache_.end())
443 PendingSnippets::const_iterator pit = pending_.begin();
444 PendingSnippets::const_iterator pend = pending_.end();
446 pit = find(pit, pend, latex_snippet);
450 InProgressProcesses::const_iterator ipit = in_progress_.begin();
451 InProgressProcesses::const_iterator ipend = in_progress_.end();
453 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
461 void PreviewLoader::Impl::add(string const & latex_snippet)
463 if (!pconverter_ || status(latex_snippet) != NotFound)
466 string const snippet = trim(latex_snippet);
470 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
472 pending_.push_back(snippet);
480 EraseSnippet(string const & s) : snippet_(s) {}
481 void operator()(InProgressProcess & process)
483 BitmapFile & snippets = process.second.snippets;
484 BitmapFile::iterator it = snippets.begin();
485 BitmapFile::iterator end = snippets.end();
487 it = find_if(it, end, FindFirst(snippet_));
489 snippets.erase(it, it+1);
493 string const & snippet_;
499 void PreviewLoader::Impl::remove(string const & latex_snippet)
501 Cache::iterator cit = cache_.find(latex_snippet);
502 if (cit != cache_.end())
505 PendingSnippets::iterator pit = pending_.begin();
506 PendingSnippets::iterator pend = pending_.end();
508 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
510 InProgressProcesses::iterator ipit = in_progress_.begin();
511 InProgressProcesses::iterator ipend = in_progress_.end();
513 for_each(ipit, ipend, EraseSnippet(latex_snippet));
515 while (ipit != ipend) {
516 InProgressProcesses::iterator curr = ipit++;
517 if (curr->second.snippets.empty())
518 in_progress_.erase(curr);
523 void PreviewLoader::Impl::startLoading()
525 if (pending_.empty() || !pconverter_)
528 // Only start the process off after the buffer is loaded from file.
529 if (!buffer_.isFullyLoaded())
532 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
534 // As used by the LaTeX file and by the resulting image files
535 string const directory = buffer_.temppath();
537 string const filename_base = unique_filename(directory);
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 FileName const latexfile(filename_base + ".tex");
549 // we use the encoding of the buffer
550 Encoding const & enc = buffer_.params().encoding();
552 try { of.reset(enc.iconvName()); }
553 catch (iconv_codecvt_facet_exception & e) {
554 LYXERR0("Caught iconv exception: " << e.what()
555 << "\nUnable to create LaTeX file: " << latexfile);
560 OutputParams runparams(&enc);
561 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
563 if (!openFileWrite(of, latexfile))
567 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
568 << "Unable to create LaTeX file\n" << latexfile);
571 of << "\\batchmode\n";
573 // handle inputenc etc.
574 buffer_.params().writeEncodingPreamble(of, features, texrow);
575 of << "\n\\begin{document}\n";
576 dumpData(of, inprogress.snippets);
577 of << "\n\\end{document}\n";
580 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
581 << "File was not closed properly.");
585 double font_scaling_factor = 0.01 * lyxrc.dpi * lyxrc.zoom
586 * lyxrc.preview_scale_factor;
588 // The conversion command.
590 cs << pconverter_->command << ' ' << pconverter_->to << ' '
591 << quoteName(latexfile.toFilesystemEncoding()) << ' '
592 << int(font_scaling_factor) << ' '
593 << theApp()->hexName(PreviewLoader::foregroundColor()) << ' '
594 << theApp()->hexName(PreviewLoader::backgroundColor());
595 if (buffer_.params().useXetex)
598 string const command = libScriptSearch(cs.str());
600 // Initiate the conversion from LaTeX to bitmap images files.
601 ForkedCall::SignalTypePtr
602 convert_ptr(new ForkedCall::SignalType);
603 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
606 int ret = call.startScript(command, convert_ptr);
609 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
610 << "Unable to start process\n" << command);
614 // Store the generation process in a list of all such processes
615 inprogress.pid = call.pid();
616 inprogress.command = command;
617 in_progress_[inprogress.pid] = inprogress;
621 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
624 InProgressProcesses::iterator git = in_progress_.find(pid);
625 if (git == in_progress_.end()) {
626 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
627 "data for PID " << pid << endl;
631 string const command = git->second.command;
632 string const status = retval > 0 ? "failed" : "succeeded";
633 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
634 << retval << "): processing " << status
635 << " for " << command);
639 // Read the metrics file, if it exists
640 vector<double> ascent_fractions(git->second.snippets.size());
641 setAscentFractions(ascent_fractions, git->second.metrics_file);
643 // Add these newly generated bitmap files to the cache and
644 // start loading them into LyX.
645 BitmapFile::const_iterator it = git->second.snippets.begin();
646 BitmapFile::const_iterator end = git->second.snippets.end();
648 list<PreviewImagePtr> newimages;
650 int metrics_counter = 0;
651 for (; it != end; ++it, ++metrics_counter) {
652 string const & snip = it->first;
653 FileName const & file = it->second;
654 double af = ascent_fractions[metrics_counter];
656 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
659 newimages.push_back(ptr);
662 // Remove the item from the list of still-executing processes.
663 in_progress_.erase(git);
665 // Tell the outside world
666 list<PreviewImagePtr>::const_reverse_iterator
667 nit = newimages.rbegin();
668 list<PreviewImagePtr>::const_reverse_iterator
669 nend = newimages.rend();
670 for (; nit != nend; ++nit) {
671 imageReady(*nit->get());
676 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
678 // Dump the preamble only.
679 // We don't need an encoding for runparams since it is not used by
681 OutputParams runparams(0);
682 runparams.flavor = OutputParams::LATEX;
683 runparams.nice = true;
684 runparams.moving_arg = true;
685 runparams.free_spacing = true;
686 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
688 // FIXME! This is a HACK! The proper fix is to control the 'true'
689 // passed to WriteStream below:
690 // int InsetMathNest::latex(Buffer const &, odocstream & os,
691 // OutputParams const & runparams) const
693 // WriteStream wi(os, runparams.moving_arg, true);
698 << "\\def\\lyxlock{}\n"
701 // All equation labels appear as "(#)" + preview.sty's rendering of
703 if (lyxrc.preview_hashed_labels)
704 os << "\\renewcommand{\\theequation}{\\#}\n";
706 // Use the preview style file to ensure that each snippet appears on a
708 // Also support PDF output (automatically generated e.g. when
709 // \usepackage[pdftex]{hyperref} is used and XeTeX.
711 << "\\newif\\ifxetex\n"
712 << "\\expandafter\\ifx\\csname XeTeXrevision\\endcsname\\relax\n"
717 << "\\newif\\ifpdf\n"
718 << "\\ifx\\pdfoutput\\undefined\n"
719 << "\\else\\ifx\\pdfoutput\\relax\n"
720 << "\\else\\ifnum0=\\pdfoutput\n"
721 << "\\else\\pdftrue\\fi\\fi\\fi\n"
723 << " \\usepackage[active,delayed,tightpage,showlabels,lyx,xetex]{preview}\n"
726 << " \\usepackage[active,delayed,tightpage,showlabels,lyx,pdftex]{preview}\n"
728 << " \\usepackage[active,delayed,showlabels,lyx,dvips]{preview}\n"
735 void PreviewLoader::Impl::dumpData(odocstream & os,
736 BitmapFile const & vec) const
741 BitmapFile::const_iterator it = vec.begin();
742 BitmapFile::const_iterator end = vec.end();
744 for (; it != end; ++it) {
746 os << "\\begin{preview}\n"
747 << from_utf8(it->first)
748 << "\n\\end{preview}\n\n";
752 } // namespace graphics