]> git.lyx.org Git - lyx.git/blob - src/graphics/PreviewLoader.cpp
Do not redefine \jobname for previews
[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         LYXERR(Debug::OUTFILE, "Format = " << buffer_.params().getDefaultOutputFormat());
623         string latexparam = "";
624         bool docformat = !buffer_.params().default_output_format.empty()
625                         && buffer_.params().default_output_format != "default";
626         // Use LATEX flavor if the document does not specify a specific
627         // output format (see bug 9371).
628         Flavor flavor = docformat
629                                         ? buffer_.params().getOutputFlavor()
630                                         : Flavor::LaTeX;
631         if (buffer_.params().encoding().package() == Encoding::japanese) {
632                 latexparam = " --latex=platex";
633                 flavor = Flavor::LaTeX;
634         }
635         else if (buffer_.params().useNonTeXFonts) {
636                 if (flavor == Flavor::LuaTeX)
637                         latexparam = " --latex=lualatex";
638                 else {
639                         flavor = Flavor::XeTeX;
640                         latexparam = " --latex=xelatex";
641                 }
642         }
643         else {
644                 switch (flavor) {
645                         case Flavor::PdfLaTeX:
646                                 latexparam = " --latex=pdflatex";
647                                 break;
648                         case Flavor::XeTeX:
649                                 latexparam = " --latex=xelatex";
650                                 break;
651                         case Flavor::LuaTeX:
652                                 latexparam = " --latex=lualatex";
653                                 break;
654                         case Flavor::DviLuaTeX:
655                                 latexparam = " --latex=dvilualatex";
656                                 break;
657                         default:
658                                 flavor = Flavor::LaTeX;
659                 }
660         }
661         dumpPreamble(os, flavor);
662         // handle inputenc etc.
663         // I think this is already handled by dumpPreamble(): Kornel
664         // buffer_.params().writeEncodingPreamble(os, features);
665         of << "\n\\begin{document}\n";
666         dumpData(of, inprogress.snippets);
667         of << "\n\\end{document}\n";
668         of.close();
669         if (of.fail()) {
670                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
671                                          << "File was not closed properly.");
672                 return;
673         }
674
675         // The conversion command.
676         ostringstream cs;
677         cs << subst(pconverter_->command(), "$${python}", os::python())
678            << " " << quoteName(latexfile.toFilesystemEncoding())
679            << " --dpi " << font_scaling_factor_;
680
681         // FIXME XHTML
682         // The colors should be customizable.
683         if (!buffer_.isExporting()) {
684                 ColorCode const fg = PreviewLoader::foregroundColor();
685                 ColorCode const bg = PreviewLoader::backgroundColor();
686                 cs << " --fg " << theApp()->hexName(fg)
687                    << " --bg " << theApp()->hexName(bg);
688         }
689
690         cs << latexparam;
691         cs << " --bibtex=" << quoteName(buffer_.params().bibtexCommand());
692         if (buffer_.params().bufferFormat() == "lilypond-book")
693                 cs << " --lilypond";
694
695         string const command = cs.str();
696
697         if (wait) {
698                 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
699                 int ret = call.startScript(ForkedProcess::Wait, command);
700                 // PID_MAX_LIMIT is 2^22 so we start one after that
701                 static atomic_int fake((1 << 22) + 1);
702                 int pid = fake++;
703                 inprogress.pid = pid;
704                 inprogress.command = command;
705                 in_progress_[pid] = inprogress;
706                 finishedGenerating(pid, ret);
707                 return;
708         }
709
710         // Initiate the conversion from LaTeX to bitmap images files.
711         ForkedCall::sigPtr convert_ptr = make_shared<ForkedCall::sig>();
712         weak_ptr<PreviewLoader::Impl> this_ = parent_.pimpl_;
713         convert_ptr->connect([this_](pid_t pid, int retval){
714                         if (auto p = this_.lock()) {
715                                 p->finishedGenerating(pid, retval);
716                         }
717                 });
718
719         ForkedCall call(buffer_.filePath());
720         int ret = call.startScript(command, convert_ptr);
721
722         if (ret != 0) {
723                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
724                                         << "Unable to start process\n" << command);
725                 return;
726         }
727
728         // Store the generation process in a list of all such processes
729         inprogress.pid = call.pid();
730         inprogress.command = command;
731         in_progress_[inprogress.pid] = inprogress;
732 }
733
734
735 double PreviewLoader::displayPixelRatio() const
736 {
737         return buffer().params().display_pixel_ratio;
738 }
739
740 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
741 {
742         // Paranoia check!
743         InProgressProcesses::iterator git = in_progress_.find(pid);
744         if (git == in_progress_.end()) {
745                 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
746                         "data for PID " << pid << endl;
747                 finished_generating_ = true;
748                 return;
749         }
750
751         string const command = git->second.command;
752         string const status = retval > 0 ? "failed" : "succeeded";
753         LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
754                                 << retval << "): processing " << status
755                                 << " for " << command);
756         if (retval > 0) {
757                 in_progress_.erase(git);
758                 finished_generating_ = true;
759                 return;
760         }
761
762         // Read the metrics file, if it exists
763         vector<double> ascent_fractions(git->second.snippets.size());
764         setAscentFractions(ascent_fractions, git->second.metrics_file);
765
766         // Add these newly generated bitmap files to the cache and
767         // start loading them into LyX.
768         BitmapFile::const_iterator it  = git->second.snippets.begin();
769         BitmapFile::const_iterator end = git->second.snippets.end();
770
771         list<PreviewImagePtr> newimages;
772
773         size_t metrics_counter = 0;
774         for (; it != end; ++it, ++metrics_counter) {
775                 string const & snip = it->first;
776                 FileName const & file = it->second;
777                 double af = ascent_fractions[metrics_counter];
778
779                 // Add the image to the cache only if it's actually present
780                 // and not empty (an empty image is signaled by af < 0)
781                 if (af >= 0 && file.isReadableFile()) {
782                         PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
783                         cache_[snip] = ptr;
784
785                         newimages.push_back(ptr);
786                 }
787
788         }
789
790         // Remove the item from the list of still-executing processes.
791         in_progress_.erase(git);
792
793         // Tell the outside world
794         list<PreviewImagePtr>::const_reverse_iterator
795                 nit  = newimages.rbegin();
796         list<PreviewImagePtr>::const_reverse_iterator
797                 nend = newimages.rend();
798         for (; nit != nend; ++nit) {
799                 imageReady(*nit->get());
800         }
801         finished_generating_ = true;
802 }
803
804
805 void PreviewLoader::Impl::dumpPreamble(otexstream & os, Flavor flavor) const
806 {
807         // Dump the preamble only.
808         LYXERR(Debug::OUTFILE, "dumpPreamble, flavor == " << static_cast<int>(flavor));
809         OutputParams runparams(&buffer_.params().encoding());
810         runparams.flavor = flavor;
811         runparams.nice = true;
812         runparams.moving_arg = true;
813         runparams.free_spacing = true;
814         runparams.is_child = buffer_.parent();
815         buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
816
817         // FIXME! This is a HACK! The proper fix is to control the 'true'
818         // passed to TeXMathStream below:
819         // int InsetMathNest::latex(Buffer const &, odocstream & os,
820         //                          OutputParams const & runparams) const
821         // {
822         //      TeXMathStream wi(os, runparams.moving_arg, true);
823         //      par_->write(wi);
824         //      return wi.line();
825         // }
826         os << "\n"
827            << "\\def\\lyxlock{}\n"
828            << "\n";
829
830         // All equation labels appear as "(#)" + preview.sty's rendering of
831         // the label name
832         if (lyxrc.preview_hashed_labels)
833                 os << "\\renewcommand{\\theequation}{\\#}\n";
834
835         // Use the preview style file to ensure that each snippet appears on a
836         // fresh page.
837         // Also support PDF output (automatically generated e.g. when
838         // \usepackage[pdftex]{hyperref} is used and XeTeX.
839         os << "\n"
840            << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
841            << "\n";
842 }
843
844
845 void PreviewLoader::Impl::dumpData(odocstream & os,
846                                    BitmapFile const & vec) const
847 {
848         if (vec.empty())
849                 return;
850
851         BitmapFile::const_iterator it  = vec.begin();
852         BitmapFile::const_iterator end = vec.end();
853
854         for (; it != end; ++it) {
855                 // FIXME UNICODE
856                 os << "\\begin{preview}\n"
857                    << from_utf8(it->first)
858                    << "\n\\end{preview}\n\n";
859         }
860 }
861
862 } // namespace graphics
863 } // namespace lyx
864
865 #include "moc_PreviewLoader.cpp"