Exemplo n.º 1
0
def WRFun(name, dll, result, *args):
    '''myfunc = wfunc( '函数名',
                       DLL,
                       返回值类型,
                       (参数类型, '参数名', 参数方向,默认值),
                       (参数类型, '参数名', 参数方向,默认值)
                     )
    '''
    atypes = []
    aflags = []
    for arg in args:
        atypes.append(arg[0])
        aflags.append((arg[2], arg[1]) + arg[3:])
    func = WINFUNCTYPE(result, *atypes)((name, dll), tuple(aflags))
    #func.errcheck = ErrCheck
    func.FuncName = name
    return func
Exemplo n.º 2
0
def CheckFreeSpace(path):
  """Return path/drive free space (in bytes)."""
  if IS_WINDOWS:
    try:
      # pylint: disable=invalid-name
      get_disk_free_space_ex = WINFUNCTYPE(c_int, c_wchar_p,
                                           POINTER(c_uint64),
                                           POINTER(c_uint64),
                                           POINTER(c_uint64))
      get_disk_free_space_ex = get_disk_free_space_ex(
          ('GetDiskFreeSpaceExW', windll.kernel32), (
              (1, 'lpszPathName'),
              (2, 'lpFreeUserSpace'),
              (2, 'lpTotalSpace'),
              (2, 'lpFreeSpace'),))
    except AttributeError:
      get_disk_free_space_ex = WINFUNCTYPE(c_int, c_char_p,
                                           POINTER(c_uint64),
                                           POINTER(c_uint64),
                                           POINTER(c_uint64))
      get_disk_free_space_ex = get_disk_free_space_ex(
          ('GetDiskFreeSpaceExA', windll.kernel32), (
              (1, 'lpszPathName'),
              (2, 'lpFreeUserSpace'),
              (2, 'lpTotalSpace'),
              (2, 'lpFreeSpace'),))

    def GetDiskFreeSpaceExErrCheck(result, unused_func, args):
      if not result:
        raise WinError()
      return args[1].value
    get_disk_free_space_ex.errcheck = GetDiskFreeSpaceExErrCheck

    return get_disk_free_space_ex(os.getenv('SystemDrive'))
  else:
    (_, f_frsize, _, _, f_bavail, _, _, _, _, _) = os.statvfs(path)
    return f_frsize * f_bavail
Exemplo n.º 3
0
from __future__ import absolute_import
import random
import logging
import traceback
from threading import Thread
from ctypes import WINFUNCTYPE, POINTER
from ctypes import c_bool, c_int, create_unicode_buffer, create_string_buffer, memmove, sizeof

from lib.common.abstracts import Auxiliary
from lib.common.defines import KERNEL32, USER32
from lib.common.defines import WM_GETTEXT, WM_GETTEXTLENGTH, WM_CLOSE, BM_CLICK
from lib.common.defines import GMEM_MOVEABLE, CF_TEXT

log = logging.getLogger(__name__)

EnumWindowsProc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int))
EnumChildProc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int))

RESOLUTION = {"x": USER32.GetSystemMetrics(0), "y": USER32.GetSystemMetrics(1)}

INITIAL_HWNDS = []

CLOSED_OFFICE = False
OFFICE_CLICK_AROUND = False


def foreach_child(hwnd, lparam):
    # List of buttons labels to click.
    buttons = [
        # english
        "yes",
from ctypes import create_string_buffer, create_unicode_buffer
from ctypes.wintypes import HINSTANCE, LPARAM, DWORD, LPWSTR
''' Copydata '''

GetModuleHandle = ctypes.windll.kernel32.GetModuleHandleW
FindWindow = ctypes.windll.user32.FindWindowW
SendMessage = ctypes.windll.user32.SendMessageW
RegisterClass = ctypes.windll.user32.RegisterClassW
CreateWindow = ctypes.windll.user32.CreateWindowExW
DefWindowProc = ctypes.windll.user32.DefWindowProcW
GetMessage = ctypes.windll.user32.GetMessageW
TranslateMessage = ctypes.windll.user32.TranslateMessage
DispatchMessage = ctypes.windll.user32.DispatchMessageW

WM_COPYDATA = 74
WNDPROC = WINFUNCTYPE(c_long, c_int, c_uint, c_int, c_int)


class WNDCLASS(Structure):
    _fields_ = [('style', c_uint), ('lpfnWndProc', WNDPROC),
                ('cbClsExtra', c_int), ('cbWndExtra', c_int),
                ('hInstance', HINSTANCE), ('hIcon', c_int), ('hCursor', c_int),
                ('hbrBackground', c_int), ('lpszMenuName', c_char_p),
                ('lpszClassName', c_char_p)]


class COPYDATASTRUCT(Structure):
    _fields_ = [('dwData', LPARAM), ('cbData', DWORD), ('lpData', c_void_p)]


PCOPYDATASTRUCT = POINTER(COPYDATASTRUCT)
Exemplo n.º 5
0
GetMessageA = user32.GetMessageA
TranslateMessage = user32.TranslateMessage
DispatchMessageA = user32.DispatchMessageA
MapVirtualKeyW = user32.MapVirtualKeyW
GetAsyncKeyState = user32.GetAsyncKeyState
VkKeyScanW = user32.VkKeyScanW
VkKeyScanW.argtypes = [c_wchar]
keybd_event = user32.keybd_event
GetKeyState = user32.GetKeyState
GetKeyState.restype = SHORT
GetKeyboardLayout = user32.GetKeyboardLayout
GetKeyboardLayoutList = user32.GetKeyboardLayoutList
GetKeyboardLayoutList.argtypes = [c_int, POINTER(HANDLE*32)]
SystemParametersInfoA = user32.SystemParametersInfoA
EnumWindows = user32.EnumWindows
EnumWindowsProc = WINFUNCTYPE(BOOL, HWND, LPARAM)
IsWindowVisible = user32.IsWindowVisible
GetWindowTextLengthW = user32.GetWindowTextLengthW
GetWindowTextW = user32.GetWindowTextW
GetWindowThreadProcessId = user32.GetWindowThreadProcessId
GetWindowThreadProcessId.restype = DWORD
GetDesktopWindow = user32.GetDesktopWindow
GetDesktopWindow.restype = HWND
GetWindowDC = user32.GetWindowDC
GetWindowDC.restype = HWND
ReleaseDC = user32.ReleaseDC
ReleaseDC.restype = c_int
ReleaseDC.argtypes = [HWND, HDC]
mouse_event = user32.mouse_event
LoadIconA = user32.LoadIconA
RegisterWindowMessageA = user32.RegisterWindowMessageA
Exemplo n.º 6
0
def proto(*argtypes, retval=None):
    if retval is not None:
        argtypes = (*argtypes, POINTER(retval))
    proto = WINFUNCTYPE(HRESULT, *argtypes)
    proto._retval = retval
    return proto
    def __make_interface_pointer(self, itf):
        methods = []  # method implementations
        fields = []  # (name, prototype) for virtual function table
        iids = []  # interface identifiers.
        # iterate over interface inheritance in reverse order to build the
        # virtual function table, and leave out the 'object' base class.
        finder = self._get_method_finder_(itf)
        for interface in itf.__mro__[-2::-1]:
            iids.append(interface._iid_)
            for m in interface._methods_:
                restype, mthname, argtypes, paramflags, idlflags, helptext = m
                proto = WINFUNCTYPE(restype, c_void_p, *argtypes)
                fields.append((mthname, proto))
                mth = finder.get_impl(interface, mthname, paramflags, idlflags)
                methods.append(proto(mth))
        Vtbl = _create_vtbl_type(tuple(fields), itf)
        vtbl = Vtbl(*methods)
        for iid in iids:
            self._com_pointers_[iid] = pointer(pointer(vtbl))
        if hasattr(itf, "_disp_methods_"):
            self._dispimpl_ = {}
            for m in itf._disp_methods_:
                what, mthname, idlflags, restype, argspec = m
                #################
                # What we have:
                #
                # restypes is a ctypes type or None
                # argspec is seq. of (['in'], paramtype, paramname) tuples (or
                # lists?)
                #################
                # What we need:
                #
                # idlflags must contain 'propget', 'propset' and so on:
                # Must be constructed by converting disptype
                #
                # paramflags must be a sequence
                # of (F_IN|F_OUT|F_RETVAL, paramname[, default-value]) tuples
                #
                # comtypes has this function which helps:
                #    def _encode_idl(names):
                #        # convert to F_xxx and sum up "in", "out",
                #        # "retval" values found in _PARAMFLAGS, ignoring
                #        # other stuff.
                #        return sum([_PARAMFLAGS.get(n, 0) for n in names])
                #################

                if what == "DISPMETHOD":
                    if 'propget' in idlflags:
                        invkind = 2  # DISPATCH_PROPERTYGET
                        mthname = "_get_" + mthname
                    elif 'propput' in idlflags:
                        invkind = 4  # DISPATCH_PROPERTYPUT
                        mthname = "_set_" + mthname
                    elif 'propputref' in idlflags:
                        invkind = 8  # DISPATCH_PROPERTYPUTREF
                        mthname = "_setref_" + mthname
                    else:
                        invkind = 1  # DISPATCH_METHOD
                        if restype:
                            argspec = argspec + ((['out'], restype, ""),)
                    self.__make_dispentry(finder, interface, mthname,
                                          idlflags, argspec, invkind)
                elif what == "DISPPROPERTY":
                    # DISPPROPERTY have implicit "out"
                    if restype:
                        argspec += ((['out'], restype, ""),)
                    self.__make_dispentry(finder, interface,
                                          "_get_" + mthname,
                                          idlflags, argspec,
                                          2  # DISPATCH_PROPERTYGET
                                          )
                    if not 'readonly' in idlflags:
                        self.__make_dispentry(finder, interface,
                                              "_set_" + mthname,
                                              idlflags, argspec,
                                              4)  # DISPATCH_PROPERTYPUT
Exemplo n.º 8
0
def ief(p1,t1,p2,t2):
    iefprototype=WINFUNCTYPE(c_double,c_double,c_double,c_double,c_double)
    f=iefprototype(("ief",windll.seuif97),)
    result=f(p1,t1,p2,t2)
    return result
Exemplo n.º 9
0
This is a python api of shared linrary  for windows platform to

calculate the properties of water and steam

using the IAPWS-IF97 industry-standard steam properties correlations.

License: this code is in the public domain

Author:   Cheng Maohua
Email:    [email protected]

Last modified: 2016.4.20
"""

from ctypes import c_int,c_double,WINFUNCTYPE,windll
prototype=WINFUNCTYPE(c_double,c_double,c_double,c_int)

def pt(p,t,w): 
    f=prototype(("pt",windll.seuif97),)
    result=f(p,t,w)
    return result

def pt2h(p,t): 
    f=prototype(("pt",windll.seuif97),)
    result=f(p,t,4)
    return result

def pt2s(p,t): 
    f=prototype(("pt",windll.seuif97),)
    result=f(p,t,5)
    return result
Exemplo n.º 10
0

PSecPkgInfo = POINTER(SecPkgInfo)


class SecPkgCredentials_Names(Structure):
    _fields_ = [('UserName', c_wchar_p)]


def ret_val(value):
    if value < 0:
        raise Exception('SSPI Error {0}'.format(Status.getname(value)))
    return value


ENUMERATE_SECURITY_PACKAGES_FN = WINFUNCTYPE(ret_val, POINTER(c_ulong),
                                             POINTER(POINTER(SecPkgInfo)))

ACQUIRE_CREDENTIALS_HANDLE_FN = WINFUNCTYPE(
    ret_val,
    c_wchar_p,  # principal
    c_wchar_p,  # package
    ULONG,  # fCredentialUse
    PLUID,  # pvLogonID
    PVOID,  # pAuthData
    PVOID,  # pGetKeyFn
    PVOID,  # pvGetKeyArgument
    PCredHandle,  # phCredential
    PTimeStamp  # ptsExpiry
)
FREE_CREDENTIALS_HANDLE_FN = WINFUNCTYPE(ret_val, POINTER(SecHandle))
INITIALIZE_SECURITY_CONTEXT_FN = WINFUNCTYPE(
Exemplo n.º 11
0
def fix_unicode_out():
    #code found here:
    #http://stackoverflow.com/a/3259271/428751
    import codecs
    from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
    from ctypes.wintypes import BOOL, HANDLE, DWORD, LPWSTR, LPCWSTR, LPVOID

    original_stderr = sys.stderr

    # 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.
    def _complain(message):
        print >> original_stderr, message if isinstance(message,
                                                        str) else repr(message)

    # 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);

        GetStdHandle = WINFUNCTYPE(HANDLE,
                                   DWORD)(("GetStdHandle", windll.kernel32))
        STD_OUTPUT_HANDLE = DWORD(-11)
        STD_ERROR_HANDLE = DWORD(-12)
        GetFileType = WINFUNCTYPE(DWORD,
                                  DWORD)(("GetFileType", windll.kernel32))
        FILE_TYPE_CHAR = 0x0002
        FILE_TYPE_REMOTE = 0x8000
        GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
            ("GetConsoleMode", windll.kernel32))
        INVALID_HANDLE_VALUE = DWORD(-1).value

        def not_a_console(handle):
            if handle == INVALID_HANDLE_VALUE or handle is None:
                return True
            return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
                    or GetConsoleMode(handle, byref(DWORD())) == 0)

        old_stdout_fileno = None
        old_stderr_fileno = None
        if hasattr(sys.stdout, 'fileno'):
            old_stdout_fileno = sys.stdout.fileno()
        if hasattr(sys.stderr, 'fileno'):
            old_stderr_fileno = sys.stderr.fileno()

        STDOUT_FILENO = 1
        STDERR_FILENO = 2
        real_stdout = (old_stdout_fileno == STDOUT_FILENO)
        real_stderr = (old_stderr_fileno == STDERR_FILENO)

        if real_stdout:
            hStdout = GetStdHandle(STD_OUTPUT_HANDLE)
            if not_a_console(hStdout):
                real_stdout = False

        if real_stderr:
            hStderr = GetStdHandle(STD_ERROR_HANDLE)
            if not_a_console(hStderr):
                real_stderr = False

        if real_stdout or real_stderr:
            # BOOL WINAPI WriteConsoleW(HANDLE hOutput, LPWSTR lpBuffer, DWORD nChars,
            #                           LPDWORD lpCharsWritten, LPVOID lpReserved);

            WriteConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPWSTR, DWORD,
                                        POINTER(DWORD), LPVOID)(
                                            ("WriteConsoleW", windll.kernel32))

            class UnicodeOutput:
                def __init__(self, hConsole, stream, fileno, name):
                    self._hConsole = hConsole
                    self._stream = stream
                    self._fileno = fileno
                    self.closed = False
                    self.softspace = False
                    self.mode = 'w'
                    self.encoding = 'utf-8'
                    self.name = name
                    self.flush()

                def isatty(self):
                    return False

                def close(self):
                    # don't really close the handle, that would only cause problems
                    self.closed = True

                def fileno(self):
                    return self._fileno

                def flush(self):
                    if self._hConsole is None:
                        try:
                            self._stream.flush()
                        except Exception as e:
                            _complain("%s.flush: %r from %r" %
                                      (self.name, e, self._stream))
                            raise

                def write(self, text):
                    try:
                        if self._hConsole is None:
                            if isinstance(text, unicode):
                                text = text.encode('utf-8')
                            self._stream.write(text)
                        else:
                            if not isinstance(text, unicode):
                                text = str(text).decode('utf-8')
                            remaining = len(text)
                            while remaining:
                                n = DWORD(0)
                                # There is a shorter-than-documented limitation on the
                                # length of the string passed to WriteConsoleW (see
                                # <http://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232>.
                                retval = WriteConsoleW(self._hConsole, text,
                                                       min(remaining, 10000),
                                                       byref(n), None)
                                if retval == 0 or n.value == 0:
                                    raise IOError(
                                        "WriteConsoleW returned %r, n.value = %r"
                                        % (retval, n.value))
                                remaining -= n.value
                                if not remaining:
                                    break
                                text = text[n.value:]
                    except Exception as e:
                        _complain("%s.write: %r" % (self.name, e))
                        raise

                def writelines(self, lines):
                    try:
                        for line in lines:
                            self.write(line)
                    except Exception as e:
                        _complain("%s.writelines: %r" % (self.name, e))
                        raise

            if real_stdout:
                sys.stdout = UnicodeOutput(hStdout, None, STDOUT_FILENO,
                                           '<Unicode console stdout>')
            else:
                sys.stdout = UnicodeOutput(None, sys.stdout, old_stdout_fileno,
                                           '<Unicode redirected stdout>')

            if real_stderr:
                sys.stderr = UnicodeOutput(hStderr, None, STDERR_FILENO,
                                           '<Unicode console stderr>')
            else:
                sys.stderr = UnicodeOutput(None, sys.stderr, old_stderr_fileno,
                                           '<Unicode redirected stderr>')
    except Exception as e:
        _complain("exception %r while fixing up sys.stdout and sys.stderr" %
                  (e, ))
Exemplo n.º 12
0
    def notify(self, msg):
        """Show a desktop notification with the supplied message

        On Linux and Mac, this will show a desktop notification with the message,
        but on Windows we can only flash the screen.
        """
        moz_nospam = os.environ.get('MOZ_NOSPAM')
        if moz_nospam:
            return

        try:
            if sys.platform.startswith('darwin'):
                notifier = which('terminal-notifier')
                if not notifier:
                    raise Exception('Install terminal-notifier to get '
                                    'a notification when the build finishes.')
                self.run_process([
                    notifier, '-title', 'Mozilla Build System', '-group',
                    'mozbuild', '-message', msg
                ],
                                 ensure_exit_code=False)
            elif sys.platform.startswith('win'):
                from ctypes import Structure, windll, POINTER, sizeof, WINFUNCTYPE
                from ctypes.wintypes import DWORD, HANDLE, BOOL, UINT

                class FLASHWINDOW(Structure):
                    _fields_ = [("cbSize", UINT), ("hwnd", HANDLE),
                                ("dwFlags", DWORD), ("uCount", UINT),
                                ("dwTimeout", DWORD)]

                FlashWindowExProto = WINFUNCTYPE(BOOL, POINTER(FLASHWINDOW))
                FlashWindowEx = FlashWindowExProto(
                    ("FlashWindowEx", windll.user32))
                FLASHW_CAPTION = 0x01
                FLASHW_TRAY = 0x02
                FLASHW_TIMERNOFG = 0x0C

                # GetConsoleWindows returns NULL if no console is attached. We
                # can't flash nothing.
                console = windll.kernel32.GetConsoleWindow()
                if not console:
                    return

                params = FLASHWINDOW(
                    sizeof(FLASHWINDOW), console,
                    FLASHW_CAPTION | FLASHW_TRAY | FLASHW_TIMERNOFG, 3, 0)
                FlashWindowEx(params)
            else:
                notifier = which('notify-send')
                if not notifier:
                    raise Exception(
                        'Install notify-send (usually part of '
                        'the libnotify package) to get a notification when '
                        'the build finishes.')
                self.run_process([
                    notifier, '--app-name=Mozilla Build System',
                    'Mozilla Build System', msg
                ],
                                 ensure_exit_code=False)
        except Exception as e:
            self.log(logging.WARNING, 'notifier-failed', {'error': str(e)},
                     'Notification center failed: {error}')
Exemplo n.º 13
0
def get_unicode_console():
    """
    Get Unicode console objects.

    @return: stdin, stdout, stderr, argv
    @rtype: tuple
    """
    # 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
    # <https://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>.

    global stdin, stdout, stderr, argv

    if not OSWIN32:
        return stdin, stdout, stderr, argv

    try:
        # <https://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx>
        # HANDLE WINAPI GetStdHandle(DWORD nStdHandle);
        # returns INVALID_HANDLE_VALUE, NULL, or a valid handle
        #
        # <https://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx>
        # DWORD WINAPI GetFileType(DWORD hFile);
        #
        # <https://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx>
        # BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode);

        GetStdHandle = WINFUNCTYPE(HANDLE,
                                   DWORD)(('GetStdHandle', windll.kernel32))
        STD_INPUT_HANDLE = DWORD(-10)
        STD_OUTPUT_HANDLE = DWORD(-11)
        STD_ERROR_HANDLE = DWORD(-12)
        GetFileType = WINFUNCTYPE(DWORD,
                                  DWORD)(('GetFileType', windll.kernel32))
        FILE_TYPE_CHAR = 0x0002
        FILE_TYPE_REMOTE = 0x8000
        GetConsoleMode = (WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
            ("GetConsoleMode", windll.kernel32)))
        INVALID_HANDLE_VALUE = DWORD(-1).value

        def not_a_console(handle):
            """Return whether the handle is not to a console."""
            if handle == INVALID_HANDLE_VALUE or handle is None:
                return True
            return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
                    or GetConsoleMode(handle, byref(DWORD())) == 0)

        old_stdin_fileno = old_fileno('in')
        old_stdout_fileno = old_fileno('out')
        old_stderr_fileno = old_fileno('err')

        STDIN_FILENO = 0
        STDOUT_FILENO = 1
        STDERR_FILENO = 2
        real_stdin = (old_stdin_fileno == STDIN_FILENO)
        real_stdout = (old_stdout_fileno == STDOUT_FILENO)
        real_stderr = (old_stderr_fileno == STDERR_FILENO)

        if real_stdin:
            hStdin = GetStdHandle(STD_INPUT_HANDLE)
            if not_a_console(hStdin):
                real_stdin = False

        if real_stdout:
            hStdout = GetStdHandle(STD_OUTPUT_HANDLE)
            force_truetype_console(hStdout)
            if not_a_console(hStdout):
                real_stdout = False

        if real_stderr:
            hStderr = GetStdHandle(STD_ERROR_HANDLE)
            force_truetype_console(hStderr)
            if not_a_console(hStderr):
                real_stderr = False

        if real_stdout or real_stderr:
            if real_stdin:
                stdin = UnicodeInput(hStdin, name='<Unicode console stdin>')

            if real_stdout:
                stdout = UnicodeOutput(hStdout, sys.stdout, STDOUT_FILENO,
                                       '<Unicode console stdout>')
            else:
                stdout = UnicodeOutput(None, sys.stdout, old_stdout_fileno,
                                       '<Unicode redirected stdout>')

            if real_stderr:
                stderr = UnicodeOutput(hStderr, sys.stderr, STDERR_FILENO,
                                       '<Unicode console stderr>')
            else:
                stderr = UnicodeOutput(None, sys.stderr, old_stderr_fileno,
                                       '<Unicode redirected stderr>')
    except Exception as e:
        _complain(
            'exception {!r} while fixing up sys.stdout and sys.stderr'.format(
                e))

    if PY3:
        # no need to work around issue2128 since it's a Python 2 only issue
        return stdin, stdout, stderr, argv

    # While we're at it, let's unmangle the command-line arguments:

    # This works around <http://bugs.python.org/issue2128>.
    GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
    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('utf-8') for i in range(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(b"-") 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

    if argv == []:
        argv = [u'']

    return stdin, stdout, stderr, argv
Exemplo n.º 14
0
    PY3 = False

stdin = sys.stdin
stdout = sys.stdout
stderr = sys.stderr
argv = sys.argv

original_stderr = sys.stderr

if OSWIN32:
    from ctypes import WINFUNCTYPE, windll, POINTER, WinError
    from ctypes.wintypes import (BOOL, DWORD, HANDLE, LPCWSTR, LPWSTR, SHORT,
                                 ULONG, UINT, WCHAR)

try:
    ReadConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPVOID, DWORD, POINTER(DWORD),
                               LPVOID)(("ReadConsoleW", windll.kernel32))
    WriteConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD),
                                LPVOID)(("WriteConsoleW", windll.kernel32))
except NameError:
    ReadConsoleW = WriteConsoleW = None


class UnicodeInput(IOBase):
    """Unicode terminal input class."""
    def __init__(self, hConsole, name, bufsize=1024):
        """Initialize the input stream."""
        self._hConsole = hConsole
        self.bufsize = bufsize
        self.buffer = create_unicode_buffer(bufsize)
        self.name = name
        self.encoding = 'utf-8'
Exemplo n.º 15
0
                                 LPARAM, BOOL, HWND, POINT, RECT as RECT_BASE)
    from ctypes import (windll, WINFUNCTYPE, POINTER, c_int, c_longlong,
                        c_void_p, Structure, sizeof, byref, cast)

    class RECT(RECT_BASE):
        x = property(lambda self: self.left)
        y = property(lambda self: self.top)
        w = property(lambda self: self.right - self.left)
        h = property(lambda self: self.bottom - self.top)

    # check availability of RegisterTouchWindow
    if not hasattr(windll.user32, 'RegisterTouchWindow'):
        raise Exception('Unsupported Window version')

    LRESULT = LPARAM
    WNDPROC = WINFUNCTYPE(LRESULT, HWND, UINT, WPARAM, LPARAM)

    class TOUCHINPUT(Structure):
        _fields_ = [('x', LONG), ('y', LONG), ('pSource', HANDLE),
                    ('id', DWORD), ('flags', DWORD), ('mask', DWORD),
                    ('time', DWORD), ('extraInfo', POINTER(ULONG)),
                    ('size_x', DWORD), ('size_y', DWORD)]

        def size(self):
            return (self.size_x, self.size_y)

        def screen_x(self):
            return self.x / 100.0

        def screen_y(self):
            return self.y / 100.0
Exemplo n.º 16
0
from ctypes.wintypes import BOOL
from ctypes.wintypes import DWORD
from ctypes.wintypes import HANDLE

STD_OUTPUT_HANDLE = -11
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4


def bool_errcheck(result, func, args):
    if not result:
        raise WinError()
    return args


GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(
    ("GetStdHandle", windll.kernel32),
    ((1, "nStdHandle"), ),
)

GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
    ("GetConsoleMode", windll.kernel32),
    ((1, "hConsoleHandle"), (2, "lpMode")),
)
GetConsoleMode.errcheck = bool_errcheck

SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, DWORD)(
    ("SetConsoleMode", windll.kernel32),
    ((1, "hConsoleHandle"), (1, "dwMode")),
)
SetConsoleMode.errcheck = bool_errcheck

Exemplo n.º 17
0
class VCP:
    '''Collection of screen brightness related methods using the DDC/CI commands'''
    _MONITORENUMPROC = WINFUNCTYPE(BOOL, HMONITOR, HDC, POINTER(RECT), LPARAM)

    class _PHYSICAL_MONITOR(Structure):
        '''internal class, do not call'''
        _fields_ = [('handle', HANDLE),
                    ('description', WCHAR * 128)]

    @classmethod
    def iter_physical_monitors(cls) -> Iterable[ctypes.wintypes.HANDLE]:
        '''
        A generator to iterate through all physical monitors
        and then close them again afterwards, yielding their handles.
        It is not recommended to use this function unless you are familiar with `ctypes` and `windll`

        Yields:
            ctypes.wintypes.HANDLE

        Raises:
            ctypes.WinError: upon failure to enumerate through the monitors

        Example:
            ```python
            import screen_brightness_control as sbc

            for monitor in sbc.windows.VCP.iter_physical_monitors():
                print(sbc.windows.VCP.get_monitor_caps(monitor))
            ```
        '''
        def callback(hmonitor, hdc, lprect, lparam):
            monitors.append(HMONITOR(hmonitor))
            return True

        monitors = []
        if not windll.user32.EnumDisplayMonitors(None, None, cls._MONITORENUMPROC(callback), None):
            raise WinError('EnumDisplayMonitors failed')
        for monitor in monitors:
            # Get physical monitor count
            count = DWORD()
            if not windll.dxva2.GetNumberOfPhysicalMonitorsFromHMONITOR(monitor, byref(count)):
                raise WinError()
            if count.value > 0:
                # Get physical monitor handles
                physical_array = (cls._PHYSICAL_MONITOR * count.value)()
                if not windll.dxva2.GetPhysicalMonitorsFromHMONITOR(monitor, count.value, physical_array):
                    raise WinError()
                for item in physical_array:
                    yield item.handle
                    windll.dxva2.DestroyPhysicalMonitor(item.handle)

    @classmethod
    def get_display_info(cls, display: Optional[Union[int, str]] = None) -> List[dict]:
        '''
        Returns a dictionary of info about all detected monitors or a selection of monitors

        Args:
            display (int or str): [*Optional*] the monitor to return info about.
                Pass in the serial number, name, model, edid or index

        Returns:
            list: list of dicts

        Example:
            ```python
            import screen_brightness_control as sbc

            # get the information about all monitors
            vcp_info = sbc.windows.VCP.get_display_info()
            print(vcp_info)
            # EG output: [{'name': 'BenQ GL2450H', ... }, {'name': 'Dell U2211H', ... }]

            # get information about a monitor with this specific model
            bnq_info = sbc.windows.VCP.get_display_info('GL2450H')
            # EG output: {'name': 'BenQ GL2450H', 'model': 'GL2450H', ... }
            ```
        '''
        try:
            info = __cache__.get('vcp_monitor_info')
        except Exception:
            info = [i for i in get_display_info() if i['method'] == cls]
            __cache__.store('vcp_monitor_info', info)
        if display is not None:
            info = filter_monitors(display=display, haystack=info)
        return info

    @staticmethod
    def get_monitor_caps(monitor: ctypes.wintypes.HANDLE) -> str:
        '''
        Fetches and returns the VCP capabilities string of a monitor.
        This function takes anywhere from 1-2 seconds to run

        Args:
            monitor: a monitor handle as returned by `VCP.iter_physical_monitors()`

        Returns:
            str: a string of the monitor's capabilities

        Examples:
            ```python
            import screen_brightness_control as sbc

            for monitor in sbc.windows.VCP.iter_physical_monitors():
                print(sbc.windows.VCP.get_monitor_caps(monitor))
            # EG output: '(prot(monitor)type(LCD)model(GL2450HM)cmds(01 02 03 07 0C F3)vcp(02...)'
            ```
        '''
        caps_string_length = DWORD()
        if not windll.dxva2.GetCapabilitiesStringLength(monitor, ctypes.byref(caps_string_length)):
            return
        caps_string = (ctypes.c_char * caps_string_length.value)()
        if not windll.dxva2.CapabilitiesRequestAndCapabilitiesReply(monitor, caps_string, caps_string_length):
            return
        return caps_string.value.decode('ASCII')

    @classmethod
    def get_display_names(cls) -> List[str]:
        '''
        Return the names of each detected monitor

        Returns:
            list: list of strings

        Example:
            ```python
            import screen_brightness_control as sbc

            names = sbc.windows.VCP.get_display_names()
            print(names)
            # EG output: ['BenQ GL2450H', 'Dell U2211H']
            ```
        '''
        return [i['name'] for i in cls.get_display_info()]

    @classmethod
    def get_brightness(cls, display: Optional[Union[int, str]] = None) -> List[int]:
        '''
        Retrieve the brightness of all connected displays using the `ctypes.windll` API

        Args:
            display (int or str): The specific display you wish to query.
                Can be index, name, model, serial or edid string.
                `int` is faster as it isn't passed to `filter_monitors` to be matched against.
                `str` is slower as it is passed to `filter_monitors` to match to a display.

        Returns:
            list: list of ints (0 to 100)

        Examples:
            ```python
            import screen_brightness_control as sbc

            # Get the brightness for all detected displays
            current_brightness = sbc.windows.VCP.get_brightness()
            print('There are', len(current_brightness), 'detected displays')

            # Get the brightness for the primary display
            primary_brightness = sbc.windows.VCP.get_brightness(display = 0)[0]

            # Get the brightness for a secondary display
            secondary_brightness = sbc.windows.VCP.get_brightness(display = 1)[0]

            # Get the brightness for a display with the model 'GL2450H'
            benq_brightness = sbc.windows.VCP.get_brightness(display = 'GL2450H')[0]
            ```
        '''
        # filter monitors even if display kwarg is not specified due to oddities surrounding issues #7 and #8
        # https://github.com/Crozzers/screen_brightness_control/issues/7
        # https://github.com/Crozzers/screen_brightness_control/issues/8
        # essentially, we get 'ghost' monitors showing up here that cannot actually
        # be adjusted (even if no error gets raised) so we use this to filter out
        # such ghost monitors by only attempting to get the brightness for valid monitors
        # (determined by VCP.get_display_info)
        # yes, it does add an unnecessary function call but that's only if you're using this module low-level.
        # Top-level functions always end up specifying the display kwarg anyway
        if type(display) == int:
            indexes = [display]
        else:
            indexes = [i['index'] for i in filter_monitors(display=display, haystack=cls.get_display_info())]

        count = 0
        values = []
        for m in cls.iter_physical_monitors():
            try:
                v = __cache__.get(f'vcp_brightness_{count}')
            except Exception:
                cur_out = DWORD()
                for _ in range(10):
                    if windll.dxva2.GetVCPFeatureAndVCPFeatureReply(HANDLE(m), BYTE(0x10), None, byref(cur_out), None):
                        v = cur_out.value
                        break
                    else:
                        time.sleep(0.02)
                        v = None
                del(cur_out)
            if v is not None:
                if count in indexes:
                    try:
                        __cache__.store(f'vcp_brightness_{count}', v, expires=0.1)
                    except IndexError:
                        pass
                    values.append(v)
                    if count >= max(indexes):
                        break
            count += 1

        return values

    @classmethod
    def set_brightness(
        cls, value: int,
        display: Optional[Union[int, str]] = None,
        no_return: bool = False
    ) -> Union[List[int], None]:
        '''
        Sets the brightness for all connected displays using the `ctypes.windll` API

        Args:
            display (int or str): The specific display you wish to query.
                Can be index, name, model, serial or edid string.
                `int` is faster as it isn't passed to `filter_monitors` to be matched against.
                `str` is slower as it is passed to `filter_monitors` to match to a display.
            no_return (bool): if set to `True` this function will return `None`

        Returns:
            list: list of ints (0 to 100) (the result of `VCP.get_brightness`) if `no_return` is False
            None: if `no_return` is True

        Examples:
            ```python
            import screen_brightness_control as sbc

            # Set the brightness for all detected displays to 50%
            sbc.windows.VCP.set_brightness(50)

            # Set the brightness for the primary display to 75%
            sbc.windows.VCP.set_brightness(75, display = 0)

            # Set the brightness for a secondary display to 25%
            sbc.windows.VCP.set_brightness(25, display = 1)

            # Set the brightness for a display with the model 'GL2450H' to 100%
            sbc.windows.VCP.set_brightness(100, display = 'GL2450H')
            ```
        '''
        if type(display) == int:
            indexes = [display]
        else:
            # see VCP.set_brightness for the explanation for why we always gather this list
            indexes = [i['index'] for i in filter_monitors(display=display, haystack=cls.get_display_info())]

        __cache__.expire(startswith='vcp_brightness_')

        count = 0
        for m in cls.iter_physical_monitors():
            if display is None or (count in indexes):
                for _ in range(10):
                    if windll.dxva2.SetVCPFeature(HANDLE(m), BYTE(0x10), DWORD(value)):
                        break
                    else:
                        time.sleep(0.02)
            count += 1
        return cls.get_brightness(display=display) if not no_return else None
Exemplo n.º 18
0
LPVOID = c_void_p
LPBYTE = POINTER(BYTE)
LPDWORD = POINTER(DWORD)


def ErrCheckBool(result, func, args):
    """errcheck function for Windows functions that return a BOOL True
    on success"""
    if not result:
        raise WinError()
    return args


# CloseHandle()

CloseHandleProto = WINFUNCTYPE(BOOL, HANDLE)
CloseHandle = CloseHandleProto(("CloseHandle", windll.kernel32))
CloseHandle.errcheck = ErrCheckBool

# AutoHANDLE


class AutoHANDLE(HANDLE):
    """Subclass of HANDLE which will call CloseHandle() on deletion."""
    def Close(self):
        if self.value:
            CloseHandle(self)
            self.value = 0

    def __del__(self):
        self.Close()
Exemplo n.º 19
0
def ishd(p1,t1,p2):
    ishdprototype=WINFUNCTYPE(c_double,c_double,c_double,c_double)
    f=ishdprototype(("shd",windll.seuif97),)
    result=f(p1,t1,p2)
    return result
Exemplo n.º 20
0
PM_REMOVE = 0x0001
WM_QUIT = 0x0012


class _Msg(Structure):
    _fields_ = [
        ('hwnd', c_ulong),
        ('message', c_ulong),
        ('wParam', c_ulong),
        ('lParam', c_ulong),
        ('time', c_ulong),
        ('x', c_ulong),
        ('y', c_ulong),
    ]

WNDPROC = WINFUNCTYPE(c_int, c_ulong, c_ulong, c_ulong, c_ulong)


class _WndClassEx(Structure):
    _fields_ = [
        ('size', c_uint),
        ('style', c_uint),
        ('wndproc', WNDPROC),
        ('cls_extra', c_int),
        ('wnd_extra', c_int),
        ('instance', c_ulong),
        ('icon', c_ulong),
        ('cursor', c_ulong),
        ('background', c_ulong),
        ('menu_name', c_char_p),
        ('class_name', c_char_p),
Exemplo n.º 21
0
                values.append("{}={}".format(k, v))
            values.append("")
            self._as_parameter_ = LPCWSTR("\0".join(values))


# Error Messages we need to watch for go here

# https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx (0 - 499)
ERROR_ACCESS_DENIED = 5
ERROR_INVALID_PARAMETER = 87

# http://msdn.microsoft.com/en-us/library/ms681388%28v=vs.85%29.aspx (500 - 999)
ERROR_ABANDONED_WAIT_0 = 735

# GetLastError()
GetLastErrorProto = WINFUNCTYPE(DWORD)  # Return Type
GetLastErrorFlags = ()
GetLastError = GetLastErrorProto(("GetLastError", windll.kernel32),
                                 GetLastErrorFlags)

# CreateProcess()

CreateProcessProto = WINFUNCTYPE(
    BOOL,  # Return type
    LPCWSTR,  # lpApplicationName
    LPWSTR,  # lpCommandLine
    LPVOID,  # lpProcessAttributes
    LPVOID,  # lpThreadAttributes
    BOOL,  # bInheritHandles
    DWORD,  # dwCreationFlags
    LPVOID,  # lpEnvironment
Exemplo n.º 22
0
    def __init__(self, _class):
        if isinstance(_class, six.string_types):
            assert _class in self.mapping, \
                'Class should be one of %s; you gave %s' % (self.mapping, _class)
            _class = self.mapping[_class]
        assert _class in self.structures, \
            'Class should be one of %s; you gave %s' % (self.structures, _class)
        self.code = _class
        self.info = self.structures[_class]()


QueryInformationJobObjectProto = WINFUNCTYPE(
    BOOL,  # Return type
    HANDLE,  # hJob
    DWORD,  # JobObjectInfoClass
    LPVOID,  # lpJobObjectInfo
    DWORD,  # cbJobObjectInfoLength
    LPDWORD  # lpReturnLength
)

QueryInformationJobObjectFlags = ((1, 'hJob'), (1, 'JobObjectInfoClass'),
                                  (1, 'lpJobObjectInfo'),
                                  (1, 'cbJobObjectInfoLength'),
                                  (1, 'lpReturnLength', None))

_QueryInformationJobObject = QueryInformationJobObjectProto(
    ('QueryInformationJobObject', windll.kernel32),
    QueryInformationJobObjectFlags)


class SubscriptableReadOnlyStruct(object):
Exemplo n.º 23
0
from ctypes import WINFUNCTYPE, HRESULT, POINTER, Structure, c_void_p, cast, pointer
import traceback
from .inspectable import IUnknown
from .types import REFGUID, VOIDPP, ULONG, GUID, E_NOINTERFACE, S_OK, E_FAIL

_refmap = {}

_typeof_QueryInterface = WINFUNCTYPE(HRESULT, c_void_p, REFGUID, VOIDPP)
_typeof_AddRef = WINFUNCTYPE(ULONG, c_void_p)
_typeof_Release = WINFUNCTYPE(ULONG, c_void_p)


class _impl_delegate_vtbl(Structure):
    _fields_ = [('QueryInterface', _typeof_QueryInterface),
                ('AddRef', _typeof_AddRef), ('Release', _typeof_Release),
                ('Invoke', c_void_p)]


class _impl_delegate(Structure):
    _fields_ = [('vtbl', POINTER(_impl_delegate_vtbl))]


def proto(*argtypes, retval=None):
    if retval is not None:
        argtypes = (*argtypes, POINTER(retval))
    proto = WINFUNCTYPE(HRESULT, *argtypes)
    proto._retval = retval
    return proto


IID_IAgileObject = GUID('94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90')
Exemplo n.º 24
0
class _WinHttpRequest(c_void_p):
    '''
    Maps the Com API to Python class functions. Not all methods in
    IWinHttpWebRequest are mapped - only the methods we use.
    '''
    _AddRef = WINFUNCTYPE(c_long) \
        (1, 'AddRef')
    _Release = WINFUNCTYPE(c_long) \
        (2, 'Release')
    _SetProxy = WINFUNCTYPE(HRESULT,
                            HTTPREQUEST_PROXY_SETTING,
                            VARIANT,
                            VARIANT) \
        (7, 'SetProxy')
    _SetCredentials = WINFUNCTYPE(HRESULT,
                                  BSTR,
                                  BSTR,
                                  HTTPREQUEST_SETCREDENTIALS_FLAGS) \
        (8, 'SetCredentials')
    _Open = WINFUNCTYPE(HRESULT, BSTR, BSTR, VARIANT) \
        (9, 'Open')
    _SetRequestHeader = WINFUNCTYPE(HRESULT, BSTR, BSTR) \
        (10, 'SetRequestHeader')
    _GetResponseHeader = WINFUNCTYPE(HRESULT, BSTR, POINTER(c_void_p)) \
        (11, 'GetResponseHeader')
    _GetAllResponseHeaders = WINFUNCTYPE(HRESULT, POINTER(c_void_p)) \
        (12, 'GetAllResponseHeaders')
    _Send = WINFUNCTYPE(HRESULT, VARIANT) \
        (13, 'Send')
    _Status = WINFUNCTYPE(HRESULT, POINTER(c_long)) \
        (14, 'Status')
    _StatusText = WINFUNCTYPE(HRESULT, POINTER(c_void_p)) \
        (15, 'StatusText')
    _ResponseText = WINFUNCTYPE(HRESULT, POINTER(c_void_p)) \
        (16, 'ResponseText')
    _ResponseBody = WINFUNCTYPE(HRESULT, POINTER(VARIANT)) \
        (17, 'ResponseBody')
    _ResponseStream = WINFUNCTYPE(HRESULT, POINTER(VARIANT)) \
        (18, 'ResponseStream')
    _WaitForResponse = WINFUNCTYPE(HRESULT, VARIANT, POINTER(c_ushort)) \
        (21, 'WaitForResponse')
    _Abort = WINFUNCTYPE(HRESULT) \
        (22, 'Abort')
    _SetTimeouts = WINFUNCTYPE(HRESULT, c_long, c_long, c_long, c_long) \
        (23, 'SetTimeouts')
    _SetClientCertificate = WINFUNCTYPE(HRESULT, BSTR) \
        (24, 'SetClientCertificate')

    def open(self, method, url):
        '''
        Opens the request.

        method:
            the request VERB 'GET', 'POST', etc.
        url:
            the url to connect
        '''
        flag = VARIANT.create_bool_false()
        _method = BSTR(method)
        _url = BSTR(url)
        _WinHttpRequest._Open(self, _method, _url, flag)

    def set_timeout(self, timeout_in_seconds):
        ''' Sets up the timeout for the request. '''
        timeout_in_ms = int(timeout_in_seconds * 1000)
        _WinHttpRequest._SetTimeouts(self, 0, timeout_in_ms, timeout_in_ms,
                                     timeout_in_ms)

    def set_request_header(self, name, value):
        ''' Sets the request header. '''

        _name = BSTR(name)
        _value = BSTR(value)
        _WinHttpRequest._SetRequestHeader(self, _name, _value)

    def get_all_response_headers(self):
        ''' Gets back all response headers. '''

        bstr_headers = c_void_p()
        _WinHttpRequest._GetAllResponseHeaders(self, byref(bstr_headers))
        bstr_headers = ctypes.cast(bstr_headers, c_wchar_p)
        headers = bstr_headers.value
        _SysFreeString(bstr_headers)
        return headers

    def send(self, request=None):
        ''' Sends the request body. '''

        # Sends VT_EMPTY if it is GET, HEAD request.
        if request is None:
            var_empty = VARIANT.create_empty()
            _WinHttpRequest._Send(self, var_empty)
        else:  # Sends request body as SAFEArray.
            _request = VARIANT.create_safearray_from_str(request)
            _WinHttpRequest._Send(self, _request)

    def status(self):
        ''' Gets status of response. '''

        status = c_long()
        _WinHttpRequest._Status(self, byref(status))
        return int(status.value)

    def status_text(self):
        ''' Gets status text of response. '''

        bstr_status_text = c_void_p()
        _WinHttpRequest._StatusText(self, byref(bstr_status_text))
        bstr_status_text = ctypes.cast(bstr_status_text, c_wchar_p)
        status_text = bstr_status_text.value
        _SysFreeString(bstr_status_text)
        return status_text

    def response_body(self):
        '''
        Gets response body as a SAFEARRAY and converts the SAFEARRAY to str.
        '''
        var_respbody = VARIANT()
        _WinHttpRequest._ResponseBody(self, byref(var_respbody))
        if var_respbody.is_safearray_of_bytes():
            respbody = var_respbody.str_from_safearray()
            return respbody
        else:
            return ''

    def set_client_certificate(self, certificate):
        '''Sets client certificate for the request. '''
        _certificate = BSTR(certificate)
        _WinHttpRequest._SetClientCertificate(self, _certificate)

    def set_tunnel(self, host, port):
        ''' Sets up the host and the port for the HTTP CONNECT Tunnelling.'''
        url = host
        if port:
            url = url + u':' + port

        var_host = VARIANT.create_bstr_from_str(url)
        var_empty = VARIANT.create_empty()

        _WinHttpRequest._SetProxy(self, HTTPREQUEST_PROXYSETTING_PROXY,
                                  var_host, var_empty)

    def set_proxy_credentials(self, user, password):
        _WinHttpRequest._SetCredentials(self, BSTR(user), BSTR(password),
                                        HTTPREQUEST_SETCREDENTIALS_FOR_PROXY)

    def __del__(self):
        if self.value is not None:
            _WinHttpRequest._Release(self)
Exemplo n.º 25
0
        info = self._widgets[ref]
        if info[0]:
            self._update_widget(False, widget, info)

        del self._widgets[ref]


###############################################################################
# Wrapped Functions
###############################################################################

pythonapi.PyCObject_AsVoidPtr.restype = c_void_p
pythonapi.PyCObject_AsVoidPtr.argtypes = [py_object]

prototype = WINFUNCTYPE(c_int, c_int, POINTER(MARGINS))
params = (1, "hWnd", 0), (1, "pMarInset", MARGINS(-1, -1, -1, -1))
_DwmExtendFrameIntoClientArea = prototype(
    ("DwmExtendFrameIntoClientArea", windll.dwmapi), params)

prototype = WINFUNCTYPE(c_int, c_int, POINTER(DWM_BLURBEHIND))
params = (1, "hWnd", 0), (1, "pBlurBehind", 0)
_DwmEnableBlurBehindWindow = prototype(
    ("DwmEnableBlurBehindWindow", windll.dwmapi), params)

prototype = WINFUNCTYPE(c_int, POINTER(DWORD), POINTER(c_bool))
params = (2, "pcrColorization", DWORD(0)), (1, "pfOpaqueBlend", c_bool(False))
_DwmGetColorizationColor = prototype(
    ("DwmGetColorizationColor", windll.dwmapi), params)

prototype = WINFUNCTYPE(c_int, POINTER(c_bool))
Exemplo n.º 26
0
    (0x400e,
     'A server-side transaction was attempted on a conversation terminated by the client, or the server terminated before completing a transaction.'
     ),  # noqa
    'SYS_ERROR': (0x400f, 'An internal error has occurred in the DDEML.'),
    'UNADVACKTIMEOUT':
    (0x4010, 'A request to end an advise transaction has timed out.'),
    'UNFOUND_QUEUE_ID':
    (0x4011,
     'An invalid transaction identifier was passed to a DDEML function. Once the application has returned from an XTYP_XACT_COMPLETE callback, the transaction identifier for that callback function is no longer valid.'
     ),  # noqa
}
DML_ERROR_TEXT = {code: text for (code, text) in itervalues(DML_ERRORS)}

user32 = windll.user32

DDECALLBACK = WINFUNCTYPE(HDDEDATA, UINT, UINT, HCONV, HSZ, HSZ, HDDEDATA,
                          ULONG_PTR, ULONG_PTR)
APPCMD_CLIENTONLY = 0x10
CP_WINUNICODE = 1200
# See windows/ddeml.h for declaration of struct CONVCONTEXT
PCONVCONTEXT = c_void_p
XCLASS_FLAGS = 0x4000
XTYP_EXECUTE = (0x0050 | XCLASS_FLAGS)


class DDEError(ValueError):
    pass


def init_errcheck(result, func, args):
    if result != 0:
        raise DDEError('Failed to initialize DDE client with return code: %x' %
Exemplo n.º 27
0
    def _shutdown_with_windows_restart_manager(self, pid):
        """Shut down a process using the Windows Restart Manager.

        When Windows shuts down, it uses a protocol including the
        WM_QUERYENDSESSION and WM_ENDSESSION messages to give
        applications a chance to shut down safely. The best way to
        simulate this is via the Restart Manager, which allows a process
        (such as an installer) to use the same mechanism to shut down
        any other processes which are using registered resources.

        This function starts a Restart Manager session, registers the
        process as a resource, and shuts down the process.

        :param pid: The process id (int) of the process to shutdown

        :raises: WindowsError: if a Windows API call fails
        """
        import ctypes
        from ctypes import Structure, POINTER, WINFUNCTYPE, windll, pointer, WinError
        from ctypes.wintypes import HANDLE, DWORD, BOOL, WCHAR, UINT, ULONG, LPCWSTR

        # set up Windows SDK types
        OpenProcess = windll.kernel32.OpenProcess
        OpenProcess.restype = HANDLE
        OpenProcess.argtypes = [
            DWORD,  # dwDesiredAccess
            BOOL,  # bInheritHandle
            DWORD,
        ]  # dwProcessId
        PROCESS_QUERY_INFORMATION = 0x0400

        class FILETIME(Structure):
            _fields_ = [("dwLowDateTime", DWORD), ("dwHighDateTime", DWORD)]

        LPFILETIME = POINTER(FILETIME)

        GetProcessTimes = windll.kernel32.GetProcessTimes
        GetProcessTimes.restype = BOOL
        GetProcessTimes.argtypes = [
            HANDLE,  # hProcess
            LPFILETIME,  # lpCreationTime
            LPFILETIME,  # lpExitTime
            LPFILETIME,  # lpKernelTime
            LPFILETIME,
        ]  # lpUserTime

        ERROR_SUCCESS = 0

        class RM_UNIQUE_PROCESS(Structure):
            _fields_ = [("dwProcessId", DWORD), ("ProcessStartTime", FILETIME)]

        RmStartSession = windll.rstrtmgr.RmStartSession
        RmStartSession.restype = DWORD
        RmStartSession.argtypes = [
            POINTER(DWORD),  # pSessionHandle
            DWORD,  # dwSessionFlags
            POINTER(WCHAR),
        ]  # strSessionKey

        class GUID(ctypes.Structure):
            _fields_ = [
                ("Data1", ctypes.c_ulong),
                ("Data2", ctypes.c_ushort),
                ("Data3", ctypes.c_ushort),
                ("Data4", ctypes.c_ubyte * 8),
            ]

        CCH_RM_SESSION_KEY = ctypes.sizeof(GUID) * 2

        RmRegisterResources = windll.rstrtmgr.RmRegisterResources
        RmRegisterResources.restype = DWORD
        RmRegisterResources.argtypes = [
            DWORD,  # dwSessionHandle
            UINT,  # nFiles
            POINTER(LPCWSTR),  # rgsFilenames
            UINT,  # nApplications
            POINTER(RM_UNIQUE_PROCESS),  # rgApplications
            UINT,  # nServices
            POINTER(LPCWSTR),
        ]  # rgsServiceNames

        RM_WRITE_STATUS_CALLBACK = WINFUNCTYPE(None, UINT)
        RmShutdown = windll.rstrtmgr.RmShutdown
        RmShutdown.restype = DWORD
        RmShutdown.argtypes = [
            DWORD,  # dwSessionHandle
            ULONG,  # lActionFlags
            RM_WRITE_STATUS_CALLBACK,
        ]  # fnStatus

        RmEndSession = windll.rstrtmgr.RmEndSession
        RmEndSession.restype = DWORD
        RmEndSession.argtypes = [DWORD]  # dwSessionHandle

        # Get the info needed to uniquely identify the process
        hProc = OpenProcess(PROCESS_QUERY_INFORMATION, False, pid)
        if not hProc:
            raise WinError()

        creationTime = FILETIME()
        exitTime = FILETIME()
        kernelTime = FILETIME()
        userTime = FILETIME()
        if not GetProcessTimes(
                hProc,
                pointer(creationTime),
                pointer(exitTime),
                pointer(kernelTime),
                pointer(userTime),
        ):
            raise WinError()

        # Start the Restart Manager Session
        dwSessionHandle = DWORD()
        sessionKeyType = WCHAR * (CCH_RM_SESSION_KEY + 1)
        sessionKey = sessionKeyType()
        if RmStartSession(pointer(dwSessionHandle), 0,
                          sessionKey) != ERROR_SUCCESS:
            raise WinError()

        try:
            UProcs_count = 1
            UProcsArrayType = RM_UNIQUE_PROCESS * UProcs_count
            UProcs = UProcsArrayType(RM_UNIQUE_PROCESS(pid, creationTime))

            # Register the process as a resource
            if (RmRegisterResources(dwSessionHandle, 0, None, UProcs_count,
                                    UProcs, 0, None) != ERROR_SUCCESS):
                raise WinError()

            # Shut down all processes using registered resources
            if (RmShutdown(dwSessionHandle, 0,
                           ctypes.cast(None, RM_WRITE_STATUS_CALLBACK)) !=
                    ERROR_SUCCESS):
                raise WinError()

        finally:
            RmEndSession(dwSessionHandle)
Exemplo n.º 28
0
def cwrap(name, restype, *args, **kw):
    params = (restype, ) + tuple(x.typ for x in args)
    paramflags = tuple(x.spec for x in args)
    func = WINFUNCTYPE(*params)((name, kw.get('lib', user32)), paramflags)
    func.errcheck = kw.get('errcheck', default_errcheck)
    return func
Exemplo n.º 29
0
else:
    from ctypes.wintypes import (ULONG, HANDLE, DWORD, LONG, UINT,
                                 WPARAM, LPARAM, BOOL)
    from ctypes import (windll, WINFUNCTYPE, POINTER,
                        c_int, Structure, sizeof, byref)
    from collections import deque
    from kivy.input.provider import MotionEventProvider
    from kivy.input.factory import MotionEventFactory

    # check availability of RegisterTouchWindow
    if not hasattr(windll.user32, 'RegisterTouchWindow'):
        raise Exception('Unsupported Window version')

    LRESULT = LPARAM
    WNDPROC = WINFUNCTYPE(LRESULT, HANDLE, UINT, WPARAM, LPARAM)

    class TOUCHINPUT(Structure):
        _fields_ = [
            ('x', LONG),
            ('y', LONG),
            ('pSource', HANDLE),
            ('id', DWORD),
            ('flags', DWORD),
            ('mask', DWORD),
            ('time', DWORD),
            ('extraInfo', POINTER(ULONG)),
            ('size_x', DWORD),
            ('size_y', DWORD)]

        def size(self):
Exemplo n.º 30
0
from xpra.util import envbool
from xpra.platform.win32 import constants as win32con
from xpra.platform.win32.common import (
    GetStdHandle,
    SetConsoleTitleA,
    GetConsoleScreenBufferInfo,
    MessageBoxA,
    GetLastError,
    kernel32,
)

STD_INPUT_HANDLE = DWORD(-10)
STD_OUTPUT_HANDLE = DWORD(-11)
STD_ERROR_HANDLE = DWORD(-12)
GetFileType = WINFUNCTYPE(DWORD, DWORD)(("GetFileType", kernel32))
FILE_TYPE_CHAR = 0x0002
FILE_TYPE_REMOTE = 0x8000
GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE,
                             POINTER(DWORD))(("GetConsoleMode", kernel32))
INVALID_HANDLE_VALUE = DWORD(-1).value
STDOUT_FILENO = 1
STDERR_FILENO = 2
WriteConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD),
                            LPVOID)(("WriteConsoleW", kernel32))

GetConsoleCP = kernel32.GetConsoleCP

#redirect output if we're not running from a console:
frozen = getattr(sys, 'frozen', False)
REDIRECT_OUTPUT = envbool("XPRA_REDIRECT_OUTPUT", frozen is True
Exemplo n.º 31
0
        return [
            _Mouse.MOUSEEVENTF_LEFTDOWN, _Mouse.MOUSEEVENTF_MIDDLEDOWN,
            _Mouse.MOUSEEVENTF_RIGHTDOWN
        ][button - 1]

    def _map_button_up(self, button):
        assert button in [
            _Mouse.LEFT_BUTTON, _Mouse.MIDDLE_BUTTON, _Mouse.RIGHT_BUTTON
        ]
        return [
            _Mouse.MOUSEEVENTF_LEFTUP, _Mouse.MOUSEEVENTF_MIDDLEUP,
            _Mouse.MOUSEEVENTF_RIGHTUP
        ][button - 1]


_EnumWindowsProc = WINFUNCTYPE(BOOL, HWND, LPARAM)


def hwnd_to_pid(hwnd):
    pid = DWORD()
    _USER32.GetWindowThreadProcessId(int(hwnd), byref(pid))
    return pid.value


class Process(object):
    def __init__(self, pid):
        self.__pid = int(pid)

    @property
    def pid(self):
        return self.__pid
Exemplo n.º 32
0
    # 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);

        GetStdHandle = WINFUNCTYPE(HANDLE,
                                   DWORD)(("GetStdHandle", windll.kernel32))
        STD_OUTPUT_HANDLE = DWORD(-11)
        STD_ERROR_HANDLE = DWORD(-12)
        GetFileType = WINFUNCTYPE(DWORD,
                                  DWORD)(("GetFileType", windll.kernel32))
        FILE_TYPE_CHAR = 0x0002
        FILE_TYPE_REMOTE = 0x8000
        GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
            ("GetConsoleMode", windll.kernel32))
        INVALID_HANDLE_VALUE = DWORD(-1).value

        def not_a_console(handle):
            if handle == INVALID_HANDLE_VALUE or handle is None:
                return True
            return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
                    or GetConsoleMode(handle, byref(DWORD())) == 0)
Exemplo n.º 33
0
def cwrap(name, restype, *args, **kw):
    params=(restype,) + tuple(x.typ for x in args)
    paramflags=tuple(x.spec for x in args)
    func=WINFUNCTYPE(*params)((name, kw.get('lib', user32)), paramflags)
    func.errcheck=kw.get('errcheck', default_errcheck)
    return func
Exemplo n.º 34
0
        fptr.errcheck = errcheck
    return fptr

get_user32_api = lambda *args, **kwds: fptr_from_dll(user32, *args, **kwds)
get_kernel32_api = lambda *args, **kwds: fptr_from_dll(kernel32, *args, **kwds)

## ~~~ stdlib ~~~
strcpy = ctypes.cdll.msvcrt.strcpy
wcscpy = ctypes.cdll.msvcrt.wcscpy
wcscpy_s = ctypes.cdll.msvcrt.wcscpy_s

## ~~~ WindowsAPI ~~~
_en = errcheck_null

FindWindow = WINFUNCTYPE(HWND, HWND, LPCTSTR)(
    ('FindWindowW', user32),
    ((1, 'lpClassName'), (1, 'lpWindowName'))
    )
FindWindow.errcheck = _en

FindWindowEx = WINFUNCTYPE(HWND, HWND, HWND, LPCTSTR, LPCTSTR)(
    ('FindWindowExW', user32),
    ((1, 'hwndParent'),
     (1, 'hwndChildAfter'),
     (1, 'lpClassName'),
     (1, 'lpWindowName'),
     ))
FindWindowEx.errcheck = _en

GetClassNameW = WINFUNCTYPE(INT, HWND, LPTSTR, INT)(
    ('GetClassNameW', user32),
    ((1, 'hWnd'),