1 # -*- coding: utf-8 -*-
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.
8 # Full author contact details are available in file CREDITS
10 # with much advice from members of the preview-latex project:
11 # David Kastrup, dak@gnu.org and
12 # Jan-Åke Larsson, jalar@mai.liu.se.
13 # and with much help testing the code under Windows from
14 # Paul A. Rubin, rubin@msu.edu.
16 # This script takes a LaTeX file and generates a collection of
17 # png or ppm image files, one per previewed snippet.
19 # legacy_lyxpreview2bitmap.py 0lyxpreview.tex 128 ppm 000000 faf0e6
21 # This script takes five arguments:
22 # TEXFILE: the name of the .tex file to be converted.
23 # SCALEFACTOR: a scale factor, used to ascertain the resolution of the
24 # generated image which is then passed to gs.
25 # OUTPUTFORMAT: the format of the output bitmap image files.
26 # This particular script can produce only "ppm" format output.
27 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
28 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
30 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
31 # if executed successfully, leave in DIR:
32 # * a (possibly large) number of image files with names
33 # like BASE[0-9]+.(ppm|png)
34 # * a file BASE.metrics, containing info needed by LyX to position
35 # the images correctly on the screen.
37 # The script uses several external programs and files:
38 # * python 2.4 or later (subprocess module);
39 # * A latex executable;
43 # * pdflatex (optional);
44 # * pnmcrop (optional).
46 # preview.sty is part of the preview-latex project
47 # http://preview-latex.sourceforge.net/
48 # Alternatively, it can be obtained from
49 # CTAN/support/preview-latex/
51 # What does this script do?
53 # 0) Process command-line arguments
54 # [legacy_conversion_step1]
55 # 1) Call latex to create a DVI file from LaTeX
56 # [legacy_conversion_step2]
57 # 2) Call dvips to create one PS file for each DVI page
58 # [legacy_conversion_step3]
59 # 3) If dvips fails look for PDF and call gs to produce bitmaps
60 # 4) Otherwise call gs on each PostScript file to produce bitmaps
61 # [legacy_conversion_pdflatex]
62 # 5) Keep track of pages on which gs failed and pass them to pdflatex
63 # 6) Call gs on the PDF output from pdflatex to produce bitmaps
64 # 7) Extract and write to file (or return to lyxpreview2bitmap)
65 # metrics from both methods (standard and pdflatex)
67 # The script uses the old dvi->ps->png conversion route,
68 # which is good when using PSTricks, TikZ or other packages involving
69 # PostScript literals (steps 1, 2, 4).
70 # This script also generates bitmaps from PDF created by a call to
71 # lyxpreview2bitmap.py passing "pdflatex" to the CONVERTER parameter
73 # Finally, there's also has a fallback method based on pdflatex, which
74 # is required in certain cases, if hyperref is active for instance,
76 # If possible, dvipng should be used, as it's much faster.
78 import glob, os, pipes, re, string, sys
80 from lyxpreview_tools import copyfileobj, error, filter_pages, find_exe, \
81 find_exe_or_terminate, join_metrics_and_rename, latex_commands, \
82 latex_file_re, make_texcolor, mkstemp, pdflatex_commands, progress, \
83 run_command, run_latex, warning, write_metrics_info
87 return "Usage: %s <latex file> <dpi> ppm <fg color> <bg color>\n" \
88 "\twhere the colors are hexadecimal strings, eg 'faf0e6'" \
91 # Returns a list of tuples containing page number and ascent fraction
92 # extracted from dvipng output.
93 # Use write_metrics_info to create the .metrics file with this info
94 def legacy_extract_metrics_info(log_file):
96 log_re = re.compile("Preview: ([ST])")
97 data_re = re.compile("(-?[0-9]+) (-?[0-9]+) (-?[0-9]+) (-?[0-9]+)")
105 for line in open(log_file, 'r').readlines():
106 match = log_re.match(line)
110 snippet = (match.group(1) == 'S')
112 match = data_re.search(line)
114 error("Unexpected data in %s\n%s" % (log_file, line))
117 ascent = string.atof(match.group(2))
118 descent = string.atof(match.group(3))
121 if ascent == 0 and descent == 0:
122 # This is an empty image, forbid its display
124 elif ascent >= 0 or descent >= 0:
125 ascent = ascent + tp_ascent
126 descent = descent - tp_descent
128 if abs(ascent + descent) > 0.1:
129 frac = ascent / (ascent + descent)
132 if frac < 0 or frac > 1:
135 results.append((int(match.group(1)), frac))
138 tp_descent = string.atof(match.group(2))
139 tp_ascent = string.atof(match.group(4))
142 # Unable to open the file, but do nothing here because
143 # the calling function will act on the value of 'success'.
144 warning('Warning in legacy_extract_metrics_info! Unable to open "%s"' % log_file)
145 warning(`sys.exc_type` + ',' + `sys.exc_value`)
148 error("Failed to extract metrics info from %s" % log_file)
152 def extract_resolution(log_file, dpi):
153 fontsize_re = re.compile("Preview: Fontsize")
154 magnification_re = re.compile("Preview: Magnification")
155 extract_decimal_re = re.compile("([0-9\.]+)")
156 extract_integer_re = re.compile("([0-9]+)")
159 found_magnification = 0
162 magnification = 1000.0
166 for line in open(log_file, 'r').readlines():
167 if found_fontsize and found_magnification:
170 if not found_fontsize:
171 match = fontsize_re.match(line)
173 match = extract_decimal_re.search(line)
175 error("Unable to parse: %s" % line)
176 fontsize = string.atof(match.group(1))
180 if not found_magnification:
181 match = magnification_re.match(line)
183 match = extract_integer_re.search(line)
185 error("Unable to parse: %s" % line)
186 magnification = string.atof(match.group(1))
187 found_magnification = 1
191 warning('Warning in extract_resolution! Unable to open "%s"' % log_file)
192 warning(`sys.exc_type` + ',' + `sys.exc_value`)
194 # This is safe because both fontsize and magnification have
195 # non-zero default values.
196 return dpi * (10.0 / fontsize) * (1000.0 / magnification)
199 def legacy_latex_file(latex_file, fg_color, bg_color):
200 use_preview_re = re.compile(r"\s*\\usepackage\[([^]]+)\]{preview}")
201 fg_color_gr = make_texcolor(fg_color, True)
202 bg_color_gr = make_texcolor(bg_color, True)
208 f = open(latex_file, 'r')
210 # Unable to open the file, but do nothing here because
211 # the calling function will act on the value of 'success'.
212 warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
213 warning(`sys.exc_type` + ',' + `sys.exc_value`)
215 for line in f.readlines():
219 match = use_preview_re.match(line)
224 # Package order: color should be loaded before preview
225 # Preview options: add the options lyx and tightpage
228 \definecolor{fg}{rgb}{%s}
229 \definecolor{bg}{rgb}{%s}
231 \usepackage[%s,tightpage]{preview}
233 \g@addto@macro\preview{\begingroup\color{bg}\special{ps::clippath fill}\color{fg}}
234 \g@addto@macro\endpreview{\endgroup}
236 """ % (fg_color_gr, bg_color_gr, match.group(1)))
239 copyfileobj(tmp, open(latex_file,"wb"), 1)
244 def crop_files(pnmcrop, basename):
246 t.append('%s -left' % pnmcrop, '--')
247 t.append('%s -right' % pnmcrop, '--')
249 for file in glob.glob("%s*.ppm" % basename):
251 new = t.open(file, "r")
252 copyfileobj(new, tmp)
254 copyfileobj(tmp, open(file,"wb"), 1)
257 def legacy_conversion(argv, skipMetrics = False):
258 # Parse and manipulate the command line arguments.
262 error(usage(argv[0]))
266 dir, latex_file = os.path.split(argv[1])
270 dpi = string.atoi(argv[2])
272 output_format = argv[3]
277 # External programs used by the script.
278 latex = find_exe_or_terminate(latex or latex_commands)
280 pdf_output = latex in pdflatex_commands
282 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
283 bg_color, latex, pdf_output, skipMetrics)
286 # Add color info to the latex file, since ghostscript doesn't
287 # have the option to set foreground and background colors on
288 # the command line. Run the resulting file through latex.
289 def legacy_conversion_step1(latex_file, dpi, output_format, fg_color, bg_color,
290 latex, pdf_output = False, skipMetrics = False):
292 # Move color information, lyx and tightpage options into the latex file.
293 if not legacy_latex_file(latex_file, fg_color, bg_color):
294 error("""Unable to move the color information, and the lyx and tightpage
295 options of preview-latex, into the latex file""")
297 # Compile the latex file.
298 latex_status, latex_stdout = run_latex(latex, latex_file)
300 return (latex_status, [])
303 return legacy_conversion_step3(latex_file, dpi, output_format, True, skipMetrics)
305 return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
307 # Creates a new LaTeX file from the original with pages specified in
308 # failed_pages, pass it through pdflatex and updates the metrics
309 # from the standard legacy route
310 def legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
311 gs_device, gs_ext, alpha, resolution, output_format):
313 # Search for pdflatex executable
314 pdflatex = find_exe(["pdflatex"])
316 warning("Can't find pdflatex. Some pages failed with all the possible routes.")
318 # Create a new LaTeX file from the original but only with failed pages
319 pdf_latex_file = latex_file_re.sub("_pdflatex.tex", latex_file)
320 filter_pages(latex_file, pdf_latex_file, failed_pages)
323 pdflatex_status, pdflatex_stdout = run_latex(pdflatex, pdf_latex_file)
325 pdf_file = latex_file_re.sub(".pdf", pdf_latex_file)
327 # GhostScript call to produce bitmaps
328 gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
329 '-sOutputFile="%s%%d.%s" ' \
330 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
332 % (gs, gs_device, latex_file_re.sub("", pdf_latex_file), \
333 gs_ext, alpha, alpha, resolution, pdf_file)
334 gs_status, gs_stdout = run_command(gs_call)
337 warning("Some pages failed with all the possible routes")
340 pdf_log_file = latex_file_re.sub(".log", pdf_latex_file)
341 pdf_metrics = legacy_extract_metrics_info(pdf_log_file)
343 original_bitmap = latex_file_re.sub("%d." + output_format, pdf_latex_file)
344 destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
346 # Join the metrics with the those from dvips and rename the bitmap images
347 join_metrics_and_rename(legacy_metrics, pdf_metrics, failed_pages,
348 original_bitmap, destination_bitmap)
351 # The file has been processed through latex and we expect dvi output.
352 # Run dvips, taking note whether it was successful.
353 def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False):
354 # External programs used by the script.
355 dvips = find_exe_or_terminate(["dvips"])
357 # Run the dvi file through dvips.
358 dvi_file = latex_file_re.sub(".dvi", latex_file)
359 ps_file = latex_file_re.sub(".ps", latex_file)
361 dvips_call = '%s -i -o "%s" "%s"' % (dvips, ps_file, dvi_file)
364 dvips_status, dvips_stdout = run_command(dvips_call)
366 warning('Failed: %s %s ... looking for PDF' \
367 % (os.path.basename(dvips), dvi_file))
370 return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics)
373 # Either latex and dvips have been run and we have a ps file, or
374 # pdflatex has been run and we have a pdf file. Proceed with gs.
375 def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics = False):
376 # External programs used by the script.
377 gs = find_exe_or_terminate(["gswin32c", "gswin64c", "gs"])
378 pnmcrop = find_exe(["pnmcrop"])
381 pdf_file = latex_file_re.sub(".pdf", latex_file)
382 ps_file = latex_file_re.sub(".ps", latex_file)
384 # Extract resolution data for gs from the log file.
385 log_file = latex_file_re.sub(".log", latex_file)
386 resolution = extract_resolution(log_file, dpi)
388 # Older versions of gs have problems with a large degree of
389 # anti-aliasing at high resolutions
396 if output_format == "ppm":
400 # Extract the metrics from the log file
401 legacy_metrics = legacy_extract_metrics_info(log_file)
403 # List of pages which failed to produce a correct output
406 # Generate the bitmap images
408 # dvips failed, maybe there's a PDF, try to produce bitmaps
409 gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
410 '-sOutputFile="%s%%d.%s" ' \
411 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
413 % (gs, gs_device, latex_file_re.sub("", latex_file), \
414 gs_ext, alpha, alpha, resolution, pdf_file)
416 gs_status, gs_stdout = run_command(gs_call)
418 error("Failed: %s %s" % (os.path.basename(gs), ps_file))
420 # Model for calling gs on each file
421 gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
422 '-sOutputFile="%s%%d.%s" ' \
423 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
425 % (gs, gs_device, latex_file_re.sub("", latex_file), \
426 gs_ext, alpha, alpha, resolution)
429 # Collect all the PostScript files (like *.001, *.002, ...)
430 ps_files = glob.glob("%s.[0-9][0-9][0-9]" % latex_file_re.sub("", latex_file))
433 # Call GhostScript for each file
434 for file in ps_files:
436 progress("Processing page %s, file %s" % (i, file))
437 gs_status, gs_stdout = run_command(gs_call % (i, file))
439 # gs failed, keep track of this
440 warning("Ghostscript failed on page %s, file %s" % (i, file))
441 failed_pages.append(i)
443 # Pass failed pages to pdflatex
444 if len(failed_pages) > 0:
445 legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
446 gs_device, gs_ext, alpha, resolution, output_format)
450 crop_files(pnmcrop, latex_file_re.sub("", latex_file))
452 # Allow to skip .metrics creation for custom management
453 # (see the dvipng method)
455 # Extract metrics info from the log file.
456 metrics_file = latex_file_re.sub(".metrics", latex_file)
457 write_metrics_info(legacy_metrics, metrics_file)
459 return (0, legacy_metrics)
462 if __name__ == "__main__":
463 sys.exit(legacy_conversion(sys.argv)[0])