2 # -*- coding: iso-8859-1 -*-
4 # file legacy_lyxpreview2ppm.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
9 # Full author contact details are available in file CREDITS
11 # with much advice from members of the preview-latex project:
12 # David Kastrup, dak@gnu.org and
13 # Jan-Åke Larsson, jalar@mai.liu.se.
14 # and with much help testing the code under Windows from
15 # Paul A. Rubin, rubin@msu.edu.
17 # This script takes a LaTeX file and generates a collection of
18 # ppm image files, one per previewed snippet.
20 # legacy_lyxpreview2bitmap.py 0lyxpreview.tex 128 ppm 000000 faf0e6
22 # This script takes five arguments:
23 # TEXFILE: the name of the .tex file to be converted.
24 # SCALEFACTOR: a scale factor, used to ascertain the resolution of the
25 # generated image which is then passed to gs.
26 # OUTPUTFORMAT: the format of the output bitmap image files.
27 # This particular script can produce only "ppm" format output.
28 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
29 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
31 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
32 # if executed successfully, leave in DIR:
33 # * a (possibly large) number of image files with names
35 # * a file BASE.metrics, containing info needed by LyX to position
36 # the images correctly on the screen.
38 # The script uses several external programs and files:
39 # * A latex executable;
43 # * pnmcrop (optional).
45 # preview.sty is part of the preview-latex project
46 # http://preview-latex.sourceforge.net/
47 # Alternatively, it can be obtained from
48 # CTAN/support/preview-latex/
50 # The script uses the deprecated dvi->ps->ppm conversion route.
51 # If possible, please grab 'dvipng'; it's faster and more robust.
52 # If you have it then this script will not be invoked by
53 # lyxpreview2bitmap.py.
54 # Warning: this legacy support will be removed one day...
56 import glob, os, pipes, re, string, sys
58 from lyxpreview_tools import copyfileobj, error, find_exe, \
59 find_exe_or_terminate, mkstemp, run_command
61 # Pre-compiled regular expression.
62 latex_file_re = re.compile("\.tex$")
66 return "Usage: %s <latex file> <dpi> ppm <fg color> <bg color>\n"\
67 "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
71 def extract_metrics_info(log_file, metrics_file):
72 metrics = open(metrics_file, 'w')
74 log_re = re.compile("Preview: ([ST])")
75 data_re = re.compile("(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)")
82 for line in open(log_file, 'r').readlines():
83 match = log_re.match(line)
87 snippet = (match.group(1) == 'S')
89 match = data_re.search(line)
91 error("Unexpected data in %s\n%s" % (log_file, line))
94 ascent = string.atof(match.group(2)) + tp_ascent
95 descent = string.atof(match.group(3)) - tp_descent
98 if abs(ascent + descent) > 0.1:
99 frac = ascent / (ascent + descent)
101 metrics.write("Snippet %s %f\n" % (match.group(1), frac))
104 tp_descent = string.atof(match.group(2))
105 tp_ascent = string.atof(match.group(4))
108 # Unable to open the file, but do nothing here because
109 # the calling function will act on the value of 'success'.
110 warning('Warning in extract_metrics_info! Unable to open "%s"' % log_file)
111 warning(`sys.exc_type` + ',' + `sys.exc_value`)
116 def extract_resolution(log_file, dpi):
117 fontsize_re = re.compile("Preview: Fontsize")
118 magnification_re = re.compile("Preview: Magnification")
119 extract_decimal_re = re.compile("([0-9\.]+)")
120 extract_integer_re = re.compile("([0-9]+)")
123 found_magnification = 0
126 magnification = 1000.0
130 for line in open(log_file, 'r').readlines():
131 if found_fontsize and found_magnification:
134 if not found_fontsize:
135 match = fontsize_re.match(line)
137 match = extract_decimal_re.search(line)
139 error("Unable to parse: %s" % line)
140 fontsize = string.atof(match.group(1))
144 if not found_magnification:
145 match = magnification_re.match(line)
147 match = extract_integer_re.search(line)
149 error("Unable to parse: %s" % line)
150 magnification = string.atof(match.group(1))
151 found_magnification = 1
155 warning('Warning in extract_resolution! Unable to open "%s"' % log_file)
156 warning(`sys.exc_type` + ',' + `sys.exc_value`)
158 # This is safe because both fontsize and magnification have
159 # non-zero default values.
160 return dpi * (10.0 / fontsize) * (1000.0 / magnification)
163 def legacy_latex_file(latex_file, fg_color, bg_color):
164 use_preview_re = re.compile("(\\\\usepackage\[[^]]+)(\]{preview})")
170 for line in open(latex_file, 'r').readlines():
171 match = use_preview_re.match(line)
177 tmp.write("%s,dvips,tightpage%s\n\n" \
178 "\\AtBeginDocument{\\AtBeginDvi{%%\n" \
179 "\\special{!userdict begin/bop-hook{//bop-hook exec\n" \
180 "<%s%s>{255 div}forall setrgbcolor\n" \
181 "clippath fill setrgbcolor}bind def end}}}\n" \
182 % (match.group(1), match.group(2), fg_color, bg_color))
185 # Unable to open the file, but do nothing here because
186 # the calling function will act on the value of 'success'.
187 warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
188 warning(`sys.exc_type` + ',' + `sys.exc_value`)
191 copyfileobj(tmp, open(latex_file,"wb"), 1)
196 def crop_files(pnmcrop, basename):
198 t.append('"%s" -left' % pnmcrop, '--')
199 t.append('"%s" -right' % pnmcrop, '--')
201 for file in glob.glob("%s*.ppm" % basename):
203 new = t.open(file, "r")
204 copyfileobj(new, tmp)
206 copyfileobj(tmp, open(file,"wb"), 1)
209 def legacy_conversion(argv):
210 # Parse and manipulate the command line arguments.
212 error(usage(argv[0]))
214 dir, latex_file = os.path.split(argv[1])
218 dpi = string.atoi(argv[2])
220 output_format = argv[3]
221 if output_format != "ppm":
222 error("This script will generate ppm format images only.")
227 # External programs used by the script.
228 path = string.split(os.getenv("PATH"), os.pathsep)
229 latex = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
230 dvips = find_exe_or_terminate(["dvips"], path)
231 gs = find_exe_or_terminate(["gswin32", "gs"], path)
232 pnmcrop = find_exe(["pnmcrop"], path)
234 # Move color information into the latex file.
235 if not legacy_latex_file(latex_file, fg_color, bg_color):
236 error("Unable to move color info into the latex file")
238 # Compile the latex file.
239 latex_call = '"%s" "%s"' % (latex, latex_file)
241 latex_status, latex_stdout = run_command(latex_call)
242 if latex_status != None:
243 error("%s failed to compile %s" \
244 % (os.path.basename(latex), latex_file))
246 # Run the dvi file through dvips.
247 dvi_file = latex_file_re.sub(".dvi", latex_file)
248 ps_file = latex_file_re.sub(".ps", latex_file)
250 dvips_call = '"%s" -o "%s" "%s"' % (dvips, ps_file, dvi_file)
252 dvips_status, dvips_stdout = run_command(dvips_call)
253 if dvips_status != None:
254 error("Failed: %s %s" % (os.path.basename(dvips), dvi_file))
256 # Extract resolution data for gs from the log file.
257 log_file = latex_file_re.sub(".log", latex_file)
258 resolution = extract_resolution(log_file, dpi)
260 # Older versions of gs have problems with a large degree of
261 # anti-aliasing at high resolutions
266 # Generate the bitmap images
267 gs_call = '"%s" -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pnmraw ' \
268 '-sOutputFile="%s%%d.ppm" ' \
269 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
271 % (gs, latex_file_re.sub("", latex_file), \
272 alpha, alpha, resolution, ps_file)
274 gs_status, gs_stdout = run_command(gs_call)
275 if gs_status != None:
276 error("Failed: %s %s" % (os.path.basename(gs), ps_file))
280 crop_files(pnmcrop, latex_file_re.sub("", latex_file))
282 # Extract metrics info from the log file.
283 metrics_file = latex_file_re.sub(".metrics", latex_file)
284 if not extract_metrics_info(log_file, metrics_file):
285 error("Failed to extract metrics info from %s" % log_file)
290 if __name__ == "__main__":
291 legacy_conversion(sys.argv)