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