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