class RPCMethod(NSObject): def initWithDocument_name_(self, aDocument, aName): self = super(RPCMethod, self).init() self.document = aDocument self.k_methodName = aName self.k_methodSignature = None self.k_methodDescription = None return self def methodName(self): return self.k_methodName def displayName(self): if self.k_methodSignature is None: return self.k_methodName else: return self.k_methodSignature def setMethodSignature_(self, aSignature): self.k_methodSignature = aSignature setMethodSignature_ = objc.accessor(setMethodSignature_) def methodDescription(self): if self.k_methodDescription is None: self.setMethodDescription_(u"<description not yet received>") self.document.fetchMethodDescription_(self) return self.k_methodDescription def setMethodDescription_(self, aDescription): self.k_methodDescription = aDescription setMethodDescription_ = objc.accessor(setMethodDescription_)
class FilteringControllerDocument(NibClassBuilder.AutoBaseClass): # the actual base class is NSDocument # The following outlets are added to the class: # peopleController def init(self): self = super(FilteringControllerDocument, self).init() if self is None: return None self._k_people = [] return self def windowNibName(self): return u"FilteringControllerDocument" def windowControllerDidLoadNib_(self, controller): super(FilteringControllerDocument, self).windowControllerDidLoadNib_(controller) def dataRepresentationOfType_(self, aType): return NSKeyedArchiver.archivedDataWithRootObject_(self._k_people) def loadDataRepresentation_ofType_(self, data, aType): self.setPeople_(NSKeyedUnarchiver.unarchiveObjectWithData_(data)) return True ### indexed accessors def people(self): return self._k_people def setPeople_(self, people): self._k_people[:] = people def countOfPeople(self): return len(self._k_people) countOfPeople = objc.accessor(countOfPeople) def objectInPeopleAtIndex_(self, idx): return self._k_people[idx] objectInPeopleAtIndex_ = objc.accessor(objectInPeopleAtIndex_) def insertObject_inPeopleAtIndex_(self, obj, idx): self._k_people.insert(idx, obj) insertObject_inPeopleAtIndex_ = objc.accessor( insertObject_inPeopleAtIndex_) def removeObjectFromPeopleAtIndex_(self, idx): del self._k_people[idx] removeObjectFromPeopleAtIndex_ = objc.accessor( removeObjectFromPeopleAtIndex_) def replaceObjectInPeopleAtIndex_withObject_(self, idx, obj): self._k_people[idx] = obj replaceObjectInPeopleAtIndex_withObject_ = objc.accessor( replaceObjectInPeopleAtIndex_withObject_)
class Item(NSObject): def price(self): return getattr(self, '_k_price', 0.0) def setPrice_(self, aPrice): self._k_price = aPrice def name(self): return getattr(self, '_k_name', None) def setName_(self, aName): self._k_name = aName def validatePrice_error_(self, value): print ">>>> validatePrice_error_", value #.price error = None if value >= 0: return True, value, error errorString = u'Price cannot be negative' userInfoDict = {NSLocalizedDescriptionKey: errorString} error = NSError.alloc().initWithDomain_code_userInfo_( ITEM_ERROR_DOMAIN, ITEM_NEGATIVE_PRICE, userInfoDict) return False, value, error validatePrice_error_ = objc.accessor(validatePrice_error_)
class PyObjCTestObserved1(NSObject): if sys.version_info[0] == 3: __slots__ = ("_kvo_bar", "_kvo_foo") else: __slots__ = (b"_kvo_bar", b"_kvo_foo") FOOBASE = "base" def init(self): self = objc.super(PyObjCTestObserved1, self).init() if self is not None: self._kvo_bar = None self._kvo_foo = None return self def initiateDestructionSequence(self): # Exercise a bug between KVO and the old # initialization scheme. pass def setBar_(self, value): self.initiateDestructionSequence() self._kvo_bar = value setBar_ = objc.accessor(setBar_) def bar(self): self.initiateDestructionSequence() return self._kvo_bar bar = objc.accessor(bar) def setFoo_(self, value): self.initiateDestructionSequence() self._kvo_foo = self.FOOBASE + value setFoo_ = objc.accessor(setFoo_) def foo(self): self.initiateDestructionSequence() return self._kvo_foo foo = objc.accessor(foo) def __del__(self): global DEALLOCS DEALLOCS += 1
class FooClass(NSObject): _kvc_bar = None outlet = objc.IBOutlet("outlet") def XXaddObserver_forKeyPath_options_context_(self, observer, keyPath, options, context): print( "addObserver_forKeyPath_options_context_", observer, keyPath, options, context, ) orig = FooClass # type(self) super(orig, self).addObserver_forKeyPath_options_context_( observer, keyPath, options, context) new = self.class__() print(orig, type(self), new) if orig is not new: print("class changed!!") self.__class__ = toKVOClass(orig, new) def XXremoveObserver_forKeyPath_(self, observer, keyPath): print("removeObserver_forKeyPath_", observer, keyPath) orig = type(self) super(orig, self).removeObserver_forKeyPath_(observer, keyPath) new = self.class__() print(orig, type(self), new) if orig is not new: print("class changed!!") self.__class__ = fromKVOClass(orig) def setBar_(self, bar): print("setBar_ ->", bar) print(self, type(self), self.class__()) # print('->', bar) self._kvc_bar = bar setBar_ = objc.accessor(setBar_) def bar(self): print("bar", self._kvc_bar) # print(self, type(self), self.class__()) return self._kvc_bar bar = objc.accessor(bar)
class FooClass(NSObject): _kvc_bar = None outlet = objc.IBOutlet('outlet') def XXaddObserver_forKeyPath_options_context_(self, observer, keyPath, options, context): print 'addObserver_forKeyPath_options_context_', observer, keyPath, options, context orig = FooClass #type(self) super(orig, self).addObserver_forKeyPath_options_context_(observer, keyPath, options, context) new = self.class__() print orig, type(self), new if orig is not new: print "class changed!!" self.__class__ = toKVOClass(orig, new) def XXremoveObserver_forKeyPath_(self, observer, keyPath): print 'removeObserver_forKeyPath_', observer, keyPath orig = type(self) super(orig, self).removeObserver_forKeyPath_(observer, keyPath) new = self.class__() print orig, type(self), new if orig is not new: print "class changed!!" self.__class__ = fromKVOClass(orig) def setBar_(self, bar): print 'setBar_ ->', bar print self, type(self), self.class__() #print '->', bar self._kvc_bar = bar setBar_ = objc.accessor(setBar_) def bar(self): print 'bar', self._kvc_bar #print self, type(self), self.class__() return self._kvc_bar bar = objc.accessor(bar)
class ASDictionary(NSDocument): mainWindow = objc.IBOutlet() filenameTableView = objc.IBOutlet() selectedFilesController = objc.IBOutlet() progressPanel = objc.IBOutlet() progressBar = objc.IBOutlet() itemName = objc.IBOutlet() logDrawer = objc.IBOutlet() logTextView = objc.IBOutlet() objcPrefixColumn = objc.IBOutlet() def init(self): self = super(ASDictionary, self).init() if self is None: return self._selectedFiles = [] # {'obcPrefix': u'...', 'name': u'...', 'path': u'...'} self._canExport = False self._htmlOptionsEnabled = False self._itemName = u'' self._progressBar = 0 NSValueTransformer.setValueTransformer_forName_( ArrayToBooleanTransformer.alloc().init(), u"ArrayToBoolean") return self def applicationDidFinishLaunching_(self, sender): for m in [appscriptsupport, osaxfinder, dictionaryexporter]: m.init() self.standardAdditions = osax.OSAX() aemreceive.installeventhandler(handle_get,'coregetd', ('----', 'ref', aemreceive.kae.typeObjectSpecifier)) def awakeFromNib(self): userDefaults = NSUserDefaults.standardUserDefaults() NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( self, 'notifyPreferencesChanged:', NSUserDefaultsDidChangeNotification, userDefaults) self._updateLocks() self.filenameTableView.registerForDraggedTypes_([NSFilenamesPboardType]) self.filenameTableView.setDraggingSourceOperationMask_forLocal_(NSDragOperationLink, False) self.mainWindow.setFrameAutosaveName_(u'ExportWindow') self.logDrawer.setContentSize_(userDefaults.arrayForKey_(u'LogDrawer') or self.logDrawer.contentSize()) self.selectedFilesController.setSortDescriptors_([ NSSortDescriptor.alloc().initWithKey_ascending_selector_(u'name', True, 'caseInsensitiveCompare:'), NSSortDescriptor.alloc().initWithKey_ascending_selector_(u'path', True, 'caseInsensitiveCompare:')]) def applicationWillTerminate_(self, notification): userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject_forKey_(list(self.logDrawer.contentSize()), u'LogDrawer') ####### # Update enabled/disabled status of 'Export' window's checkboxes and 'Export' button when # chosen files list or preferences change def _updateLocks(self): userDefaults = NSUserDefaults.standardUserDefaults() self.setHtmlOptionsEnabled_(userDefaults.boolForKey_(u'singleHTML') or userDefaults.boolForKey_(u'frameHTML')) hasSelectedFiles = bool(self.selectedFiles()) willExportDict = self.htmlOptionsEnabled() or userDefaults.boolForKey_(u'plainText') willExportGlue = userDefaults.boolForKey_(u'objcGlue') hasSelectedStyles = bool([name for name in [u'applescriptStyle', u'pythonStyle', u'rubyStyle', u'objcStyle'] if userDefaults.boolForKey_(name)]) self.setCanExport_(hasSelectedFiles and ((willExportDict and hasSelectedStyles) or willExportGlue)) try: self.objcPrefixColumn.setHidden_(not willExportGlue) # 10.5+ except: pass @objc.IBAction def notifyPreferencesChanged_(self, sender): self._updateLocks() ####### # delete items in files list @objc.IBAction def delete_(self, sender): self.selectedFilesController.removeObjects_(self.selectedFilesController.selectedObjects()) self._updateLocks() @objc.IBAction def clear_(self, sender): self.selectedFilesController.removeObjects_(self.selectedFilesController.content()) self._updateLocks() ####### # drag-n-drop support def application_openFile_(self, application, filename): self._addPathToSelectedFiles(filename) return True def tableView_validateDrop_proposedRow_proposedDropOperation_(self, tableView, info, row, operation): return NSDragOperationLink def tableView_acceptDrop_row_dropOperation_(self, tableView, info, row, operation): for path in info.draggingPasteboard().propertyListForType_(NSFilenamesPboardType): self._addPathToSelectedFiles(path) return True ####### # show/hide export log drawer @objc.IBAction def showLog_(self, sender): pass ####### # files list controller bindings def selectedFiles(self): return self._selectedFiles def setSelectedFiles_(self, selectedFiles): self._selectedFiles = selectedFiles[:] def countOfSelectedFiles(self): return len(self._selectedFiles) countOfSelectedFiles = objc.accessor(countOfSelectedFiles) def objectInSelectedFilesAtIndex_(self, idx): return self._selectedFiles[idx] objectInSelectedFilesAtIndex_ = objc.accessor(objectInSelectedFilesAtIndex_) def insertObject_inSelectedFilesAtIndex_(self, obj, idx): self._selectedFiles.insert(idx, obj) insertObject_inSelectedFilesAtIndex_ = objc.accessor(insertObject_inSelectedFilesAtIndex_) def removeObjectFromSelectedFilesAtIndex_(self, idx): del self._selectedFiles[idx] removeObjectFromSelectedFilesAtIndex_ = objc.accessor(removeObjectFromSelectedFilesAtIndex_) def replaceObjectInSelectedFilesAtIndex_withObject_(self, idx, obj): self._selectedFiles[idx] = obj replaceObjectInSelectedFilesAtIndex_withObject_ = objc.accessor(replaceObjectInSelectedFilesAtIndex_withObject_) ####### # 'Export' window checkbox bindings def canExport(self): return self._canExport def setCanExport_(self, value): self._canExport = value def htmlOptionsEnabled(self): return self._htmlOptionsEnabled def setHtmlOptionsEnabled_(self, value): self._htmlOptionsEnabled = value ####### # 'Dictionary' menu methods def _addPathToSelectedFiles(self, path): name = os.path.splitext(os.path.basename(path.rstrip('/')))[0] item = {'objcPrefix': nametoprefix(name), 'name': name, 'path': path} if item not in self.selectedFiles(): self.insertObject_inSelectedFilesAtIndex_(item, self.countOfSelectedFiles()) self._updateLocks() ## @objc.IBAction def chooseFromFileBrowser_(self, sender): try: selection = self.standardAdditions.choose_file(with_prompt='Select the item(s) to process:', invisibles=False, multiple_selections_allowed=True) except osax.CommandError, e: if int(e) == -128: return else: raise for alias in selection: self._addPathToSelectedFiles(alias.path)
class WSTConnectionWindowController(AppKit.NSWindowController): methodDescriptionTextView = objc.IBOutlet() methodsTable = objc.IBOutlet() progressIndicator = objc.IBOutlet() statusTextField = objc.IBOutlet() urlTextField = objc.IBOutlet() @classmethod def connectionWindowController(self): """ Create and return a default connection window instance. """ return WSTConnectionWindowController.alloc().init() def init(self): """ Designated initializer. Returns self (as per ObjC designated initializer definition, unlike Python's __init__() method). """ self = self.initWithWindowNibName_("WSTConnection") self.k_toolbarItems = {} self.k_toolbarDefaultItemIdentifiers = [] self.k_toolbarAllowedItemIdentifiers = [] self.k_methods = {} self.k_methodArray = [] return self def awakeFromNib(self): """ Invoked when the NIB file is loaded. Initializes the various UI widgets. """ self.retain() # balanced by autorelease() in windowWillClose_ self.statusTextField.setStringValue_("No host specified.") self.progressIndicator.setStyle_( AppKit.NSProgressIndicatorSpinningStyle) self.progressIndicator.setDisplayedWhenStopped_(False) self.createToolbar() def windowWillClose_(self, aNotification): """ Clean up when the document window is closed. """ self.autorelease() def createToolbar(self): """ Creates and configures the toolbar to be used by the window. """ toolbar = AppKit.NSToolbar.alloc().initWithIdentifier_( "WST Connection Window") toolbar.setDelegate_(self) toolbar.setAllowsUserCustomization_(True) toolbar.setAutosavesConfiguration_(True) self.createToolbarItems() self.window().setToolbar_(toolbar) lastURL = AppKit.NSUserDefaults.standardUserDefaults().stringForKey_( "LastURL") if lastURL and len(lastURL): self.urlTextField.setStringValue_(lastURL) def createToolbarItems(self): """ Creates all of the toolbar items that can be made available in the toolbar. The actual set of available toolbar items is determined by other mechanisms (user defaults, for example). """ addToolbarItem(self, kWSTReloadContentsToolbarItemIdentifier, "Reload", "Reload", "Reload Contents", None, "reloadVisibleData:", AppKit.NSImage.imageNamed_("Reload"), None) addToolbarItem(self, kWSTPreferencesToolbarItemIdentifier, "Preferences", "Preferences", "Show Preferences", None, "orderFrontPreferences:", AppKit.NSImage.imageNamed_("Preferences"), None) addToolbarItem(self, kWSTUrlTextFieldToolbarItemIdentifier, "URL", "URL", "Server URL", None, None, self.urlTextField, None) self.k_toolbarDefaultItemIdentifiers = [ kWSTReloadContentsToolbarItemIdentifier, kWSTUrlTextFieldToolbarItemIdentifier, AppKit.NSToolbarSeparatorItemIdentifier, AppKit.NSToolbarCustomizeToolbarItemIdentifier, ] self.k_toolbarAllowedItemIdentifiers = [ kWSTReloadContentsToolbarItemIdentifier, kWSTUrlTextFieldToolbarItemIdentifier, AppKit.NSToolbarSeparatorItemIdentifier, AppKit.NSToolbarSpaceItemIdentifier, AppKit.NSToolbarFlexibleSpaceItemIdentifier, AppKit.NSToolbarPrintItemIdentifier, kWSTPreferencesToolbarItemIdentifier, AppKit.NSToolbarCustomizeToolbarItemIdentifier, ] def toolbarDefaultItemIdentifiers_(self, anIdentifier): """ Return an array of toolbar item identifiers that identify the set, in order, of items that should be displayed on the default toolbar. """ return self.k_toolbarDefaultItemIdentifiers def toolbarAllowedItemIdentifiers_(self, anIdentifier): """ Return an array of toolbar items that may be used in the toolbar. """ return self.k_toolbarAllowedItemIdentifiers def toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar_( self, toolbar, itemIdentifier, flag): """ Delegate method fired when the toolbar is about to insert an item into the toolbar. Item is identified by itemIdentifier. Effectively makes a copy of the cached reference instance of the toolbar item identified by itemIdentifier. """ newItem = AppKit.NSToolbarItem.alloc().initWithItemIdentifier_( itemIdentifier) item = self.k_toolbarItems[itemIdentifier] newItem.setLabel_(item.label()) newItem.setPaletteLabel_(item.paletteLabel()) if item.view(): newItem.setView_(item.view()) else: newItem.setImage_(item.image()) newItem.setToolTip_(item.toolTip()) newItem.setTarget_(item.target()) newItem.setAction_(item.action()) newItem.setMenuFormRepresentation_(item.menuFormRepresentation()) if newItem.view(): newItem.setMinSize_(item.minSize()) newItem.setMaxSize_(item.maxSize()) return newItem def setStatusTextFieldMessage_(self, aMessage): """ Sets the contents of the statusTextField to aMessage and forces the fileld's contents to be redisplayed. """ if not aMessage: aMessage = "Displaying information about %d methods." % (len( self.k_methods), ) self.statusTextField.setStringValue_(aMessage) setStatusTextFieldMessage_ = objc.accessor(setStatusTextFieldMessage_) def startWorking(self): """Signal the UI there's work goin on.""" self.progressIndicator.startAnimation_(self) def stopWorking(self): """Signal the UI that the work is done.""" self.progressIndicator.stopAnimation_(self) @objc.IBAction def reloadVisibleData_(self, sender): """ Reloads the list of methods and their signatures from the XML-RPC server specified in the urlTextField. Displays appropriate error messages, if necessary. """ url = self.urlTextField.stringValue() self.k_methods = {} if not url: self.window().setTitle_("Untitled.") self.setStatusTextFieldMessage_("No URL specified.") return self.window().setTitle_(url) AppKit.NSUserDefaults.standardUserDefaults().setObject_forKey_( url, "LastURL") self.setStatusTextFieldMessage_("Retrieving method list...") self.getMethods(url) @objc.python_method def getMethods(self, url): _server = self.k_server = Proxy(url.encode('utf8')) self.startWorking() return _server.callRemote('listMethods').addCallback( # call self.receivedMethods(result, _server, "") on success self.receivedMethods, _server, "").addErrback( # on error, call this lambda lambda e: _server.callRemote('system.listMethods').addCallback( # call self.receievedMethods(result, _server, "system.") self.receivedMethods, _server, 'system.') ).addErrback( # log the failure instance, with a method self.receivedMethodsFailure, 'listMethods()').addBoth( # stop working nomatter what trap all errors (returns None) lambda n: self.stopWorking()) @objc.python_method def receivedMethodsFailure(self, why, method): self.k_server = None self.k_methodPrefix = None self.setStatusTextFieldMessage_( ("Server failed to respond to %s. " "See below for more information.") % (method, )) #log.err(why) self.methodDescriptionTextView.setString_(why.getTraceback()) @objc.python_method def receivedMethods(self, _methods, _server, _methodPrefix): self.k_server = _server self.k_methods = {} self.k_methodPrefix = _methodPrefix for aMethod in _methods: self.k_methods[aMethod] = RPCMethod.alloc().initWithDocument_name_( self, aMethod) self.setMethodArray_(self.k_methods.values()) self.k_methodPrefix = _methodPrefix self.setStatusTextFieldMessage_( "Retrieving information about %d methods." % (len(self.k_methods), )) # we could make all the requests at once :) # but the server might not like that so we will chain them d = defer.succeed(None) for index, aMethod in enumerate(self.k_methodArray): d.addCallback(self.fetchMethodSignature, index, aMethod).addCallbacks( callback=self.processSignatureForMethod, callbackArgs=(index, aMethod), errback=self.couldntProcessSignatureForMethod, errbackArgs=(index, aMethod), ) return d.addCallback(lambda ig: self.setStatusTextFieldMessage_(None)) @objc.python_method def fetchMethodSignature(self, ignore, index, aMethod): self.setStatusTextFieldMessage_( "Retrieving signature for method %s (%d of %d)." % (aMethod.methodName(), index, len(self.k_methods))) return self.k_server.callRemote( (self.k_methodPrefix + 'methodSignature').encode('utf-8'), aMethod.methodName().encode('utf-8')) @objc.python_method def processSignatureForMethod(self, methodSignature, index, aMethod): signatures = None if not len(methodSignature): return for aSignature in methodSignature: if isinstance(aSignature, list) and len(aSignature) > 0: signature = "%s %s(%s)" % (aSignature[0], aMethod.methodName(), ", ".join(aSignature[1:])) else: signature = aSignature if signatures: signatures = signatures + ", " + signature else: signatures = signature aMethod.setMethodSignature_(signatures) self.replaceObjectInMethodArrayAtIndex_withObject_(index, aMethod) @objc.python_method def couldntProcessSignatureForMethod(self, why, index, aMethod): #log.err(why) aMethod.setMethodSignature_( "<error> %s %s" % (aMethod.methodName(), why.getBriefTraceback())) self.replaceObjectInMethodArrayAtIndex_withObject_(index, aMethod) def fetchMethodDescription_(self, aMethod): def cacheDesc(v): aMethod.setMethodDescription_(v or 'No description available.') self.setStatusTextFieldMessage_( "Retrieving documentation for method %s..." % (aMethod.methodName(), )) self.startWorking() self.k_server.callRemote( (self.k_methodPrefix + 'methodHelp').encode('utf-8'), aMethod.methodName().encode('utf-8')).addCallback(cacheDesc) def methodArray(self): return self.k_methodArray @objc.accessor def countOfMethodArray(self): if self.k_methodArray is None: return 0 return self.k_methodArray @objc.accessor def objectInMethodArrayAtIndex_(self, anIndex): return self.k_methodArray[anIndex] @objc.accessor def insertObject_inMethodArrayAtIndex_(self, anObject, anIndex): self.k_methodArray.insert(anIndex, anObject) @objc.accessor def removeObjectFromMethodArrayAtIndex_(self, anIndex): del self.k_methodArray[anIndex] @objc.accessor def replaceObjectInMethodArrayAtIndex_withObject_(self, anIndex, anObject): self.k_methodArray[anIndex] = anObject @objc.accessor def setMethodArray_(self, anArray): self.k_methodArray = anArray
class ASDictionary(NibClassBuilder.AutoBaseClass): # Outlets: # mainWindow # filenameTableView # selectedFilesController # progressPanel # progressBar # itemName # logDrawer # logTextView # objcPrefixColumn def init(self): self = super(ASDictionary, self).init() if self is None: return self._selectedFiles = [ ] # {'obcPrefix': u'...', 'name': u'...', 'path': u'...'} self._canExport = False self._htmlOptionsEnabled = False self._itemName = u'' self._progressBar = 0 # Connect to StandardAdditions (see note at top of script) self.standardAdditions = osax.ScriptingAddition() return self def awakeFromNib(self): NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( self, 'notifyPreferencesChanged:', NSUserDefaultsDidChangeNotification, userDefaults) self._updateLocks() self.filenameTableView.registerForDraggedTypes_( [NSFilenamesPboardType]) self.filenameTableView.setDraggingSourceOperationMask_forLocal_( NSDragOperationLink, False) self.mainWindow.setFrameAutosaveName_(u'ExportWindow') self.logDrawer.setContentSize_( userDefaults.arrayForKey_(u'LogDrawer') or self.logDrawer.contentSize()) self.selectedFilesController.setSortDescriptors_([ NSSortDescriptor.alloc().initWithKey_ascending_selector_( u'name', True, 'caseInsensitiveCompare:'), NSSortDescriptor.alloc().initWithKey_ascending_selector_( u'path', True, 'caseInsensitiveCompare:') ]) def applicationWillTerminate_(self, notification): userDefaults.setObject_forKey_(list(self.logDrawer.contentSize()), u'LogDrawer') ####### # Update enabled/disabled status of 'Export' window's checkboxes and 'Export' button when # chosen files list or preferences change def _updateLocks(self): self.setHtmlOptionsEnabled_( userDefaults.boolForKey_(u'singleHTML') or userDefaults.boolForKey_(u'frameHTML')) hasSelectedFiles = bool(self.selectedFiles()) willExportDict = self.htmlOptionsEnabled() or userDefaults.boolForKey_( u'plainText') willExportGlue = userDefaults.boolForKey_(u'objcGlue') hasSelectedStyles = bool([ name for name in [u'applescriptStyle', u'pythonStyle', u'rubyStyle', u'objcStyle'] if userDefaults.boolForKey_(name) ]) self.setCanExport_( hasSelectedFiles and ((willExportDict and hasSelectedStyles) or willExportGlue)) try: self.objcPrefixColumn.setHidden_(not willExportGlue) # 10.5+ except: pass def notifyPreferencesChanged_(self, sender): self._updateLocks() ####### # delete items in files list def delete_(self, sender): self.selectedFilesController.removeObjects_( self.selectedFilesController.selectedObjects()) self._updateLocks() def clear_(self, sender): self.selectedFilesController.removeObjects_( self.selectedFilesController.content()) self._updateLocks() ####### # drag-n-drop support def application_openFile_(self, application, filename): self._addPathToSelectedFiles(filename) return True def tableView_validateDrop_proposedRow_proposedDropOperation_( self, tableView, info, row, operation): return NSDragOperationLink def tableView_acceptDrop_row_dropOperation_(self, tableView, info, row, operation): for path in info.draggingPasteboard().propertyListForType_( NSFilenamesPboardType): self._addPathToSelectedFiles(path) return True ####### # show/hide export log drawer def showLog_(self, sender): pass ####### # files list controller bindings def selectedFiles(self): return self._selectedFiles def setSelectedFiles_(self, selectedFiles): self._selectedFiles = selectedFiles[:] def countOfSelectedFiles(self): return len(self._selectedFiles) countOfSelectedFiles = objc.accessor(countOfSelectedFiles) def objectInSelectedFilesAtIndex_(self, idx): return self._selectedFiles[idx] objectInSelectedFilesAtIndex_ = objc.accessor( objectInSelectedFilesAtIndex_) def insertObject_inSelectedFilesAtIndex_(self, obj, idx): self._selectedFiles.insert(idx, obj) insertObject_inSelectedFilesAtIndex_ = objc.accessor( insertObject_inSelectedFilesAtIndex_) def removeObjectFromSelectedFilesAtIndex_(self, idx): del self._selectedFiles[idx] removeObjectFromSelectedFilesAtIndex_ = objc.accessor( removeObjectFromSelectedFilesAtIndex_) def replaceObjectInSelectedFilesAtIndex_withObject_(self, idx, obj): self._selectedFiles[idx] = obj replaceObjectInSelectedFilesAtIndex_withObject_ = objc.accessor( replaceObjectInSelectedFilesAtIndex_withObject_) ####### # 'Export' window checkbox bindings def canExport(self): return self._canExport def setCanExport_(self, value): self._canExport = value def htmlOptionsEnabled(self): return self._htmlOptionsEnabled def setHtmlOptionsEnabled_(self, value): self._htmlOptionsEnabled = value ####### # 'Dictionary' menu methods def _addPathToSelectedFiles(self, path, isosax=False): name = namefrompath(path) item = { 'objcPrefix': osaglue.prefixfromname(name), 'name': name, 'path': path, 'isOSAX': isosax } if item not in self.selectedFiles(): self.insertObject_inSelectedFilesAtIndex_( item, self.countOfSelectedFiles()) self._updateLocks() ## def chooseFromFileBrowser_(self, sender): try: selection = self.standardAdditions.choose_file( with_prompt='Select the item(s) to process:', invisibles=False, multiple_selections_allowed=True) except osax.CommandError, e: if int(e) == -128: return else: raise for alias in selection: self._addPathToSelectedFiles(alias.path, alias.path.lower().endswith('.osax'))
class AppController(NibClassBuilder.AutoBaseClass): def awakeFromNib(self): self.totalCountField.bind_toObject_withKeyPath_options_( u"value", self.arrayController, u"*****@*****.**", None) bindingOptions = {} bindingOptions[u'NSNullPlaceholder'] = u"No Name" self.selectedNameField.bind_toObject_withKeyPath_options_( u"value", self.arrayController, u"selection.name", bindingOptions) # binding for "name" column tableColumn = self.tableView.tableColumnWithIdentifier_(u'name') tableColumn.bind_toObject_withKeyPath_options_( u"value", self.arrayController, u"arrangedObjects.name", bindingOptions) # binding options for "price" del bindingOptions[u'NSNullPlaceholder'] bindingOptions[NSValidatesImmediatelyBindingOption] = True # binding for selected "price" field self.selectedPriceField.bind_toObject_withKeyPath_options_( u"value", self.arrayController, u"selection.price", bindingOptions) #binding for "price" column tableColumn = self.tableView.tableColumnWithIdentifier_(u'price') tableColumn.bind_toObject_withKeyPath_options_( u"value", self.arrayController, u"arrangedObjects.price", bindingOptions) # bind array controller to self's itemsArray # we use _k_itemsArray because Python does not have a separate # namespace for instance variables, and we are using accessors. self._k_itemsArray = [] self.arrayController.bind_toObject_withKeyPath_options_( u"contentArray", self, u"self.itemsArray", None) def countOfItemsArray(self): print "countOfItemsArray" return len(self._k_itemsArray) countOfItemsArray = objc.accessor(countOfItemsArray) def objectInItemsArrayAtIndex_(self, index): print "objectInItemsArrayAtIndex_", index return self._k_itemsArray[index] objectInItemsArrayAtIndex_ = objc.accessor(objectInItemsArrayAtIndex_) def insertObject_inItemsArrayAtIndex_(self, obj, idx): print "insertObject_inItemsArrayAtIndex_", idx self._k_itemsArray.insert(idx, obj) insertObject_inItemsArrayAtIndex_ = objc.accessor( insertObject_inItemsArrayAtIndex_) def removeObjectFromItemsArrayAtIndex_(self, idx): print "removeObjectFromItemsArrayAtIndex_", idx del self._k_itemsArray[idx] removeObjectFromItemsArrayAtIndex_ = objc.accessor( removeObjectFromItemsArrayAtIndex_) def replaceObjectInItemsArrayAtIndex_withObject_(self, idx, obj): print "!!! replaceObjectInItemsArrayAtIndex_withObject_", idx self._k_itemsArray[idx] = obj replaceObjectInItemsArrayAtIndex_withObject_ = objc.accessor( replaceObjectInItemsArrayAtIndex_withObject_)