Python objc.loadBundleFunctions() Examples

The following are 12 code examples of objc.loadBundleFunctions(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module objc , or try the search function .
Example #1
Source File: login.py    From salt-osx with MIT License 6 votes vote down vote up
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 
Example #2
Source File: darwin.py    From vorta with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: manufactured_date.py    From unearth with Apache License 2.0 6 votes vote down vote up
def get_serial():
    """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 serial 
Example #4
Source File: shard.py    From unearth with Apache License 2.0 6 votes vote down vote up
def get_serial():
    """Return the machine serial number."""
    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 
Example #5
Source File: serial_number.py    From unearth with Apache License 2.0 6 votes vote down vote up
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} 
Example #6
Source File: backend_cocoaagg.py    From Computable with MIT License 5 votes vote down vote up
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 
Example #7
Source File: backend_cocoaagg.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
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 
Example #8
Source File: backend_cocoaagg.py    From neural-network-animation with MIT License 5 votes vote down vote up
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 
Example #9
Source File: backend_cocoaagg.py    From ImageFusion with MIT License 5 votes vote down vote up
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 
Example #10
Source File: Venator.py    From Venator with GNU General Public License v3.0 5 votes vote down vote up
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")))

#uuid saved to variable 
Example #11
Source File: global_hotkey_mac.py    From FeelUOwn with GNU General Public License v3.0 4 votes vote down vote up
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 [] 
Example #12
Source File: _bridgesupport.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 4 votes vote down vote up
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)