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