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