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