Beispiel #1
0
    def test_auto_struct_creation(self):
        "Structs from method signatures are created automatically."
        Example = ObjCClass('Example')

        types.unregister_encoding_all(b'{simple=ii}')
        types.unregister_encoding_all(b'{simple}')
        types.unregister_encoding_all(b'{complex=[4s]^?{simple=ii}^{complex}b8b16b8}')
        types.unregister_encoding_all(b'{complex}')

        # Look up the method, so the return/argument types are decoded and the structs are registered.
        Example.doStuffWithStruct_

        struct_simple = types.ctype_for_encoding(b'{simple=ii}')
        self.assertEqual(struct_simple, types.ctype_for_encoding(b'{simple}'))

        simple = struct_simple(123, 456)
        ret = Example.doStuffWithStruct_(simple)
        struct_complex = types.ctype_for_encoding(b'{complex=[4s]^?{simple=ii}^{complex}b8b16b8}')
        self.assertIsInstance(ret, struct_complex)
        self.assertEqual(struct_complex, types.ctype_for_encoding(b'{complex}'))
        self.assertEqual(list(ret.field_0), [1, 2, 3, 4])
        self.assertEqual(ret.field_1.value, None)
        self.assertEqual(ret.field_2.field_0, 123)
        self.assertEqual(ret.field_2.field_1, 456)
        self.assertEqual(cast(ret.field_3, c_void_p).value, None)
        self.assertEqual(ret.field_4, 0)
        self.assertEqual(ret.field_5, 1)
        self.assertEqual(ret.field_6, 2)
Beispiel #2
0
    def test_enum_argument(self):
        "An enumerated type can be used as an argument."
        Example = ObjCClass('Example')

        obj = Example.alloc().init()

        self.assertEqual(obj.accessBaseIntField(), 22)
        self.assertEqual(obj.accessIntField(), 33)

        class MyEnum(Enum):
            value1 = 8888
            value2 = 9999
            value3 = 3333
            value4 = 4444

        obj.mutateBaseIntFieldWithValue_(MyEnum.value1)
        obj.mutateIntFieldWithValue_(MyEnum.value2)

        self.assertEqual(obj.accessBaseIntField(), MyEnum.value1.value)
        self.assertEqual(obj.accessIntField(), MyEnum.value2.value)

        obj.baseIntField = MyEnum.value3
        obj.intField = MyEnum.value4

        self.assertEqual(obj.accessBaseIntField(), MyEnum.value3.value)
        self.assertEqual(obj.accessIntField(), MyEnum.value4.value)
Beispiel #3
0
    def test_no_convert_return(self):
        Example = ObjCClass("Example")
        example = Example.alloc().init()

        res = example.toString(convert_result=False)
        self.assertNotIsInstance(res, ObjCInstance)
        self.assertEqual(str(ObjCInstance(res)), "This is an ObjC Example object")
Beispiel #4
0
    def test_number_return(self):
        "If a method or field returns a NSNumber, it is converted back to native types"
        Example = ObjCClass('Example')
        example = Example.alloc().init()

        self.assertEqual(example.theAnswer(), 42)
        self.assertAlmostEqual(example.twopi(), 2.0 * math.pi, 5)
Beispiel #5
0
    def test_decimal_method(self):
        "A method with a NSDecimalNumber arguments can be handled."
        Example = ObjCClass('Example')
        example = Example.alloc().init()

        result = example.areaOfTriangleWithWidth_andHeight_(Decimal('3.0'), Decimal('4.0'))
        self.assertEqual(result, Decimal('6.0'))
        self.assertIsInstance(result, Decimal, 'Result should be a Decimal')
Beispiel #6
0
    def test_struct_return_send(self):
        "Methods returning structs of different sizes by value can be handled when using send_message."
        Example = ObjCClass('Example')
        example = Example.alloc().init()

        self.assertEqual(send_message(example, "intSizedStruct", restype=struct_int_sized).x, b"abc")
        self.assertEqual(send_message(example, "oddlySizedStruct", restype=struct_oddly_sized).x, b"abcd")
        self.assertEqual(send_message(example, "largeStruct", restype=struct_large).x, b"abcdefghijklmnop")
Beispiel #7
0
    def test_block_receiver_unannotated(self):
        BlockReceiverExample = ObjCClass("BlockReceiverExample")
        instance = BlockReceiverExample.alloc().init()

        def block(a, b):
            return a + b
        with self.assertRaises(ValueError):
            instance.receiverMethod_(block)
Beispiel #8
0
    def test_sequence_arg_to_struct(self):
        "Sequence arguments are converted to structures."
        Example = ObjCClass('Example')

        ret = Example.extractSimpleStruct(([9, 8, 7, 6], None, (987, 654), None, 0, 0, 0))
        struct_simple = types.ctype_for_encoding(b'{simple=ii}')
        self.assertIsInstance(ret, struct_simple)
        self.assertEqual(ret.field_0, 987)
        self.assertEqual(ret.field_1, 654)
Beispiel #9
0
    def test_non_static_access_static(self):
        "A static field/method cannot be accessed from an instance context"
        Example = ObjCClass('Example')

        with self.assertRaises(AttributeError):
            Example.intField

        with self.assertRaises(AttributeError):
            Example.accessIntField()
Beispiel #10
0
    def test_argument(self):
        Example = ObjCClass("Example")
        example = Example.alloc().init()

        a = self.make_array(self.py_list)
        # Call a method with an NSArray instance
        self.assertEqual(example.processArray(a), 'two')
        # Call the same method with the Python list
        self.assertEqual(example.processArray(self.py_list), 'two')
Beispiel #11
0
    def test_block_round_trip(self):
        BlockRoundTrip = ObjCClass("BlockRoundTrip")
        instance = BlockRoundTrip.alloc().init()

        def block(a: int, b: int) -> int:
            return a + b

        returned_block = instance.roundTrip_(block)
        self.assertEqual(returned_block(8, 9), 17)
Beispiel #12
0
    def test_property(self):
        Example = ObjCClass("Example")
        example = Example.alloc().init()

        a = self.make_array(self.py_list)
        example.array = a

        self.assertEqual(example.array, self.py_list)
        self.assertIsInstance(example.array, ObjCListInstance)
        self.assertEqual(example.array[1], 'two')
Beispiel #13
0
 def test_block_delegate_method_manual_pytypes(self):
     class DelegateManualPY(NSObject):
         @objc_method
         def exampleMethod_(self, block):
             ObjCBlock(block, None, int, int)(2, 3)
     BlockObjectExample = ObjCClass("BlockObjectExample")
     delegate = DelegateManualPY.alloc().init()
     instance = BlockObjectExample.alloc().initWithDelegate_(delegate)
     result = instance.blockExample()
     self.assertEqual(result, 5)
Beispiel #14
0
    def test_block_receiver_explicit(self):
        BlockReceiverExample = ObjCClass("BlockReceiverExample")
        instance = BlockReceiverExample.alloc().init()

        values = []

        block = Block(lambda a, b: values.append(a + b), None, int, int)
        instance.receiverMethod_(block)

        self.assertEqual(values, [27])
Beispiel #15
0
 def test_block_delegate_auto(self):
     class DelegateAuto(NSObject):
         @objc_method
         def exampleMethod_(self, block: objc_block):
             block(4, 5)
     BlockObjectExample = ObjCClass("BlockObjectExample")
     delegate = DelegateAuto.alloc().init()
     instance = BlockObjectExample.alloc().initWithDelegate_(delegate)
     result = instance.blockExample()
     self.assertEqual(result, 9)
Beispiel #16
0
    def test_property(self):
        Example = ObjCClass("Example")
        example = Example.alloc().init()

        d = self.make_dictionary(self.py_dict)
        example.dict = d

        self.assertEqual(example.dict, self.py_dict)
        self.assertIsInstance(example.dict, ObjCDictInstance)
        self.assertEqual(example.dict['one'], 'ONE')
Beispiel #17
0
    def test_block_receiver(self):
        BlockReceiverExample = ObjCClass("BlockReceiverExample")
        instance = BlockReceiverExample.alloc().init()

        values = []

        def block(a: int, b: int) -> None:
            values.append(a + b)
        instance.receiverMethod_(block)

        self.assertEqual(values, [27])
Beispiel #18
0
    def test_non_existent_static_method(self):
        "An attribute error is raised if you invoke a non-existent static method."
        Example = ObjCClass('Example')

        # Non-existent methods raise an error.
        with self.assertRaises(AttributeError):
            Example.static_method_doesnt_exist()

        # Cache warming doesn't affect anything.
        with self.assertRaises(AttributeError):
            Example.static_method_doesnt_exist()
Beispiel #19
0
    def test_static_access_non_static(self):
        "An instance field/method cannot be accessed from the static context"
        Example = ObjCClass('Example')

        obj = Example.alloc().init()

        with self.assertRaises(AttributeError):
            obj.staticIntField

        with self.assertRaises(AttributeError):
            obj.get_staticIntField()
Beispiel #20
0
    def test_object_return(self):
        "If a method or field returns an object, you get an instance of that type returned"
        Example = ObjCClass('Example')
        example = Example.alloc().init()

        Thing = ObjCClass('Thing')
        thing = Thing.alloc().initWithName_value_('This is thing', 2)

        example.thing = thing

        the_thing = example.thing
        self.assertEqual(the_thing.toString(), "This is thing 2")
Beispiel #21
0
 def test_double_method_send(self):
     "A method with a double argument can be handled by send_message."
     Example = ObjCClass('Example')
     example = Example.alloc().init()
     self.assertAlmostEqual(
         send_message(
             example, "areaOfCircle:", 1.5,
             restype=c_double,
             argtypes=[c_double]
         ),
         1.5 * math.pi, 5
     )
Beispiel #22
0
    def test_non_existent_field(self):
        "An attribute error is raised if you invoke a non-existent field."
        Example = ObjCClass('Example')

        obj1 = Example.alloc().init()

        # Non-existent fields raise an error.
        with self.assertRaises(AttributeError):
            obj1.field_doesnt_exist

        # Cache warming doesn't affect anything.
        with self.assertRaises(AttributeError):
            obj1.field_doesnt_exist
Beispiel #23
0
    def test_multitype_list_property(self):
        class MultitypeListContainer(NSObject):
            data = objc_property()

        Example = ObjCClass('Example')
        example = Example.alloc().init()

        # All types can be stored in a list.
        obj = MultitypeListContainer.alloc().init()

        obj.data = [4, True, 'Hello', example]
        self.assertEqual(obj.data, [4, True, 'Hello', example])
        self.assertIsInstance(obj.data, ObjCListInstance)
Beispiel #24
0
    def test_struct_return(self):
        "Methods returning structs of different sizes by value can be handled."
        Example = ObjCClass('Example')
        example = Example.alloc().init()

        types.register_encoding(b'{int_sized=[4c]}', struct_int_sized)
        self.assertEqual(example.intSizedStruct().x, b"abc")

        types.register_encoding(b'{oddly_sized=[5c]}', struct_oddly_sized)
        self.assertEqual(example.oddlySizedStruct().x, b"abcd")

        types.register_encoding(b'{large=[17c]}', struct_large)
        self.assertEqual(example.largeStruct().x, b"abcdefghijklmnop")
Beispiel #25
0
    def test_class_properties(self):
        "A Python class can have ObjC properties with synthesized getters and setters."

        NSURL = ObjCClass('NSURL')

        class URLBox(NSObject):

            url = objc_property(ObjCInstance)
            data = objc_property(ObjCInstance)

            @objc_method
            def getSchemeIfPresent(self):
                if self.url is not None:
                    return self.url.scheme
                return None

        box = URLBox.alloc().init()

        # Default property value is None
        self.assertIsNone(box.url)

        # Assign an object via synthesized property setter and call method that uses synthesized property getter
        url = NSURL.alloc().initWithString_('https://www.google.com')
        box.url = url
        self.assertEqual(box.getSchemeIfPresent(), 'https')

        # Assign None to dealloc property and see if method returns expected None
        box.url = None
        self.assertIsNone(box.getSchemeIfPresent())

        # Try composing URLs using constructors
        base = NSURL.URLWithString('https://pybee.org')
        full = NSURL.URLWithString('contributing/', relativeToURL=base)

        self.assertEqual(
            "Visit %s for details" % full.absoluteURL,
            "Visit https://pybee.org/contributing/ for details"
        )

        # ObjC type conversions are performed on property assignment.
        box.data = "Jabberwock"
        self.assertEqual(box.data, "Jabberwock")

        Example = ObjCClass('Example')
        example = Example.alloc().init()
        box.data = example
        self.assertEqual(box.data, example)

        box.data = None
        self.assertIsNone(box.data)
Beispiel #26
0
    def test_method(self):
        "An instance method can be invoked."
        Example = ObjCClass('Example')

        obj = Example.alloc().init()

        self.assertEqual(obj.accessBaseIntField(), 22)
        self.assertEqual(obj.accessIntField(), 33)

        obj.mutateBaseIntFieldWithValue_(8888)
        obj.mutateIntFieldWithValue_(9999)

        self.assertEqual(obj.accessBaseIntField(), 8888)
        self.assertEqual(obj.accessIntField(), 9999)
Beispiel #27
0
    def test_method_send(self):
        "An instance method can be invoked with send_message."
        Example = ObjCClass('Example')

        obj = Example.alloc().init()

        self.assertEqual(send_message(obj, "accessBaseIntField", restype=c_int), 22)
        self.assertEqual(send_message(obj, "accessIntField", restype=c_int), 33)

        send_message(obj, "mutateBaseIntFieldWithValue:", 8888, restype=None, argtypes=[c_int])
        send_message(obj, "mutateIntFieldWithValue:", 9999, restype=None, argtypes=[c_int])

        self.assertEqual(send_message(obj, "accessBaseIntField", restype=c_int), 8888)
        self.assertEqual(send_message(obj, "accessIntField", restype=c_int), 9999)
Beispiel #28
0
    def test_field(self):
        "A field on an instance can be accessed and mutated"

        Example = ObjCClass('Example')

        obj = Example.alloc().init()

        self.assertEqual(obj.baseIntField, 22)
        self.assertEqual(obj.intField, 33)

        obj.baseIntField = 8888
        obj.intField = 9999

        self.assertEqual(obj.baseIntField, 8888)
        self.assertEqual(obj.intField, 9999)
Beispiel #29
0
    def test_argument(self):
        Example = ObjCClass("Example")
        example = Example.alloc().init()

        d = self.make_dictionary(self.py_dict)
        # Call a method with an NSDictionary instance
        self.assertIsNone(example.processDictionary(d))
        # Call the same method with the raw Python dictionary
        self.assertIsNone(example.processDictionary(self.py_dict))

        raw = {'data': 'stuff', 'other': 'gadgets'}
        d = self.make_dictionary(raw)
        # Call a method with an NSDictionary instance
        self.assertEqual(example.processDictionary(d), 'stuff')
        # Call the same method with the raw Python dictionary
        self.assertEqual(example.processDictionary(raw), 'stuff')
Beispiel #30
0
    def test_block_delegate_auto_struct(self):
        class BlockStruct(Structure):
            _fields_ = [
                ('a', c_int),
                ('b', c_int),
            ]

        class DelegateAutoStruct(NSObject):
            @objc_method
            def structBlockMethod_(self, block: objc_block) -> int:
                return block(BlockStruct(42, 43))
        BlockObjectExample = ObjCClass("BlockObjectExample")
        delegate = DelegateAutoStruct.alloc().init()
        instance = BlockObjectExample.alloc().initWithDelegate_(delegate)
        result = instance.structBlockExample()
        self.assertEqual(result, 85)
Beispiel #31
0
def _Class(name):
    try:
        return ObjCClass(name)
    except NameError:
        return None
Beispiel #32
0
# -*- coding: utf-8 -*-
"""
Sharing Items

This module allows you to share items, to import files and to open URLs.
"""

from rubicon.objc import ObjCClass
from UIKit import UIApplication as __UIApplication__
import pyto
import mainthread
import threading
from typing import List
__PySharingHelper__ = pyto.PySharingHelper
NSURL = ObjCClass("NSURL")


def share_items(items: object):
    """
    Opens a share sheet with given items.
    
    :param items: Items to be shared with the sheet.
    """

    __PySharingHelper__.share(items)


if __host__ is not widget:

    def quick_look(path: str):
        """
Beispiel #33
0
import base64
from UIKit import UIImage
from io import BytesIO

try:
    from rubicon.objc import ObjCClass
except ValueError:

    def ObjCClass(name):
        return None


NSData = ObjCClass("NSData")


def __ui_image_from_pil_image__(image):

    if image is None:
        return None

    with BytesIO() as buffered:
        image.save(buffered, format="PNG")
        img_str = base64.b64encode(buffered.getvalue())

    data = NSData.alloc().initWithBase64EncodedString(img_str, options=0)
    image = UIImage.alloc().initWithData(data)
    data.release()
    return image


def __pil_image_from_ui_image__(image):
Beispiel #34
0
import logging
from collections import deque

import click

from maestral.config import MaestralConfig
from maestral.constants import IS_MACOS_BUNDLE

if platform.system() == 'Darwin':

    from ctypes import cdll, util
    from rubicon.objc import ObjCClass

    uns = cdll.LoadLibrary(util.find_library('UserNotifications'))

    UNUserNotificationCenter = ObjCClass('UNUserNotificationCenter')
    UNMutableNotificationContent = ObjCClass('UNMutableNotificationContent')
    UNNotificationRequest = ObjCClass('UNNotificationRequest')

    NSUserNotification = ObjCClass('NSUserNotification')
    NSUserNotificationCenter = ObjCClass('NSUserNotificationCenter')
    NSDate = ObjCClass('NSDate')

elif platform.system() == 'Linux':
    from jeepney.integrate.blocking import Proxy, connect_and_authenticate
    from maestral.utils.dbus_interfaces import FreedesktopNotifications

logger = logging.getLogger(__name__)

APP_ICON_PATH = pkg_resources.resource_filename('maestral',
                                                'resources/maestral.png')
Beispiel #35
0
from ctypes import cdll, c_int, c_void_p, util
from rubicon.objc import ObjCClass, objc_method
from rubicon.objc.core_foundation import from_value, to_value

__all__ = ('UIKit', 'ObjCClass', 'objc_method', 'NSObject', 'UIScreen',
           'UIView', 'UIViewController', 'UIResponder', 'UIWindow', 'UIColor',
           'UILabel')

UIKit = cdll.LoadLibrary(util.find_library('UIKit'))
UIKit.UIApplicationMain.restypes = (c_int, c_void_p, c_void_p, c_void_p)
UIKit.UIApplicationMain.restype = c_int

for item in __all__:
    if item not in globals():
        globals()[item] = ObjCClass(item)


class ObjCAppDelegate(NSObject):
    @objc_method('@B')
    def application_didFinishLaunchingWithOptions_(self, launchOptions):
        self.__dict__['delegate'] = PyAppDelegate()
        return 0


class PyAppDelegate(object):
    def __init__(self):
        self.window = UIWindow.alloc().initWithFrame_(
            UIScreen.mainScreen().bounds)

        view_controller = UIViewController.alloc().init()
Beispiel #36
0
 def test_string_return(self):
     "If a method or field returns a string, you get a Python string back"
     Example = ObjCClass('Example')
     example = Example.alloc().init()
     self.assertEqual(example.toString(), "This is an ObjC Example object")
Beispiel #37
0
 def test_float_method(self):
     "A method with a float argument can be handled."
     Example = ObjCClass('Example')
     example = Example.alloc().init()
     self.assertEqual(example.areaOfSquare_(1.5), 2.25)
Beispiel #38
0
    def test_class_by_pointer(self):
        """An Objective-C class can be created from a pointer."""

        example_ptr = objc.objc_getClass(b"Example")
        Example = ObjCClass(example_ptr)
        self.assertEqual(Example, ObjCClass("Example"))
Beispiel #39
0
    def test_interface(self):
        "An ObjC protocol implementation can be defined in Python."

        results = {}

        NSObject = ObjCClass('NSObject')

        class Handler(NSObject):
            @objc_method
            def initWithValue_(self, value: int):
                self.value = value
                return self

            @objc_method
            def peek_withValue_(self, example, value: int) -> None:
                results['string'] = example.toString() + " peeked"
                results['int'] = value + self.value

            @objc_method
            def poke_withValue_(self, example, value: int) -> None:
                results['string'] = example.toString() + " poked"
                results['int'] = value + self.value

            @objc_method
            def reverse_(self, input):
                return ''.join(reversed(input))

            @objc_method
            def message(self):
                return "Alea iacta est."

            @objc_classmethod
            def fiddle_(cls, value: int) -> None:
                results['string'] = "Fiddled with it"
                results['int'] = value

        # Create two handler instances so we can check the right one
        # is being invoked.
        handler1 = Handler.alloc().initWithValue_(5)
        handler2 = Handler.alloc().initWithValue_(10)

        # Create an Example object, and register a handler with it.
        Example = ObjCClass('Example')
        example = Example.alloc().init()
        example.callback = handler2

        # Check some Python-side attributes
        self.assertEqual(handler1.value, 5)
        self.assertEqual(handler2.value, 10)

        # Invoke the callback; check that the results have been peeked as expected
        example.testPeek_(42)

        self.assertEqual(results['string'],
                         'This is an ObjC Example object peeked')
        self.assertEqual(results['int'], 52)

        example.testPoke_(37)

        self.assertEqual(results['string'],
                         'This is an ObjC Example object poked')
        self.assertEqual(results['int'], 47)

        self.assertEqual(example.getMessage(), 'Alea iacta est.')

        self.assertEqual(example.reverseIt_('Alea iacta est.'),
                         '.tse atcai aelA')

        Handler.fiddle_(99)

        self.assertEqual(results['string'], 'Fiddled with it')
        self.assertEqual(results['int'], 99)
Beispiel #40
0
    def test_nonexistant_class(self):
        """A NameError is raised if a class doesn't exist."""

        with self.assertRaises(NameError):
            ObjCClass('DoesNotExist')
Beispiel #41
0
class NSArrayMixinTest(unittest.TestCase):
    nsarray = ObjCClass('NSArray')
    nsmutablearray = ObjCClass('NSMutableArray')

    py_list = ['one', 'two', 'three']

    def make_array(self, contents=None):
        a = self.nsmutablearray.alloc().init()
        if contents is not None:
            for value in contents:
                a.addObject(value)

        return self.nsarray.arrayWithArray(a)

    def test_getitem(self):
        a = self.make_array(self.py_list)

        for pos, value in enumerate(self.py_list):
            self.assertEqual(a[pos], value)

        self.assertRaises(IndexError, lambda: a[len(self.py_list) + 10])

    def test_len(self):
        a = self.make_array(self.py_list)

        self.assertEqual(len(a), len(self.py_list))

    def test_iter(self):
        a = self.make_array(self.py_list)

        keys = list(self.py_list)
        for k in a:
            self.assertTrue(k in keys)
            keys.remove(k)

        self.assertTrue(len(keys) == 0)

    def test_contains(self):
        a = self.make_array(self.py_list)
        for value in self.py_list:
            self.assertTrue(value in a)

    def test_index(self):
        a = self.make_array(self.py_list)
        self.assertEqual(a.index('two'), 1)
        self.assertRaises(ValueError, lambda: a.index('umpteen'))

    def test_count(self):
        a = self.make_array(self.py_list)
        self.assertEqual(a.count('one'), 1)

    def test_copy(self):
        a = self.make_array(self.py_list)
        b = a.copy()
        self.assertEqual(b, a)
        self.assertEqual(b, self.py_list)

        self.assertRaises(AttributeError, lambda: b.append('four'))

    def test_equivalence(self):
        a = self.make_array(self.py_list)
        b = self.make_array(self.py_list)

        self.assertEqual(a, self.py_list)
        self.assertEqual(b, self.py_list)
        self.assertEqual(a, b)
        self.assertEqual(self.py_list, a)
        self.assertEqual(self.py_list, b)
        self.assertEqual(b, a)

    def test_slice_access(self):
        a = self.make_array(self.py_list * 2)
        self.assertEqual(a[1:4], ['two', 'three', 'one'])
        self.assertEqual(a[:-2], ['one', 'two', 'three', 'one'])
        self.assertEqual(a[4:], ['two', 'three'])
        self.assertEqual(a[1:5:2], ['two', 'one'])
Beispiel #42
0
class NSDictionaryMixinTest(unittest.TestCase):
    nsdict = ObjCClass('NSDictionary')
    nsmutabledict = ObjCClass('NSMutableDictionary')

    py_dict = {
        'one': 'ONE',
        'two': 'TWO',
        'three': 'THREE',
    }

    def make_dictionary(self, contents=None):
        d = self.nsmutabledict.alloc().init()
        if contents is not None:
            for key, value in contents.items():
                d.setObject_forKey_(value, key)

        return self.nsdict.dictionaryWithDictionary(d)

    def test_getitem(self):
        d = self.make_dictionary(self.py_dict)

        for key, value in self.py_dict.items():
            self.assertEqual(d[key], value)

        self.assertRaises(KeyError, lambda: d['NO SUCH KEY'])

    def test_iter(self):
        d = self.make_dictionary(self.py_dict)

        keys = set(self.py_dict)
        for k in d:
            self.assertTrue(k in keys)
            keys.remove(k)

        self.assertTrue(len(keys) == 0)

    def test_len(self):
        d = self.make_dictionary(self.py_dict)
        self.assertEqual(len(d), len(self.py_dict))

    def test_get(self):
        d = self.make_dictionary(self.py_dict)

        self.assertEqual(d.get('one'), 'ONE')
        self.assertEqual(d.get('two', None), 'TWO')
        self.assertEqual(d.get('four', None), None)
        self.assertEqual(d.get('five', 5), 5)
        self.assertEqual(d.get('six', None), None)

    def test_contains(self):
        d = self.make_dictionary(self.py_dict)
        for key in self.py_dict:
            self.assertTrue(key in d)

    def test_copy(self):
        d = self.make_dictionary(self.py_dict)
        e = d.copy()
        self.assertEqual(e, d)
        self.assertEqual(e, self.py_dict)

        def doomed():
            e['four'] = 'FOUR'

        self.assertRaises(TypeError, doomed)

    def test_keys(self):
        a = self.make_dictionary(self.py_dict)
        for k1, k2 in zip(sorted(a.keys()), sorted(self.py_dict.keys())):
            self.assertEqual(k1, k2)

    def test_values(self):
        a = self.make_dictionary(self.py_dict)
        for v1, v2 in zip(sorted(a.values()), sorted(self.py_dict.values())):
            self.assertEqual(v1, v2)

    def test_items(self):
        d = self.make_dictionary(self.py_dict)
        for i1, i2 in zip(sorted(d.items()), sorted(self.py_dict.items())):
            self.assertEqual(i1[0], i2[0])
            self.assertEqual(i1[1], i2[1])
Beispiel #43
0
from toga.constants import LEFT, RIGHT, CENTER, JUSTIFY

from toga_iOS.libs.core_graphics import CGContextRef

######################################################################
uikit = cdll.LoadLibrary(util.find_library('UIKit'))
######################################################################

uikit.UIApplicationMain.restype = c_int
uikit.UIApplicationMain.argtypes = [
    c_int, POINTER(c_char_p), c_void_p, c_void_p
]

######################################################################
# NSAttributedString.h
NSAttributedString = ObjCClass('NSAttributedString')

NSFontAttributeName = objc_const(uikit, 'NSFontAttributeName')
NSForegroundColorAttributeName = objc_const(uikit,
                                            'NSForegroundColorAttributeName')
NSStrokeColorAttributeName = objc_const(uikit, 'NSStrokeColorAttributeName')
NSStrokeWidthAttributeName = objc_const(uikit, 'NSStrokeWidthAttributeName')

######################################################################
# NSLayoutConstraint.h
NSLayoutConstraint = ObjCClass('NSLayoutConstraint')

NSLayoutRelationLessThanOrEqual = -1
NSLayoutRelationEqual = 0
NSLayoutRelationGreaterThanOrEqual = 1
Beispiel #44
0
 def test_partial_method_two_args(self):
     Example = ObjCClass("Example")
     self.assertEqual(Example.overloaded(12, extraArg=34), 12 + 34)
Beispiel #45
0
 def test_double_method(self):
     "A method with a double argument can be handled."
     Example = ObjCClass('Example')
     example = Example.alloc().init()
     self.assertAlmostEqual(example.areaOfCircle_(1.5), 1.5 * math.pi, 5)
Beispiel #46
0
 def test_partial_method_one_arg(self):
     Example = ObjCClass("Example")
     self.assertEqual(Example.overloaded(42), 42)
Beispiel #47
0
 def test_constant_string_return(self):
     "If a method or field returns a *constant* string, you get a Python string back"
     Example = ObjCClass('Example')
     example = Example.alloc().init()
     self.assertEqual(example.smiley(), "%-)")
Beispiel #48
0
 def test_partial_method_no_args(self):
     Example = ObjCClass("Example")
     self.assertEqual(Example.overloaded(), 0)
Beispiel #49
0
    def test_property_forcing(self):
        "An instance or property method can be explicitly declared as a property."
        Example = ObjCClass('Example')
        Example.declare_class_property('classMethod')
        Example.declare_class_property('classAmbiguous')
        Example.declare_property('instanceMethod')
        Example.declare_property('instanceAmbiguous')

        # A class method can be turned into a property
        self.assertEqual(Example.classMethod, 37)

        # An actual class property can be accessed as a property
        self.assertEqual(Example.classAmbiguous, 37)

        # An instance property can be accessed
        obj1 = Example.alloc().init()

        # An instance method can be turned into a property
        self.assertEqual(obj1.instanceMethod, 42)

        # An actual property can be accessed as a property
        self.assertEqual(obj1.instanceAmbiguous, 42)

        # Practical example: In Sierra, mainBundle was turned into a class property.
        # Previously, it was a method.
        NSBundle = ObjCClass('NSBundle')
        NSBundle.declare_class_property('mainBundle')
        self.assertFalse(
            type(NSBundle.mainBundle) == ObjCBoundMethod,
            'NSBundle.mainBundle should not be a method')
Beispiel #50
0
try:
    from PIL import Image as PIL_Image
except ModuleNotFoundError:
    PIL_Image = None
except ImportError:
    PIL_Image = None


def __Class__(name):
    try:
        return ObjCClass("Pyto." + name)
    except NameError:
        return ObjCClass("WidgetExtension." + name)


UIDevice = ObjCClass("UIDevice")
__UIFont__ = ObjCClass("UIFont")


def wait_for_internet_connection():
    while not __Class__("InternetConnection").isReachable:
        sleep(0.2)


if (UIDevice is not None and
        float(str(UIDevice.currentDevice.systemVersion).split(".")[0]) < 14):
    raise ImportError(
        "Home Screen Widgets were introduced on iPadOS / iOS 14.")


class PytoUIView:  # Travis CI doesn't let me mark a parameter as 'ui.View' without importing PytoUI
Beispiel #51
0
    music.set_queue_with_items(music.pick_music())
    music.play()
"""

from pyto_ui import __pil_image_from_ui_image__
from typing import List
from pyto import PyMusicHelper, __Class__
from ctypes import cdll
import PIL
import threading
from __check_type__ import check

try:
    from rubicon.objc import ObjCClass

    MPMusicPlayerController = ObjCClass("MPMusicPlayerController")
    """ The 'MPMusicPlayerController' class from the 'MediaPlayer' framework. """

    MPMediaItem = ObjCClass("MPMediaItem")
    """ The 'MPMediaItem' class from the 'MediaPlayer' framework. """

    MPMediaItemCollection = ObjCClass("MPMediaItemCollection")
    """ The 'MPMediaItemCollection' class from the 'MediaPlayer' framework. """

    MPMediaQuery = ObjCClass("MPMediaQuery")
    """ The 'MPMusicMPMediaQueryPlayerController' class from the 'MediaPlayer' framework. """

    MediaPlayer = cdll.LoadLibrary(
        "/System/Library/Frameworks/MediaPlayer.framework/MediaPlayer")

    _PyMusicItem = __Class__("PyMusicItem")
Beispiel #52
0
import os
from ctypes import cast, c_char_p

import toga
from rubicon.objc import ObjCClass, objc_method
from toga.style import Pack
from toga_cocoa.libs import (NSDocument, NSURL, NSScreen, NSNumber, NSCursor,
                             NSCommandKeyMask)

NSMutableDictionary = ObjCClass('NSMutableDictionary')


class TogaSlideDeck(NSDocument):
    @objc_method
    def autosavesInPlace(self) -> bool:
        return True

    @objc_method
    def readFromFileWrapper_ofType_error_(self, fileWrapper, typeName,
                                          outError) -> bool:
        print("Read from File Wrapper: %s" % fileWrapper.filename)
        print("   type: %s" % typeName)

        if fileWrapper.isDirectory:
            # Multi-file .podium files must contain slides.md; may contain theme.css
            themeFile = fileWrapper.fileWrappers.valueForKey("theme.css")
            contentFile = fileWrapper.fileWrappers.valueForKey("slides.md")
            if contentFile is None:
                return False

            self.content = cast(contentFile.regularFileContents.bytes,
Beispiel #53
0
import os
import warnings
from rubicon.objc import ObjCClass
import _extensionsimporter
import ctypes
import threading
import weakref
import gc
from pyto import PyOutputHelper
from importlib import util
from importlib.machinery import ExtensionFileLoader, ModuleSpec, PathFinder
from types import BuiltinFunctionType
from inspect import isclass
from time import sleep

NSBundle = ObjCClass("NSBundle")


class __UpgradeException__(Exception):
    pass


if "widget" not in os.environ:
    from _sharing import open_url
    import urllib.parse
    from pyto import Python, __Class__

    def have_internet():
        return __Class__("InternetConnection").isReachable

    def update_mods():
Beispiel #54
0
import struct
from threading import Event
from typing import Tuple

from typing_extensions import Protocol as StructuralType

from . import MessagePayload, Transport
from ..messages import FirmwareUpload

IS_ANDROID = True
PROCESS_REPORTER = None
if "iOS_DATA" in os.environ:
    IS_ANDROID = False
    from rubicon.objc import ObjCClass

    PROCESS_REPORTER = ObjCClass(
        "OKBlueManager").sharedInstance().getNotificationCenter()
REPLEN = 64
REAL_REPLEN = REPLEN - 1
BLE_REPLEN = int(REPLEN * 3 - 3) if IS_ANDROID else int(REPLEN * 2 - 2)
REPLEN_NFC = 1024
V2_FIRST_CHUNK = 0x01
V2_NEXT_CHUNK = 0x02
V2_BEGIN_SESSION = 0x03
V2_END_SESSION = 0x04
HTTP = False
OFFSET = 0
TOTAL = 0
event = Event()

LOG = logging.getLogger(__name__)
Beispiel #55
0
def __Class__(name):
    try:
        return ObjCClass("Pyto." + name)
    except NameError:
        return ObjCClass("WidgetExtension." + name)
Beispiel #56
0
 def test_string_argument(self):
     "A method with a string argument can be passed."
     Example = ObjCClass('Example')
     example = Example.alloc().init()
     self.assertEqual(example.duplicateString_("Wagga"), "WaggaWagga")
 def test_python2_string_argument(self):
     "If a non-unicode string argument is provided, it is converted."
     Example = ObjCClass('Example')
     example = Example.alloc().init()
     self.assertEqual(example.duplicateString_(b"Wagga"), "WaggaWagga")
Beispiel #58
0
    def test_class_by_name(self):
        """An Objective-C class can be looked up by name."""

        Example = ObjCClass("Example")
        self.assertEqual(Example.name, "Example")
Beispiel #59
0
 def test_float_method_send(self):
     "A method with a float argument can be handled by send_message."
     Example = ObjCClass('Example')
     example = Example.alloc().init()
     self.assertEqual(send_message(example, "areaOfSquare:", 1.5, restype=c_float, argtypes=[c_float]), 2.25)
Beispiel #60
0
from rubicon.objc import objc_method, ObjCClass, SEL, send_message
from rubicon.objc.types import CGSize, CGRect, CGPoint, NSTimeInterval

import game
import sound


if __name__.split(".")[-1] == "__main__":
    # I'm ran as a module
    # drop low-level logging handler
    # set up logging properly
    del logging.root.handlers[:]
    logging.basicConfig(level=logging.DEBUG, handlers=[nslog.handler()])
    logging.debug("yep, in main")

UIView = ObjCClass("UIView")
UILabel = ObjCClass("UILabel")
UIColor = ObjCClass("UIColor")
UIWindow = ObjCClass("UIWindow")
UIScreen = ObjCClass("UIScreen")
UIResponder = ObjCClass("UIResponder")
UIViewController = ObjCClass("UIViewController")
UICollectionViewCell = ObjCClass("UICollectionViewCell")
UITapGestureRecognizer = ObjCClass("UITapGestureRecognizer")
NSBundle = ObjCClass("NSBundle")
NSDictionary = ObjCClass("NSDictionary")

UIViewAnimationOptionTransitionFlipFromBottom = 7 << 20


def rect(x, y, w, h):