]> git.lyx.org Git - features.git/blob - lib/scripts/lyxpreview2bitmap.py
Re-enable preview generation using dvips, gs and pnmcrop.
[features.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 from legacy_lyxpreview2ppm import legacy_conversion
48
49
50 # Pre-compiled regular expressions.
51 hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
52 latex_file_re = re.compile("\.tex$")
53
54
55 def usage(prog_name):
56     return "Usage: %s <latex file> <dpi> <fg color> <bg color>\n"\
57            "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
58            % prog_name
59
60
61 def error(message):
62     sys.stderr.write(message + '\n')
63     sys.exit(1)
64
65
66 def find_exe(candidates, path):
67     for prog in candidates:
68         for directory in path:
69             full_path = os.path.join(directory, prog)
70             if os.access(full_path, os.X_OK):
71                 return full_path
72
73     return None
74
75
76 def find_exe_or_terminate(candidates, path):
77     exe = find_exe(candidates, path)
78     if exe == None:
79         error("Unable to find executable from '%s'" % string.join(candidates))
80
81     return exe
82
83
84 def run_command(cmd):
85     handle = os.popen(cmd, 'r')
86     cmd_stdout = handle.read()
87     cmd_status = handle.close()
88
89     return cmd_status, cmd_stdout
90
91
92 def make_texcolor(hexcolor):
93     # Test that the input string contains 6 hexadecimal chars.
94     if not hexcolor_re.match(hexcolor):
95         error("Cannot convert color '%s'" % hexcolor)
96
97     red   = float(string.atoi(hexcolor[0:2], 16)) / 255.0
98     green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
99     blue  = float(string.atoi(hexcolor[4:6], 16)) / 255.0
100
101     return "rgb %f %f %f" % (red, green, blue)
102
103
104 def extract_metrics_info(dvipng_stdout, metrics_file):
105     metrics = open(metrics_file, 'w')
106     metrics_re = re.compile("\[([0-9]+) depth=(-?[0-9]+) height=(-?[0-9]+)")
107
108     success = 0
109     pos = 0
110     while 1:
111         match = metrics_re.search(dvipng_stdout, pos)
112         if match == None:
113             break
114         success = 1
115
116         # Calculate the 'ascent fraction'.
117         descent = string.atof(match.group(2))
118         ascent  = string.atof(match.group(3))
119         frac = 0.5
120         if abs(ascent + descent) > 0.1:
121             frac = ascent / (ascent + descent)
122
123         metrics.write("Snippet %s %f\n" % (match.group(1), frac))
124         pos = match.end(3) + 2
125
126     return success
127
128
129 def convert_to_ppm_format(pngtopnm, basename):
130     png_file_re = re.compile("\.png$")
131
132     for png_file in glob.glob("%s*.png" % basename):
133         ppm_file = png_file_re.sub(".ppm", png_file)
134
135         p2p_cmd = "%s %s" % (pngtopnm, png_file)
136         p2p_status, p2p_stdout = run_command(p2p_cmd)
137         if p2p_status != None:
138             error("Unable to convert %s to ppm format" % png_file)
139
140         ppm = open(ppm_file, 'w')
141         ppm.write(p2p_stdout)
142         os.remove(png_file)
143
144
145 def main(argv):
146     # Parse and manipulate the command line arguments.
147     if len(argv) != 6:
148         error(usage(argv[0]))
149
150     output_format = string.lower(argv[1])
151
152     dir, latex_file = os.path.split(argv[2])
153     if len(dir) != 0:
154         os.chdir(dir)
155
156     dpi = string.atoi(argv[3])
157     fg_color = make_texcolor(argv[4])
158     bg_color = make_texcolor(argv[5])
159
160     # External programs used by the script.
161     path = string.split(os.getenv("PATH"), os.pathsep)
162     latex = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
163
164     # This can go once dvipng becomes widespread.
165     dvipng = find_exe(["dvipng"], path)
166     if dvipng == None:
167         if output_format == "ppm":
168             return legacy_conversion(argv)
169         else:
170             error("The old 'dvi->ps->ppm' conversion requires "
171                   "ppm as the output format")
172
173     pngtopnm = ""
174     if output_format == "ppm":
175         pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
176
177     # Compile the latex file.
178     latex_call = "%s %s" % (latex, latex_file)
179
180     latex_status, latex_stdout = run_command(latex_call)
181     if latex_status != None:
182         error("%s failed to compile %s" \
183               % (os.path.basename(latex), latex_file))
184
185     # Run the dvi file through dvipng.
186     dvi_file = latex_file_re.sub(".dvi", latex_file)
187     dvipng_call = "%s -Ttight -depth -height -D %d -fg '%s' -bg '%s' %s" \
188                   % (dvipng, dpi, fg_color, bg_color, dvi_file)
189
190     dvipng_status, dvipng_stdout = run_command(dvipng_call)
191     if dvipng_status != None:
192         error("%s failed to generate images from %s" \
193               % (os.path.basename(dvipng), dvi_file))
194
195     # Extract metrics info from dvipng_stdout.
196     metrics_file = latex_file_re.sub(".metrics", latex_file)
197     if not extract_metrics_info(dvipng_stdout, metrics_file):
198         error("Failed to extract metrics info from dvipng")
199
200     # Convert images to ppm format if necessary.
201     if output_format == "ppm":
202         convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
203
204     return 0
205
206 if __name__ == "__main__":
207     main(sys.argv)