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