def do_in_mainthread(f, wait=True): # Note: We don't need/want the NSThread.isMainThread() check and extra handling. # The `performSelectorOnMainThread:withObject:waitUntilDone:` does the right thing # in case we are the main thread: if wait is True, it is executed from here, # otherwise it is queued and executed in the next frame. try: NSObject = objc.lookUpClass("NSObject") class PyAsyncCallHelper(NSObject): def initWithArgs_(self, f): self.f = f self.ret = None self.exc = None return self def call_(self, o): try: self.ret = self.f() except (KeyboardInterrupt,SystemExit) as exc: self.exc = exc except: print "Exception in PyAsyncCallHelper call" sys.excepthook(*sys.exc_info()) except Exception: PyAsyncCallHelper = objc.lookUpClass("PyAsyncCallHelper") # already defined earlier helper = PyAsyncCallHelper.alloc().initWithArgs_(f) helper.performSelectorOnMainThread_withObject_waitUntilDone_(helper.call_, None, wait) if wait and helper.exc: raise helper.exc return helper.ret
def __init__(self, driver_name="DMX Bridge", universe=0): """ midi->dmx bridge :param driver_name: The midi name of the bridge. This will show up in Logic :param universe: The DMX universe to connect to """ self.driver_name = driver_name self.appname = "{} - {}".format(__appname__, driver_name) # initialize a default dmx frame self.midi_source = MIDIDestination(driver_name) self.frame = [0] * 255 self.universe = universe # this is the starting note for all midi channels self.note_offset = 24 # this is the number of dmx channels per midi channel # each midi channel will support 32 notes. This will allow # 16 fixtures via 16 midi channels. self.dmx_offset = 32 # MacOS X related stuff self.NSUserNotification = objc.lookUpClass('NSUserNotification') self.NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') self.dmx_wrapper = None self.dmx_client = None self.dmx_tick = 100 self.midi_tick = 10 super(Midi2Dmx, self).__init__()
def testNullTerminated(self): o = OC_MetaDataTest.new() v = o.makeStringArray_((b"hello", b"world", b"there")) self.assertEqual(len(v), 3) self.assertEqual(list(v), ["hello", "world", "there"]) self.assertIsInstance(v, objc.lookUpClass("NSArray")) self.assertIsInstance(v[0], unicode) NSObject = objc.lookUpClass('NSObject') p, q, r = NSObject.new(), NSObject.new(), NSObject.new() v = o.makeObjectArray_((p, q, r)) self.assertEqual(len(v), 3) self.assertIs(v[0], p) self.assertIs(v[1], q) self.assertIs(v[2], r) v = o.makeStringArray_(()) self.assertEqual(len(v), 0) self.assertRaises(ValueError, o.makeStringArray_, [1,2]) self.assertRaises(ValueError, o.makeStringArray_, objc.NULL) v = o.nullStringArray_(objc.NULL) self.assertEqual(v, None)
def __init__(self): if self.NSUSERDEFAULTS_SUITE is not None: self._user_defaults = objc.lookUpClass('NSUserDefaults').alloc().initWithSuiteName_(self.NSUSERDEFAULTS_SUITE) else: self._user_defaults = objc.lookUpClass('NSUserDefaults').standardUserDefaults() super(NSUserDefaultsConfig, self).__init__()
def do_in_mainthread(f, wait=True): from AppKit import NSThread if NSThread.isMainThread(): return f() try: NSObject = objc.lookUpClass("NSObject") class PyAsyncCallHelper(NSObject): def initWithArgs_(self, f): self.f = f self.ret = None self.exc = None return self def call_(self, o): try: self.ret = self.f() except (KeyboardInterrupt,SystemExit) as exc: self.exc = exc except: print "Exception in PyAsyncCallHelper call" sys.excepthook(*sys.exc_info()) except: PyAsyncCallHelper = objc.lookUpClass("PyAsyncCallHelper") # already defined earlier helper = PyAsyncCallHelper.alloc().initWithArgs_(f) helper.performSelectorOnMainThread_withObject_waitUntilDone_(helper.call_, None, wait) if wait and helper.exc: raise helper.exc return helper.ret
def register_URL_handler(handler): log("register_URL_handler(%s)", handler) import objc #@UnresolvedImport NSAppleEventManager = objc.lookUpClass('NSAppleEventManager') NSObject = objc.lookUpClass('NSObject') class GURLHandler(NSObject): def handleEvent_withReplyEvent_(self, event, reply_event): log("GURLHandler.handleEvent") url = event.descriptorForKeyword_(fourCharToInt('----')).stringValue() log("URL=%s", url) handler(url.encode()) # A helper to make struct since cocoa headers seem to make # it impossible to use kAE* import struct fourCharToInt = lambda code: struct.unpack('>l', code)[0] urlh = GURLHandler.alloc() urlh.init() urlh.retain() manager = NSAppleEventManager.sharedAppleEventManager() manager.setEventHandler_andSelector_forEventClass_andEventID_( urlh, 'handleEvent:withReplyEvent:', fourCharToInt('GURL'), fourCharToInt('GURL') )
def testNullTerminated(self): v = makeStringArray_(("hello", "world", "there")) self.assertEquals(len(v), 3) self.assertEquals(list(v), [u"hello", u"world", u"there"]) self.assert_( isinstance(v, objc.lookUpClass("NSArray")) ) self.assert_( isinstance(v[0], unicode) ) NSObject = objc.lookUpClass('NSObject') p, q, r = NSObject.new(), NSObject.new(), NSObject.new() v = makeObjectArray_((p, q, r)) self.assertEquals(len(v), 3) self.assert_( v[0] is p ) self.assert_( v[1] is q ) self.assert_( v[2] is r ) v = makeStringArray_(()) self.assertEquals(len(v), 0) self.assertRaises(ValueError, makeStringArray_, [1,2]) self.assertRaises(ValueError, makeStringArray_, objc.NULL) v = nullStringArray_(objc.NULL) self.assertEquals(v, None)
def test_kvc_helper(self): o = objc.lookUpClass('NSURL').URLWithString_('http://www.python.org/') self.assertEqual(o.host(), 'www.python.org') self.assertEqual(o._.host, 'www.python.org') self.assertEqual(o._['host'], 'www.python.org') self.assertRaises(TypeError, lambda: o._[42]) self.assertEqual(repr(o._), '<KVC accessor for %r>'%(o,)) self.assertRaises(AttributeError, getattr, o._, 'nosuchattr') self.assertRaises(AttributeError, getattr, o._, '') self.assertRaises(TypeError, o._.__getitem__, 42) o = objc.lookUpClass('NSMutableDictionary').dictionary() o._.key1 = 1 o._['key2'] = 2 self.assertEqual(o, {'key1': 1, 'key2': 2 }) # At least on OSX 10.11 the KVC accessor for NSDictionary returns # nil for non-existing keys. #self.assertRaises(AttributeError, getattr, o._, 'nosuchattr') self.assertRaises(TypeError, o._.__setitem__, 42, 1) o = OC_WithHash.alloc().initWithHash_(1) self.assertRaises(IndexError, getattr, o._, 'someKey') self.assertRaises(KeyError, getattr, o._, 'someOtherKey')
def testNullTerminated(self): o = OC_MetaDataTest.new() m = o.methodForSelector_('makeStringArray:') v = m(o, ("hello", "world", "there")) self.assertEquals(len(v), 3) self.assertEquals(list(v), [u"hello", u"world", u"there"]) self.assert_( isinstance(v, objc.lookUpClass("NSArray")) ) self.assert_( isinstance(v[0], unicode) ) m = o.methodForSelector_('makeObjectArray:') NSObject = objc.lookUpClass('NSObject') p, q, r = NSObject.new(), NSObject.new(), NSObject.new() v = m(o, (p, q, r)) self.assertEquals(len(v), 3) self.assert_( v[0] is p ) self.assert_( v[1] is q ) self.assert_( v[2] is r ) m = o.methodForSelector_('makeStringArray:') v = m(o, ()) self.assertEquals(len(v), 0) self.assertRaises(ValueError, m, o, [1,2]) self.assertRaises(ValueError, m, o, objc.NULL) m = o.methodForSelector_('nullStringArray:') v = m(o, objc.NULL) self.assertEquals(v, None)
def notify(title, subtitle, info_text, delay=0, sound=False, userInfo={}): """ Python method to show a desktop notification on Mountain Lion. Where: title: Title of notification subtitle: Subtitle of notification info_text: Informative text of notification delay: Delay (in seconds) before showing the notification sound: Play the default notification sound userInfo: a dictionary that can be used to handle clicks in your app's applicationDidFinishLaunching:aNotification method """ from Foundation import NSDate from objc import lookUpClass NSUserNotification = lookUpClass('NSUserNotification') NSUserNotificationCenter = lookUpClass('NSUserNotificationCenter') notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(info_text) notification.setUserInfo_(userInfo) if sound: notification.setSoundName_("NSUserNotificationDefaultSoundName") notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date())) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
def notify(title, message, retcode=None): """ adapted from https://gist.github.com/baliw/4020619 """ try: import Foundation import objc except ImportError: import sys import logging logger = logging.getLogger(__name__) if sys.platform.startswith('darwin') and hasattr(sys, 'real_prefix'): logger.error( "Using ntfy with the MacOS Notification Center doesn't " "work within a virtualenv") sys.exit(1) else: raise NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') notification = NSUserNotification.alloc().init() notification.setTitle_(title) if message is not None: notification.setInformativeText_(message) notification.setDeliveryDate_(Foundation.NSDate.date()) NSUserNotificationCenter.defaultUserNotificationCenter()\ .scheduleNotification_(notification)
def ping(self, expr, out, exception=None): try: import Foundation, AppKit, objc except ImportError: raise Exception("Could not import Foundation/AppKit/objc -- maybe" "you're not on OS X 10.8+") NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') notification = NSUserNotification.alloc().init() if exception: notification.setTitle_('%s in iPython Task' % str(exception.__class__.__name__)) notification.setInformativeText_(str(exception)) else: notification.setTitle_('iPython Task Complete') notification.setInformativeText_(out) notification.setSubtitle_(expr.split('\n')[0]) notification.setUserInfo_({}) if self.sound: notification.setSoundName_('NSUserNotificationDefaultSoundName') NSUserNotificationCenter\ .defaultUserNotificationCenter()\ .scheduleNotification_(notification) return None
def run_browser_window_(self,filename,browser,window): self.DicomStudy = objc.lookUpClass("DicomStudy") # XXX would prefer to do these in init, but not sure init is ever called self.DCMObject = objc.lookUpClass("DCMObject") self.filename = filename self.browser = browser self.window = window self.database = OpyrixDatabase(self) sys.stdout = OpyrixOutput(self) sys.stderr = sys.stdout #print ">>> OpyrixScript::run_browser_window_" try: return execfile(filename,{"database":self.database, "OpyrixMetaDataStudy":OpyrixMetaDataStudy, "OpyrixMetaDataSeries":OpyrixMetaDataSeries, "OpyrixMetaDataImageMRI":OpyrixMetaDataImageMRI, "OpyrixServer":OpyrixServer, "OpyrixQuery":OpyrixQuery, "OpyrixStopScript":OpyrixStopScript}) except OpyrixStopScript as e: print ">>> Stopped script during execution" return 1 except Exception as e: print ">>> Caught an exception during execution:" traceback.print_exc() return 1
def _classExists(className): """Return True if a class exists in the Obj-C runtime.""" try: objc.lookUpClass(className) except objc.error: return 0 else: return 1
def testClasses(self): self.assert_( hasattr(SearchKit, 'SKDocumentRef') ) self.assert_( issubclass(SearchKit.SKDocumentRef, objc.lookUpClass('NSCFType')) ) self.assert_( SearchKit.SKDocumentRef is not objc.lookUpClass('NSCFType') ) self.assert_( hasattr(SearchKit, 'SKIndexRef') ) self.assert_( issubclass(SearchKit.SKIndexRef, objc.lookUpClass('NSCFType')) ) self.assert_( SearchKit.SKIndexRef is not objc.lookUpClass('NSCFType') )
def init(self): self = super(MountainLionNotification, self).init() if self is None: return None # Get objc references to the classes we need. self.NSUserNotification = objc.lookUpClass('NSUserNotification') self.NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') return self
def testClassList(self): ###! This test should probably be moved down to the Foundation test suite... NSObject = objc.lookUpClass('NSObject') NSException = objc.lookUpClass('NSException') NSMutableArray = objc.lookUpClass('NSMutableArray') self.assert_(NSObject in objc.getClassList(), "getClassList() does not appear to contain NSObject class") self.assert_(NSException in objc.getClassList(), "getClassList() does not appear to contain NSException class") self.assert_(NSMutableArray in objc.getClassList(), "getClassList() does not appear to contain NSMutableArray class")
def testClassList(self): ###! This test should probably be moved down to the Foundation test suite... NSObject = objc.lookUpClass('NSObject') NSException = objc.lookUpClass('NSException') NSMutableArray = objc.lookUpClass('NSMutableArray') self.assertIn(NSObject, objc.getClassList()) self.assertIn(NSException, objc.getClassList()) self.assertIn(NSMutableArray, objc.getClassList())
def __init__(self): # It's only possible to send notifications if we have a bundle # identifier set. This happens by default if using Python # installed as a Framework (e.g. the system Python), but isn't # set in a virtualenv. NSBundle.mainBundle().infoDictionary().setdefault( "CFBundleIdentifier", "org.4pisky.tools") self.NSUserNotification = lookUpClass("NSUserNotification") NCenter = lookUpClass("NSUserNotificationCenter") self.center = NCenter.defaultUserNotificationCenter()
def _load_globals(): global world, renderer, engine, archive_manager, load_notification_handler world = objc.lookUpClass('RXWorld').sharedWorld() if world: renderer = world.cardRenderer() if renderer: engine = renderer.scriptEngine() archive_manager = objc.lookUpClass('RXArchiveManager').sharedArchiveManager() if load_notification_handler: del load_notification_handler
def notify(title, subtitle, info_text, delay=0, userInfo={}): NSUserNotification = objc.lookUpClass("NSUserNotification") NSUserNotificationCenter = objc.lookUpClass("NSUserNotificationCenter") notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(info_text) notification.setUserInfo_(userInfo) notification.setDeliveryDate_(Foundation.NSDate.dateWithTimeInterval_sinceDate_(delay, Foundation.NSDate.date())) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
def test_assert_cftype(self): self.assertRaises(AssertionError, self.assertIsCFType, long) self.assertRaises(AssertionError, self.assertIsCFType, objc.lookUpClass('NSCFType')) self.assertIsCFType(objc.lookUpClass('NSObject')) #self.assertRaises(AssertionError, self.assertIsCFType, objc.lookUpClass('NSObject')) class OC_OPAQUE_TEST_1 (objc.lookUpClass('NSCFType')): pass try: self.assertIsCFType(OC_OPAQUE_TEST_1) except AssertionError: self.fail("CFType subclass not recognized as CFType")
def test_creation(self): NSData = objc.lookUpClass('NSData') NSMutableData = objc.lookUpClass('NSMutableData') data = NSData(b'hello') data2 = NSMutableData(b'moon') self.assertEqual(bytes(data), b'hello') self.assertEqual(bytes(data2), b'moon') self.assertIsInstance(data, NSData) self.assertIsInstance(data2, NSMutableData)
def notify(self, title, subtitle, text, url): NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') notification = NSUserNotification.alloc().init() notification.setTitle_(str(title)) notification.setSubtitle_(str(subtitle)) notification.setInformativeText_(str(text)) notification.setSoundName_("NSUserNotificationDefaultSoundName") notification.setHasActionButton_(True) notification.setOtherButtonTitle_("View") notification.setUserInfo_({"action":"open_url", "value":url}) NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
def _setup(): NSArray = _objc.lookUpClass('NSArray') NSMutableArray = _objc.lookUpClass('NSMutableArray') def CFArrayCreate(allocator, values, numvalues, callbacks): assert callbacks is None return NSArray.alloc().initWithArray_(values[:numvalues]) def CFArrayCreateMutable(allocator, capacity, callbacks): assert callbacks is None return NSMutableArray.alloc().init() return CFArrayCreate, CFArrayCreateMutable
def _notify(self, **kwargs): NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') notification = NSUserNotification.alloc().init() notification.setTitle_(kwargs.get('title').encode('utf-8')) #notification.setSubtitle_(str(subtitle)) notification.setInformativeText_(kwargs.get('message').encode('utf-8')) notification.setSoundName_("NSUserNotificationDefaultSoundName") #notification.setHasActionButton_(False) #notification.setOtherButtonTitle_("View") #notification.setUserInfo_({"action":"open_url", "value":url}) NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
def send_OS_X_notify(self, title, content, img_path): NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') NSImage = objc.lookUpClass('NSImage') notification = NSUserNotification.alloc().init() notification.setTitle_(title.decode('utf-8')) notification.setSubtitle_('') notification.setInformativeText_(content.decode('utf-8')) notification.setUserInfo_({}) image = NSImage.alloc().initWithContentsOfFile_(img_path) notification.setContentImage_(image) notification.setSoundName_("NSUserNotificationDefaultSoundName") notification.setDeliveryDate_(Foundation.NSDate.dateWithTimeInterval_sinceDate_(0, Foundation.NSDate.date())) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
def dont_testNSString(self): # This would always fail, NSStrings get a new proxy everytime # they cross the bridge, otherwise it would be unnecessarily hard # to get at the current value of NSMutableStrings. container = OC_TestIdentity.alloc().init() cls = objc.lookUpClass("NSObject") container.setStoredObjectToResultOf_on_("description", cls) self.assertFetchingTwice(container, "string") cls = objc.lookUpClass("NSMutableString") container.setStoredObjectToResultOf_on_("new", cls) self.assertFetchingTwice(container, "mutable string")
def notify(title, subtitle=None): """Display a NSUserNotification on Mac OS X >= 10.8""" NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') if not NSUserNotification or not NSUserNotificationCenter: return notification = NSUserNotification.alloc().init() notification.setTitle_(str(title)) if subtitle: notification.setSubtitle_(str(subtitle)) notification_center = NSUserNotificationCenter.defaultUserNotificationCenter() notification_center.deliverNotification_(notification)
def testTollFree(self): obj = OC_TestCoreFoundation.today() self.assert_( CFDateRef, objc.lookUpClass("NSDate") ) self.assert_( isinstance(obj, CFDateRef) ) v = OC_TestCoreFoundation.formatDate_(obj) self.assert_( isinstance(v, unicode) ) formatter = objc.lookUpClass("NSDateFormatter").new() formatter.setDateStyle_(OC_TestCoreFoundation.shortStyle()) formatter.setTimeStyle_(OC_TestCoreFoundation.shortStyle()) formatter.setLocale_(objc.lookUpClass("NSLocale").currentLocale()) v2 = formatter.stringForObjectValue_(obj)
def testNSDecimalNumber(self): container = OC_TestIdentity.alloc().init() cls = objc.lookUpClass("NSDecimalNumber") container.setStoredObjectToResultOf_on_("zero", cls) v = container.storedObject() self.assertTrue(container.isSameObjectAsStored_(v), repr(v))
import Foundation import objc import AppKit import sys NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def notify(title, subtitle, info_text, delay=0, sound=False, userInfo={}): notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(info_text) notification.setUserInfo_(userInfo) if sound: notification.setSoundName_("NSUserNotificationDefaultSoundName") notification.setDeliveryDate_( Foundation.NSDate.dateWithTimeInterval_sinceDate_( delay, Foundation.NSDate.date())) NSUserNotificationCenter.defaultUserNotificationCenter( ).scheduleNotification_(notification) notify("homebrew", "update", "update your f*****g things") sys.stdout.write("Notification sent...\n")
import objc from PyObjCTools.TestSupport import TestCase, main # try: # from Foundation import NSRange # # _C_NSRange = NSRange.__typestr__ # # except ImportError: if 1: if sys.maxsize > 2**32: _C_NSRange = b"{_NSRange=QQ}" else: _C_NSRange = b"{_NSRange=II}" NSObject = objc.lookUpClass("NSObject") class TestBasicDescriptors(TestCase): # IBOutlet is tested in test_ivar def test_ibaction(self): @objc.IBAction def myAction_(self, sender): return 1 self.assertIsInstance(myAction_, objc.selector) self.assertEqual(myAction_.signature, b"v@:@") self.assertEqual(myAction_.selector, b"myAction:") self.assertFalse(myAction_.isClassMethod)
from PyObjCTools.TestSupport import * import objc import sys # Most useful systems will at least have 'NSObject'. #NSObject = objc.lookUpClass('NSObject') # Use a class that isn't used in the rest of the testsuite, # should write a native class for this! NSPortCoder BaseName = 'NSPortCoder' BaseClass = objc.lookUpClass(BaseName) if sys.maxint >= 2 ** 32: # -poseAsClass: is not supported in 64-bit mode (the functionality is # not present in the 64-bit runtime and will never be because it # conflicts with new functionality such as non-fragile class layouts) pass else: class TestPosing(TestCase): def testPosing(self): class PoseClass(BaseClass): __slots__ = () # Don't add instance variables, not even __dict__ def testPosingMethod(self): return u"<PoseClass instance>" PoseClass.poseAsClass_(BaseClass) # BaseClass still refers to the old class, if we look it up again
import objc from PyObjCTools.TestSupport import * NSObject = objc.lookUpClass('NSObject') class TestBasicIMP(TestCase): # Test the basic functionality of IMP's. Imp's are basically unbound # selectors if you look at the interface. The implementation refers to # the actual functions that implements the method for calling the IMP # instead of passing through the usual message sending machinery. # def testIMPType(self): self.assertHasAttr(objc, "IMP") def testAlloc(self): cls = NSObject m = cls.pyobjc_classMethods.methodForSelector_("alloc") self.assertIsInstance(m, objc.IMP) self.assertTrue(m.__metadata__()['classmethod']) self.assertEqual( m.__metadata__()['retval']['already_retained'], cls.alloc.__metadata__()['retval']['already_retained']) self.assertEqual(m.selector, b'alloc') o = m(cls).init() self.assertIsInstance(o, cls) def testInit1(self): cls = NSObject m = cls.instanceMethodForSelector_("init")
import objc LineNumberNSRulerView = objc.lookUpClass("GSLineNumberView") ''' from Foundation import NSInvocation, NSString, NSMakeRange, NSMaxRange, NSLocationInRange, NSNotFound, NSMakeRect, NSMinY, NSWidth, NSHeight from AppKit import NSRulerView, NSMiniControlSize, NSTextView, NSNotificationCenter, \ NSFontAttributeName, NSForegroundColorAttributeName, NSTextStorageDidProcessEditingNotification, \ NSFont, NSColor, NSBezierPath, NSRectFill import math from objc import super """ Based/translated from NoodleLineNumberView http://www.noodlesoft.com/blog/2008/10/05/displaying-line-numbers-with-nstextview/ """ class LineNumberNSRulerView(NSRulerView): DEFAULT_THICKNESS = 22. RULER_MARGIN = 5. def init(self): self = super(LineNumberNSRulerView, self).init() self._font = NSFont.labelFontOfSize_(NSFont.systemFontSizeForControlSize_(NSMiniControlSize)) self._textColor = NSColor.colorWithCalibratedWhite_alpha_(.42, 1) self._rulerBackgroundColor = None self._lineIndices = None return self
""" Test locking objects and interaction with @synchronized() statements These tests take an annoyingly long time to ensure that we'd hit a race condition when locking doesn't actually lock. It should be possible to find a faster mechanism for this. """ import threading import time import objc from PyObjCTest.locking import OC_LockTest from PyObjCTools.TestSupport import TestCase, main NSAutoreleasePool = objc.lookUpClass("NSAutoreleasePool") class OtherThread(threading.Thread): def __init__(self, obj): self.obj = obj threading.Thread.__init__(self) def run(self): pool = NSAutoreleasePool.alloc().init() lck = objc.object_lock(self.obj) for i in range(6): time.sleep(0.05) lck.lock() if self.obj.isLocked():
DefaultProjectDir = "/Users/virgil/Documents/Epub1/epub.xcodeproj" #ipa 文件输出的文件夹 OutPutDir = "/Users/virgil/Documents/Archive/" #FTP 设置 FTPServer = "10.38.178.77" Port = "21" UploadDir ="/Fred/" IPA_Extentsion = ".ipa" ProjectExtentsion =".xcodeproj" ProjectFileName = "project.pbxproj" BuildReleaseDir = "build/Release-iphoneos/" NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') NSDictionary = objc.lookUpClass('NSDictionary') NSPasteboard = objc.lookUpClass('NSPasteboard') def notify(title, subtitle, info_text, delay=0, sound=False, userInfo={}): """ Python method to show a desktop notification on Mountain Lion. Where: title: Title of notification subtitle: Subtitle of notification info_text: Informative text of notification delay: Delay (in seconds) before showing the notification sound: Play the default notification sound userInfo: a dictionary that can be used to handle clicks in your app's applicationDidFinishLaunching:aNotification method """ notification = NSUserNotification.alloc().init()
import objc from PyObjCTest.testbndl import OC_TestClass2 from PyObjCTools.TestSupport import TestCase, main from collections import UserDict as IterableUserDict, UserList import collections.abc NSMutableArray = objc.lookUpClass("NSMutableArray") NSMutableDictionary = objc.lookUpClass("NSMutableDictionary") def classOfProxy(value): return OC_TestClass2.classOfObject_(value) class TestBridges(TestCase): # NOTE: the two "register" functions from objc._bridges aren't # tested explictly, but the tests in this class do verify that # the default registrations (which are made through those two # functions) work properly. def test_range(self): v = range(0, 10) self.assertIsSubclass(classOfProxy(v), NSMutableArray) def test_user_collections(self): # Note: Not "UserDict" because UserDict doesn't implement # __iter__ and hence isn't a collections.abc.Mapping, and doesn't # implement enough API to implement the NSDictionary interface. v = IterableUserDict() self.assertIsSubclass(classOfProxy(v), NSMutableDictionary)
class Number(objc.lookUpClass("NSObject")): def objCType(self): return objc._C_INT def longValue(self): return 42
NOTE: Decimal conversion is not tested, the required proxy is part of the Foundation bindings :-( """ from __future__ import unicode_literals import sys, os from PyObjCTools.TestSupport import * from PyObjCTest.fnd import NSNumber, NSNumberFormatter from PyObjCTest.pythonnumber import OC_TestNumber import objc if sys.version_info[0] == 3: unicode = str long = int OC_PythonNumber = objc.lookUpClass("OC_PythonNumber") try: NSCFNumber = objc.lookUpClass("__NSCFNumber") except objc.error: NSCFNumber = objc.lookUpClass("NSCFNumber") NSOrderedAscending = -1 NSOrderedSame = 0 NSOrderedDescending = 1 class TestNSNumber(TestCase): # These testcases check the behaviour of NSNumber, these # are mostly here to verify that NSNumbers behave as # we expect them to.
def getDate(querydate): DCMCalendarDate = objc.lookUpClass("DCMCalendarDate") return DCMCalendarDate.queryDate_(querydate)
""" Minimal tests for sequence proxies NOTE: this file is very, very incomplete and just tests copying at the moment. """ import sys from PyObjCTools.TestSupport import * from PyObjCTest.fnd import NSArray, NSMutableArray, NSPredicate, NSObject, NSNull from PyObjCTest.pythonset import OC_TestSet import objc OC_PythonArray = objc.lookUpClass("OC_PythonArray") OC_BuiltinPythonArray = objc.lookUpClass("OC_BuiltinPythonArray") class BasicSequenceTests: # Tests for sets that don't try to mutate the set. # Shared between tests for set() and frozenset() seqClass = None def testProxyClass(self): # Ensure that the right class is used to proxy sets self.assertIs(OC_TestSet.classOf_(self.seqClass()), OC_BuiltinPythonArray) def testMutableCopy(self): s = self.seqClass(range(20)) o = OC_TestSet.set_mutableCopyWithZone_(s, None) self.assertEqual(list(s), o) self.assertIsNot(s, o) self.assertIsInstance(o, list)
def CFSTR(strval): return _objc.lookUpClass('NSString').stringWithString_(strval)
from PyObjCTools.TestSupport import * import objc NSObject = objc.lookUpClass("NSObject") NSSortDescriptor = objc.lookUpClass("NSSortDescriptor") objc.registerMetaDataForSelector(b"NSObject", b"selector", dict(retval=dict(type=objc._C_VOID))) class MetadataInheritanceHelper(NSObject): def selector(self): return 1 class TestMetadataInheritance(TestCase): # These tests that PyObjC's signatures overrides don't # kick in when the new signature is incompatible with # the native signature. def testPythonMeta(self): o = MetadataInheritanceHelper.alloc().init() self.assertResultHasType(o.selector, objc._C_VOID) def testObjCMeta(self): o = NSSortDescriptor.alloc().init() self.assertResultHasType(o.selector, objc._C_SEL) if __name__ == "__main__": main()
import copy import objc from PyObjCTest.copying import OC_CopyBase, OC_CopyHelper from PyObjCTools.TestSupport import TestCase, main NSObject = objc.lookUpClass("NSObject") NSAutoreleasePool = objc.lookUpClass("NSAutoreleasePool") def funcattr(**kwds): def annotate(func): for k, v in kwds.items(): setattr(func, k, v) return func return annotate class OC_TestCopy1(NSObject): def init(self): self = objc.super(OC_TestCopy1, self).init() if self is not None: self.x = 1 self.y = 2 return self def modify(self): self.x = 42 self.y = 24 self.z = 0
class TestSpecialProperty(objc.lookUpClass("NSObject")): myprop = specialproperty() self.assertEqual(myprop.name, None)
class BlocksCompletion(objc.lookUpClass("NSObject")): def callWithCompletion_(self, completion): completion("hello") completion("world")
from AppKit import NSRunAlertPanel, NSAlternateKeyMask, NSEvent, NSKeyDown, NSFlagsChanged, NSControlKeyMask, MessageViewer from Foundation import NSLog from quotefix.utils import swizzle from quotefix.attribution import CustomizedAttribution from quotefix.messagetypes import * from objc import Category, lookUpClass from logger import logger import re, traceback, objc MailApp = lookUpClass('MailApp') class MailApp(Category(MailApp)): @classmethod def registerQuoteFixApplication(cls, app): cls.app = app @swizzle(MailApp, 'sendEvent:') def sendEvent(self, original, event): if not hasattr(self, 'app'): original(self, event) return # Keep track of an active Opt key if event.type() == NSFlagsChanged: flags = event.modifierFlags() self.app.toggle_key_active = ( flags & NSAlternateKeyMask) and not (flags & NSControlKeyMask) # Handle reply/reply-all (XXX: won't work if you have assigned a different shortcut key to these actions) if self.app.toggle_key_active and event.type(
def testObject(self): container = OC_TestIdentity.alloc().init() cls = objc.lookUpClass("Object") container.setStoredObjectAnInstanceOfClassic_(cls) self.assertFetchingTwice(container, "object")
__all__ = ('object_property', 'bool_property', 'array_property', 'set_property', 'dict_property') from objc import ivar, selector, _C_ID, _C_NSBOOL, _C_BOOL, NULL, _C_NSUInteger from objc import lookUpClass import collections from copy import copy as copy_func import sys NSSet = lookUpClass('NSSet') NSObject = lookUpClass('NSObject') if sys.version_info[0] == 2: # pragma: no 3.x cover range = xrange def _str(value): return value else: # pragma: no 2.x cover long = int def _str(value): return value.decode('ascii') def attrsetter(prop, name, copy): if copy: def func(self, value): if isinstance(value, NSObject): setattr(self, name, value.copy())
from PyObjCTools.TestSupport import * from test import list_tests, seq_tests import objc import sys import operator # Import some of the stdlib tests from test import mapping_tests NSArray = objc.lookUpClass('NSArray') NSMutableArray = objc.lookUpClass('NSMutableArray') class ArrayTests(seq_tests.CommonTest): type2test = NSArray def test_from_iterator(self): a = NSArray(i for i in range(5)) self.assertEqual(a, NSArray([0, 1, 2, 3, 4])) def test_pyobjc_copy(self): a = NSArray() b = a.copy() self.assertEqual(a, b) self.assertIsInstance(b, NSArray) a = NSArray([0]) b = a.copy() self.assertEqual(a, b) self.assertIsInstance(b, NSArray)
def lookUpClass(name): try: return objc.lookUpClass(name) except objc.nosuchclass_error: return None
See the Cocoa documentation on the Apple developer website for more information on Key-Value coding. The protocol is basicly used to enable weaker coupling between the view and model layers. """ __all__ = ("getKey", "setKey", "getKeyPath", "setKeyPath") import objc import types from itertools import imap try: set except NameError: from sets import Set as set if objc.lookUpClass('NSObject').alloc().init().respondsToSelector_( 'setValue:forKey:'): SETVALUEFORKEY = 'setValue_forKey_' SETVALUEFORKEYPATH = 'setValue_forKeyPath_' else: SETVALUEFORKEY = 'takeValue_forKey_' SETVALUEFORKEYPATH = 'takeValue_forKeyPath_' def keyCaps(s): return s[:1].capitalize() + s[1:] # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090 # Title: Binary floating point summation accurate to full precision # Version no: 2.2
def testFunctions(self): self.assertResultIsCFRetained(AddressBook.ABPickerCreate) ref = AddressBook.ABPickerCreate() try: self.assertIsInstance( ref, (AddressBook.ABPickerRef, objc.lookUpClass("ABPeoplePickerCAdapter")), ) except objc.error: self.assertIsInstance(ref, AddressBook.ABPickerRef) AddressBook.ABPickerSetFrame(ref, ((90, 100), (200, 400))) r = AddressBook.ABPickerGetFrame(ref, None) self.assertIsInstance(r, AddressBook.NSRect) self.assertEqual(r, ((90, 100), (200, 400))) self.assertResultHasType(AddressBook.ABPickerIsVisible, objc._C_BOOL) r = AddressBook.ABPickerIsVisible(ref) self.assertIsInstance(r, bool) self.assertTrue(r is False) self.assertArgHasType(AddressBook.ABPickerSetVisibility, 1, objc._C_BOOL) AddressBook.ABPickerSetVisibility(ref, True) r = AddressBook.ABPickerIsVisible(ref) self.assertTrue(r is True) AddressBook.ABPickerSetVisibility(ref, False) r = AddressBook.ABPickerIsVisible(ref) self.assertTrue(r is False) r = AddressBook.ABPickerGetAttributes(ref) self.assertIsInstance(r, int) r = AddressBook.ABPickerChangeAttributes( ref, AddressBook.kABPickerAllowMultipleSelection, 0) self.assertTrue(r is None) AddressBook.ABPickerAddProperty(ref, AddressBook.kABFirstNameProperty) AddressBook.ABPickerAddProperty(ref, AddressBook.kABLastNameProperty) AddressBook.ABPickerRemoveProperty(ref, AddressBook.kABFirstNameProperty) v = AddressBook.ABPickerCopyProperties(ref) self.assertIsInstance(v, AddressBook.NSArray) # Disable detailed testing, the RemoveProperties function # doesn't actually remove. See radar #7999195. # self.assertEqual(tuple(v), (AddressBook.kABLastNameProperty,)) AddressBook.ABPickerSetColumnTitle(ref, "Achternaam", AddressBook.kABLastNameProperty) v = AddressBook.ABPickerCopyColumnTitle( ref, AddressBook.kABLastNameProperty) self.assertResultIsCFRetained(AddressBook.ABPickerCopyColumnTitle) self.assertEqual(v, "Achternaam") AddressBook.ABPickerSetDisplayedProperty( ref, AddressBook.kABLastNameProperty) v = AddressBook.ABPickerCopyDisplayedProperty(ref) self.assertResultIsCFRetained( AddressBook.ABPickerCopyDisplayedProperty) self.assertIsInstance(v, str) v = AddressBook.ABPickerCopySelectedGroups(ref) self.assertIsInstance(v, AddressBook.NSArray) v = AddressBook.ABPickerCopySelectedRecords(ref) self.assertIsInstance(v, AddressBook.NSArray) v = AddressBook.ABPickerCopySelectedIdentifiers( ref, AddressBook.ABGetMe(AddressBook.ABGetSharedAddressBook())) if v is not None: self.assertIsInstance(v, AddressBook.NSArray) v = AddressBook.ABPickerCopySelectedValues(ref) self.assertIsInstance(v, AddressBook.NSArray) grp = AddressBook.ABCopyArrayOfAllGroups( AddressBook.ABGetSharedAddressBook())[0] usr = AddressBook.ABGetMe(AddressBook.ABGetSharedAddressBook()) AddressBook.ABPickerSelectGroup(ref, grp, True) self.assertArgHasType(AddressBook.ABPickerSelectGroup, 2, objc._C_BOOL) AddressBook.ABPickerSelectRecord(ref, usr, False) self.assertArgHasType(AddressBook.ABPickerSelectRecord, 2, objc._C_BOOL) AddressBook.ABPickerSelectIdentifier( ref, usr, "Last", False) # AddressBook.ABRecordCopyUniqueId(usr), False) self.assertArgHasType(AddressBook.ABPickerSelectIdentifier, 3, objc._C_BOOL) AddressBook.ABPickerDeselectIdentifier(ref, usr, "Last") AddressBook.ABPickerDeselectGroup(ref, grp) AddressBook.ABPickerDeselectRecord(ref, usr) AddressBook.ABPickerDeselectAll(ref) AddressBook.ABPickerClearSearchField(ref) if 0: # These are annoying, don't actually call AddressBook.ABPickerEditInAddressBook(ref) AddressBook.ABPickerSelectInAddressBook(ref) else: AddressBook.self.assertResultHasType( AddressBook.ABPickerEditInAddressBook, objc._C_VOID) AddressBook.self.assertResultHasType( AddressBook.ABPickerSelectInAddressBook, objc._C_VOID) r = AddressBook.ABPickerGetDelegate(ref) AddressBook.ABPickerSetDelegate
def decorator(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) return wrapper return decorator @swizzle(objc.lookUpClass('NSBundle'), b'bundleIdentifier') def swizzled_bundleIdentifier(self, original): """Swizzle [NSBundle bundleIdentifier] to make NSUserNotifications work. To post NSUserNotifications OS X requires the binary to be packaged as an application bundle. To circumvent this restriction, as it would be difficult (impossible?) to implement in an Alfred Extension, we modify `bundleIdentifier` to return a fake bundle identifier. Original idea for this approach by Norio Numura: https://github.com/norio-nomura/usernotification """ # Return Alfred's bundle identifier to display the Alfred.app logo. if 'Alfred 2' in os.getcwd(): return 'com.runningwithcrayons.Alfred-2'
from PyObjCTools.TestSupport import * import objc import sys NSObject = objc.lookUpClass("NSObject") # _NSZombie = objc.lookUpClass('_NSZombie') NSProxy = objc.lookUpClass("NSProxy") class MethodAccessTest(TestCase): def testObjCObject(self): # Trying to access the methods of objc.objc_object should not # crash the interpreter. self.assertRaises(AttributeError, getattr, objc.objc_object.pyobjc_classMethods, "func_code") self.assertRaises( AttributeError, getattr, objc.objc_object.pyobjc_instanceMethods, "func_code", ) def testNSProxyStuff(self): # NSProxy is incompatitble with pyobjc_{class,instance}Methods, but # this should not crash the interpreter self.assertRaises(AttributeError, getattr, NSProxy.pyobjc_instanceMethods, "foobar") self.assertRaises(AttributeError, getattr, NSProxy.pyobjc_classMethods, "foobar") self.assertRaises(AttributeError, getattr, NSProxy, "foobar")
Tests for the proxy of Python sets """ import sys from PyObjCTools.TestSupport import * from PyObjCTest.fnd import NSSet, NSMutableSet, NSPredicate, NSObject, NSNull from PyObjCTest.pythonset import OC_TestSet import objc import os if sys.version_info[0] == 3: unicode = str onLeopard = int(os.uname()[2].split('.')[0]) >= 9 OC_PythonSet = objc.lookUpClass("OC_PythonSet") OC_BuiltinPythonSet = objc.lookUpClass("OC_BuiltinPythonSet") class OC_SetPredicate(NSPredicate): # A simple test predicate class def initWithFunction_(self, pred): self = objc.super(OC_SetPredicate, self).init() if self is None: return None self.pred = pred return self def evaluateWithObject_(self, object): return self.pred(object)
def testNSDecimalNumber(self): container = OC_TestIdentity.alloc().init() cls = objc.lookUpClass("NSDecimalNumber") container.setStoredObjectToResultOf_on_("zero", cls) self.assertFetchingTwice(container, "decimal")
""" Tests if NSSet conforms to the interface of the python type set() This is a port of the set tests from the Python stdlib for 3.2 """ import collections.abc import operator import test.test_set from test.test_set import PassThru, check_pass_thru import objc from PyObjCTools.TestSupport import TestCase, onlyIf NSSet = objc.lookUpClass("NSSet") NSMutableSet = objc.lookUpClass("NSMutableSet") test.test_set.empty_set = NSMutableSet() class TestPyObjCSet(TestCase): def test_reverse_operator(self): class MySet(collections.abc.Set): def __init__(self, init=()): self._value = list(init) def __iter__(self): return iter(self._value) def __contains__(self, value): return value in self._value