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