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