2004-08-09 11:31:18 +00:00
|
|
|
# file lyxpreview_tools.py
|
|
|
|
# This file is part of LyX, the document processor.
|
|
|
|
# Licence details can be found in the file COPYING.
|
|
|
|
|
|
|
|
# author Angus Leeming
|
|
|
|
# Full author contact details are available in file CREDITS
|
|
|
|
|
|
|
|
# and with much help testing the code under Windows from
|
|
|
|
# Paul A. Rubin, rubin@msu.edu.
|
|
|
|
|
|
|
|
# A repository of the following functions, used by the lyxpreview2xyz scripts.
|
2017-05-12 09:01:48 +00:00
|
|
|
# copyfileobj, error, find_exe, find_exe_or_terminate, make_texcolor,
|
2011-10-03 16:35:27 +00:00
|
|
|
# progress, run_command, run_latex, warning
|
2004-08-09 11:31:18 +00:00
|
|
|
|
2011-09-11 18:23:29 +00:00
|
|
|
# Requires python 2.4 or later (subprocess module).
|
2004-08-09 11:31:18 +00:00
|
|
|
|
2017-05-09 10:20:34 +00:00
|
|
|
import os, re, subprocess, sys, tempfile
|
2011-09-11 18:23:29 +00:00
|
|
|
|
|
|
|
|
|
|
|
# Control the output to stdout
|
|
|
|
debug = False
|
|
|
|
verbose = False
|
2011-09-11 18:22:29 +00:00
|
|
|
|
2011-10-03 16:35:27 +00:00
|
|
|
# Known flavors of latex and bibtex
|
|
|
|
bibtex_commands = ("bibtex", "bibtex8", "biber")
|
2011-09-11 18:22:29 +00:00
|
|
|
latex_commands = ("latex", "pplatex", "platex", "latex2e")
|
|
|
|
pdflatex_commands = ("pdflatex", "xelatex", "lualatex")
|
|
|
|
|
|
|
|
# Pre-compiled regular expressions
|
|
|
|
latex_file_re = re.compile(r"\.tex$")
|
|
|
|
|
|
|
|
# PATH and PATHEXT environment variables
|
|
|
|
path = os.environ["PATH"].split(os.pathsep)
|
|
|
|
extlist = ['']
|
|
|
|
if "PATHEXT" in os.environ:
|
|
|
|
extlist += os.environ["PATHEXT"].split(os.pathsep)
|
2012-06-27 11:41:19 +00:00
|
|
|
extlist.append('.py')
|
2011-09-11 18:22:29 +00:00
|
|
|
|
2004-08-09 11:31:18 +00:00
|
|
|
use_win32_modules = 0
|
|
|
|
if os.name == "nt":
|
|
|
|
use_win32_modules = 1
|
|
|
|
try:
|
|
|
|
import pywintypes
|
|
|
|
import win32con
|
|
|
|
import win32event
|
|
|
|
import win32file
|
|
|
|
import win32pipe
|
|
|
|
import win32process
|
|
|
|
import win32security
|
|
|
|
import winerror
|
|
|
|
except:
|
2011-09-11 18:22:12 +00:00
|
|
|
sys.stderr.write("Consider installing the PyWin extension modules " \
|
2004-08-09 11:31:18 +00:00
|
|
|
"if you're irritated by windows appearing briefly.\n")
|
|
|
|
use_win32_modules = 0
|
|
|
|
|
|
|
|
|
2011-09-11 18:23:29 +00:00
|
|
|
def progress(message):
|
|
|
|
global verbose
|
|
|
|
if verbose:
|
|
|
|
sys.stdout.write("Progress: %s\n" % message)
|
|
|
|
|
|
|
|
|
2004-08-09 11:31:18 +00:00
|
|
|
def warning(message):
|
2011-09-11 18:23:29 +00:00
|
|
|
sys.stderr.write("Warning: %s\n" % message)
|
2004-08-09 11:31:18 +00:00
|
|
|
|
|
|
|
|
|
|
|
def error(message):
|
2011-09-11 18:23:29 +00:00
|
|
|
sys.stderr.write("Error: %s\n" % message)
|
2004-08-09 11:31:18 +00:00
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
|
2008-07-02 14:42:04 +00:00
|
|
|
def make_texcolor(hexcolor, graphics):
|
|
|
|
# Test that the input string contains 6 hexadecimal chars.
|
2017-05-11 14:50:08 +00:00
|
|
|
hexcolor_re = re.compile(b"^[0-9a-fA-F]{6}$")
|
2008-07-02 14:42:04 +00:00
|
|
|
if not hexcolor_re.match(hexcolor):
|
|
|
|
error("Cannot convert color '%s'" % hexcolor)
|
|
|
|
|
2017-05-09 10:20:34 +00:00
|
|
|
red = float(int(hexcolor[0:2], 16)) / 255.0
|
|
|
|
green = float(int(hexcolor[2:4], 16)) / 255.0
|
|
|
|
blue = float(int(hexcolor[4:6], 16)) / 255.0
|
2008-07-02 14:42:04 +00:00
|
|
|
|
|
|
|
if graphics:
|
2017-05-11 14:50:08 +00:00
|
|
|
return b"%f,%f,%f" % (red, green, blue)
|
2008-07-02 14:42:04 +00:00
|
|
|
else:
|
2017-05-11 14:50:08 +00:00
|
|
|
return b"rgb %f %f %f" % (red, green, blue)
|
2008-07-02 14:42:04 +00:00
|
|
|
|
|
|
|
|
2011-09-11 18:22:29 +00:00
|
|
|
def find_exe(candidates):
|
|
|
|
global extlist, path
|
2010-11-28 01:22:36 +00:00
|
|
|
|
2011-10-03 16:35:25 +00:00
|
|
|
for command in candidates:
|
|
|
|
prog = command.split()[0]
|
2004-08-09 11:31:18 +00:00
|
|
|
for directory in path:
|
2010-11-28 01:22:36 +00:00
|
|
|
for ext in extlist:
|
|
|
|
full_path = os.path.join(directory, prog + ext)
|
|
|
|
if os.access(full_path, os.X_OK):
|
|
|
|
# The thing is in the PATH already (or we wouldn't
|
|
|
|
# have found it). Return just the basename to avoid
|
|
|
|
# problems when the path to the executable contains
|
|
|
|
# spaces.
|
2012-06-27 11:41:19 +00:00
|
|
|
if full_path.lower().endswith('.py'):
|
|
|
|
return command.replace(prog, '"%s" "%s"'
|
|
|
|
% (sys.executable, full_path))
|
2011-10-03 16:35:25 +00:00
|
|
|
return command
|
2004-08-09 11:31:18 +00:00
|
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2011-09-11 18:22:29 +00:00
|
|
|
def find_exe_or_terminate(candidates):
|
|
|
|
exe = find_exe(candidates)
|
2004-08-09 11:31:18 +00:00
|
|
|
if exe == None:
|
2017-05-09 10:20:34 +00:00
|
|
|
error("Unable to find executable from '%s'" % " ".join(candidates))
|
2004-08-09 11:31:18 +00:00
|
|
|
|
|
|
|
return exe
|
|
|
|
|
|
|
|
|
2013-04-12 19:35:50 +00:00
|
|
|
def run_command_popen(cmd, stderr2stdout):
|
2011-09-24 01:27:40 +00:00
|
|
|
if os.name == 'nt':
|
|
|
|
unix = False
|
|
|
|
else:
|
|
|
|
unix = True
|
2013-04-12 19:35:50 +00:00
|
|
|
if stderr2stdout:
|
|
|
|
pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
|
|
|
|
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
|
|
|
|
cmd_stdout = pipe.communicate()[0]
|
|
|
|
else:
|
|
|
|
pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
|
|
|
|
stdout=subprocess.PIPE, universal_newlines=True)
|
|
|
|
(cmd_stdout, cmd_stderr) = pipe.communicate()
|
|
|
|
if cmd_stderr:
|
|
|
|
sys.stderr.write(cmd_stderr)
|
2011-09-11 18:23:29 +00:00
|
|
|
cmd_status = pipe.returncode
|
|
|
|
|
|
|
|
global debug
|
|
|
|
if debug:
|
|
|
|
sys.stdout.write(cmd_stdout)
|
2004-08-09 11:31:18 +00:00
|
|
|
return cmd_status, cmd_stdout
|
|
|
|
|
|
|
|
|
|
|
|
def run_command_win32(cmd):
|
|
|
|
sa = win32security.SECURITY_ATTRIBUTES()
|
|
|
|
sa.bInheritHandle = True
|
|
|
|
stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
|
|
|
|
|
|
|
|
si = win32process.STARTUPINFO()
|
|
|
|
si.dwFlags = (win32process.STARTF_USESTDHANDLES
|
|
|
|
| win32process.STARTF_USESHOWWINDOW)
|
|
|
|
si.wShowWindow = win32con.SW_HIDE
|
|
|
|
si.hStdOutput = stdout_w
|
|
|
|
|
|
|
|
process, thread, pid, tid = \
|
|
|
|
win32process.CreateProcess(None, cmd, None, None, True,
|
|
|
|
0, None, None, si)
|
|
|
|
if process == None:
|
|
|
|
return -1, ""
|
|
|
|
|
|
|
|
# Must close the write handle in this process, or ReadFile will hang.
|
|
|
|
stdout_w.Close()
|
|
|
|
|
|
|
|
# Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
|
|
|
|
# which is okay because it happens when child process ends).
|
|
|
|
data = ""
|
|
|
|
error = 0
|
|
|
|
while 1:
|
|
|
|
try:
|
|
|
|
hr, buffer = win32file.ReadFile(stdout_r, 4096)
|
|
|
|
if hr != winerror.ERROR_IO_PENDING:
|
2024-02-16 13:17:17 +00:00
|
|
|
data = data + str(buffer)
|
2004-08-09 11:31:18 +00:00
|
|
|
|
2016-06-08 18:02:33 +00:00
|
|
|
except pywintypes.error as e:
|
2004-08-09 11:31:18 +00:00
|
|
|
if e.args[0] != winerror.ERROR_BROKEN_PIPE:
|
|
|
|
error = 1
|
|
|
|
break
|
|
|
|
|
|
|
|
if error:
|
|
|
|
return -2, ""
|
|
|
|
|
|
|
|
# Everything is okay --- the called process has closed the pipe.
|
|
|
|
# For safety, check that the process ended, then pick up its exit code.
|
|
|
|
win32event.WaitForSingleObject(process, win32event.INFINITE)
|
|
|
|
if win32process.GetExitCodeProcess(process):
|
|
|
|
return -3, ""
|
|
|
|
|
2011-09-11 18:23:29 +00:00
|
|
|
global debug
|
|
|
|
if debug:
|
|
|
|
sys.stdout.write(data)
|
|
|
|
return 0, data
|
2004-08-09 11:31:18 +00:00
|
|
|
|
|
|
|
|
2013-04-12 19:35:50 +00:00
|
|
|
def run_command(cmd, stderr2stdout = True):
|
2011-09-11 18:23:29 +00:00
|
|
|
progress("Running %s" % cmd)
|
2004-08-09 11:31:18 +00:00
|
|
|
if use_win32_modules:
|
|
|
|
return run_command_win32(cmd)
|
|
|
|
else:
|
2013-04-12 19:35:50 +00:00
|
|
|
return run_command_popen(cmd, stderr2stdout)
|
2004-08-09 11:31:18 +00:00
|
|
|
|
|
|
|
|
|
|
|
def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
|
|
|
|
"""copy data from file-like object fsrc to file-like object fdst"""
|
|
|
|
if rewind:
|
|
|
|
fsrc.flush()
|
|
|
|
fsrc.seek(0)
|
|
|
|
|
|
|
|
while 1:
|
|
|
|
buf = fsrc.read(length)
|
|
|
|
if not buf:
|
|
|
|
break
|
|
|
|
fdst.write(buf)
|
|
|
|
|
|
|
|
|
2011-01-20 23:39:08 +00:00
|
|
|
def write_metrics_info(metrics_info, metrics_file):
|
|
|
|
metrics = open(metrics_file, 'w')
|
|
|
|
for metric in metrics_info:
|
|
|
|
metrics.write("Snippet %s %f\n" % metric)
|
|
|
|
metrics.close()
|
2011-04-04 14:33:45 +00:00
|
|
|
|
2017-05-12 09:01:48 +00:00
|
|
|
|
2011-04-04 14:33:45 +00:00
|
|
|
# Reads a .tex files and create an identical file but only with
|
|
|
|
# pages whose index is in pages_to_keep
|
|
|
|
def filter_pages(source_path, destination_path, pages_to_keep):
|
2020-02-15 18:27:45 +00:00
|
|
|
def_re = re.compile(b"(\\\\newcommandx|\\\\renewcommandx|\\\\global\\\\long\\\\def)(\\[a-zA-Z]+)(.+)")
|
2019-09-04 20:18:03 +00:00
|
|
|
source_file = open(source_path, "rb")
|
|
|
|
destination_file = open(destination_path, "wb")
|
2011-04-04 14:33:45 +00:00
|
|
|
|
|
|
|
page_index = 0
|
|
|
|
skip_page = False
|
2015-06-20 14:37:12 +00:00
|
|
|
macros = []
|
2011-04-04 14:33:45 +00:00
|
|
|
for line in source_file:
|
|
|
|
# We found a new page
|
2019-09-04 20:18:03 +00:00
|
|
|
if line.startswith(b"\\begin{preview}"):
|
2011-04-04 14:33:45 +00:00
|
|
|
page_index += 1
|
|
|
|
# If the page index isn't in pages_to_keep we don't copy it
|
|
|
|
skip_page = page_index not in pages_to_keep
|
|
|
|
|
|
|
|
if not skip_page:
|
2015-06-20 14:37:12 +00:00
|
|
|
match = def_re.match(line)
|
|
|
|
if match != None:
|
|
|
|
definecmd = match.group(1)
|
|
|
|
macroname = match.group(2)
|
|
|
|
if not macroname in macros:
|
|
|
|
macros.append(macroname)
|
2019-09-04 20:18:03 +00:00
|
|
|
if definecmd == b"\\renewcommandx":
|
|
|
|
line = line.replace(definecmd, b"\\newcommandx")
|
2011-04-04 14:33:45 +00:00
|
|
|
destination_file.write(line)
|
|
|
|
|
|
|
|
# End of a page, we reset the skip_page bool
|
2019-09-04 20:18:03 +00:00
|
|
|
if line.startswith(b"\\end{preview}"):
|
2011-04-04 14:33:45 +00:00
|
|
|
skip_page = False
|
|
|
|
|
|
|
|
destination_file.close()
|
|
|
|
source_file.close()
|
2011-09-11 18:22:12 +00:00
|
|
|
|
2011-04-04 14:33:45 +00:00
|
|
|
# Joins two metrics list, that is a list of tuple (page_index, metric)
|
|
|
|
# new_page_indexes contains the original page number of the pages in new_metrics
|
|
|
|
# e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting
|
|
|
|
# original_bitmap and destination_bitmap are file name models used to rename the new files
|
|
|
|
# e.g. image_new%d.png and image_%d.png
|
|
|
|
def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap):
|
|
|
|
legacy_index = 0
|
|
|
|
for (index, metric) in new_metrics:
|
|
|
|
# If the file exists we rename it
|
|
|
|
if os.path.isfile(original_bitmap % (index)):
|
|
|
|
os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1])
|
|
|
|
|
|
|
|
# Extract the original page index
|
|
|
|
index = new_page_indexes[index-1]
|
|
|
|
# Goes through the array until the end is reached or the correct index is found
|
|
|
|
while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index:
|
|
|
|
legacy_index += 1
|
2011-09-11 18:22:12 +00:00
|
|
|
|
2011-04-04 14:33:45 +00:00
|
|
|
# Add or update the metric for this page
|
|
|
|
if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index:
|
|
|
|
original_metrics[legacy_index] = (index, metric)
|
|
|
|
else:
|
|
|
|
original_metrics.insert(legacy_index, (index, metric))
|
2011-10-03 16:35:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
def run_latex(latex, latex_file, bibtex = None):
|
|
|
|
# Run latex
|
|
|
|
latex_status, latex_stdout = run_tex(latex, latex_file)
|
|
|
|
|
|
|
|
if bibtex is None:
|
|
|
|
return latex_status, latex_stdout
|
|
|
|
|
|
|
|
# The aux and log output file names
|
|
|
|
aux_file = latex_file_re.sub(".aux", latex_file)
|
|
|
|
log_file = latex_file_re.sub(".log", latex_file)
|
|
|
|
|
|
|
|
# Run bibtex/latex if necessary
|
|
|
|
progress("Checking if a bibtex run is necessary")
|
|
|
|
if string_in_file(r"\bibdata", aux_file):
|
|
|
|
bibtex_status, bibtex_stdout = run_tex(bibtex, aux_file)
|
|
|
|
latex_status, latex_stdout = run_tex(latex, latex_file)
|
|
|
|
# Rerun latex if necessary
|
|
|
|
progress("Checking if a latex rerun is necessary")
|
2022-12-10 10:31:51 +00:00
|
|
|
if string_in_file("Warning: (Citation|Reference)", log_file):
|
2011-10-03 16:35:27 +00:00
|
|
|
latex_status, latex_stdout = run_tex(latex, latex_file)
|
|
|
|
|
|
|
|
return latex_status, latex_stdout
|
|
|
|
|
|
|
|
|
|
|
|
def run_tex(tex, tex_file):
|
2024-06-10 10:29:56 +00:00
|
|
|
tex_call = f'{tex} "{tex_file}"'
|
2011-10-03 16:35:27 +00:00
|
|
|
|
|
|
|
tex_status, tex_stdout = run_command(tex_call)
|
|
|
|
if tex_status:
|
2015-06-03 15:52:30 +00:00
|
|
|
progress("Warning: %s had problems compiling %s" \
|
2011-10-03 16:35:27 +00:00
|
|
|
% (os.path.basename(tex), tex_file))
|
|
|
|
return tex_status, tex_stdout
|
|
|
|
|
|
|
|
|
|
|
|
def string_in_file(string, infile):
|
|
|
|
if not os.path.isfile(infile):
|
|
|
|
return False
|
2022-12-10 10:31:51 +00:00
|
|
|
string_re = re.compile(string.encode())
|
2020-03-14 16:03:16 +00:00
|
|
|
f = open(infile, 'rb')
|
2011-10-03 16:35:27 +00:00
|
|
|
for line in f.readlines():
|
2022-12-10 10:31:51 +00:00
|
|
|
if string_re.search(line):
|
2011-10-03 16:35:27 +00:00
|
|
|
f.close()
|
|
|
|
return True
|
|
|
|
f.close()
|
|
|
|
return False
|
2015-04-29 22:35:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
# Returns a list of indexes of pages giving errors extracted from the latex log
|
|
|
|
def check_latex_log(log_file):
|
|
|
|
|
2020-03-14 16:03:16 +00:00
|
|
|
error_re = re.compile(b"^! ")
|
|
|
|
snippet_re = re.compile(b"^Preview: Snippet ")
|
|
|
|
data_re = re.compile(b"([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)")
|
2015-04-29 22:35:28 +00:00
|
|
|
|
|
|
|
found_error = False
|
|
|
|
error_pages = []
|
|
|
|
|
|
|
|
try:
|
2020-03-14 16:03:16 +00:00
|
|
|
for line in open(log_file, 'rb').readlines():
|
2015-04-29 22:35:28 +00:00
|
|
|
if not found_error:
|
|
|
|
match = error_re.match(line)
|
|
|
|
if match != None:
|
|
|
|
found_error = True
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
match = snippet_re.match(line)
|
|
|
|
if match == None:
|
|
|
|
continue
|
|
|
|
|
|
|
|
found_error = False
|
|
|
|
match = data_re.search(line)
|
|
|
|
if match == None:
|
2024-06-10 10:29:56 +00:00
|
|
|
error(f"Unexpected data in {log_file}\n{line}")
|
2015-04-29 22:35:28 +00:00
|
|
|
|
|
|
|
error_pages.append(int(match.group(1)))
|
|
|
|
|
|
|
|
except:
|
|
|
|
warning('check_latex_log: Unable to open "%s"' % log_file)
|
2016-06-08 18:02:33 +00:00
|
|
|
warning(repr(sys.exc_info()[0]) + ',' + repr(sys.exc_info()[1]))
|
2015-04-29 22:35:28 +00:00
|
|
|
|
|
|
|
return error_pages
|