]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
*lib/scripts/layout2layout.py: Fix section labelling
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
1 #! /usr/bin/env python
2 # -*- coding: iso-8859-1 -*-
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 five 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
41 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
42 # if executed successfully, leave in DIR:
43 # * a (possibly large) number of image files with names
44 #   like BASE[0-9]+.png
45 # * a file BASE.metrics, containing info needed by LyX to position
46 #   the images correctly on the screen.
47
48 import glob, os, re, string, sys
49
50 from legacy_lyxpreview2ppm import legacy_conversion
51
52 from lyxpreview_tools import error, find_exe, \
53      find_exe_or_terminate, run_command
54
55
56 # Pre-compiled regular expressions.
57 hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
58 latex_file_re = re.compile("\.tex$")
59
60
61 def usage(prog_name):
62     return "Usage: %s <format> <latex file> <dpi> <fg color> <bg color>\n"\
63            "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
64            % prog_name
65
66
67 def make_texcolor(hexcolor):
68     # Test that the input string contains 6 hexadecimal chars.
69     if not hexcolor_re.match(hexcolor):
70         error("Cannot convert color '%s'" % hexcolor)
71
72     red   = float(string.atoi(hexcolor[0:2], 16)) / 255.0
73     green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
74     blue  = float(string.atoi(hexcolor[4:6], 16)) / 255.0
75
76     return "rgb %f %f %f" % (red, green, blue)
77
78
79 def extract_metrics_info(dvipng_stdout, metrics_file):
80     metrics = open(metrics_file, 'w')
81 # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
82 # and glyph numbers from mktexpk. The glyph numbers always match
83 # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
84     page_re = re.compile("\[([0-9]+)[^]]");
85     metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
86
87     success = 0
88     page = ""
89     pos = 0
90     while 1:
91         match = page_re.search(dvipng_stdout, pos)
92         if match == None:
93             break
94         page = match.group(1)
95         pos = match.end()
96         match = metrics_re.search(dvipng_stdout, pos)
97         if match == None:
98             break
99         success = 1
100
101         # Calculate the 'ascent fraction'.
102         descent = string.atof(match.group(1))
103         ascent  = string.atof(match.group(2))
104
105         frac = 0.5
106         if ascent >= 0 or descent >= 0:
107             if abs(ascent + descent) > 0.1:
108                 frac = ascent / (ascent + descent)
109
110             # Sanity check
111             if frac < 0:
112                 frac = 0.5
113
114         metrics.write("Snippet %s %f\n" % (page, frac))
115         pos = match.end() + 2
116
117     return success
118
119
120 def convert_to_ppm_format(pngtopnm, basename):
121     png_file_re = re.compile("\.png$")
122
123     for png_file in glob.glob("%s*.png" % basename):
124         ppm_file = png_file_re.sub(".ppm", png_file)
125
126         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
127         p2p_status, p2p_stdout = run_command(p2p_cmd)
128         if p2p_status != None:
129             error("Unable to convert %s to ppm format" % png_file)
130
131         ppm = open(ppm_file, 'w')
132         ppm.write(p2p_stdout)
133         os.remove(png_file)
134
135
136 def main(argv):
137     # Parse and manipulate the command line arguments.
138     if len(argv) != 6:
139         error(usage(argv[0]))
140
141     output_format = string.lower(argv[1])
142
143     dir, latex_file = os.path.split(argv[2])
144     if len(dir) != 0:
145         os.chdir(dir)
146
147     dpi = string.atoi(argv[3])
148     fg_color = make_texcolor(argv[4])
149     bg_color = make_texcolor(argv[5])
150
151     # External programs used by the script.
152     path = string.split(os.environ["PATH"], os.pathsep)
153     latex = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
154
155     # This can go once dvipng becomes widespread.
156     dvipng = find_exe(["dvipng"], path)
157     if dvipng == None:
158         if output_format == "ppm":
159             # The data is input to legacy_conversion in as similar
160             # as possible a manner to that input to the code used in
161             # LyX 1.3.x.
162             vec = [ argv[0], argv[2], argv[3], argv[1], argv[4], argv[5] ]
163             return legacy_conversion(vec)
164         else:
165             error("The old 'dvi->ps->ppm' conversion requires "
166                   "ppm as the output format")
167
168     pngtopnm = ""
169     if output_format == "ppm":
170         pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
171
172     # Compile the latex file.
173     latex_call = '%s "%s"' % (latex, latex_file)
174
175     latex_status, latex_stdout = run_command(latex_call)
176     if latex_status != None:
177         error("%s failed to compile %s" \
178               % (os.path.basename(latex), latex_file))
179
180     # Run the dvi file through dvipng.
181     dvi_file = latex_file_re.sub(".dvi", latex_file)
182     dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" "%s"' \
183                   % (dvipng, dpi, fg_color, bg_color, dvi_file)
184
185     dvipng_status, dvipng_stdout = run_command(dvipng_call)
186     if dvipng_status != None:
187         error("%s failed to generate images from %s" \
188               % (os.path.basename(dvipng), dvi_file))
189
190     # Extract metrics info from dvipng_stdout.
191     metrics_file = latex_file_re.sub(".metrics", latex_file)
192     if not extract_metrics_info(dvipng_stdout, metrics_file):
193         error("Failed to extract metrics info from dvipng")
194
195     # Convert images to ppm format if necessary.
196     if output_format == "ppm":
197         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
198
199     return 0
200
201
202 if __name__ == "__main__":
203     main(sys.argv)