]> git.lyx.org Git - lyx.git/blob - src/graphics/PreviewLoader.cpp
remove a few uses of boost::scoped_ptr
[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 "debug.h"
21 #include "Encoding.h"
22 #include "Format.h"
23 #include "InsetIterator.h"
24 #include "LaTeXFeatures.h"
25 #include "LyXRC.h"
26 #include "output.h"
27 #include "OutputParams.h"
28 #include "TexRow.h"
29
30 #include "frontends/Application.h" // hexName
31
32 #include "insets/Inset.h"
33
34 #include "support/filetools.h"
35 #include "support/Forkedcall.h"
36 #include "support/ForkedcallsController.h"
37 #include "support/lstrings.h"
38 #include "support/lyxlib.h"
39 #include "support/convert.h"
40
41 #include <boost/bind.hpp>
42
43 #include <sstream>
44 #include <fstream>
45 #include <iomanip>
46
47 using lyx::support::FileName;
48
49 using std::endl;
50 using std::find;
51 using std::fill;
52 using std::find_if;
53 using std::make_pair;
54
55 using boost::bind;
56
57 using std::ifstream;
58 using std::list;
59 using std::map;
60 using std::ostringstream;
61 using std::pair;
62 using std::vector;
63 using std::string;
64
65
66 namespace {
67
68 typedef pair<string, FileName> SnippetPair;
69
70 // A list of all snippets to be converted to previews
71 typedef list<string> PendingSnippets;
72
73 // Each item in the vector is a pair<snippet, image file name>.
74 typedef vector<SnippetPair> BitmapFile;
75
76
77 string const unique_filename(string const & bufferpath)
78 {
79         static int theCounter = 0;
80         string const filename = lyx::convert<string>(theCounter++) + "lyxpreview";
81         return lyx::support::addName(bufferpath, filename);
82 }
83
84
85 lyx::Converter const * setConverter()
86 {
87         string const from = "lyxpreview";
88
89         typedef vector<string> FmtList;
90         typedef lyx::graphics::Cache GCache;
91         FmtList const loadableFormats = GCache::get().loadableFormats();
92         FmtList::const_iterator it = loadableFormats.begin();
93         FmtList::const_iterator const end = loadableFormats.end();
94
95         for (; it != end; ++it) {
96                 string const to = *it;
97                 if (from == to)
98                         continue;
99
100                 lyx::Converter const * ptr = lyx::theConverters().getConverter(from, to);
101                 if (ptr)
102                         return ptr;
103         }
104
105         static bool first = true;
106         if (first) {
107                 first = false;
108                 lyx::lyxerr << "PreviewLoader::startLoading()\n"
109                        << "No converter from \"lyxpreview\" format has been "
110                         "defined."
111                        << endl;
112         }
113         return 0;
114 }
115
116
117 void setAscentFractions(vector<double> & ascent_fractions,
118                         FileName const & metrics_file)
119 {
120         // If all else fails, then the images will have equal ascents and
121         // descents.
122         vector<double>::iterator it  = ascent_fractions.begin();
123         vector<double>::iterator end = ascent_fractions.end();
124         fill(it, end, 0.5);
125
126         ifstream in(metrics_file.toFilesystemEncoding().c_str());
127         if (!in.good()) {
128                 lyx::lyxerr[lyx::Debug::GRAPHICS]
129                         << "setAscentFractions(" << metrics_file << ")\n"
130                         << "Unable to open file!" << endl;
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                 lyx::lyxerr[lyx::Debug::GRAPHICS]
164                         << "setAscentFractions(" << metrics_file << ")\n"
165                         << "Error reading file!\n" << endl;
166         }
167 }
168
169
170 class FindFirst : public std::unary_function<SnippetPair, bool> {
171 public:
172         FindFirst(string const & comp) : comp_(comp) {}
173         bool operator()(SnippetPair const & sp) const
174         {
175                 return sp.first == comp_;
176         }
177 private:
178         string const comp_;
179 };
180
181
182 /// Store info on a currently executing, forked process.
183 class InProgress {
184 public:
185         ///
186         InProgress() : pid(0) {}
187         ///
188         InProgress(string const & filename_base,
189                    PendingSnippets const & pending,
190                    string const & to_format);
191         /// Remove any files left lying around and kill the forked process.
192         void stop() const;
193
194         ///
195         pid_t pid;
196         ///
197         string command;
198         ///
199         FileName metrics_file;
200         ///
201         BitmapFile snippets;
202 };
203
204 typedef map<pid_t, InProgress>  InProgressProcesses;
205
206 typedef InProgressProcesses::value_type InProgressProcess;
207
208 } // namespace anon
209
210
211
212 namespace lyx {
213 namespace graphics {
214
215 class PreviewLoader::Impl : public boost::signals::trackable {
216 public:
217         ///
218         Impl(PreviewLoader & p, Buffer const & b);
219         /// Stop any InProgress items still executing.
220         ~Impl();
221         ///
222         PreviewImage const * preview(string const & latex_snippet) const;
223         ///
224         PreviewLoader::Status status(string const & latex_snippet) const;
225         ///
226         void add(string const & latex_snippet);
227         ///
228         void remove(string const & latex_snippet);
229         ///
230         void startLoading();
231
232         /// Emit this signal when an image is ready for display.
233         boost::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(odocstream &) 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 boost::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         double font_scaling_factor_;
271
272         /// We don't own this
273         static lyx::Converter const * pconverter_;
274 };
275
276
277 lyx::Converter const * PreviewLoader::Impl::pconverter_;
278
279
280 //
281 // The public interface, defined in PreviewLoader.h
282 //
283
284 PreviewLoader::PreviewLoader(Buffer const & b)
285         : pimpl_(new Impl(*this, b))
286 {}
287
288
289 PreviewLoader::~PreviewLoader()
290 {
291         delete pimpl_;
292 }
293
294
295 PreviewImage const * PreviewLoader::preview(string const & latex_snippet) const
296 {
297         return pimpl_->preview(latex_snippet);
298 }
299
300
301 PreviewLoader::Status PreviewLoader::status(string const & latex_snippet) const
302 {
303         return pimpl_->status(latex_snippet);
304 }
305
306
307 void PreviewLoader::add(string const & latex_snippet) const
308 {
309         pimpl_->add(latex_snippet);
310 }
311
312
313 void PreviewLoader::remove(string const & latex_snippet) const
314 {
315         pimpl_->remove(latex_snippet);
316 }
317
318
319 void PreviewLoader::startLoading() const
320 {
321         pimpl_->startLoading();
322 }
323
324
325 boost::signals::connection PreviewLoader::connect(slot_type const & slot) const
326 {
327         return pimpl_->imageReady.connect(slot);
328 }
329
330
331 void PreviewLoader::emitSignal(PreviewImage const & pimage) const
332 {
333         pimpl_->imageReady(pimage);
334 }
335
336
337 Buffer const & PreviewLoader::buffer() const
338 {
339         return pimpl_->buffer();
340 }
341
342 } // namespace graphics
343 } // namespace lyx
344
345
346 // The details of the Impl
347 // =======================
348
349 namespace {
350
351 class IncrementedFileName {
352 public:
353         IncrementedFileName(string const & to_format,
354                             string const & filename_base)
355                 : to_format_(to_format), base_(filename_base), counter_(1)
356         {}
357
358         SnippetPair const operator()(string const & snippet)
359         {
360                 ostringstream os;
361                 os << base_ << counter_++ << '.' << to_format_;
362                 string const file = os.str();
363
364                 return make_pair(snippet, FileName(file));
365         }
366
367 private:
368         string const & to_format_;
369         string const & base_;
370         int counter_;
371 };
372
373
374 InProgress::InProgress(string const & filename_base,
375                        PendingSnippets const & pending,
376                        string const & to_format)
377         : pid(0),
378           metrics_file(FileName(filename_base + ".metrics")),
379           snippets(pending.size())
380 {
381         PendingSnippets::const_iterator pit  = pending.begin();
382         PendingSnippets::const_iterator pend = pending.end();
383         BitmapFile::iterator sit = snippets.begin();
384
385         std::transform(pit, pend, sit,
386                        IncrementedFileName(to_format, filename_base));
387 }
388
389
390 void InProgress::stop() const
391 {
392         if (pid)
393                 lyx::support::ForkedcallsController::get().kill(pid, 0);
394
395         if (!metrics_file.empty())
396                 lyx::support::unlink(metrics_file);
397
398         BitmapFile::const_iterator vit  = snippets.begin();
399         BitmapFile::const_iterator vend = snippets.end();
400         for (; vit != vend; ++vit) {
401                 if (!vit->second.empty())
402                         lyx::support::unlink(vit->second);
403         }
404 }
405
406 } // namespace anon
407
408
409 namespace lyx {
410 namespace graphics {
411
412 PreviewLoader::Impl::Impl(PreviewLoader & p, Buffer const & b)
413         : parent_(p), buffer_(b), font_scaling_factor_(0.0)
414 {
415         font_scaling_factor_ = 0.01 * lyxrc.dpi * lyxrc.zoom *
416                 convert<double>(lyxrc.preview_scale_factor);
417
418         LYXERR(Debug::GRAPHICS, "The font scaling factor is "
419                                 << font_scaling_factor_);
420
421         if (!pconverter_)
422                 pconverter_ = setConverter();
423 }
424
425
426 PreviewLoader::Impl::~Impl()
427 {
428         InProgressProcesses::iterator ipit  = in_progress_.begin();
429         InProgressProcesses::iterator ipend = in_progress_.end();
430
431         for (; ipit != ipend; ++ipit) {
432                 ipit->second.stop();
433         }
434 }
435
436
437 PreviewImage const *
438 PreviewLoader::Impl::preview(string const & latex_snippet) const
439 {
440         Cache::const_iterator it = cache_.find(latex_snippet);
441         return (it == cache_.end()) ? 0 : it->second.get();
442 }
443
444
445 namespace {
446
447 class FindSnippet : public std::unary_function<InProgressProcess, bool> {
448 public:
449         FindSnippet(string const & s) : snippet_(s) {}
450         bool operator()(InProgressProcess const & process) const
451         {
452                 BitmapFile const & snippets = process.second.snippets;
453                 BitmapFile::const_iterator beg  = snippets.begin();
454                 BitmapFile::const_iterator end = snippets.end();
455                 return find_if(beg, end, FindFirst(snippet_)) != end;
456         }
457
458 private:
459         string const snippet_;
460 };
461
462 } // namespace anon
463
464 PreviewLoader::Status
465 PreviewLoader::Impl::status(string const & latex_snippet) const
466 {
467         Cache::const_iterator cit = cache_.find(latex_snippet);
468         if (cit != cache_.end())
469                 return Ready;
470
471         PendingSnippets::const_iterator pit  = pending_.begin();
472         PendingSnippets::const_iterator pend = pending_.end();
473
474         pit = find(pit, pend, latex_snippet);
475         if (pit != pend)
476                 return InQueue;
477
478         InProgressProcesses::const_iterator ipit  = in_progress_.begin();
479         InProgressProcesses::const_iterator ipend = in_progress_.end();
480
481         ipit = find_if(ipit, ipend, FindSnippet(latex_snippet));
482         if (ipit != ipend)
483                 return Processing;
484
485         return NotFound;
486 }
487
488
489 void PreviewLoader::Impl::add(string const & latex_snippet)
490 {
491         if (!pconverter_ || status(latex_snippet) != NotFound)
492                 return;
493
494         string const snippet = support::trim(latex_snippet);
495         if (snippet.empty())
496                 return;
497
498         LYXERR(Debug::GRAPHICS, "adding snippet:\n" << snippet);
499
500         pending_.push_back(snippet);
501 }
502
503
504 namespace {
505
506 class EraseSnippet {
507 public:
508         EraseSnippet(string const & s) : snippet_(s) {}
509         void operator()(InProgressProcess & process)
510         {
511                 BitmapFile & snippets = process.second.snippets;
512                 BitmapFile::iterator it  = snippets.begin();
513                 BitmapFile::iterator end = snippets.end();
514
515                 it = find_if(it, end, FindFirst(snippet_));
516                 if (it != end)
517                         snippets.erase(it, it+1);
518         }
519
520 private:
521         string const & snippet_;
522 };
523
524 } // namespace anon
525
526
527 void PreviewLoader::Impl::remove(string const & latex_snippet)
528 {
529         Cache::iterator cit = cache_.find(latex_snippet);
530         if (cit != cache_.end())
531                 cache_.erase(cit);
532
533         PendingSnippets::iterator pit  = pending_.begin();
534         PendingSnippets::iterator pend = pending_.end();
535
536         pending_.erase(std::remove(pit, pend, latex_snippet), pend);
537
538         InProgressProcesses::iterator ipit  = in_progress_.begin();
539         InProgressProcesses::iterator ipend = in_progress_.end();
540
541         std::for_each(ipit, ipend, EraseSnippet(latex_snippet));
542
543         while (ipit != ipend) {
544                 InProgressProcesses::iterator curr = ipit++;
545                 if (curr->second.snippets.empty())
546                         in_progress_.erase(curr);
547         }
548 }
549
550
551 void PreviewLoader::Impl::startLoading()
552 {
553         if (pending_.empty() || !pconverter_)
554                 return;
555
556         // Only start the process off after the buffer is loaded from file.
557         if (!buffer_.isFullyLoaded())
558                 return;
559
560         LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()");
561
562         // As used by the LaTeX file and by the resulting image files
563         string const directory = buffer_.temppath();
564
565         string const filename_base = unique_filename(directory);
566
567         // Create an InProgress instance to place in the map of all
568         // such processes if it starts correctly.
569         InProgress inprogress(filename_base, pending_, pconverter_->to);
570
571         // clear pending_, so we're ready to start afresh.
572         pending_.clear();
573
574         // Output the LaTeX file.
575         FileName const latexfile(filename_base + ".tex");
576
577         // we use the encoding of the buffer
578         Encoding const & enc = buffer_.params().encoding();
579         odocfstream of(enc.iconvName());
580         TexRow texrow;
581         OutputParams runparams(&enc);
582         LaTeXFeatures features(buffer_, buffer_.params(), runparams);
583
584         if (!openFileWrite(of, latexfile))
585                 return;
586
587         if (!of) {
588                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
589                                         << "Unable to create LaTeX file\n" << latexfile);
590                 return;
591         }
592         of << "\\batchmode\n";
593         dumpPreamble(of);
594         // handle inputenc etc.
595         buffer_.params().writeEncodingPreamble(of, features, texrow);
596         of << "\n\\begin{document}\n";
597         dumpData(of, inprogress.snippets);
598         of << "\n\\end{document}\n";
599         of.close();
600         if (of.fail()) {
601                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
602                                          << "File was not closed properly.");
603                 return;
604         }
605
606         // The conversion command.
607         ostringstream cs;
608         cs << pconverter_->command << ' ' << pconverter_->to << ' '
609            << support::quoteName(latexfile.toFilesystemEncoding()) << ' '
610            << int(font_scaling_factor_) << ' '
611            << theApp()->hexName(Color_preview) << ' '
612            << theApp()->hexName(Color_background);
613
614         string const command = support::libScriptSearch(cs.str());
615
616         // Initiate the conversion from LaTeX to bitmap images files.
617         support::Forkedcall::SignalTypePtr
618                 convert_ptr(new support::Forkedcall::SignalType);
619         convert_ptr->connect(bind(&Impl::finishedGenerating, this, _1, _2));
620
621         support::Forkedcall call;
622         int ret = call.startscript(command, convert_ptr);
623
624         if (ret != 0) {
625                 LYXERR(Debug::GRAPHICS, "PreviewLoader::startLoading()\n"
626                                         << "Unable to start process\n" << command);
627                 return;
628         }
629
630         // Store the generation process in a list of all such processes
631         inprogress.pid = call.pid();
632         inprogress.command = command;
633         in_progress_[inprogress.pid] = inprogress;
634 }
635
636
637 void PreviewLoader::Impl::finishedGenerating(pid_t pid, int retval)
638 {
639         // Paranoia check!
640         InProgressProcesses::iterator git = in_progress_.find(pid);
641         if (git == in_progress_.end()) {
642                 lyxerr << "PreviewLoader::finishedGenerating(): unable to find "
643                         "data for PID " << pid << endl;
644                 return;
645         }
646
647         string const command = git->second.command;
648         string const status = retval > 0 ? "failed" : "succeeded";
649         LYXERR(Debug::GRAPHICS, "PreviewLoader::finishedInProgress("
650                                 << retval << "): processing " << status
651                                 << " for " << command);
652         if (retval > 0)
653                 return;
654
655         // Read the metrics file, if it exists
656         vector<double> ascent_fractions(git->second.snippets.size());
657         setAscentFractions(ascent_fractions, git->second.metrics_file);
658
659         // Add these newly generated bitmap files to the cache and
660         // start loading them into LyX.
661         BitmapFile::const_iterator it  = git->second.snippets.begin();
662         BitmapFile::const_iterator end = git->second.snippets.end();
663
664         std::list<PreviewImagePtr> newimages;
665
666         int metrics_counter = 0;
667         for (; it != end; ++it, ++metrics_counter) {
668                 string const & snip = it->first;
669                 FileName const & file = it->second;
670                 double af = ascent_fractions[metrics_counter];
671
672                 PreviewImagePtr ptr(new PreviewImage(parent_, snip, file, af));
673                 cache_[snip] = ptr;
674
675                 newimages.push_back(ptr);
676         }
677
678         // Remove the item from the list of still-executing processes.
679         in_progress_.erase(git);
680
681         // Tell the outside world
682         std::list<PreviewImagePtr>::const_reverse_iterator
683                 nit  = newimages.rbegin();
684         std::list<PreviewImagePtr>::const_reverse_iterator
685                 nend = newimages.rend();
686         for (; nit != nend; ++nit) {
687                 imageReady(*nit->get());
688         }
689 }
690
691
692 void PreviewLoader::Impl::dumpPreamble(odocstream & os) const
693 {
694         // Why on earth is Buffer::makeLaTeXFile a non-const method?
695         Buffer & tmp = const_cast<Buffer &>(buffer_);
696         // Dump the preamble only.
697         // We don't need an encoding for runparams since it is not used by
698         // the preamble.
699         OutputParams runparams(0);
700         runparams.flavor = OutputParams::LATEX;
701         runparams.nice = true;
702         runparams.moving_arg = true;
703         runparams.free_spacing = true;
704         tmp.writeLaTeXSource(os, buffer_.filePath(), runparams, true, false);
705
706         // FIXME! This is a HACK! The proper fix is to control the 'true'
707         // passed to WriteStream below:
708         // int InsetMathNest::latex(Buffer const &, odocstream & os,
709         //                          OutputParams const & runparams) const
710         // {
711         //      WriteStream wi(os, runparams.moving_arg, true);
712         //      par_->write(wi);
713         //      return wi.line();
714         // }
715         os << "\n"
716            << "\\def\\lyxlock{}\n"
717            << "\n";
718
719         // Loop over the insets in the buffer and dump all the math-macros.
720         Inset & inset = buffer_.inset();
721         InsetIterator it = inset_iterator_begin(inset);
722         InsetIterator const end = inset_iterator_end(inset);
723
724         for (; it != end; ++it)
725                 if (it->lyxCode() == MATHMACRO_CODE)
726                         it->latex(buffer_, os, runparams);
727
728         // All equation labels appear as "(#)" + preview.sty's rendering of
729         // the label name
730         if (lyxrc.preview_hashed_labels)
731                 os << "\\renewcommand{\\theequation}{\\#}\n";
732
733         // Use the preview style file to ensure that each snippet appears on a
734         // fresh page.
735         os << "\n"
736            << "\\usepackage[active,delayed,dvips,showlabels,lyx]{preview}\n"
737            << "\n";
738 }
739
740
741 void PreviewLoader::Impl::dumpData(odocstream & os,
742                                    BitmapFile const & vec) const
743 {
744         if (vec.empty())
745                 return;
746
747         BitmapFile::const_iterator it  = vec.begin();
748         BitmapFile::const_iterator end = vec.end();
749
750         for (; it != end; ++it) {
751                 // FIXME UNICODE
752                 os << "\\begin{preview}\n"
753                    << from_utf8(it->first)
754                    << "\n\\end{preview}\n\n";
755         }
756 }
757
758 } // namespace graphics
759 } // namespace lyx