def process(): entry = 0 start_time = time.time() # print("Tracking active") while True: activeAppName = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] active = activeAppName if entry == 0: start_time = time.time() entry = 1 time.sleep(0.1) activeAppName = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] if active != activeAppName: entry = 0 current_time = time.time() elapsed_time = current_time - start_time to_send[activeAppName] = elapsed_time # print(to_send) payload = { "userHash": 'd0b529ed-e312-4170-b64e-a98aced1f531', "activities": to_send, } payload_json = json.dumps(payload) response = requests.post("{}/storeactivity/".format(base_url), payload_json)
def loadGlyphsInfo(): try: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_("com.GeorgSeifert.Glyphs2") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_("com.GeorgSeifert.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_( "com.schriftgestaltung.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_( "com.schriftgestaltung.GlyphsMini") GlyphsPath = GlyphsPath.path() except: return if GlyphsPath is not None: GlyphsInfoPath = GlyphsPath + "/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/GlyphData.xml" WeightCodesPath = GlyphsPath + "/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/weights.plist" parseGlyphDataFile(GlyphsInfoPath) CustomGlyphsInfoPath = applicationSupportFolder() if CustomGlyphsInfoPath: CustomGlyphsInfoPath = CustomGlyphsInfoPath.stringByAppendingPathComponent_( "/Info/GlyphData.xml") if os.path.isfile(CustomGlyphsInfoPath): parseGlyphDataFile(CustomGlyphsInfoPath) global weightCodes weightCodes = NSDictionary.alloc().initWithContentsOfFile_(WeightCodesPath)
def loadGlyphsInfo(): try: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.GeorgSeifert.Glyphs2") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.GeorgSeifert.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.schriftgestaltung.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.schriftgestaltung.GlyphsMini") GlyphsPath = GlyphsPath.path() except: return if GlyphsPath is not None: GlyphsInfoPath = GlyphsPath+"/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/GlyphData.xml" WeightCodesPath = GlyphsPath+"/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/weights.plist" parseGlyphDataFile(GlyphsInfoPath) CustomGlyphsInfoPath = applicationSupportFolder() if CustomGlyphsInfoPath: CustomGlyphsInfoPath = CustomGlyphsInfoPath.stringByAppendingPathComponent_("/Info/GlyphData.xml") if os.path.isfile(CustomGlyphsInfoPath): parseGlyphDataFile(CustomGlyphsInfoPath) global weightCodes weightCodes = NSDictionary.alloc().initWithContentsOfFile_(WeightCodesPath)
def alertShowHelp_(self, alert): TRACE('Help button clicked on boot error dialog') help_link = alert.helpAnchor() if help_link is not None: url = NSURL.alloc().initWithString_(help_link) NSWorkspace.sharedWorkspace().openURL_(url) return YES
def active_window_info(): app = NSWorkspace.sharedWorkspace().frontmostApplication() active_app_pid = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationProcessIdentifier'] #active_app_pid = app['NSApplicationProcessIdentifier'] active_app_name = app.localizedName() options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) windowTitle = 'Unknown' for window in windowList: pid = window['kCGWindowOwnerPID'] #windowNumber = window['kCGWindowNumber'] ownerName = window['kCGWindowOwnerName'] geometry = window['kCGWindowBounds'] windowTitle = window.get('kCGWindowName', u'Unknown') if windowTitle and (pid == active_app_pid or ownerName == active_app_name): LOGGER.debug( 'darwin: ownerName=%s, windowName=%s, x=%s, y=%s, ' 'width=%s, height=%s', window['kCGWindowOwnerName'], window.get('kCGWindowName', u'Unknown'), geometry['X'], geometry['Y'], geometry['Width'], geometry['Height']) return { 'app': ownerName, 'geometry': geometry, 'title': windowTitle, 'name': window.get('kCGWindowName', u'Unknown'), }
def webView_decidePolicyForNavigationAction_request_frame_decisionListener_( self, webView, info, request, frame, listener): # intercept link clicks so that they are opened in Safari theURL = info[WebActionOriginalURLKey] if theURL.scheme() == "file": listener.use() else: listener.ignore() NSWorkspace.sharedWorkspace().openURL_(theURL)
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 awakeFromNib(self): # Initialise our session and selected state parameters self.session = None self.columns = [[]] self.selectedResource = None self.selectedDetails = None self.selectedData = None # Cache some useful icons self.fileImage = NSWorkspace.sharedWorkspace().iconForFileType_( NSPlainFileType) self.fileImage.setSize_(NSSize(16, 16)) self.directoryImage = NSWorkspace.sharedWorkspace().iconForFile_( "/usr/") self.directoryImage.setSize_(NSSize(16, 16)) # Initialise the toolbar self._toolbarItems = {} self._toolbarDefaultItemIdentifiers = [] self._toolbarAllowedItemIdentifiers = [] self.createToolbar() # Set up browser view container = self.mainSplitterView.subviews()[0] container.addSubview_(self.columnView) container.addSubview_(self.listView) self.currentBrowserView = None self.setBrowserView(self.BROWSERVIEW_COLUMNS) self.browser.setMaxVisibleColumns_(7) self.browser.setMinColumnWidth_(150) # Set up data view container = self.mainSplitterView.subviews()[1] container.addSubview_(self.propertiesView) container.addSubview_(self.dataView) self.currentDataView = None self.setDataView(self.DATAVIEW_PROPERTIES) self.text.setString_("") self.pathLabel.setStringValue_("No server specified") # Get preferences lastServer = NSUserDefaults.standardUserDefaults().stringForKey_( "LastServer") if lastServer and len(lastServer): self.serverText.setStringValue_(lastServer) lastPath = NSUserDefaults.standardUserDefaults().stringForKey_( "LastPath") if lastPath and len(lastPath): self.pathText.setStringValue_(lastPath) else: self.pathText.setStringValue_("/") lastUser = NSUserDefaults.standardUserDefaults().stringForKey_( "LastUser") if lastUser and len(lastUser): self.userText.setStringValue_(lastUser)
def loadGlyphsInfo(GlyphsInfoPath=None): if GlyphsInfoPath is None: try: from AppKit import NSWorkspace except ImportError: pass # on Windows, skip else: try: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_( "com.GeorgSeifert.Glyphs2" ) if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_( "com.GeorgSeifert.Glyphs" ) if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_( "com.schriftgestaltung.Glyphs" ) if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_( "com.schriftgestaltung.GlyphsMini" ) GlyphsPath = GlyphsPath.path() except: return if GlyphsPath is not None: bundledGlyphData = ( GlyphsPath + "/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/GlyphData.xml" ) if os.path.isfile(bundledGlyphData): GlyphsInfoPath = bundledGlyphData if GlyphsInfoPath is None: # try to locate GlyphData.xml in FontLab's "Data" directory flGlyphData = os.path.join(fl.path, "Data", "GlyphData.xml") if os.path.isfile(flGlyphData): GlyphsInfoPath = flGlyphData if GlyphsInfoPath and os.path.isfile(GlyphsInfoPath): parseGlyphDataFile(GlyphsInfoPath) else: print ( 'Cannot find "GlyphData.xml".\n' 'Make sure Glyphs.app is installed correctly, or download "GlyphData.xml" from\n' 'https://github.com/schriftgestalt/GlyphsInfo, and place it inside "FontLab/Studio 5/Data".' ) CustomGlyphsInfoPath = applicationSupportFolder() if CustomGlyphsInfoPath: CustomGlyphsInfoPath = CustomGlyphsInfoPath.stringByAppendingPathComponent_("/Info/GlyphData.xml") if os.path.isfile(CustomGlyphsInfoPath): parseGlyphDataFile(CustomGlyphsInfoPath)
def getActiveWindowBBox(self): # https://github.com/asweigart/PyGetWindow/blob/master/random_notes.txt # print("system:", platform.system()) if (platform.system() == "Windows"): # import win32gui from win32 import win32gui from ctypes import windll # Make program aware of DPI scaling user32 = windll.user32 user32.SetProcessDPIAware() # w = win32gui.GetForegroundWindow() hwnd = win32gui.GetForegroundWindow() rect = win32gui.GetWindowRect(hwnd) print("rect: ", rect) x = rect[0] y = rect[1] w = rect[2] - x h = rect[3] - y x2 = rect[2] y2 = rect[3] print("Window %s:" % win32gui.GetWindowText(hwnd)) print("\tLocation: (%d, %d)" % (x, y)) print("\tLocation: (%d, %d)" % (x2, y2)) print("\t Size: (%d, %d)" % (w, h)) bbox = (x, y, x2, y2) return bbox elif (platform.system() == "Darwin"): # https://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python from AppKit import NSWorkspace # activeApp = NSWorkspace.sharedWorkspace().activeApplication() # depricated activeApp = NSWorkspace.sharedWorkspace().frontmostApplication() print(activeApp) activeAppID = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationProcessIdentifier'] print(activeAppID) # activeAppName = NSWorkspace.sharedWorkspace().frontmostApplication()['NSApplicationName'] # print(activeAppName) activeAppName = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] print(activeAppName) bbox = (10, 10, 510, 510) return bbox else: # try linux? bbox = (10, 10, 510, 510) return bbox bbox = (10, 10, 510, 510) return bbox
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 loadGlyphsInfo(GlyphsInfoPath=None): if GlyphsInfoPath is None: try: from AppKit import NSWorkspace except ImportError: pass # on Windows, skip else: try: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_( "com.GeorgSeifert.Glyphs2") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_( "com.GeorgSeifert.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_( "com.schriftgestaltung.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_( "com.schriftgestaltung.GlyphsMini") GlyphsPath = GlyphsPath.path() except: return if GlyphsPath is not None: bundledGlyphData = GlyphsPath + "/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/GlyphData.xml" if os.path.isfile(bundledGlyphData): GlyphsInfoPath = bundledGlyphData if GlyphsInfoPath is None: # try to locate GlyphData.xml in FontLab's "Data" directory flGlyphData = os.path.join(fl.path, "Data", "GlyphData.xml") if os.path.isfile(flGlyphData): GlyphsInfoPath = flGlyphData if GlyphsInfoPath and os.path.isfile(GlyphsInfoPath): parseGlyphDataFile(GlyphsInfoPath) else: print( "Cannot find \"GlyphData.xml\".\n" "Make sure Glyphs.app is installed correctly, or download \"GlyphData.xml\" from\n" "https://github.com/schriftgestalt/GlyphsInfo, and place it inside \"FontLab/Studio 5/Data\"." ) CustomGlyphsInfoPath = applicationSupportFolder() if CustomGlyphsInfoPath: CustomGlyphsInfoPath = CustomGlyphsInfoPath.stringByAppendingPathComponent_( "/Info/GlyphData.xml") if os.path.isfile(CustomGlyphsInfoPath): parseGlyphDataFile(CustomGlyphsInfoPath)
def webView_decidePolicyForNewWindowAction_request_newFrameName_decisionListener_(self, webView, info, request, frame, listener): try: theURL = info[WebActionOriginalURLKey] if self._account.server.settings_url is not None and theURL.host() == self._account.server.settings_url.hostname: listener.use() elif self._account.web_alert.alert_url is not None and theURL.host() == self._account.web_alert.alert_url.hostname: listener.use() else: # use system wide web browser NSWorkspace.sharedWorkspace().openURL_(theURL) listener.ignore() except KeyError: pass
def awakeFromNib(self): # Initialise our session and selected state parameters self.session = None self.columns = [[]] self.selectedResource = None self.selectedDetails = None self.selectedData = None # Cache some useful icons self.fileImage = NSWorkspace.sharedWorkspace().iconForFileType_(NSPlainFileType) self.fileImage.setSize_(NSSize(16, 16)) self.directoryImage = NSWorkspace.sharedWorkspace().iconForFile_("/usr/") self.directoryImage.setSize_(NSSize(16, 16)) # Initialise the toolbar self._toolbarItems = {} self._toolbarDefaultItemIdentifiers = [] self._toolbarAllowedItemIdentifiers = [] self.createToolbar() # Set up browser view container = self.mainSplitterView.subviews()[0] container.addSubview_(self.columnView) container.addSubview_(self.listView) self.currentBrowserView = None self.setBrowserView(self.BROWSERVIEW_COLUMNS) self.browser.setMaxVisibleColumns_(7) self.browser.setMinColumnWidth_(150) # Set up data view container = self.mainSplitterView.subviews()[1] container.addSubview_(self.propertiesView) container.addSubview_(self.dataView) self.currentDataView = None self.setDataView(self.DATAVIEW_PROPERTIES) self.text.setString_("") self.pathLabel.setStringValue_("No server specified") # Get preferences lastServer = NSUserDefaults.standardUserDefaults().stringForKey_("LastServer") if lastServer and len(lastServer): self.serverText.setStringValue_(lastServer) lastPath = NSUserDefaults.standardUserDefaults().stringForKey_("LastPath") if lastPath and len(lastPath): self.pathText.setStringValue_(lastPath) else: self.pathText.setStringValue_("/") lastUser = NSUserDefaults.standardUserDefaults().stringForKey_("LastUser") if lastUser and len(lastUser): self.userText.setStringValue_(lastUser)
def webView_decidePolicyForNavigationAction_request_frame_decisionListener_(self, webView, info, request, frame, listener): # intercept when user clicks on links so that we process them in different ways try: theURL = info[WebActionOriginalURLKey] if self._account.server.settings_url is not None and theURL.host() == self._account.server.settings_url.hostname: listener.use() elif self._account.web_alert.alert_url is not None and theURL.host() == self._account.web_alert.alert_url.hostname: listener.use() else: # use system wide web browser NSWorkspace.sharedWorkspace().openURL_(theURL) listener.ignore() except KeyError: pass
def GetActiveWindow_macOS(self): curr_app = NSWorkspace.sharedWorkspace().frontmostApplication() curr_pid = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationProcessIdentifier'] curr_app_name = curr_app.localizedName() options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) for window in windowList: pid = window['kCGWindowOwnerPID'] windowNumber = window['kCGWindowNumber'] ownerName = window['kCGWindowOwnerName'] geometry = window['kCGWindowBounds'] windowTitle = window.get('kCGWindowName', u'Unknown') if curr_pid == pid: return windowTitle
def monitor_apps(desired_app, pids): last_active_app = None is_stopped = True while True: active_app = NSWorkspace.sharedWorkspace().activeApplication() active_app_name = active_app["NSApplicationName"] if isinstance(active_app_name, unicode): # XXX: We might not want to ignore errors. active_app_name = active_app_name.encode("utf8", "ignore") if last_active_app != active_app_name: last_active_app = active_app_name print("Currently focused on", last_active_app) if last_active_app == desired_app: is_stopped = True for pid in pids: os.kill(pid, signal.SIGCONT) elif is_stopped: is_stopped = False for pid in pids: os.kill(pid, signal.SIGSTOP) time.sleep(1)
def get_browser_bounds(): runningApp = NSWorkspace.sharedWorkspace().frontmostApplication() runningAppPid = runningApp.processIdentifier() windows = CGWindowListCopyWindowInfo( kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID) possibleWindows = [] for wnd in windows: if wnd['kCGWindowOwnerPID'] == runningAppPid: possibleWindows.append(wnd) fallback = False if len(possibleWindows) == 0: # fallback mode fallback = True elif len(possibleWindows) == 1: window = possibleWindows[0] else: fallback = True for wnd in possibleWindows: #if 'netflix' in wnd['kCGWindowName'].lower(): if int(wnd['kCGWindowLayer']) < 0: window = wnd fallback = False break if fallback: # return fallback return dict(Height=NSScreen.mainScreen().frame().size.height, Width=NSScreen.mainScreen().frame().size.width, X=0, Y=0) else: return window['kCGWindowBounds']
def next_image(self, _): if not os.path.exists(self.media_dir): os.makedirs(self.media_dir) url = 'https://unsplash.it/' if self.gray_mood: url += 'g/' url += '{w}/{h}/?random' if self.blur: url += '&blur' url = url.format(w=self.screen_width, h=self.screen_height) file_name = self.media_dir + datetime.datetime.now().strftime("%H:%M:%S.%f") + '.jpg' try: self.icon = 'img/wait.png' urllib.urlretrieve(url, file_name) file_url = NSURL.fileURLWithPath_(file_name) # Get shared workspace ws = NSWorkspace.sharedWorkspace() # Iterate over all screens for screen in NSScreen.screens(): # Tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_url, screen, {}, None) self.icon = 'img/icon.png' except IOError: print('Service unavailable, check your internet connection.') rumps.alert(title='Connection Error', message='Service unavailable\n' 'Please, check your internet connection')
def main(): nc = NSWorkspace.sharedWorkspace().notificationCenter() observer = Observer.new() nc.addObserver_selector_name_object_( observer, "handle:", NSWorkspaceDidActivateApplicationNotification, None) AppHelper.runConsoleEventLoop(installInterrupt=True)
def registerNotifications(self): """Register the app to listen to system state events such as: wake, sleep, and power off""" workspace = NSWorkspace.sharedWorkspace() notificationCenter = workspace.notificationCenter() notificationCenter.addObserver_selector_name_object_( self, self.receiveSleepNotification_, NSWorkspaceWillSleepNotification, None ) notificationCenter.addObserver_selector_name_object_( self, self.receiveWakeNotification_, NSWorkspaceDidWakeNotification, None ) notificationCenter.addObserver_selector_name_object_( self, self.receivePowerOffNotification_, NSWorkspaceWillPowerOffNotification, None ) notificationCenter.addObserver_selector_name_object_( self, self.receiveScreensDidSleep_, NSWorkspaceScreensDidSleepNotification, None ) notificationCenter.addObserver_selector_name_object_( self, self.receiveScreensDidWake_, NSWorkspaceScreensDidWakeNotification, None )
def is_network_volume(share_path): '''NSWorkspace alows us to check for filesystem type of a specified path''' #pylint: disable=C0301,C0103 ws = NSWorkspace.alloc().init() share_type = ws.getFileSystemInfoForPath_isRemovable_isWritable_isUnmountable_description_type_( share_path, None, None, None, None, None)[-1] return True if share_type == 'smbfs' or share_type == 'webdav' else False
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 run(self) -> None: NSApplication.sharedApplication() self.delegate = AppDelegate.alloc().init() self.delegate.handler = Handler() NSApp().setDelegate_(self.delegate) self.workspace = NSWorkspace.sharedWorkspace() nc = self.workspace.notificationCenter() nc.addObserver_selector_name_object_( self.delegate, 'applicationActivated:', 'NSWorkspaceDidActivateApplicationNotification', None, ) nc.addObserver_selector_name_object_( self.delegate, 'screenSleep:', 'NSWorkspaceScreensDidSleepNotification', None, ) NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( self.polling_time, self.delegate, 'writeActiveApp:', None, True) AppHelper.runConsoleEventLoop(maxTimeout=1)
def what_doin(): active_app = NSWorkspace.sharedWorkspace().activeApplication() return { 'Name': active_app['NSApplicationName'], 'Path': active_app['NSApplicationPath'], 'BundleID': active_app['NSApplicationBundleIdentifier'] }
def openUrl(self, url, background=False): ws = NSWorkspace.sharedWorkspace() option = NSWorkspaceLaunchDefault if background: option = NSWorkspaceLaunchWithoutActivation ws.openURL_options_configuration_error_(NSURL.URLWithString_(url), option, dict(), None)
def game_running(self): if platform == 'darwin': for app in NSWorkspace.sharedWorkspace().runningApplications(): if app.bundleIdentifier() == 'uk.co.frontier.EliteDangerous': return True elif platform == 'win32': def WindowTitle(h): if h: l = GetWindowTextLength(h) + 1 buf = ctypes.create_unicode_buffer(l) if GetWindowText(h, buf, l): return buf.value return None def callback(hWnd, lParam): name = WindowTitle(hWnd) if name and name.startswith('Elite - Dangerous'): handle = GetProcessHandleFromHwnd(hWnd) if handle: # If GetProcessHandleFromHwnd succeeds then the app is already running as this user CloseHandle(handle) return False # stop enumeration return True return not EnumWindows(EnumWindowsProc(callback), 0) return False
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() AppHelper.runEventLoop()
def get_active_window(): global activityDict, words, currentAppName, start_time, end_time, activity_totalTime, total_mouse_clicks def calculate_activity_totals(activity_totalTime, currentAppName): global activityDict, words, start, total_mouse_clicks total_mouse_clicks = int(total_mouse_clicks / 2) if currentAppName in activityDict.keys(): activity_totalTime += activityDict[currentAppName][0] words += activityDict[currentAppName][1] total_mouse_clicks += activityDict[currentAppName][2] activityDict[currentAppName] = (activity_totalTime, words, total_mouse_clicks) activeAppName = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] if currentAppName != activeAppName: end_time = time.time() activity_totalTime = end_time - start_time calculate_activity_totals(activity_totalTime, currentAppName) start_time = time.time() currentAppName = activeAppName words = 0 total_mouse_clicks = 0 previous_key = None print(activityDict)
def observeValueForKeyPath_ofObject_change_context_(self, path, obj, change, context): if context == self.FinderTerminatedContext: if path == self.FinderTerminationKey: TRACE('Restarting finder %r', obj) self.ret.set(NSWorkspace.sharedWorkspace().launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_(self.FinderIdentifier, NSWorkspaceLaunchDefault, None, None)) else: return super(FinderRestarterHelper, self).observeValueForKeyPath_ofObject_change_context_(path, obj, change, context)
def run(self): NSApplication.sharedApplication() self.delegate = AppDelegate.alloc().init() self.delegate.event_sniffer = self NSApp().setDelegate_(self.delegate) self.workspace = NSWorkspace.sharedWorkspace() nc = self.workspace.notificationCenter() # This notification needs OS X v10.6 or later nc.addObserver_selector_name_object_( self.delegate, 'applicationActivated:', 'NSWorkspaceDidActivateApplicationNotification', None) nc.addObserver_selector_name_object_( self.delegate, 'screenSleep:', 'NSWorkspaceScreensDidSleepNotification', None) # I don't think we need to track when the screen comes awake, but in case # we do we can listen for NSWorkspaceScreensDidWakeNotification NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( self.options.active_window_time, self.delegate, 'writeActiveApp:', None, True) # Start the application. This doesn't return. AppHelper.runEventLoop()
def is_alias (path): uti, err = NSWorkspace.sharedWorkspace().typeOfFile_error_( os.path.realpath(path), None) if err: raise Exception(unicode(err)) else: return "com.apple.alias-file" == uti
def get_active_window(): if sys.platform == "darwin": active_app = NSWorkspace.sharedWorkspace().frontmostApplication() active_app.localizedName() else: root_check = '' root = Popen(['xprop', '-root'], stdout=PIPE) if root.stdout != root_check: root_check = root.stdout for i in root.stdout: if '_NET_ACTIVE_WINDOW(WINDOW):' in i: id_ = i.split()[4] id_w = Popen(['xprop', '-id', id_], stdout=PIPE) id_w.wait() buff = [] for j in id_w.stdout: buff.append(j) for line in buff: match = re.match("WM_NAME\((?P<type>.+)\) = (?P<name>.+)", line) if match != None: type = match.group("type") if type == "STRING" or type == "COMPOUND_TEXT": return match.group("name") return "Active window not found"
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 set_desktop_background(desktop_picture_path): file_url = NSURL.fileURLWithPath_(desktop_picture_path) ws = NSWorkspace.sharedWorkspace() screens = NSScreen.screens() for screen in screens: ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
def set_background(image_file): from AppKit import NSWorkspace, NSScreen from Foundation import NSURL file_url = NSURL.fileURLWithPath_(image_file) ws = NSWorkspace.sharedWorkspace() for screen in NSScreen.screens(): ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
def initWithBrowser_andForest_reloadInvalidState_(self, browser, forest, reloadInvalidState): self = super(SelectiveSyncBrowserDelegate, self).init() if self is None: return from dropbox.mac.internal import get_resources_dir self.default_width = None icons_path = get_resources_dir() if hasattr(build_number, 'frozen') else u'icons/' self.images = {} for key, icon in (('dropbox', 'DropboxFolderIcon_leopard.icns'), ('shared', 'shared_leopard.icns'), ('public', 'public_leopard.icns'), ('photos', 'photos_leopard.icns'), ('sandbox', 'sandbox_leopard.icns'), ('camerauploads', 'camerauploads_leopard.icns')): image = NSImage.alloc().initByReferencingFile_(os.path.join(icons_path, icon)) image.setSize_((16, 16)) image.setFlipped_(YES) image.recache() self.images[key] = image images_path = get_resources_dir() if hasattr(build_number, 'frozen') else u'images/mac' folder_image = NSWorkspace.sharedWorkspace().iconForFileType_(NSFileTypeForHFSTypeCode('fldr')) folder_image.setFlipped_(YES) folder_image.setSize_(NSMakeSize(16, 16)) self.images['folder'] = folder_image self.forest = forest self.browser_reloadAdvancedView_(browser, self.forest.advanced_view) self.reloadInvalidState = reloadInvalidState TRACE('initialized %r', self.forest) self.browser = browser return self
def run_profiler(): samples = [] while True: activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName'] samples.append([int(time.time()), activeAppName]) print_summary(samples) time.sleep(sample_interval)
def close_window(self): workspace = NSWorkspace.sharedWorkspace() activeApps = workspace.runningApplications() for app in activeApps: if app.isActive() and app.localizedName() == "Blizzard Battle.net": app.hide()
def get_currently_active_appname(self): # Get the active window application name active_app_name = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] return active_app_name
def get_active_app_name(): """ Asigna a active_app la app en uso y :return: el nombre de la app en uso """ active_app = NSWorkspace.sharedWorkspace().activeApplication() return active_app['NSApplicationName']
def change_desktop_background(file, desk_id): """Function that applies the named file as wallaper for the specified monitor (desk_id)""" file_url = NSURL.fileURLWithPath_(file) screen = NSScreen.screens()[desk_id] ws = NSWorkspace.sharedWorkspace() ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
def webView_decidePolicyForNewWindowAction_request_newFrameName_decisionListener_( self, webView, info, request, frame, listener): try: theURL = info[WebActionOriginalURLKey] if self._account.server.settings_url is not None and theURL.host( ) == self._account.server.settings_url.hostname: listener.use() elif self._account.web_alert.alert_url is not None and theURL.host( ) in self._account.web_alert.alert_url: listener.use() else: # use system wide web browser NSWorkspace.sharedWorkspace().openURL_(theURL) listener.ignore() except KeyError: pass
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 get_running_apps(): """Return a list of running applications""" procs = [] workspace = NSWorkspace.sharedWorkspace() running_apps = workspace.runningApplications() for app in running_apps: procs.append(app.localizedName()) return procs
def on_release(key): try: active_app_name = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] if key.char in left: key = 'left' elif key.char in right: key = 'right' else: key = key key_logger.info('{0}, released, {1}'.format(key, active_app_name)) except AttributeError: active_app_name = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] key_logger.info('{0}, released, {1}'.format(key, active_app_name))
def register_sleep_handlers(self): log("register_sleep_handlers()") workspace = NSWorkspace.sharedWorkspace() notificationCenter = workspace.notificationCenter() notificationCenter.addObserver_selector_name_object_(self, self.receiveSleepNotification_, NSWorkspaceWillSleepNotification, None) notificationCenter.addObserver_selector_name_object_(self, self.receiveWakeNotification_, NSWorkspaceDidWakeNotification, None)
def run_profiler(): samples = [] while True: activeAppName = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] samples.append([int(time.time()), activeAppName]) print_summary(samples) time.sleep(sample_interval)
def extract_icon(file_path): file_icon_tiff = NSWorkspace.sharedWorkspace().iconForFile_( file_path).TIFFRepresentation() file_icon_png = NSBitmapImageRep.imageRepWithData_( file_icon_tiff).representationUsingType_properties_(NSPNGFileType, None) file_icon_png_path = file_path + ".png" file_icon_png.writeToFile_atomically_(file_icon_png_path, None) return file_icon_png_path
def track_app_focus_change(sleep_time): last_active_name = None while True: active_app = NSWorkspace.sharedWorkspace().activeApplication() if active_app['NSApplicationName'] != last_active_name: last_active_name = active_app['NSApplicationName'] print_app_data(active_app) sleep(sleep_time)
def determine_state_and_nudge(self): '''Determine the state of nudge and re-fresh window''' workspace = NSWorkspace.sharedWorkspace() currently_active = NSApplication.sharedApplication().isActive() frontmost_app = workspace.frontmostApplication().bundleIdentifier() if not currently_active and frontmost_app not in self.acceptable_apps: nudgelog('Nudge or acceptable applications not currently active') # If this is the under max dismissed count, just bring nudge back to the forefront # This is the old behavior if self.nudge_dismissed_count < self.dismissall_count_threshold: nudgelog('Nudge dismissed count under threshold') self.nudge_dismissed_count += 1 bring_nudge_to_forefront(self.nudge) else: # Get more aggressive - new behavior nudgelog('Nudge dismissed count over threshold') self.nudge_dismissed_count += 1 nudgelog('Enforcing acceptable applications') # Loop through all the running applications for app in NSWorkspace.sharedWorkspace().runningApplications(): app_name = str(app.bundleIdentifier()) app_bundle = str(app.bundleURL()) if app_bundle: # The app bundle contains file://, quoted path and trailing slashes app_bundle_path = unquote( urlparse(app_bundle).path).rstrip('/') # Add Software Update pane or macOS upgrade app to acceptable app list if app_bundle_path == self.nudge.path_to_app: self.acceptable_apps.append(app_name) else: # Some of the apps from NSWorkspace don't have bundles, # so force empty string app_bundle_path = '' # Hide any apps that are not in acceptable list or are not the macOS upgrade app if (app_name not in self.acceptable_apps) or ( app_bundle_path != self.nudge.path_to_app): app.hide() # Race condition with NSWorkspace. Python is faster :) time.sleep(0.001) # Another small sleep to ensure we can bring Nudge on top time.sleep(0.5) bring_nudge_to_forefront(self.nudge) # Pretend to open the button and open the update mechanism self.nudge.button_update(True) self.ux_when_timer_is_controlling()
def _handler(self, event): # use event.charactersIgnoringModifiers to handle composing characters like Alt-e if (event.modifierFlags() & HotkeyMgr.MODIFIERMASK) == self.modifiers and ord(event.charactersIgnoringModifiers()[0]) == self.keycode: if config.getint('hotkey_always'): self.activated = True else: # Only trigger if game client is front process front = NSWorkspace.sharedWorkspace().frontmostApplication() if front and front.bundleIdentifier() == 'uk.co.frontier.EliteDangerous': self.activated = True
def get_app_name(bundle_id): '''Get display name for app specified by bundle_id''' from AppKit import NSWorkspace from Foundation import NSFileManager app_path = NSWorkspace.sharedWorkspace( ).absolutePathForAppBundleWithIdentifier_(bundle_id) if app_path: return NSFileManager.defaultManager().displayNameAtPath_(app_path) return bundle_id
def isApp(self, itemId, itemPath): currentAppPath = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationPath'] currentApp = currentAppPath.split('/')[-1] if itemId != -1: assert itemId < len(self.itemList), "Actor::isApp: itemId not exist" app = self.itemList[itemId].split('/')[-1] else: app = itemPath.split('/')[-1] return currentApp == app
def get_bundle_id(app_name): '''Given an app_name, get the bundle_id''' from AppKit import NSWorkspace from Foundation import NSBundle app_path = NSWorkspace.sharedWorkspace( ).fullPathForApplication_(app_name) if app_path: return NSBundle.bundleWithPath_(app_path).bundleIdentifier() return None
def bundleid_is_running(app_bundleid): '''Returns a boolean indicating if the application with the given bundleid is currently running.''' workspace = NSWorkspace.sharedWorkspace() running_apps = workspace.runningApplications() for app in running_apps: if app.bundleIdentifier() == app_bundleid: return True return False
def __defaults(self, plistName='Defaults'): if self.__bundlePath is None: self.__bundlePath = NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier_(self.__bundleID) if self.__bundlePath: plistPath = path.join(self.__bundlePath, "Contents/Resources/%s.plist" % plistName) plist = NSDictionary.dictionaryWithContentsOfFile_(plistPath) if plist: return plist return NSDictionary.dictionary()