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