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