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