def get_apps(tag, removal): """use spotlight to find apps by custom tag""" # main dictionary removals = {} # set NSMetaDatQuery predicate by your custom tag with value of true predicate = "%s = 'true'" % tag # build and execute the spotlight query query = NSMetadataQuery.alloc().init() query.setPredicate_(NSPredicate.predicateWithFormat_(predicate)) query.setSearchScopes_(['/Applications']) query.startQuery() start_time = 0 max_time = 20 while query.isGathering() and start_time <= max_time: start_time += 0.3 NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.3)) query.stopQuery() # iterate through the results to grab spotlight attributes for item in query.results(): app = item.valueForAttribute_('kMDItemFSName') path = item.valueForAttribute_('kMDItemPath') customtag = item.valueForAttribute_(removal) if customtag: # build nested dictionary of tagged apps and attribute values removals[app] = {} removals[app]['path'] = path removals[app]['method'] = customtag return removals
def __init__(self, image): NSBundle.loadNibNamed_owner_("ScreensharingPreviewPanel", self) self.view.setImage_(image) self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(5.0, self, "closeTimer:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) self.window.orderFront_(None)
def find_apps_in_dirs(dirlist): """Do spotlight search for type applications within the list of directories provided. Returns a list of paths to applications these appear to always be some form of unicode string. """ applist = [] query = NSMetadataQuery.alloc().init() query.setPredicate_( NSPredicate.predicateWithFormat_('(kMDItemKind = "Application")')) query.setSearchScopes_(dirlist) query.startQuery() # Spotlight isGathering phase - this is the initial search. After the # isGathering phase Spotlight keeps running returning live results from # filesystem changes, we are not interested in that phase. # Run for 0.3 seconds then check if isGathering has completed. runtime = 0 maxruntime = 20 while query.isGathering() and runtime <= maxruntime: runtime += 0.3 NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.3)) query.stopQuery() if runtime >= maxruntime: display.display_warning( 'Spotlight search for applications terminated due to excessive ' 'time. Possible causes: Spotlight indexing is turned off for a ' 'volume; Spotlight is reindexing a volume.') for item in query.results(): pathname = item.valueForAttribute_('kMDItemPath') if pathname and not is_excluded_filesystem(pathname): applist.append(pathname) return applist
def end(self): if self.ended: return self.sessionController.log_debug(u"End %s" % self) self.ended = True NSApp.delegate().contactsWindowController.hideLocalVideoWindow() status = self.status if status in [STREAM_IDLE, STREAM_FAILED]: self.changeStatus(STREAM_IDLE) elif status == STREAM_PROPOSING: self.sessionController.cancelProposal(self.stream) self.changeStatus(STREAM_CANCELLING) else: self.sessionController.endStream(self) self.changeStatus(STREAM_IDLE) self.removeFromSession() self.videoWindowController.close() self.notification_center.discard_observer(self, sender=self.sessionController) dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(5.0, self, "deallocTimer:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(dealloc_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_(dealloc_timer, NSEventTrackingRunLoopMode)
def notify(title, subtitle, text, bundleid=None, url=None): if bundleid: # fake our bundleid set_fake_bundleid(bundleid) # create a new user notification notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(text) if url: userInfo = NSDictionary.dictionaryWithDictionary_({ 'action': u'open_url', 'value': unicode(url) }) notification.setUserInfo_(userInfo) notification.setHasActionButton_(True) notification.setActionButtonTitle_('Details') # get the default User Notification Center nc = NSUserNotificationCenter.defaultUserNotificationCenter() # create a delegate object that implements our delegate methods my_delegate = NotificationCenterDelegate.alloc().init() nc.setDelegate_(my_delegate) nc.removeAllDeliveredNotifications() # deliver the notification nc.deliverNotification_(notification) # keep running until the notification is activated while (my_delegate.keepRunning): NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.1))
def get_apps(): # credit to the Munki project for borrowing code, thanks Munki! apps_dict = {} query = NSMetadataQuery.alloc().init() query.setPredicate_( NSPredicate.predicateWithFormat_( "(kMDItemContentType = 'com.apple.application-bundle')")) query.setSearchScopes_(['/Applications']) query.startQuery() start_time = 0 max_time = 20 while query.isGathering() and start_time <= max_time: start_time += 0.3 NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.3)) query.stopQuery() # check if the app returns a None value for this query, some apps may have embedded Applescripts # that will return a None value and will be set to blank for app in query.results(): name = app.valueForAttribute_('kMDItemDisplayName') if name: version = app.valueForAttribute_('kMDItemVersion') or '' apps_dict[name] = version return apps_dict
def notify(title, subtitle, text, bundleid=None): if bundleid: # fake our bundleid set_fake_bundleid(bundleid) # create a new user notification notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(text) # get the default User Notification Center nc = NSUserNotificationCenter.defaultUserNotificationCenter() # create a delegate object that implements our delegate methods my_delegate = NotificationCenterDelegate.alloc().init() nc.setDelegate_(my_delegate) # deliver the notification nc.deliverNotification_(notification) # keep running until the notification is activated while (my_delegate.keepRunning): NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.1))
def applicationDidFinishLaunching_(self, notification): self.noDevice = None #Create menu self.menu = NSMenu.alloc().init() self.barItem = dict() # Load images self.noDeviceImage = NSImage.alloc().initByReferencingFile_('icons/no_device.png') self.barImage = dict(kb = NSImage.alloc().initByReferencingFile_('icons/kb.png'), magicMouse = NSImage.alloc().initByReferencingFile_('icons/magic_mouse.png'), mightyMouse = NSImage.alloc().initByReferencingFile_('icons/mighty_mouse.png'), magicTrackpad = NSImage.alloc().initByReferencingFile_('icons/TrackpadIcon.png')) #Define menu items self.statusbar = NSStatusBar.systemStatusBar() self.menuAbout = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('About BtBatStat', 'about:', '') self.separator_menu_item = NSMenuItem.separatorItem() self.menuQuit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') # Get the timer going self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 10.0, self, 'tick:', None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) self.timer.fire() #Add menu items self.menu.addItem_(self.menuAbout) self.menu.addItem_(self.separator_menu_item) self.menu.addItem_(self.menuQuit) #Check for updates checkForUpdates()
def find_apps_in_dirs(dirlist): """Do spotlight search for type applications within the list of directories provided. Returns a list of paths to applications these appear to always be some form of unicode string. """ applist = [] query = NSMetadataQuery.alloc().init() query.setPredicate_( NSPredicate.predicateWithFormat_('(kMDItemKind = "Application")')) query.setSearchScopes_(dirlist) query.startQuery() # Spotlight isGathering phase - this is the initial search. After the # isGathering phase Spotlight keeps running returning live results from # filesystem changes, we are not interested in that phase. # Run for 0.3 seconds then check if isGathering has completed. runtime = 0 maxruntime = 20 while query.isGathering() and runtime <= maxruntime: runtime += 0.3 NSRunLoop.currentRunLoop( ).runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.3)) query.stopQuery() if runtime >= maxruntime: display.display_warning( 'Spotlight search for applications terminated due to excessive ' 'time. Possible causes: Spotlight indexing is turned off for a ' 'volume; Spotlight is reindexing a volume.') for item in query.results(): pathname = item.valueForAttribute_('kMDItemPath') if pathname and not is_excluded_filesystem(pathname): applist.append(pathname) return applist
def __init__(self, callback, interval): self.set_callback(callback) self._nsdate = NSDate.date() self._nstimer = NSTimer.alloc( ).initWithFireDate_interval_target_selector_userInfo_repeats_( self._nsdate, interval, self, 'callback:', None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self._nstimer, NSDefaultRunLoopMode)
def start(self): if not self._status: self._nsdate = NSDate.date() self._nstimer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_( self._nsdate, self._interval, self, 'callback:', None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self._nstimer, NSDefaultRunLoopMode) _TIMERS.add(self) self._status = True
def awakeFromNib(self): NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "contactSelectionChanged:", NSTableViewSelectionDidChangeNotification, self.contactTable) timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1, self, "refreshContactsTimer:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSModalPanelRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSDefaultRunLoopMode) self.contactTable.setDoubleAction_("doubleClick:")
def awakeFromNib(self): NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "contactSelectionChanged:", NSTableViewSelectionDidChangeNotification, self.contactTable) timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(0.3, self, "refreshContactsTimer:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSModalPanelRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSDefaultRunLoopMode) self.contactTable.setDoubleAction_("doubleClick:")
def startDeallocTimer(self): # workaround to keep the object alive as cocoa still sends delegate tableview messages after close self.dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( 2.0, self, "deallocTimer:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(self.dealloc_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_( self.dealloc_timer, NSEventTrackingRunLoopMode)
def isDone(self): '''Check if the connection request is complete. As a side effect, allow the delegates to work by letting the run loop run for a bit''' if self.done: return self.done # let the delegates do their thing NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(.1)) return self.done
def start_auto_close_timer(self): if not self.close_timer: # auto-close everything in 5s self.close_timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 5, self, "closeWindows:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_( self.close_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_( self.close_timer, NSEventTrackingRunLoopMode)
def enableAutoAnswer(self, view, session, delay=30): if session not in self.autoAnswerTimers: label = view.viewWithTag_(15) info = dict(delay = delay, session = session, label = label, time = time.time()) timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "timerTickAutoAnswer:", info, True) NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSEventTrackingRunLoopMode) self.autoAnswerTimers[session] = timer self.timerTickAutoAnswer_(timer) label.setHidden_(False)
def __init__(self, image): NSBundle.loadNibNamed_owner_("ScreensharingPreviewPanel", self) self.view.setImage_(image) self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( 5.0, self, "closeTimer:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) self.window.orderFront_(None)
def do_it(): delegate = BluetoothDelegate.alloc().init() manager = CBCentralManager.alloc().initWithDelegate_queue_(delegate, None) manager.scanForPeripheralsWithServices_options_(None, None) while True: try: NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.5)) except (KeyboardInterrupt, SystemExit): break
def _finish(self): self.smp_running = False self.finished = True self.secretText.setEnabled_(False) self.questionText.setEnabled_(False) self.progressBar.setDoubleValue_(9) self.continueButton.setEnabled_(True) self.continueButton.setTitle_('Finish') self.cancelButton.setHidden_(True) self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(5, self, "verificationFinished:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSRunLoopCommonModes)
def _NH_SIPApplicationDidStart(self, notification): settings = SIPSimpleSettings() if settings.presence_state.timestamp is None: settings.presence_state.timestamp = ISOTimestamp.now() settings.save() self.get_location([account for account in AccountManager().iter_accounts() if account is not BonjourAccount()]) self.publish() idle_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "updateIdleTimer:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(idle_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_(idle_timer, NSEventTrackingRunLoopMode)
def __init__(self, start_val, end_val, k, damp, duration, update_period, value_cb, done_cb): self.last_time = self.start_time = time.time() self.start_val = self.cur_val = start_val self.end_val = end_val self.cur_velocity = 0 self.damp = damp self.k = k self.duration = duration self.value_cb = value_cb self.done_cb = done_cb self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(update_period, self, selector(self.period, signature='v@:'), None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSEventTrackingRunLoopMode)
def initWithStartVal_endVal_duration_interval_valueCb_doneCb_(self, start_val, end_val, duration, update_period, value_callback, done_callback): self = super(LinearAnimator, self).init() if not self: return self.start_time = time.time() self.duration = duration self.end_val = end_val self.start_val = start_val self.value_callback = value_callback self.done_callback = done_callback self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(update_period, self, 'period:', None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSEventTrackingRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
def start(self): notification_center = NotificationCenter() notification_center.add_observer(self, name="BlinkFileTransferDidEnd") notification_center.add_observer(self, name="AudioStreamDidChangeHoldState") notification_center.add_observer(self, name="CFGSettingsObjectDidChange") notification_center.add_observer(self, name="ChatViewControllerDidDisplayMessage") notification_center.add_observer(self, name="ConferenceHasAddedAudio") notification_center.add_observer(self, name="BlinkWillCancelProposal") self.cleanupTimer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(3, self, "cleanupTimer:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.cleanupTimer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_(self.cleanupTimer, NSEventTrackingRunLoopMode) self.started = True
def finishLaunching(self): self._setup_menuBar() # Create a timer which fires the update_ method every 1second, # and add it to the runloop NSRunLoop.currentRunLoop().addTimer_forMode_( NSTimer. scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 1, self, 'update:', '', True), NSEventTrackingRunLoopMode) print('Simon is now running.') print('CTRL+C does not work here.') print('You can quit through the menubar (Simon -> Quit).')
def finishLaunching(self): """Setup the menu and run the app loop.""" self._setup_menu_bar() # Create a timer which fires the update_ method every 1second, # and add it to the runloop NSRunLoop.currentRunLoop().addTimer_forMode_( NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1, self, "update:", "", True), NSEventTrackingRunLoopMode, ) print("Sentinel is now running.") print("CTRL+C does not work here.") print("You can quit through the menu bar (Sentinel -> Quit).")
def _finish(self, result=False): self.finished = True self.smp_running = False self.requested_by_remote = False self.secretText.setEnabled_(False) self.questionText.setEnabled_(False) self.progressBar.setDoubleValue_(9) self.continueButton.setEnabled_(False) self.continueButton.setTitle_(NSLocalizedString("Finish", "Button Title")) self.cancelButton.setHidden_(True) self.continueButton.setEnabled_(True) wait_interval = 5 if result else 10 self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(wait_interval, self, "verificationFinished:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSRunLoopCommonModes)
def _NH_MediaStreamDidStart(self, sender, data): super(VideoController, self)._NH_MediaStreamDidStart(sender, data) self.started = True sample_rate = self.stream.clock_rate/1000 codec = beautify_video_codec(self.stream.codec) self.sessionController.log_info("Video stream established to %s:%s using %s %0.fkHz codec" % (self.stream.remote_rtp_address, self.stream.remote_rtp_port, codec, sample_rate)) self.videoWindowController.show() self.changeStatus(STREAM_CONNECTED) if self.sessionController.hasStreamOfType("chat") and self.videoWindowController.always_on_top: self.videoWindowController.toogleAlwaysOnTop() self.statistics_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(STATISTICS_INTERVAL, self, "updateStatisticsTimer:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.statistics_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_(self.statistics_timer, NSEventTrackingRunLoopMode)
def runConsoleEventLoop(argv=None, installInterrupt=False, mode=NSDefaultRunLoopMode, maxTimeout=3.0): if argv is None: argv = sys.argv if installInterrupt: installMachInterrupt() runLoop = NSRunLoop.currentRunLoop() stopper = PyObjCAppHelperRunLoopStopper.alloc().init() PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_( stopper, runLoop) try: while stopper.shouldRun(): nextfire = runLoop.limitDateForMode_(mode) if not stopper.shouldRun(): break soon = NSDate.dateWithTimeIntervalSinceNow_(maxTimeout) if nextfire is not None: nextfire = soon.earlierDate_(nextfire) if not runLoop.runMode_beforeDate_(mode, nextfire): stopper.stop() finally: PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
def apple_music_loop(): AppleMusicHandler(command=on_song_detected) while True: loop = NSRunLoop.currentRunLoop() loop.run() if not run_thread: break
def enableAnsweringMachine(self, view, session, run_now=False): try: timer = self.answeringMachineTimers[session] except KeyError: settings = SIPSimpleSettings() amLabel = view.viewWithTag_(15) delay = 0 if run_now else settings.answering_machine.answer_delay info = dict(delay = delay, session = session, label = amLabel, time = time.time()) timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "timerTickAnsweringMachine:", info, True) NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSEventTrackingRunLoopMode) self.answeringMachineTimers[session] = timer self.timerTickAnsweringMachine_(timer) amLabel.setHidden_(False) else: if run_now: self.acceptAudioStreamAnsweringMachine(session)
def findDomains(serviceName, seconds=5.0): runloop = NSRunLoop.currentRunLoop() browser = NSNetServiceBrowser.new() pbd = PrintingBrowserDelegate.new() browser.setDelegate_(pbd) browser.searchForServicesOfType_inDomain_(serviceName, "") untilWhen = NSDate.dateWithTimeIntervalSinceNow_(seconds) runloop.runUntilDate_(untilWhen)
def __init__(self): self.main_loop = asyncio.get_event_loop() self.main_loop.create_task(self._handle_nsrunloop()) self.main_loop.create_task(self._central_manager_delegate_ready()) self.nsrunloop = NSRunLoop.currentRunLoop() self.central_manager_delegate = CentralManagerDelegate.alloc().init()
def end(self): if self.ended: return self.sessionController.log_debug("End %s" % self) self.ended = True if self.sessionController.waitingForLocalVideo: self.stop_wait_for_camera_timer() self.sessionController.cancelBeforeDNSLookup() if self.sessionController.video_consumer == "audio": NSApp.delegate().contactsWindowController.detachVideo( self.sessionController) elif self.sessionController.video_consumer == "chat": NSApp.delegate().chatWindowController.detachVideo( self.sessionController) status = self.status if status in [STREAM_IDLE, STREAM_FAILED]: self.changeStatus(STREAM_IDLE) elif status == STREAM_PROPOSING: self.sessionController.cancelProposal(self) self.changeStatus(STREAM_CANCELLING) else: self.sessionController.endStream(self) self.changeStatus(STREAM_IDLE) self.removeFromSession() self.videoRecorder.stop() self.videoWindowController.close() self.notification_center.remove_observer( self, sender=self.sessionController, name='VideoRemovedByRemoteParty') dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( 5.0, self, "deallocTimer:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(dealloc_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_( dealloc_timer, NSEventTrackingRunLoopMode)
def captureButtonClicked_(self, sender): if self.countdownCheckbox.state() == NSOnState: self.countdown_counter = 10 self.previewButton.setHidden_(True) self.captureButton.setHidden_(True) self.countdownCheckbox.setHidden_(True) self.countdownProgress.setHidden_(False) self.countdownProgress.startAnimation_(None) self.countdownProgress.setIndeterminate_(False) self.countdownProgress.setDoubleValue_(self.countdown_counter) self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1, self, "executeTimerCapture:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) else: self.countdownCheckbox.setHidden_(True) self.countdownProgress.setHidden_(True) self.executeCapture()
def applicationDidFinishLaunching_(self, notification): global start_time statusbar = NSStatusBar.systemStatusBar() # Create the statusbar item self.statusitem = statusbar.statusItemWithLength_(70.0) # Set initial image self.statusitem.setTitle_(self.updateGeektime()) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) self.menu = NSMenu.alloc().init() menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') self.menu.addItem_(menuitem) self.statusitem.setMenu_(self.menu) self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 0.65, self, 'tick:', None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) self.timer.fire()
def _NH_MediaStreamDidStart(self, sender, data): self.started = True sample_rate = self.stream.sample_rate / 1000 codec = beautify_video_codec(self.stream.codec) self.sessionController.log_info( "Video stream established to %s:%s using %s codec" % (self.stream.remote_rtp_address, self.stream.remote_rtp_port, codec)) self.changeStatus(STREAM_CONNECTED) self.sessionController.setVideoConsumer( self.sessionController.video_consumer) self.statistics_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( STATISTICS_INTERVAL, self, "updateStatisticsTimer:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.statistics_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_( self.statistics_timer, NSEventTrackingRunLoopMode)
class ReverseLookup(object): def myCompletionHandler(placemarks, error): if error is not None: print error else: print placemarks # Convert coordinates to address geocoder = CLGeocoder.alloc().init() geocoder.reverseGeocodeLocation_completionHandler_(location, myCompletionHandler) NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(1)) # Convert street address into coordinates geocoder.geocodeAddressString_completionHandler_(address, myCompletionHandler) NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(1))
def __init__(self, owner): BlinkLogger().log_debug('Starting Ringtone Manager') self.owner = owner notification_center = NotificationCenter() notification_center.add_observer(self, name="BlinkFileTransferDidEnd") notification_center.add_observer(self, name="RTPStreamDidChangeHoldState") notification_center.add_observer(self, name="CFGSettingsObjectDidChange") notification_center.add_observer( self, name="ChatViewControllerDidDisplayMessage") notification_center.add_observer(self, name="ConferenceHasAddedAudio") notification_center.add_observer(self, name="BlinkWillCancelProposal") self.cleanupTimer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( 3, self, "cleanupTimer:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.cleanupTimer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_( self.cleanupTimer, NSEventTrackingRunLoopMode) self.update_ringtones()
def startOutgoing(self, is_update): if self.videoWindowController: self.videoWindowController.initLocalVideoWindow() self.ended = False self.notification_center.add_observer(self, sender=self.stream) self.notification_center.add_observer(self, sender=self.sessionController) self.notification_center.add_observer(self, sender=self.sessionController, name='VideoRemovedByRemoteParty') if is_update and self.sessionController.canProposeMediaStreamChanges(): self.changeStatus(STREAM_PROPOSING) else: self.changeStatus(STREAM_WAITING_DNS_LOOKUP) self.wait_for_camera_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( 5.0, self, "localVideoReadyTimer:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_( self.wait_for_camera_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_( self.wait_for_camera_timer, NSEventTrackingRunLoopMode)
def __init__(self, sessionController): self.notification_center = NotificationCenter() self.sessionController = None self.audio_stream = None self.chat_stream = None self.add_session(sessionController) self.add_audio_stream() self.add_chat_stream() self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "updateTimer:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) NSBundle.loadNibNamed_owner_("SessionInfoPanel", self) sessionBoxTitle = NSAttributedString.alloc().initWithString_attributes_("SIP Session", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName)) self.sessionBox.setTitle_(sessionBoxTitle) audioBoxTitle = NSAttributedString.alloc().initWithString_attributes_("Audio Stream", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName)) self.audioBox.setTitle_(audioBoxTitle) chatBoxTitle = NSAttributedString.alloc().initWithString_attributes_("Chat Stream", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName)) self.chatBox.setTitle_(chatBoxTitle) self.audio_rtt_graph.setLineWidth_(1.0) self.audio_rtt_graph.setLineSpacing_(1.0) self.audio_rtt_graph.setAboveLimit_(200) # if higher than 200 ms show red color self.audio_rtt_graph.setMinimumHeigth_(200) self.audio_packet_loss_graph.setLineWidth_(1.0) self.audio_packet_loss_graph.setLineSpacing_(1.0) self.audio_packet_loss_graph.setAboveLimit_(3) # if higher than 3% show red color self.audio_packet_loss_graph.setLineColor_(NSColor.greenColor()) self.audio_packet_loss_graph.setMinimumHeigth_(5) self.resetSession() self.updatePanelValues()
def start(self): self.stop() #ns_timer = \ # NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( # self._interval, self._target, '_ns_fire', None, self._repeat) ns_timer = \ NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( self._interval, trigger, 'fire:', None, self._repeat) self._ns_timer = ns_timer ns_timer_to_task[ns_timer] = self ns_run_loop = NSRunLoop.currentRunLoop() ns_run_loop.addTimer_forMode_(ns_timer, NSDefaultRunLoopMode) ns_run_loop.addTimer_forMode_(ns_timer, NSEventTrackingRunLoopMode) ns_run_loop.addTimer_forMode_(ns_timer, NSModalPanelRunLoopMode)
def captureButtonClicked_(self, sender): if self.countdownCheckbox.state() == NSOnState: self.countdown_counter = 5 self.previewButton.setHidden_(True) self.captureButton.setHidden_(True) self.countdownCheckbox.setHidden_(True) self.mirrorButton.setHidden_(True) self.countdownProgress.setHidden_(False) self.countdownProgress.startAnimation_(None) self.countdownProgress.setIndeterminate_(False) self.countdownProgress.setDoubleValue_(self.countdown_counter) self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( 1, self, "executeTimerCapture:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_( self.timer, NSModalPanelRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_( self.timer, NSDefaultRunLoopMode) else: self.countdownCheckbox.setHidden_(True) self.mirrorButton.setHidden_(True) self.countdownProgress.setHidden_(True) self.executeCapture()
def start(self): self.stop() #ns_timer = \ # NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( # self._interval, self._target, '_ns_fire', None, self._repeat) ns_timer = \ NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_( self._interval, trigger, 'fire:', None, self._repeat) self._ns_timer = ns_timer ns_timer_to_task[ns_timer] = self ns_run_loop = NSRunLoop.currentRunLoop() ns_run_loop.addTimer_forMode_( ns_timer, NSDefaultRunLoopMode) ns_run_loop.addTimer_forMode_( ns_timer, NSEventTrackingRunLoopMode) ns_run_loop.addTimer_forMode_( ns_timer, NSModalPanelRunLoopMode)
def runConsoleEventLoop(argv=None, installInterrupt=False, mode=NSDefaultRunLoopMode): if argv is None: argv = sys.argv if installInterrupt: installMachInterrupt() runLoop = NSRunLoop.currentRunLoop() stopper = PyObjCAppHelperRunLoopStopper.alloc().init() PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop) try: while stopper.shouldRun(): nextfire = runLoop.limitDateForMode_(mode) if not stopper.shouldRun(): break if not runLoop.runMode_beforeDate_(mode, nextfire): stopper.stop() finally: PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
def __init__(self): ds = SCDynamicStoreCreate(None, "foo", self.callback, self) self.delegate = SCDelegate.alloc().init() # ds.setDelegate_(self.delegate) # ds.addToCurrentRunLoop() self.runloop = NSRunLoop.currentRunLoop() dnspattern = u"State:/Network/global/DNS" pattern = r'State:/Network/Global/IPv[46]' # keys = list(ds.keyListForPattern_(pattern)) # keys.extend(list(ds.keyListForPattern_(dnspattern))) # ds.notifyValuesForKeys_matchingPatterns_(None, [pattern, dnspattern]) keys = [] keys.append(dnspattern) keys.append(pattern) SCDynamicStoreSetNotificationKeys(ds, None, keys) # self.delegate.keysChanged_inDynamicStore_(keys, ds) for key in keys: print "Watching key " + str(key) self.ds = ds
def search(path, searchValue): ''' List records that match the given query. ''' node = _get_node(path) if not node: log.error('Query not possible, cannot get reference to node at path: {}'.format(path)) return None # @objc.callbackFor("CFOpenDirectory.ODQuerySetCallback") # def query_callback(query, value, context, error, info): # log.warning('got callback') # pass query, err = ODQuery.queryWithNode_forRecordTypes_attribute_matchType_queryValues_returnAttributes_maximumResults_error_( node, kODRecordTypeUsers, kODAttributeTypeRecordName, kODMatchContains, searchValue, kODAttributeTypeStandardOnly, 0, None ) if err: log.error('Failed to construct query: {}'.format(err)) return None ODQueryDelegate = objc.protocolNamed('ODQueryDelegate') class QueryDelegate(NSObject, ODQueryDelegate): def query_foundResults_error_(self, inQuery, inResults, inError): log.error('FOUND RESULTS') qd = QueryDelegate() query.setDelegate_(qd) query.scheduleInRunLoop_forMode_(NSRunLoop.currentRunLoop(), NSDefaultRunLoopMode)
def wait(time): from Foundation import NSDate from Foundation import NSRunLoop NSRunLoop.mainRunLoop().runBeforeDate_(NSDate.dateWithTimeIntervalSinceNow_(time))
def startDeallocTimer(self): # workaround to keep the object alive as cocoa still sends delegate tableview messages after close self.dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(2.0, self, "deallocTimer:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(self.dealloc_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_(self.dealloc_timer, NSEventTrackingRunLoopMode)
def loop(): from Foundation import NSRunLoop NSRunLoop.mainRunLoop().run()
def startSpeechSynthesizerTimer(self): self.speech_synthesizer_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(2, self, "startSpeaking:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(self.speech_synthesizer_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_(self.speech_synthesizer_timer, NSEventTrackingRunLoopMode)
def runEventLoop(argv=None, unexpectedErrorAlert=None, installInterrupt=None, pdb=None, main=NSApplicationMain): """Run the event loop, ask the user if we should continue if an exception is caught. Use this function instead of NSApplicationMain(). """ if argv is None: argv = sys.argv if pdb is None: pdb = 'USE_PDB' in os.environ if pdb: from PyObjCTools import Debugging Debugging.installVerboseExceptionHandler() # bring it to the front, starting from terminal # often won't activator = PyObjCAppHelperApplicationActivator.alloc().init() NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( activator, 'activateNow:', NSApplicationDidFinishLaunchingNotification, None, ) else: Debugging = None if installInterrupt is None and pdb: installInterrupt = True if unexpectedErrorAlert is None: if pdb: unexpectedErrorAlert = unexpectedErrorAlertPdb else: unexpectedErrorAlert = unexpectedErrorAlertPanel runLoop = NSRunLoop.currentRunLoop() stopper = PyObjCAppHelperRunLoopStopper.alloc().init() PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop) firstRun = NSApp() is None try: while stopper.shouldRun(): try: if firstRun: firstRun = False if installInterrupt: installMachInterrupt() main(argv) else: NSApp().run() except RAISETHESE: traceback.print_exc() break except: exctype, e, tb = sys.exc_info() objc_exception = False if isinstance(e, objc.error): NSLog("%@", unicode(str(e), 'utf-8', 'replace')) elif not unexpectedErrorAlert(): NSLog("%@", "An exception has occured:") traceback.print_exc() sys.exit(0) else: NSLog("%@", "An exception has occured:") traceback.print_exc() else: break finally: if Debugging is not None: Debugging.removeExceptionHandler() PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
def getRunLoop(self, runLoop=None): if self.runLoop is None: self.nsRunLoop = runLoop or NSRunLoop.currentRunLoop() self.runLoop = cf.PyCFRunLoop(self.nsRunLoop.getCFRunLoop()) return self.runLoop
def currentRunLoopStopper(cls): runLoop = NSRunLoop.currentRunLoop() return cls.singletons.get(runLoop)