def test_objcprotocol_instancecheck(self): """isinstance works with an ObjCProtocol as the second argument.""" NSCoding = ObjCProtocol('NSCoding') NSSecureCoding = ObjCProtocol('NSSecureCoding') self.assertIsInstance(at(''), NSSecureCoding) self.assertIsInstance(at(''), NSCoding) self.assertNotIsInstance(object(), NSSecureCoding) self.assertNotIsInstance(NSObject.new(), NSSecureCoding)
def test_objcprotocol_instancecheck(self): """isinstance works with an ObjCProtocol as the second argument.""" NSCoding = ObjCProtocol('NSCoding') NSSecureCoding = ObjCProtocol('NSSecureCoding') self.assertIsInstance(at(''), NSSecureCoding) self.assertIsInstance(at(''), NSCoding) self.assertNotIsInstance(object(), NSSecureCoding) self.assertNotIsInstance(NSObject.new(), NSSecureCoding)
def test_method_varargs_send(self): """A variadic method can be called using send_message.""" NSString = ObjCClass('NSString') formatted = send_message( NSString, 'stringWithFormat:', at('This is a %@ with %@'), varargs=[at('string'), at('placeholders')], restype=objc_id, argtypes=[objc_id], ) self.assertEqual(str(ObjCInstance(formatted)), 'This is a string with placeholders')
def test_objcclass_instancecheck(self): """isinstance works with an ObjCClass as the second argument.""" NSArray = ObjCClass('NSArray') NSString = ObjCClass('NSString') self.assertIsInstance(NSObject.new(), NSObject) self.assertIsInstance(at(''), NSString) self.assertIsInstance(at(''), NSObject) self.assertIsInstance(NSObject, NSObject) self.assertIsInstance(NSObject, NSObject.objc_class) self.assertNotIsInstance(object(), NSObject) self.assertNotIsInstance(NSObject.new(), NSString) self.assertNotIsInstance(NSArray.array, NSString)
def test_objcclass_instancecheck(self): """isinstance works with an ObjCClass as the second argument.""" NSArray = ObjCClass('NSArray') NSString = ObjCClass('NSString') self.assertIsInstance(NSObject.new(), NSObject) self.assertIsInstance(at(''), NSString) self.assertIsInstance(at(''), NSObject) self.assertIsInstance(NSObject, NSObject) self.assertIsInstance(NSObject, NSObject.objc_class) self.assertNotIsInstance(object(), NSObject) self.assertNotIsInstance(NSObject.new(), NSString) self.assertNotIsInstance(NSArray.array, NSString)
def test_class_ivars(self): """An Objective-C class can have instance variables.""" class Ivars(NSObject): object = objc_ivar(objc_id) int = objc_ivar(c_int) rect = objc_ivar(NSRect) ivars = Ivars.alloc().init() set_ivar(ivars, 'object', at('foo').ptr) set_ivar(ivars, 'int', c_int(12345)) set_ivar(ivars, 'rect', NSMakeRect(12, 34, 56, 78)) s = ObjCInstance(get_ivar(ivars, 'object')) self.assertEqual(str(s), 'foo') i = get_ivar(ivars, 'int') self.assertEqual(i.value, 12345) r = get_ivar(ivars, 'rect') self.assertEqual(r.origin.x, 12) self.assertEqual(r.origin.y, 34) self.assertEqual(r.size.width, 56) self.assertEqual(r.size.height, 78)
def test_class_ivars(self): """An Objective-C class can have instance variables.""" class Ivars(NSObject): object = objc_ivar(objc_id) int = objc_ivar(c_int) rect = objc_ivar(NSRect) ivars = Ivars.alloc().init() set_ivar(ivars, 'object', at('foo').ptr) set_ivar(ivars, 'int', c_int(12345)) set_ivar(ivars, 'rect', NSMakeRect(12, 34, 56, 78)) s = ObjCInstance(get_ivar(ivars, 'object')) self.assertEqual(str(s), 'foo') i = get_ivar(ivars, 'int') self.assertEqual(i.value, 12345) r = get_ivar(ivars, 'rect') self.assertEqual(r.origin.x, 12) self.assertEqual(r.origin.y, 34) self.assertEqual(r.size.width, 56) self.assertEqual(r.size.height, 78)
def tableView_viewForTableColumn_row_(self, table, column, row: int): data_row = self.interface.data[row] col_identifier = str(column.identifier) try: value = getattr(data_row, col_identifier) # if the value is a widget itself, just draw the widget! if isinstance(value, toga.Widget): return value._impl.native # Allow for an (icon, value) tuple as the simple case # for encoding an icon in a table cell. Otherwise, look # for an icon attribute. elif isinstance(value, tuple): icon_iface, value = value else: try: icon_iface = value.icon except AttributeError: icon_iface = None except AttributeError: # The accessor doesn't exist in the data. Use the missing value. try: value = self.interface.missing_value except ValueError as e: # There is no explicit missing value. Warn the user. message, value = e.args print(message.format(row, col_identifier)) icon_iface = None # If the value has an icon, get the _impl. # Icons are deferred resources, so we provide the factory. if icon_iface: icon = icon_iface.bind(self.interface.factory) else: icon = None # creates a NSTableCellView from interface-builder template (does not exist) # or reuses an existing view which is currently not needed for painting # returns None (nil) if both fails identifier = at('CellView_{}'.format(self.interface.id)) tcv = self.makeViewWithIdentifier(identifier, owner=self) if not tcv: # there is no existing view to reuse so create a new one tcv = TogaIconView.alloc().initWithFrame_( CGRectMake(0, 0, column.width, 16)) tcv.identifier = identifier tcv.setText(str(value)) if icon: tcv.setImage(icon.native) else: tcv.setImage(None) # Keep track of last visible view for row self._impl._view_for_row[data_row] = tcv return tcv
def _add_column(self, heading, accessor): column_identifier = at(accessor) self.column_identifiers[accessor] = column_identifier column = NSTableColumn.alloc().initWithIdentifier(column_identifier) self.table.addTableColumn(column) self.columns.append(column) column.headerCell.stringValue = heading
def create(self): # Create a tree view, and put it in a scroll view. # The scroll view is the _impl, because it's the outer container. self.native = NSScrollView.alloc().init() self.native.hasVerticalScroller = True self.native.hasHorizontalScroller = False self.native.autohidesScrollers = False self.native.borderType = NSBezelBorder # Create the Tree widget self.tree = TogaTree.alloc().init() self.tree.interface = self.interface self.tree._impl = self self.tree.columnAutoresizingStyle = NSTableViewUniformColumnAutoresizingStyle self.tree.usesAlternatingRowBackgroundColors = True self.tree.allowsMultipleSelection = self.interface.multiple_select # Create columns for the tree self.columns = [] # Cocoa identifies columns by an accessor; to avoid repeated # conversion from ObjC string to Python String, create the # ObjC string once and cache it. self.column_identifiers = {} for i, (heading, accessor) in enumerate( zip(self.interface.headings, self.interface._accessors)): column_identifier = at(accessor) self.column_identifiers[id(column_identifier)] = accessor column = NSTableColumn.alloc().initWithIdentifier( column_identifier) # column.editable = False column.midWidth = 100 # if self.interface.sorting: # sort_descriptor = NSSortDescriptor.sortDescriptorWithKey(column_identifier, ascending=True) # column.sortDescriptorPrototype = sort_descriptor self.tree.addTableColumn(column) self.columns.append(column) column.headerCell.stringValue = heading # Put the tree arrows in the first column. self.tree.outlineTableColumn = self.columns[0] self.tree.delegate = self.tree self.tree.dataSource = self.tree # Embed the tree view in the scroll view self.native.documentView = self.tree # Add the layout constraints self.add_constraints()
def outlineView_viewForTableColumn_item_(self, tree, column, item): col_identifier = self._impl.column_identifiers[id(column.identifier)] try: value = getattr(item.attrs['node'], col_identifier) # if the value is a widget itself, just draw the widget! if isinstance(value, toga.Widget): return value._impl.native # Allow for an (icon, value) tuple as the simple case # for encoding an icon in a table cell. Otherwise, look # for an icon attribute. elif isinstance(value, tuple): icon_iface, value = value else: try: icon_iface = value.icon except AttributeError: icon_iface = None except AttributeError: # If the node doesn't have a property with the # accessor name, assume an empty string value. value = '' icon_iface = None # If the value has an icon, get the _impl. # Icons are deferred resources, so we provide the factory. if icon_iface: icon = icon_iface.bind(self.interface.factory) else: icon = None # creates a NSTableCellView from interface-builder template (does not exist) # or reuses an existing view which is currently not needed for painting # returns None (nil) if both fails identifier = at('CellView_{}'.format(self.interface.id)) tcv = self.makeViewWithIdentifier(identifier, owner=self) if not tcv: # there is no existing view to reuse so create a new one tcv = TogaIconView.alloc().initWithFrame_( CGRectMake(0, 0, column.width, 16)) tcv.identifier = identifier tcv.setText(str(value)) if icon: tcv.setImage(icon.native) else: tcv.setImage(None) return tcv
def test_partial_method_lots_of_args(self): pystring = "Uñîçö∂€" pybytestring = pystring.encode("utf-8") nsstring = at(pystring) buf = create_string_buffer(len(pybytestring) + 1) usedLength = NSUInteger() remaining = NSRange(0, 0) nsstring.getBytes( buf, maxLength=32, usedLength=byref(usedLength), encoding=4, # NSUTF8StringEncoding options=0, range=NSRange(0, 7), remainingRange=byref(remaining), ) self.assertEqual(buf.value.decode("utf-8"), pystring)
def test_partial_method_lots_of_args(self): pystring = "Uñîçö∂€" pybytestring = pystring.encode("utf-8") nsstring = at(pystring) buf = create_string_buffer(len(pybytestring) + 1) usedLength = NSUInteger() remaining = NSRange(0, 0) nsstring.getBytes( buf, maxLength=32, usedLength=byref(usedLength), encoding=4, # NSUTF8StringEncoding options=0, range=NSRange(0, 7), remainingRange=byref(remaining), ) self.assertEqual(buf.value.decode("utf-8"), pystring)
def create(self): # Create a table view, and put it in a scroll view. # The scroll view is the native, because it's the outer container. self.native = NSScrollView.alloc().init() self.native.hasVerticalScroller = True self.native.hasHorizontalScroller = False self.native.autohidesScrollers = False self.native.borderType = NSBezelBorder self.table = TogaTable.alloc().init() self.table.interface = self.interface self.table._impl = self self.table.columnAutoresizingStyle = NSTableViewColumnAutoresizingStyle.Uniform self.table.allowsMultipleSelection = self.interface.multiple_select # Create columns for the table self.columns = [] # Cocoa identifies columns by an accessor; to avoid repeated # conversion from ObjC string to Python String, create the # ObjC string once and cache it. self.column_identifiers = {} for i, (heading, accessor) in enumerate( zip(self.interface.headings, self.interface._accessors)): column_identifier = at(accessor) self.column_identifiers[id(column_identifier)] = accessor column = NSTableColumn.alloc().initWithIdentifier( column_identifier) self.table.addTableColumn(column) self.columns.append(column) cell = TogaIconCell.alloc().init() column.dataCell = cell column.headerCell.stringValue = heading self.table.delegate = self.table self.table.dataSource = self.table # Embed the table view in the scroll view self.native.documentView = self.table # Add the layout constraints self.add_constraints()
def test_class_nonobject_properties(self): """An Objective-C class can have properties of non-object types.""" class Properties(NSObject): object = objc_property(ObjCInstance) int = objc_property(c_int) rect = objc_property(NSRect) properties = Properties.alloc().init() properties.object = at('foo') properties.int = 12345 properties.rect = NSMakeRect(12, 34, 56, 78) self.assertEqual(properties.object, 'foo') self.assertEqual(properties.int, 12345) r = properties.rect self.assertEqual(r.origin.x, 12) self.assertEqual(r.origin.y, 34) self.assertEqual(r.size.width, 56) self.assertEqual(r.size.height, 78)
def test_class_nonobject_properties(self): """An Objective-C class can have properties of non-object types.""" class Properties(NSObject): object = objc_property(ObjCInstance) int = objc_property(c_int) rect = objc_property(NSRect) properties = Properties.alloc().init() properties.object = at('foo') properties.int = 12345 properties.rect = NSMakeRect(12, 34, 56, 78) self.assertEqual(properties.object, 'foo') self.assertEqual(properties.int, 12345) r = properties.rect self.assertEqual(r.origin.x, 12) self.assertEqual(r.origin.y, 34) self.assertEqual(r.size.width, 56) self.assertEqual(r.size.height, 78)
def test_cfstring_to_str(self): "CFString/NSString instances can be converted to Python str." self.assertEqual(str(at("abcdef")), "abcdef")
def tabView_didSelectTabViewItem_(self, view, item) -> None: index = at(item.identifier).longValue if self.interface.on_select: self.interface.on_select(self.interface, option=self.interface.content[index])