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