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"
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);
206 /// \p wait whether to wait for the process to complete or, instead,
207 /// to do it in the background.
208 void startLoading(bool wait = false);
210 /// Emit this signal when an image is ready for display.
211 boost::signal<void(PreviewImage const &)> imageReady;
213 Buffer const & buffer() const { return buffer_; }
216 /// Called by the ForkedCall process that generated the bitmap files.
217 void finishedGenerating(pid_t, int);
219 void dumpPreamble(odocstream &) const;
221 void dumpData(odocstream &, BitmapFile const &) const;
223 /** cache_ allows easy retrieval of already-generated images
224 * using the LaTeX snippet as the identifier.
226 typedef shared_ptr<PreviewImage> PreviewImagePtr;
228 typedef map<string, PreviewImagePtr> Cache;
232 /** pending_ stores the LaTeX snippets in anticipation of them being
233 * sent to the converter.
235 PendingSnippets pending_;
237 /** in_progress_ stores all forked processes so that we can proceed
239 The map uses the conversion commands as its identifiers.
241 InProgressProcesses in_progress_;
244 PreviewLoader & parent_;
246 Buffer const & buffer_;
248 /// We don't own this
249 static lyx::Converter const * pconverter_;
253 lyx::Converter const * PreviewLoader::Impl::pconverter_;
257 // The public interface, defined in PreviewLoader.h
260 PreviewLoader::PreviewLoader(Buffer const & b)
261 : pimpl_(new Impl(*this, b))
265 PreviewLoader::~PreviewLoader()
271 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
273 return pimpl_->preview(latex_snippet);
277 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
279 return pimpl_->status(latex_snippet);
283 void PreviewLoader::add(string const & latex_snippet) const
285 pimpl_->add(latex_snippet);
289 void PreviewLoader::remove(string const & latex_snippet) const
291 pimpl_->remove(latex_snippet);
295 void PreviewLoader::startLoading(bool wait) const
297 pimpl_->startLoading(wait);
301 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
303 return pimpl_->imageReady.connect(slot);
307 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
309 pimpl_->imageReady(pimage);
313 Buffer const & PreviewLoader::buffer() const
315 return pimpl_->buffer();
318 } // namespace graphics
322 // The details of the Impl
323 // =======================
327 class IncrementedFileName {
329 IncrementedFileName(string const & to_format,
330 string const & filename_base)
331 : to_format_(to_format), base_(filename_base), counter_(1)
334 SnippetPair const operator()(string const & snippet)
337 os << base_ << counter_++ << '.' << to_format_;
338 string const file = os.str();
340 return make_pair(snippet, FileName(file));
344 string const & to_format_;
345 string const & base_;
350 InProgress::InProgress(string const & filename_base,
351 PendingSnippets const & pending,
352 string const & to_format)
354 metrics_file(filename_base + ".metrics"),
355 snippets(pending.size())
357 PendingSnippets::const_iterator pit = pending.begin();
358 PendingSnippets::const_iterator pend = pending.end();
359 BitmapFile::iterator sit = snippets.begin();
361 transform(pit, pend, sit,
362 IncrementedFileName(to_format, filename_base));
366 void InProgress::stop() const
369 ForkedCallsController::kill(pid, 0);
371 if (!metrics_file.empty())
372 metrics_file.removeFile();
374 BitmapFile::const_iterator vit = snippets.begin();
375 BitmapFile::const_iterator vend = snippets.end();
376 for (; vit != vend; ++vit) {
377 if (!vit->second.empty())
378 vit->second.removeFile();
388 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
389 : parent_(p), buffer_(b)
392 if (b.params().encoding().package() == Encoding::japanese)
393 pconverter_ = setConverter("lyxpreview-platex");
395 pconverter_ = setConverter("lyxpreview");
400 PreviewLoader::Impl::~Impl()
402 InProgressProcesses::iterator ipit = in_progress_.begin();
403 InProgressProcesses::iterator ipend = in_progress_.end();
405 for (; ipit != ipend; ++ipit)
411 PreviewLoader::Impl::preview(string const & latex_snippet) const
413 Cache::const_iterator it = cache_.find(latex_snippet);
414 return (it == cache_.end()) ? 0 : it->second.get();
422 FindSnippet(string const & s) : snippet_(s) {}
423 bool operator()(InProgressProcess const & process) const
425 BitmapFile const & snippets = process.second.snippets;
426 BitmapFile::const_iterator beg = snippets.begin();
427 BitmapFile::const_iterator end = snippets.end();
428 return find_if(beg, end, FindFirst(snippet_)) != end;
432 string const snippet_;
437 PreviewLoader::Status
438 PreviewLoader::Impl::status(string const & latex_snippet) const
440 Cache::const_iterator cit = cache_.find(latex_snippet);
441 if (cit != cache_.end())
444 PendingSnippets::const_iterator pit = pending_.begin();
445 PendingSnippets::const_iterator pend = pending_.end();
447 pit = find(pit, pend, latex_snippet);
451 InProgressProcesses::const_iterator ipit = in_progress_.begin();
452 InProgressProcesses::const_iterator ipend = in_progress_.end();
454 ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
462 void PreviewLoader::Impl::add(string const & latex_snippet)
464 if (!pconverter_ || status(latex_snippet) != NotFound)
467 string const snippet = trim(latex_snippet);
471 LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
473 pending_.push_back(snippet);
481 EraseSnippet(string const & s) : snippet_(s) {}
482 void operator()(InProgressProcess & process)
484 BitmapFile & snippets = process.second.snippets;
485 BitmapFile::iterator it = snippets.begin();
486 BitmapFile::iterator end = snippets.end();
488 it = find_if(it, end, FindFirst(snippet_));
490 snippets.erase(it, it+1);
494 string const & snippet_;
500 void PreviewLoader::Impl::remove(string const & latex_snippet)
502 Cache::iterator cit = cache_.find(latex_snippet);
503 if (cit != cache_.end())
506 PendingSnippets::iterator pit = pending_.begin();
507 PendingSnippets::iterator pend = pending_.end();
509 pending_.erase(std::remove(pit, pend, latex_snippet), pend);
511 InProgressProcesses::iterator ipit = in_progress_.begin();
512 InProgressProcesses::iterator ipend = in_progress_.end();
514 for_each(ipit, ipend, EraseSnippet(latex_snippet));
516 while (ipit != ipend) {
517 InProgressProcesses::iterator curr = ipit++;
518 if (curr->second.snippets.empty())
519 in_progress_.erase(curr);
524 void PreviewLoader::Impl::startLoading(bool wait)
526 if (pending_.empty() || !pconverter_)
529 // Only start the process off after the buffer is loaded from file.
530 if (!buffer_.isFullyLoaded())
533 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
535 // As used by the LaTeX file and by the resulting image files
536 string const directory = buffer_.temppath();
538 string const filename_base = unique_filename(directory);
540 // Create an InProgress instance to place in the map of all
541 // such processes if it starts correctly.
542 InProgress inprogress(filename_base, pending_, pconverter_->to);
544 // clear pending_, so we're ready to start afresh.
547 // Output the LaTeX file.
548 FileName const latexfile(filename_base + ".tex");
550 // we use the encoding of the buffer
551 Encoding const & enc = buffer_.params().encoding();
553 try { of.reset(enc.iconvName()); }
554 catch (iconv_codecvt_facet_exception & e) {
555 LYXERR0("Caught iconv exception: " << e.what()
556 << "\nUnable to create LaTeX file: " << latexfile);
561 OutputParams runparams(&enc);
562 LaTeXFeatures features(buffer_, buffer_.params(), runparams);
564 if (!openFileWrite(of, latexfile))
568 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
569 << "Unable to create LaTeX file\n" << latexfile);
572 of << "\\batchmode\n";
574 // handle inputenc etc.
575 buffer_.params().writeEncodingPreamble(of, features, texrow);
576 of << "\n\\begin{document}\n";
577 dumpData(of, inprogress.snippets);
578 of << "\n\\end{document}\n";
581 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
582 << "File was not closed properly.");
586 double font_scaling_factor = 0.01 * lyxrc.dpi * lyxrc.zoom
587 * lyxrc.preview_scale_factor;
589 // For XHTML image export, we need to control the background
591 ColorCode bg = buffer_.isClone()
592 ? Color_white : PreviewLoader::backgroundColor();
593 // The conversion command.
595 cs << pconverter_->command << ' ' << pconverter_->to << ' '
596 << quoteName(latexfile.toFilesystemEncoding()) << ' '
597 << int(font_scaling_factor) << ' '
598 << theApp()->hexName(PreviewLoader::foregroundColor()) << ' '
599 << theApp()->hexName(bg);
600 if (buffer_.params().useXetex)
603 string const command = libScriptSearch(cs.str());
607 int ret = call.startScript(ForkedProcess::Wait, command);
608 static int fake = (2^20) + 1;
610 inprogress.pid = pid;
611 inprogress.command = command;
612 in_progress_[pid] = inprogress;
613 finishedGenerating(pid, ret);
617 // Initiate the conversion from LaTeX to bitmap images files.
618 ForkedCall::SignalTypePtr
619 convert_ptr(new ForkedCall::SignalType);
620 convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
623 int ret = call.startScript(command, convert_ptr);
626 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
627 << "Unable to start process\n" << command);
631 // Store the generation process in a list of all such processes
632 inprogress.pid = call.pid();
633 inprogress.command = command;
634 in_progress_[inprogress.pid] = inprogress;
638 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
641 InProgressProcesses::iterator git = in_progress_.find(pid);
642 if (git == in_progress_.end()) {
643 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
644 "data for PID " << pid << endl;
648 string const command = git->second.command;
649 string const status = retval > 0 ? "failed" : "succeeded";
650 LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
651 << retval << "): processing " << status
652 << " for " << command);
656 // Read the metrics file, if it exists
657 vector<double> ascent_fractions(git->second.snippets.size());
658 setAscentFractions(ascent_fractions, git->second.metrics_file);
660 // Add these newly generated bitmap files to the cache and
661 // start loading them into LyX.
662 BitmapFile::const_iterator it = git->second.snippets.begin();
663 BitmapFile::const_iterator end = git->second.snippets.end();
665 list<PreviewImagePtr> newimages;
667 int metrics_counter = 0;
668 for (; it != end; ++it, ++metrics_counter) {
669 string const & snip = it->first;
670 FileName const & file = it->second;
671 double af = ascent_fractions[metrics_counter];
673 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
676 newimages.push_back(ptr);
679 // Remove the item from the list of still-executing processes.
680 in_progress_.erase(git);
682 // Tell the outside world
683 list<PreviewImagePtr>::const_reverse_iterator
684 nit = newimages.rbegin();
685 list<PreviewImagePtr>::const_reverse_iterator
686 nend = newimages.rend();
687 for (; nit != nend; ++nit) {
688 imageReady(*nit->get());
693 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
695 // Dump the preamble only.
696 OutputParams runparams(&buffer_.params().encoding());
697 runparams.flavor = OutputParams::LATEX;
698 runparams.nice = true;
699 runparams.moving_arg = true;
700 runparams.free_spacing = true;
701 buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
703 // FIXME! This is a HACK! The proper fix is to control the 'true'
704 // passed to WriteStream below:
705 // int InsetMathNest::latex(Buffer const &, odocstream & os,
706 // OutputParams const & runparams) const
708 // WriteStream wi(os, runparams.moving_arg, true);
713 << "\\def\\lyxlock{}\n"
716 // All equation labels appear as "(#)" + preview.sty's rendering of
718 if (lyxrc.preview_hashed_labels)
719 os << "\\renewcommand{\\theequation}{\\#}\n";
721 // Use the preview style file to ensure that each snippet appears on a
723 // Also support PDF output (automatically generated e.g. when
724 // \usepackage[pdftex]{hyperref} is used and XeTeX.
726 << "\\newif\\ifxetex\n"
727 << "\\expandafter\\ifx\\csname XeTeXrevision\\endcsname\\relax\n"
732 << "\\newif\\ifpdf\n"
733 << "\\ifx\\pdfoutput\\undefined\n"
734 << "\\else\\ifx\\pdfoutput\\relax\n"
735 << "\\else\\ifnum0=\\pdfoutput\n"
736 << "\\else\\pdftrue\\fi\\fi\\fi\n"
738 << " \\usepackage[active,delayed,tightpage,showlabels,lyx,xetex]{preview}\n"
741 << " \\usepackage[active,delayed,tightpage,showlabels,lyx,pdftex]{preview}\n"
743 << " \\usepackage[active,delayed,showlabels,lyx,dvips]{preview}\n"
750 void PreviewLoader::Impl::dumpData(odocstream & os,
751 BitmapFile const & vec) const
756 BitmapFile::const_iterator it = vec.begin();
757 BitmapFile::const_iterator end = vec.end();
759 for (; it != end; ++it) {
761 os << "\\begin{preview}\n"
762 << from_utf8(it->first)
763 << "\n\\end{preview}\n\n";
767 } // namespace graphics