Beispiel #1
0
 def testCreation(self):
     cal = CoreFoundation.CFCalendarCopyCurrent()
     self.assertIsInstance(cal, CoreFoundation.CFCalendarRef)
     cal = CoreFoundation.CFCalendarCreateWithIdentifier(
         None, CoreFoundation.kCFBuddhistCalendar
     )
     self.assertIsInstance(cal, CoreFoundation.CFCalendarRef)
Beispiel #2
0
 def testFunctions(self):
     dta = CoreFoundation.CFPropertyListCreateXMLData(
         None, {
             b"key".decode("ascii"): 42,
             b"key2".decode("ascii"): 1
         })
     self.assertIsInstance(dta, CoreFoundation.CFDataRef)
     self.assertArgIsOut(CoreFoundation.CFPropertyListCreateFromXMLData, 3)
     v, err = CoreFoundation.CFPropertyListCreateFromXMLData(
         None, dta, 0, None)
     self.assertIs(err, None)
     self.assertIsInstance(v, CoreFoundation.CFDictionaryRef)
     self.assertIn("key", v)
     self.assertIn("key2", v)
     self.assertEqual(v["key"], 42)
     self.assertEqual(v["key2"], True)
     v = CoreFoundation.CFPropertyListCreateDeepCopy(
         None, {
             b"key".decode("ascii"): 42,
             b"key2".decode("ascii"): True
         }, 0)
     self.assertIsInstance(v, CoreFoundation.CFDictionaryRef)
     self.assertIn("key", v)
     self.assertIn("key2", v)
     self.assertEqual(v["key"], 42)
     self.assertEqual(v["key2"], True)
     valid = CoreFoundation.CFPropertyListIsValid(
         {
             b"key".decode("ascii"): 42,
             b"key2".decode("ascii"): True
         },
         CoreFoundation.kCFPropertyListBinaryFormat_v1_0,
     )
     self.assertIs(valid, True)
Beispiel #3
0
 def testFunctions10_9(self):
     obj = CoreFoundation.CFURLCreateWithString(None,
                                                "http://www.apple.com/",
                                                None)
     CoreFoundation.CFRetain(obj)
     CoreFoundation.CFAutorelease(obj)
     del obj
Beispiel #4
0
 def testInspection(self):
     st = CoreFoundation.CFSetCreate(None, ["a", "b", "c"], 3,
                                     CoreFoundation.kCFTypeSetCallBacks)
     self.assertIsInstance(st, CoreFoundation.CFSetRef)
     self.assertIsInstance(st, objc.lookUpClass("NSSet"))
     v = CoreFoundation.CFSetGetCount(st)
     self.assertEqual(v, 3)
     self.assertArgHasType(CoreFoundation.CFSetGetCountOfValue, 1, b"@")
     v = CoreFoundation.CFSetGetCountOfValue(st, "d")
     self.assertEqual(v, 0)
     v = CoreFoundation.CFSetGetCountOfValue(st, "b")
     self.assertEqual(v, 1)
     self.assertArgHasType(CoreFoundation.CFSetContainsValue, 1, b"@")
     v = CoreFoundation.CFSetContainsValue(st, "d")
     self.assertIs(v, False)
     v = CoreFoundation.CFSetContainsValue(st, "b")
     self.assertIs(v, True)
     self.assertResultHasType(CoreFoundation.CFSetGetValue, b"@")
     self.assertArgHasType(CoreFoundation.CFSetGetValue, 1, b"@")
     v = CoreFoundation.CFSetGetValue(st, "d")
     self.assertIs(v, None)
     v = CoreFoundation.CFSetGetValue(st, "b")
     self.assertEqual(v, "b")
     self.assertResultIsBOOL(CoreFoundation.CFSetGetValueIfPresent)
     self.assertArgHasType(CoreFoundation.CFSetGetValueIfPresent, 1, b"@")
     self.assertArgHasType(CoreFoundation.CFSetGetValueIfPresent, 2, b"o^@")
     present, value = CoreFoundation.CFSetGetValueIfPresent(st, "c", None)
     self.assertIs(present, True)
     self.assertEqual(value, "c")
     values = CoreFoundation.CFSetGetValues(st, None)
     values = list(values)
     values.sort()
     self.assertEqual(values, ["a", "b", "c"])
Beispiel #5
0
    def testCreation(self):
        userInfo = {"foo": "bar"}
        err = CoreFoundation.CFErrorCreate(None,
                                           CoreFoundation.kCFErrorDomainPOSIX,
                                           42, userInfo)
        self.assertIsInstance(err, CoreFoundation.CFErrorRef)
        self.assertResultIsCFRetained(CoreFoundation.CFErrorCopyUserInfo)
        dct = CoreFoundation.CFErrorCopyUserInfo(err)
        self.assertEqual(dct, userInfo)

        keys = ["key1", "key2"]
        values = ["value1", "value2"]

        keys = [Foundation.NSString.stringWithString_(v) for v in keys]
        values = [Foundation.NSString.stringWithString_(v) for v in values]

        self.assertArgHasType(
            CoreFoundation.CFErrorCreateWithUserInfoKeysAndValues, 3, b"n^@")
        self.assertArgSizeInArg(
            CoreFoundation.CFErrorCreateWithUserInfoKeysAndValues, 3, 5)
        self.assertArgHasType(
            CoreFoundation.CFErrorCreateWithUserInfoKeysAndValues, 4, b"n^@")
        self.assertArgSizeInArg(
            CoreFoundation.CFErrorCreateWithUserInfoKeysAndValues, 4, 5)
        err = CoreFoundation.CFErrorCreateWithUserInfoKeysAndValues(
            None, CoreFoundation.kCFErrorDomainPOSIX, 42, keys, values, 2)
        self.assertIsInstance(err, CoreFoundation.CFErrorRef)
        dct = CoreFoundation.CFErrorCopyUserInfo(err)
        self.assertEqual(dct, {"key1": "value1", "key2": "value2"})
Beispiel #6
0
 def ResolveBuildLocation(cls, project, sym_root):
     build_dir_path = '';
     derived_data = cls.ResolveDerivedDataPath();
     
     location_style = CoreFoundation.CFPreferencesCopyAppValue('IDEBuildLocationStyle', 'com.apple.dt.Xcode');
     if location_style == 'Unique':
         xcodeproj_path = os.path.join(project.projectRoot.obj_path, project.name);
         unique_path = cls.hashStringForPath(xcodeproj_path);
         # this is missing the configuration path.
         project_dir_name = os.path.splitext(project.name)[0]+'-'+unique_path+'/Build/Products/';
         build_dir_path = os.path.join(derived_data, project_dir_name);
     elif location_style == 'Shared':
         shared_path = CoreFoundation.CFPreferencesCopyAppValue('IDESharedBuildFolderName', 'com.apple.dt.Xcode');
         build_dir_path = os.path.join(derived_data, shared_path);
     elif location_style == 'Custom':
         location_type = CoreFoundation.CFPreferencesCopyAppValue('IDECustomBuildLocationType', 'com.apple.dt.Xcode');
         custom_path = CoreFoundation.CFPreferencesCopyAppValue('IDECustomBuildProductsPath', 'com.apple.dt.Xcode');
         if location_type == 'RelativeToDerivedData':
             build_dir_path = os.path.join(derived_data, custom_path);
         elif location_type == 'RelativeToWorkspace':
             build_dir_path = os.path.join(project.path.base_path, custom_path);
         elif location_type == 'Absolute':
             build_dir_path = custom_path;
     elif location_style == 'DeterminedByTargets':
         # this is missing the configuration path
         build_dir_path = os.path.join(project.projectRoot.obj_path, sym_root);
     
     return build_dir_path;
 def testInlines(self):
     flag = CoreFoundation.CFUserNotificationCheckBoxChecked(2)
     self.assertEqual(flag, 1 << 10)
     flag = CoreFoundation.CFUserNotificationSecureTextField(2)
     self.assertEqual(flag, 1 << 18)
     flag = CoreFoundation.CFUserNotificationPopUpSelection(2)
     self.assertEqual(flag, 2 << 24)
Beispiel #8
0
def get_avaliable_languages():
    single_langs = filter(lambda x: x.count() == 1, \
        map(lambda x: objc_object(carbon.TISGetInputSourceProperty(CoreFoundation.CFArrayGetValueAtIndex(objc_object(s), x).__c_void_p__(), kTISPropertyInputSourceLanguages_p)), \
            range(CoreFoundation.CFArrayGetCount(objc_object(carbon.TISCreateInputSourceList(None, 0))))))
    res = set()
    map(lambda y: res.add(y[0]), single_langs)
    return res
    def _datetime_to_cfdate(self, date_time):
        """
        Convert python datetime object to a Core Foundation CFDate object.
        """
        offset = date_time.utcoffset()
        if offset is None:
            # Get local timezone offset when datetime have no timezone.
            timestamp = calendar.timegm(date_time.timetuple())
            local_date_time = datetime.datetime.fromtimestamp(timestamp)
            utc_date_time = datetime.datetime.utcfromtimestamp(timestamp)
            offset = local_date_time - utc_date_time

        # Get timezone offset from datetime object.
        offset = (offset.days * 60 * 60 * 24) + offset.seconds

        # Need to redirect PyObjC errors that are not errors.
        with silence_stderr():
            gregorian_date = CoreFoundation.CFCalendarCreateWithIdentifier(
                None, CoreFoundation.kCFGregorianCalendar)
            timezone = CoreFoundation.CFTimeZoneCreateWithTimeIntervalFromGMT(
                None, offset)

        CoreFoundation.CFCalendarSetTimeZone(gregorian_date, timezone)
        absolute_time = CoreFoundation.CFCalendarComposeAbsoluteTime(
            gregorian_date, None, "yMdHms", date_time.year, date_time.month,
            date_time.day, date_time.hour, date_time.minute,
            date_time.second)[1]
        cfdate = CoreFoundation.CFDateCreate(None, absolute_time)

        return cfdate
Beispiel #10
0
    def testInspection(self):
        letters = CoreFoundation.CFCharacterSetGetPredefined(
            CoreFoundation.kCFCharacterSetLetter)
        digits = CoreFoundation.CFCharacterSetGetPredefined(
            CoreFoundation.kCFCharacterSetDecimalDigit)
        charset = CoreFoundation.CFCharacterSetCreateWithCharactersInString(
            None, b"abcdef".decode("latin1"))

        self.assertTrue(
            CoreFoundation.CFCharacterSetIsSupersetOfSet(letters, charset))
        self.assertFalse(
            CoreFoundation.CFCharacterSetIsSupersetOfSet(digits, charset))

        self.assertTrue(
            CoreFoundation.CFCharacterSetHasMemberInPlane(digits, 0))
        self.assertFalse(
            CoreFoundation.CFCharacterSetHasMemberInPlane(digits, 4))

        self.assertTrue(
            CoreFoundation.CFCharacterSetIsCharacterMember(
                letters, b"A".decode("latin1")))
        self.assertFalse(
            CoreFoundation.CFCharacterSetIsCharacterMember(
                letters, b"9".decode("latin1")))

        data = CoreFoundation.CFCharacterSetCreateBitmapRepresentation(
            None, charset)
        self.assertIsInstance(data, CoreFoundation.CFDataRef)
Beispiel #11
0
    def testCreateWithBytes(self):
        url = b"http://www.omroep.nl/"

        ref = CoreFoundation.CFURLCreateWithBytes(
            None, url, len(url), CoreFoundation.kCFStringEncodingUTF8, None
        )
        self.assertIsInstance(ref, CoreFoundation.CFURLRef)

        strval = CoreFoundation.CFURLGetString(ref)
        self.assertEqual(strval, str(url, "utf-8"))

        ref2 = CoreFoundation.CFURLCreateWithBytes(
            None, url, len(url), CoreFoundation.kCFStringEncodingUTF8, ref
        )
        self.assertIsInstance(ref2, CoreFoundation.CFURLRef)

        a = array.array("b", b"http://www.nu.nl/")
        ref3 = CoreFoundation.CFURLCreateWithBytes(
            None, a, len(a), CoreFoundation.kCFStringEncodingUTF8, None
        )
        self.assertIsInstance(ref3, CoreFoundation.CFURLRef)

        # Explictely test for str's buffer madness.
        self.assertRaises(
            (ValueError, TypeError),
            CoreFoundation.CFURLCreateWithBytes,
            None,
            str(url),
            len(url),
            CoreFoundation.kCFStringEncodingUTF8,
            None,
        )
Beispiel #12
0
    def testBSearchValues(self):
        # This method causes a hard crash, reason unclear.
        array = CoreFoundation.CFArrayCreate(
            None, range(20), 20, CoreFoundation.kCFTypeArrayCallBacks)

        self.assertArgHasType(CoreFoundation.CFArrayBSearchValues, 2, b"@")
        self.assertArgIsFunction(CoreFoundation.CFArrayBSearchValues, 3,
                                 b"l@@@", False)
        self.assertArgHasType(CoreFoundation.CFArrayBSearchValues, 4, b"@")

        def compare(l, r, context):
            return cmp(l, r)

        r = CoreFoundation.CFArrayBSearchValues(array, (0, 20), 10, compare,
                                                None)
        self.assertEqual(r, 10)

        r = CoreFoundation.CFArrayBSearchValues(array, (0, 20), 9.5, compare,
                                                None)
        self.assertEqual(r, 10)

        r = CoreFoundation.CFArrayBSearchValues(array, (0, 20), 99, compare,
                                                None)
        self.assertTrue(r >= 20)

        r = CoreFoundation.CFArrayBSearchValues(array, (0, 20), -1, compare,
                                                None)
        self.assertEqual(r, 0)
Beispiel #13
0
    def testCreation(self):
        dictionary = CoreFoundation.CFDictionaryCreate(
            None,
            ("aap", "noot", "mies", "wim"),
            ("monkey", "nut", "missy", "john"),
            4,
            CoreFoundation.kCFTypeDictionaryKeyCallBacks,
            CoreFoundation.kCFTypeDictionaryValueCallBacks,
        )
        self.assertIsInstance(dictionary, CoreFoundation.CFDictionaryRef)
        self.assertEqual(dictionary, {
            "aap": "monkey",
            "noot": "nut",
            "mies": "missy",
            "wim": "john"
        })

        dictionary = CoreFoundation.CFDictionaryCreateMutable(
            None,
            0,
            CoreFoundation.kCFTypeDictionaryKeyCallBacks,
            CoreFoundation.kCFTypeDictionaryValueCallBacks,
        )
        self.assertIsInstance(dictionary,
                              CoreFoundation.CFMutableDictionaryRef)
        CoreFoundation.CFDictionarySetValue(dictionary, "hello", "world")
        self.assertEqual(dictionary, {"hello": "world"})
Beispiel #14
0
    def testApplyFunction(self):
        dictionary = CoreFoundation.CFDictionaryCreate(
            None,
            ("aap", "noot", "mies", "wim"),
            ("monkey", "nut", "missy", "john"),
            4,
            CoreFoundation.kCFTypeDictionaryKeyCallBacks,
            CoreFoundation.kCFTypeDictionaryValueCallBacks,
        )

        context = []

        def function(key, value, context):
            context.append((key, value))

        self.assertArgIsFunction(CoreFoundation.CFDictionaryApplyFunction, 1,
                                 b"v@@@", False)
        self.assertArgHasType(CoreFoundation.CFDictionaryApplyFunction, 2,
                              b"@")
        CoreFoundation.CFDictionaryApplyFunction(dictionary, function, context)

        context.sort()
        self.assertEqual(len(context), 4)
        self.assertEqual(
            context,
            [
                (b"aap".decode("ascii"), b"monkey".decode("ascii")),
                (b"mies".decode("ascii"), b"missy".decode("ascii")),
                (b"noot".decode("ascii"), b"nut".decode("ascii")),
                (b"wim".decode("ascii"), b"john".decode("ascii")),
            ],
        )
Beispiel #15
0
    def testContains(self):
        array = CoreFoundation.CFArrayCreate(
            None, ["a", 2, 3, 4, 4, 2], 6, CoreFoundation.kCFTypeArrayCallBacks
        )
        self.assertEqual(array, ["a", 2, 3, 4, 4, 2])
        self.assertIsInstance(array, NSArray)

        self.assertFalse(CoreFoundation.CFArrayContainsValue(array, (0, 6), "hello"))
        self.assertTrue(CoreFoundation.CFArrayContainsValue(array, (0, 6), 4))
        self.assertFalse(CoreFoundation.CFArrayContainsValue(array, (0, 2), 4))

        self.assertEqual(
            CoreFoundation.CFArrayGetFirstIndexOfValue(array, (0, 6), 3), 2
        )
        self.assertEqual(
            CoreFoundation.CFArrayGetFirstIndexOfValue(array, (0, 6), 2), 1
        )
        self.assertEqual(
            CoreFoundation.CFArrayGetFirstIndexOfValue(array, (0, 6), "hello"),
            CoreFoundation.kCFNotFound,
        )
        self.assertEqual(CoreFoundation.CFArrayGetLastIndexOfValue(array, (0, 6), 3), 2)
        self.assertEqual(CoreFoundation.CFArrayGetLastIndexOfValue(array, (0, 6), 2), 5)
        self.assertEqual(
            CoreFoundation.CFArrayGetLastIndexOfValue(array, (0, 6), "hello"),
            CoreFoundation.kCFNotFound,
        )
        self.assertArgHasType(CoreFoundation.CFArrayGetFirstIndexOfValue, 2, b"@")
        self.assertArgHasType(CoreFoundation.CFArrayGetLastIndexOfValue, 2, b"@")
    def read(self, key):
        """
        Read a preference value for the specified key. Nested values can be
        access by giving all keys and indexes, separated by colons (:).
        Indexes are zero-based.

        Example: 'NSToolbar Configuration Browser:TB Item Identifiers:1'

        Here we assume that the plist root is a dict, not an array. So first
        key's level should always be a key (string) not an index (int).
        """
        # Can't pass an array index to CFPreferencesCopyAppValue,
        # we could probably read the entire plist in this case.

        keys_n_idxs = self._split_keys_n_idxs(key)
        # Get value/structure of the first level key.
        if self._is_current_app_and_user():
            value = CoreFoundation.CFPreferencesCopyAppValue(
                keys_n_idxs[0], self.domain)
        else:
            value = CoreFoundation.CFPreferencesCopyValue(
                keys_n_idxs[0], self.domain, self.user, self.host)
        # If there's more then one key level, follow the structure until the
        # last level is reach or return None if some substructures are missing.
        for key_or_idx in keys_n_idxs[1:]:
            try:
                value = value[key_or_idx]
            except (KeyError, IndexError, TypeError, ValueError):
                return None

        value = self._normalize_to_python(value)
        return value
 def testGetting(self):
     ref = CoreFoundation.CFNotificationCenterGetLocalCenter()
     self.assertIsInstance(ref, CoreFoundation.CFNotificationCenterRef)
     ref = CoreFoundation.CFNotificationCenterGetDistributedCenter()
     self.assertIsInstance(ref, CoreFoundation.CFNotificationCenterRef)
     ref = CoreFoundation.CFNotificationCenterGetDarwinNotifyCenter()
     self.assertIsInstance(ref, CoreFoundation.CFNotificationCenterRef)
Beispiel #18
0
    def testCreateFromUUIDBytes(self):
        bytes_value = CoreFoundation.CFUUIDBytes(*range(16, 32))
        uuid = CoreFoundation.CFUUIDCreateFromUUIDBytes(None, bytes_value)

        self.assertIsNot(uuid, None)
        self.assertIsInstance(uuid, CoreFoundation.CFUUIDRef)
        text = CoreFoundation.CFUUIDCreateString(None, uuid)
        self.assertEqual(text, "10111213-1415-1617-1819-1A1B1C1D1E1F")
Beispiel #19
0
 def testCopy(self):
     bag = CoreFoundation.CFBagCreate(None, [1, 1, 2, 3, 4], 5)
     self.assertIsInstance(bag, CoreFoundation.CFBagRef)
     bag2 = CoreFoundation.CFBagCreateCopy(None, bag)
     self.assertIsInstance(bag2, CoreFoundation.CFBagRef)
     bag3 = CoreFoundation.CFBagCreateMutableCopy(None, 0, bag)
     self.assertIsInstance(bag3, CoreFoundation.CFBagRef)
     self.assertIsNot(bag3, bag)
Beispiel #20
0
    def testFunctions10_7(self):
        self.assertArgIsBOOL(CoreFoundation.CFRunLoopObserverCreateWithHandler, 2)
        self.assertArgIsBlock(
            CoreFoundation.CFRunLoopObserverCreateWithHandler,
            4,
            b"v^{__CFRunLoopObserver=}" + objc._C_NSUInteger,
        )

        lst = []

        def record(observer, activity):
            lst.append((observer, activity))

        ref = CoreFoundation.CFRunLoopObserverCreateWithHandler(
            None, CoreFoundation.kCFRunLoopAllActivities, False, 0, record
        )
        self.assertIsInstance(ref, CoreFoundation.CFRunLoopObserverRef)

        runloop_mode = CoreFoundation.kCFRunLoopDefaultMode
        rl = CoreFoundation.CFRunLoopGetCurrent()

        CoreFoundation.CFRunLoopAddObserver(rl, ref, runloop_mode)
        res = CoreFoundation.CFRunLoopRunInMode(runloop_mode, 0.5, True)
        CoreFoundation.CFRunLoopRemoveObserver(rl, ref, runloop_mode)

        self.assertNotEqual(lst, [])
        for a, b in lst:
            self.assertEqual(a, ref)
            self.assertIsInstance(b, int)

        self.assertArgIsBlock(
            CoreFoundation.CFRunLoopTimerCreateWithHandler, 5, b"v^{__CFRunLoopTimer=}"
        )
        lst = []
        ref = CoreFoundation.CFRunLoopTimerCreateWithHandler(
            None,
            CoreFoundation.CFAbsoluteTimeGetCurrent() + 2.9,
            0.0,
            0,
            0,
            lambda x: lst.append(x),
        )
        self.assertIsInstance(ref, CoreFoundation.CFRunLoopTimerRef)

        CoreFoundation.CFRunLoopAddTimer(rl, ref, runloop_mode)
        res = CoreFoundation.CFRunLoopRunInMode(runloop_mode, 6.0, True)
        self.assertIsInstance(res, int)
        CoreFoundation.CFRunLoopRemoveTimer(rl, ref, runloop_mode)

        import __main__

        # XXX: See issue #11 in the pyobjc tracker
        if "setup" in __main__.__file__:
            return

        self.assertNotEqual(lst, [])
        for a in lst:
            self.assertEqual(a, ref)
Beispiel #21
0
    def testNameRegistry(self):
        p1 = CoreFoundation.CFSocketGetDefaultNameRegistryPortNumber()
        self.assertIsInstance(p1, int)
        CoreFoundation.CFSocketSetDefaultNameRegistryPortNumber(p1 + 1)
        p2 = CoreFoundation.CFSocketGetDefaultNameRegistryPortNumber()
        self.assertIsInstance(p2, int)
        self.assertEqual(p2, p1 + 1)

        CoreFoundation.CFSocketSetDefaultNameRegistryPortNumber(p1)
Beispiel #22
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
Beispiel #23
0
 def testCreate(self):
     self.assertResultIsCFRetained(CoreFoundation.CFUUIDCreate)
     uuid = CoreFoundation.CFUUIDCreate(None)
     self.assertIsNot(uuid, None)
     self.assertIsInstance(uuid, CoreFoundation.CFUUIDRef)
     text = CoreFoundation.CFUUIDCreateString(None, uuid)
     self.assertIsInstance(text, str)
     m = re.match("^[0-9A-Z]{8}(-[0-9A-Z]{4}){3}-[0-9A-Z]{12}$", text)
     self.assertIsNot(m, None)
Beispiel #24
0
    def testCreation(self):
        context = object()
        tree = CoreFoundation.CFTreeCreate(None, context)

        self.assertIsInstance(tree, CoreFoundation.CFTreeRef)

        self.assertTrue(CoreFoundation.CFTreeGetContext(tree, None) is context)
        CoreFoundation.CFTreeSetContext(tree, 42)
        self.assertEqual(CoreFoundation.CFTreeGetContext(tree, None), 42)
 def testCreate(self):
     val = CoreFoundation.CFAttributedStringCreate(
         None, b"hello".decode("ascii"), {b"foo".decode("ascii"): 42})
     self.assertIsInstance(val, CoreFoundation.CFAttributedStringRef)
     val = CoreFoundation.CFAttributedStringCreateWithSubstring(
         None, val, (1, 2))
     self.assertIsInstance(val, CoreFoundation.CFAttributedStringRef)
     val2 = CoreFoundation.CFAttributedStringCreateCopy(None, val)
     self.assertIs(val2, val)
Beispiel #26
0
    def testCopy(self):
        heap = CoreFoundation.CFBinaryHeapCreate(None, 0)
        self.assertIsInstance(heap, CoreFoundation.CFBinaryHeapRef)

        CoreFoundation.CFBinaryHeapAddValue(heap, "hello")
        CoreFoundation.CFBinaryHeapAddValue(heap, "world")
        CoreFoundation.CFBinaryHeapAddValue(heap, "aapjes")

        heap2 = CoreFoundation.CFBinaryHeapCreateCopy(None, 0, heap)
        self.assertIsInstance(heap2, CoreFoundation.CFBinaryHeapRef)
Beispiel #27
0
 def testBoolean(self):
     self.assertIsInstance(CoreFoundation.CFBooleanGetTypeID(), int)
     self.assertIs(
         CoreFoundation.CFBooleanGetValue(CoreFoundation.kCFBooleanTrue),
         True)
     self.assertIs(
         CoreFoundation.CFBooleanGetValue(CoreFoundation.kCFBooleanFalse),
         False)
     self.assertTrue(CoreFoundation.CFBooleanGetValue(True))
     self.assertFalse(CoreFoundation.CFBooleanGetValue(False))
    def testInspection(self):
        def callout(fd, types, context):
            pass

        class Context:
            pass

        context = Context()
        fd = CoreFoundation.CFFileDescriptorCreate(None, 0, False, callout, context)
        self.assertIsInstance(fd, CoreFoundation.CFFileDescriptorRef)
        self.assertEqual(CoreFoundation.CFFileDescriptorGetNativeDescriptor(fd), 0)
        ctx = CoreFoundation.CFFileDescriptorGetContext(fd, None)
        self.assertIs(ctx, context)
        CoreFoundation.CFFileDescriptorEnableCallBacks(
            fd, CoreFoundation.kCFFileDescriptorReadCallBack
        )
        CoreFoundation.CFFileDescriptorDisableCallBacks(
            fd,
            CoreFoundation.kCFFileDescriptorReadCallBack
            | CoreFoundation.kCFFileDescriptorWriteCallBack,
        )

        rls = CoreFoundation.CFFileDescriptorCreateRunLoopSource(None, fd, 0)
        self.assertIsInstance(rls, CoreFoundation.CFRunLoopSourceRef)
        self.assertTrue(CoreFoundation.CFFileDescriptorIsValid(fd))
        CoreFoundation.CFFileDescriptorInvalidate(fd)
        self.assertFalse(CoreFoundation.CFFileDescriptorIsValid(fd))

        self.assertResultIsBOOL(CoreFoundation.CFFileDescriptorIsValid)
Beispiel #29
0
    def testUpdating(self):
        base = CoreFoundation.CFURLCreateWithString(
            None, b"http://www.omroep.nl/sport".decode("ascii"), None
        )
        self.assertIsInstance(base, CoreFoundation.CFURLRef)

        url = CoreFoundation.CFURLCreateCopyAppendingPathComponent(
            None, base, "soccer", True
        )
        self.assertIsInstance(url, CoreFoundation.CFURLRef)

        strval = CoreFoundation.CFURLGetString(url)
        self.assertEqual(strval, "http://www.omroep.nl/sport/soccer/")

        url = CoreFoundation.CFURLCreateCopyDeletingLastPathComponent(None, base)
        self.assertIsInstance(url, CoreFoundation.CFURLRef)
        strval = CoreFoundation.CFURLGetString(url)
        self.assertEqual(strval, "http://www.omroep.nl/")

        url = CoreFoundation.CFURLCreateCopyAppendingPathExtension(None, base, "cgi")
        self.assertIsInstance(url, CoreFoundation.CFURLRef)
        strval = CoreFoundation.CFURLGetString(url)
        self.assertEqual(strval, "http://www.omroep.nl/sport.cgi")

        url2 = CoreFoundation.CFURLCreateCopyDeletingPathExtension(None, base)
        self.assertIsInstance(url2, CoreFoundation.CFURLRef)
        strval = CoreFoundation.CFURLGetString(url2)
        self.assertEqual(strval, "http://www.omroep.nl/sport")
Beispiel #30
0
 def testPlugin(self):
     url = CoreFoundation.CFURLCreateWithFileSystemPath(
         None,
         b"/System/Library/Components/AppleScript.component".decode("ascii"),
         CoreFoundation.kCFURLPOSIXPathStyle,
         True,
     )
     bundle = CoreFoundation.CFBundleCreate(None, url)
     self.assertIsInstance(bundle, CoreFoundation.CFBundleRef)
     ref = CoreFoundation.CFBundleGetPlugIn(bundle)
     self.assertIs(ref, None)