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