]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
* enable instant preview with XeTeX (requires preview-latex v.11.86) [bug #5577]
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file lyxpreview2bitmap.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Angus Leeming
9 # with much advice from members of the preview-latex project:
10 # David Kastrup, dak@gnu.org and
11 # Jan-Åke Larsson, jalar@mai.liu.se.
12
13 # Full author contact details are available in file CREDITS
14
15 # This script takes a LaTeX file and generates a collection of
16 # png or ppm image files, one per previewed snippet.
17
18 # Pre-requisites:
19 # * A latex executable;
20 # * preview.sty;
21 # * dvipng;
22 # * pngtoppm (if outputing ppm format images).
23
24 # preview.sty and dvipng are part of the preview-latex project
25 # http://preview-latex.sourceforge.net/
26
27 # preview.sty can alternatively be obtained from
28 # CTAN/support/preview-latex/
29
30 # Example usage:
31 # lyxpreview2bitmap.py png 0lyxpreview.tex 128 000000 faf0e6
32
33 # This script takes six arguments:
34 # FORMAT:   The desired output format. Either 'png' or 'ppm'.
35 # TEXFILE:  the name of the .tex file to be converted.
36 # DPI:      a scale factor, used to ascertain the resolution of the
37 #           generated image which is then passed to gs.
38 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
39 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
40 # CONVERTER: the converter (optional). Default is latex.
41
42 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
43 # if executed successfully, leave in DIR:
44 # * a (possibly large) number of image files with names
45 #   like BASE[0-9]+.png
46 # * a file BASE.metrics, containing info needed by LyX to position
47 #   the images correctly on the screen.
48
49 import glob, os, re, string, sys
50
51 from legacy_lyxpreview2ppm import legacy_conversion, \
52      legacy_conversion_step2
53
54 from lyxpreview_tools import copyfileobj, error, find_exe, \
55      find_exe_or_terminate, make_texcolor, mkstemp, run_command, warning
56
57
58 # Pre-compiled regular expressions.
59 latex_file_re = re.compile("\.tex$")
60
61
62 def usage(prog_name):
63     return "Usage: %s <format> <latex file> <dpi> <fg color> <bg color>\n"\
64            "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
65            % prog_name
66
67
68 def extract_metrics_info(dvipng_stdout, metrics_file):
69     metrics = open(metrics_file, 'w')
70 # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
71 # and glyph numbers from mktexpk. The glyph numbers always match
72 # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
73     page_re = re.compile("\[([0-9]+)[^]]");
74     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
75
76     success = 0
77     page = ""
78     pos = 0
79     while 1:
80         match = page_re.search(dvipng_stdout, pos)
81         if match == None:
82             break
83         page = match.group(1)
84         pos = match.end()
85         match = metrics_re.search(dvipng_stdout, pos)
86         if match == None:
87             break
88         success = 1
89
90         # Calculate the 'ascent fraction'.
91         descent = string.atof(match.group(1))
92         ascent  = string.atof(match.group(2))
93
94         frac = 0.5
95         if ascent >= 0 or descent >= 0:
96             if abs(ascent + descent) > 0.1:
97                 frac = ascent / (ascent + descent)
98
99             # Sanity check
100             if frac < 0:
101                 frac = 0.5
102
103         metrics.write("Snippet %s %f\n" % (page, frac))
104         pos = match.end() + 2
105
106     return success
107
108
109 def color_pdf(latex_file, bg_color):
110     use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)(pdftex\]{preview})")
111
112     tmp = mkstemp()
113
114     success = 0
115     try:
116         for line in open(latex_file, 'r').readlines():
117             match = use_preview_pdf_re.match(line)
118             if match == None:
119                 tmp.write(line)
120                 continue
121             success = 1
122             tmp.write("  \\usepackage{color}\n" \
123                   "  \\pagecolor[rgb]{%s}\n" \
124                   "%s\n" \
125                   % (bg_color, match.group()))
126             continue
127
128     except:
129         # Unable to open the file, but do nothing here because
130         # the calling function will act on the value of 'success'.
131         warning('Warning in color_pdf! Unable to open "%s"' % latex_file)
132         warning(`sys.exc_type` + ',' + `sys.exc_value`)
133
134     if success:
135         copyfileobj(tmp, open(latex_file,"wb"), 1)
136
137     return success
138
139
140 def convert_to_ppm_format(pngtopnm, basename):
141     png_file_re = re.compile("\.png$")
142
143     for png_file in glob.glob("%s*.png" % basename):
144         ppm_file = png_file_re.sub(".ppm", png_file)
145
146         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
147         p2p_status, p2p_stdout = run_command(p2p_cmd)
148         if p2p_status != None:
149             error("Unable to convert %s to ppm format" % png_file)
150
151         ppm = open(ppm_file, 'w')
152         ppm.write(p2p_stdout)
153         os.remove(png_file)
154
155
156 def main(argv):
157     # Parse and manipulate the command line arguments.
158     if len(argv) != 6 and len(argv) != 7:
159         error(usage(argv[0]))
160
161     output_format = string.lower(argv[1])
162
163     dir, latex_file = os.path.split(argv[2])
164     if len(dir) != 0:
165         os.chdir(dir)
166
167     dpi = string.atoi(argv[3])
168     fg_color = make_texcolor(argv[4], False)
169     bg_color = make_texcolor(argv[5], False)
170
171     bg_color_gr = make_texcolor(argv[5], True)
172
173     # External programs used by the script.
174     path = string.split(os.environ["PATH"], os.pathsep)
175     if len(argv) == 7:
176         latex = argv[6]
177     else:
178         latex = find_exe_or_terminate(["latex", "pplatex", "platex", "latex2e"], path)
179
180     # This can go once dvipng becomes widespread.
181     dvipng = find_exe(["dvipng"], path)
182     if dvipng == None:
183         # The data is input to legacy_conversion in as similar
184         # as possible a manner to that input to the code used in
185         # LyX 1.3.x.
186         vec = [ argv[0], argv[2], argv[3], argv[1], argv[4], argv[5], argv[6] ]
187         return legacy_conversion(vec)
188
189     pngtopnm = ""
190     if output_format == "ppm":
191         pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
192
193     # Move color information for PDF into the latex file.
194     if not color_pdf(latex_file, bg_color_gr):
195         error("Unable to move color info into the latex file")
196
197     # Compile the latex file.
198     latex_call = '%s "%s"' % (latex, latex_file)
199
200     latex_status, latex_stdout = run_command(latex_call)
201     if latex_status != None:
202         warning("%s failed to compile %s" \
203               % (os.path.basename(latex), latex_file))
204
205     if latex == "xelatex":
206         warning("Using XeTeX")
207         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
208         return legacy_conversion_step2(latex_file, dpi, output_format)
209
210     # Run the dvi file through dvipng.
211     dvi_file = latex_file_re.sub(".dvi", latex_file)
212     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" "%s"' \
213                   % (dvipng, dpi, fg_color, bg_color, dvi_file)
214
215     dvipng_status, dvipng_stdout = run_command(dvipng_call)
216     if dvipng_status != None:
217         warning("%s failed to generate images from %s ... looking for PDF" \
218               % (os.path.basename(dvipng), dvi_file))
219         # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
220         return legacy_conversion_step2(latex_file, dpi, output_format)
221
222     # Extract metrics info from dvipng_stdout.
223     metrics_file = latex_file_re.sub(".metrics", latex_file)
224     if not extract_metrics_info(dvipng_stdout, metrics_file):
225         error("Failed to extract metrics info from dvipng")
226
227     # Convert images to ppm format if necessary.
228     if output_format == "ppm":
229         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
230
231     return 0
232
233
234 if __name__ == "__main__":
235     main(sys.argv)