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 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 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 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 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, 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 gotIsComposing(self, window, state, refresh, last_active): self.enableIsComposing = True flag = state == "active" if flag: if refresh is None: refresh = 120 if last_active is not None and ( last_active - ISOTimestamp.now() > datetime.timedelta(seconds=refresh)): # message is old, discard it return if self.remoteTypingTimer: # if we don't get any indications in the request refresh, then we assume remote to be idle self.remoteTypingTimer.setFireDate_( NSDate.dateWithTimeIntervalSinceNow_(refresh)) else: self.remoteTypingTimer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( refresh, self, "remoteBecameIdle:", window, False) else: if self.remoteTypingTimer: self.remoteTypingTimer.invalidate() self.remoteTypingTimer = None window.noteView_isComposing_(self, flag)
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 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 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 looponce(): app = NSApplication.sharedApplication() # to push the run loops I seem to have to do this twice # use NSEventTrackingRunLoopMode or NSDefaultRunLoopMode? for i in range(2): event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_(0.02), NSDefaultRunLoopMode, False)
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 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 looponce(): app = NSApplication.sharedApplication() # to push the run loops I seem to have to do this twice # use NSEventTrackingRunLoopMode or NSDefaultRunLoopMode? for i in range(2): event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_(0.02), NSDefaultRunLoopMode, False)
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 set(self, value): """ Set the value of the progress bar to **value**. *Only available in determinate progress bars.* """ self._nsObject.setDoubleValue_(value) self._nsObject.display() if osVersionCurrent >= osVersion10_11: NSRunLoop.mainRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.0001))
def increment(self, value=1): """ Increment the progress bar by **value**. *Only available in determinate progress bars.* """ self._nsObject.incrementBy_(value) self._nsObject.display() if osVersionCurrent >= osVersion10_11: NSRunLoop.mainRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.0001))
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 set(self, value): """ Set the value of the progress bar to **value**. *Only available in determinate progress bars.* """ self._nsObject.setDoubleValue_(value) self._nsObject.display() if osVersionCurrent >= osVersion10_11: NSRunLoop.mainRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.0001))
def increment(self, value=1): """ Increment the progress bar by **value**. *Only available in determinate progress bars.* """ self._nsObject.incrementBy_(value) self._nsObject.display() if osVersionCurrent >= osVersion10_11: NSRunLoop.mainRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.0001))
def looponce(): app = NSApplication.sharedApplication() # It is very likely that this code will run in a separate python thread. # An autoreleasepool won't be created automatically for us, so do so "manually" to avoid leaking. # http://www.opensource.apple.com/source/pyobjc/pyobjc-14/pyobjc/stable/pyobjc-core/Doc/api-notes-macosx.txt pool = NSAutoreleasePool.alloc().init() # to push the run loops I seem to have to do this twice # use NSEventTrackingRunLoopMode or NSDefaultRunLoopMode? for i in range(2): event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_(0.02), NSDefaultRunLoopMode, False) del pool
def looponce(): app = NSApplication.sharedApplication() # It is very likely that this code will run in a separate python thread. # An autoreleasepool won't be created automatically for us, so do so "manually" to avoid leaking. # http://www.opensource.apple.com/source/pyobjc/pyobjc-14/pyobjc/stable/pyobjc-core/Doc/api-notes-macosx.txt pool = NSAutoreleasePool.alloc().init() # to push the run loops I seem to have to do this twice # use NSEventTrackingRunLoopMode or NSDefaultRunLoopMode? for i in range(2): event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_(0.02), NSDefaultRunLoopMode, False) del pool
def textDidChange_(self, notification): self.lastTypedTime = datetime.datetime.now() if self.inputText.textStorage().length() == 0: self.becameIdle_(None) else: if not self.lastTypeNotifyTime or time.time() - self.lastTypeNotifyTime > TYPING_NOTIFY_INTERVAL: self.lastTypeNotifyTime = time.time() self.delegate.chatView_becameActive_(self, self.lastTypedTime) if self.typingTimer: # delay the timeout a bit more self.typingTimer.setFireDate_(NSDate.dateWithTimeIntervalSinceNow_(TYPING_IDLE_TIMEOUT)) else: self.typingTimer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(TYPING_IDLE_TIMEOUT, self, "becameIdle:", None, False)
def _send_message(self, event_type, *arguments): if not self._port: self._connect_port() message_type = bytearray([event_type]) message_args = [ NSString.stringWithString_(arg).dataUsingEncoding_(NSUTF16StringEncoding) for arg in arguments ] components = [message_type] + message_args try: message = NSPortMessage.alloc().initWithSendPort_receivePort_components_(self._port, None, components) if not message.sendBeforeDate_(NSDate.dateWithTimeIntervalSinceNow_(self.EVENT_TIMEOUT)): raise Exception('Failed to send the port message.') except Exception: TRACE('Mach port became invalid.') self._port = None raise
def notify(self, title='', subtitle='', message='', data=None, sound='NSUserNotificationDefaultSoundName', after=0, repeat={}): """Send a notification to Notification Center (Mac OS X 10.8+). If running on a version of Mac OS X that does not support notifications, a ``RuntimeError`` will be raised. Apple says, "The userInfo content must be of reasonable serialized size (less than 1k) or an exception will be thrown." So don't do that! :param title: text in a larger font. :param subtitle: text in a smaller font below the `title`. :param message: text representing the body of the notification below the `subtitle`. :param data: will be passed to the application's "notification center" (see :func:`rumps.notifications`) when this notification is clicked. :param sound: whether the notification should make a noise when it arrives. :param after: number of seconds to postpone the notification. :param repeat: dict of date components that specify how the notification shoul be repeated. e.g. {'hour': 1, 'minute': 30} """ after = max(after, 0) if not _NOTIFICATIONS: raise RuntimeError('Mac OS X 10.8+ is required to send notifications') if data is not None and not isinstance(data, Mapping): raise TypeError('notification data must be a mapping') _require_string_or_none(title, subtitle, message, sound) notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(message) notification.setUserInfo_(data or {}) if sound: notification.setSoundName_(sound) if after: notification.setDeliveryDate_(NSDate.dateWithTimeIntervalSinceNow_(after)) if repeat: deliveryRepeatInterval = NSDateComponents.alloc().init() for k, v in repeat.items(): kvc.setKey(deliveryRepeatInterval, k, v) notification.setDeliveryRepeatInterval_(deliveryRepeatInterval) self.defaultNotificationCenter.scheduleNotification_(notification) return notification
def thereAreUpdatesToBeForcedSoon(hours=72): '''Return True if any updates need to be installed within the next X hours, false otherwise''' installinfo = getInstallInfo() if installinfo: now = NSDate.date() now_xhours = NSDate.dateWithTimeIntervalSinceNow_(hours * 3600) for item in installinfo.get('managed_installs', []): force_install_after_date = item.get('force_install_after_date') if force_install_after_date: force_install_after_date = discardTimeZoneFromDate( force_install_after_date) if now_xhours >= force_install_after_date: return True return False
def thereAreUpdatesToBeForcedSoon(hours=72): '''Return True if any updates need to be installed within the next X hours, false otherwise''' installinfo = getInstallInfo() if installinfo: now = NSDate.date() now_xhours = NSDate.dateWithTimeIntervalSinceNow_(hours * 3600) for item in installinfo.get('managed_installs', []): force_install_after_date = item.get('force_install_after_date') if force_install_after_date: force_install_after_date = discardTimeZoneFromDate( force_install_after_date) if now_xhours >= force_install_after_date: return True return False
def textDidChange_(self, notification): self.lastTypedTime = datetime.datetime.now() if self.inputText.textStorage().length() == 0: self.becameIdle_(None) else: if not self.lastTypeNotifyTime or time.time( ) - self.lastTypeNotifyTime > TYPING_NOTIFY_INTERVAL: self.lastTypeNotifyTime = time.time() self.delegate.chatView_becameActive_(self, self.lastTypedTime) if self.typingTimer: # delay the timeout a bit more self.typingTimer.setFireDate_( NSDate.dateWithTimeIntervalSinceNow_(TYPING_IDLE_TIMEOUT)) else: self.typingTimer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( TYPING_IDLE_TIMEOUT, self, "becameIdle:", None, False)
def waituntil(conditionfunc, timeout=None): """ Waits until conditionfunc() returns true, or <timeout> seconds have passed. (If timeout=None, this waits indefinitely until conditionfunc() returns true.) Returns false if the process timed out, otherwise returns true. Note!! You must call interruptwait() when you know that conditionfunc() should be checked (e.g. if you are waiting for data and you know some data has arrived) so that this can check conditionfunc(); otherwise it will just continue to wait. (This allows the function to wait for an event that is sent by interruptwait() instead of polling conditionfunc().) This allows the caller to wait while the main event loop processes its events. This must be done for certain situations, e.g. to receive socket data or to accept client connections on a server socket, since IOBluetooth requires the presence of an event loop to run these operations. This function doesn't need to be called if there is something else that is already processing the main event loop, e.g. if called from within a Cocoa application. """ app = NSApplication.sharedApplication() starttime = time.time() if timeout is None: timeout = NSDate.distantFuture().timeIntervalSinceNow() if not isinstance(timeout, (int, float)): raise TypeError("timeout must be int or float, was %s" % \ type(timeout)) endtime = starttime + timeout while True: currtime = time.time() if currtime >= endtime: return False # use WAIT_MAX_TIMEOUT, don't wait forever in case of KeyboardInterrupt e = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_( min(endtime - currtime, WAIT_MAX_TIMEOUT)), NSDefaultRunLoopMode, True) if e is not None: if (e.type() == NSApplicationDefined and e.subtype() == LIGHTBLUE_NOTIFY_ID): if conditionfunc(): return True else: app.postEvent_atStart_(e, True)
def thereAreUpdatesToBeForcedSoon(hours=72): """Return True if any updates need to be installed within the next X hours, false otherwise""" installinfo = getInstallInfo().get("managed_installs", []) installinfo.extend(getAppleUpdates().get("AppleUpdates", [])) if installinfo: now_xhours = NSDate.dateWithTimeIntervalSinceNow_(hours * 3600) for item in installinfo: force_install_after_date = item.get("force_install_after_date") if force_install_after_date: try: force_install_after_date = discardTimeZoneFromDate(force_install_after_date) if now_xhours >= force_install_after_date: return True except BadDateError: # some issue with the stored date pass return False
def thereAreUpdatesToBeForcedSoon(hours=72): '''Return True if any updates need to be installed within the next X hours, false otherwise''' installinfo = getInstallInfo().get('managed_installs', []) installinfo.extend(getAppleUpdates().get('AppleUpdates', [])) if installinfo: now_xhours = NSDate.dateWithTimeIntervalSinceNow_(hours * 3600) for item in installinfo: force_install_after_date = item.get('force_install_after_date') if force_install_after_date: try: force_install_after_date = discardTimeZoneFromDate( force_install_after_date) if now_xhours >= force_install_after_date: return True except BadDateError: # some issue with the stored date pass return False
def waituntil(conditionfunc, timeout=None): """ Waits until conditionfunc() returns true, or <timeout> seconds have passed. (If timeout=None, this waits indefinitely until conditionfunc() returns true.) Returns false if the process timed out, otherwise returns true. Note!! You must call interruptwait() when you know that conditionfunc() should be checked (e.g. if you are waiting for data and you know some data has arrived) so that this can check conditionfunc(); otherwise it will just continue to wait. (This allows the function to wait for an event that is sent by interruptwait() instead of polling conditionfunc().) This allows the caller to wait while the main event loop processes its events. This must be done for certain situations, e.g. to receive socket data or to accept client connections on a server socket, since IOBluetooth requires the presence of an event loop to run these operations. This function doesn't need to be called if there is something else that is already processing the main event loop, e.g. if called from within a Cocoa application. """ app = NSApplication.sharedApplication() starttime = time.time() if timeout is None: timeout = NSDate.distantFuture().timeIntervalSinceNow() if not isinstance(timeout, (int, float)): raise TypeError("timeout must be int or float, was %s" % \ type(timeout)) endtime = starttime + timeout while True: currtime = time.time() if currtime >= endtime: return False # use WAIT_MAX_TIMEOUT, don't wait forever in case of KeyboardInterrupt e = app.nextEventMatchingMask_untilDate_inMode_dequeue_(NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_(min(endtime - currtime, WAIT_MAX_TIMEOUT)), NSDefaultRunLoopMode, True) if e is not None: if (e.type() == NSApplicationDefined and e.subtype() == LIGHTBLUE_NOTIFY_ID): if conditionfunc(): return True else: app.postEvent_atStart_(e, True)
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) nextfire = nextfire.earlierDate_(soon) if not runLoop.runMode_beforeDate_(mode, nextfire): stopper.stop() finally: PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
def _writeString_forOutput_(self, s, name): self.textView.textStorage().appendAttributedString_(getattr(self, name + "String_")(s)) window = self.textView.window() app = NSApplication.sharedApplication() st = time.time() now = time.time if self._autoscroll: self.textView.scrollRangeToVisible_((self.lengthOfTextView(), 0)) while app.isRunning() and now() - st < 0.01: event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSUIntegerMax, NSDate.dateWithTimeIntervalSinceNow_(0.01), NSDefaultRunLoopMode, True ) if event is None: continue if (event.type() == NSKeyDown) and (event.window() == window): chr = event.charactersIgnoringModifiers() if chr == "c" and (event.modifierFlags() & NSControlKeyMask): raise KeyboardInterrupt app.sendEvent_(event)
def gotIsComposing(self, window, state, refresh, last_active): self.enableIsComposing = True flag = state == "active" if flag: if refresh is None: refresh = 120 if last_active is not None and (last_active - ISOTimestamp.now() > datetime.timedelta(seconds=refresh)): # message is old, discard it return if self.remoteTypingTimer: # if we don't get any indications in the request refresh, then we assume remote to be idle self.remoteTypingTimer.setFireDate_(NSDate.dateWithTimeIntervalSinceNow_(refresh)) else: self.remoteTypingTimer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(refresh, self, "remoteBecameIdle:", window, False) else: if self.remoteTypingTimer: self.remoteTypingTimer.invalidate() self.remoteTypingTimer = None window.noteView_isComposing_(self, flag)
def main(): finder = MyLocationManagerDelegate.alloc().init() for x in range(5): print "loop", x NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(10))
from Foundation import NSObject, NSUserDefaults, NSKeyValueObservingOptionNew from Foundation import NSRunLoop, NSDate class PrefsObserver(NSObject): def observe(self, domain, key): self.domain = domain self.key = key if self: self.defaults = NSUserDefaults.alloc().initWithSuiteName_( self.domain) self.defaults.addObserver_forKeyPath_options_context_( self, self.key, NSKeyValueObservingOptionNew, None) return self def __del__(self): self.defaults.removeObserver_forKeyPath_(self, self.key) def observeValueForKeyPath_ofObject_change_context_( self, keyPath, object, change, context): print change observer = PrefsObserver.alloc().init().observe( 'ManagedInstalls', 'LastCheckDate') while True: NSRunLoop.currentRunLoop( ).runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.3))
CurrentStatus=str("Successful"), GoogleMap=str(gmap), LastLocationRun=str(time), Latitude=str(lat), LatitudeAccuracy=int(verAcc), Longitude=str(lon), LongitudeAccuracy=int(horAcc), ) print("Successful lookup request: {0}, {1}".format( plist['Latitude'], plist['Longitude'])) def locationManager_didFailWithError_(self, manager, err): """Handlers errors for location manager.""" if self.is_enabled is True: if self.is_authorized == 3: status = "Unable to locate" if self.is_authorized == 2: status = "Denied" if self.is_authorized == 1: status = "Restricted" if self.is_authorized == 0: status = "Not Determined" else: status = "Location Services Disabled" print(status) finder = MyLocationManagerDelegate.alloc().init() NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(5))
def pr7z(self, item_dict, stak=None, depth_limit=None, verbose_level_threshold=1): """0-0 vol0006 5651 6227 Wed 2013.03.20 13:29 EDT 1 <filename>""" if self.verbose_level < verbose_level_threshold: return # from "man ls" # If the -l option is given, the following information is displayed for each file: # file mode, number of links, owner name, group name, number of bytes in the file, # abbreviated month, day-of-month file was last modified, hour file last modified, # minute file last modified, and the pathname. # assemble a list of strings to print, then " ".join() s = [] if GPR.verbose_level >= 2 and 'current_item_directory_is_being_checked' in item_dict: g = "[^]" if item_dict['current_item_directory_is_being_checked'] else "[-]" s += [g] # if RS1_db_rels is not None: # s0 = dict([(k, RS1_db_rels[k]) for k in RS1_db_rels] )# avoid self-creation # s1 = '[%s]' % "-".join([ "%d"%(len(s0[k])) if k in s0 else "*" for k in stak]) # s += [ "%-6s" % s1 ] # # # this line *creates* an entry since RS is a *default* dict and k isn't already present in RS # # s1 = '[%s]' % "-".join(["%d"%(len(RS1_db_rels[k])) for k in stak]) # # if False: # s2 = '[%s]' % "-".join(["%d"%(len(RS2_ins[k])) for k in RS2_ins]) # s1 += '+'+s2 # s += [ "%-12s" % s3 ] if 'vol_id' in item_dict: fmt = "%%-%ds" % self.vol_id_width # "%-7s" s += [ fmt % item_dict['vol_id'] ] if 'NSFileSystemFolderNumber' in item_dict: # really, if is NSDict or relation folder_id = item_dict['NSFileSystemFolderNumber'] else: folder_id = item_dict['folder_id'] file_id = item_dict['NSFileSystemFileNumber'] fmt = "%%%dd %%%dd" % (self.file_id_width , self.file_id_width) s += [ "%8d %8d" % (folder_id, file_id) ] # If the modification time of the file is more than 6 months # in the past or future, then the year of the last modification # is displayed in place of the hour and minute fields. [man ls] file_mod_date = item_dict[NSURLContentModificationDateKey] # compare: # Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date. # date_six_months_ago = NSDate.dateWithTimeIntervalSinceNow_(0- 6 * 30 * 24 *60 * 60) date_six_months_ago = NSDate.dateWithTimeIntervalSinceNow_(0- 12 * 30 * 24 *60 * 60) # one year ago if False: # ie, if doing short versions if date_six_months_ago.compare_(file_mod_date) == NSOrderedDescending: # ie, date_six_months_ago is later in time than file_mod_date format_string = self.date_format_short_early if format_string.endswith(" z"): fmt = "%3s %15s" else: fmt = "%3s %11s" else: format_string = self.date_format_short if format_string.endswith(" z"): fmt = "%3s %15s" else: fmt = "%3s %11s" # don't need to set format string for this formatter? each time through? NSDateFormatter.setDateFormat_(dateFormatters[0]['df'], format_string) sa = dateFormatters[0]['df'].stringFromDate_(file_mod_date) s += [ fmt % ( sa[0:3], sa[4:] ) ] else: # no difference for early or recent for long date format if date_six_months_ago.compare_(file_mod_date) == NSOrderedDescending: format_string = self.date_format_early fmt = "%19s" else: format_string = self.date_format fmt = "%19s" # don't need to set format string for this formatter? each time through? NSDateFormatter.setDateFormat_(dateFormatters[0]['df'], format_string) sa = dateFormatters[0]['df'].stringFromDate_(file_mod_date) s += [ fmt % ( sa, ) ] depth = item_dict['depth'] filename = item_dict[NSURLNameKey] if item_dict['NSURLIsDirectoryKey']: filename += "/" if 'directory_is_up_to_date' in item_dict: filename += ("(up-to-date)" if item_dict['directory_is_up_to_date'] else "(modified)" ) file_uti = item_dict[NSURLLocalizedTypeDescriptionKey] # NSURLTypeIdentifierKey] if len(file_uti) > self.file_uti_width: n1 = int(self.file_uti_width/2) n2 = self.file_uti_width - n1 file_uti = file_uti[:n1] + u"—" + file_uti[-n2:] fmt = "%%-%ds" % ( self.file_uti_width ) s += [ fmt % file_uti ] if depth_limit and depth >= depth_limit-1: s += [ "%2d! %-54s" % (depth, filename) ] else: s += [ "%2d %-54s" % (depth, filename) ] if GPR.verbose_level >= 2: print print " ".join(s) #print repr(s) # " ".join(s) if GPR.verbose_level >= 2: print
def wait(time): from Foundation import NSDate from Foundation import NSRunLoop NSRunLoop.mainRunLoop().runBeforeDate_(NSDate.dateWithTimeIntervalSinceNow_(time))
def continue_runloop(self): NSRunLoop.mainRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.01))
def force_install_package_check(): """Check installable packages and applicable Apple updates for force install parameters. This method modifies InstallInfo and/or AppleUpdates in one scenario: It enables the unattended_install flag on all packages which need to be force installed and do not have a RestartAction. The return value may be one of: 'now': a force install is about to occur 'soon': a force install will occur within FORCE_INSTALL_WARNING_HOURS 'logout': a force install is about to occur and requires logout 'restart': a force install is about to occur and requires restart None: no force installs are about to occur """ result = None managed_install_dir = prefs.pref('ManagedInstallDir') installinfo_types = { 'InstallInfo.plist' : 'managed_installs', 'AppleUpdates.plist': 'AppleUpdates' } now = NSDate.date() now_xhours = NSDate.dateWithTimeIntervalSinceNow_( FORCE_INSTALL_WARNING_HOURS * 3600) for installinfo_plist in installinfo_types: pl_dict = installinfo_types[installinfo_plist] installinfopath = os.path.join(managed_install_dir, installinfo_plist) try: installinfo = FoundationPlist.readPlist(installinfopath) except FoundationPlist.NSPropertyListSerializationException: continue writeback = False for i in xrange(len(installinfo.get(pl_dict, []))): install = installinfo[pl_dict][i] force_install_after_date = install.get('force_install_after_date') if not force_install_after_date: continue force_install_after_date = ( info.subtract_tzoffset_from_date(force_install_after_date)) display.display_debug1( 'Forced install for %s at %s', install['name'], force_install_after_date) if now >= force_install_after_date: result = 'now' if install.get('RestartAction'): if install['RestartAction'] == 'RequireLogout': result = 'logout' elif (install['RestartAction'] == 'RequireRestart' or install['RestartAction'] == 'RecommendRestart'): result = 'restart' elif not install.get('unattended_install', False): display.display_debug1( 'Setting unattended install for %s', install['name']) install['unattended_install'] = True installinfo[pl_dict][i] = install writeback = True if not result and now_xhours >= force_install_after_date: result = 'soon' if writeback: FoundationPlist.writePlist(installinfo, installinfopath) return result
def force_install_package_check(): """Check installable packages and applicable Apple updates for force install parameters. This method modifies InstallInfo and/or AppleUpdates in one scenario: It enables the unattended_install flag on all packages which need to be force installed and do not have a RestartAction. The return value may be one of: 'now': a force install is about to occur 'soon': a force install will occur within FORCE_INSTALL_WARNING_HOURS 'logout': a force install is about to occur and requires logout 'restart': a force install is about to occur and requires restart None: no force installs are about to occur """ result = None managed_install_dir = prefs.pref('ManagedInstallDir') installinfo_types = { 'InstallInfo.plist': 'managed_installs', 'AppleUpdates.plist': 'AppleUpdates' } now = NSDate.date() now_xhours = NSDate.dateWithTimeIntervalSinceNow_( FORCE_INSTALL_WARNING_HOURS * 3600) for installinfo_plist in installinfo_types: pl_dict = installinfo_types[installinfo_plist] installinfopath = os.path.join(managed_install_dir, installinfo_plist) try: installinfo = FoundationPlist.readPlist(installinfopath) except FoundationPlist.NSPropertyListSerializationException: continue writeback = False for i in xrange(len(installinfo.get(pl_dict, []))): install = installinfo[pl_dict][i] force_install_after_date = install.get('force_install_after_date') if not force_install_after_date: continue force_install_after_date = ( info.subtract_tzoffset_from_date(force_install_after_date)) display.display_debug1('Forced install for %s at %s', install['name'], force_install_after_date) if now >= force_install_after_date: result = 'now' if install.get('RestartAction'): if install['RestartAction'] == 'RequireLogout': result = 'logout' elif (install['RestartAction'] == 'RequireRestart' or install['RestartAction'] == 'RecommendRestart'): result = 'restart' elif not install.get('unattended_install', False): display.display_debug1('Setting unattended install for %s', install['name']) install['unattended_install'] = True installinfo[pl_dict][i] = install writeback = True if not result and now_xhours >= force_install_after_date: result = 'soon' if writeback: FoundationPlist.writePlist(installinfo, installinfopath) return result