2 # -*- coding: utf-8 -*-
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, make_texcolor, mkstemp, run_command, warning, \
62 # Pre-compiled regular expression.
63 latex_file_re = re.compile("\.tex$")
67 return "Usage: %s <latex file> <dpi> ppm <fg color> <bg color>\n"\
68 "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
71 # Returns a list of tuples containing page number and ascent fraction
72 # extracted from dvipng output.
73 # Use write_metrics_info to create the .metrics file with this info
74 def legacy_extract_metrics_info(log_file):
76 log_re = re.compile("Preview: ([ST])")
77 data_re = re.compile("(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)")
85 for line in open(log_file, 'r').readlines():
86 match = log_re.match(line)
90 snippet = (match.group(1) == 'S')
92 match = data_re.search(line)
94 error("Unexpected data in %s\n%s" % (log_file, line))
97 ascent = string.atoi(match.group(2))
98 descent = string.atoi(match.group(3))
101 if ascent >= 0 and descent >= 0:
102 ascent = float(ascent) + tp_ascent
103 descent = float(descent) - tp_descent
105 if abs(ascent + descent) > 0.1:
106 frac = ascent / (ascent + descent)
109 if frac < 0 or frac > 1:
112 results.append((match.group(1), frac))
115 tp_descent = string.atof(match.group(2))
116 tp_ascent = string.atof(match.group(4))
119 # Unable to open the file, but do nothing here because
120 # the calling function will act on the value of 'success'.
121 warning('Warning in legacy_extract_metrics_info! Unable to open "%s"' % log_file)
122 warning(`sys.exc_type` + ',' + `sys.exc_value`)
125 error("Failed to extract metrics info from %s" % log_file)
130 def extract_resolution(log_file, dpi):
131 fontsize_re = re.compile("Preview: Fontsize")
132 magnification_re = re.compile("Preview: Magnification")
133 extract_decimal_re = re.compile("([0-9\.]+)")
134 extract_integer_re = re.compile("([0-9]+)")
137 found_magnification = 0
140 magnification = 1000.0
144 for line in open(log_file, 'r').readlines():
145 if found_fontsize and found_magnification:
148 if not found_fontsize:
149 match = fontsize_re.match(line)
151 match = extract_decimal_re.search(line)
153 error("Unable to parse: %s" % line)
154 fontsize = string.atof(match.group(1))
158 if not found_magnification:
159 match = magnification_re.match(line)
161 match = extract_integer_re.search(line)
163 error("Unable to parse: %s" % line)
164 magnification = string.atof(match.group(1))
165 found_magnification = 1
169 warning('Warning in extract_resolution! Unable to open "%s"' % log_file)
170 warning(`sys.exc_type` + ',' + `sys.exc_value`)
172 # This is safe because both fontsize and magnification have
173 # non-zero default values.
174 return dpi * (10.0 / fontsize) * (1000.0 / magnification)
177 def legacy_latex_file(latex_file, fg_color, bg_color, bg_color_gr):
178 use_preview_dvi_re = re.compile("(\s*\\\\usepackage\[[^]]+)(dvips\]{preview})")
179 use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)(pdftex\]{preview})")
185 for line in open(latex_file, 'r').readlines():
186 match = use_preview_dvi_re.match(line)
188 match = use_preview_pdf_re.match(line)
193 tmp.write(" \\usepackage{color}\n" \
194 " \\pagecolor[rgb]{%s}\n" \
196 % (bg_color_gr, match.group()))
200 tmp.write("%stightpage,%s\n" \
201 " \\AtBeginDocument{\\AtBeginDvi{%%\n" \
202 " \\special{!userdict begin/bop-hook{//bop-hook exec\n" \
203 " <%s%s>{255 div}forall setrgbcolor\n" \
204 " clippath fill setrgbcolor}bind def end}}}\n" \
205 % (match.group(1), match.group(2), fg_color, bg_color))
208 # Unable to open the file, but do nothing here because
209 # the calling function will act on the value of 'success'.
210 warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
211 warning(`sys.exc_type` + ',' + `sys.exc_value`)
214 copyfileobj(tmp, open(latex_file,"wb"), 1)
219 def crop_files(pnmcrop, basename):
221 t.append('%s -left' % pnmcrop, '--')
222 t.append('%s -right' % pnmcrop, '--')
224 for file in glob.glob("%s*.ppm" % basename):
226 new = t.open(file, "r")
227 copyfileobj(new, tmp)
229 copyfileobj(tmp, open(file,"wb"), 1)
232 def legacy_conversion(argv, skipMetrics = False):
233 latex_commands = ["latex", "pplatex", "platex", "latex2e"]
234 # Parse and manipulate the command line arguments.
236 latex_commands = [argv[6]]
238 error(usage(argv[0]))
240 dir, latex_file = os.path.split(argv[1])
244 dpi = string.atoi(argv[2])
246 output_format = argv[3]
250 bg_color_gr = make_texcolor(argv[5], True)
252 # External programs used by the script.
253 path = string.split(os.environ["PATH"], os.pathsep)
254 latex = find_exe_or_terminate(latex_commands, path)
256 # Move color information into the latex file.
257 if not legacy_latex_file(latex_file, fg_color, bg_color, bg_color_gr):
258 error("Unable to move color info into the latex file")
260 # Compile the latex file.
261 latex_call = '%s "%s"' % (latex, latex_file)
263 latex_status, latex_stdout = run_command(latex_call)
264 if latex_status != None:
265 warning("%s had problems compiling %s" \
266 % (os.path.basename(latex), latex_file))
268 return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
271 def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False):
272 # External programs used by the script.
273 path = string.split(os.environ["PATH"], os.pathsep)
274 dvips = find_exe_or_terminate(["dvips"], path)
275 gs = find_exe_or_terminate(["gswin32c", "gs"], path)
276 pnmcrop = find_exe(["pnmcrop"], path)
278 # Run the dvi file through dvips.
279 dvi_file = latex_file_re.sub(".dvi", latex_file)
280 ps_file = latex_file_re.sub(".ps", latex_file)
281 pdf_file = latex_file_re.sub(".pdf", latex_file)
283 dvips_call = '%s -i -o "%s" "%s"' % (dvips, ps_file, dvi_file)
286 dvips_status, dvips_stdout = run_command(dvips_call)
287 if dvips_status != None:
288 warning('Failed: %s %s ... looking for PDF' \
289 % (os.path.basename(dvips), dvi_file))
292 # Extract resolution data for gs from the log file.
293 log_file = latex_file_re.sub(".log", latex_file)
294 resolution = extract_resolution(log_file, dpi)
296 # Older versions of gs have problems with a large degree of
297 # anti-aliasing at high resolutions
304 if output_format == "ppm":
308 # Generate the bitmap images
311 gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
312 '-sOutputFile="%s%%d.%s" ' \
313 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
315 % (gs, gs_device, latex_file_re.sub("", latex_file), \
316 gs_ext, alpha, alpha, resolution, pdf_file)
318 gs_status, gs_stdout = run_command(gs_call)
319 if gs_status != None:
320 error("Failed: %s %s" % (os.path.basename(gs), ps_file))
322 gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
323 '-sOutputFile="%s%%d.%s" ' \
324 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
326 % (gs, gs_device, latex_file_re.sub("", latex_file), \
327 gs_ext, alpha, alpha, resolution)
329 ps_files = glob.glob("%s.[0-9][0-9][0-9]" % latex_file_re.sub("", latex_file))
331 for file in ps_files:
333 gs_status, gs_stdout = run_command(gs_call % (i, file))
334 if gs_status != None:
335 warning("Failed: %s %s" % (os.path.basename(gs), file))
341 crop_files(pnmcrop, latex_file_re.sub("", latex_file))
343 # Allow to skip .metrics creation for custom management
344 # (see the dvipng method)
346 # Extract metrics info from the log file.
347 metrics_file = latex_file_re.sub(".metrics", latex_file)
348 write_metrics_info(legacy_extract_metrics_info(log_file), metrics_file)
353 if __name__ == "__main__":
354 legacy_conversion(sys.argv)