3 # file legacy_lyxpreview2ppm.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
9 # Full author contact details are available in file CREDITS
11 # This script converts a LaTeX file to a bunch of ppm files using the
12 # deprecated dvi->ps->ppm conversion route.
14 # If possible, please grab 'dvipng'; it's faster and more robust.
15 # This legacy support will be removed one day...
17 import glob, os, re, string, sys
18 import pipes, shutil, tempfile
21 # Pre-compiled regular expressions.
22 latex_file_re = re.compile("\.tex$")
26 return "Usage: %s <latex file> <dpi> <fg color> <bg color>\n"\
27 "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
32 sys.stderr.write(message + '\n')
36 def find_exe(candidates, path):
37 for prog in candidates:
38 for directory in path:
39 full_path = os.path.join(directory, prog)
40 if os.access(full_path, os.X_OK):
46 def find_exe_or_terminate(candidates, path):
47 exe = find_exe(candidates, path)
49 error("Unable to find executable from '%s'" % string.join(candidates))
55 handle = os.popen(cmd, 'r')
56 cmd_stdout = handle.read()
57 cmd_status = handle.close()
59 return cmd_status, cmd_stdout
62 def extract_metrics_info(log_file, metrics_file):
63 metrics = open(metrics_file, 'w')
65 log_re = re.compile("Preview: ([ST])")
66 data_re = re.compile("(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)")
72 for line in open(log_file, 'r').readlines():
73 match = log_re.match(line)
77 snippet = (match.group(1) == 'S')
79 match = data_re.search(line)
81 error("Unexpected data in %s\n%s" % (log_file, line))
84 ascent = string.atof(match.group(2)) + tp_ascent
85 descent = string.atof(match.group(3)) - tp_descent
88 if abs(ascent + descent) > 0.1:
89 frac = ascent / (ascent + descent)
91 metrics.write("Snippet %s %f\n" % (match.group(1), frac))
94 tp_descent = string.atof(match.group(2))
95 tp_ascent = string.atof(match.group(4))
100 def extract_resolution(log_file, dpi):
101 fontsize_re = re.compile("Preview: Fontsize")
102 magnification_re = re.compile("Preview: Magnification")
103 extract_decimal_re = re.compile("([0-9\.]+)")
104 extract_integer_re = re.compile("([0-9]+)")
107 found_magnification = 0
110 magnification = 1000.0
113 for line in open(log_file, 'r').readlines():
114 if found_fontsize and found_magnification:
117 if not found_fontsize:
118 match = fontsize_re.match(line)
120 match = extract_decimal_re.search(line)
122 error("Unable to parse: %s" % line)
123 fontsize = string.atof(match.group(1))
127 if not found_magnification:
128 match = magnification_re.match(line)
130 match = extract_integer_re.search(line)
132 error("Unable to parse: %s" % line)
133 magnification = string.atof(match.group(1))
134 found_magnification = 1
137 return dpi * (10.0 / fontsize) * (1000.0 / magnification)
140 def get_version_info():
141 version_re = re.compile("([0-9])\.([0-9])")
143 match = version_re.match(sys.version)
145 error("Unable to extract version info from 'sys.version'")
147 return string.atoi(match.group(1)), string.atoi(match.group(2))
151 major, minor = get_version_info()
153 if major >= 2 and minor >= 3:
154 return tempfile.mkstemp()
156 tmp_name = tempfile.mktemp()
157 return open(tmp_name, 'w'), tmp_name
160 def legacy_latex_file(latex_file, fg_color, bg_color):
161 use_preview_re = re.compile("(\\\\usepackage\[[^]]+)(\]{preview})")
163 tmp, tmp_name = mkstemp()
166 for line in open(latex_file, 'r').readlines():
167 match = use_preview_re.match(line)
173 tmp.write("%s,dvips,tightpage%s\n\n" \
174 "\\AtBeginDocument{\\AtBeginDvi{%%\n" \
175 "\\special{!userdict begin/bop-hook{//bop-hook exec\n" \
176 "<%s%s>{255 div}forall setrgbcolor\n" \
177 "clippath fill setrgbcolor}bind def end}}}\n" \
178 % (match.group(1), match.group(2), fg_color, bg_color))
182 shutil.copy(tmp_name, latex_file)
188 def crop_files(pnmcrop, basename):
190 t.append("%s -left $IN" % pnmcrop, 'f-')
191 t.append("%s -right > $OUT" % pnmcrop, '-f')
193 tmp, tmp_name = mkstemp()
197 for file in glob.glob("%s*.ppm" % basename):
198 if t.copy(file, tmp_name):
199 shutil.copy(tmp_name, file)
203 def legacy_conversion(argv):
204 # Parse and manipulate the command line arguments.
206 error(usage(argv[0]))
210 dir, latex_file = os.path.split(argv[2])
214 dpi = string.atoi(argv[3])
218 # External programs used by the script.
219 path = string.split(os.getenv("PATH"), os.pathsep)
220 latex = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
221 dvips = find_exe_or_terminate(["dvips"], path)
222 gs = find_exe_or_terminate(["gs"], path)
223 pnmcrop = find_exe(["pnmcrop"], path)
225 # Move color information into the latex file.
226 if not legacy_latex_file(latex_file, fg_color, bg_color):
227 error("Unable to move color info into the latex file")
229 # Compile the latex file.
230 latex_call = "%s %s" % (latex, latex_file)
232 latex_status, latex_stdout = run_command(latex_call)
233 if latex_status != None:
234 error("%s failed to compile %s" \
235 % (os.path.basename(latex), latex_file))
237 # Run the dvi file through dvips.
238 dvi_file = latex_file_re.sub(".dvi", latex_file)
239 ps_file = latex_file_re.sub(".ps", latex_file)
241 dvips_call = "%s -o %s %s" % (dvips, ps_file, dvi_file)
243 dvips_status, dvips_stdout = run_command(dvips_call)
244 if dvips_status != None:
245 error("Failed: %s %s" % (os.path.basename(dvips), dvi_file))
247 # Extract resolution data for gs from the log file.
248 log_file = latex_file_re.sub(".log", latex_file)
249 resolution = extract_resolution(log_file, dpi)
251 # Older versions of gs have problems with a large degree of
252 # anti-aliasing at high resolutions
257 # Generate the bitmap images
258 gs_call = "%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pnmraw " \
259 "-sOutputFile=%s%%d.ppm " \
260 "-dGraphicsAlphaBit=%d -dTextAlphaBits=%d " \
262 % (gs, latex_file_re.sub("", latex_file), \
263 alpha, alpha, resolution, ps_file)
265 gs_status, gs_stdout = run_command(gs_call)
266 if gs_status != None:
267 error("Failed: %s %s" % (os.path.basename(gs), ps_file))
271 crop_files(pnmcrop, latex_file_re.sub("", latex_file))
273 # Extract metrics info from the log file.
274 metrics_file = latex_file_re.sub(".metrics", latex_file)
275 if not extract_metrics_info(log_file, metrics_file):
276 error("Failed to extract metrics info from %s" % log_file)