Exemplo n.º 1
0
def get_hardware_info():
    """
    system_profiler is not included in a 10.13 NetInstall NBI, therefore a new method of getting serial numer and model identifier is required
    Thanks to frogor's work on how to access IOKit from python: https://gist.github.com/pudquick/c7dd1262bd81a32663f0
    """

    IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')

    functions = [
        ("IOServiceGetMatchingService", b"II@"),
        ("IOServiceMatching", b"@*"),
        ("IORegistryEntryCreateCFProperty", b"@I@@I"),
    ]

    objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

    def io_key(keyname):
        return IORegistryEntryCreateCFProperty(
            IOServiceGetMatchingService(
                0, IOServiceMatching("IOPlatformExpertDevice")), keyname, None,
            0)

    hardware_info_plist = {}
    hardware_info_plist['serial_number'] = io_key("IOPlatformSerialNumber")
    hardware_info_plist['machine_model'] = str(io_key("model")).rstrip('\x00')

    return hardware_info_plist
Exemplo n.º 2
0
def get_serial():
  """Get system serial number."""
  # Credit to Mike Lynn
  IOKit_bundle = NSBundle.bundleWithIdentifier_("com.apple.framework.IOKit")
  functions = [
    ("IOServiceGetMatchingService", b"II@"),
    ("IOServiceMatching", b"@*"),
    ("IORegistryEntryCreateCFProperty", b"@I@@I")
  ]
  objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

  kIOMasterPortDefault = 0
  kIOPlatformSerialNumberKey = 'IOPlatformSerialNumber'
  kCFAllocatorDefault = None

  platformExpert = IOServiceGetMatchingService(
    kIOMasterPortDefault,
    IOServiceMatching("IOPlatformExpertDevice")
  )
  serial = IORegistryEntryCreateCFProperty(
    platformExpert,
    kIOPlatformSerialNumberKey,
    kCFAllocatorDefault,
    0
  )
  return serial
Exemplo n.º 3
0
def WMEnable(name="Python"):
    if isinstance(name, unicode):
        name = name.encode("utf8")
    mainBundle = NSBundle.mainBundle()
    bPath = os.path.split(os.path.split(os.path.split(sys.executable)[0])[0])[0]
    if mainBundle.bundlePath() == bPath:
        return True
    bndl = NSBundle.bundleWithPath_(objc.pathForFramework("/System/Library/Frameworks/ApplicationServices.framework"))
    if bndl is None:
        print >>sys.stderr, "ApplicationServices missing"
        return False
    d = {}
    objc.loadBundleFunctions(bndl, d, FUNCTIONS)
    for (fn, sig) in FUNCTIONS:
        if fn not in d:
            print >>sys.stderr, "Missing", fn
            return False
    err, psn = d["GetCurrentProcess"]()
    if err:
        print >>sys.stderr, "GetCurrentProcess", (err, psn)
        return False
    err = d["CPSSetProcessName"](psn, name)
    if err:
        print >>sys.stderr, "CPSSetProcessName", (err, psn)
        return False
    err = d["CPSEnableForegroundOperation"](psn)
    if err:
        # print >>sys.stderr, 'CPSEnableForegroundOperation', (err, psn)
        return False
    err = d["SetFrontProcess"](psn)
    if err:
        print >>sys.stderr, "SetFrontProcess", (err, psn)
        return False
    return True
Exemplo n.º 4
0
def WMEnable(name=None):
    if name is None:
        name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    if isinstance(name, unicode):
        name = name.encode('utf-8')
    if not hasattr(objc, 'loadBundleFunctions'):
        return False
    bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework'))
    if bndl is None:
        print >>sys.stderr, 'ApplicationServices missing'
        return False
    d = {}
    app = NSApplication.sharedApplication()
    objc.loadBundleFunctions(bndl, d, FUNCTIONS)
    for (fn, sig) in FUNCTIONS:
        if fn not in d:
            print >>sys.stderr, 'Missing', fn
            return False
    err, psn = d['GetCurrentProcess']()
    if err:
        print >>sys.stderr, 'GetCurrentProcess', (err, psn)
        return False
    err = d['CPSSetProcessName'](psn, name)
    if err:
        print >>sys.stderr, 'CPSSetProcessName', (err, psn)
        return False
    err = d['CPSEnableForegroundOperation'](psn)
    if err:
        print >>sys.stderr, 'CPSEnableForegroundOperation', (err, psn)
        return False
    err = d['SetFrontProcess'](psn)
    if err:
        print >>sys.stderr, 'SetFrontProcess', (err, psn)
        return False
    return True
Exemplo n.º 5
0
def WMEnable(name='Python'):
    if isinstance(name, unicode):
        name = name.encode('utf8')
    mainBundle = NSBundle.mainBundle()
    bPath = os.path.split(os.path.split(os.path.split(sys.executable)[0])[0])[0]
    if mainBundle.bundlePath() == bPath:
        return True
    bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework'))
    if bndl is None:
        print('ApplicationServices missing', file=sys.stderr)
        return False
    d = {}
    objc.loadBundleFunctions(bndl, d, FUNCTIONS)
    for (fn, sig) in FUNCTIONS:
        if fn not in d:
            print('Missing', fn, file=sys.stderr)
            return False
    err, psn = d['GetCurrentProcess']()
    if err:
        print('GetCurrentProcess', (err, psn), file=sys.stderr)
        return False
    err = d['CPSSetProcessName'](psn, name)
    if err:
        print('CPSSetProcessName', (err, psn), file=sys.stderr)
        return False
    err = d['CPSEnableForegroundOperation'](psn)
    if err:
        #print >>sys.stderr, 'CPSEnableForegroundOperation', (err, psn)
        return False
    err = d['SetFrontProcess'](psn)
    if err:
        print('SetFrontProcess', (err, psn), file=sys.stderr)
        return False
    return True
Exemplo n.º 6
0
def WMEnable(name=None):
    if name is None:
        name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    if isinstance(name, six.unicode):
        name = name.encode("utf-8")
    if not hasattr(objc, "loadBundleFunctions"):
        return False
    bndl = NSBundle.bundleWithPath_(objc.pathForFramework("/System/Library/Frameworks/ApplicationServices.framework"))
    if bndl is None:
        print("ApplicationServices missing", file=sys.stderr)
        return False
    d = {}
    app = NSApplication.sharedApplication()
    objc.loadBundleFunctions(bndl, d, FUNCTIONS)
    for (fn, sig) in FUNCTIONS:
        if fn not in d:
            print("Missing", fn, file=sys.stderr)
            return False
    err, psn = d["GetCurrentProcess"]()
    if err:
        print("GetCurrentProcess", (err, psn), file=sys.stderr)
        return False
    err = d["CPSSetProcessName"](psn, name)
    if err:
        print("CPSSetProcessName", (err, psn), file=sys.stderr)
        return False
    err = d["CPSEnableForegroundOperation"](psn)
    if err:
        print("CPSEnableForegroundOperation", (err, psn))
        return False
    err = d["SetFrontProcess"](psn)
    if err:
        print("SetFrontProcess", (err, psn))
        return False
    return True
Exemplo n.º 7
0
def get_serial():
  """Get system serial number."""
  # Credit to Mike Lynn
  IOKit_bundle = NSBundle.bundleWithIdentifier_("com.apple.framework.IOKit")
  functions = [
    ("IOServiceGetMatchingService", b"II@"),
    ("IOServiceMatching", b"@*"),
    ("IORegistryEntryCreateCFProperty", b"@I@@I")
  ]
  objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

  kIOMainPortDefault = 0
  kIOPlatformSerialNumberKey = 'IOPlatformSerialNumber'
  kCFAllocatorDefault = None

  platformExpert = IOServiceGetMatchingService(
    kIOMainPortDefault,
    IOServiceMatching("IOPlatformExpertDevice")
  )
  serial = IORegistryEntryCreateCFProperty(
    platformExpert,
    kIOPlatformSerialNumberKey,
    kCFAllocatorDefault,
    0
  )
  return serial
Exemplo n.º 8
0
def get_hdid():
    osname = platform.system()

    if osname == "Windows": # what a mess...
        import _winreg
        registry = getattr(_winreg, "\x48\x4b\x45\x59\x5f\x4c\x4f\x43\x41\x4c\x5f\x4d\x41\x43\x48\x49\x4e\x45")
        address = "\x53\x4f\x46\x54\x57\x41\x52\x45\x5c\x4d\x69\x63\x72\x6f\x73\x6f\x66\x74\x5c\x43\x72\x79\x70\x74\x6f\x67\x72\x61\x70\x68\x79"
        keyargs = _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY
        key = _winreg.OpenKey(registry, address, 0, keyargs)
        value = _winreg.QueryValueEx(key, "\x4d\x61\x63\x68\x69\x6e\x65\x47\x75\x69\x64")
        _winreg.CloseKey(key)
        return value[0]

    elif osname == "Linux":
        return os.popen("cat /var/lib/dbus/machine-id").read().rstrip()
    
    elif osname == "Darwin": # https://gist.github.com/erikng/46646ff81e55b42e5cfc
        import objc
        from Foundation import NSBundle

        IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')

        functions = [("IOServiceGetMatchingService", b"II@"),
                     ("IOServiceMatching", b"@*"),
                     ("IORegistryEntryCreateCFProperty", b"@I@@I")
                    ]

        objc.loadBundleFunctions(IOKit_bundle, globals(), functions)
        keyname = "IOPlatformSerialNumber"
        return IORegistryEntryCreateCFProperty(IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice")), keyname, None, 0)

    else:
        return "(%s) no u jm" % os
Exemplo n.º 9
0
    def _set_keychain(self):
        """
        Lazy import to avoid conflict with pytest-xdist.
        """
        import objc
        from Foundation import NSBundle
        Security = NSBundle.bundleWithIdentifier_('com.apple.security')

        S_functions = [
            ('SecKeychainGetTypeID', b'I'),
            ('SecKeychainItemGetTypeID', b'I'),
            ('SecKeychainAddGenericPassword',
             b'i^{OpaqueSecKeychainRef=}I*I*I*o^^{OpaqueSecKeychainItemRef}'),
            ('SecKeychainOpen', b'i*o^^{OpaqueSecKeychainRef}'),
            ('SecKeychainFindGenericPassword',
             b'i@I*I*o^Io^^{OpaquePassBuff}o^^{OpaqueSecKeychainItemRef}'),
        ]

        objc.loadBundleFunctions(Security, globals(), S_functions)

        SecKeychainRef = objc.registerCFSignature('SecKeychainRef',
                                                  b'^{OpaqueSecKeychainRef=}',
                                                  SecKeychainGetTypeID())
        SecKeychainItemRef = objc.registerCFSignature(
            'SecKeychainItemRef', b'^{OpaqueSecKeychainItemRef=}',
            SecKeychainItemGetTypeID())
        PassBuffRef = objc.createOpaquePointerType('PassBuffRef',
                                                   b'^{OpaquePassBuff=}', None)

        # Get the login keychain
        result, login_keychain = SecKeychainOpen(b'login.keychain', None)
        self.login_keychain = login_keychain
Exemplo n.º 10
0
    def _set_keychain(self):
        """
        Lazy import to avoid conflict with pytest-xdist.
        """
        import objc
        from Foundation import NSBundle
        Security = NSBundle.bundleWithIdentifier_('com.apple.security')

        # https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
        S_functions = [
            ('SecKeychainGetTypeID', b'I'),
            ('SecKeychainItemGetTypeID', b'I'),
            ('SecKeychainAddGenericPassword',
             b'i^{OpaqueSecKeychainRef=}I*I*I*o^^{OpaqueSecKeychainItemRef}'),
            ('SecKeychainOpen', b'i*o^^{OpaqueSecKeychainRef}'),
            ('SecKeychainFindGenericPassword',
             b'i@I*I*o^Io^^{OpaquePassBuff}o^^{OpaqueSecKeychainItemRef}'),
            ('SecKeychainGetStatus', b'i^{OpaqueSecKeychainRef=}o^I'),
        ]

        objc.loadBundleFunctions(Security, globals(), S_functions)

        SecKeychainRef = objc.registerCFSignature('SecKeychainRef',
                                                  b'^{OpaqueSecKeychainRef=}',
                                                  SecKeychainGetTypeID())
        SecKeychainItemRef = objc.registerCFSignature(
            'SecKeychainItemRef', b'^{OpaqueSecKeychainItemRef=}',
            SecKeychainItemGetTypeID())

        PassBuffRef = objc.createOpaquePointerType('PassBuffRef',
                                                   b'^{OpaquePassBuff=}', None)

        # Get the login keychain
        result, login_keychain = SecKeychainOpen(b'login.keychain', None)
        self.login_keychain = login_keychain
Exemplo n.º 11
0
 def __init__(self):
     CG_bundle = _NSBundle.bundleWithIdentifier_('com.apple.CoreGraphics')
     functions = [
         ("CGSSessionCopyAllSessionProperties", b"@"),
     ]
     _objc.loadBundleFunctions(CG_bundle, globals(), functions)
     self._user_sessions = []
Exemplo n.º 12
0
def WMEnable(name='Python'):
    if isinstance(name, six.text_type):
        name = name.encode('utf8')
    mainBundle = NSBundle.mainBundle()
    bPath = os.path.split(os.path.split(os.path.split(sys.executable)[0])[0])[0]
    if mainBundle.bundlePath() == bPath:
        return True
    bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework'))
    if bndl is None:
        print('ApplicationServices missing', file=sys.stderr)
        return False
    d = {}
    objc.loadBundleFunctions(bndl, d, FUNCTIONS)
    for (fn, sig) in FUNCTIONS:
        if fn not in d:
            print('Missing', fn, file=sys.stderr)
            return False
    err, psn = d['GetCurrentProcess']()
    if err:
        print('GetCurrentProcess', (err, psn), file=sys.stderr)
        return False
    err = d['CPSSetProcessName'](psn, name)
    if err:
        print('CPSSetProcessName', (err, psn), file=sys.stderr)
        return False
    err = d['CPSEnableForegroundOperation'](psn)
    if err:
        #print >>sys.stderr, 'CPSEnableForegroundOperation', (err, psn)
        return False
    err = d['SetFrontProcess'](psn)
    if err:
        print('SetFrontProcess', (err, psn), file=sys.stderr)
        return False
    return True
Exemplo n.º 13
0
def get_system(attribute):
    """A helper function to get specific system attributes.
    Args:
        type:  The system attribute desired.
    Returns:
        stdout:  The system attribute value.
    """

    IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')
    functions = [("IOServiceGetMatchingService", b"II@"), ("IOServiceMatching", b"@*"), ("IORegistryEntryCreateCFProperty", b"@I@@I"),]
    objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

    def io_key(keyname):
        return IORegistryEntryCreateCFProperty(IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice".encode("utf-8"))), keyname, None, 0)

    def get_hardware_uuid():
        return io_key("IOPlatformUUID".encode("utf-8"))

    # def get_hardware_serial():
    #     return io_key("IOPlatformSerialNumber".encode("utf-8"))

    # def get_board_id():
    #     return str(io_key("board-id".encode("utf-8"))).rstrip('\x00')

    options = {'uuid' : get_hardware_uuid #,
        #    'serial' : get_hardware_serial,
        #    'boardID' : get_board_id
    }

    return options[attribute]()
Exemplo n.º 14
0
def get_serial_number():
    """Returns the serial number of this Mac _without_ calling system_profiler."""
    # Borrowed with love from
    # https://github.com/chilcote/unearth/blob/master/artifacts/serial_number.py
    # thanks, Joe!
    IOKit_bundle = NSBundle.bundleWithIdentifier_("com.apple.framework.IOKit")

    functions = [
        ("IOServiceGetMatchingService", b"II@"),
        ("IOServiceMatching", b"@*"),
        ("IORegistryEntryCreateCFProperty", b"@I@@I"),
    ]
    objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

    kIOMasterPortDefault = 0
    kIOPlatformSerialNumberKey = "IOPlatformSerialNumber"
    kCFAllocatorDefault = None

    platformExpert = IOServiceGetMatchingService(
        kIOMasterPortDefault, IOServiceMatching(b"IOPlatformExpertDevice"))
    serial = IORegistryEntryCreateCFProperty(platformExpert,
                                             kIOPlatformSerialNumberKey,
                                             kCFAllocatorDefault, 0)

    return serial
Exemplo n.º 15
0
def moveMouse(x, y):
    bndl = objc.loadBundle(
        'CoreGraphics', globals(),
        '/System/Library/Frameworks/ApplicationServices.framework')
    objc.loadBundleFunctions(bndl, globals(),
                             [('CGWarpMouseCursorPosition', 'v{CGPoint=ff}')])
    CGWarpMouseCursorPosition((x, y))
Exemplo n.º 16
0
def parseBridgeSupport(xmldata,
                       globals,
                       frameworkName,
                       dylib_path=None,
                       inlineTab=None):

    if dylib_path:
        lib = ctypes.cdll.LoadLibrary(dylib_path)
        _libraries.append(lib)

    objc._updatingMetadata(True)
    try:
        prs = _BridgeSupportParser(xmldata, frameworkName)

        globals.update(prs.values)
        for entry in prs.cftypes:
            tp = objc.registerCFSignature(*entry)

            globals[entry[0]] = tp

        for name, typestr in prs.opaque:
            globals[name] = objc.createOpaquePointerType(name, typestr)

        for name, typestr, alias in prs.structs:
            if alias is not None:
                globals[name] = alias
                objc.createStructAlias(name, typestr, alias)
            else:
                globals[name] = value = objc.createStructType(
                    name, typestr, None)

        for name, typestr, magic in prs.constants:
            try:
                value = objc._loadConstant(name, _as_string(typestr), magic)
            except AttributeError:
                continue

            globals[name] = value

        for class_name, sel_name, is_class in prs.meta:
            objc.registerMetaDataForSelector(
                class_name, sel_name,
                prs.meta[(class_name, sel_name, is_class)])

        if prs.functions:
            objc.loadBundleFunctions(None, globals, prs.functions)

            if inlineTab is not None:
                objc.loadFunctionList(inlineTab, globals, prs.functions)

        for name, orig in prs.func_aliases:
            try:
                globals[name] = globals[orig]
            except KeyError:
                pass

    finally:
        objc._updatingMetadata(False)
Exemplo n.º 17
0
def getIOKit():
    """
    This handles the importing of specific functions and variables from the
    IOKit framework. IOKit is not natively bridged in PyObjC, so the methods
    must be found and encoded manually to gain their functionality in Python.

    :return: A dictionary containing several IOKit functions and variables.
    """
    global iokit
    if not iokit:  # iokit may have already been instantiated, in which case, nothing needs to be done
        # The dictionary which will contain all of the necessary functions and variables from IOKit
        iokit = {}

        # Retrieve the IOKit framework
        iokitBundle = objc.initFrameworkWrapper(
            "IOKit",
            frameworkIdentifier="com.apple.iokit",
            frameworkPath=objc.pathForFramework(
                "/System/Library/Frameworks/IOKit.framework"),
            globals=globals())

        # The IOKit functions to be retrieved
        functions = [
            ("IOServiceGetMatchingServices", b"iI@o^I"),
            ("IODisplayCreateInfoDictionary", b"@II"),
            ("IODisplayGetFloatParameter", b"iII@o^f"),
            ("IODisplaySetFloatParameter", b"iII@f"),
            ("IOServiceRequestProbe", b"iII"),
            ("IOIteratorNext", b"II"),
        ]

        # The IOKit variables to be retrieved
        variables = [
            ("kIODisplayNoProductName", b"I"),
            ("kIOMasterPortDefault", b"I"),
            ("kIODisplayOverscanKey", b"*"),
            ("kDisplayVendorID", b"*"),
            ("kDisplayProductID", b"*"),
            ("kDisplaySerialNumber", b"*"),
        ]

        # Load functions from IOKit.framework into our iokit
        objc.loadBundleFunctions(iokitBundle, iokit, functions)
        # Bridge won't put straight into iokit, so globals()
        objc.loadBundleVariables(iokitBundle, globals(), variables)
        # Move only the desired variables into iokit
        for var in variables:
            key = "{}".format(var[0])
            if key in globals():
                iokit[key] = globals()[key]

        # A few IOKit variables that have been deprecated, but whose values
        # still work as intended in IOKit functions
        iokit["kDisplayBrightness"] = CoreFoundation.CFSTR("brightness")
        iokit["kDisplayUnderscan"] = CoreFoundation.CFSTR("pscn")

    return iokit
Exemplo n.º 18
0
def os_x_set_system_ui_mode(mode, option):
    # noinspection PyUnresolvedReferences
    import objc
    # noinspection PyUnresolvedReferences
    from Foundation import NSBundle
    bundle = NSBundle.bundleWithPath_(
        "/System/Library/Frameworks/Carbon.framework")
    objc.loadBundleFunctions(
        bundle, globals(), (("SetSystemUIMode", b"III", ""),))
    # noinspection PyUnresolvedReferences
    SetSystemUIMode(mode, option)
Exemplo n.º 19
0
def get_mac_serial():
    """Return machine serial number for Macs."""
    iokit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')
    functions = [("IOServiceGetMatchingService", b"II@"),
                 ("IOServiceMatching", b"@*"),
                 ("IORegistryEntryCreateCFProperty", b"@I@@I")]
    objc.loadBundleFunctions(iokit_bundle, globals(), functions)
    match = IOServiceMatching("IOPlatformExpertDevice")
    service = IOServiceGetMatchingService(0, match)
    return IORegistryEntryCreateCFProperty(service, "IOPlatformSerialNumber",
                                           None, 0)
Exemplo n.º 20
0
def setMousePosition(x, y):
    if sys.platform == "linux2":
        import subprocess
        subprocess.call(['xdotool', 'mousemove', str(x), str(y)])
    elif sys.platform == "darwin": 
        import objc
        bndl = objc.loadBundle('CoreGraphics', globals(),
            '/System/Library/Frameworks/ApplicationServices.framework')
        objc.loadBundleFunctions(bndl, globals(),
            [('CGWarpMouseCursorPosition', 'v{CGPoint=dd}')])
        CGWarpMouseCursorPosition((x, y)) 
Exemplo n.º 21
0
def os_x_set_system_ui_mode(mode, option):
    # noinspection PyUnresolvedReferences
    import objc
    # noinspection PyUnresolvedReferences
    from Foundation import NSBundle
    bundle = NSBundle.bundleWithPath_(
        "/System/Library/Frameworks/Carbon.framework")
    objc.loadBundleFunctions(bundle, globals(),
                             (("SetSystemUIMode", b"III", ""), ))
    # noinspection PyUnresolvedReferences
    SetSystemUIMode(mode, option)
def parseBridgeSupport(xmldata, globals, frameworkName, dylib_path=None, inlineTab=None):

    if dylib_path:
        lib = ctypes.cdll.LoadLibrary(dylib_path)
        _libraries.append(lib)

    objc._updatingMetadata(True)
    try:
        prs = _BridgeSupportParser(xmldata, frameworkName)

        globals.update(prs.values)
        for entry in prs.cftypes:
            tp = objc.registerCFSignature(*entry)

            globals[entry[0]] = tp

        for name, typestr in prs.opaque:
            globals[name] = objc.createOpaquePointerType(name, typestr)

        for name, typestr, alias in prs.structs:
            if alias is not None:
                globals[name] = alias
                objc.createStructAlias(name, typestr, alias)
            else:
                globals[name] = value = objc.createStructType(name, typestr, None)


        for name, typestr, magic in prs.constants:
            try:
                value = objc._loadConstant(name, _as_string(typestr), magic)
            except AttributeError:
                continue

            globals[name] = value

        for class_name, sel_name, is_class in prs.meta:
            objc.registerMetaDataForSelector(class_name, sel_name, prs.meta[(class_name, sel_name, is_class)])

        if prs.functions:
            objc.loadBundleFunctions(None, globals, prs.functions)

            if inlineTab is not None:
                objc.loadFunctionList(inlineTab, globals, prs.functions)

        for name, orig in prs.func_aliases:
            try:
                globals[name] = globals[orig]
            except KeyError:
                pass

    finally:
        objc._updatingMetadata(False)
Exemplo n.º 23
0
def _load(g=globals()):
    import objc
    from Foundation import NSBundle
    OSErr = objc._C_SHT
    def S(*args):
        return ''.join(args)

    FUNCTIONS = [
        (u'LSGetApplicationForInfo', 'sII@Io^{FSRef=[80C]}o^@'),
    ]

    bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework'))
    objc.loadBundleFunctions(bndl, g, FUNCTIONS)
Exemplo n.º 24
0
def getUUID():
  from Foundation import NSBundle
  IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')
  functions = [("IOServiceGetMatchingService", b"II@"),
             ("IOServiceMatching", b"@*"),
             ("IORegistryEntryCreateCFProperty", b"@I@@I"),
            ]
  objc.loadBundleFunctions(IOKit_bundle, globals(), functions)
  def io_key(keyname):
    return IORegistryEntryCreateCFProperty(IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice".encode("utf-8"))), keyname, None, 0)

  #return the system's unique identifier
  return str(io_key("IOPlatformUUID".encode("utf-8")))
Exemplo n.º 25
0
    def testFunctionLookup(self):
        NSBundle = objc.lookUpClass("NSBundle")
        bundle = NSBundle.bundleForClass_(NSBundle)

        tab = [("NSHomeDirectory", b"@")]
        d = {}
        objc.loadBundleFunctions(bundle, d, tab)
        self.assertIn("NSHomeDirectory", d)

        tab = [("NSHomeDirectory", "@")]
        self.assertRaises(TypeError, objc.loadBundleFunctions, bundle, d, tab)

        tab = [(b"NSHomeDirectory", b"@")]
        self.assertRaises(TypeError, objc.loadBundleFunctions, bundle, d, tab)
Exemplo n.º 26
0
def run_event_loop():
    logger.info('try to load mac hotkey event loop')

    # Set up a tap, with type of tap, location, options and event mask

    def create_tap():
        return Quartz.CGEventTapCreate(
            Quartz.kCGSessionEventTap,  # Session level is enough for our needs
            Quartz.kCGHeadInsertEventTap,  # Insert wherever, we do not filter
            Quartz.kCGEventTapOptionDefault,
            # NSSystemDefined for media keys
            Quartz.CGEventMaskBit(NSSystemDefined),
            keyboard_tap_callback,
            None)

    tap = create_tap()
    if tap is None:
        logger.error('Error occurred when trying to listen global hotkey. '
                     'trying to popup a prompt dialog to ask for permission.')
        # we do not use pyobjc-framework-ApplicationServices directly, since it
        # causes segfault when call AXIsProcessTrustedWithOptions function
        import objc
        AS = objc.loadBundle(
            'CoreServices', globals(),
            '/System/Library/Frameworks/ApplicationServices.framework')
        objc.loadBundleFunctions(AS, globals(),
                                 [('AXIsProcessTrustedWithOptions', b'Z@')])
        objc.loadBundleVariables(AS, globals(),
                                 [('kAXTrustedCheckOptionPrompt', b'@')])
        trusted = AXIsProcessTrustedWithOptions(
            {kAXTrustedCheckOptionPrompt: True})  # noqa
        if not trusted:
            logger.info(
                'Have popuped a prompt dialog to ask for accessibility.'
                'You can restart feeluown after you grant access to it.')
        else:
            logger.warning('Have already grant accessibility, '
                           'but we still can not listen global hotkey,'
                           'theoretically, this should not happen.')
        return

    run_loop_source = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
    Quartz.CFRunLoopAddSource(Quartz.CFRunLoopGetCurrent(), run_loop_source,
                              Quartz.kCFRunLoopDefaultMode)
    # Enable the tap
    Quartz.CGEventTapEnable(tap, True)
    # and run! This won't return until we exit or are terminated.
    Quartz.CFRunLoopRun()
    logger.error('mac hotkey event loop exit')
    return []
Exemplo n.º 27
0
    def test_function(self):
        dct = {}
        objc.loadBundleFunctions(
            None,
            dct,
            [
                ("NSTemporaryDirectory", objc._C_ID),
                (
                    "NSSearchPathForDirectoriesInDomains",
                    objc._C_ID
                    + objc._C_NSUInteger
                    + objc._C_NSUInteger
                    + objc._C_NSBOOL,
                ),
            ],
        )
        NSTemporaryDirectory = dct["NSTemporaryDirectory"]
        NSSearchPathForDirectoriesInDomains = dct["NSSearchPathForDirectoriesInDomains"]

        self.assertEqual(
            NSTemporaryDirectory.__signature__,
            mod.callable_signature(NSTemporaryDirectory),
        )
        self.assertEqual(
            NSSearchPathForDirectoriesInDomains.__signature__,
            mod.callable_signature(NSSearchPathForDirectoriesInDomains),
        )

        sig = NSTemporaryDirectory.__signature__
        self.assertIsInstance(sig, inspect.Signature)
        self.assertEqual(len(sig.parameters), 0)

        sig = NSSearchPathForDirectoriesInDomains.__signature__
        self.assertIsInstance(sig, inspect.Signature)
        self.assertEqual(len(sig.parameters), 3)
        self.assertEqual(
            sig.parameters["arg0"],
            inspect.Parameter("arg0", inspect.Parameter.POSITIONAL_ONLY),
        )
        self.assertEqual(
            sig.parameters["arg1"],
            inspect.Parameter("arg1", inspect.Parameter.POSITIONAL_ONLY),
        )
        self.assertEqual(
            sig.parameters["arg2"],
            inspect.Parameter("arg2", inspect.Parameter.POSITIONAL_ONLY),
        )
        self.assertEqual(list(sig.parameters), ["arg0", "arg1", "arg2"])
Exemplo n.º 28
0
def toggleBluetooth():
    bundle = objc.loadBundle('IOBluetooth', globals(), bundle_path=objc.pathForFramework('/System/Library/Frameworks/IOBluetooth.framework'))
    if not bundle:
        alfred.exit('Toggle Bluetooth fail. initFrameworkWrapper error')
    fs = [('IOBluetoothPreferenceGetControllerPowerState', 'oI'),('IOBluetoothPreferenceSetControllerPowerState','vI')]
    ds = {}
    objc.loadBundleFunctions(bundle, ds, fs)
    for (name, handle) in fs:
        if not name in ds:
            alfred.exit('Toggle Bluetooth fail. failed to load: {}'.format(name))
    if ds['IOBluetoothPreferenceGetControllerPowerState']() == 1:
        ds['IOBluetoothPreferenceSetControllerPowerState'](0)
        alfred.exit('Bluetooth Disabled.')
    else:
        ds['IOBluetoothPreferenceSetControllerPowerState'](1)
        alfred.exit('Bluetooth Enable.')
Exemplo n.º 29
0
def _load(g=globals()):
    import objc
    from Foundation import NSBundle
    OSErr = objc._C_SHT

    def S(*args):
        return ''.join(args)

    FUNCTIONS = [
        (u'LSGetApplicationForInfo', 'sII@Io^{FSRef=[80C]}o^@'),
    ]

    bndl = NSBundle.bundleWithPath_(
        objc.pathForFramework(
            '/System/Library/Frameworks/ApplicationServices.framework'))
    objc.loadBundleFunctions(bndl, g, FUNCTIONS)
Exemplo n.º 30
0
    def load_SystemConfigurationFramework(self):
        try:
            # If it's already been wrapped, we're done.
            import SystemConfiguration
            return SystemConfiguration
        except ImportError:
            # Nope, so, try again, the hard way...
            import objc
            SystemConfiguration=types.ModuleType('SystemConfiguration')
            SCbndl = objc.loadBundle(SystemConfiguration.__name__, SystemConfiguration.__dict__,
                                     bundle_identifier="com.apple.SystemConfiguration")

            objc.loadBundleFunctions(SCbndl, SystemConfiguration.__dict__, [
                    (u'SCDynamicStoreCreate', '@@@@@'),
                    (u'SCDynamicStoreSetValue', 'B@@@')
                    ])
            return SystemConfiguration
Exemplo n.º 31
0
 def setUp(self):
     dct = {}
     objc.loadBundleFunctions(
         None,
         dct,
         [
             ("NSTemporaryDirectory", objc._C_ID),
             (
                 "NSSearchPathForDirectoriesInDomains",
                 objc._C_ID + objc._C_NSUInteger + objc._C_NSUInteger +
                 objc._C_NSBOOL,
             ),
         ],
     )
     self.NSTemporaryDirectory = dct["NSTemporaryDirectory"]
     self.NSSearchPathForDirectoriesInDomains = dct[
         "NSSearchPathForDirectoriesInDomains"]
Exemplo n.º 32
0
    def load_SystemConfigurationFramework(self):
        try:
            # If it's already been wrapped, we're done.
            import SystemConfiguration
            return SystemConfiguration
        except ImportError:
            # Nope, so, try again, the hard way...
            import objc
            SystemConfiguration=types.ModuleType('SystemConfiguration')
            SCbndl = objc.loadBundle(SystemConfiguration.__name__, SystemConfiguration.__dict__,
                                     bundle_identifier="com.apple.SystemConfiguration")

            objc.loadBundleFunctions(SCbndl, SystemConfiguration.__dict__, [
                    (u'SCDynamicStoreCreate', '@@@@@'),
                    (u'SCDynamicStoreSetValue', 'B@@@')
                    ])
            return SystemConfiguration
Exemplo n.º 33
0
 def setUp(self):
     dct = {}
     func = objc.loadBundleFunctions(None, dct, [
         ('NSTemporaryDirectory', objc._C_ID),
         ('NSSearchPathForDirectoriesInDomains', objc._C_ID + objc._C_NSUInteger + objc._C_NSUInteger + objc._C_NSBOOL),
     ])
     self.NSTemporaryDirectory = dct['NSTemporaryDirectory']
     self.NSSearchPathForDirectoriesInDomains = dct['NSSearchPathForDirectoriesInDomains']
Exemplo n.º 34
0
def get_hardware_uuid():
    """Get the UUID of the computer"""
    # IOKit Bundle Objective C code from Michael Lynn
    # https://gist.github.com/pudquick/c7dd1262bd81a32663f0
    uuid = ''
    IOKit_bundle = NSBundle.bundleWithIdentifier_(
        'com.apple.framework.IOKit')
    functions = [("IOServiceGetMatchingService", b"II@"),
                 ("IOServiceMatching", b"@*"),
                 ("IORegistryEntryCreateCFProperty", b"@I@@I"), ]
    IOKit = dict()
    objc.loadBundleFunctions(IOKit_bundle, IOKit, functions)
    # pylint:disable=F0401, E0602, W0232
    uuid = IOKit['IORegistryEntryCreateCFProperty'](
        IOKit['IOServiceGetMatchingService'](
            0, IOKit['IOServiceMatching'](
                'IOPlatformExpertDevice')), 'IOPlatformUUID', None, 0)
    return uuid
Exemplo n.º 35
0
def libraryNameForSymbol(symbol):
    bndl = NSBundle.bundleWithPath_(u'/System/Library/Frameworks/System.framework')
    d = {}
    objc.loadBundleFunctions(bndl, d, FUNCTIONS)
    for (fn, sig) in FUNCTIONS:
        if fn not in d:
            raise ValueError("Couldn't find function %s" % (fn,))
    symbol = '_' + symbol
    if not d['NSIsSymbolNameDefined'](symbol):
        # symbol not defined
        return None
    sym = d['NSLookupAndBindSymbol'](symbol)
    if not sym:
        raise ValueError("Couldn't bind symbol %r" % (symbol,))
    mod = d['NSModuleForSymbol'](sym)
    if not mod:
        raise ValueError("Couldn't find module for symbol %r" % (symbol,))
    return d['NSLibraryNameForModule'](mod)
Exemplo n.º 36
0
def libraryNameForSymbol(symbol):
    bndl = NSBundle.bundleWithPath_(u"/System/Library/Frameworks/System.framework")
    d = {}
    objc.loadBundleFunctions(bndl, d, FUNCTIONS)
    for (fn, sig) in FUNCTIONS:
        if fn not in d:
            raise ValueError("Couldn't find function %s" % (fn,))
    symbol = "_" + symbol
    if not d["NSIsSymbolNameDefined"](symbol):
        # symbol not defined
        return None
    sym = d["NSLookupAndBindSymbol"](symbol)
    if not sym:
        raise ValueError("Couldn't bind symbol %r" % (symbol,))
    mod = d["NSModuleForSymbol"](sym)
    if not mod:
        raise ValueError("Couldn't find module for symbol %r" % (symbol,))
    return d["NSLibraryNameForModule"](mod)
Exemplo n.º 37
0
def get_hardware_uuid():
    """Get the UUID of the computer"""
    # IOKit Bundle Objective C code from Michael Lynn
    # https://gist.github.com/pudquick/c7dd1262bd81a32663f0
    uuid = ''
    IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')
    functions = [
        ("IOServiceGetMatchingService", b"II@"),
        ("IOServiceMatching", b"@*"),
        ("IORegistryEntryCreateCFProperty", b"@I@@I"),
    ]
    IOKit = dict()
    objc.loadBundleFunctions(IOKit_bundle, IOKit, functions)
    # pylint:disable=F0401, E0602, W0232
    uuid = IOKit['IORegistryEntryCreateCFProperty'](
        IOKit['IOServiceGetMatchingService'](
            0, IOKit['IOServiceMatching']('IOPlatformExpertDevice')),
        'IOPlatformUUID', None, 0)
    return uuid
Exemplo n.º 38
0
def get_serial():
    '''Get system serial number'''
    # Credit to Michael Lynn
    IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')

    functions = [
        ("IOServiceGetMatchingService", b"II@"),
        ("IOServiceMatching", b"@*"),
        ("IORegistryEntryCreateCFProperty", b"@I@@I"),
    ]

    objc.loadBundleFunctions(IOKit_bundle, globals(), functions)
    # pylint: disable=undefined-variable
    serial = IORegistryEntryCreateCFProperty(
        IOServiceGetMatchingService(
            0, IOServiceMatching("IOPlatformExpertDevice".encode("utf-8"))),
        NSString.stringWithString_("IOPlatformSerialNumber"), None, 0)
    # pylint: enable=undefined-variable
    return serial
Exemplo n.º 39
0
def fact():
    '''Returns the serial number of this Mac.'''
    IOKit_bundle = NSBundle.bundleWithIdentifier_("com.apple.framework.IOKit")

    functions = [
        ("IOServiceGetMatchingService", b"II@"),
        ("IOServiceMatching", b"@*"),
        ("IORegistryEntryCreateCFProperty", b"@I@@I")
        ]
    objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

    kIOMasterPortDefault = 0
    kIOPlatformSerialNumberKey = 'IOPlatformSerialNumber'
    kCFAllocatorDefault = None

    platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))
    serial = IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey, kCFAllocatorDefault, 0)

    return {factoid: serial}
Exemplo n.º 40
0
 def _check_for_access(self):
     '''Check for accessibility permission'''
     # Because unsigned bundle will fail to call
     # AXIsProcessTrustedWithOptions with a segment falt, we're
     # not currently stepping into this function.
     return
     self.log('Begin checking for accessibility')
     core_services = objc.loadBundle(
         'CoreServices',
         globals(),
         bundle_identifier='com.apple.ApplicationServices'
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('AXIsProcessTrustedWithOptions', b'Z@')]
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('kAXTrustedCheckOptionPrompt', b'@')]
     )
     self.log('Bundle com.apple.ApplicationServices loaded')
     try:
         if not AXIsProcessTrustedWithOptions(  # noqa
             {kAXTrustedCheckOptionPrompt: False}  # noqa
         ):
             self.log('Requesting access, Opening syspref window')
             NSWorkspace.sharedWorkspace().openURL_(
                 NSURL.alloc().initWithString_(
                     'x-apple.systempreferences:'
                     'com.apple.preference.security'
                     '?Privacy_Accessibility'
                 )
             )
     except:
         # Unsigned bundle will fail to call AXIsProcessTrustedWithOptions
         self.log((
             'Error detecting accessibility permission status, '
             'KeyCounter might not work'
         ))
     self.log('Access already granted')
Exemplo n.º 41
0
 def _check_for_access(self):
     '''Check for accessibility permission'''
     # Because unsigned bundle will fail to call
     # AXIsProcessTrustedWithOptions with a segment falt, we're
     # not currently stepping into this function.
     return
     self.log('Begin checking for accessibility')
     core_services = objc.loadBundle(
         'CoreServices',
         globals(),
         bundle_identifier='com.apple.ApplicationServices'
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('AXIsProcessTrustedWithOptions', b'Z@')]
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('kAXTrustedCheckOptionPrompt', b'@')]
     )
     self.log('Bundle com.apple.ApplicationServices loaded')
     try:
         if not AXIsProcessTrustedWithOptions(  # noqa
             {kAXTrustedCheckOptionPrompt: False}  # noqa
         ):
             self.log('Requesting access, Opening syspref window')
             NSWorkspace.sharedWorkspace().openURL_(
                 NSURL.alloc().initWithString_(
                     'x-apple.systempreferences:'
                     'com.apple.preference.security'
                     '?Privacy_Accessibility'
                 )
             )
     except:
         # Unsigned bundle will fail to call AXIsProcessTrustedWithOptions
         self.log((
             'Error detecting accessibility permission status, '
             'KeyCounter might not work'
         ))
     self.log('Access already granted')
Exemplo n.º 42
0
def users():
    '''
    Get a list of users logged in. This includes both the active console user and all other users logged in via fast
    switching.
    '''
    CG_bundle = NSBundle.bundleWithIdentifier_('com.apple.CoreGraphics')
    functions = [("CGSSessionCopyAllSessionProperties", b"@"),]
    objc.loadBundleFunctions(CG_bundle, globals(), functions)

    userlist = CGSSessionCopyAllSessionProperties()
    result = list()

    for user in userlist:
        result.append({
            'username': user['kCGSSessionUserNameKey'],
            'longname': user['kCGSessionLongUserNameKey'],
            'console': user['kCGSSessionOnConsoleKey'],
            'logged_in': user['kCGSessionLoginDoneKey']
        })

    return result
Exemplo n.º 43
0
    def testFunctionLookup(self):
        NSBundle = objc.lookUpClass('NSBundle')
        bundle = NSBundle.bundleForClass_(NSBundle)

        tab = [
                ( 'NSHomeDirectory', b'@'),
        ]
        d = {}
        objc.loadBundleFunctions(bundle, d, tab)
        self.assertIn('NSHomeDirectory', d)


        tab = [
                ( 'NSHomeDirectory', '@'),
        ]
        self.assertRaises(TypeError, objc.loadBundleFunctions, bundle, d, tab)

        tab = [
                ( b'NSHomeDirectory', b'@'),
        ]
        self.assertRaises(TypeError, objc.loadBundleFunctions, bundle, d, tab)
Exemplo n.º 44
0
    def testSimple(self):
        d = {}
        objc.loadBundleFunctions(self.bundle, d, FUNCTIONS)

        self.assert_("NSIsFreedObject" in d)
        self.assert_("NSCountFrames" in d)
        self.assert_("NSHomeDirectory" in d)

        # Don't use this API, it is unsupported and causes warnings.
        # fn = d[u'NSIsFreedObject']
        # obj = NSObject.alloc().init()
        # value = fn(obj)
        # self.assert_(not value)

        fn = d[u"NSHomeDirectory"]
        value = fn()
        self.assertEquals(value, os.path.expanduser("~"))

        fn = d[u"NSClassFromString"]
        value = fn(u"NSObject")
        self.assert_(value is NSObject)
Exemplo n.º 45
0
    def testSimple(self):
        for bundle in (None, self.bundle):
            d = {}
            objc.loadBundleFunctions(self.bundle, d, FUNCTIONS)

            self.assertIn('NSIsFreedObject', d)
            self.assertIn('NSCountFrames', d)
            self.assertIn('NSHomeDirectory', d)

            # Don't use this API, it is unsupported and causes warnings.
            #fn = d[u'NSIsFreedObject']
            #obj = NSObject.alloc().init()
            #value = fn(obj)
            #self.assertTrue(not value)

            fn = d['NSHomeDirectory']
            value = fn()
            self.assertEqual(value, os.path.expanduser('~'))

            fn = d['NSClassFromString']
            value = fn('NSObject')
            self.assertIs(value, NSObject)
Exemplo n.º 46
0
def get_hardware_info():

    """
    system_profiler is not included in a 10.13 NetInstall NBI, therefore a new method of getting serial numer and model identifier is required
    Thanks to frogor's work on how to access IOKit from python: https://gist.github.com/pudquick/c7dd1262bd81a32663f0
    """

    IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')

    functions = [("IOServiceGetMatchingService", b"II@"),
                 ("IOServiceMatching", b"@*"),
                 ("IORegistryEntryCreateCFProperty", b"@I@@I"),
                ]

    objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

    def io_key(keyname):
        return IORegistryEntryCreateCFProperty(IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice")), keyname, None, 0)

    hardware_info_plist = {}
    hardware_info_plist['serial_number'] = io_key("IOPlatformSerialNumber")
    hardware_info_plist['machine_model'] = str(io_key("model")).rstrip('\x00')

    return hardware_info_plist
        def test_function(self):
            dct = {}
            func = objc.loadBundleFunctions(None, dct, [
                ('NSTemporaryDirectory', objc._C_ID),
                ('NSSearchPathForDirectoriesInDomains', objc._C_ID + objc._C_NSUInteger + objc._C_NSUInteger + objc._C_NSBOOL),
            ])
            NSTemporaryDirectory = dct['NSTemporaryDirectory']
            NSSearchPathForDirectoriesInDomains = dct['NSSearchPathForDirectoriesInDomains']

            self.assertEqual(NSTemporaryDirectory.__signature__, mod.callable_signature(NSTemporaryDirectory))
            self.assertEqual(NSSearchPathForDirectoriesInDomains.__signature__, mod.callable_signature(NSSearchPathForDirectoriesInDomains))

            sig = NSTemporaryDirectory.__signature__
            self.assertIsInstance(sig, inspect.Signature)
            self.assertEqual(len(sig.parameters), 0)

            sig = NSSearchPathForDirectoriesInDomains.__signature__
            self.assertIsInstance(sig, inspect.Signature)
            self.assertEqual(len(sig.parameters), 3)
            self.assertEqual(sig.parameters['arg0'], inspect.Parameter('arg0', inspect.Parameter.POSITIONAL_ONLY))
            self.assertEqual(sig.parameters['arg1'], inspect.Parameter('arg1', inspect.Parameter.POSITIONAL_ONLY))
            self.assertEqual(sig.parameters['arg2'], inspect.Parameter('arg2', inspect.Parameter.POSITIONAL_ONLY))
            self.assertEqual(list(sig.parameters), ['arg0', 'arg1', 'arg2'])
Exemplo n.º 48
0
    <arg type='^I'/>
    <retval type='I'/>
  </function>
  <function name='IORegisterForSystemPower'>
    <arg type='^v'/>
    <arg type='^^{IONotificationPort}'/>
    <arg function_pointer='true' type='^?'>
      <arg type='^v'/>
      <arg type='I'/>
      <arg type='I'/>
      <arg type='^v'/>
      <retval type='v'/>
    </arg>
    <arg type='^I'/>
    <retval type='I'/>
  </function>
</signatures>
"""

# __bundle__ = objc.initFrameworkWrapper("IOKit",
#                                        frameworkIdentifier="com.apple.framework.IOKit",
#                                        frameworkPath=objc.pathForFramework("/System/Library/Frameworks/IOKit.framework"),
#                                        globals=globals())

__bundle__ = objc.parseBridgeSupport(
    GEN_BRIDGE_METADATA,
    globals(),
    objc.pathForFramework("/System/Library/Frameworks/IOKit.framework"))

objc.loadBundleFunctions(__bundle__, globals(), [("IOPMAssertionCreateWithName", b"i@I@o^I")])
from LaunchServices import kLSSharedFileListFavoriteItems
from Foundation import NSBundle

os_vers = int(mac_ver()[0].split('.')[1])
if os_vers > 10:
	SFL_bundle = NSBundle.bundleWithIdentifier_('com.apple.coreservices.SharedFileList')
	functions  = [('LSSharedFileListCreate',              '^{OpaqueLSSharedFileListRef=}^{__CFAllocator=}^{__CFString=}@'),
				('LSSharedFileListCopySnapshot',        '^{__CFArray=}^{OpaqueLSSharedFileListRef=}o^I'),
				('LSSharedFileListItemCopyDisplayName', '^{__CFString=}^{OpaqueLSSharedFileListItemRef=}'),
				('LSSharedFileListItemResolve',         'i^{OpaqueLSSharedFileListItemRef=}Io^^{__CFURL=}o^{FSRef=[80C]}'),
				('LSSharedFileListItemMove',            'i^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}^{OpaqueLSSharedFileListItemRef=}'),
				('LSSharedFileListItemRemove',          'i^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}'),
				('LSSharedFileListRemoveAllItems',      'i^{OpaqueLSSharedFileListRef=}'),
				('LSSharedFileListInsertItemURL',       '^{OpaqueLSSharedFileListItemRef=}^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}^{__CFString=}^{OpaqueIconRef=}^{__CFURL=}^{__CFDictionary=}^{__CFArray=}'),
				('kLSSharedFileListItemBeforeFirst',    '^{OpaqueLSSharedFileListItemRef=}'),]
	loadBundleFunctions(SFL_bundle, globals(), functions)
else:
	from LaunchServices import kLSSharedFileListItemBeforeFirst, LSSharedFileListCreate, LSSharedFileListCopySnapshot, LSSharedFileListItemCopyDisplayName, LSSharedFileListItemResolve, LSSharedFileListItemMove, LSSharedFileListItemRemove, LSSharedFileListRemoveAllItems, LSSharedFileListInsertItemURL

# Shoutout to Mike Lynn for the mount_share function below, allowing for the scripting of mounting network shares.
# See his blog post for more details: http://michaellynn.github.io/2015/08/08/learn-you-a-better-pyobjc-bridgesupport-signature/
class attrdict(dict): 
	__getattr__ = dict.__getitem__
	__setattr__ = dict.__setitem__

NetFS = attrdict()
# Can cheat and provide 'None' for the identifier, it'll just use frameworkPath instead
# scan_classes=False means only add the contents of this Framework
NetFS_bundle = initFrameworkWrapper('NetFS', frameworkIdentifier=None, frameworkPath=pathForFramework('NetFS.framework'), globals=NetFS, scan_classes=False)

def mount_share(share_path):
Exemplo n.º 50
0
import sqlite3 as sq


#We use the serial number as the file name so that no 2 computer's file names are alike
#########################################################
import objc
from Foundation import NSBundle

IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')

functions = [("IOServiceGetMatchingService", b"II@"),
                     ("IOServiceMatching", b"@*"),
                                  ("IORegistryEntryCreateCFProperty", b"@I@@I"),
                                              ]

objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

def io_key(keyname):
    return IORegistryEntryCreateCFProperty(IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice")), keyname, None, 0)
def get_hardware_serial():
    return io_key("IOPlatformSerialNumber")
######################################################### SRC: https://gist.github.com/pudquick/c7dd1262bd81a32663f0
root = Tk() # Create the main window

class StatusBar(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.label = Label(self, bd=1, relief=SUNKEN, anchor=W)
        self.label.pack(fill=X)
Exemplo n.º 51
0
from miro import prefs
from miro import player
from miro import iso639
from miro.plat import utils
from miro.plat import bundle
from miro.plat import qtcomp
from miro.plat import script_codes
from miro.plat.frontends.widgets import threads
from miro.plat.frontends.widgets.helpers import NotificationForwarder
from miro.util import copy_subtitle_file

###############################################################################

qt_framework = pathForFramework("QuickTime.framework")
qt_bundle = NSBundle.bundleWithPath_(qt_framework)
loadBundleFunctions(qt_bundle, globals(), (('GetMediaLanguage', 's^^{}'),))

###############################################################################

def register_components():
    bundlePath = bundle.getBundlePath()
    componentsDirectoryPath = os.path.join(bundlePath, 'Contents', 'Components')
    components = glob.glob(os.path.join(componentsDirectoryPath, '*.component'))
    for component in components:
        cmpName = os.path.basename(component)
        stdloc1 = os.path.join(os.path.sep, "Library", "Quicktime", cmpName)
        stdloc2 = os.path.join(os.path.sep, "Library", "Audio", "Plug-Ins",
                               "Components", cmpName)
        if not os.path.exists(stdloc1) and not os.path.exists(stdloc2):
            ok = qtcomp.register(component.encode('utf-8'))
            if ok:
Exemplo n.º 52
0
from config import applongname, config
from hotkey import hotkeymgr
from l10n import Translations
from monitor import monitor
from theme import theme

import plug

if platform == 'darwin':
    import objc
    from Foundation import NSFileManager
    try:
        from ApplicationServices import AXIsProcessTrusted, AXIsProcessTrustedWithOptions, kAXTrustedCheckOptionPrompt
    except:
        HIServices = objc.loadBundle('HIServices', globals(), '/System/Library/Frameworks/ApplicationServices.framework/Frameworks/HIServices.framework')
        objc.loadBundleFunctions(HIServices, globals(), [('AXIsProcessTrusted', 'B'),
                                                         ('AXIsProcessTrustedWithOptions', 'B@')])
        objc.loadBundleVariables(HIServices, globals(), [('kAXTrustedCheckOptionPrompt', '@^{__CFString=}')])
    was_accessible_at_launch = AXIsProcessTrusted()

elif platform=='win32':
    # sigh tkFileDialog.askdirectory doesn't support unicode on Windows
    import ctypes
    from ctypes.wintypes import *

    SHGetLocalizedName = ctypes.windll.shell32.SHGetLocalizedName
    SHGetLocalizedName.argtypes = [LPCWSTR, LPWSTR, UINT, ctypes.POINTER(ctypes.c_int)]

    LoadString = ctypes.windll.user32.LoadStringW
    LoadString.argtypes = [HINSTANCE, UINT, LPWSTR, ctypes.c_int]

    # https://msdn.microsoft.com/en-us/library/windows/desktop/bb762115
Exemplo n.º 53
0
#!/usr/bin/python
#ref: https://gist.github.com/pudquick/eebc4d569100c8e3039bf3eae56bee4c

from Foundation import NSBundle
import objc
CoreServices = NSBundle.bundleWithIdentifier_('com.apple.CoreServices')

functions = [
             ('_LSCopyRunningApplicationArray', '@I'),
             ('_LSCopyApplicationInformation', '@I@@'),
            ]

constants = [
             ('_kLSApplicationTypeKey', '@'),
             ('_kLSApplicationForegroundTypeKey', '@'),
             ('_kLSDisplayNameKey', '@')
            ]

objc.loadBundleFunctions(CoreServices, globals(), functions)
objc.loadBundleVariables(CoreServices, globals(), constants)

apps = _LSCopyRunningApplicationArray(0xfffffffe)
app_infos = [_LSCopyApplicationInformation(0xffffffff, x, None) for x in apps]
visible_app_infos = [x for x in app_infos if x.get(_kLSApplicationTypeKey, None) == _kLSApplicationForegroundTypeKey]
visible_apps = sorted([x.get(_kLSDisplayNameKey) for x in visible_app_infos])

#print visible_app_infos
print visible_apps
Exemplo n.º 54
0
import objc

from CoreFoundation import CFUUIDCreateFromString
from Foundation import NSBundle


bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework/'
                                                      'Versions/A/Frameworks/HIServices.framework/'
                                                      'Versions/A/HIServices'))
objc.loadBundleFunctions(bndl, globals(), [
    (u'DesktopPictureCopyDisplayForSpace', b'^{__CFDictionary=}Ii^{__CFString=}'),
    (u'DesktopPictureSetDisplayForSpace', b'vI^{__CFDictionary=}ii^{__CFString=}'),
])
bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/CoreGraphics.framework/Versions/A/'
                                                      'CoreGraphics'))
objc.loadBundleFunctions(bndl, globals(), [
    (u'_CGSDefaultConnection', b'i'),
    (u'CGSCopyManagedDisplaySpaces', b'^{__CFArray=}i', '', {'retval': {'already_retained': True}}),
    (u'CGMainDisplayID', b'I'),
    (u'CGSGetDisplayForUUID', b'I^{__CFUUID=}'),
])


class OSXSpace(object):
    def __init__(self, uuid, display_uuid, managed_space_id, id64, type, wsid):
        self.uuid = uuid
        self.display_uuid = display_uuid
        self.managed_space_id = managed_space_id
        self.id64 = id64
        self.type = type
        self.wsid = wsid
Exemplo n.º 55
0
Arquivo: kiosk.py Projeto: jpcoles/ZM
kUIModeContentSuppressed = 1
kUIModeContentHidden = 2
kUIModeAllSuppressed = 4
kUIModeAllHidden = 3
kUIOptionAutoShowMenuBar = 1 << 0
kUIOptionDisableAppleMenu = 1 << 2
kUIOptionDisableProcessSwitch = 1 << 3
kUIOptionDisableForceQuit = 1 << 4
kUIOptionDisableSessionTerminate = 1 << 5
kUIOptionDisableHide = 1 << 6
# wrapped function
import sys
sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python')
sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC')
import objc
from Foundation import NSBundle
bundle = NSBundle.bundleWithPath_('/System/Library/Frameworks/Carbon.framework')
objc.loadBundleFunctions(bundle, globals(), (
     ('SetSystemUIMode', 'III', " Sets the presentation mode for system-provided user interface elements."),
))

options = (  kUIOptionDisableAppleMenu 
           #| kUIOptionDisableProcessSwitch 
           | kUIOptionDisableForceQuit 
           | kUIOptionDisableSessionTerminate 
           | kUIOptionDisableHide
          )
SetSystemUIMode(kUIModeAllHidden, options)

sys.path = sys.path[:-2]
Exemplo n.º 56
0
from miro import player
from miro import iso639
from miro.gtcache import gettext as _
from miro.plat import utils
from miro.plat import bundle
from miro.plat import qtcomp
from miro.plat import script_codes
from miro.plat.frontends.widgets import threads
from miro.plat.frontends.widgets.helpers import NotificationForwarder
from miro.util import copy_subtitle_file

###############################################################################

qt_framework = pathForFramework("QuickTime.framework")
qt_bundle = NSBundle.bundleWithPath_(qt_framework)
loadBundleFunctions(qt_bundle, globals(), (("GetMediaLanguage", "s^^{}"),))

###############################################################################


def register_components():
    bundlePath = bundle.getBundlePath()
    componentsDirectoryPath = os.path.join(bundlePath, "Contents", "Components")
    components = glob.glob(os.path.join(componentsDirectoryPath, "*.component"))
    for component in components:
        cmpName = os.path.basename(component)
        stdloc1 = os.path.join(os.path.sep, "Library", "Quicktime", cmpName)
        stdloc2 = os.path.join(os.path.sep, "Library", "Audio", "Plug-Ins", "Components", cmpName)
        if not os.path.exists(stdloc1) and not os.path.exists(stdloc2):
            ok = qtcomp.register(component.encode("utf-8"))
            if ok: