]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
0a1f77c85fd3a6887e7c06ca61246be67531a1ef
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
1 #! /usr/bin/env python
2
3 # file lyxpreview2bitmap.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
6
7 # author Angus Leeming
8 # with much advice from members of the preview-latex project:
9 # David Kastrup, dak@gnu.org and
10 # Jan-Åke Larsson, jalar@mai.liu.se.
11
12 # Full author contact details are available in file CREDITS
13
14 # This script takes a LaTeX file and generates a collection of
15 # png or ppm image files, one per previewed snippet.
16
17 # Pre-requisites:
18 # * A latex executable;
19 # * preview.sty;
20 # * dvipng;
21 # * pngtoppm (if outputing ppm format images).
22
23 # preview.sty and dvipng are part of the preview-latex project
24 # http://preview-latex.sourceforge.net/
25
26 # preview.sty can alternatively be obtained from
27 # CTAN/support/preview-latex/
28
29 # Example usage:
30 # lyxpreview2bitmap.py png 0lyxpreview.tex 128 000000 faf0e6
31
32 # This script takes five arguments:
33 # FORMAT:   either 'png' or 'ppm'. The desired output format.
34 # TEXFILE:  the name of the .tex file to be converted.
35 # DPI:      a scale factor, passed to dvipng.
36 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
37 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
38
39 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
40 # if executed successfully, leave in DIR:
41 # * a (possibly large) number of image files with names
42 #   like BASE[0-9]+.png
43 # * a file BASE.metrics, containing info needed by LyX to position
44 #   the images correctly on the screen.
45
46 import glob, os, re, string, sys
47
48
49 # Pre-compiled regular expressions.
50 hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
51 latex_file_re = re.compile("\.tex$")
52
53
54 def usage(prog_name):
55     return "Usage: %s <latex file> <dpi> <fg color> <bg color>\n"\
56            "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
57            % prog_name
58
59
60 def error(message):
61     sys.stderr.write(message + '\n')
62     sys.exit(1)
63
64
65 def find_exe(candidates, path):
66     for prog in candidates:
67         for directory in path:
68             full_path = os.path.join(directory, prog)
69             if os.access(full_path, os.X_OK):
70                 return full_path
71
72     return None
73
74
75 def find_exe_or_terminate(candidates, path):
76     exe = find_exe(candidates, path)
77     if exe == None:
78         error("Unable to find executable from '%s'" % string.join(candidates))
79
80     return exe
81
82
83 def run_command(cmd):
84     handle = os.popen(cmd, 'r')
85     cmd_stdout = handle.read()
86     cmd_status = handle.close()
87
88     return cmd_status, cmd_stdout
89
90
91 def make_texcolor(hexcolor):
92     # Test that the input string contains 6 hexadecimal chars.
93     if not hexcolor_re.match(hexcolor):
94         error("Cannot convert color '%s'" % hexcolor)
95
96     red   = float(string.atoi(hexcolor[0:2], 16)) / 255.0
97     green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
98     blue  = float(string.atoi(hexcolor[4:6], 16)) / 255.0
99
100     return "rgb %f %f %f" % (red, green, blue)
101
102
103 def extract_metrics_info(dvipng_stdout, metrics_file):
104     metrics = open(metrics_file, 'w')
105     metrics_re = re.compile("\[([0-9]+) depth=([0-9]+) height=([0-9]+)\]")
106
107     success = 0
108     pos = 0
109     while 1:
110         match = metrics_re.search(dvipng_stdout, pos)
111         if match == None:
112             break
113         success = 1
114
115         # Calculate the 'ascent fraction'.
116         descent = string.atof(match.group(2))
117         ascent  = string.atof(match.group(3))
118         frac = 0.5
119         if abs(ascent + descent) > 0.1:
120             frac = ascent / (ascent + descent)
121
122         metrics.write("Snippet %s %f\n" % (match.group(1), frac))
123         pos = match.end(3) + 2
124
125     return success
126
127
128 def convert_to_ppm_format(pngtopnm, basename):
129     png_file_re = re.compile("\.png$")
130
131     for png_file in glob.glob("%s*.png" % basename):
132         ppm_file = png_file_re.sub(".ppm", png_file)
133
134         p2p_cmd = "%s %s" % (pngtopnm, png_file)
135         p2p_status, p2p_stdout = run_command(p2p_cmd)
136         if p2p_status != None:
137             error("Unable to convert %s to ppm format" % png_file)
138
139         ppm = open(ppm_file, 'w')
140         ppm.write(p2p_stdout)
141         os.remove(png_file)
142
143
144 def main(argv):
145     # Parse and manipulate the command line arguments.
146     if len(argv) != 6:
147         error(usage(argv[0]))
148
149     output_format = string.lower(argv[1])
150
151     dir, latex_file = os.path.split(argv[2])
152     if len(dir) != 0:
153         os.chdir(dir)
154
155     dpi = string.atoi(argv[3])
156     fg_color = make_texcolor(argv[4])
157     bg_color = make_texcolor(argv[5])
158
159     # External programs used by the script.
160     path = string.split(os.getenv("PATH"), os.pathsep)
161     latex = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
162     dvipng = find_exe_or_terminate(["dvipng"], path)
163     pngtopnm = ""
164     if output_format == "ppm":
165         pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
166
167     # Compile the latex file.
168     latex_call = "%s %s" % (latex, latex_file)
169
170     latex_status, latex_stdout = run_command(latex_call)
171     if latex_status != None:
172         error("%s failed to compile %s" \
173               % (os.path.basename(latex), latex_file))
174
175     # Run the dvi file through dvipng.
176     dvi_file = latex_file_re.sub(".dvi", latex_file)
177     dvipng_call = "%s -Ttight -depth -height -D %d -fg '%s' -bg '%s' %s" \
178                   % (dvipng, dpi, fg_color, bg_color, dvi_file)
179
180     dvipng_status, dvipng_stdout = run_command(dvipng_call)
181     if dvipng_status != None:
182         error("%s failed to generate images from %s" \
183               % (os.path.basename(dvipng), dvi_file))
184
185     # Extract metrics info from dvipng_stdout.
186     metrics_file = latex_file_re.sub(".metrics", latex_file)
187     if not extract_metrics_info(dvipng_stdout, metrics_file):
188         error("Failed to extract metrics info from dvipng")
189
190     # Convert images to ppm format if necessary.
191     if output_format == "ppm":
192         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
193
194
195 if __name__ == "__main__":
196     main(sys.argv)