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.atoi(match.group(2))
118 descent = string.atoi(match.group(3))
121 if ascent >= 0 and descent >= 0:
122 ascent = float(ascent) + tp_ascent
123 descent = float(descent) - tp_descent
125 if abs(ascent + descent) > 0.1:
126 frac = ascent / (ascent + descent)
129 if frac < 0 or frac > 1:
132 results.append((int(match.group(1)), frac))
135 tp_descent = string.atof(match.group(2))
136 tp_ascent = string.atof(match.group(4))
139 # Unable to open the file, but do nothing here because
140 # the calling function will act on the value of 'success'.
141 warning('Warning in legacy_extract_metrics_info! Unable to open "%s"' % log_file)
142 warning(`sys.exc_type` + ',' + `sys.exc_value`)
145 error("Failed to extract metrics info from %s" % log_file)
149 def extract_resolution(log_file, dpi):
150 fontsize_re = re.compile("Preview: Fontsize")
151 magnification_re = re.compile("Preview: Magnification")
152 extract_decimal_re = re.compile("([0-9\.]+)")
153 extract_integer_re = re.compile("([0-9]+)")
156 found_magnification = 0
159 magnification = 1000.0
163 for line in open(log_file, 'r').readlines():
164 if found_fontsize and found_magnification:
167 if not found_fontsize:
168 match = fontsize_re.match(line)
170 match = extract_decimal_re.search(line)
172 error("Unable to parse: %s" % line)
173 fontsize = string.atof(match.group(1))
177 if not found_magnification:
178 match = magnification_re.match(line)
180 match = extract_integer_re.search(line)
182 error("Unable to parse: %s" % line)
183 magnification = string.atof(match.group(1))
184 found_magnification = 1
188 warning('Warning in extract_resolution! Unable to open "%s"' % log_file)
189 warning(`sys.exc_type` + ',' + `sys.exc_value`)
191 # This is safe because both fontsize and magnification have
192 # non-zero default values.
193 return dpi * (10.0 / fontsize) * (1000.0 / magnification)
196 def legacy_latex_file(latex_file, fg_color, bg_color):
197 use_preview_re = re.compile(r"\s*\\usepackage\[([^]]+)\]{preview}")
198 fg_color_gr = make_texcolor(fg_color, True)
199 bg_color_gr = make_texcolor(bg_color, True)
205 f = open(latex_file, 'r')
207 # Unable to open the file, but do nothing here because
208 # the calling function will act on the value of 'success'.
209 warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
210 warning(`sys.exc_type` + ',' + `sys.exc_value`)
212 for line in f.readlines():
216 match = use_preview_re.match(line)
221 # Package order: color should be loaded before preview
222 # Preview options: add the options lyx and tightpage
225 \definecolor{fg}{rgb}{%s}
226 \definecolor{bg}{rgb}{%s}
228 \usepackage[%s,lyx,tightpage]{preview}
230 \g@addto@macro\preview{\begingroup\color{bg}\special{ps::clippath fill}\color{fg}}
231 \g@addto@macro\endpreview{\endgroup}
233 """ % (fg_color_gr, bg_color_gr, match.group(1)))
236 copyfileobj(tmp, open(latex_file,"wb"), 1)
241 def crop_files(pnmcrop, basename):
243 t.append('%s -left' % pnmcrop, '--')
244 t.append('%s -right' % pnmcrop, '--')
246 for file in glob.glob("%s*.ppm" % basename):
248 new = t.open(file, "r")
249 copyfileobj(new, tmp)
251 copyfileobj(tmp, open(file,"wb"), 1)
254 def legacy_conversion(argv, skipMetrics = False):
255 # Parse and manipulate the command line arguments.
259 error(usage(argv[0]))
263 dir, latex_file = os.path.split(argv[1])
267 dpi = string.atoi(argv[2])
269 output_format = argv[3]
274 # External programs used by the script.
275 latex = find_exe_or_terminate(latex or latex_commands)
277 pdf_output = latex in pdflatex_commands
279 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
280 bg_color, latex, pdf_output, skipMetrics)
283 # Add color info to the latex file, since ghostscript doesn't
284 # have the option to set foreground and background colors on
285 # the command line. Run the resulting file through latex.
286 def legacy_conversion_step1(latex_file, dpi, output_format, fg_color, bg_color,
287 latex, pdf_output = False, skipMetrics = False):
289 # Move color information, lyx and tightpage options into the latex file.
290 if not legacy_latex_file(latex_file, fg_color, bg_color):
291 error("""Unable to move the color information, and the lyx and tightpage
292 options of preview-latex, into the latex file""")
294 # Compile the latex file.
295 latex_status, latex_stdout = run_latex(latex, latex_file)
298 return legacy_conversion_step3(latex_file, dpi, output_format, True, skipMetrics)
300 return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
302 # Creates a new LaTeX file from the original with pages specified in
303 # failed_pages, pass it through pdflatex and updates the metrics
304 # from the standard legacy route
305 def legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
306 gs_device, gs_ext, alpha, resolution, output_format):
308 # Search for pdflatex executable
309 pdflatex = find_exe(["pdflatex"])
311 warning("Can't find pdflatex. Some pages failed with all the possible routes.")
313 # Create a new LaTeX file from the original but only with failed pages
314 pdf_latex_file = latex_file_re.sub("_pdflatex.tex", latex_file)
315 filter_pages(latex_file, pdf_latex_file, failed_pages)
318 pdflatex_status, pdflatex_stdout = run_latex(pdflatex, pdf_latex_file)
320 pdf_file = latex_file_re.sub(".pdf", pdf_latex_file)
322 # GhostScript call to produce bitmaps
323 gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
324 '-sOutputFile="%s%%d.%s" ' \
325 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
327 % (gs, gs_device, latex_file_re.sub("", pdf_latex_file), \
328 gs_ext, alpha, alpha, resolution, pdf_file)
329 gs_status, gs_stdout = run_command(gs_call)
332 warning("Some pages failed with all the possible routes")
335 pdf_log_file = latex_file_re.sub(".log", pdf_latex_file)
336 pdf_metrics = legacy_extract_metrics_info(pdf_log_file)
338 original_bitmap = latex_file_re.sub("%d." + output_format, pdf_latex_file)
339 destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
341 # Join the metrics with the those from dvips and rename the bitmap images
342 join_metrics_and_rename(legacy_metrics, pdf_metrics, failed_pages,
343 original_bitmap, destination_bitmap)
346 # The file has been processed through latex and we expect dvi output.
347 # Run dvips, taking note whether it was successful.
348 def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False):
349 # External programs used by the script.
350 dvips = find_exe_or_terminate(["dvips"])
352 # Run the dvi file through dvips.
353 dvi_file = latex_file_re.sub(".dvi", latex_file)
354 ps_file = latex_file_re.sub(".ps", latex_file)
356 dvips_call = '%s -i -o "%s" "%s"' % (dvips, ps_file, dvi_file)
359 dvips_status, dvips_stdout = run_command(dvips_call)
361 warning('Failed: %s %s ... looking for PDF' \
362 % (os.path.basename(dvips), dvi_file))
365 return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics)
368 # Either latex and dvips have been run and we have a ps file, or
369 # pdflatex has been run and we have a pdf file. Proceed with gs.
370 def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics = False):
371 # External programs used by the script.
372 gs = find_exe_or_terminate(["gswin32c", "gswin64c", "gs"])
373 pnmcrop = find_exe(["pnmcrop"])
376 pdf_file = latex_file_re.sub(".pdf", latex_file)
377 ps_file = latex_file_re.sub(".ps", latex_file)
379 # Extract resolution data for gs from the log file.
380 log_file = latex_file_re.sub(".log", latex_file)
381 resolution = extract_resolution(log_file, dpi)
383 # Older versions of gs have problems with a large degree of
384 # anti-aliasing at high resolutions
391 if output_format == "ppm":
395 # Extract the metrics from the log file
396 legacy_metrics = legacy_extract_metrics_info(log_file)
398 # List of pages which failed to produce a correct output
401 # Generate the bitmap images
403 # dvips failed, maybe there's a PDF, try to produce bitmaps
404 gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
405 '-sOutputFile="%s%%d.%s" ' \
406 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
408 % (gs, gs_device, latex_file_re.sub("", latex_file), \
409 gs_ext, alpha, alpha, resolution, pdf_file)
411 gs_status, gs_stdout = run_command(gs_call)
413 error("Failed: %s %s" % (os.path.basename(gs), ps_file))
415 # Model for calling gs on each file
416 gs_call = '%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=%s ' \
417 '-sOutputFile="%s%%d.%s" ' \
418 '-dGraphicsAlphaBit=%d -dTextAlphaBits=%d ' \
420 % (gs, gs_device, latex_file_re.sub("", latex_file), \
421 gs_ext, alpha, alpha, resolution)
424 # Collect all the PostScript files (like *.001, *.002, ...)
425 ps_files = glob.glob("%s.[0-9][0-9][0-9]" % latex_file_re.sub("", latex_file))
428 # Call GhostScript for each file
429 for file in ps_files:
431 progress("Processing page %s, file %s" % (i, file))
432 gs_status, gs_stdout = run_command(gs_call % (i, file))
434 # gs failed, keep track of this
435 warning("Ghostscript failed on page %s, file %s" % (i, file))
436 failed_pages.append(i)
438 # Pass failed pages to pdflatex
439 if len(failed_pages) > 0:
440 legacy_conversion_pdflatex(latex_file, failed_pages, legacy_metrics, gs,
441 gs_device, gs_ext, alpha, resolution, output_format)
445 crop_files(pnmcrop, latex_file_re.sub("", latex_file))
447 # Allow to skip .metrics creation for custom management
448 # (see the dvipng method)
450 # Extract metrics info from the log file.
451 metrics_file = latex_file_re.sub(".metrics", latex_file)
452 write_metrics_info(legacy_metrics, metrics_file)
454 return (0, legacy_metrics)
457 if __name__ == "__main__":
458 sys.exit(legacy_conversion(sys.argv)[0])