def init(self): self = objc.super(BlinkAppDelegate, self).init() if self: self.applicationName = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleExecutable")) self.applicationNamePrint = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleName")) build = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleVersion")) date = str(NSBundle.mainBundle().infoDictionary().objectForKey_("BlinkVersionDate")) branding_file = NSBundle.mainBundle().infoDictionary().objectForKey_("BrandingFile") try: branding = __import__(branding_file) except ImportError: try: import branding except ImportError: branding = Null branding.init(self) BlinkLogger().log_info("Starting %s %s" % (self.applicationNamePrint, build)) self.registerURLHandler() NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerDidWake:", NSWorkspaceDidWakeNotification, None) NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerWillSleep:", NSWorkspaceWillSleepNotification, None) NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallTelephoneNumberWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately) NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallSipAddressWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately) NotificationCenter().add_observer(self, name="CFGSettingsObjectDidChange") NotificationCenter().add_observer(self, name="SIPApplicationDidStart") NotificationCenter().add_observer(self, name="SIPApplicationWillEnd") NotificationCenter().add_observer(self, name="SIPApplicationDidEnd") NotificationCenter().add_observer(self, name="NetworkConditionsDidChange") NotificationCenter().add_observer(self, name="SIPEngineTransportDidDisconnect") NotificationCenter().add_observer(self, name="SIPEngineTransportDidConnect") NotificationCenter().add_observer(self, name="DNSNameserversDidChange") NotificationCenter().add_observer(self, name="SystemDidWakeUpFromSleep") # remove obsolete settings userdef = NSUserDefaults.standardUserDefaults() userdef.removeObjectForKey_('SIPTrace') userdef.removeObjectForKey_('MSRPTrace') userdef.removeObjectForKey_('XCAPTrace') userdef.removeObjectForKey_('EnablePJSIPTrace') userdef.removeObjectForKey_('EnableNotificationsTrace') try: from Updater import Updater except ImportError: pass else: self.updater = Updater() self.purge_temporary_files() return self
def dealloc(self): try: NSDistributedNotificationCenter.defaultCenter().removeObserver_(self) except Exception: unhandled_exc_handler() try: NSWorkspace.sharedWorkspace().notificationCenter().removeObserver_(self) except Exception: unhandled_exc_handler() super(CameraNotifier, self).dealloc()
def act(): q = sys.argv[1:] tmp = tempfile.mkdtemp() stamp = time.strftime("%Y-%m-%d (%H.%M)") cache = alp.jsonLoad("cache.json", default={}) def do_download(address, name): r = alp.Request(address, cache=False) r.download() r.request.encoding = "utf-8" f = tempfile.NamedTemporaryFile(suffix=".alfredworkflow", dir=tmp, delete=False) f.write(r.request.content) f.close() d_path = os.path.join(os.path.expanduser("~/Downloads"), "{0} - {1}.alfredworkflow".format(stamp, name)) shutil.copy(f.name, d_path) remme = None for wf in cache["cached_workflows"]: cached_name = wf.get("name", None) if cached_name == name: remme = wf break if remme: cache["cached_workflows"].remove(remme) alp.jsonDump(cache, "cache.json") return d_path if q[0] == "update-all": to_download = q[1:] i = len(to_download) for download in to_download: name, target_path, remote = download.split(">") ret_path = do_download(remote, name) i -= 1 i_sib = "" if i == 1 else "s" n = alp.Notification() n.notify("Alleyoop", "Downloaded {0}".format(name), "{0} update{1} remaining.".format(i, i_sib)) NSDistributedNotificationCenter.defaultCenter().postNotificationName_object_("com.apple.DownloadFileFinished", ret_path) print "All updates downloaded." elif q[0] == "update": name, target_path, remote = q[1].split(">") ret_path = do_download(remote, name) NSDistributedNotificationCenter.defaultCenter().postNotificationName_object_("com.apple.DownloadFileFinished", ret_path) print "Saved {0} to Downloads".format(name) shutil.rmtree(tmp, True)
def finishLaunching(self): global http super(StreamVision, self).finishLaunching() caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, True)[0] cache = os.path.join(caches, 'StreamVision') http = httplib2.Http(OneFileCache(cache), 5) self.imagePath = os.path.join(cache, 'image') self.registerHotKey(self.requestedDisplayTrackInfo, 100) # F8 self.registerHotKey(self.showTrack, 100, cmdKey) # cmd-F8 self.registerHotKey(self.playPause, 101) # F9 self.registerHotKey(self.previousTrack, 103) # F11 self.registerHotKey(self.nextTrack, 111) # F12 self.registerHotKey(lambda: self.incrementRatingBy(-20), 103, shiftKey) # shift-F11 self.registerHotKey(lambda: self.incrementRatingBy(20), 111, shiftKey) # shift-F12 self.registerHotKey(lambda: self.adjustVolumeBy(-10), 103, cmdKey) # cmd-F11 self.registerHotKey(lambda: self.adjustVolumeBy(10), 111, cmdKey) # cmd-F12 workspaceNotificationCenter = NSWorkspace.sharedWorkspace().notificationCenter() workspaceNotificationCenter.addObserver_selector_name_object_(self, self.applicationDidActivate, NSWorkspaceDidActivateApplicationNotification, None) workspaceNotificationCenter.addObserver_selector_name_object_(self, self.screensDidSleep, NSWorkspaceScreensDidSleepNotification, None) distributedNotificationCenter = NSDistributedNotificationCenter.defaultCenter() distributedNotificationCenter.addObserver_selector_name_object_(self, self.playerInfoChanged, 'com.apple.iTunes.playerInfo', None) distributedNotificationCenter.addObserver_selector_name_object_(self, self.spotifyPlaybackStateChanged, 'com.spotify.client.PlaybackStateChanged', None) distributedNotificationCenter.addObserver_selector_name_object_(self, self.terminate_, 'com.apple.logoutContinued', None) set_default_output_device_changed_callback( self.defaultOutputDeviceChanged) turnStereoOnOrOff()
def __init__(self, command): self.command = command self.app_resource_manager = AppResourceManager() nc = NSDistributedNotificationCenter.defaultCenter() nc.addObserver_selector_name_object_(self, 'get_current_song:', 'com.apple.Music.playerInfo', None)
def init(self): self = super(CameraNotifier, self).init() if self is None: return def register(events, center): for event, selector in events.iteritems(): center.addObserver_selector_name_object_(self, selector, event, None) self._screen_handler = Handler() self.add_screen_handler = self._screen_handler.add_handler self.remove_screen_handler = self._screen_handler.remove_handler self._mount_handler = Handler() self.add_mount_handler = self._mount_handler.add_handler self.remove_mount_handler = self._mount_handler.remove_handler notifications = {'com.apple.screensaver.didstart': self.onScreenSaverStarted_, 'com.apple.screensaver.didstop': self.onScreenSaverStopped_, 'com.apple.screenIsLocked': self.onScreenLocked_, 'com.apple.screenIsUnlocked': self.onScreenUnlocked_} register(notifications, NSDistributedNotificationCenter.defaultCenter()) notifications = {'NSWorkspaceSessionDidBecomeActiveNotification': self.onFastUserSwitchEnd_, 'NSWorkspaceSessionDidResignActiveNotification': self.onFastUserSwitchStart_, 'NSWorkspaceWillUnmountNotification': self.onMountEvent_, 'NSWorkspaceDidUnmountNotification': self.onMountEvent_, 'NSWorkspaceDidMountNotification': self.onMountEvent_} register(notifications, NSWorkspace.sharedWorkspace().notificationCenter()) self._fast_user_switching = False self._screen_saver_running = False self._screen_locked = False self._screen_busy = False return self
def __init__(self, notificationName, callback): self.notificationName = notificationName self.callback = callback from Foundation import NSDistributedNotificationCenter nc = NSDistributedNotificationCenter.defaultCenter() nc.addObserver_selector_name_object_(self, 'callback:', notificationName, None)
def init(self): self = super(BlinkAppDelegate, self).init() if self: self.applicationName = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleExecutable")) self.applicationNamePrint = 'Blink' if self.applicationName == 'Blink Pro' else self.applicationName build = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleVersion")) date = str(NSBundle.mainBundle().infoDictionary().objectForKey_("BlinkVersionDate")) BlinkLogger().log_info(u"Starting %s build %s from %s" % (self.applicationNamePrint, build, date)) self.registerURLHandler() NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerDidWake:", NSWorkspaceDidWakeNotification, None) NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerWillSleep:", NSWorkspaceWillSleepNotification, None) NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallTelephoneNumberWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately) NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallSipAddressWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately) NotificationCenter().add_observer(self, name="SIPApplicationDidStart") NotificationCenter().add_observer(self, name="SIPApplicationWillEnd") NotificationCenter().add_observer(self, name="SIPApplicationDidEnd") NotificationCenter().add_observer(self, name="CFGSettingsObjectDidChange") # remove obsolete settings userdef = NSUserDefaults.standardUserDefaults() userdef.removeObjectForKey_('SIPTrace') userdef.removeObjectForKey_('MSRPTrace') userdef.removeObjectForKey_('XCAPTrace') userdef.removeObjectForKey_('EnablePJSIPTrace') userdef.removeObjectForKey_('EnableNotificationsTrace') def purge_screenshots(): screenshots_folder = ApplicationData.get('.tmp_screenshots') if os.path.exists(screenshots_folder): try: shutil.rmtree(screenshots_folder) except EnvironmentError: pass try: from Updater import Updater except ImportError: pass else: self.updater = Updater() call_in_thread('file-io', purge_screenshots) return self
def initWithNotifier_(self, npn): self = super().init() self._npn = npn logger.info('Adding observers…') dnc = NSDistributedNotificationCenter.defaultCenter() dnc.addObserver_selector_name_object_(self, 'iTunesPlaybackStateChanged:', 'com.apple.iTunes.playerInfo', None) dnc.addObserver_selector_name_object_(self, 'spotifyPlaybackStateChanged:', 'com.spotify.client.PlaybackStateChanged', None) return self
def postStatusNotification(): '''Post a status notification''' dnc = NSDistributedNotificationCenter.defaultCenter() dnc.postNotificationName_object_userInfo_options_( NOTIFICATION_ID, None, _currentStatus, NSNotificationDeliverImmediately + NSNotificationPostToAllSessions)
def init(self): self = super(BlinkAppDelegate, self).init() if self: self.applicationName = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleExecutable")) self.applicationNamePrint = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleName")) build = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleVersion")) date = str(NSBundle.mainBundle().infoDictionary().objectForKey_("BlinkVersionDate")) BlinkLogger().log_info(u"Starting %s build %s from %s" % (self.applicationNamePrint, build, date)) self.registerURLHandler() NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerDidWake:", NSWorkspaceDidWakeNotification, None) NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerWillSleep:", NSWorkspaceWillSleepNotification, None) NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallTelephoneNumberWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately) NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallSipAddressWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately) NotificationCenter().add_observer(self, name="CFGSettingsObjectDidChange") NotificationCenter().add_observer(self, name="SIPApplicationDidStart") NotificationCenter().add_observer(self, name="SIPApplicationWillEnd") NotificationCenter().add_observer(self, name="SIPApplicationDidEnd") NotificationCenter().add_observer(self, name="SystemIPAddressDidChange") NotificationCenter().add_observer(self, name="NetworkConditionsDidChange") NotificationCenter().add_observer(self, name="SIPEngineTransportDidDisconnect") NotificationCenter().add_observer(self, name="SIPEngineTransportDidConnect") NotificationCenter().add_observer(self, name="DNSNameserversDidChange") # remove obsolete settings userdef = NSUserDefaults.standardUserDefaults() userdef.removeObjectForKey_('SIPTrace') userdef.removeObjectForKey_('MSRPTrace') userdef.removeObjectForKey_('XCAPTrace') userdef.removeObjectForKey_('EnablePJSIPTrace') userdef.removeObjectForKey_('EnableNotificationsTrace') try: from Updater import Updater except ImportError: pass else: self.updater = Updater() call_in_thread('file-io', self.purge_temporary_files) return self
def _send_notification(self, name: str, content: Dict[str, Any]) -> None: """ Send a notification through the macOS notification center to the FinderSync app extension. :param name: name of the notification :param content: content to send """ nc = NSDistributedNotificationCenter.defaultCenter() nc.postNotificationName_object_userInfo_(name, None, content)
def __init__(self, message_type, text=""): """Set up NotifyingString for use. Args: message_type (str): String name appended to message identifier. text (str, optional): Used to fill the instance. Defaults to "". """ # NSDistributedNotificationCenter is the NotificationCenter # that allows messages to be sent between applications. self.notification_center = NSDistributedNotificationCenter.defaultCenter() self.send_notification(text) super(NotifyingString, self).__init__()
def __init__(self, message_type, iterable=None): """Set up NotifyingList for use. Args: message_type (str): String name appended to message identifier. iterable (iterable, optional): Used to fill the instance. Defaults to None. """ super(NotifyingList, self).__init__(iterable) # NSDistributedNotificationCenter is the NotificationCenter # that allows messages to be sent between applications. self.notification_center = NSDistributedNotificationCenter.defaultCenter() self.message_type = message_type
def __init__(self, message_type, iterable=None): """Set up NotifyingList for use. Args: message_type: String name appended to message identifier. iterable: Optional iterable to use to fill the instance. """ super(NotifyingList, self).__init__(iterable) # NSDistributedNotificationCenter is the NotificationCenter # that allows messages to be sent between applications. self.notification_center = ( NSDistributedNotificationCenter.defaultCenter()) self.message_type = message_type
def __init__(self, message_type, text=""): """Set up NotifyingString for use. Args: message_type: String name appended to message identifier. text: Optional string to use to fill the instance. """ # NSDistributedNotificationCenter is the NotificationCenter # that allows messages to be sent between applications. self.notification_center = ( NSDistributedNotificationCenter.defaultCenter()) self.send_notification(text) super(NotifyingString, self).__init__(self, text)
def __new__(cls, message_type, val): """Set up NotifyingBool for use. Args: message_type (str): String name appended to message identifier. val (bool): Contents of the boolean - True or False """ instance = super(NotifyingBool, cls).__new__(cls) instance.message_type = message_type # NSDistributedNotificationCenter is the NotificationCenter # that allows messages to be sent between applications. instance.notification_center = NSDistributedNotificationCenter.defaultCenter() instance.send_notification(val) return bool(val)
def __new__(cls, message_type, val): """Set up NotifyingBool for use. Args: message_type: String name appended to message identifier. val: True or False """ instance = super(NotifyingBool, cls).__new__(cls) instance.message_type = message_type # NSDistributedNotificationCenter is the NotificationCenter # that allows messages to be sent between applications. instance.notification_center = ( NSDistributedNotificationCenter.defaultCenter()) instance.send_notification(val) return bool(val)
def _register_notification(self): set_idle = self.set_idle class Notify(NSObject): def screensaverDidStart_(self, _): logging.info("idle (screensaver started)") set_idle(True) def screensaverDidStop_(self, _): logging.info("active (screensaver stopped)") set_idle(False) def workspaceWillSleep_(self, _): logging.info("idle (sleep)") set_idle(True) def workspaceDidWake_(self, _): logging.info("active (wake)") set_idle(False) self._notify = Notify.new() # screensaver notifications nc = NSDistributedNotificationCenter.defaultCenter() nc.addObserver_selector_name_object_(self._notify, 'screensaverDidStart:', 'com.apple.screensaver.didstart', None) nc.addObserver_selector_name_object_(self._notify, 'screensaverDidStop:', 'com.apple.screensaver.didstop', None) # sleep notifications nc = NSWorkspace.sharedWorkspace().notificationCenter() nc.addObserver_selector_name_object_( self._notify, 'workspaceWillSleep:', 'NSWorkspaceWillSleepNotification', None) nc.addObserver_selector_name_object_(self._notify, 'workspaceDidWake:', 'NSWorkspaceDidWakeNotification', None)
def __init__(self) -> None: # Store reference to Music app in AppleScript self.__applescript_app = SBApplication.applicationWithBundleIdentifier_('com.apple.Music') super().__init__(self.__applescript_app) # Set up NSNotificationCenter (refer to https://lethain.com/how-to-use-selectors-in-pyobjc) self.__default_center = NSDistributedNotificationCenter.defaultCenter() self.__default_center.addObserver_selector_name_object_( self, '__handleNotificationFromMusic:', 'com.apple.Music.playerInfo', None ) # Store latest state self.__state: MediaPlayerState = None # Store whether the last notification failed was missing data to notify when it's been fixed self.__last_notification_had_error = False self.__last_state_with_error: MediaPlayerState = None
def __init__(self) -> None: # Store reference to Spotify app in AppleScript self.__applescript_app = SBApplication.applicationWithBundleIdentifier_( 'com.spotify.client') super().__init__(self.__applescript_app) self.is_plugin_available = False # Store the current media player state self.__state: MediaPlayerState = None if self.__applescript_app: self.is_plugin_available = True # Set up NSNotificationCenter (refer to https://lethain.com/how-to-use-selectors-in-pyobjc) self.__default_center = NSDistributedNotificationCenter.defaultCenter( ) self.__default_center.addObserver_selector_name_object_( self, '__handleNotificationFromSpotify:', 'com.spotify.client.PlaybackStateChanged', None)
# Update the preferences prefs.setPersistentDomain_forName_(globalPrefs, '.GlobalPreferences') prefs.synchronize() # Release the preferences from memory NSUserDefaults.resetStandardUserDefaults() # Build notification userInfo object userInfo = {} userInfoEntries = [] for item in items: userInfoEntries.append({ 'shortcut': item.valueForKey_('replace'), 'phrase': item.valueForKey_('with'), 'timestamp': int(time.time()) }) userInfo = { 'IMKUserDictionaryUserInfoCurrentEntriesKey': userInfoEntries } # Makes our changes to apply immediately on running processes. # It's undocumented but this is the notification that the prefpane # sends out when you make changes. nc = NSDistributedNotificationCenter.defaultCenter() nc.postNotificationName_object_('NSSpellServerReplacementsChanged', None) nc.postNotificationName_object_userInfo_( 'IMKUserDictionaryDidChangeNotification', None, userInfo) print repr(added) + " substitutions added." print repr(updated) + " substitutions updated."
def __init__(self): nc = NSDistributedNotificationCenter.defaultCenter() nc.addObserver_selector_name_object_(self, 'gotIt:', None, None)
import time from Foundation import NSObject, NSAppleScript, NSBundle, NSDistributedNotificationCenter from AppKit import NSWorkspace, NSWorkspaceDidWakeNotification, NSWorkspaceDidLaunchApplicationNotification, NSWorkspaceDidTerminateApplicationNotification from PyObjCTools import AppHelper class NotificationHandler(NSObject): def handler_(self, aNotification): print aNotification.name() return dnc = NSDistributedNotificationCenter.defaultCenter() no = NotificationHandler.new() dnc.addObserver_selector_name_object_(no, "handler:", None, None) AppHelper.runConsoleEventLoop()
def __init__(self): self.notification_handlers = [] self.ws = NSWorkspace.sharedWorkspace() self.nc = self.ws.notificationCenter() self.dnc = NSDistributedNotificationCenter.defaultCenter() return
def dealloc(self): logger.info('Removing observers…') dnc = NSDistributedNotificationCenter.defaultCenter() dnc.removeObserver_(self) return super().dealloc()