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