1# 2# FilteringArrayController.py 3# FilteringController 4# 5# Converted by u.fiedler on 05.02.05. 6# 7# The original version was written in Objective-C by Malcolm Crawford 8# at http://homepage.mac.com/mmalc/CocoaExamples/controllers.html 9 10from Foundation import * 11from AppKit import NSArrayController 12 13class FilteringArrayController(NSArrayController): 14 _k_searchString = u"" 15 16 def search_(self, sender): 17 self.setSearchString_(sender.stringValue()) 18 self.rearrangeObjects() 19 20 def newObject(self): 21 """ 22 Creates and returns a new object of the class specified by objectClass. 23 Set default values, and keep reference to new object -- see arrangeObjects_ 24 """ 25 self.newObj = super(FilteringArrayController, self).newObject() 26 self.newObj.setValue_forKey_(u"First", u"firstName") 27 self.newObj.setValue_forKey_(u"Last", u"lastName") 28 return self.newObj 29 30 def arrangeObjects_(self, objects): 31 if self._k_searchString == None or self._k_searchString == u"": 32 self.newObj = None 33 return super(FilteringArrayController, self).arrangeObjects_(objects) 34 35 # Create array of objects that match search string. 36 # Also add any newly-created object unconditionally: 37 # (a) You'll get an error if a newly-added object isn't added to 38 # arrangedObjects. 39 # (b) The user will see newly-added objects even if they don't 40 # match the search term. 41 42 matchedObjects = [] 43 lowerSearch = self._k_searchString.lower() 44 for item in objects: 45 if item == self.newObj: 46 # if the item has just been created, add it unconditionally 47 matchedObjects.append(item) 48 self.newObj = None 49 else: 50 lowerName = item.valueForKeyPath_(u"firstName").lower() 51 if lowerSearch in lowerName: 52 matchedObjects.append(item) 53 else: 54 lowerName = item.valueForKeyPath_(u"lastName").lower() 55 if lowerSearch in lowerName: 56 matchedObjects.append(item) 57 return super(FilteringArrayController, self).arrangeObjects_(matchedObjects) 58 59 def searchString(self): 60 return self._k_searchString 61 62 def setSearchString_(self, newStr): 63 self._k_searchString = newStr 64 65