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 # run_command, warning
17 import os, re, string, sys, tempfile
32 sys.stderr.write("Consider installing the PyWin extension modules "\
33 "if you're irritated by windows appearing briefly.\n")
38 sys.stderr.write(message + '\n')
42 sys.stderr.write(message + '\n')
46 def make_texcolor(hexcolor, graphics):
47 # Test that the input string contains 6 hexadecimal chars.
48 hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
49 if not hexcolor_re.match(hexcolor):
50 error("Cannot convert color '%s'" % hexcolor)
52 red = float(string.atoi(hexcolor[0:2], 16)) / 255.0
53 green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
54 blue = float(string.atoi(hexcolor[4:6], 16)) / 255.0
57 return "%f,%f,%f" % (red, green, blue)
59 return "rgb %f %f %f" % (red, green, blue)
62 def find_exe(candidates, path):
63 for prog in candidates:
64 for directory in path:
66 full_path = os.path.join(directory, prog + ".exe")
68 full_path = os.path.join(directory, prog)
70 if os.access(full_path, os.X_OK):
71 # The thing is in the PATH already (or we wouldn't
72 # have found it). Return just the basename to avoid
73 # problems when the path to the executable contains
75 return os.path.basename(full_path)
80 def find_exe_or_terminate(candidates, path):
81 exe = find_exe(candidates, path)
83 error("Unable to find executable from '%s'" % string.join(candidates))
88 def run_command_popen(cmd):
89 handle = os.popen(cmd, 'r')
90 cmd_stdout = handle.read()
91 cmd_status = handle.close()
93 return cmd_status, cmd_stdout
96 def run_command_win32(cmd):
97 sa = win32security.SECURITY_ATTRIBUTES()
98 sa.bInheritHandle = True
99 stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
101 si = win32process.STARTUPINFO()
102 si.dwFlags = (win32process.STARTF_USESTDHANDLES
103 | win32process.STARTF_USESHOWWINDOW)
104 si.wShowWindow = win32con.SW_HIDE
105 si.hStdOutput = stdout_w
107 process, thread, pid, tid = \
108 win32process.CreateProcess(None, cmd, None, None, True,
113 # Must close the write handle in this process, or ReadFile will hang.
116 # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
117 # which is okay because it happens when child process ends).
122 hr, buffer = win32file.ReadFile(stdout_r, 4096)
123 if hr != winerror.ERROR_IO_PENDING:
126 except pywintypes.error, e:
127 if e.args[0] != winerror.ERROR_BROKEN_PIPE:
134 # Everything is okay --- the called process has closed the pipe.
135 # For safety, check that the process ended, then pick up its exit code.
136 win32event.WaitForSingleObject(process, win32event.INFINITE)
137 if win32process.GetExitCodeProcess(process):
143 def run_command(cmd):
144 if use_win32_modules:
145 return run_command_win32(cmd)
147 return run_command_popen(cmd)
150 def get_version_info():
151 version_re = re.compile("([0-9])\.([0-9])")
153 match = version_re.match(sys.version)
155 error("Unable to extract version info from 'sys.version'")
157 return string.atoi(match.group(1)), string.atoi(match.group(2))
160 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
161 """copy data from file-like object fsrc to file-like object fdst"""
167 buf = fsrc.read(length)
174 """clone of tempfile.TemporaryFile to use with python < 2.0."""
175 # Cache the unlinker so we don't get spurious errors at shutdown
176 # when the module-level "os" is None'd out. Note that this must
177 # be referenced as self.unlink, because the name TempFile
178 # may also get None'd out before __del__ is called.
182 self.filename = tempfile.mktemp()
183 self.file = open(self.filename,"w+b")
184 self.close_called = 0
187 if not self.close_called:
188 self.close_called = 1
190 self.unlink(self.filename)
195 def read(self, size = -1):
196 return self.file.read(size)
198 def write(self, line):
199 return self.file.write(line)
201 def seek(self, offset):
202 return self.file.seek(offset)
205 return self.file.flush()
209 """create a secure temporary file and return its object-like file"""
210 major, minor = get_version_info()
212 if major >= 2 and minor >= 0:
213 return tempfile.TemporaryFile()