2 # -*- coding: iso-8859-1 -*-
4 # file lyxpreview2bitmap.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
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.
13 # Full author contact details are available in file CREDITS
15 # This script takes a LaTeX file and generates a collection of
16 # png or ppm image files, one per previewed snippet.
19 # * A latex executable;
22 # * pngtoppm (if outputing ppm format images).
24 # preview.sty and dvipng are part of the preview-latex project
25 # http://preview-latex.sourceforge.net/
27 # preview.sty can alternatively be obtained from
28 # CTAN/support/preview-latex/
31 # lyxpreview2bitmap.py png 0lyxpreview.tex 128 000000 faf0e6
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'.
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
45 # * a file BASE.metrics, containing info needed by LyX to position
46 # the images correctly on the screen.
48 import glob, os, re, string, sys
50 from legacy_lyxpreview2ppm import legacy_conversion
52 from lyxpreview_tools import error, find_exe, \
53 find_exe_or_terminate, run_command
56 # Pre-compiled regular expressions.
57 hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
58 latex_file_re = re.compile("\.tex$")
62 return "Usage: %s <format> <latex file> <dpi> <fg color> <bg color>\n"\
63 "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
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)
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
76 return "rgb %f %f %f" % (red, green, blue)
79 def extract_metrics_info(dvipng_stdout, metrics_file):
80 metrics = open(metrics_file, 'w')
81 metrics_re = re.compile("\[([0-9]+) depth=(-?[0-9]+) height=(-?[0-9]+)")
86 match = metrics_re.search(dvipng_stdout, pos)
91 # Calculate the 'ascent fraction'.
92 descent = string.atof(match.group(2))
93 ascent = string.atof(match.group(3))
96 if ascent > 0 and descent > 0:
97 if abs(ascent + descent) > 0.1:
98 frac = ascent / (ascent + descent)
101 if frac < 0 or frac > 1:
104 metrics.write("Snippet %s %f\n" % (match.group(1), frac))
105 pos = match.end(3) + 2
110 def convert_to_ppm_format(pngtopnm, basename):
111 png_file_re = re.compile("\.png$")
113 for png_file in glob.glob("%s*.png" % basename):
114 ppm_file = png_file_re.sub(".ppm", png_file)
116 p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
117 p2p_status, p2p_stdout = run_command(p2p_cmd)
118 if p2p_status != None:
119 error("Unable to convert %s to ppm format" % png_file)
121 ppm = open(ppm_file, 'w')
122 ppm.write(p2p_stdout)
127 # Parse and manipulate the command line arguments.
129 error(usage(argv[0]))
131 output_format = string.lower(argv[1])
133 dir, latex_file = os.path.split(argv[2])
137 dpi = string.atoi(argv[3])
138 fg_color = make_texcolor(argv[4])
139 bg_color = make_texcolor(argv[5])
141 # External programs used by the script.
142 path = string.split(os.environ["PATH"], os.pathsep)
143 latex = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
145 # This can go once dvipng becomes widespread.
146 dvipng = find_exe(["dvipng"], path)
148 if output_format == "ppm":
149 # The data is input to legacy_conversion in as similar
150 # as possible a manner to that input to the code used in
152 vec = [ argv[0], argv[2], argv[3], argv[1], argv[4], argv[5] ]
153 return legacy_conversion(vec)
155 error("The old 'dvi->ps->ppm' conversion requires "
156 "ppm as the output format")
159 if output_format == "ppm":
160 pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
162 # Compile the latex file.
163 latex_call = '%s "%s"' % (latex, latex_file)
165 latex_status, latex_stdout = run_command(latex_call)
166 if latex_status != None:
167 error("%s failed to compile %s" \
168 % (os.path.basename(latex), latex_file))
170 # Run the dvi file through dvipng.
171 dvi_file = latex_file_re.sub(".dvi", latex_file)
172 dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" "%s"' \
173 % (dvipng, dpi, fg_color, bg_color, dvi_file)
175 dvipng_status, dvipng_stdout = run_command(dvipng_call)
176 if dvipng_status != None:
177 error("%s failed to generate images from %s" \
178 % (os.path.basename(dvipng), dvi_file))
180 # Extract metrics info from dvipng_stdout.
181 metrics_file = latex_file_re.sub(".metrics", latex_file)
182 if not extract_metrics_info(dvipng_stdout, metrics_file):
183 error("Failed to extract metrics info from dvipng")
185 # Convert images to ppm format if necessary.
186 if output_format == "ppm":
187 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
192 if __name__ == "__main__":