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