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