]> git.lyx.org Git - lyx.git/blob - src/graphics/PreviewLoader.cpp
Avoid an exception when the lyxpreview2bitmap.py script fails completely
[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 "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         // Reschedule refresh until the previous process completed.
454         if (!finished_generating_) {
455                 delay_refresh_->start(1000);
456                 return;
457         }
458         Cache::const_iterator cit = cache_.begin();
459         Cache::const_iterator cend = cache_.end();
460         while (cit != cend)
461                 parent_.remove((cit++)->first);
462         finished_generating_ = false;
463         buffer_.updatePreviews();
464 }
465
466
467 namespace {
468
469 class FindSnippet {
470 public:
471         FindSnippet(string const & s) : snippet_(s) {}
472         bool operator()(InProgressProcess const & process) const
473         {
474                 BitmapFile const & snippets = process.second.snippets;
475                 BitmapFile::const_iterator beg  = snippets.begin();
476                 BitmapFile::const_iterator end = snippets.end();
477                 return find_if(beg, end, FindFirst(snippet_)) != end;
478         }
479
480 private:
481         string const snippet_;
482 };
483
484 } // namespace anon
485
486 PreviewLoader::Status
487 PreviewLoader::Impl::status(string const & latex_snippet) const
488 {
489         Cache::const_iterator cit = cache_.find(latex_snippet);
490         if (cit != cache_.end())
491                 return Ready;
492
493         PendingSnippets::const_iterator pit  = pending_.begin();
494         PendingSnippets::const_iterator pend = pending_.end();
495
496         pit = find(pit, pend, latex_snippet);
497         if (pit != pend)
498                 return InQueue;
499
500         InProgressProcesses::const_iterator ipit  = in_progress_.begin();
501         InProgressProcesses::const_iterator ipend = in_progress_.end();
502
503         ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
504         if (ipit != ipend)
505                 return Processing;
506
507         return NotFound;
508 }
509
510
511 void PreviewLoader::Impl::add(string const & latex_snippet)
512 {
513         if (!pconverter_ || status(latex_snippet) != NotFound)
514                 return;
515
516         string const snippet = trim(latex_snippet);
517         if (snippet.empty())
518                 return;
519
520         LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
521
522         pending_.push_back(snippet);
523 }
524
525
526 namespace {
527
528 class EraseSnippet {
529 public:
530         EraseSnippet(string const & s) : snippet_(s) {}
531         void operator()(InProgressProcess & process)
532         {
533                 BitmapFile & snippets = process.second.snippets;
534                 BitmapFile::iterator it  = snippets.begin();
535                 BitmapFile::iterator end = snippets.end();
536
537                 it = find_if(it, end, FindFirst(snippet_));
538                 if (it != end)
539                         snippets.erase(it, it+1);
540         }
541
542 private:
543         string const & snippet_;
544 };
545
546 } // namespace anon
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         TexRow texrow;
609         otexstream os(of, texrow);
610         OutputParams runparams(&enc);
611         LaTeXFeatures features(buffer_, buffer_.params(), runparams);
612
613         if (!openFileWrite(of, latexfile))
614                 return;
615
616         if (!of) {
617                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
618                                         << "Unable to create LaTeX file\n" << latexfile);
619                 return;
620         }
621         of << "\\batchmode\n";
622
623         LYXERR(Debug::LATEX, "Format = " << buffer_.params().getDefaultOutputFormat());
624         string latexparam = "";
625         bool docformat = !buffer_.params().default_output_format.empty()
626                         && buffer_.params().default_output_format != "default";
627         // Use LATEX flavor if the document does not specify a specific
628         // output format (see bug 9371).
629         OutputParams::FLAVOR flavor = docformat
630                                         ? buffer_.params().getOutputFlavor()
631                                         : OutputParams::LATEX;
632         if (buffer_.params().encoding().package() == Encoding::japanese) {
633                 latexparam = " --latex=platex";
634                 flavor = OutputParams::LATEX;
635         }
636         else if (buffer_.params().useNonTeXFonts) {
637                 if (flavor == OutputParams::LUATEX)
638                         latexparam = " --latex=lualatex";
639                 else {
640                         flavor = OutputParams::XETEX;
641                         latexparam = " --latex=xelatex";
642                 }
643         }
644         else {
645                 switch (flavor) {
646                         case OutputParams::PDFLATEX:
647                                 latexparam = " --latex=pdflatex";
648                                 break;
649                         case OutputParams::XETEX:
650                                 latexparam = " --latex=xelatex";
651                                 break;
652                         case OutputParams::LUATEX:
653                                 latexparam = " --latex=lualatex";
654                                 break;
655                         case OutputParams::DVILUATEX:
656                                 latexparam = " --latex=dvilualatex";
657                                 break;
658                         default:
659                                 flavor = OutputParams::LATEX;
660                 }
661         }
662         dumpPreamble(os, flavor);
663         // handle inputenc etc.
664         // I think, this is already hadled by dumpPreamble(): Kornel
665         // buffer_.params().writeEncodingPreamble(os, features);
666         of << "\n\\begin{document}\n";
667         dumpData(of, inprogress.snippets);
668         of << "\n\\end{document}\n";
669         of.close();
670         if (of.fail()) {
671                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
672                                          << "File was not closed properly.");
673                 return;
674         }
675
676         // The conversion command.
677         ostringstream cs;
678         cs << pconverter_->command()
679            << " " << quoteName(latexfile.toFilesystemEncoding())
680            << " --dpi " << font_scaling_factor_;
681
682         // FIXME XHTML 
683         // The colors should be customizable.
684         if (!buffer_.isExporting()) {
685                 ColorCode const fg = PreviewLoader::foregroundColor();
686                 ColorCode const bg = PreviewLoader::backgroundColor();
687                 cs << " --fg " << theApp()->hexName(fg) 
688                    << " --bg " << theApp()->hexName(bg);
689         }
690
691         cs << latexparam;
692         if (buffer_.params().bibtex_command != "default")
693                 cs << " --bibtex=" << quoteName(buffer_.params().bibtex_command);
694         else if (buffer_.params().encoding().package() == Encoding::japanese)
695                 cs << " --bibtex=" << quoteName(lyxrc.jbibtex_command);
696         else
697                 cs << " --bibtex=" << quoteName(lyxrc.bibtex_command);
698         if (buffer_.params().bufferFormat() == "lilypond-book")
699                 cs << " --lilypond";
700
701         string const command = cs.str();
702
703         if (wait) {
704                 ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
705                 int ret = call.startScript(ForkedProcess::Wait, command);
706                 // FIXME THREAD
707                 static int fake = (2^20) + 1;
708                 int pid = fake++;
709                 inprogress.pid = pid;
710                 inprogress.command = command;
711                 in_progress_[pid] = inprogress;
712                 finishedGenerating(pid, ret);
713                 return;
714         }
715
716         // Initiate the conversion from LaTeX to bitmap images files.
717         ForkedCall::SignalTypePtr
718                 convert_ptr(new ForkedCall::SignalType);
719         convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
720
721         ForkedCall call(buffer_.filePath());
722         int ret = call.startScript(command, convert_ptr);
723
724         if (ret != 0) {
725                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
726                                         << "Unable to start process\n" << command);
727                 return;
728         }
729
730         // Store the generation process in a list of all such processes
731         inprogress.pid = call.pid();
732         inprogress.command = command;
733         in_progress_[inprogress.pid] = inprogress;
734 }
735
736
737 double PreviewLoader::displayPixelRatio() const
738 {
739         return buffer().params().display_pixel_ratio;
740 }
741
742 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
743 {
744         // Paranoia check!
745         InProgressProcesses::iterator git = in_progress_.find(pid);
746         if (git == in_progress_.end()) {
747                 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
748                         "data for PID " << pid << endl;
749                 finished_generating_ = true;
750                 return;
751         }
752
753         string const command = git->second.command;
754         string const status = retval > 0 ? "failed" : "succeeded";
755         LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
756                                 << retval << "): processing " << status
757                                 << " for " << command);
758         if (retval > 0) {
759                 in_progress_.erase(git);
760                 finished_generating_ = true;
761                 return;
762         }
763
764         // Read the metrics file, if it exists
765         vector<double> ascent_fractions(git->second.snippets.size());
766         setAscentFractions(ascent_fractions, git->second.metrics_file);
767
768         // Add these newly generated bitmap files to the cache and
769         // start loading them into LyX.
770         BitmapFile::const_iterator it  = git->second.snippets.begin();
771         BitmapFile::const_iterator end = git->second.snippets.end();
772
773         list<PreviewImagePtr> newimages;
774
775         int metrics_counter = 0;
776         for (; it != end; ++it, ++metrics_counter) {
777                 string const & snip = it->first;
778                 FileName const & file = it->second;
779                 double af = ascent_fractions[metrics_counter];
780
781                 // Add the image to the cache only if it's actually present
782                 // and not empty (an empty image is signaled by af < 0)
783                 if (af >= 0 && file.isReadableFile()) {
784                         PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
785                         cache_[snip] = ptr;
786
787                         newimages.push_back(ptr);
788                 }
789
790         }
791
792         // Remove the item from the list of still-executing processes.
793         in_progress_.erase(git);
794
795         // Tell the outside world
796         list<PreviewImagePtr>::const_reverse_iterator
797                 nit  = newimages.rbegin();
798         list<PreviewImagePtr>::const_reverse_iterator
799                 nend = newimages.rend();
800         for (; nit != nend; ++nit) {
801                 imageReady(*nit->get());
802         }
803         finished_generating_ = true;
804 }
805
806
807 void PreviewLoader::Impl::dumpPreamble(otexstream & os, OutputParams::FLAVOR flavor) const
808 {
809         // Dump the preamble only.
810         LYXERR(Debug::LATEX, "dumpPreamble, flavor == " << flavor);
811         OutputParams runparams(&buffer_.params().encoding());
812         runparams.flavor = flavor;
813         runparams.nice = true;
814         runparams.moving_arg = true;
815         runparams.free_spacing = true;
816         runparams.is_child = buffer_.parent();
817         buffer_.writeLaTeXSource(os, buffer_.filePath(), runparams, Buffer::OnlyPreamble);
818
819         // FIXME! This is a HACK! The proper fix is to control the 'true'
820         // passed to WriteStream below:
821         // int InsetMathNest::latex(Buffer const &, odocstream & os,
822         //                          OutputParams const & runparams) const
823         // {
824         //      WriteStream wi(os, runparams.moving_arg, true);
825         //      par_->write(wi);
826         //      return wi.line();
827         // }
828         os << "\n"
829            << "\\def\\lyxlock{}\n"
830            << "\n";
831
832         // All equation labels appear as "(#)" + preview.sty's rendering of
833         // the label name
834         if (lyxrc.preview_hashed_labels)
835                 os << "\\renewcommand{\\theequation}{\\#}\n";
836
837         // Use the preview style file to ensure that each snippet appears on a
838         // fresh page.
839         // Also support PDF output (automatically generated e.g. when
840         // \usepackage[pdftex]{hyperref} is used and XeTeX.
841         os << "\n"
842            << "\\usepackage[active,delayed,showlabels,lyx]{preview}\n"
843            << "\n";
844 }
845
846
847 void PreviewLoader::Impl::dumpData(odocstream & os,
848                                    BitmapFile const & vec) const
849 {
850         if (vec.empty())
851                 return;
852
853         BitmapFile::const_iterator it  = vec.begin();
854         BitmapFile::const_iterator end = vec.end();
855
856         for (; it != end; ++it) {
857                 // FIXME UNICODE
858                 os << "\\begin{preview}\n"
859                    << from_utf8(it->first)
860                    << "\n\\end{preview}\n\n";
861         }
862 }
863
864 } // namespace graphics
865 } // namespace lyx
866
867 #include "moc_PreviewLoader.cpp"