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