def run_mainloop_with(self, target):
        """Start the OS's main loop to process asyncronous BLE events and then
        run the specified target function in a background thread.  Target
        function should be a function that takes no parameters and optionally
        return an integer response code.  When the target function stops
        executing or returns with value then the main loop will be stopped and
        the program will exit with the returned code.

        Note that an OS main loop is required to process asyncronous BLE events
        and this function is provided as a convenience for writing simple tools
        and scripts that don't need to be full-blown GUI applications.  If you
        are writing a GUI application that has a main loop (a GTK glib main loop
        on Linux, or a Cocoa main loop on OSX) then you don't need to call this
        function.
        """
        # Create background thread to run user code.
        self._user_thread = threading.Thread(target=self._user_thread_main,
                                             args=(target,))
        self._user_thread.daemon = True
        self._user_thread.start()
        # Run main loop.  This call will never return!
        try:
            AppHelper.runConsoleEventLoop(installInterrupt=True)
        except KeyboardInterrupt:
            AppHelper.stopEventLoop()
            sys.exit(0)
Esempio n. 2
0
 def start(self):
     try:
         logger.info('Starting eventloop')
         AppHelper.runConsoleEventLoop()
     except KeyboardInterrupt:
         self.outputter.out_signal()
         logger.exception("KeyboardInterrrupt, shutting down")
Esempio n. 3
0
def main():
    nc = NSWorkspace.sharedWorkspace().notificationCenter()
    observer = Observer.new()
    nc.addObserver_selector_name_object_(
        observer, "handle:", NSWorkspaceDidActivateApplicationNotification,
        None)
    AppHelper.runConsoleEventLoop(installInterrupt=True)
Esempio n. 4
0
    def run(self) -> None:
        NSApplication.sharedApplication()
        self.delegate = AppDelegate.alloc().init()
        self.delegate.handler = Handler()

        NSApp().setDelegate_(self.delegate)

        self.workspace = NSWorkspace.sharedWorkspace()
        nc = self.workspace.notificationCenter()

        nc.addObserver_selector_name_object_(
            self.delegate,
            'applicationActivated:',
            'NSWorkspaceDidActivateApplicationNotification',
            None,
        )

        nc.addObserver_selector_name_object_(
            self.delegate,
            'screenSleep:',
            'NSWorkspaceScreensDidSleepNotification',
            None,
        )

        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
            self.polling_time, self.delegate, 'writeActiveApp:', None, True)

        AppHelper.runConsoleEventLoop(maxTimeout=1)
Esempio n. 5
0
	def eol_flush(self):
		if self.queue:
			self.do_play()
		if self.playing:
			self.loop = True
			AppHelper.runConsoleEventLoop()
			self.loop = False
Esempio n. 6
0
	def pick(self, **kwargs):
		dialog = NSColorPanel.alloc().init()
		print('\n'.join(dir(NSColorPanel)))

		# Set look
		dialog.setColor_(Cocoa.NSColor.redColor())
		dialog.setShowsAlpha_(True)
		dialog.setMode_(1)
		dialog.setFloatingPanel_(True)
		dialog.setUsingModalAppearance_(True)

		# Set Action
		dialog.setTarget_(self)
		dialog.setAction_('picked:')

		# Set behaviour
		dialog._setModal_(True)
		dialog.setWorksWhenModal_(True)

		dialog.setContinuous_(True)

		#dialog._orderFrontRelativeToWindow_(self)
		dialog.orderFrontRegardless()
		#dialog.orderFront_(None)

		dialog.makeKeyWindow()

		NSApp.activateIgnoringOtherApps_(True)
		AppHelper.runConsoleEventLoop()
Esempio n. 7
0
def main():
    #NSLog(u"main()")
    serviceProvider = ServiceTest.alloc().init()
    #NSLog(u"serviceProvider = %s", serviceProvider)
    NSRegisterServicesProvider(serviceProvider, u"PyObjCSimpleService")
    #NSLog(u"registered as PyObjCSimpleService")
    AppHelper.runConsoleEventLoop()
Esempio n. 8
0
        def notify(self, title, subtitle, text):
            """Create a user notification and display it."""

             # if appImage:
             #    source_img = AppKit.NSImage.alloc().initByReferencingFile_(appImage)
             #    notification.set_identityImage_(source_img)
             # if contentImage:
             #    source_img = AppKit.NSImage.alloc().initBy
            #     notification.setContentImage_(source_img)

            notification = NSUserNotification.alloc().init()
            notification.setTitle_(str(title))
            notification.setSubtitle_(str(subtitle))
            notification.setInformativeText_(str(text))
            notification.setSoundName_("NSUserNotificationDefaultSoundName")

            # notification.set_showsButtons_(True)
            # notification.setHasActionButton_(True)
            # notification.setHasReplyButton_ (True) # this will allow the user to enter text to "reply"
            # notification.setActionButtonTitle_("View")
            # notification.setUserInfo_({"action":"open_url", "value":url})

            NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self)
            NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)

            # Note that the notification center saves a *copy* of our object.
            AppHelper.runConsoleEventLoop()
Esempio n. 9
0
    def run_mainloop_with(self, target):
        """Start the OS's main loop to process asyncronous BLE events and then
        run the specified target function in a background thread.  Target
        function should be a function that takes no parameters and optionally
        return an integer response code.  When the target function stops
        executing or returns with value then the main loop will be stopped and
        the program will exit with the returned code.

        Note that an OS main loop is required to process asyncronous BLE events
        and this function is provided as a convenience for writing simple tools
        and scripts that don't need to be full-blown GUI applications.  If you
        are writing a GUI application that has a main loop (a GTK glib main loop
        on Linux, or a Cocoa main loop on OSX) then you don't need to call this
        function.
        """
        # Create background thread to run user code.
        self._user_thread = threading.Thread(target=self._user_thread_main,
                                             args=(target, ))
        self._user_thread.daemon = True
        self._user_thread.start()
        # Run main loop.  This call will never return!
        try:
            AppHelper.runConsoleEventLoop(installInterrupt=True)
        except KeyboardInterrupt:
            AppHelper.stopEventLoop()
            sys.exit(0)
Esempio n. 10
0
def get_running_apps():
    """Get a list of the running applications"""
    AppHelper.callLater(1, AppHelper.stopEventLoop)
    AppHelper.runConsoleEventLoop()
    # Get a list of running applications
    ws = AppKit.NSWorkspace.sharedWorkspace()
    apps = ws.runningApplications()
    return apps
Esempio n. 11
0
def main():
    configure_logging()

    global CRANKD_OPTIONS, CRANKD_CONFIG

    CRANKD_OPTIONS = process_commandline()
    CRANKD_CONFIG = load_config(CRANKD_OPTIONS)

    if "NSDistributed" in CRANKD_CONFIG:
        add_distributed_notifications(CRANKD_CONFIG["NSDistributed"])

    if "NSWorkspace" in CRANKD_CONFIG:
        add_workspace_notifications(CRANKD_CONFIG['NSWorkspace'])

    if "SystemConfiguration" in CRANKD_CONFIG:
        add_sc_notifications(CRANKD_CONFIG['SystemConfiguration'])

    if "FSEvents" in CRANKD_CONFIG:
        add_fs_notifications(CRANKD_CONFIG['FSEvents'])

    if "NSNetService" in CRANKD_CONFIG:
        add_mdns_notifications(CRANKD_CONFIG['NSNetService'])

    if "CLLocation" in CRANKD_CONFIG:
        add_cl_notifications(CRANKD_CONFIG['CLLocation'])

    # We reuse our FSEvents code to watch for changes to our files and
    # restart if any of our libraries have been updated:
    add_conditional_restart(
        CRANKD_OPTIONS.config_file,
        "Configuration file %s changed" % CRANKD_OPTIONS.config_file)
    for m in filter(lambda i: i and hasattr(i, '__file__'),
                    sys.modules.values()):
        if m.__name__ == "__main__":
            msg = "%s was updated" % m.__file__
        else:
            msg = "Module %s was updated" % m.__name__

        add_conditional_restart(m.__file__, msg)

    signal.signal(signal.SIGHUP, partial(restart, "SIGHUP received"))

    start_fs_events()

    # NOTE: This timer is basically a kludge around the fact that we can't reliably get
    #       signals or Control-C inside a runloop. This wakes us up often enough to
    #       appear tolerably responsive:
    CFRunLoopAddTimer(
        NSRunLoop.currentRunLoop().getCFRunLoop(),
        CFRunLoopTimerCreate(None, CFAbsoluteTimeGetCurrent(), 2.0, 0, 0,
                             timer_callback, None), kCFRunLoopCommonModes)

    try:
        AppHelper.runConsoleEventLoop(installInterrupt=True)
    except KeyboardInterrupt:
        logging.info("KeyboardInterrupt received, exiting")

    sys.exit(0)
 def frame(self):
     """ Returns a frame as a byte string of TIFF image data (or None).
         The byte string can be displayed with image(None, data=Camera.frame()).
     """
     try:
         AppHelper.runConsoleEventLoop(installInterrupt=True)
         return str(self._delegate.frame.representations()[0].TIFFRepresentation().bytes())
     except:
         return None
Esempio n. 13
0
    def watch(ime):
        txtObj = NSTextInputContext.alloc().initWithClient_(NSTextView.new())

        obs = Observer.new().initWithValue_(txtObj)
        obs.ime = ime

        Foundation.NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            obs, 'bundle:', NSTextInputContextKeyboardSelectionDidChangeNotification, None)
        AppHelper.runConsoleEventLoop()
Esempio n. 14
0
def listen(callback):
    """Listen for song changes and trigger the callback for each."""

    nc = Foundation.NSDistributedNotificationCenter.defaultCenter()
    observer = GetSongsObserver.alloc().initWithCallback_(callback)
    nc.addObserver_selector_name_object_(observer, 'getMySongs:',
                                         'com.apple.iTunes.playerInfo', None)

    AppHelper.runConsoleEventLoop()
Esempio n. 15
0
def main():
    configure_logging()
    
    global CRANKD_OPTIONS, CRANKD_CONFIG
    
    CRANKD_OPTIONS = process_commandline()
    CRANKD_CONFIG  = load_config(CRANKD_OPTIONS)
    
    if "NSDistributed" in CRANKD_CONFIG:
        add_distributed_notifications(CRANKD_CONFIG["NSDistributed"])
    
    if "NSWorkspace" in CRANKD_CONFIG:
        add_workspace_notifications(CRANKD_CONFIG['NSWorkspace'])
    
    if "SystemConfiguration" in CRANKD_CONFIG:
        add_sc_notifications(CRANKD_CONFIG['SystemConfiguration'])
    
    if "FSEvents" in CRANKD_CONFIG:
        add_fs_notifications(CRANKD_CONFIG['FSEvents'])
    
    if "NSNetService" in CRANKD_CONFIG:
        add_mdns_notifications(CRANKD_CONFIG['NSNetService'])
    
    if "CLLocation" in CRANKD_CONFIG:
        add_cl_notifications(CRANKD_CONFIG['CLLocation'])
    
    # We reuse our FSEvents code to watch for changes to our files and
    # restart if any of our libraries have been updated:
    add_conditional_restart(CRANKD_OPTIONS.config_file, "Configuration file %s changed" % CRANKD_OPTIONS.config_file)
    for m in filter(lambda i: i and hasattr(i, '__file__'), sys.modules.values()):
        if m.__name__ == "__main__":
            msg = "%s was updated" % m.__file__
        else:
            msg = "Module %s was updated" % m.__name__
        
        add_conditional_restart(m.__file__, msg)
    
    signal.signal(signal.SIGHUP, partial(restart, "SIGHUP received"))
    
    start_fs_events()
    
    # NOTE: This timer is basically a kludge around the fact that we can't reliably get
    #       signals or Control-C inside a runloop. This wakes us up often enough to
    #       appear tolerably responsive:
    CFRunLoopAddTimer(
        NSRunLoop.currentRunLoop().getCFRunLoop(),
        CFRunLoopTimerCreate(None, CFAbsoluteTimeGetCurrent(), 2.0, 0, 0, timer_callback, None),
        kCFRunLoopCommonModes
    )
    
    try:
        AppHelper.runConsoleEventLoop(installInterrupt=True)
    except KeyboardInterrupt:
        logging.info("KeyboardInterrupt received, exiting")
    
    sys.exit(0)
Esempio n. 16
0
            def loop(self):

                # Check if camera isn't detected
                cameras = []
                for camera in QTKit.QTCaptureDevice.inputDevices():
                    cameras += [str(camera)]
                if cameraPort not in cameras:

                    # Display message
                    print "Camera not detected"

                    # Exit
                    exit()

                # Initialize camera
                camera = QTKit.QTCaptureDevice.inputDevices()[cameras.index(
                    cameraPort)]
                error = None
                if not camera.open_(error):
                    exit()

                # Create capture session
                captureSession = QTKit.QTCaptureSession.alloc().init()

                # Create input device from camera
                inputDevice = QTKit.QTCaptureDeviceInput.alloc(
                ).initWithDevice_(camera)
                if not captureSession.addInput_error_(inputDevice, error):
                    exit()

                # Create output device
                outputDevice = QTKit.QTCaptureDecompressedVideoOutput.alloc(
                ).init()

                # Set fames/second
                outputDevice.setMinimumVideoFrameInterval_(cameraFrameDelay)
                outputDevice.setAutomaticallyDropsLateVideoFrames_(True)

                # Set camera size
                outputDevice.setPixelBufferAttributes_({
                    kCVPixelBufferWidthKey:
                    cameraWidth,
                    kCVPixelBufferHeightKey:
                    cameraHeight
                })

                # Delegate frame task
                outputDevice.setDelegate_(self)
                if not captureSession.addOutput_error_(outputDevice, error):
                    exit()

                # Start the capture session
                captureSession.startRunning()

                # Start main loop
                AppHelper.runConsoleEventLoop(installInterrupt=True)
Esempio n. 17
0
 def _getRunningApps(cls):
    '''Get a list of the running applications'''
    def runLoopAndExit():
       AppHelper.stopEventLoop()
    AppHelper.callLater(1, runLoopAndExit)
    AppHelper.runConsoleEventLoop()
    # Get a list of running applications
    ws = AppKit.NSWorkspace.sharedWorkspace()
    apps = ws.runningApplications()
    return apps
Esempio n. 18
0
def setupGuiEnvironment(cb):
    if sys.platform == 'darwin':
        from PyObjCTools import AppHelper
        m = {'run': cb}
        proxy = _jproxy.JProxy('java.lang.Runnable', m)
        cbthread = _jclass.JClass("java.lang.Thread")(proxy)
        cbthread.start()
        AppHelper.runConsoleEventLoop()
    else:
        cb()
Esempio n. 19
0
def main():
    nc = NSWorkspace.sharedWorkspace().notificationCenter()
    observer = Observer.new()
    nc.addObserver_selector_name_object_(
        observer,
        "handle:",
        NSWorkspaceDidActivateApplicationNotification,
        None
    )
    AppHelper.runConsoleEventLoop(installInterrupt=True)
Esempio n. 20
0
def setupGuiEnvironment(cb):
    if _sys.platform == 'darwin':
        from PyObjCTools import AppHelper
        m = {'run': cb}
        proxy = _jproxy.JProxy('java.lang.Runnable', m)
        cbthread = _jclass.JClass("java.lang.Thread")(proxy)
        cbthread.start()
        AppHelper.runConsoleEventLoop()
    else:
        cb()
Esempio n. 21
0
 def frame(self):
     """ Returns a frame as a byte string of TIFF image data (or None).
         The byte string can be displayed with image(None, data=Camera.frame()).
     """
     try:
         AppHelper.runConsoleEventLoop(installInterrupt=True)
         return str(self._delegate.frame.representations()
                    [0].TIFFRepresentation().bytes())
     except:
         return None
Esempio n. 22
0
 def _getRunningApps(cls):
    '''Get a list of the running applications'''
    def runLoopAndExit():
       AppHelper.stopEventLoop()
    AppHelper.callLater(1, runLoopAndExit)
    AppHelper.runConsoleEventLoop()
    # Get a list of running applications
    ws = AppKit.NSWorkspace.sharedWorkspace()
    apps = ws.runningApplications()
    return apps
 def _runMainRunLoop(self):
     # Create background thread to run user code.
     self._user_thread = threading.Thread(target=self._user_thread_main)
     self._user_thread.daemon = True
     self._user_thread.start()
     # Run main loop.  This call will never return!
     try:
         AppHelper.runConsoleEventLoop(installInterrupt=True)
     except KeyboardInterrupt:
         AppHelper.stopEventLoop()
         sys.exit(0)
Esempio n. 24
0
    def main(self):
        # Callback that quits after a frame is captured
        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(0.1, self, "quitMainLoop:", None, True)

        # Turn on the camera and start the capture
        self.startImageCapture(None)

        # Start Cocoa's main event loop
        AppHelper.runConsoleEventLoop(installInterrupt=True)

        print "Frame capture completed."
Esempio n. 25
0
    def main(self):
        # Callback that quits after a frame is captured
        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
            0.1, self, 'quitMainLoop:', None, True)

        # Turn on the camera and start the capture
        self.startImageCapture(None)

        # Start Cocoa's main event loop
        AppHelper.runConsoleEventLoop(installInterrupt=True)

        print "Frame capture completed."
Esempio n. 26
0
			def loop(self) :
				
				# Check if camera isn't detected
				cameras = []
				for camera in QTKit.QTCaptureDevice.inputDevices() :
					cameras += [str(camera)]
				if cameraPort not in cameras :
				
					# Display message
					print "Camera not detected"
				
					# Exit
					exit()
		
				# Initialize camera
				camera = QTKit.QTCaptureDevice.inputDevices()[cameras.index(cameraPort)]
				error = None
				if not camera.open_(error) :
					exit()

				# Create capture session
				captureSession = QTKit.QTCaptureSession.alloc().init()

				# Create input device from camera
				inputDevice = QTKit.QTCaptureDeviceInput.alloc().initWithDevice_(camera)
				if not captureSession.addInput_error_(inputDevice, error) :
					exit()

				# Create output device
				outputDevice = QTKit.QTCaptureDecompressedVideoOutput.alloc().init()

				# Set fames/second
				outputDevice.setMinimumVideoFrameInterval_(cameraFrameDelay)
				outputDevice.setAutomaticallyDropsLateVideoFrames_(True)

				# Set camera size
				outputDevice.setPixelBufferAttributes_({
					kCVPixelBufferWidthKey: cameraWidth,
					kCVPixelBufferHeightKey: cameraHeight
				})

				# Delegate frame task
				outputDevice.setDelegate_(self)
				if not captureSession.addOutput_error_(outputDevice, error) :
					exit()

				# Start the capture session
				captureSession.startRunning()

				# Start main loop
				AppHelper.runConsoleEventLoop(installInterrupt = True)
Esempio n. 27
0
    def requestLivePhotoResources(self, version=PHOTOS_VERSION_CURRENT):
        """ return the photos and video components of a live video as [PHAssetResource] """

        with objc.autorelease_pool():
            options = Photos.PHLivePhotoRequestOptions.alloc().init()
            options.setNetworkAccessAllowed_(True)
            options.setVersion_(version)
            options.setDeliveryMode_(
                Photos.PHVideoRequestOptionsDeliveryModeHighQualityFormat
            )
            delegate = PhotoKitNotificationDelegate.alloc().init()

            self.nc.addObserver_selector_name_object_(
                delegate, "liveNotification:", None, None
            )

            self.live_photo = None

            def handler(result, info):
                """ result handler for requestLivePhotoForAsset:targetSize:contentMode:options:resultHandler: """
                if not info["PHImageResultIsDegradedKey"]:
                    self.live_photo = result
                    self.info = info
                    self.nc.postNotificationName_object_(
                        PHOTOKIT_NOTIFICATION_FINISHED_REQUEST, self
                    )

            try:
                self.manager.requestLivePhotoForAsset_targetSize_contentMode_options_resultHandler_(
                    self.asset,
                    Photos.PHImageManagerMaximumSize,
                    Photos.PHImageContentModeDefault,
                    options,
                    handler,
                )
                AppHelper.runConsoleEventLoop(installInterrupt=True)
            except KeyboardInterrupt:
                AppHelper.stopEventLoop()
            finally:
                pass

            asset_resources = Photos.PHAssetResource.assetResourcesForLivePhoto_(
                self.live_photo
            )

            # not sure why this is needed -- some weird ref count thing maybe
            # if I don't do this, memory leaks
            data = copy.copy(asset_resources)
            del asset_resources
            return data
Esempio n. 28
0
def run(reminder, *reminders):
    reminders = [reminder] + list(reminders)
    sharedapp = NSApplication.sharedApplication()
    app = App.alloc().init()
    app.reminder = " ".join(reminders)
    sharedapp.setDelegate_(app)
    app.applicationDidFinishLaunching_(None)
    print("Reminder saved")
    print("Waiting ...")
    try:
        AppHelper.runConsoleEventLoop(installInterrupt=True)
    except KeyboardInterrupt:
        print('Interrupt, pending reminders:')
        app.show_reminder()
Esempio n. 29
0
    def __init__(self):
        self.cf = BLE_CF.BLE_CrazyFlie()
        # add methods that the crazyflie executes
        #Pool().map(self.cf.add_callback, self._preCtrlFly())
        Pool().map(self.cf.add_callback, self._liveFly())
        #self.cf.add_callback(self._preCtrlFly)
        #self.cf.add_callback(self._liveFly)
        manager = CBCentralManager.alloc()
        manager.initWithDelegate_queue_options_(self.cf, None, None)

        try:
            AppHelper.runConsoleEventLoop(installInterrupt=True)
        except KeyboardInterrupt:
            AppHelper.stopEventLoop()
Esempio n. 30
0
    def _setNotification(self, timeout=0, notificationStr=None, callbackFn=None, callbackArgs=None, callbackKwargs=None):
        if callable(callbackFn):
            self.callbackFn = callbackFn

        if isinstance(callbackArgs, tuple):
            self.callbackArgs = callbackArgs
        else:
            self.callbackArgs = tuple()

        if isinstance(callbackKwargs, dict):
            self.callbackKwargs = callbackKwargs

        self.observerRes = None

        pid = self._getPid()
        err, observer = AXObserverCreate(pid, observerCallback, None)
        if err != kAXErrorSuccess:
            _setError(err, 'Could not create observer for notification')

        err = AXObserverAddNotification(
            observer, self.ref,
            notificationStr,
            self
        )

        if err != kAXErrorSuccess:
            _setError(err, 'Could not add notification to observer')

        #Add observer source to run loop
        CFRunLoopAddSource(
            CFRunLoopGetCurrent(),
            AXObserverGetRunLoopSource(observer),
            kCFRunLoopDefaultMode
        )

        # Set the signal handlers prior to running the run loop
        oldSigIntHandler = MachSignals.signal(signal.SIGINT, _sigHandler)
        # If an error occurs (return value is SIG_ERR), continue as it's not fatal
        AppHelper.runConsoleEventLoop(
            mode=kCFRunLoopDefaultMode,
            installInterrupt=False,
            maxTimeout=timeout,
        )
        MachSignals.signal(signal.SIGINT, oldSigIntHandler)
        err = AXObserverRemoveNotification(observer, self.ref, notificationStr)
        if err != kAXErrorSuccess:
            _setError(err, 'Could not remove notification from observer')

        return self.observerRes
Esempio n. 31
0
    def _setNotification(self,
                         timeout=0,
                         notificationStr=None,
                         callbackFn=None,
                         callbackArgs=None,
                         callbackKwargs=None):
        if callable(callbackFn):
            self.callbackFn = callbackFn

        if isinstance(callbackArgs, tuple):
            self.callbackArgs = callbackArgs
        else:
            self.callbackArgs = tuple()

        if isinstance(callbackKwargs, dict):
            self.callbackKwargs = callbackKwargs

        self.observerRes = None

        pid = self._getPid()
        err, observer = AXObserverCreate(pid, observerCallback, None)
        if err != kAXErrorSuccess:
            _setError(err, 'Could not create observer for notification')

        err = AXObserverAddNotification(observer, self.ref, notificationStr,
                                        self)

        if err != kAXErrorSuccess:
            _setError(err, 'Could not add notification to observer')

        #Add observer source to run loop
        CFRunLoopAddSource(CFRunLoopGetCurrent(),
                           AXObserverGetRunLoopSource(observer),
                           kCFRunLoopDefaultMode)

        # Set the signal handlers prior to running the run loop
        oldSigIntHandler = MachSignals.signal(signal.SIGINT, _sigHandler)
        # If an error occurs (return value is SIG_ERR), continue as it's not fatal
        AppHelper.runConsoleEventLoop(
            mode=kCFRunLoopDefaultMode,
            installInterrupt=False,
            maxTimeout=timeout,
        )
        MachSignals.signal(signal.SIGINT, oldSigIntHandler)
        err = AXObserverRemoveNotification(observer, self.ref, notificationStr)
        if err != kAXErrorSuccess:
            _setError(err, 'Could not remove notification from observer')

        return self.observerRes
def main():

	global gMLNotification
	global gImportFullPath

	# Anything to process? Also needed for mmap function.	
	fileSize = os.stat(gImportFullPath).st_size

	if fileSize > 0:
		# Setup our app environment.
		app=AppKit.NSApplication.sharedApplication()
	
		theFile = open(gImportFullPath)
		importData = mmap.mmap(theFile.fileno(), fileSize, access=mmap.ACCESS_READ)

		# Get lines with a non-zero error code, extracting the date, time, error object, and error number
		rePattern = re.compile (r"(\d\d\d\d-\d\d-\d\d) (\d\d\:\d\d:\d\d).*?\t(.*?)\t([123456789]\d*)\t(.*)")

		# Banner notifications stay up for about 6 seconds, but there may be delays posting them.
		# We need to hang around long enough to handle a user clicking on the notification.
		t = Timer(9.0, stopRunLoop)
		t.start()

		allMatches = rePattern.findall (importData)
		print "Found",len (allMatches),"errors"
		hadMatch = False
		matchNum = -1
		n = []
	
		# This should be the last logged error in import log.
		for match in allMatches:
			matchNum += 1
			n.append (None)
			dt = datetime.strptime(match[0] + " " + match[1], "%Y-%m-%d %H:%M:%S")
	
			if (datetime.now() - dt).seconds < 15:
				n[matchNum] = gMLNotification.notify ("FileMaker Import Error",match[2],match[3] + ": " + match[4],gImportFullPath)
				print "notification",matchNum,"added"
				print match
				time.sleep (0.5)
				hadMatch = True
								
		if hadMatch:
			# The timer set up previously will kill the event loop after the notifications have expired.
			AppHelper.runConsoleEventLoop(installInterrupt=True)

		else:
			# There were no matches, and nothing to do, just exit now.
			sys.exit(0)
Esempio n. 33
0
    def _layout_watcher(self):
        layout = self

        class LayoutWatchingCallback(AppKit.NSObject):
            def layoutChanged_(self, event):
                log.info('Mac keyboard layout changed, updating')
                layout._update_layout()

        center = Foundation.NSDistributedNotificationCenter.defaultCenter()
        watcher_callback = LayoutWatchingCallback.new()
        center.addObserver_selector_name_object_suspensionBehavior_(
            watcher_callback, 'layoutChanged:',
            'com.apple.Carbon.TISNotifySelectedKeyboardInputSourceChanged',
            None,
            Foundation.NSNotificationSuspensionBehaviorDeliverImmediately)
        AppHelper.runConsoleEventLoop(installInterrupt=True)
Esempio n. 34
0
    def _runloop_thread(self):
        try:
            with objc.autorelease_pool():
                queue_ptr = objc.objc_object(c_void_p=self._dispatch_queue)

                self._manager = CoreBluetooth.CBCentralManager.alloc()
                self._manager.initWithDelegate_queue_options_(
                    self, queue_ptr, None)

                #self._peripheral_manager = CoreBluetooth.CBPeripheralManager.alloc()
                #self._peripheral_manager.initWithDelegate_queue_options_(self, queue_ptr, None)
                self._runloop_started_lock.set()
                AppHelper.runConsoleEventLoop(installInterrupt=True)
        except Exception as e:
            log.exception(e)
        log.info("Exiting runloop")
Esempio n. 35
0
def test_console():
    from PyObjCTools import AppHelper
    from ConsoleReactor import ConsoleReactor
    host = '127.0.0.1'
    port = 0
    interpreterPath = sys.executable
    scriptPath = unicode(os.path.abspath('tcpinterpreter.py'))
    commandReactor = ConsoleReactor.alloc().init()
    interp = AsyncPythonInterpreter.alloc().initWithHost_port_interpreterPath_scriptPath_commandReactor_(host, port, interpreterPath, scriptPath, commandReactor)
    interp.connect()
    class ThisEventLoopStopper(NSObject):
        def interpFinished_(self, notification):
            AppHelper.stopEventLoop()
    stopper = ThisEventLoopStopper.alloc().init()
    NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(stopper, 'interpFinished:', u'AsyncPythonInterpreterClosed', interp)
    AppHelper.runConsoleEventLoop(installInterrupt=True)
Esempio n. 36
0
def test_console():
    from PyObjCTools import AppHelper
    from ConsoleReactor import ConsoleReactor
    host = '127.0.0.1'
    port = 0
    interpreterPath = sys.executable
    scriptPath = unicode(os.path.abspath('tcpinterpreter.py'))
    commandReactor = ConsoleReactor.alloc().init()
    interp = AsyncPythonInterpreter.alloc().initWithHost_port_interpreterPath_scriptPath_commandReactor_(host, port, interpreterPath, scriptPath, commandReactor)
    interp.connect()
    class ThisEventLoopStopper(NSObject):
        def interpFinished_(self, notification):
            AppHelper.stopEventLoop()
    stopper = ThisEventLoopStopper.alloc().init()
    NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(stopper, 'interpFinished:', u'AsyncPythonInterpreterClosed', interp)
    AppHelper.runConsoleEventLoop(installInterrupt=True)
Esempio n. 37
0
def main():
    add_workspace_notifications(load_workspace_notifications())

    # NOTE: This timer is basically a kludge around the fact that we can't reliably get
    #       signals or Control-C inside a runloop. This wakes us up often enough to
    #       appear tolerably responsive:
    CFRunLoopAddTimer(
        NSRunLoop.currentRunLoop().getCFRunLoop(),
        CFRunLoopTimerCreate(None, CFAbsoluteTimeGetCurrent(), 2.0, 0, 0,
                             timer_callback, None), kCFRunLoopCommonModes)

    try:
        AppHelper.runConsoleEventLoop(installInterrupt=True)
    except KeyboardInterrupt:
        logging.info("KeyboardInterrupt received, exiting")

    sys.exit(0)
Esempio n. 38
0
def main():
    global CRANKD_OPTIONS, CRANKD_CONFIG
    CRANKD_OPTIONS = process_commandline()
    CRANKD_CONFIG  = load_config(CRANKD_OPTIONS)

    # We replace the initial program name with one which won't break if relative paths are used:
    sys.argv[0]    = os.path.realpath(sys.argv[0])

    configure_logging()

    logging.info("Loaded configuration from %s" % CRANKD_OPTIONS.config_file)

    if "NSWorkspace" in CRANKD_CONFIG:
        add_workspace_notifications(CRANKD_CONFIG['NSWorkspace'])

    if "SystemConfiguration" in CRANKD_CONFIG:
        add_sc_notifications(CRANKD_CONFIG['SystemConfiguration'])

    if "FSEvents" in CRANKD_CONFIG:
        add_fs_notifications(CRANKD_CONFIG['FSEvents'])

    # We reuse our FSEvents code to watch for changes to our files and
    # restart if any of our libraries have been updated:
    add_conditional_restart(CRANKD_OPTIONS.config_file, "Configuration file %s changed" % CRANKD_OPTIONS.config_file)
    for (m_name, m_file) in [(k, v) for k, v in sys.modules.iteritems() if hasattr(v, '__file__')]:
        add_conditional_restart(m_file.__file__, "Module %s was updated" % m_name)

    signal.signal(signal.SIGHUP, partial(restart, "SIGHUP received"))

    start_fs_events()

    # NOTE: This timer is basically a kludge around the fact that we can't reliably get
    #       signals or Control-C inside a runloop. This wakes us up often enough to
    #       appear tolerably responsive:
    CFRunLoopAddTimer(
        NSRunLoop.currentRunLoop().getCFRunLoop(),
        CFRunLoopTimerCreate(None, CFAbsoluteTimeGetCurrent(), 5.0, 0, 0, timer_callback, None),
        kCFRunLoopCommonModes
    )

    try:
        AppHelper.runConsoleEventLoop(installInterrupt=True)
    except KeyboardInterrupt:
        logging.info("KeyboardInterrupt received, exiting")

    sys.exit(0)
def start_screen_state_observer():
    '''
    Kill the main loop whenever screen turns off, so that we dont keep getting dialogs and sounds
    even when laptop is unattended.
    Start the main loop again once screen is on again.
    '''
    logging.info('ScreenStateObserver process started.')
    setproctitle.setproctitle(mp.current_process().name)
    nc = Foundation.NSDistributedNotificationCenter.defaultCenter()
    screen_state_observer = ScreenStateObserver.new()
    nc.addObserver_selector_name_object_(screen_state_observer,
                                         'screenOffHandler:',
                                         'com.apple.screenIsLocked', None)
    nc.addObserver_selector_name_object_(screen_state_observer,
                                         'screenOnHandler:',
                                         'com.apple.screenIsUnlocked', None)
    AppHelper.runConsoleEventLoop()
Esempio n. 40
0
 def setup_event_loop(self):
     if NSWorkspace is None:
         return
     ws = NSWorkspace.sharedWorkspace()
     self.notificationCenter = ws.notificationCenter()
     self.handler = NotificationHandler.new()
     self.handler.sleep_callback = self.client.suspend
     self.handler.wake_callback = self.client.resume
     self.notificationCenter.addObserver_selector_name_object_(
              self.handler, "handleSleepNotification:",
              AppKit.NSWorkspaceWillSleepNotification, None)
     self.notificationCenter.addObserver_selector_name_object_(
              self.handler, "handleWakeNotification:",
              AppKit.NSWorkspaceDidWakeNotification, None)
     log("starting console event loop with notifcation center=%s and handler=%s", self.notificationCenter, self.handler)
     if self.blocking:
         #this is for running standalone
         AppHelper.runConsoleEventLoop(installInterrupt=self.blocking)
Esempio n. 41
0
def main():
    add_workspace_notifications(load_workspace_notifications())

    # NOTE: This timer is basically a kludge around the fact that we can't reliably get
    #       signals or Control-C inside a runloop. This wakes us up often enough to
    #       appear tolerably responsive:
    CFRunLoopAddTimer(
        NSRunLoop.currentRunLoop().getCFRunLoop(),
        CFRunLoopTimerCreate(None, CFAbsoluteTimeGetCurrent(), 2.0, 0, 0, timer_callback, None),
        kCFRunLoopCommonModes
    )

    try:
        AppHelper.runConsoleEventLoop(installInterrupt=True)
    except KeyboardInterrupt:
        logging.info("KeyboardInterrupt received, exiting")

    sys.exit(0)
Esempio n. 42
0
    def _layout_watcher(self):
        layout = self

        class LayoutWatchingCallback(AppKit.NSObject):
            def layoutChanged_(self, event):
                log.info('Mac keyboard layout changed, updating')
                layout._update_layout()

        center = Foundation.NSDistributedNotificationCenter.defaultCenter()
        watcher_callback = LayoutWatchingCallback.new()
        center.addObserver_selector_name_object_suspensionBehavior_(
            watcher_callback,
            'layoutChanged:',
            'com.apple.Carbon.TISNotifySelectedKeyboardInputSourceChanged',
            None,
            Foundation.NSNotificationSuspensionBehaviorDeliverImmediately
        )
        AppHelper.runConsoleEventLoop(installInterrupt=True)
Esempio n. 43
0
def discover(devToFind=None, timeout=2, connectableOnly=False):
	# do this for every function to ensure user not ignoring dependencies
	if( checkDep() == False ): quit()

	devices = list(())

	# check if library is properly loaded yet
	global LOADED
	global DEBUG
	if( LOADED == False ):
		helpers.debugMsg("[WARNING] ...bleach module not loaded, calling bleach.load() now, this should be called at start of main program")
		if( load() == False ):
			helpers.debugMsg("[WARNING] ...bleach module failed to load")
			return None

	# MAC discovery here
	if( OSTAG == "MAC" ):
		try:
			# Using CoreBluetooth
			import CoreBluetooth
			from PyObjCTools import AppHelper

			bleManage = CoreBluetooth.CBCentralManager.alloc()
			if( bleManage is not None ):
				helpers.debugMsg( "[INFO] CBCentralManager loaded OK")
				bleManage.init()
				# create the CBManager Delegate
				myDelegate = cbmanagerDelegate.managerDelegate()
				myDelegate.setTimeout(timeout)
				myDelegate.setParams(connectableOnly, DEBUG)

				bleManage.initWithDelegate_queue_options_(myDelegate, None, None)
				AppHelper.runConsoleEventLoop()

				# grab the device list
				devices = myDelegate.getDevices()

			else:
				helpers.debugMsg("[WARNING] CBCentralManager.alloc() returned <None>")
		except Exception as err:
				helpers.debugMsg("[WARNING] BLEach discover() failed with error <"+str(err)+">")

	# send back the list of devices
	return devices
Esempio n. 44
0
    def wait_for(self, notification=None, filter_=None, timeout=5):
        self.callback_result = None

        @PAXObserverCallback
        def _callback(observer, element, notification, refcon):
            logger.debug("CALLBACK")
            logger.debug("%s, %s, %s, %s" %
                         (observer, element, notification, refcon))
            ret_element = self.ref.__class__(element)
            if filter_(ret_element):
                self.callback_result = ret_element

        observer = PAXObserverCreate(self.ref.pid, _callback)

        PAXObserverAddNotification(observer, self.ref.ref, notification,
                                   id(self.ref.ref))

        # Add observer source to run loop
        CFRunLoopAddSource(
            CFRunLoopGetCurrent(),
            AXObserverGetRunLoopSource(observer),
            NSDefaultRunLoopMode,
        )

        def event_stopper():
            end_time = time.time() + timeout
            while time.time() < end_time:
                if self.callback_result is not None:
                    break
            AppHelper.callAfter(AppHelper.stopEventLoop)

        event_watcher = threading.Thread(target=event_stopper)
        event_watcher.daemon = True
        event_watcher.start()

        # Set the signal handlers prior to running the run loop
        oldSigIntHandler = MachSignals.signal(signal.SIGINT, _sigHandler)
        AppHelper.runConsoleEventLoop()
        MachSignals.signal(signal.SIGINT, oldSigIntHandler)

        PAXObserverRemoveNotification(observer, self.ref.ref, notification)

        return self.callback_result
Esempio n. 45
0
 def setup_event_loop(self):
     if NSWorkspace is None:
         return
     ws = NSWorkspace.sharedWorkspace()
     self.notificationCenter = ws.notificationCenter()
     self.handler = NotificationHandler.new()
     self.handler.sleep_callback = self.client.suspend
     self.handler.wake_callback = self.client.resume
     self.notificationCenter.addObserver_selector_name_object_(
         self.handler, "handleSleepNotification:",
         AppKit.NSWorkspaceWillSleepNotification, None)
     self.notificationCenter.addObserver_selector_name_object_(
         self.handler, "handleWakeNotification:",
         AppKit.NSWorkspaceDidWakeNotification, None)
     log(
         "starting console event loop with notifcation center=%s and handler=%s",
         self.notificationCenter, self.handler)
     if self.blocking:
         #this is for running standalone
         AppHelper.runConsoleEventLoop(installInterrupt=self.blocking)
Esempio n. 46
0
   def getAppRefByLocalizedName(cls, name):
      '''getAppRefByLocalizedName - Get the top level element for the
         application with the specified localized name, such as
         VMware Fusion.

         Wildcards are also allowed.
      '''
      # Refresh the runningApplications list
      def runLoopAndExit():
         AppHelper.stopEventLoop()
      AppHelper.callLater(1, runLoopAndExit)
      AppHelper.runConsoleEventLoop()
      # Get a list of running applications
      ws = AppKit.NSWorkspace.sharedWorkspace()
      apps = ws.runningApplications()
      for app in apps:
         if fnmatch.fnmatch(app.localizedName(), name):
            pid = app.processIdentifier()
            return cls.getAppRefByPid(pid)
      raise ValueError('Specified application not found in running apps.')
Esempio n. 47
0
def main():
	
	# Pre-populate skip set with all existing screen shots
	firstLoadFileList = os.listdir(WATCH_PATH)
	for filename in firstLoadFileList:
		if MAC_SCREENSHOT_REGEX.match(filename):
			macgrab.addUploaded(filename)
			
	# Listen for filesystem events at the watch_path
	addFSEventListener()
	
	# Keep alive
	CFRunLoopAddTimer(NSRunLoop.currentRunLoop().getCFRunLoop(), 
					CFRunLoopTimerCreate(None, CFAbsoluteTimeGetCurrent(), INTERVAL_TO_CHECK_FOR_PROGRAM_EXIT, 0, 0, onTimerCallback, None), 
					kCFRunLoopCommonModes)

	# respond to control-c to terminate
	try:
		AppHelper.runConsoleEventLoop(installInterrupt=True)
	except KeyboardInterrupt:
		print "exiting"
Esempio n. 48
0
    def getAppRefByLocalizedName(cls, name):
        '''getAppRefByLocalizedName - Get the top level element for the
         application with the specified localized name, such as
         VMware Fusion.

         Wildcards are also allowed.
      '''

        # Refresh the runningApplications list
        def runLoopAndExit():
            AppHelper.stopEventLoop()

        AppHelper.callLater(1, runLoopAndExit)
        AppHelper.runConsoleEventLoop()
        # Get a list of running applications
        ws = AppKit.NSWorkspace.sharedWorkspace()
        apps = ws.runningApplications()
        for app in apps:
            if fnmatch.fnmatch(app.localizedName(), name):
                pid = app.processIdentifier()
                return cls.getAppRefByPid(pid)
        raise ValueError('Specified application not found in running apps.')
Esempio n. 49
0
def do_run_query_loop0(query):
    """docstring for do_run_loop"""
    
    class MyEventHandlers():
        def __init__(self, code, description=""):
            self.code = code
            self.description = description
        
        def __str__(self):
            return "%s (%d)" %  (self.description,  self.code)
        
        def gathering_(self, notification):
            print   notification.name() # NSMetadataQueryGatheringProgressNotification

        def did_update_(self, notification):
            print   "name", notification.name()
            print   "userInfo is: " , notification.userInfo()
        
        def did_finish_(self, notification):
            print   notification.name() # NSMetadataQueryDidFinishGatheringNotification
            # Stops the event loop (if started by runConsoleEventLoop) or sends the NSApplication a terminate: message.
            didStop = AppHelper.stopEventLoop()
            if didStop: 
                print "stopping the event loop "
            raise ValueError, "this will stop you!"

    my_handlers = MyEventHandlers(1)

    nc.addObserver_selector_name_object_(my_handlers, "did_finish:", NSMetadataQueryDidFinishGatheringNotification, query)
    nc.addObserver_selector_name_object_(my_handlers, "did_update:", NSMetadataQueryDidUpdateNotification, query)
    nc.addObserver_selector_name_object_(my_handlers, "gathering:",  NSMetadataQueryGatheringProgressNotification, query)

    query.startQuery()

    print "Listening for new tunes...."
    try:
        AppHelper.runConsoleEventLoop( mode = NSDefaultRunLoopMode)
    except ValueError, e:
        print "ValueError", e
Esempio n. 50
0
    def run(self, installSignalHandlers=True):
        """
        Start the reactor.
        """
        self._postQueue = Queue.Queue()

        # start select() thread:
        self.interleave(AppHelper.callAfter,
                        installSignalHandlers=installSignalHandlers)
        #if installSignalHandlers:
        #    self.callLater(0, self._installSignalHandlersAgain)

        # add cleanup events:
        self.addSystemEventTrigger("after", "shutdown", AppHelper.stopEventLoop)
        self.addSystemEventTrigger("after", "shutdown",
                                   lambda: self._postQueue.put(None))

        AppHelper.runConsoleEventLoop(installInterrupt=True)
            
        if not self._stopping:
            # if event loop exited without reactor.stop() being
            # called.  At this point events from select() thread will
            # be added to _postQueue
            self.stop()
            while 1:
                try:
                    f = self._postQueue.get(timeout=0.01)
                except Queue.Empty:
                    continue
                else:
                    if f is None:
                        break
                    try:
                        f()
                    except:
                        log.err()
Esempio n. 51
0
def run():
    # enter the main event loop
    AppHelper.runConsoleEventLoop()
Esempio n. 52
0
# from ConsoleReactor import ConsoleReactor
# host = '127.0.0.1'
# port = 0
# interpreterPath = sys.executable
# scriptPath = unicode(os.path.abspath('tcpinterpreter.py'))
# commandReactor = ConsoleReactor.alloc().init()
# interp = AsyncPythonInterpreter.alloc().initWithHost_port_interpreterPath_scriptPath_commandReactor_(host, port, interpreterPath, scriptPath, commandReactor)
# interp.connect()

query = NSMetadataQuery.alloc().init()
query.setPredicate_(NSPredicate.predicateWithFormat_( 'kMDItemKind = "Aperture Library"' ))
scopes = [NSMetadataQueryUserHomeScope]             
query.setSearchScopes_( scopes )


class ThisEventLoopStopper(NSObject):
    def interpFinished_(self, notification):
        AppHelper.stopEventLoop()
stopper = ThisEventLoopStopper.alloc().init()

NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(stopper, 'interpFinished:', NSMetadataQueryDidFinishGatheringNotification, query)
query.startQuery()

# NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(stopper, 'interpFinished:', u'AsyncPythonInterpreterClosed', interp)
AppHelper.runConsoleEventLoop(installInterrupt=True)

query.stopQuery()
print "count: ", len(query.results())
for item in query.results():
    print "item: ", item.valueForAttribute_("kMDItemPath")
Esempio n. 53
0
def main():
    serviceProvider = TinyURLService.alloc().init()
    NSRegisterServicesProvider(serviceProvider, u"TinyURLService")
    AppHelper.runConsoleEventLoop()
Esempio n. 54
0
def start_event_loop():
    AppHelper.runConsoleEventLoop(installInterrupt=True)
Esempio n. 55
0
 def run(self):
     #this is for running standalone
     log("starting console event loop")
     self.event_loop_started = True
     import PyObjCTools.AppHelper as AppHelper   #@UnresolvedImport
     AppHelper.runConsoleEventLoop(installInterrupt=True)
Esempio n. 56
0
        # Find the path to the just inserted volume
        path = aNotification.userInfo()['NSDevicePath']

        for aFile in os.listdir(path):
            if readTheseFiles.match(aFile):
                # Found a readme file, try to open it using the Workspace API

                fullPath = os.path.join(path, aFile)
                success, app, None = workspace.getInfoForFile_application_type_(
                        fullPath)
                if not success:
                    NSLog("Failed to find application to open file %s",
                        fullPath)
                    return
                workspace.openFile_withApplication_(fullPath, app)

# Create an instance of our notification handler, and ask the workspace 
# notification center to tell us when a new volume is mounted.
workspace = NSWorkspace.sharedWorkspace()
notificationCenter = workspace.notificationCenter()
notificationHandler = NotificationHandler.new()
notificationCenter.addObserver_selector_name_object_(
    notificationHandler,
    "handleMountNotification:",
    NSWorkspaceDidMountNotification,
    None)

NSLog("Listening for mount notifications....")
AppHelper.runConsoleEventLoop()
Esempio n. 57
0
'''
This python script listens for distributed notifications from iTunes of new songs playing, 
works alot better then constantly polling. 
'''
import Foundation
from AppKit import *
from PyObjCTools import AppHelper

class GetSongs(NSObject):
    def getMySongs_(self, song):
        song_details = {}
        ui = song.userInfo()
        song_details = dict(zip(ui.keys(), ui.values()))
        print song_details

nc = Foundation.NSDistributedNotificationCenter.defaultCenter()
GetSongs = GetSongs.new()
nc.addObserver_selector_name_object_(GetSongs, 'getMySongs:', 'com.apple.iTunes.playerInfo',None)

NSLog("Listening for new tunes....")
AppHelper.runConsoleEventLoop()
Esempio n. 58
0
 def startLoop(self):
     NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
         0.0, self, 'onPumpFirst:', None, False)
     AppHelper.runConsoleEventLoop()
Esempio n. 59
0
 def run(self):
     #this is for running standalone
     AppHelper.runConsoleEventLoop(installInterrupt=True)