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