def decorator(func): oldIMP = cls.instanceMethodForSelector_(SEL) def wrapper(self, *args, **kwargs): return func(self, oldIMP, *args, **kwargs) newMethod = objc.selector(wrapper, selector = oldIMP.selector, signature = oldIMP.signature) objc.classAddMethod(cls, SEL, newMethod) return wrapper
def swizzle(cls, SEL, func): old_IMP = cls.instanceMethodForSelector_(SEL) def wrapper(self, *args, **kwargs): return func(self, old_IMP, *args, **kwargs) new_IMP = objc.selector(wrapper, selector=old_IMP.selector, signature=old_IMP.signature) objc.classAddMethod(cls, SEL, new_IMP)
def decorator(fun): original = cls.instanceMethodForSelector_(sel) if original.isClassMethod: original = cls.methodForSelector_(sel) def wrapper(self, *args, **kwargs): return fun(self, original, *args, **kwargs) new = objc.selector(wrapper, selector = original.selector, signature = original.signature, isClassMethod = original.isClassMethod) objc.classAddMethod(cls, sel, new) return wrapper
def decorator(function): old = cls.instanceMethodForSelector_(selector) if old.isClassMethod: old = cls.methodForSelector_(selector) def wrapper(self, *args, **kwargs): return function(self, old, *args, **kwargs) new = objc.selector(wrapper, selector = old.selector, signature = old.signature, isClassMethod = old.isClassMethod) objc.classAddMethod(cls, selector, new) return wrapper
def testClassAddMethod(self): import objc._category as mod orig_classAddMethods = mod.classAddMethods try: l = [] def classAddMethods(cls, values): self.assertIsInstance(cls, objc.objc_class) for item in values: self.assertIsInstance(item, objc.selector) l.append((cls, values)) mod.classAddMethods = classAddMethods def my_python_description(self): return "foo the bar" objc.classAddMethod(NSObject, b"python_description", my_python_description) self.assertEqual(len(l), 1) self.assertIs(l[0][0], NSObject) self.assertEqual(len(l[0][1]), 1) m = l[0][1][0] self.assertIsInstance(m, objc.selector) self.assertIs(m.callable, my_python_description) self.assertEqual(m.selector, b"python_description") self.assertEqual(m.signature, b"@@:") @objc.typedSelector(b"q@:") def myAction(self): return 1 l[:] = [] objc.classAddMethod(NSObject, b"value", myAction) self.assertIs(l[0][0], NSObject) self.assertEqual(len(l[0][1]), 1) m = l[0][1][0] self.assertIsInstance(m, objc.selector) self.assertIs(m.callable, myAction.callable) self.assertEqual(m.selector, b"value") self.assertEqual(m.signature, b"q@:") # Cannot add native selectors: self.assertRaises( AttributeError, objc.classAddMethod, NSObject, b"descriptionAlias", NSObject.description, ) finally: mod.classAddMethods = orig_classAddMethods
def decorator(fun): original = cls.instanceMethodForSelector_(sel) if original.isClassMethod: original = cls.methodForSelector_(sel) def wrapper(self, *args, **kwargs): return fun(self, original, *args, **kwargs) new = objc.selector(wrapper, selector=original.selector, signature=original.signature, isClassMethod=original.isClassMethod) objc.classAddMethod(cls, sel, new) return wrapper
def decorator(function): cls = objc.lookUpClass(classname) old = cls.instanceMethodForSelector_(selector) if old.isClassMethod: old = cls.methodForSelector_(selector) def wrapper(self, *args, **kwargs): return function(self, old, *args, **kwargs) new = objc.selector(wrapper, selector=old.selector, signature=old.signature, isClassMethod=old.isClassMethod) objc.classAddMethod(cls, selector, new) return wrapper
def testClassAddMethod(self): import objc._category as mod orig_classAddMethods = mod.classAddMethods try: l = [] def classAddMethods(cls, values): self.assertIsInstance(cls, objc.objc_class) for item in values: self.assertIsInstance(item, objc.selector) l.append((cls, values)) mod.classAddMethods = classAddMethods def my_python_description(self): return "foo the bar" objc.classAddMethod(NSObject, b"python_description", my_python_description) self.assertEqual(len(l), 1) self.assertIs(l[0][0], NSObject) self.assertEqual(len(l[0][1]), 1) m = l[0][1][0] self.assertIsInstance(m, objc.selector) self.assertIs(m.callable, my_python_description) self.assertEqual(m.selector, b"python_description") self.assertEqual(m.signature, b"@@:") @objc.typedSelector(b"q@:") def myAction(self): return 1 l[:] = [] objc.classAddMethod(NSObject, b"value", myAction) self.assertIs(l[0][0], NSObject) self.assertEqual(len(l[0][1]), 1) m = l[0][1][0] self.assertIsInstance(m, objc.selector) self.assertIs(m.callable, myAction.callable) self.assertEqual(m.selector, b"value") self.assertEqual(m.signature, b"q@:") # Cannot add native selectors: self.assertRaises(AttributeError, objc.classAddMethod, NSObject, b"descriptionAlias", NSObject.description) finally: mod.classAddMethods = orig_classAddMethods
def swizzleWithNewMethod_(f): cls = old.definingClass oldSelectorName = old.__name__.replace("_", ":") oldIMP = cls.instanceMethodForSelector_(oldSelectorName) newSelectorName = f.__name__.replace("_", ":") argc = len(inspect.getargspec(f)[0]) newSEL = objc.selector(f, selector=newSelectorName, signature=old.signature) #oldSEL = objc.selector(lambda self, *args: oldIMP(self, *args), selector=newSelectorName, signature=old.signature) oldSEL = objc.selector(__swizzleIMPMap[argc](oldIMP), selector=newSelectorName, signature=old.signature) # Swap the two methods objc.classAddMethod(cls, newSelectorName, oldSEL) objc.classAddMethod(cls, oldSelectorName, newSEL) #NSLog(u"Swizzled %s.%s <-> %s" % (cls.__name__, oldSelectorName, newSelectorName)) return f
def register(self, root, keycode, modifiers): self.root = root self.keycode = keycode self.modifiers = modifiers self.activated = False if keycode: if not self.observer: self.root.after_idle(self._observe) self.root.after(HotkeyMgr.POLL, self._poll) # Monkey-patch tk (tkMacOSXKeyEvent.c) if not self.tkProcessKeyEvent_old: sel = 'tkProcessKeyEvent:' cls = NSApplication.sharedApplication().class__() self.tkProcessKeyEvent_old = NSApplication.sharedApplication().methodForSelector_(sel) newmethod = objc.selector(self.tkProcessKeyEvent, selector = self.tkProcessKeyEvent_old.selector, signature = self.tkProcessKeyEvent_old.signature) objc.classAddMethod(cls, sel, newmethod)
def injectTestMethod(klass, test): test_name = test.id() # Mangle the test name into a valid name. method_name = "test" + re.sub(r"[^A-Za-z_0-9]", "_", test_name) # Inject the method. def runTest(obj): print "Running Lit test: %s" % (test.id(),) result = test.defaultTestResult() test.run(result) # Report an XCTest failure, if the test failed. if not result.wasSuccessful(): # Get the underlying Lit result object. lit_result = test._test.result obj.recordFailureWithDescription_inFile_atLine_expected_(lit_result.output, test._test.getSourcePath(), 1, True) objc.classAddMethod(klass, method_name, runTest)
def decorator(func): oldIMP = None # try the selector, or any of the proposed alternatives for SEL in alternatives: try: oldIMP = cls.instanceMethodForSelector_(SEL) break except: pass if not oldIMP: logger.debug('Couldn\'t swizzle selector "%s" for class "%s"' % (SEL, cls)) return func if oldIMP.isClassMethod: oldIMP = cls.methodForSelector_(SEL) def wrapper(self, *args, **kwargs): return func(self, oldIMP, *args, **kwargs) newMethod = objc.selector(wrapper, selector = oldIMP.selector, signature = oldIMP.signature, isClassMethod = oldIMP.isClassMethod) objc.classAddMethod(cls, SEL, newMethod) return wrapper
def discard(self, obj): for i, (mocked, mock, passthrough) in enumerate(list(self.registry)): if obj is mocked: del self.registry[i] break if issubclass(self.objtype, NSObject) and hasattr(self, "original_method"): if self.original_method is None: return del self.replaced_methods[(self.objtype, self.name)] import objc sel = objc.selector( self.original_method, selector=self.func.selector, signature=self.func.signature ) objc.classAddMethod(self.objtype, self.func.selector, sel) else: # restore the world to the way it was before # (not possible with PyObjC types) del self.replaced_methods[(self.objtype, self.name)] setattr(self.objtype, self.name, self.func) #self.__get__(None, self.objtype))
def awakeFromNib(self): self.handlers = {} self.current_clue = None # get the RGB hex code of the system 'background' color. bg = self.window().backgroundColor().colorUsingColorSpaceName_( NSCalibratedRGBColorSpace ) rgb = "%x%x%x"%( bg.redComponent() * 255.999999, bg.greenComponent() * 255.999999, bg.blueComponent() * 255.999999 ) # TODO - ok. Now do something with this information. Specifically, get it into the CSS. # evil. Alter the webkit view object so that it'll accept a clickthrough # - this is very handy, as the window is on top and full of context. # Alas, right now, the hover doesn't percolate through, so you don't # get mouseover effects. But clicks work. objc.classAddMethod( WebHTMLView, "acceptsFirstMouse:", lambda a,b: 1 ) # ps - when I say 'evil', I mean it. Really, _really_ evil. TODO - # subclass the thing and do it properly. # create application support folder. The cache goes here. I suppose # I should really keep it in a Cache folder somewhere folder = os.path.join( os.environ['HOME'], "Library", "Application Support", "Shelf" ) if not os.path.exists( folder ): os.mkdir( folder ) # Add a handler for the event GURL/GURL. One might think that # Carbon.AppleEvents.kEISInternetSuite/kAEISGetURL would work, # but the system headers (and hence the Python wrapper for those) # are wrong. manager = NSAppleEventManager.sharedAppleEventManager() manager.setEventHandler_andSelector_forEventClass_andEventID_( self, 'handleURLEvent:withReplyEvent:', fourCharToInt( "GURL" ), fourCharToInt( "GURL" ))
# peripheral:didReadRSSI:error: in macOS 10.13 if objc.macos_available(10, 13): def peripheral_didReadRSSI_error_( self: PeripheralDelegate, peripheral: CBPeripheral, rssi: NSNumber, error: Optional[NSError], ) -> None: logger.debug("peripheral_didReadRSSI_error_") self._event_loop.call_soon_threadsafe(self.did_read_rssi, peripheral, rssi, error) objc.classAddMethod( PeripheralDelegate, b"peripheral:didReadRSSI:error:", peripheral_didReadRSSI_error_, ) else: def peripheralDidUpdateRSSI_error_(self: PeripheralDelegate, peripheral: CBPeripheral, error: Optional[NSError]) -> None: logger.debug("peripheralDidUpdateRSSI_error_") self._event_loop.call_soon_threadsafe(self.did_read_rssi, peripheral, peripheral.RSSI(), error) objc.classAddMethod( PeripheralDelegate, b"peripheralDidUpdateRSSI:error:",
def startIDNSnitch_(self, sender): objc.classAddMethod(NSURLRequest, SEL, initWithURL_cachePolicy_timeoutInterval_)
self.updateTimer.invalidate() self.updateTimer = None def restartCallback_(self, notification): try: data = urllib2.urlopen("http://%s:%s/check_restart" % (HOST, self.server_port), timeout=2).read() if data == "true": self.restartService_("") except Exception, e: pass if __name__ == "__main__": freeze_support() # add these methods to the menubar objc.classAddMethod(systrayosx.Backup, "restartCallback:", restartCallback_) objc.classAddMethod(systrayosx.Backup, "restartService:", restartService_) objc.classAddMethod(systrayosx.Backup, "updateMonitor:", updateMonitor_) objc.classAddMethod(systrayosx.Backup, "withUpdateDialog:", withUpdateDialog_) objc.classAddMethod(systrayosx.Backup, "withoutUpdateDialog:", withoutUpdateDialog_) app = NSApplication.sharedApplication() menus = [ (('Open Dashboard', 'openDashboard:', ''), openDashboard_), (('Start', 'startService:', ''), startService_), #(('Stop', 'stopService:', ''), stopService_), (('Check for updates', 'checkUpdates:', ''), checkUpdates_), (('Quit', 'quitServices:', ''), quitServices_) #(('Open at Login', 'toggleOpenAtLogin:'******''), toggleOpenAtLogin_), #(('Reset Password', 'resetPassword:'******''), resetPassword_) ]