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