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, 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
27 latex_commands = ("latex", "pplatex", "platex", "latex2e")
28 pdflatex_commands = ("pdflatex", "xelatex", "lualatex")
30 # Pre-compiled regular expressions
31 latex_file_re = re.compile(r"\.tex$")
33 # PATH and PATHEXT environment variables
34 path = os.environ["PATH"].split(os.pathsep)
36 if "PATHEXT" in os.environ:
37 extlist += os.environ["PATHEXT"].split(os.pathsep)
52 sys.stderr.write("Consider installing the PyWin extension modules " \
53 "if you're irritated by windows appearing briefly.\n")
57 def progress(message):
60 sys.stdout.write("Progress: %s\n" % message)
64 sys.stderr.write("Warning: %s\n" % message)
68 sys.stderr.write("Error: %s\n" % message)
72 def make_texcolor(hexcolor, graphics):
73 # Test that the input string contains 6 hexadecimal chars.
74 hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
75 if not hexcolor_re.match(hexcolor):
76 error("Cannot convert color '%s'" % hexcolor)
78 red = float(string.atoi(hexcolor[0:2], 16)) / 255.0
79 green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
80 blue = float(string.atoi(hexcolor[4:6], 16)) / 255.0
83 return "%f,%f,%f" % (red, green, blue)
85 return "rgb %f %f %f" % (red, green, blue)
88 def find_exe(candidates):
91 for prog in candidates:
92 for directory in path:
94 full_path = os.path.join(directory, prog + ext)
95 if os.access(full_path, os.X_OK):
96 # The thing is in the PATH already (or we wouldn't
97 # have found it). Return just the basename to avoid
98 # problems when the path to the executable contains
100 return os.path.basename(full_path)
105 def find_exe_or_terminate(candidates):
106 exe = find_exe(candidates)
108 error("Unable to find executable from '%s'" % string.join(candidates))
113 def run_command_popen(cmd):
114 pipe = subprocess.Popen(cmd, shell=True, close_fds=True, stdin=subprocess.PIPE, \
115 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
116 cmd_stdout = pipe.communicate()[0]
117 cmd_status = pipe.returncode
121 sys.stdout.write(cmd_stdout)
122 return cmd_status, cmd_stdout
125 def run_command_win32(cmd):
126 sa = win32security.SECURITY_ATTRIBUTES()
127 sa.bInheritHandle = True
128 stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
130 si = win32process.STARTUPINFO()
131 si.dwFlags = (win32process.STARTF_USESTDHANDLES
132 | win32process.STARTF_USESHOWWINDOW)
133 si.wShowWindow = win32con.SW_HIDE
134 si.hStdOutput = stdout_w
136 process, thread, pid, tid = \
137 win32process.CreateProcess(None, cmd, None, None, True,
142 # Must close the write handle in this process, or ReadFile will hang.
145 # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
146 # which is okay because it happens when child process ends).
151 hr, buffer = win32file.ReadFile(stdout_r, 4096)
152 if hr != winerror.ERROR_IO_PENDING:
155 except pywintypes.error, e:
156 if e.args[0] != winerror.ERROR_BROKEN_PIPE:
163 # Everything is okay --- the called process has closed the pipe.
164 # For safety, check that the process ended, then pick up its exit code.
165 win32event.WaitForSingleObject(process, win32event.INFINITE)
166 if win32process.GetExitCodeProcess(process):
171 sys.stdout.write(data)
175 def run_command(cmd):
176 progress("Running %s" % cmd)
177 if use_win32_modules:
178 return run_command_win32(cmd)
180 return run_command_popen(cmd)
183 def get_version_info():
184 version_re = re.compile("([0-9])\.([0-9])")
186 match = version_re.match(sys.version)
188 error("Unable to extract version info from 'sys.version'")
190 return string.atoi(match.group(1)), string.atoi(match.group(2))
193 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
194 """copy data from file-like object fsrc to file-like object fdst"""
200 buf = fsrc.read(length)
207 """clone of tempfile.TemporaryFile to use with python < 2.0."""
208 # Cache the unlinker so we don't get spurious errors at shutdown
209 # when the module-level "os" is None'd out. Note that this must
210 # be referenced as self.unlink, because the name TempFile
211 # may also get None'd out before __del__ is called.
215 self.filename = tempfile.mktemp()
216 self.file = open(self.filename,"w+b")
217 self.close_called = 0
220 if not self.close_called:
221 self.close_called = 1
223 self.unlink(self.filename)
228 def read(self, size = -1):
229 return self.file.read(size)
231 def write(self, line):
232 return self.file.write(line)
234 def seek(self, offset):
235 return self.file.seek(offset)
238 return self.file.flush()
242 """create a secure temporary file and return its object-like file"""
243 major, minor = get_version_info()
245 if major >= 2 and minor >= 0:
246 return tempfile.TemporaryFile()
250 def write_metrics_info(metrics_info, metrics_file):
251 metrics = open(metrics_file, 'w')
252 for metric in metrics_info:
253 metrics.write("Snippet %s %f\n" % metric)
256 # Reads a .tex files and create an identical file but only with
257 # pages whose index is in pages_to_keep
258 def filter_pages(source_path, destination_path, pages_to_keep):
259 source_file = open(source_path, "r")
260 destination_file = open(destination_path, "w")
264 for line in source_file:
265 # We found a new page
266 if line.startswith("\\begin{preview}"):
268 # If the page index isn't in pages_to_keep we don't copy it
269 skip_page = page_index not in pages_to_keep
272 destination_file.write(line)
274 # End of a page, we reset the skip_page bool
275 if line.startswith("\\end{preview}"):
278 destination_file.close()
281 # Joins two metrics list, that is a list of tuple (page_index, metric)
282 # new_page_indexes contains the original page number of the pages in new_metrics
283 # e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting
284 # original_bitmap and destination_bitmap are file name models used to rename the new files
285 # e.g. image_new%d.png and image_%d.png
286 def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap):
288 for (index, metric) in new_metrics:
289 # If the file exists we rename it
290 if os.path.isfile(original_bitmap % (index)):
291 os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1])
293 # Extract the original page index
294 index = new_page_indexes[index-1]
295 # Goes through the array until the end is reached or the correct index is found
296 while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index:
299 # Add or update the metric for this page
300 if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index:
301 original_metrics[legacy_index] = (index, metric)
303 original_metrics.insert(legacy_index, (index, metric))