1 /**
2  * \file PreviewLoader.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10 
11 #include <config.h>
12 
13 #include "PreviewLoader.h"
14 #include "PreviewImage.h"
15 #include "GraphicsCache.h"
16 
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "Converter.h"
20 #include "Encoding.h"
21 #include "Format.h"
22 #include "InsetIterator.h"
23 #include "LaTeXFeatures.h"
24 #include "LyXRC.h"
25 #include "output.h"
26 #include "OutputParams.h"
27 #include "TexRow.h"
28 #include "texstream.h"
29 
30 #include "frontends/Application.h" // hexName
31 
32 #include "insets/Inset.h"
33 
34 #include "support/convert.h"
35 #include "support/debug.h"
36 #include "support/FileName.h"
37 #include "support/filetools.h"
38 #include "support/ForkedCalls.h"
39 #include "support/lstrings.h"
40 
41 #include "support/TempFile.h"
42 
43 #include <atomic>
44 #include <fstream>
45 #include <iomanip>
46 #include <memory>
47 #include <mutex>
48 #include <sstream>
49 
50 #include <QTimer>
51 
52 using namespace std;
53 using namespace lyx::support;
54 
55 
56 
57 namespace {
58 
59 typedef pair<string, FileName> SnippetPair;
60 
61 // A list of all snippets to be converted to previews
62 typedef list<string> PendingSnippets;
63 
64 // Each item in the vector is a pair<snippet, image file name>.
65 typedef vector<SnippetPair> BitmapFile;
66 
67 
unique_tex_filename(FileName const & bufferpath)68 FileName const unique_tex_filename(FileName const & bufferpath)
69 {
70 	TempFile tempfile(bufferpath, "lyxpreviewXXXXXX.tex");
71 	tempfile.setAutoRemove(false);
72 	return tempfile.name();
73 }
74 
75 
setAscentFractions(vector<double> & ascent_fractions,FileName const & metrics_file)76 void setAscentFractions(vector<double> & ascent_fractions,
77 			FileName const & metrics_file)
78 {
79 	// If all else fails, then the images will have equal ascents and
80 	// descents.
81 	vector<double>::iterator it  = ascent_fractions.begin();
82 	vector<double>::iterator end = ascent_fractions.end();
83 	fill(it, end, 0.5);
84 
85 	ifstream in(metrics_file.toFilesystemEncoding().c_str());
86 	if (!in.good()) {
87 		LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
88 			<< "Unable to open file!");
89 		return;
90 	}
91 
92 	bool error = false;
93 
94 	int snippet_counter = 1;
95 	while (!in.eof() && it != end) {
96 		string snippet;
97 		int id;
98 		double ascent_fraction;
99 
100 		in >> snippet >> id >> ascent_fraction;
101 
102 		if (!in.good())
103 			// eof after all
104 			break;
105 
106 		error = snippet != "Snippet";
107 		if (error)
108 			break;
109 
110 		error = id != snippet_counter;
111 		if (error)
112 			break;
113 
114 		*it = ascent_fraction;
115 
116 		++snippet_counter;
117 		++it;
118 	}
119 
120 	if (error) {
121 		LYXERR(lyx::Debug::GRAPHICS, "setAscentFractions(" << metrics_file << ")\n"
122 			<< "Error reading file!\n");
123 	}
124 }
125 
126 
127 class FindFirst
128 {
129 public:
FindFirst(string const & comp)130 	FindFirst(string const & comp) : comp_(comp) {}
operator ()(SnippetPair const & sp) const131 	bool operator()(SnippetPair const & sp) const { return sp.first == comp_; }
132 private:
133 	string const comp_;
134 };
135 
136 
137 /// Store info on a currently executing, forked process.
138 class InProgress {
139 public:
140 	///
InProgress()141 	InProgress() : pid(0) {}
142 	///
143 	InProgress(string const & filename_base,
144 		   PendingSnippets const & pending,
145 		   string const & to_format);
146 	/// Remove any files left lying around and kill the forked process.
147 	void stop() const;
148 
149 	///
150 	pid_t pid;
151 	///
152 	string command;
153 	///
154 	FileName metrics_file;
155 	///
156 	BitmapFile snippets;
157 };
158 
159 typedef map<pid_t, InProgress>  InProgressProcesses;
160 
161 typedef InProgressProcesses::value_type InProgressProcess;
162 
163 } // namespace
164 
165 
166 namespace lyx {
167 namespace graphics {
168 
169 class PreviewLoader::Impl {
170 public:
171 	///
172 	Impl(PreviewLoader & p, Buffer const & b);
173 	/// Stop any InProgress items still executing.
174 	~Impl();
175 	///
176 	PreviewImage const * preview(string const & latex_snippet) const;
177 	///
178 	PreviewLoader::Status status(string const & latex_snippet) const;
179 	///
180 	void add(string const & latex_snippet);
181 	///
182 	void remove(string const & latex_snippet);
183 	/// \p wait whether to wait for the process to complete or, instead,
184 	/// to do it in the background.
185 	void startLoading(bool wait = false);
186 	///
187 	void refreshPreviews();
188 
189 	/// Emit this signal when an image is ready for display.
190 	signals2::signal<void(PreviewImage const &)> imageReady;
191 
buffer() const192 	Buffer const & buffer() const { return buffer_; }
193 
194 	lyx::Converter const * setConverter(string const & from);
195 
196 private:
197 	/// Called by the ForkedCall process that generated the bitmap files.
198 	void finishedGenerating(pid_t, int);
199 	///
200 	void dumpPreamble(otexstream &, OutputParams::FLAVOR) const;
201 	///
202 	void dumpData(odocstream &, BitmapFile const &) const;
203 
204 	/** cache_ allows easy retrieval of already-generated images
205 	 *  using the LaTeX snippet as the identifier.
206 	 */
207 	typedef std::shared_ptr<PreviewImage> PreviewImagePtr;
208 	///
209 	typedef map<string, PreviewImagePtr> Cache;
210 	///
211 	Cache cache_;
212 
213 	/** pending_ stores the LaTeX snippets in anticipation of them being
214 	 *  sent to the converter.
215 	 */
216 	PendingSnippets pending_;
217 
218 	/** in_progress_ stores all forked processes so that we can proceed
219 	 *  thereafter.
220 	    The map uses the conversion commands as its identifiers.
221 	 */
222 	InProgressProcesses in_progress_;
223 
224 	///
225 	PreviewLoader & parent_;
226 	///
227 	Buffer const & buffer_;
228 	///
229 	mutable int font_scaling_factor_;
230 	///
231 	mutable int fg_color_;
232 	///
233 	mutable int bg_color_;
234 	///
235 	QTimer * delay_refresh_;
236 	///
237 	bool finished_generating_;
238 
239 	/// We don't own this
240 	static lyx::Converter const * pconverter_;
241 
242 	Trackable trackable_;
243 };
244 
245 
246 lyx::Converter const * PreviewLoader::Impl::pconverter_;
247 
248 
249 //
250 // The public interface, defined in PreviewLoader.h
251 //
252 
PreviewLoader(Buffer const & b)253 PreviewLoader::PreviewLoader(Buffer const & b)
254 	: pimpl_(new Impl(*this, b))
255 {}
256 
257 
~PreviewLoader()258 PreviewLoader::~PreviewLoader()
259 {
260 	delete pimpl_;
261 }
262 
263 
preview(string const & latex_snippet) const264 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
265 {
266 	return pimpl_->preview(latex_snippet);
267 }
268 
269 
status(string const & latex_snippet) const270 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
271 {
272 	return pimpl_->status(latex_snippet);
273 }
274 
275 
add(string const & latex_snippet) const276 void PreviewLoader::add(string const & latex_snippet) const
277 {
278 	pimpl_->add(latex_snippet);
279 }
280 
281 
remove(string const & latex_snippet) const282 void PreviewLoader::remove(string const & latex_snippet) const
283 {
284 	pimpl_->remove(latex_snippet);
285 }
286 
287 
startLoading(bool wait) const288 void PreviewLoader::startLoading(bool wait) const
289 {
290 	pimpl_->startLoading(wait);
291 }
292 
293 
refreshPreviews()294 void PreviewLoader::refreshPreviews()
295 {
296 	pimpl_->refreshPreviews();
297 }
298 
299 
connect(slot const & slot) const300 signals2::connection PreviewLoader::connect(slot const & slot) const
301 {
302 	return pimpl_->imageReady.connect(slot);
303 }
304 
305 
emitSignal(PreviewImage const & pimage) const306 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
307 {
308 	pimpl_->imageReady(pimage);
309 }
310 
311 
buffer() const312 Buffer const & PreviewLoader::buffer() const
313 {
314 	return pimpl_->buffer();
315 }
316 
317 } // namespace graphics
318 } // namespace lyx
319 
320 
321 // The details of the Impl
322 // =======================
323 
324 namespace {
325 
326 class IncrementedFileName {
327 public:
IncrementedFileName(string const & to_format,string const & filename_base)328 	IncrementedFileName(string const & to_format,
329 			    string const & filename_base)
330 		: to_format_(to_format), base_(filename_base), counter_(1)
331 	{}
332 
operator ()(string const & snippet)333 	SnippetPair const operator()(string const & snippet)
334 	{
335 		ostringstream os;
336 		os << base_ << counter_++ << '.' << to_format_;
337 		string const file = os.str();
338 
339 		return make_pair(snippet, FileName(file));
340 	}
341 
342 private:
343 	string const & to_format_;
344 	string const & base_;
345 	int counter_;
346 };
347 
348 
InProgress(string const & filename_base,PendingSnippets const & pending,string const & to_format)349 InProgress::InProgress(string const & filename_base,
350 		       PendingSnippets const & pending,
351 		       string const & to_format)
352 	: pid(0),
353 	  metrics_file(filename_base + ".metrics"),
354 	  snippets(pending.size())
355 {
356 	PendingSnippets::const_iterator pit  = pending.begin();
357 	PendingSnippets::const_iterator pend = pending.end();
358 	BitmapFile::iterator sit = snippets.begin();
359 
360 	transform(pit, pend, sit,
361 		       IncrementedFileName(to_format, filename_base));
362 }
363 
364 
stop() const365 void InProgress::stop() const
366 {
367 	if (pid)
368 		ForkedCallsController::kill(pid, 0);
369 
370 	if (!metrics_file.empty())
371 		metrics_file.removeFile();
372 
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();
378 	}
379 }
380 
381 } // namespace
382 
383 
384 namespace lyx {
385 namespace graphics {
386 
Impl(PreviewLoader & p,Buffer const & b)387 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
388 	: parent_(p), buffer_(b), finished_generating_(true)
389 {
390 	font_scaling_factor_ = int(buffer_.fontScalingFactor());
391 	if (theApp()) {
392 		fg_color_ = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
393 		bg_color_ = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
394 	} else {
395 		fg_color_ = 0x0;
396 		bg_color_ = 0xffffff;
397 	}
398 	if (!pconverter_)
399 		pconverter_ = setConverter("lyxpreview");
400 
401 	delay_refresh_ = new QTimer(&parent_);
402 	delay_refresh_->setSingleShot(true);
403 	QObject::connect(delay_refresh_, SIGNAL(timeout()),
404 	                 &parent_, SLOT(refreshPreviews()));
405 }
406 
407 
setConverter(string const & from)408 lyx::Converter const * PreviewLoader::Impl::setConverter(string const & from)
409 {
410 	typedef vector<string> FmtList;
411 	FmtList const & loadableFormats = graphics::Cache::get().loadableFormats();
412 	FmtList::const_iterator it = loadableFormats.begin();
413 	FmtList::const_iterator const end = loadableFormats.end();
414 
415 	for (; it != end; ++it) {
416 		string const to = *it;
417 		if (from == to)
418 			continue;
419 
420 		lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
421 		if (ptr)
422 			return ptr;
423 	}
424 
425 	// Show the error only once. This is thread-safe.
426 	static nullptr_t no_conv = [&]{
427 		LYXERR0("PreviewLoader::startLoading()\n"
428 		        << "No converter from \"" << from
429 		        << "\" format has been defined.");
430 		return nullptr;
431 	} ();
432 
433 	return no_conv;
434 }
435 
436 
~Impl()437 PreviewLoader::Impl::~Impl()
438 {
439 	delete delay_refresh_;
440 
441 	InProgressProcesses::iterator ipit  = in_progress_.begin();
442 	InProgressProcesses::iterator ipend = in_progress_.end();
443 
444 	for (; ipit != ipend; ++ipit)
445 		ipit->second.stop();
446 }
447 
448 
449 PreviewImage const *
preview(string const & latex_snippet) const450 PreviewLoader::Impl::preview(string const & latex_snippet) const
451 {
452 	int fs = int(buffer_.fontScalingFactor());
453 	int fg = 0x0;
454 	int bg = 0xffffff;
455 	if (theApp()) {
456 		fg = strtol(theApp()->hexName(foregroundColor()).c_str(), 0, 16);
457 		bg = strtol(theApp()->hexName(backgroundColor()).c_str(), 0, 16);
458 	}
459 	if (font_scaling_factor_ != fs || fg_color_ != fg || bg_color_ != bg) {
460 		// Schedule refresh of all previews on zoom or color changes.
461 		// The previews are regenerated only after the zoom factor
462 		// has not been changed for about 1 second.
463 		fg_color_ = fg;
464 		bg_color_ = bg;
465 		delay_refresh_->start(1000);
466 	}
467 	// Don't try to access the cache until we are done.
468 	if (delay_refresh_->isActive() || !finished_generating_)
469 		return 0;
470 	Cache::const_iterator it = cache_.find(latex_snippet);
471 	return (it == cache_.end()) ? 0 : it->second.get();
472 }
473 
474 
refreshPreviews()475 void PreviewLoader::Impl::refreshPreviews()
476 {
477 	font_scaling_factor_ = int(buffer_.fontScalingFactor());
478 	// Reschedule refresh until the previous process completed.
479 	if (!finished_generating_) {
480 		delay_refresh_->start(1000);
481 		return;
482 	}
483 	Cache::const_iterator cit = cache_.begin();
484 	Cache::const_iterator cend = cache_.end();
485 	while (cit != cend)
486 		parent_.remove((cit++)->first);
487 	finished_generating_ = false;
488 	buffer_.updatePreviews();
489 }
490 
491 
492 namespace {
493 
494 class FindSnippet {
495 public:
FindSnippet(string const & s)496 	FindSnippet(string const & s) : snippet_(s) {}
operator ()(InProgressProcess const & process) const497 	bool operator()(InProgressProcess const & process) const
498 	{
499 		BitmapFile const & snippets = process.second.snippets;
500 		BitmapFile::const_iterator beg  = snippets.begin();
501 		BitmapFile::const_iterator end = snippets.end();
502 		return find_if(beg, end, FindFirst(snippet_)) != end;
503 	}
504 
505 private:
506 	string const snippet_;
507 };
508 
509 } // namespace
510 
511 PreviewLoader::Status
status(string const & latex_snippet) const512 PreviewLoader::Impl::status(string const & latex_snippet) const
513 {
514 	Cache::const_iterator cit = cache_.find(latex_snippet);
515 	if (cit != cache_.end())
516 		return Ready;
517 
518 	PendingSnippets::const_iterator pit  = pending_.begin();
519 	PendingSnippets::const_iterator pend = pending_.end();
520 
521 	pit = find(pit, pend, latex_snippet);
522 	if (pit != pend)
523 		return InQueue;
524 
525 	InProgressProcesses::const_iterator ipit  = in_progress_.begin();
526 	InProgressProcesses::const_iterator ipend = in_progress_.end();
527 
528 	ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
529 	if (ipit != ipend)
530 		return Processing;
531 
532 	return NotFound;
533 }
534 
535 
add(string const & latex_snippet)536 void PreviewLoader::Impl::add(string const & latex_snippet)
537 {
538 	if (!pconverter_ || status(latex_snippet) != NotFound)
539 		return;
540 
541 	string const snippet = trim(latex_snippet);
542 	if (snippet.empty())
543 		return;
544 
545 	LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
546 
547 	pending_.push_back(snippet);
548 }
549 
550 
551 namespace {
552 
553 class EraseSnippet {
554 public:
EraseSnippet(string const & s)555 	EraseSnippet(string const & s) : snippet_(s) {}
operator ()(InProgressProcess & process)556 	void operator()(InProgressProcess & process)
557 	{
558 		BitmapFile & snippets = process.second.snippets;
559 		BitmapFile::iterator it  = snippets.begin();
560 		BitmapFile::iterator end = snippets.end();
561 
562 		it = find_if(it, end, FindFirst(snippet_));
563 		if (it != end)
564 			snippets.erase(it, it+1);
565 	}
566 
567 private:
568 	string const & snippet_;
569 };
570 
571 } // namespace
572 
573 
remove(string const & latex_snippet)574 void PreviewLoader::Impl::remove(string const & latex_snippet)
575 {
576 	Cache::iterator cit = cache_.find(latex_snippet);
577 	if (cit != cache_.end())
578 		cache_.erase(cit);
579 
580 	PendingSnippets::iterator pit  = pending_.begin();
581 	PendingSnippets::iterator pend = pending_.end();
582 
583 	pending_.erase(std::remove(pit, pend, latex_snippet), pend);
584 
585 	InProgressProcesses::iterator ipit  = in_progress_.begin();
586 	InProgressProcesses::iterator ipend = in_progress_.end();
587 
588 	for_each(ipit, ipend, EraseSnippet(latex_snippet));
589 
590 	while (ipit != ipend) {
591 		InProgressProcesses::iterator curr = ipit++;
592 		if (curr->second.snippets.empty())
593 			in_progress_.erase(curr);
594 	}
595 }
596 
597 
startLoading(bool wait)598 void PreviewLoader::Impl::startLoading(bool wait)
599 {
600 	if (pending_.empty() || !pconverter_)
601 		return;
602 
603 	// Only start the process off after the buffer is loaded from file.
604 	if (!buffer_.isFullyLoaded())
605 		return;
606 
607 	LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
608 
609 	// As used by the LaTeX file and by the resulting image files
610 	FileName const directory(buffer_.temppath());
611 
612 	FileName const latexfile = unique_tex_filename(directory);
613 	string const filename_base = removeExtension(latexfile.absFileName());
614 
615 	// Create an InProgress instance to place in the map of all
616 	// such processes if it starts correctly.
617 	InProgress inprogress(filename_base, pending_, pconverter_->to());
618 
619 	// clear pending_, so we're ready to start afresh.
620 	pending_.clear();
621 
622 	// Output the LaTeX file.
623 	// we use the encoding of the buffer
624 	Encoding const & enc = buffer_.params().encoding();
625 	ofdocstream of;
626 	try { of.reset(enc.iconvName()); }
627 	catch (iconv_codecvt_facet_exception const & e) {
628 		LYXERR0("Caught iconv exception: " << e.what()
629 			<< "\nUnable to create LaTeX file: " << latexfile);
630 		return;
631 	}
632 
633 	otexstream os(of);
634 	OutputParams runparams(&enc);
635 	LaTeXFeatures features(buffer_, buffer_.params(), runparams);
636 
637 	if (!openFileWrite(of, latexfile))
638 		return;
639 
640 	if (!of) {
641 		LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
642 					<< "Unable to create LaTeX file\n" << latexfile);
643 		return;
644 	}
645 	of << "\\batchmode\n";
646 
647 	// Set \jobname of previews to the document name (see bug 9627)
648 	of << "\\def\\jobname{"
649 	   << from_utf8(changeExtension(buffer_.latexName(true), ""))
650 	   << "}\n";
651 
652 	LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
653 	string latexparam = "";
654 	bool docformat = !buffer_.params().default_output_format.empty()
655 			&& buffer_.params().default_output_format != "default";
656 	// Use LATEX flavor if the document does not specify a specific
657 	// output format (see bug 9371).
658 	OutputParams::FLAVOR flavor = docformat
659 					? buffer_.params().getOutputFlavor()
660 					: OutputParams::LATEX;
661 	if (buffer_.params().encoding().package() == Encoding::japanese) {
662 		latexparam = " --latex=platex";
663 		flavor = OutputParams::LATEX;
664 	}
665 	else if (buffer_.params().useNonTeXFonts) {
666 		if (flavor == OutputParams::LUATEX)
667 			latexparam = " --latex=lualatex";
668 		else {
669 			flavor = OutputParams::XETEX;
670 			latexparam = " --latex=xelatex";
671 		}
672 	}
673 	else {
674 		switch (flavor) {
675 			case OutputParams::PDFLATEX:
676 				latexparam = " --latex=pdflatex";
677 				break;
678 			case OutputParams::XETEX:
679 				latexparam = " --latex=xelatex";
680 				break;
681 			case OutputParams::LUATEX:
682 				latexparam = " --latex=lualatex";
683 				break;
684 			case OutputParams::DVILUATEX:
685 				latexparam = " --latex=dvilualatex";
686 				break;
687 			default:
688 				flavor = OutputParams::LATEX;
689 		}
690 	}
691 	dumpPreamble(os, flavor);
692 	// handle inputenc etc.
693 	// I think, this is already hadled by dumpPreamble(): Kornel
694 	// buffer_.params().writeEncodingPreamble(os, features);
695 	of << "\n\\begin{document}\n";
696 	dumpData(of, inprogress.snippets);
697 	of << "\n\\end{document}\n";
698 	of.close();
699 	if (of.fail()) {
700 		LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
701 					 << "File was not closed properly.");
702 		return;
703 	}
704 
705 	// The conversion command.
706 	ostringstream cs;
707 	cs << pconverter_->command()
708 	   << " " << quoteName(latexfile.toFilesystemEncoding())
709 	   << " --dpi " << font_scaling_factor_;
710 
711 	// FIXME XHTML
712 	// The colors should be customizable.
713 	if (!buffer_.isExporting()) {
714 		ColorCode const fg = PreviewLoader::foregroundColor();
715 		ColorCode const bg = PreviewLoader::backgroundColor();
716 		cs << " --fg " << theApp()->hexName(fg)
717 		   << " --bg " << theApp()->hexName(bg);
718 	}
719 
720 	cs << latexparam;
721 	cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
722 	if (buffer_.params().bufferFormat() == "lilypond-book")
723 		cs << " --lilypond";
724 
725 	string const command = cs.str();
726 
727 	if (wait) {
728 		ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
729 		int ret = call.startScript(ForkedProcess::Wait, command);
730 		static atomic_int fake((2^20) + 1);
731 		int pid = fake++;
732 		inprogress.pid = pid;
733 		inprogress.command = command;
734 		in_progress_[pid] = inprogress;
735 		finishedGenerating(pid, ret);
736 		return;
737 	}
738 
739 	// Initiate the conversion from LaTeX to bitmap images files.
740 	ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
741 	convert_ptr->connect(ForkedProcess::slot([this](pid_t pid, int retval){
742 				finishedGenerating(pid, retval);
743 			}).track_foreign(trackable_.p()));
744 
745 	ForkedCall call(buffer_.filePath());
746 	int ret = call.startScript(command, convert_ptr);
747 
748 	if (ret != 0) {
749 		LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
750 					<< "Unable to start process\n" << command);
751 		return;
752 	}
753 
754 	// Store the generation process in a list of all such processes
755 	inprogress.pid = call.pid();
756 	inprogress.command = command;
757 	in_progress_[inprogress.pid] = inprogress;
758 }
759 
760 
displayPixelRatio() const761 double PreviewLoader::displayPixelRatio() const
762 {
763 	return buffer().params().display_pixel_ratio;
764 }
765 
finishedGenerating(pid_t pid,int retval)766 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
767 {
768 	// Paranoia check!
769 	InProgressProcesses::iterator git = in_progress_.find(pid);
770 	if (git == in_progress_.end()) {
771 		lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
772 			"data for PID " << pid << endl;
773 		finished_generating_ = true;
774 		return;
775 	}
776 
777 	string const command = git->second.command;
778 	string const status = retval > 0 ? "failed" : "succeeded";
779 	LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
780 				<< retval << "): processing " << status
781 				<< " for " << command);
782 	if (retval > 0) {
783 		in_progress_.erase(git);
784 		finished_generating_ = true;
785 		return;
786 	}
787 
788 	// Read the metrics file, if it exists
789 	vector<double> ascent_fractions(git->second.snippets.size());
790 	setAscentFractions(ascent_fractions, git->second.metrics_file);
791 
792 	// Add these newly generated bitmap files to the cache and
793 	// start loading them into LyX.
794 	BitmapFile::const_iterator it  = git->second.snippets.begin();
795 	BitmapFile::const_iterator end = git->second.snippets.end();
796 
797 	list<PreviewImagePtr> newimages;
798 
799 	int metrics_counter = 0;
800 	for (; it != end; ++it, ++metrics_counter) {
801 		string const & snip = it->first;
802 		FileName const & file = it->second;
803 		double af = ascent_fractions[metrics_counter];
804 
805 		// Add the image to the cache only if it's actually present
806 		// and not empty (an empty image is signaled by af < 0)
807 		if (af >= 0 && file.isReadableFile()) {
808 			PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
809 			cache_[snip] = ptr;
810 
811 			newimages.push_back(ptr);
812 		}
813 
814 	}
815 
816 	// Remove the item from the list of still-executing processes.
817 	in_progress_.erase(git);
818 
819 	// Tell the outside world
820 	list<PreviewImagePtr>::const_reverse_iterator
821 		nit  = newimages.rbegin();
822 	list<PreviewImagePtr>::const_reverse_iterator
823 		nend = newimages.rend();
824 	for (; nit != nend; ++nit) {
825 		imageReady(*nit->get());
826 	}
827 	finished_generating_ = true;
828 }
829 
830 
dumpPreamble(otexstream & os,OutputParams::FLAVOR flavor) const831 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
832 {
833 	// Dump the preamble only.
834 	LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
835 	OutputParams runparams(&buffer_.params().encoding());
836 	runparams.flavor = flavor;
837 	runparams.nice = true;
838 	runparams.moving_arg = true;
839 	runparams.free_spacing = true;
840 	runparams.is_child = buffer_.parent();
841 	buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
842 
843 	// FIXME! This is a HACK! The proper fix is to control the 'true'
844 	// passed to WriteStream below:
845 	// int InsetMathNest::latex(Buffer const &, odocstream & os,
846 	//                          OutputParams const & runparams) const
847 	// {
848 	//	WriteStream wi(os, runparams.moving_arg, true);
849 	//	par_->write(wi);
850 	//	return wi.line();
851 	// }
852 	os << "\n"
853 	   << "\\def\\lyxlock{}\n"
854 	   << "\n";
855 
856 	// All equation labels appear as "(#)" + preview.sty's rendering of
857 	// the label name
858 	if (lyxrc.preview_hashed_labels)
859 		os << "\\renewcommand{\\theequation}{\\#}\n";
860 
861 	// Use the preview style file to ensure that each snippet appears on a
862 	// fresh page.
863 	// Also support PDF output (automatically generated e.g. when
864 	// \usepackage[pdftex]{hyperref} is used and XeTeX.
865 	os << "\n"
866 	   << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
867 	   << "\n";
868 }
869 
870 
dumpData(odocstream & os,BitmapFile const & vec) const871 void PreviewLoader::Impl::dumpData(odocstream & os,
872 				   BitmapFile const & vec) const
873 {
874 	if (vec.empty())
875 		return;
876 
877 	BitmapFile::const_iterator it  = vec.begin();
878 	BitmapFile::const_iterator end = vec.end();
879 
880 	for (; it != end; ++it) {
881 		// FIXME UNICODE
882 		os << "\\begin{preview}\n"
883 		   << from_utf8(it->first)
884 		   << "\n\\end{preview}\n\n";
885 	}
886 }
887 
888 } // namespace graphics
889 } // namespace lyx
890 
891 #include "moc_PreviewLoader.cpp"
892