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