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