-#! /usr/bin/env python
# -*- coding: utf-8 -*-
# file legacy_lyxpreview2ppm.py
# the images correctly on the screen.
# The script uses several external programs and files:
+# * python 2.4 or later (subprocess module);
# * A latex executable;
# * preview.sty;
# * dvips;
# What does this script do?
# [legacy_conversion]
+# 0) Process command-line arguments
+# [legacy_conversion_step1]
# 1) Call latex to create a DVI file from LaTeX
# [legacy_conversion_step2]
# 2) Call dvips to create one PS file for each DVI page
+# [legacy_conversion_step3]
# 3) If dvips fails look for PDF and call gs to produce bitmaps
# 4) Otherwise call gs on each PostScript file to produce bitmaps
# [legacy_conversion_pdflatex]
import glob, os, pipes, re, string, sys
-from lyxpreview_tools import copyfileobj, error, find_exe, \
- find_exe_or_terminate, make_texcolor, mkstemp, run_command, warning, \
- write_metrics_info, filter_pages, join_metrics_and_rename
+from lyxpreview_tools import copyfileobj, error, filter_pages, find_exe, \
+ find_exe_or_terminate, join_metrics_and_rename, latex_commands, \
+ latex_file_re, make_texcolor, mkstemp, pdflatex_commands, progress, \
+ run_command, run_latex, warning, write_metrics_info
-# Pre-compiled regular expression.
-latex_file_re = re.compile("\.tex$")
-
-# PATH environment variable
-path = string.split(os.environ["PATH"], os.pathsep)
def usage(prog_name):
return "Usage: %s <latex file> <dpi> ppm <fg color> <bg color>\n" \
return dpi * (10.0 / fontsize) * (1000.0 / magnification)
-def legacy_latex_file(latex_file, fg_color, bg_color, bg_color_gr):
- use_preview_dvi_re = re.compile("(\s*\\\\usepackage\[[^]]+)(dvips\]{preview})")
- use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)(pdftex\]{preview})")
+def legacy_latex_file(latex_file, fg_color, bg_color):
+ use_preview_re = re.compile(r"\s*\\usepackage\[([^]]+)\]{preview}")
+ fg_color_gr = make_texcolor(fg_color, True)
+ bg_color_gr = make_texcolor(bg_color, True)
tmp = mkstemp()
success = 0
try:
- for line in open(latex_file, 'r').readlines():
- match = use_preview_dvi_re.match(line)
- if match == None:
- match = use_preview_pdf_re.match(line)
- if match == None:
- tmp.write(line)
- continue
- success = 1
- tmp.write(" \\usepackage{color}\n" \
- " \\pagecolor[rgb]{%s}\n" \
- "%s\n" \
- % (bg_color_gr, match.group()))
- continue
-
- success = 1
- tmp.write("%stightpage,%s\n" \
- " \\AtBeginDocument{\\AtBeginDvi{%%\n" \
- " \\special{!userdict begin/bop-hook{//bop-hook exec\n" \
- " <%s%s>{255 div}forall setrgbcolor\n" \
- " clippath fill setrgbcolor}bind def end}}}\n" \
- % (match.group(1), match.group(2), fg_color, bg_color))
-
+ f = open(latex_file, 'r')
except:
# Unable to open the file, but do nothing here because
# the calling function will act on the value of 'success'.
warning('Warning in legacy_latex_file! Unable to open "%s"' % latex_file)
warning(`sys.exc_type` + ',' + `sys.exc_value`)
+ for line in f.readlines():
+ if success:
+ tmp.write(line)
+ continue
+ match = use_preview_re.match(line)
+ if match == None:
+ tmp.write(line)
+ continue
+ success = 1
+ # Package order: color should be loaded before preview
+ # Preview options: add the options lyx and tightpage
+ tmp.write(r"""
+\usepackage{color}
+\definecolor{fg}{rgb}{%s}
+\definecolor{bg}{rgb}{%s}
+\pagecolor{bg}
+\usepackage[%s,lyx,tightpage]{preview}
+\makeatletter
+\g@addto@macro\preview{\begingroup\color{bg}\special{ps::clippath fill}\color{fg}}
+\g@addto@macro\endpreview{\endgroup}
+\makeatother
+""" % (fg_color_gr, bg_color_gr, match.group(1)))
+
if success:
copyfileobj(tmp, open(latex_file,"wb"), 1)
def legacy_conversion(argv, skipMetrics = False):
- latex_commands = ["latex", "pplatex", "platex", "latex2e"]
# Parse and manipulate the command line arguments.
if len(argv) == 7:
- latex_commands = [argv[6]]
+ latex = [argv[6]]
elif len(argv) != 6:
error(usage(argv[0]))
+ else:
+ latex = None
dir, latex_file = os.path.split(argv[1])
if len(dir) != 0:
fg_color = argv[4]
bg_color = argv[5]
- bg_color_gr = make_texcolor(argv[5], True)
# External programs used by the script.
- latex = find_exe_or_terminate(latex_commands, path)
+ latex = find_exe_or_terminate(latex or latex_commands)
- # Move color information into the latex file.
- if not legacy_latex_file(latex_file, fg_color, bg_color, bg_color_gr):
- error("Unable to move color info into the latex file")
+ pdf_output = latex in pdflatex_commands
+
+ return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
+ bg_color, latex, pdf_output, skipMetrics)
- # Compile the latex file.
- latex_call = '%s "%s"' % (latex, latex_file)
- latex_status, latex_stdout = run_command(latex_call)
- if latex_status != None:
- warning("%s had problems compiling %s" \
- % (os.path.basename(latex), latex_file))
+# Add color info to the latex file, since ghostscript doesn't
+# have the option to set foreground and background colors on
+# the command line. Run the resulting file through latex.
+def legacy_conversion_step1(latex_file, dpi, output_format, fg_color, bg_color,
+ latex, pdf_output = False, skipMetrics = False):
- return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
+ # Move color information, lyx and tightpage options into the latex file.
+ if not legacy_latex_file(latex_file, fg_color, bg_color):
+ error("""Unable to move the color information, and the lyx and tightpage
+ options of preview-latex, into the latex file""")
+
+ # Compile the latex file.
+ latex_status, latex_stdout = run_latex(latex, latex_file)
+
+ if pdf_output:
+ return legacy_conversion_step3(latex_file, dpi, output_format, True, skipMetrics)
+ else:
+ return legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics)
# Creates a new LaTeX file from the original with pages specified in
# failed_pages, pass it through pdflatex and updates the metrics
gs_device, gs_ext, alpha, resolution, output_format):
# Search for pdflatex executable
- pdflatex = find_exe(["pdflatex"], path)
+ pdflatex = find_exe(["pdflatex"])
if pdflatex == None:
warning("Can't find pdflatex. Some pages failed with all the possible routes.")
else:
filter_pages(latex_file, pdf_latex_file, failed_pages)
# pdflatex call
- pdflatex_call = '%s "%s"' % (pdflatex, pdf_latex_file)
- pdflatex_status, pdflatex_stdout = run_command(pdflatex_call)
+ pdflatex_status, pdflatex_stdout = run_latex(pdflatex, pdf_latex_file)
pdf_file = latex_file_re.sub(".pdf", pdf_latex_file)
% (gs, gs_device, latex_file_re.sub("", pdf_latex_file), \
gs_ext, alpha, alpha, resolution, pdf_file)
gs_status, gs_stdout = run_command(gs_call)
- if gs_status != None:
+ if gs_status:
# Give up!
warning("Some pages failed with all the possible routes")
else:
original_bitmap, destination_bitmap)
+# The file has been processed through latex and we expect dvi output.
+# Run dvips, taking note whether it was successful.
def legacy_conversion_step2(latex_file, dpi, output_format, skipMetrics = False):
# External programs used by the script.
- dvips = find_exe_or_terminate(["dvips"], path)
- gs = find_exe_or_terminate(["gswin32c", "gs"], path)
- pnmcrop = find_exe(["pnmcrop"], path)
+ dvips = find_exe_or_terminate(["dvips"])
# Run the dvi file through dvips.
dvi_file = latex_file_re.sub(".dvi", latex_file)
ps_file = latex_file_re.sub(".ps", latex_file)
- pdf_file = latex_file_re.sub(".pdf", latex_file)
dvips_call = '%s -i -o "%s" "%s"' % (dvips, ps_file, dvi_file)
dvips_failed = False
dvips_status, dvips_stdout = run_command(dvips_call)
- if dvips_status != None:
+ if dvips_status:
warning('Failed: %s %s ... looking for PDF' \
% (os.path.basename(dvips), dvi_file))
dvips_failed = True
+ return legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics)
+
+
+# Either latex and dvips have been run and we have a ps file, or
+# pdflatex has been run and we have a pdf file. Proceed with gs.
+def legacy_conversion_step3(latex_file, dpi, output_format, dvips_failed, skipMetrics = False):
+ # External programs used by the script.
+ gs = find_exe_or_terminate(["gswin32c", "gswin64c", "gs"])
+ pnmcrop = find_exe(["pnmcrop"])
+
+ # Files to process
+ pdf_file = latex_file_re.sub(".pdf", latex_file)
+ ps_file = latex_file_re.sub(".ps", latex_file)
+
# Extract resolution data for gs from the log file.
log_file = latex_file_re.sub(".log", latex_file)
resolution = extract_resolution(log_file, dpi)
gs_ext, alpha, alpha, resolution, pdf_file)
gs_status, gs_stdout = run_command(gs_call)
- if gs_status != None:
+ if gs_status:
error("Failed: %s %s" % (os.path.basename(gs), ps_file))
else:
# Model for calling gs on each file
# Call GhostScript for each file
for file in ps_files:
i = i + 1
+ progress("Processing page %s, file %s" % (i, file))
gs_status, gs_stdout = run_command(gs_call % (i, file))
- if gs_status != None:
+ if gs_status:
# gs failed, keep track of this
+ warning("Ghostscript failed on page %s, file %s" % (i, file))
failed_pages.append(i)
# Pass failed pages to pdflatex
if __name__ == "__main__":
- exit(legacy_conversion(sys.argv)[0])
+ sys.exit(legacy_conversion(sys.argv)[0])