def link_GL(name, restype, argtypes, requires=None, suggestions=None):
try:
func = getattr(gl_lib, name)
func.restype = restype
func.argtypes = argtypes
decorate_function(func, name)
return func
except AttributeError:
# Not in opengl32.dll. Try and get a pointer from WGL.
try:
fargs = (restype,) + tuple(argtypes)
ftype = ctypes.WINFUNCTYPE(*fargs)
if _have_get_proc_address:
from pyglet.gl import gl_info
if gl_info.have_context():
address = wglGetProcAddress(name)
if address:
func = cast(address, ftype)
decorate_function(func, name)
return func
else:
# Insert proxy until we have a context
return WGLFunctionProxy(name, ftype, requires, suggestions)
except:
pass
return missing_function(name, requires, suggestions)
python类WINFUNCTYPE的实例源码
def link_GLU(name, restype, argtypes, requires=None, suggestions=None):
try:
func = getattr(glu_lib, name)
func.restype = restype
func.argtypes = argtypes
decorate_function(func, name)
return func
except AttributeError:
# Not in glu32.dll. Try and get a pointer from WGL.
try:
fargs = (restype,) + tuple(argtypes)
ftype = ctypes.WINFUNCTYPE(*fargs)
if _have_get_proc_address:
from pyglet.gl import gl_info
if gl_info.have_context():
address = wglGetProcAddress(name)
if address:
func = cast(address, ftype)
decorate_function(func, name)
return func
else:
# Insert proxy until we have a context
return WGLFunctionProxy(name, ftype, requires, suggestions)
except:
pass
return missing_function(name, requires, suggestions)
def get_field(self):
return ctypes.WINFUNCTYPE(self.restype, *self.argtypes)
def link_GL(name, restype, argtypes, requires=None, suggestions=None):
try:
func = getattr(gl_lib, name)
func.restype = restype
func.argtypes = argtypes
decorate_function(func, name)
return func
except AttributeError:
# Not in opengl32.dll. Try and get a pointer from WGL.
try:
fargs = (restype,) + tuple(argtypes)
ftype = ctypes.WINFUNCTYPE(*fargs)
if _have_get_proc_address:
from pyglet.gl import gl_info
if gl_info.have_context():
address = wglGetProcAddress(name)
if address:
func = cast(address, ftype)
decorate_function(func, name)
return func
else:
# Insert proxy until we have a context
return WGLFunctionProxy(name, ftype, requires, suggestions)
except:
pass
return missing_function(name, requires, suggestions)
def link_GLU(name, restype, argtypes, requires=None, suggestions=None):
try:
func = getattr(glu_lib, name)
func.restype = restype
func.argtypes = argtypes
decorate_function(func, name)
return func
except AttributeError:
# Not in glu32.dll. Try and get a pointer from WGL.
try:
fargs = (restype,) + tuple(argtypes)
ftype = ctypes.WINFUNCTYPE(*fargs)
if _have_get_proc_address:
from pyglet.gl import gl_info
if gl_info.have_context():
address = wglGetProcAddress(name)
if address:
func = cast(address, ftype)
decorate_function(func, name)
return func
else:
# Insert proxy until we have a context
return WGLFunctionProxy(name, ftype, requires, suggestions)
except:
pass
return missing_function(name, requires, suggestions)
def win_get_unicode_stream(stream, excepted_fileno, output_handle, encoding):
"""Returns a unicode-compatible stream.
This function will return a direct-Console writing object only if:
- the file number is the expected console file number
- the handle the expected file handle
- the 'real' handle is in fact a handle to a console.
"""
old_fileno = getattr(stream, 'fileno', lambda: None)()
if old_fileno == excepted_fileno:
# These types are available on linux but not Mac.
# pylint: disable=no-name-in-module,F0401
from ctypes import windll, WINFUNCTYPE
from ctypes.wintypes import DWORD, HANDLE
# <http://msdn.microsoft.com/en-us/library/ms683231.aspx>
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(('GetStdHandle', windll.kernel32))
real_output_handle = GetStdHandle(DWORD(output_handle))
if win_handle_is_a_console(real_output_handle):
# It's a console.
return WinUnicodeConsoleOutput(
real_output_handle, old_fileno, stream.name, encoding)
# It's something else. Create an auto-encoding stream.
return WinUnicodeOutput(stream, old_fileno, encoding)
def win_get_unicode_stream(stream, excepted_fileno, output_handle, encoding):
"""Returns a unicode-compatible stream.
This function will return a direct-Console writing object only if:
- the file number is the expected console file number
- the handle the expected file handle
- the 'real' handle is in fact a handle to a console.
"""
old_fileno = getattr(stream, 'fileno', lambda: None)()
if old_fileno == excepted_fileno:
# These types are available on linux but not Mac.
# pylint: disable=no-name-in-module,F0401
from ctypes import windll, WINFUNCTYPE
from ctypes.wintypes import DWORD, HANDLE
# <http://msdn.microsoft.com/en-us/library/ms683231.aspx>
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(('GetStdHandle', windll.kernel32))
real_output_handle = GetStdHandle(DWORD(output_handle))
if win_handle_is_a_console(real_output_handle):
# It's a console.
return WinUnicodeConsoleOutput(
real_output_handle, old_fileno, stream.name, encoding)
# It's something else. Create an auto-encoding stream.
return WinUnicodeOutput(stream, old_fileno, encoding)
def get_field(self):
return ctypes.WINFUNCTYPE(self.restype, *self.argtypes)
def link_GL(name, restype, argtypes, requires=None, suggestions=None):
try:
func = getattr(gl_lib, name)
func.restype = restype
func.argtypes = argtypes
decorate_function(func, name)
return func
except AttributeError:
# Not in opengl32.dll. Try and get a pointer from WGL.
try:
fargs = (restype,) + tuple(argtypes)
ftype = ctypes.WINFUNCTYPE(*fargs)
if _have_get_proc_address:
from pyglet.gl import gl_info
if gl_info.have_context():
address = wglGetProcAddress(name)
if address:
func = cast(address, ftype)
decorate_function(func, name)
return func
else:
# Insert proxy until we have a context
return WGLFunctionProxy(name, ftype, requires, suggestions)
except:
pass
return missing_function(name, requires, suggestions)
def link_GLU(name, restype, argtypes, requires=None, suggestions=None):
try:
func = getattr(glu_lib, name)
func.restype = restype
func.argtypes = argtypes
decorate_function(func, name)
return func
except AttributeError:
# Not in glu32.dll. Try and get a pointer from WGL.
try:
fargs = (restype,) + tuple(argtypes)
ftype = ctypes.WINFUNCTYPE(*fargs)
if _have_get_proc_address:
from pyglet.gl import gl_info
if gl_info.have_context():
address = wglGetProcAddress(name)
if address:
func = cast(address, ftype)
decorate_function(func, name)
return func
else:
# Insert proxy until we have a context
return WGLFunctionProxy(name, ftype, requires, suggestions)
except:
pass
return missing_function(name, requires, suggestions)
def win_get_unicode_stream(stream, excepted_fileno, output_handle, encoding):
"""Returns a unicode-compatible stream.
This function will return a direct-Console writing object only if:
- the file number is the expected console file number
- the handle the expected file handle
- the 'real' handle is in fact a handle to a console.
"""
old_fileno = getattr(stream, 'fileno', lambda: None)()
if old_fileno == excepted_fileno:
# These types are available on linux but not Mac.
# pylint: disable=no-name-in-module,F0401
from ctypes import windll, WINFUNCTYPE
from ctypes.wintypes import DWORD, HANDLE
# <http://msdn.microsoft.com/en-us/library/ms683231.aspx>
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(('GetStdHandle', windll.kernel32))
real_output_handle = GetStdHandle(DWORD(output_handle))
if win_handle_is_a_console(real_output_handle):
# It's a console.
return WinUnicodeConsoleOutput(
real_output_handle, old_fileno, stream.name, encoding)
# It's something else. Create an auto-encoding stream.
return WinUnicodeOutput(stream, old_fileno, encoding)
def find(keyword):
""" ??????????? """
@ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, ctypes.c_wchar_p)
def check(hwnd, keyword):
""" ?? """
if api.IsWindowVisible(hwnd)\
and api.GetWindowTextW(hwnd, buff, 32) > 6 and keyword in buff.value:
team.add(hwnd)
return 1
for i in range(10):
api.EnumWindows(check, keyword)
time.sleep(3)
if team:
break
return {Puppet(main) for main in team}
def find(keyword):
""" ??????????? """
@ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, ctypes.c_wchar_p)
def check(hwnd, keyword):
""" ?? """
if api.IsWindowVisible(hwnd)\
and api.GetWindowTextW(hwnd, buff, 32) > 6 and keyword in buff.value:
team.add(hwnd)
return 1
api.EnumWindows(check, keyword)
return {Puppet(main) for main in team}
def platform_specific_functions():
# use stddecl on windows, cdecl on all other platforms
d = {'library_loader' : ctypes.cdll
,'function_pointer' : ctypes.CFUNCTYPE
}
if platform.system() in ('Windows', 'Microsoft'):
d['library_loader'] = ctypes.windll
d['function_pointer'] = ctypes.WINFUNCTYPE
return d
def quick_win_define(name, output, *args, **kwargs):
dllname, fname = name.split('.')
params = kwargs.get('params', None)
if params:
params = tuple([(x, ) for x in params])
func = (WINFUNCTYPE(output, *args))((fname, getattr(windll, dllname)), params)
err = kwargs.get('err', err_on_zero_or_null_check)
if err:
func.errcheck = err
return func
def get_display_monitors(self):
'''
Enumerates and returns a list of virtual screen
coordinates for the attached display devices
output = [
(left, top, right, bottom), # Monitor 1
(left, top, right, bottom) # Monitor 2
# etc...
]
'''
display_coordinates = []
def _monitorEnumProc(hMonitor, hdcMonitor, lprcMonitor, dwData):
# print('call result:', hMonitor, hdcMonitor, lprcMonitor, dwData)
# print('DC:', user32.GetWindowDC(hMonitor))
coordinates = (
lprcMonitor.contents.left,
lprcMonitor.contents.top,
lprcMonitor.contents.right,
lprcMonitor.contents.bottom
)
display_coordinates.append(coordinates)
return True
# Callback Factory
MonitorEnumProc = WINFUNCTYPE(
ctypes.c_bool,
ctypes.wintypes.HMONITOR,
ctypes.wintypes.HDC,
ctypes.POINTER(RECT),
ctypes.wintypes.LPARAM
)
# Make the callback function
enum_callback = MonitorEnumProc(_monitorEnumProc)
# Enumerate the windows
user32.EnumDisplayMonitors(
None,
None,
enum_callback,
0
)
return display_coordinates
def __init__(self):
# Initialize freeimage lib as None
self._lib = None
# A lock to create thread-safety
self._lock = threading.RLock()
# Init log messages lists
self._messages = []
# Select functype for error handler
if sys.platform.startswith('win'):
functype = ctypes.WINFUNCTYPE
else:
functype = ctypes.CFUNCTYPE
# Create output message handler
@functype(None, ctypes.c_int, ctypes.c_char_p)
def error_handler(fif, message):
message = message.decode('utf-8')
self._messages.append(message)
while (len(self._messages)) > 256:
self._messages.pop(0)
# Make sure to keep a ref to function
self._error_handler = error_handler
# Load library and register API
success = False
try:
# Try without forcing a download, but giving preference
# to the imageio-provided lib (if previously downloaded)
self._load_freeimage()
self._register_api()
if self._lib.FreeImage_GetVersion().decode('utf-8') >= '3.15':
success = True
except OSError:
pass
if not success:
# Ensure we have our own lib, try again
get_freeimage_lib()
self._load_freeimage()
self._register_api()
# Wrap up
self._lib.FreeImage_SetOutputMessage(self._error_handler)
self._lib_version = self._lib.FreeImage_GetVersion().decode('utf-8')
def fix_win_sys_argv(encoding):
"""Converts sys.argv to 'encoding' encoded string.
utf-8 is recommended.
Works around <http://bugs.python.org/issue2128>.
"""
global _SYS_ARGV_PROCESSED
if _SYS_ARGV_PROCESSED:
return False
# These types are available on linux but not Mac.
# pylint: disable=no-name-in-module,F0401
from ctypes import byref, c_int, POINTER, windll, WINFUNCTYPE
from ctypes.wintypes import LPCWSTR, LPWSTR
# <http://msdn.microsoft.com/en-us/library/ms683156.aspx>
GetCommandLineW = WINFUNCTYPE(LPWSTR)(('GetCommandLineW', windll.kernel32))
# <http://msdn.microsoft.com/en-us/library/bb776391.aspx>
CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
('CommandLineToArgvW', windll.shell32))
argc = c_int(0)
argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
argv = [
argv_unicode[i].encode(encoding, 'replace')
for i in xrange(0, argc.value)]
if not hasattr(sys, 'frozen'):
# If this is an executable produced by py2exe or bbfreeze, then it
# will have been invoked directly. Otherwise, unicode_argv[0] is the
# Python interpreter, so skip that.
argv = argv[1:]
# Also skip option arguments to the Python interpreter.
while len(argv) > 0:
arg = argv[0]
if not arg.startswith(u'-') or arg == u'-':
break
argv = argv[1:]
if arg == u'-m':
# sys.argv[0] should really be the absolute path of the
# module source, but never mind.
break
if arg == u'-c':
argv[0] = u'-c'
break
sys.argv = argv
_SYS_ARGV_PROCESSED = True
return True
def fix_win_sys_argv(encoding):
"""Converts sys.argv to 'encoding' encoded string.
utf-8 is recommended.
Works around <http://bugs.python.org/issue2128>.
"""
global _SYS_ARGV_PROCESSED
if _SYS_ARGV_PROCESSED:
return False
# These types are available on linux but not Mac.
# pylint: disable=no-name-in-module,F0401
from ctypes import byref, c_int, POINTER, windll, WINFUNCTYPE
from ctypes.wintypes import LPCWSTR, LPWSTR
# <http://msdn.microsoft.com/en-us/library/ms683156.aspx>
GetCommandLineW = WINFUNCTYPE(LPWSTR)(('GetCommandLineW', windll.kernel32))
# <http://msdn.microsoft.com/en-us/library/bb776391.aspx>
CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
('CommandLineToArgvW', windll.shell32))
argc = c_int(0)
argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
argv = [
argv_unicode[i].encode(encoding, 'replace')
for i in xrange(0, argc.value)]
if not hasattr(sys, 'frozen'):
# If this is an executable produced by py2exe or bbfreeze, then it
# will have been invoked directly. Otherwise, unicode_argv[0] is the
# Python interpreter, so skip that.
argv = argv[1:]
# Also skip option arguments to the Python interpreter.
while len(argv) > 0:
arg = argv[0]
if not arg.startswith(u'-') or arg == u'-':
break
argv = argv[1:]
if arg == u'-m':
# sys.argv[0] should really be the absolute path of the
# module source, but never mind.
break
if arg == u'-c':
argv[0] = u'-c'
break
sys.argv = argv
_SYS_ARGV_PROCESSED = True
return True
def __init__(self):
from ctypes import WINFUNCTYPE, windll
from ctypes.wintypes import BOOL, HANDLE, DWORD, WORD
self.__original_stderr = sys.stderr
self.__stdout = None
self.__SetConsoleTextAttribute = None
# Work around <http://bugs.python.org/issue6058>.
# codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
# Make Unicode console output work independently of the current code page.
# This also fixes <http://bugs.python.org/issue1602>.
# Credit to Michael Kaplan <http://blogs.msdn.com/b/michkap/archive/2010/04/07/9989346.aspx>
# and TZOmegaTZIOY
# <http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>.
try:
# <http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx>
# HANDLE WINAPI GetStdHandle(DWORD nStdHandle);
# returns INVALID_HANDLE_VALUE, NULL, or a valid handle
#
# <http://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx>
# DWORD WINAPI GetFileType(DWORD hFile);
#
# <http://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx>
# BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode);
STD_OUTPUT_HANDLE = DWORD(-11)
INVALID_HANDLE_VALUE = DWORD(-1).value
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32))
self.__SetConsoleTextAttribute = WINFUNCTYPE(BOOL, HANDLE, WORD)(("SetConsoleTextAttribute", windll.kernel32))
self.__stdout = GetStdHandle(STD_OUTPUT_HANDLE)
if self.__stdout == INVALID_HANDLE_VALUE:
self.__stdout = None
except Exception as e:
self.__stdout = None
self._complain("exception %r while fixing up sys.stdout and sys.stderr\n" % (str(e),))
# If any exception occurs in this code, we'll probably try to print it on stderr,
# which makes for frustrating debugging if stderr is directed to our wrapper.
# So be paranoid about catching errors and reporting them to original_stderr,
# so that we can at least see them.