class CustomView(Cocoa.NSView): circleImage = objc.ivar() pentaImage = objc.ivar() def awakeFromNib(self): self.circleImage = Cocoa.NSImage.imageNamed_("circle") if self.circleImage is None: sys.stderr.write("failed to access circle image\n") raise RuntimeError self.pentaImage = Cocoa.NSImage.imageNamed_("pentagram") if self.pentaImage is None: sys.stderr.write("failed to access pentagram image\n") raise RuntimeError self.setNeedsDisplay_(True) def drawRect_(self, rect): Cocoa.NSColor.clearColor().set() Cocoa.NSRectFill(self.frame()) if self.window().alphaValue() > 0.7: self.circleImage.compositeToPoint_operation_( Cocoa.NSZeroPoint, Cocoa.NSCompositeSourceOver) else: self.pentaImage.compositeToPoint_operation_( Cocoa.NSZeroPoint, Cocoa.NSCompositeSourceOver) if floor(Cocoa.NSAppKitVersionNumber ) <= Cocoa.NSAppKitVersionNumber10_1: self.window().setHasShadow_(False) self.window().setHasShadow_(True) else: self.window().invalidateShadow()
class MyClass(NSObject): base = objc.ivar("base", objc._C_INT) power = objc.ivar("power", objc._C_INT) result = objc.ivar("result", objc._C_INT) def result(self): return self.base**self.power
class Circle (Cocoa.NSObject): radius = objc.ivar(type=objc._C_FLT) center = objc.ivar(type=Cocoa.NSPoint.__typestr__) color = objc.ivar() def bounds(self): return Cocoa.NSMakeRect( self.center.x - self.radius, self.center.y - self.radius, 2 * self.radius, 2 * self.radius) def draw(self): context = Cocoa.NSGraphicsContext.currentContext().graphicsPort() self.color.set() Cocoa.CGContextSetGrayStrokeColor(context, 0, 1) Cocoa.CGContextSetLineWidth(context, 1.5) Cocoa.CGContextSaveGState(context) Cocoa.CGContextTranslateCTM(context, self.center.x, self.center.y) Cocoa.CGContextScaleCTM(context, self.radius, self.radius) Cocoa.CGContextMoveToPoint(context, 1, 0) Cocoa.CGContextAddArc(context, 0, 0, 1, 0, 2 * math.pi, False) Cocoa.CGContextClosePath(context) Cocoa.CGContextRestoreGState(context) Cocoa.CGContextDrawPath(context, Cocoa.kCGPathFill)
class WebKitInterpreter(NSView): arguments = objc.ivar("arguments") pyInterpreter = objc.ivar("pyInterpreter") scrollView = objc.ivar("scrollView") textView = objc.ivar("textView") def container(self): return self.arguments.get("WebPluginContainer") def pluginViewWithArguments_(cls, arguments): self = super(WebKitInterpreter, cls).alloc().initWithFrame_(NSZeroRect) NSLog("pluginViewWithArguments:") NSLog(arguments) self.arguments = arguments return self pluginViewWithArguments_ = classmethod(pluginViewWithArguments_) def pluginStart(self): NSLog("pluginStart") try: self.doPluginStart() except: import traceback traceback.print_exc() def doPluginStart(self): dct = self.arguments["WebPluginAttributes"] w, h = [float(dct.get(k, 0)) for k in ("width", "height")] self.setFrame_(((0.0, 0.0), (w, h))) scrollView = NSScrollView.alloc().initWithFrame_(self.frame()) scrollView.setHasVerticalScroller_(True) scrollView.setHasHorizontalScroller_(False) scrollView.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable) contentSize = scrollView.contentSize() textView = NSTextView.alloc().initWithFrame_( ((0, 0), scrollView.contentSize())) textView.setMinSize_((0, contentSize.height)) textView.setMaxSize_((FLT_MAX, FLT_MAX)) textView.setVerticallyResizable_(True) textView.setHorizontallyResizable_(False) textView.setAutoresizingMask_(NSViewWidthSizable) textView.textContainer().setContainerSize_( (contentSize.width, FLT_MAX)) textView.textContainer().setWidthTracksTextView_(True) scrollView.setDocumentView_(textView) self.addSubview_(scrollView) self.pyInterpreter = PyInterpreter.alloc().initWithTextView_(textView) self.pyInterpreter.interpreterLocals()["container"] = self.container() def objectForWebScript(self): return self
class MyBaseGradientView(Cocoa.NSView): myGradient = objc.ivar() myStartColor = objc.ivar() myEndColor = objc.ivar() forceColorChange = objc.ivar.bool() myAngle = objc.ivar.double() myIsRadial = objc.ivar.bool() myOffsetPt = objc.ivar.NSPoint() def resetGradient(self): if self.forceColorChange and self.myGradient is not None: self.myGradient = None if self.myGradient is None: self.myGradient = Cocoa.NSGradient.alloc( ).initWithStartingColor_endingColor_(self.myStartColor, self.myEndColor) self.forceColorChange = False def setStartColor_(self, startColor): self.myStartColor = startColor self.forceColorChange = True self.setNeedsDisplay_(True) def setEndColor_(self, endColor): self.myEndColor = endColor self.forceColorChange = True self.setNeedsDisplay_(True) def setAngle_(self, angle): self.myAngle = angle self.setNeedsDisplay_(True) def setRadialDraw_(self, isRadial): self.myIsRadial = isRadial self.setNeedsDisplay_(True) def getRelativeCenterPositionFromEvent_(self, theEvent): curMousePt = self.convertPoint_fromView_(theEvent.locationInWindow(), None) pt = Cocoa.NSMakePoint( (curMousePt.x - Cocoa.NSMidX(self.bounds())) / (self.bounds().size.width / 2.0), (curMousePt.y - Cocoa.NSMidY(self.bounds())) / (self.bounds().size.height / 2.0), ) return pt def mouseDown_(self, theEvent): if self.myIsRadial: self.myOffsetPt = self.getRelativeCenterPositionFromEvent_( theEvent) self.setNeedsDisplay_(True) def mouseDragged_(self, theEvent): if self.myIsRadial: self.myOffsetPt = self.getRelativeCenterPositionFromEvent_( theEvent) self.setNeedsDisplay_(True)
class PathDemoController(Cocoa.NSObject): button = objc.ivar() popup = objc.ivar() window = objc.ivar() demoView = objc.ivar() def awakeFromNib(self): # Add the title of your new demo to the END of this array. titles = ['Rectangles', 'Circles', 'Bezier Paths', 'Circle Clipping'] self.popup.removeAllItems() for t in titles: self.popup.addItemWithTitle_(t) @objc.IBAction def runAgain_(self, sender): self.select_(self) @objc.IBAction def select_(self, sender): self.demoView.setDemoNumber_(self.popup.indexOfSelectedItem()) self.demoView.setNeedsDisplay_(True) def applicationShouldTerminateAfterLastWindowClosed_(self, application): return True
class AnonIvarClass(NSObject): var = objc.ivar() var2 = objc.ivar(type=objc._C_DBL) outlet = objc.IBOutlet() self.assertTrue(outlet.__isOutlet__) self.assertFalse(outlet.__isSlot__)
class RTKGroupDocument (NSDocument): sourceTextField = objc.ivar(u"sourceTextField") destinationTextField = objc.ivar(u"destinationTextField") def duplicateAction_(self, action): destinationTextField.setStringValue_(sourceTextField.stringValue()) pass
class controller(NSWindowController): iTunesManagesMyLibrary = ivar('iTunesManagesMyLibrary') #iTunesManagesMyLibrary = ivar() iTunesManagesMyLibraryMenuItem = IBOutlet() iTunesLibraryLocationMenuItem = IBOutlet() iTunesLibraryLocationMenuItemEnabled = ivar('iTunesLibraryLocationMenuItemEnabled') def awakeFromNib(self): #NSLog('awakeFromNib') self.iTunesManagesMyLibrary = config.get_config_option('iTunesManagesMyLibrary') self.iTunesManagesMyLibraryMenuItem.setState_(self.iTunesManagesMyLibrary) self.refreshMenuEnable() #@accessor #def iTunesManagesMyLibraryValue(self): # return self.iTunesManagesMyLibrary @accessor def setITunesManagesMyLibrary_(self, value): #NSLog('setITunesManagesMyLibrary_') self.iTunesManagesMyLibrary = value #NSLog(str(self.iTunesManagesMyLibrary)) config.set_config_option('iTunesManagesMyLibrary', value) self.refreshMenuEnable() @IBAction def setLibraryLocation_(self, sender): #NSLog('setLibraryLocation_') panel = NSOpenPanel.openPanel() panel.setCanChooseDirectories_(YES) panel.setAllowsMultipleSelection_(NO) panel.setCanChooseFiles_(NO) old_path = config.get_config_option('iTunesLibraryLocation') ret = panel.runModalForDirectory_file_types_(old_path, None, None) #NSLog(str(ret)) if ret: path = panel.filenames()[0] config.set_config_option('iTunesLibraryLocation', path) else: # Canceled pass def refreshMenuEnable(self): #NSLog('refreshMenuEnable') if self.iTunesManagesMyLibrary: #NSLog('NO') #self.iTunesLibraryLocationMenuItem.setEnabled_(NO) self.iTunesLibraryLocationMenuItemEnabled = NO else: #NSLog('YES') #self.iTunesLibraryLocationMenuItem.setEnabled_(YES) self.iTunesLibraryLocationMenuItemEnabled = YES @IBAction def toggleITunesManagesMyLibrary_(self, sender): #NSLog('toggleITunesManagesMyLibrary_') #self.refreshMenuEnable() pass
class Cell(NSObject): """ Representation of the prompts, input and output of a cell in the frontend """ blockNumber = objc.ivar().unsigned_long() blockID = objc.ivar() inputBlock = objc.ivar() output = objc.ivar()
class PyObjCAccount(NSObject): openingBalance = objc.ivar('openingBalance', 'd') name = objc.ivar('name') notes = objc.ivar('notes') transactions = objc.ivar('transactions') def __new__(cls, **kw): self = cls.alloc().init() for k, v in kw.iteritems(): setattr(self, k, v) return self
class GraphicsArrayController(NibClassBuilder.AutoBaseClass ): # NSArrayController """Allow filtering by color, just for the fun of it""" filterColor = ivar('filterColor') newCircle = ivar('newCircle') shouldFilter = ivar('shouldFilter', 'c') def arrangeObjects_(self, objects): "Filtering is not yet connected in IB!" # XXX: This doesn't work yet, so disable if self.shouldFilter: self.shouldFilter = False if not self.shouldFilter: return super(GraphicsArrayController, self).arrangeObjects_(objects) if self.filterColor is None: self.filterColor = NSColor.blackColor().colorUsingColorSpaceName_( NSCalibratedRGBColorSpace) filterHue = self.filterColor.hueComponent() filteredObjects = [] for item in objects: hue = item.color.hueComponent() if ((fabs(hue - filterHue) < 0.05) or (fabs(hue - filterHue) > 0.95) or (item is self.newCircle)): filteredObjects.append(item) self.newCircle = None return super(GraphicsArrayController, self).arrangeObjects_(filteredObjects) def newObject(self): "Randomize attributes of new circles so we get a pretty display" self.newCircle = super(GraphicsArrayController, self).newObject() radius = 5.0 + 15.0 * random() self.newCircle.radius = radius height = self.graphicsView.bounds().size.height width = self.graphicsView.bounds().size.width xOffset = 10.0 + (height - 20.0) * random() yOffset = 10.0 + (width - 20.0) * random() self.newCircle.xLoc = xOffset self.newCircle.yLoc = height - yOffset color = NSColor.colorWithCalibratedHue_saturation_brightness_alpha_( random(), (0.5 + random() / 2.0), (0.333 + random() / 3.0), 1.0) self.newCircle.color = color return self.newCircle
class PyObjCAccount(NSObject): openingBalance = objc.ivar("openingBalance", "d") name = objc.ivar("name") notes = objc.ivar("notes") transactions = objc.ivar("transactions") def __new__(cls, **kw): self = cls.alloc().init() for k, v in kw.iteritems(): setattr(self, k, v) return self
class CGImageView(Cocoa.NSView): _image = objc.ivar() def setImage_(self, img): if img is not None and self._image is not img: self._image = img # Mark this view as needing to be redisplayed. self.setNeedsDisplay_(True) def image(self): return self._image def drawRect_(self, rect): # Obtain the current context ctx = Cocoa.NSGraphicsContext.currentContext().graphicsPort() # Draw the image in the context CGImageUtils.IIDrawImageTransformed( self._image, ctx, Quartz.CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)) # Draw the view border, just a simple stroked rectangle Quartz.CGContextAddRect( ctx, Quartz.CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)) Quartz.CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0) Quartz.CGContextStrokePath(ctx)
class BookmarksDocument(NibClassBuilder.AutoBaseClass): # the actual base class is NSDocument # The following outlets are added to the class: # window??? is connected in IB but can not be accessed? bookmarksArray = objc.ivar('bookmarksArray') def init(self): self = super(BookmarksDocument, self).init() if self is None: return None self.bookmarksArray = NSMutableArray.array() return self def windowNibName(self): return u"BookmarksDocument" # Straightforward, standard document class # Allows content array to be saved, and file opened # Provides accessor methods for bookmarksArray # open and save -- very simple, just (un)archive bookmarksArray def dataRepresentationOfType_(self, aType): return NSKeyedArchiver.archivedDataWithRootObject_(self.bookmarksArray) def loadDataRepresentation_ofType_(self, data, aType): self.bookmarksArray = NSKeyedUnarchiver.unarchiveObjectWithData_(data) return True
class PyObjCDebuggingDelegate(NSObject): verbosity = objc.ivar('verbosity', 'i') def initWithVerbosity_(self, verbosity): self = self.init() self.verbosity = verbosity return self def exceptionHandler_shouldLogException_mask_(self, sender, exception, aMask): try: if isPythonException(exception): if self.verbosity & LOGSTACKTRACE: nsLogObjCException(exception) return nsLogPythonException(exception) elif self.verbosity & LOGSTACKTRACE: return nsLogObjCException(exception) else: return False except: print >> sys.stderr, "*** Exception occurred during exception handler ***" traceback.print_exc(sys.stderr) return True exceptionHandler_shouldLogException_mask_ = objc.selector( exceptionHandler_shouldLogException_mask_, signature='c@:@@I') def exceptionHandler_shouldHandleException_mask_(self, sender, exception, aMask): return False exceptionHandler_shouldHandleException_mask_ = objc.selector( exceptionHandler_shouldHandleException_mask_, signature='c@:@@I')
class DebuggingDelegate(NSObject): verbosity = objc.ivar('verbosity', b'i') def initWithVerbosity_(self, verbosity): self = self.init() self.verbosity = verbosity return self @objc.typedSelector(b'c@:@@I') def exceptionHandler_shouldLogException_mask_(self, sender, exception, aMask): try: if isPythonException(exception): return log_python_exception(exception) elif self.verbosity & LOGSTACKTRACE: return log_objc_exception(exception) else: return False # don't log it for us except: print("*** Exception occurred during exception handler ***", file=sys.stderr) traceback.print_exc(sys.stderr) return True @objc.typedSelector(b'c@:@@I') def exceptionHandler_shouldHandleException_mask_(self, sender, exception, aMask): return False
class DemoView (NSView): _demoNumber = objc.ivar(objc._C_INT) def initWithFrame_(self, frameRect): self = super(DemoView, self).initWithFrame_(frameRect) if self is None: return None self._demoNumber = 0 return self def drawRect_(self, rect): context = NSGraphicsContext.currentContext().graphicsPort() CGContextSetGrayFillColor(context, 1.0, 1.0) CGContextFillRect(context, rect) if self._demoNumber == 0: rectangles(context, rect) elif self._demoNumber == 1: circles(context, rect) elif self._demoNumber == 2: bezierPaths(context, rect) elif self._demoNumber == 3: circleClipping(context, rect) else: NSLog("Invalid demo number.") def setDemoNumber_(self, number): self._demoNumber = number
class ToDosDocument(NibClassBuilder.AutoBaseClass): # the actual base class is NSDocument # The following outlets are added to the class: nix toDos = objc.ivar('toDos') def init(self): self = super(ToDosDocument, self).init() if self is None: return None self.toDos = NSMutableArray.array() return self # if this line is missing you will get the # simple message: "Can't create new document" def categories(self): return Category.allCategories() def windowNibName(self): return u"ToDosDocument" def dataRepresentationOfType_(self, aType): return NSKeyedArchiver.archivedDataWithRootObject_(self.toDos) def loadDataRepresentation_ofType_(self, data, aType): self.toDos = NSKeyedUnarchiver.unarchiveObjectWithData_(data) return True
class PyObjCDebuggingDelegate(NSObject): verbosity = objc.ivar("verbosity", b"i") def initWithVerbosity_(self, verbosity): self = self.init() self.verbosity = verbosity return self @objc.typedSelector(b"c@:@@I") def exceptionHandler_shouldLogException_mask_(self, sender, exception, aMask): try: if isPythonException(exception): if self.verbosity & LOGSTACKTRACE: nsLogObjCException(exception) return nsLogPythonException(exception) elif self.verbosity & LOGSTACKTRACE: return nsLogObjCException(exception) else: return False except: print( "*** Exception occurred during exception handler ***", file=sys.stderr ) traceback.print_exc(sys.stderr) return True @objc.typedSelector(b"c@:@@I") def exceptionHandler_shouldHandleException_mask_(self, sender, exception, aMask): return False
class HazeFilterView(Cocoa.NSView): filter = objc.ivar() # noqa: A003 distance = objc.ivar(type=objc._C_FLT) slope = objc.ivar(type=objc._C_FLT) def distanceSliderChanged_(self, sender): self.distance = sender.floatValue() self.setNeedsDisplay_(True) def slopeSliderChanged_(self, sender): self.slope = sender.floatValue() self.setNeedsDisplay_(True) def drawRect_(self, rect): cg = Quartz.CGRectMake( Cocoa.NSMinX(rect), Cocoa.NSMinY(rect), Cocoa.NSWidth(rect), Cocoa.NSHeight(rect), ) context = Cocoa.NSGraphicsContext.currentContext().CIContext() if self.filter is None: # make sure initialize is called MyHazeFilter.MyHazeFilter.pyobjc_classMethods.class__() url = Cocoa.NSURL.fileURLWithPath_( Cocoa.NSBundle.mainBundle().pathForResource_ofType_( "CraterLake", "jpg")) self.filter = Quartz.CIFilter.filterWithName_("MyHazeRemover") self.filter.setValue_forKey_( Quartz.CIImage.imageWithContentsOfURL_(url), "inputImage") self.filter.setValue_forKey_( Quartz.CIColor.colorWithRed_green_blue_(0.7, 0.9, 1), "inputColor") self.filter.setValue_forKey_(self.distance, "inputDistance") self.filter.setValue_forKey_(self.slope, "inputSlope") if context is not None: context.drawImage_atPoint_fromRect_( self.filter.valueForKey_("outputImage"), cg.origin, cg)
class Category(NSObject): title = objc.ivar('title') priority = objc.ivar('priority', 'i') def allCategories(cls): """Predefined global list of categories""" return categories allCategories = classmethod(allCategories) def categoryForPriority_(cls, thePriority): for category in categories: if thePriority >= category.priority: return category return None categoryForPriority_ = classmethod(categoryForPriority_) def categoryWithTitle_andPriority_(cls, aTitle, aValue): """Convenience constructor""" newCategory = Category.alloc().init() newCategory.title = aTitle newCategory.priority = aValue return newCategory categoryWithTitle_andPriority_ = classmethod( categoryWithTitle_andPriority_) # NSCoding methods # To encode, simply save 'priority'; on decode, replace self with # the existing instance from 'allCategories' with the same priority def encodeWithCoder_(self, encoder): if encoder.allowsKeyedCoding(): encoder.encodeInt_forKey_(self.priority, u"priority") else: encoder.encodeObject_(self.priority) def initWithCoder_(self, decoder): if decoder.allowsKeyedCoding(): thePriority = decoder.decodeIntForKey_(u"priority") else: thePriority = decoder.decodeObject() return Category.categoryForPriority_(thePriority)
class MyObject(NSObject): ivar_string = objc.ivar() def init(self): self = objc.super(MyObject, self).init() if self is None: return None self.ivar_string = NSString.stringWithString_('hello') return self
class PyObjCTestObserved2(NSObject): bar = objc.ivar('bar') def init(self): self = objc.super(PyObjCTestObserved2, self).init() self.foo = None return self def __del__(self): global DEALLOCS DEALLOCS += 1
class AppDelegate(NSObject): shadowDemo = objc.ivar() def applicationDidFinishLaunching_(self, notification): self.showTLayerDemoWindow_(self) @objc.IBAction def showTLayerDemoWindow_(self, sender): if self.shadowDemo is None: self.shadowDemo = TLayerDemo.TLayerDemo.alloc().init() self.shadowDemo.window().orderFront_(self) def applicationShouldTerminateAfterLastWindowClosed_(self, app): return True
class PyObjCTransaction(NSObject): referenceNumber = objc.ivar("referenceNumber", "I") amount = objc.ivar("amount", "d") payee = objc.ivar("payee") date = objc.ivar("date") category = objc.ivar("category") reconciled = objc.ivar(objc._C_BOOL) def __new__(cls, **kw): self = cls.alloc().init() for k, v in kw.iteritems(): setattr(self, k, v) return self
class PyObjCTransaction(NSObject): referenceNumber = objc.ivar('referenceNumber', 'I') amount = objc.ivar('amount', 'd') payee = objc.ivar('payee') date = objc.ivar('date') category = objc.ivar('category') reconciled = objc.ivar(objc._C_BOOL) def __new__(cls, **kw): self = cls.alloc().init() for k, v in kw.iteritems(): setattr(self, k, v) return self
class AppDelegate(Cocoa.NSObject): myWindowController = objc.ivar() @objc.IBAction def newDocument_(self, sender): if self.myWindowController is None: self.myWindowController = MyWindowController.alloc( ).initWithWindowNibName_("TestWindow") self.myWindowController.showWindow_(self) def applicationDidFinishLaunching_(self, notification): self.newDocument_(self) def validateMenuItem_(self, theMenuItem): enable = self.respondsToSelector_(theMenuItem.action()) # disable "New" if the window is already up if theMenuItem.action() == b'newDocument:': if self.myWindowController.window().isKeyWindow(): enable = False return enable
class BookmarksDocument(NSDocument): bookmarksArray = objc.ivar("bookmarksArray") def init(self): self = super(BookmarksDocument, self).init() if self is None: return None self.bookmarksArray = NSMutableArray.array() return self def windowNibName(self): return "BookmarksDocument" # Straightforward, standard document class # Allows content array to be saved, and file opened # Provides accessor methods for bookmarksArray # open and save -- very simple, just (un)archive bookmarksArray def dataRepresentationOfType_(self, aType): return NSKeyedArchiver.archivedDataWithRootObject_(self.bookmarksArray) def loadDataRepresentation_ofType_(self, data, aType): self.bookmarksArray = NSKeyedUnarchiver.unarchiveObjectWithData_(data) return True
class myImageObject(Cocoa.NSObject): _path = objc.ivar() # ------------------------------------------------------------------------- # setPath:path # # The data source object is just a file path representation # ------------------------------------------------------------------------- def setPath_(self, inPath): self._path = inPath # The required methods of the IKImageBrowserItem protocol. # ------------------------------------------------------------------------- # imageRepresentationType: # # Set up the image browser to use a path representation. # ------------------------------------------------------------------------- def imageRepresentationType(self): return Quartz.IKImageBrowserPathRepresentationType # ------------------------------------------------------------------------- # imageRepresentation: # # Give the path representation to the image browser. # ------------------------------------------------------------------------- def imageRepresentation(self): return self._path # ------------------------------------------------------------------------- # imageUID: # # Use the absolute file path as the identifier. # ------------------------------------------------------------------------- def imageUID(self): return self._path
def __pyobjc_class_setup__(self, name, class_dict, instance_methods, class_methods): self.__created = True if self._name is None: self._name = name if self._ivar is not NULL: if self._ivar is None: ivname = '_' + self._name else: ivname = self._ivar if self.__parent is None: ivar_ref = ivar(name=ivname, type=self._typestr) class_dict[ivname] = ivar_ref if self._ro: self._setter = None else: setterName = b'set' + name[0].upper().encode('latin1') + name[1:].encode('latin1') + b':' signature = b'v@:' + self._typestr if self._setter is None: if self.__inherit: pass elif self._dynamic: dynSetterName = 'set' + name[0].upper() + name[1:] + '_' self.__setprop = _dynamic_setter(dynSetterName) instance_methods.add(setterName) else: if self._ivar is NULL: raise ValueError( "Cannot create default setter for property " "without ivar") self.__setprop = selector( attrsetter(self._name, ivname, self._copy), selector=setterName, signature=signature ) self.__setprop.isHidden = True instance_methods.add(self.__setprop) else: self.__setprop = selector( self._setter, selector=setterName, signature=signature ) self.__setprop.isHidden = True instance_methods.add(self.__setprop) if self._typestr in (_C_NSBOOL, _C_BOOL): getterName = b'is' + name[0].upper().encode('latin1') + name[:1].encode('latin1') else: getterName = self._name.encode('latin1') if self._getter is None: if self.__inherit: pass elif self._dynamic: if self._typestr in (_C_NSBOOL, _C_BOOL): dynGetterName = 'is' + name[0].upper() + name[:1] else: dynGetterName = self._name self.__getprop = _dynamic_getter(dynGetterName) instance_methods.add(getterName) else: if self._ivar is NULL: raise ValueError( "Cannot create default getter for property without ivar") self.__getprop = selector( attrgetter(ivname), selector=getterName, signature=self._typestr + b'@:') self.__getprop.isHidden=True instance_methods.add(self.__getprop) else: self.__getprop = selector( self._getter, selector=getterName, signature=self._typestr + b'@:') self.__getprop.isHidden=True instance_methods.add(self.__getprop) if self._validate is not None: selName = b'validate' + self._name[0].upper().encode('latin') + self._name[1:].encode('latin') + b':error:' signature = _C_NSBOOL + b'@:N^@o^@' validate = selector( self._validate, selector=selName, signature=signature) validate.isHidden = True instance_methods.add(validate) if self._depends_on: if self.__parent is not None: if self.__parent._depends_on: self._depends_on.update(self.__parent._depends_on.copy()) self._depends_on = self._depends_on affecting = selector( _return_value(NSSet.setWithArray_(list(self._depends_on))), selector = b'keyPathsForValuesAffecting' + self._name[0].upper().encode('latin1') + self._name[1:].encode('latin1'), signature = b'@@:', isClassMethod=True) affecting.isHidden = True class_dict[affecting.selector] = affecting class_methods.add(affecting)
def makevar(self, name=None): if name is None: return objc.ivar(type=structencoding) else: return objc.ivar(name=name, type=structencoding)
def initWithObject_type_(self, obj, theType): """This controller is used for outline and table windows.""" if kwlog: print "DEPRECATED CactusWindowController_OLD.initWithObject_type_()" if theType == typeOutline: self = self.initWithWindowNibName_("OutlineEditor") title = u"Unnamed Outline" elif theType == typeTable: self = self.initWithWindowNibName_("TableEditor") title = u"Unnamed Table" elif theType == typeBrowser: pass #title = u"Browser" else: pass self.rowLines = 2 if not obj: obj = Document(title, None) self.path = objc.ivar() self.root = objc.ivar() self.parentNode = objc.ivar() self.variableRowHeight = objc.ivar() if isinstance(obj, Document): self.path = obj.fileorurl self.root = obj.root self.parentNode = obj.parentNode # get window name from url or path if os.path.exists(self.path): fld, fle = os.path.split(self.path) title = fle elif self.path: title = self.path else: # keep unnamed title pass self.window().setTitle_( title ) self.model = OutlineViewDelegateDatasource.alloc().initWithObject_type_parentNode_( self.root, theType, self.parentNode ) # this is evil self.root.model = self.model self.model.setController_( self ) self.outlineView.setDataSource_(self.model) self.outlineView.setDelegate_(self.model) self.outlineView.setTarget_(self) # self.outlineView.setDoubleAction_("doubleClick:") self.window().makeFirstResponder_(self.outlineView) # store them columns self.nameColumn = self.outlineView.tableColumnWithIdentifier_( "name" ) self.typeColumn = self.outlineView.tableColumnWithIdentifier_( "type" ) self.valueColumn = self.outlineView.tableColumnWithIdentifier_( "value" ) self.commentColumn = self.outlineView.tableColumnWithIdentifier_( "comment" ) # set name column to wrap self.nameColumn.dataCell().setWraps_( True ) self.commentColumn.dataCell().setWraps_( True ) self.valueColumn.dataCell().setWraps_( True ) # defaults to name & value visible, type & comment invisible typeVisible = self.optTypeVisible.setState_( False ) commentVisible = self.optCommentVisible.setState_( False ) self.applySettings_(None) self.showWindow_(self) # The window controller doesn't need to be retained (referenced) # anywhere, so we pretend to have a reference to ourselves to avoid # being garbage collected before the window is closed. The extra # reference will be released in self.windowWillClose_() self.retain() return self