def _exportFrame(self): if self.session.next(): # step to the proper FRAME value self._meta.frame = self.session.next() # run the draw() function if it exists (or the whole top-level if not) result = self.run(method="draw" if self.animated else None) # let the delegate draw to the screen self.delegate.exportFrame(result, self.canvas) # pass the frame content to the file-writer if result.ok: self.session.add(self.canvas) # know when to fold 'em if result.ok in (False, 'HALTED'): self.session.cancel() # give the runloop a chance to collect events between frames AppHelper.callLater(0.001, self._exportFrame) else: # we've drawn the final frame in the export result = self.call("stop") self.delegate.exportFrame(result, canvas=None) self.session.done()
def _exportFrame(self): if self.session.next(): # step to the proper FRAME value self._meta.next = self.session.next() # run the draw() function if it exists (or the whole top-level if not) result = self.run(method="draw" if self.animated else None) # let the delegate draw to the screen self.delegate.exportFrame(result, self.canvas) # pass the frame content to the file-writer if result.ok: self.session.add(self.canvas) # know when to fold 'em if result.ok in (False, 'HALTED'): self.session.cancel() # give the runloop a chance to collect events between frames AppHelper.callLater(0.001, self._exportFrame) else: # we've drawn the final frame in the export result = self.call("stop") self.delegate.exportFrame(result, canvas=None) self.session.done()
def applicationDidFinishLaunching_(self, aNotification): """ Create a toolbar and menu for the mac application that can be used to close shut down the application. """ self.statusItem = NSStatusBar\ .systemStatusBar()\ .statusItemWithLength_(NSVariableStatusItemLength) self.statusItem.setTitle_(u"M") self.statusItem.setHighlightMode_(TRUE) self.statusItem.setEnabled_(TRUE) self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( "Quit", "terminate:", "") # ugly but... it provides the information. self.port = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( "Listening on localhost:{0}".format(_PORT), "", "") self.menubarMenu = NSMenu.alloc().init() self.menubarMenu.addItem_(self.port) self.menubarMenu.addItem_(self.quit) # add the menu to status bar item self.statusItem.setMenu_(self.menubarMenu) self.statusItem.setToolTip_(u"mimic - rackspace mock api") AppHelper.callLater(1, startMimic)
def _loop(self): request = WAIT if not self.isbusy and self._pipe.poll(): # Coreからのメッセージ取得 try: request = self._pipe.recv() except: pass if request == CONNECT: self.isbusy = True self._state = CONNECT self._timer = Timer(self._timeout_sec, self._timeout, args=["CONNECT"]) self._timer.start() self._ble_delegate.bleConnect(self.callback) elif request == DISCONNECT: self.isbusy = True self._state = DISCONNECT self._timer = Timer(self._timeout_sec, self._timeout, args=["DISCONNECT"]) self._timer.start() self._ble_delegate.bleDisconnect(self.callback) else: self.isbusy = True self._state = WRITE self._timer = Timer(self._timeout_sec, self._timeout, args=["WRITE"]) self._timer.start() self._ble_delegate.send(request, self.callback) AppHelper.callLater(0.1, self._loop)
def atRian(self): self.start_offset += 1 if self.start_offset == self.sv.numberOfPeoplePanes(): if self.done_cb: AppHelper.callLater(PERSON_DELAY, self.done_cb) return AppHelper.callLater(PERSON_DELAY, self.proceedToDavid)
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
def _set_volatile(self, volatile): if self._volatile == volatile: return self._volatile = volatile if not volatile: AppHelper.callLater(0.2, self.cache) else: self._raster = None
def windowScriptObjectAvailable_(self, scriptObject): global log log = lambda x: AppHelper.callAfter(scriptObject.callWebScriptMethod_withArguments_, 'log', [x]) scriptObject.setValue_forKey_("yes", "TestBundleLoaded") scriptObject.setValue_forKey_(self, "TestBundle") AppHelper.callLater(1, scriptObject.callWebScriptMethod_withArguments_, 'initialize_threads', []) #log("hi!"); self.wso = scriptObject
def _updated_pixmap(self, sender): if self.first_pixmap_update: self.first_pixmap_update = False self.rfb_renderer.set_new_image_rep(self.bitmap_image_rep) else: self.rfb_renderer.refresh_image() sender.framebuffer_mv = self.bitmap_image_rep.bitmapData() AppHelper.callLater(0.1, sender.request_updated_framebuffer)
def enter_pressed(self): str = self.field.stringValue() if str == "" or str == self.field.default_value: return write("User input: " + str) self.button.setTitle_('Submitting...') self.button.setEnabled_(False) AppHelper.callLater(2, self.update_button_and_exit) return
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 invalidateUICallback_(self, paths_to_invalidate): TRACE('++ remote events told me to invalidate the following folders: %r' % (paths_to_invalidate,)) self.pending_paths_to_invalidate.update(paths_to_invalidate) incoming = time.time() if self.last_ui_invalidation is not None and incoming - self.last_ui_invalidation < REMOTE_EVENT_CHILLOUT: TRACE('chilling out for a bit') AppHelper.callLater(REMOTE_EVENT_CHILLOUT - (incoming - self.last_ui_invalidation), self.invalidateUICallback_, {}) return self.last_ui_invalidation = incoming last_selected = None for x in range(0, self.browser.lastColumn() + 1): dir_children_for_refresh = None if x == 0: for path in self.pending_paths_to_invalidate: if path.ns_rel()[1] == '/': dir_children_for_refresh = self.pending_paths_to_invalidate[path] break else: selected = self.browser.matrixInColumn_(x - 1).selectedCell() dir_children_for_refresh = self.pending_paths_to_invalidate.get(selected.path().lower()) if selected else None matrix = self.browser.matrixInColumn_(x) if matrix: if dir_children_for_refresh: TRACE('+++++ refreshing: %r, %r' % (x, dir_children_for_refresh)) ret = self.intelligentlyRefreshMatrix_withDirChildren_restoreSelection_(matrix, dir_children_for_refresh, True) matrix.sizeToCells() matrix.setNeedsDisplay_(YES) if ret > -1: last_selected = (ret, x) elif ret == -1: if last_selected is not None: self.browser.selectRow_inColumn_(last_selected[0], last_selected[1]) else: self.browser.setPath_(self.browser.pathSeparator()) break needs_display = False for y in range(matrix.numberOfRows()): cell = matrix.cellAtRow_column_(y, 0) path = cell.path().lower() if path in self.pending_paths_to_invalidate: new_state = NO if self.pending_paths_to_invalidate[path] else YES if cell.isLeaf() != new_state: TRACE('<> refreshing leaf state for %r' % (path,)) cell.setLeaf_(new_state) cell.invalidateFolderTag() needs_display = True if cell == matrix.selectedCell(): self.browser.selectRow_inColumn_(y, x) break if needs_display: matrix.setNeedsDisplay_(YES) self.pending_paths_to_invalidate = {}
def record(): path = os.path.dirname(os.path.realpath(__file__)) # DownDown is the time between KeyA being pressed down to KeyB being pressed # down, including the intermediate time if len(Helper.downDown) != 0: averageDownDown = sum(Helper.downDown)/len(Helper.downDown) else: averageDownDown = 0 # UpDown is the time from KeyA being released to KeyB being pressed down # Is the inverse of KeyCount if len(Helper.upDown) != 0: averageUpDown = sum(Helper.upDown)/len(Helper.upDown) else: averageUpDown = 0 # Hold is the time a key is held down if len(Helper.hold) != 0: averageHold = sum(Helper.hold)/len(Helper.hold) else: averageHold = 0 # Subtract inactive time at the end of the bucket by calling this once more Helper.keySpeed() # Divide the number of keys pressed by the time the user was active # Will be 0 if no keys are pressed, will be max if the most keys are pressed # in the shortest time # example: # if a user presses 60 keys in the first 10 seconds of the 30 second bucket, # the inactive 20 seconds will be subtracted from totalActiveTime by the # manual Helper.keySpeed() call. The final keySpeed will be 60/10 = 6 # (rather than 60/30 = 2 as it would be without subtracting the inactive time) keySpeed = Helper.num / Helper.totalActiveTime # Save the files tempFile = open("/keys.temp", "w") tempCsvOut = csv.writer(tempFile) tempCsvOut.writerow((Helper.num, averageDownDown, averageUpDown, averageHold, keySpeed)) tempFile.flush() timestamp = time.mktime(datetime.datetime.utcnow().timetuple()) keycountsFile = open("/keycounts.csv", "ab") keycountsCsvOut = csv.writer(keycountsFile) keycountsCsvOut.writerow((timestamp, Helper.num, averageDownDown, averageUpDown, averageHold, keySpeed)) keycountsFile.flush() Helper.reset() AppHelper.callLater(_BUCKET_SIZE_SECONDS, record)
def record(): path = os.path.dirname(os.path.realpath(__file__)) # DownDown is the time between KeyA being pressed down to KeyB being pressed # down, including the intermediate time if len(Helper.downDown) != 0: averageDownDown = sum(Helper.downDown) / len(Helper.downDown) else: averageDownDown = 0 # UpDown is the time from KeyA being released to KeyB being pressed down # Is the inverse of KeyCount if len(Helper.upDown) != 0: averageUpDown = sum(Helper.upDown) / len(Helper.upDown) else: averageUpDown = 0 # Hold is the time a key is held down if len(Helper.hold) != 0: averageHold = sum(Helper.hold) / len(Helper.hold) else: averageHold = 0 # Subtract inactive time at the end of the bucket by calling this once more Helper.keySpeed() # Divide the number of keys pressed by the time the user was active # Will be 0 if no keys are pressed, will be max if the most keys are pressed # in the shortest time # example: # if a user presses 60 keys in the first 10 seconds of the 30 second bucket, # the inactive 20 seconds will be subtracted from totalActiveTime by the # manual Helper.keySpeed() call. The final keySpeed will be 60/10 = 6 # (rather than 60/30 = 2 as it would be without subtracting the inactive time) keySpeed = Helper.num / Helper.totalActiveTime # Save the files tempFile = open("/keys.temp", "w") tempCsvOut = csv.writer(tempFile) tempCsvOut.writerow( (Helper.num, averageDownDown, averageUpDown, averageHold, keySpeed)) tempFile.flush() timestamp = time.mktime(datetime.datetime.utcnow().timetuple()) keycountsFile = open("/keycounts.csv", "ab") keycountsCsvOut = csv.writer(keycountsFile) keycountsCsvOut.writerow((timestamp, Helper.num, averageDownDown, averageUpDown, averageHold, keySpeed)) keycountsFile.flush() Helper.reset() AppHelper.callLater(_BUCKET_SIZE_SECONDS, record)
def idle_add(callback, periodic=None): def wrapper(): callback() if periodic is not None: AppHelper.callLater(periodic, wrapper) if periodic is not None and periodic < 0: raise ValueError('periodic cannot be negative') # XXX: we have a lousy thread API that doesn't allocate pools for us... pool = NSAutoreleasePool.alloc().init() if periodic is not None: AppHelper.callLater(periodic, wrapper) else: AppHelper.callAfter(wrapper) del pool
def do_bubble(self, message, caption, ctx_ref = None): TRACE('NotificationCenterController: Bubbling: %s', message) if self._current: TRACE('Queuing Notification: %s', message) self._q.put_nowait((message, caption, ctx_ref)) return user_info = {u'pid': unicode(os.getpid())} if ctx_ref is not None: user_info[u'ctx_ref'] = unicode(ctx_ref) n = NSUserNotification.alloc().init() n.setTitle_(caption) n.setInformativeText_(message) n.setHasActionButton_(False) n.setUserInfo_(user_info) self._current = n NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification_(n) AppHelper.callLater(self.POPUP_DURATION, self.timeout, n)
def __init__(self, width=320, height=240, setup=None, teardown=None): pool = NSAutoreleasePool.alloc().init() self.delegate = Delegate.alloc().init() self.app = NSApplication.sharedApplication() self.app.setDelegate_(self.delegate) window = NSWindow.alloc() window.initWithContentRect_styleMask_backing_defer_(((0, 0), (width, height)), 31, 2, 0) window.setDelegate_(self.delegate) window.setTitle_('muFAT Test') window.setLevel_(3) window.display() self.window = window if setup is not None: AppHelper.callLater(1, setup, self) del pool
def __init__(self, width=320, height=240, setup=None, teardown=None): pool = NSAutoreleasePool.alloc().init() self.delegate = Delegate.alloc().init() self.app = NSApplication.sharedApplication() self.app.setDelegate_(self.delegate) window = NSWindow.alloc() window.initWithContentRect_styleMask_backing_defer_( ((0, 0), (width, height)), 31, 2, 0) window.setDelegate_(self.delegate) window.setTitle_('muFAT Test') window.setLevel_(3) window.display() self.window = window if setup is not None: AppHelper.callLater(1, setup, self) del pool
def start_blast(self): w, h = self.frame().size radius = math.sqrt((w / 2) ** 2 + (h / 2) ** 2) + 100 for i, _vi in enumerate(self.blast_order): startx, starty = _vi.frame().origin direction = insecure_random.random() * 2 * math.pi newx = radius * math.cos(direction) + w / 2.0 newy = radius * math.sin(direction) + h / 2.0 AppHelper.callLater(self.DELAY * i, self.saveTimerForFunc_args_kwargs_(SpringAnimator, (0, 1.0, 60.0, 8.0, 4, 1 / 30.0, functools.partial(self.move_view, startx, starty, newx - startx, newy - starty, _vi), None), {})) if self.done_cb: AppHelper.callLater((len(self.blast_order) + 2) * self.DELAY, self.done_cb)
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.')
def loop(self): endpoints = [sys.stdin, self.listener] # list of connections if self.connection is not None: endpoints.append(self.connection) r, w, e = select.select(endpoints, [], [], 0) if sys.stdin in r: delegate.shutdown() return if self.listener in r: self.connection, _ = self.listener.accept() if self.connection in r: c = self.connection.recv(1) if len(c) == 0: print("closed") self.connection.close() self.connection = None elif c not in ('\r', '\n'): print(repr(c)) self.robot.send(c) AppHelper.callLater(0.1, self.loop)
def playMSFT(self): self.MSFT.setHidden_(False) self.timers.append(SpringAnimator(0 - self.MSFT.frame().size[1], self.MSFT_POS[1], 60.0, 8.0, 2, 1 / 30.0, self.moveMSFT_, None)) AppHelper.callLater(self.DELAY * 2, self.winky)
def sleep(delay): from PyObjCTools import AppHelper from monocle.core import Callback cb = Callback() AppHelper.callLater(delay, cb, None) return cb
def call_later(self, seconds, fn, *args, **kwargs): return AppHelper.callLater(seconds, fn, *args, **kwargs)
def winky2(self): self._smile.setHidden_(True) self._wink.setHidden_(False) AppHelper.callLater(self.DELAY * 2, self.winky3)
def winky3(self): self._smile.setHidden_(False) self._wink.setHidden_(True) self.blast_idx = 0 AppHelper.callLater(self.DELAY * 2, self.start_blast)
def wrapper(): callback() if periodic is not None: AppHelper.callLater(periodic, wrapper)
def main(): app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.callLater(_BUCKET_SIZE_SECONDS, record) AppHelper.runEventLoop()
def wrapper(): callback() AppHelper.callLater(1, wrapper)
def start(self): AppHelper.callLater(0.1, self._loop) AppHelper.runConsoleEventLoop()
if len(c) == 0: print("closed") self.connection.close() self.connection = None elif c not in ('\r', '\n'): print(repr(c)) self.robot.send(c) AppHelper.callLater(0.1, self.loop) def send(self, data): """ send data to localhost not used here """ while len(data): sent = self.connection.send(data) data = data[sent:] delegate = RobotDelegate() manager = CBCentralManager.alloc() manager.initWithDelegate_queue_options_(delegate, None, None) comms = CommsManager(delegate) print(repr(manager)) AppHelper.callLater(0.1, comms.loop) AppHelper.runConsoleEventLoop()
def update_button_and_exit(self): self.button.setEnabled_(True) self.button.setTitle_('Message sent!') AppHelper.callLater(1, self.exit)
def newSketch_(self, sender): kind = ['sketch','anim','ottobot'][sender.tag()] doc = self.docFromTemplate_('TMPL:'+kind) if kind=='ottobot': AppHelper.callLater(0.1, doc.script.runScript)
def playGOOG(self): self.GOOG.setHidden_(False) self.timers.append(SpringAnimator(0 - self.GOOG.frame().size[1], self.GOOG_POS[1], 60.0, 8.0, 2, 1 / 30.0, self.moveGOOG_, None)) AppHelper.callLater(self.DELAY, self.playMSFT)
def idle_add(callback): def wrapper(): callback() AppHelper.callLater(1, wrapper) AppHelper.callLater(1, wrapper)
def playTo(self): self.to.setHidden_(False) AppHelper.callLater(self.DELAY * 2, self.playAAPL)