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