3 # file lyxpreview_tools.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 # and with much help testing the code under Windows from
11 # Paul A. Rubin, rubin@msu.edu.
13 # A repository of the following functions, used by the lyxpreview2xyz scripts.
14 # copyfileobj, error, find_exe, find_exe_or_terminate, make_texcolor, mkstemp,
15 # progress, run_command, run_latex, warning
17 # Requires python 2.4 or later (subprocess module).
19 import os, re, string, subprocess, sys, tempfile
22 # Control the output to stdout
26 # Known flavors of latex and bibtex
27 bibtex_commands = ("bibtex", "bibtex8", "biber")
28 latex_commands = ("latex", "pplatex", "platex", "latex2e")
29 pdflatex_commands = ("pdflatex", "xelatex", "lualatex")
31 # Pre-compiled regular expressions
32 latex_file_re = re.compile(r"\.tex$")
34 # PATH and PATHEXT environment variables
35 path = os.environ["PATH"].split(os.pathsep)
37 if "PATHEXT" in os.environ:
38 extlist += os.environ["PATHEXT"].split(os.pathsep)
54 sys.stderr.write("Consider installing the PyWin extension modules " \
55 "if you're irritated by windows appearing briefly.\n")
59 def progress(message):
62 sys.stdout.write("Progress: %s\n" % message)
66 sys.stderr.write("Warning: %s\n" % message)
70 sys.stderr.write("Error: %s\n" % message)
74 def make_texcolor(hexcolor, graphics):
75 # Test that the input string contains 6 hexadecimal chars.
76 hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
77 if not hexcolor_re.match(hexcolor):
78 error("Cannot convert color '%s'" % hexcolor)
80 red = float(string.atoi(hexcolor[0:2], 16)) / 255.0
81 green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
82 blue = float(string.atoi(hexcolor[4:6], 16)) / 255.0
85 return "%f,%f,%f" % (red, green, blue)
87 return "rgb %f %f %f" % (red, green, blue)
90 def find_exe(candidates):
93 for command in candidates:
94 prog = command.split()[0]
95 for directory in path:
97 full_path = os.path.join(directory, prog + ext)
98 if os.access(full_path, os.X_OK):
99 # The thing is in the PATH already (or we wouldn't
100 # have found it). Return just the basename to avoid
101 # problems when the path to the executable contains
103 if full_path.lower().endswith('.py'):
104 return command.replace(prog, '"%s" "%s"'
105 % (sys.executable, full_path))
111 def find_exe_or_terminate(candidates):
112 exe = find_exe(candidates)
114 error("Unable to find executable from '%s'" % string.join(candidates))
119 def run_command_popen(cmd):
124 pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
125 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
126 cmd_stdout = pipe.communicate()[0]
127 cmd_status = pipe.returncode
131 sys.stdout.write(cmd_stdout)
132 return cmd_status, cmd_stdout
135 def run_command_win32(cmd):
136 sa = win32security.SECURITY_ATTRIBUTES()
137 sa.bInheritHandle = True
138 stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
140 si = win32process.STARTUPINFO()
141 si.dwFlags = (win32process.STARTF_USESTDHANDLES
142 | win32process.STARTF_USESHOWWINDOW)
143 si.wShowWindow = win32con.SW_HIDE
144 si.hStdOutput = stdout_w
146 process, thread, pid, tid = \
147 win32process.CreateProcess(None, cmd, None, None, True,
152 # Must close the write handle in this process, or ReadFile will hang.
155 # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
156 # which is okay because it happens when child process ends).
161 hr, buffer = win32file.ReadFile(stdout_r, 4096)
162 if hr != winerror.ERROR_IO_PENDING:
165 except pywintypes.error, e:
166 if e.args[0] != winerror.ERROR_BROKEN_PIPE:
173 # Everything is okay --- the called process has closed the pipe.
174 # For safety, check that the process ended, then pick up its exit code.
175 win32event.WaitForSingleObject(process, win32event.INFINITE)
176 if win32process.GetExitCodeProcess(process):
181 sys.stdout.write(data)
185 def run_command(cmd):
186 progress("Running %s" % cmd)
187 if use_win32_modules:
188 return run_command_win32(cmd)
190 return run_command_popen(cmd)
193 def get_version_info():
194 version_re = re.compile("([0-9])\.([0-9])")
196 match = version_re.match(sys.version)
198 error("Unable to extract version info from 'sys.version'")
200 return string.atoi(match.group(1)), string.atoi(match.group(2))
203 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
204 """copy data from file-like object fsrc to file-like object fdst"""
210 buf = fsrc.read(length)
217 """clone of tempfile.TemporaryFile to use with python < 2.0."""
218 # Cache the unlinker so we don't get spurious errors at shutdown
219 # when the module-level "os" is None'd out. Note that this must
220 # be referenced as self.unlink, because the name TempFile
221 # may also get None'd out before __del__ is called.
225 self.filename = tempfile.mktemp()
226 self.file = open(self.filename,"w+b")
227 self.close_called = 0
230 if not self.close_called:
231 self.close_called = 1
233 self.unlink(self.filename)
238 def read(self, size = -1):
239 return self.file.read(size)
241 def write(self, line):
242 return self.file.write(line)
244 def seek(self, offset):
245 return self.file.seek(offset)
248 return self.file.flush()
252 """create a secure temporary file and return its object-like file"""
253 major, minor = get_version_info()
255 if major >= 2 and minor >= 0:
256 return tempfile.TemporaryFile()
260 def write_metrics_info(metrics_info, metrics_file):
261 metrics = open(metrics_file, 'w')
262 for metric in metrics_info:
263 metrics.write("Snippet %s %f\n" % metric)
266 # Reads a .tex files and create an identical file but only with
267 # pages whose index is in pages_to_keep
268 def filter_pages(source_path, destination_path, pages_to_keep):
269 source_file = open(source_path, "r")
270 destination_file = open(destination_path, "w")
274 for line in source_file:
275 # We found a new page
276 if line.startswith("\\begin{preview}"):
278 # If the page index isn't in pages_to_keep we don't copy it
279 skip_page = page_index not in pages_to_keep
282 destination_file.write(line)
284 # End of a page, we reset the skip_page bool
285 if line.startswith("\\end{preview}"):
288 destination_file.close()
291 # Joins two metrics list, that is a list of tuple (page_index, metric)
292 # new_page_indexes contains the original page number of the pages in new_metrics
293 # e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting
294 # original_bitmap and destination_bitmap are file name models used to rename the new files
295 # e.g. image_new%d.png and image_%d.png
296 def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap):
298 for (index, metric) in new_metrics:
299 # If the file exists we rename it
300 if os.path.isfile(original_bitmap % (index)):
301 os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1])
303 # Extract the original page index
304 index = new_page_indexes[index-1]
305 # Goes through the array until the end is reached or the correct index is found
306 while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index:
309 # Add or update the metric for this page
310 if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index:
311 original_metrics[legacy_index] = (index, metric)
313 original_metrics.insert(legacy_index, (index, metric))
316 def run_latex(latex, latex_file, bibtex = None):
318 latex_status, latex_stdout = run_tex(latex, latex_file)
321 return latex_status, latex_stdout
323 # The aux and log output file names
324 aux_file = latex_file_re.sub(".aux", latex_file)
325 log_file = latex_file_re.sub(".log", latex_file)
327 # Run bibtex/latex if necessary
328 progress("Checking if a bibtex run is necessary")
329 if string_in_file(r"\bibdata", aux_file):
330 bibtex_status, bibtex_stdout = run_tex(bibtex, aux_file)
331 latex_status, latex_stdout = run_tex(latex, latex_file)
332 # Rerun latex if necessary
333 progress("Checking if a latex rerun is necessary")
334 if string_in_file("Warning: Citation", log_file):
335 latex_status, latex_stdout = run_tex(latex, latex_file)
337 return latex_status, latex_stdout
340 def run_tex(tex, tex_file):
341 tex_call = '%s "%s"' % (tex, tex_file)
343 tex_status, tex_stdout = run_command(tex_call)
345 warning("%s had problems compiling %s" \
346 % (os.path.basename(tex), tex_file))
347 return tex_status, tex_stdout
350 def string_in_file(string, infile):
351 if not os.path.isfile(infile):
353 f = open(infile, 'r')
354 for line in f.readlines():