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 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 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 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 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 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 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 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 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 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 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 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 run_profiler(): samples = [] while True: activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName'] samples.append([int(time.time()), activeAppName]) print_summary(samples) time.sleep(sample_interval)
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() AppHelper.runEventLoop()
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 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 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 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 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 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 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 __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()
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 _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_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 killRunningApps(): workspace = NSWorkspace.sharedWorkspace() running_apps = workspace.runningApplications() for app in running_apps: match = re.match(regex, str(app.bundleIdentifier())) if match: _index = match.lastindex - 1 exactBundleIDOrWildcard = re.sub(r"\(|\)", '', regex).split("|")[_index] # We call the takeaction method, with the additions below violationInfo = { "matchedRegex": exactBundleIDOrWildcard, "userName": NSProcessInfo.processInfo().userName(), "appName": app.localizedName(), "bundleIdentifier": app.bundleIdentifier(), "processIdentifier": app.processIdentifier(), "appPath...": 0 } # Take action upon the app takeAction(violationInfo)
def getInfo() -> tuple: # curr_app = NSWorkspace.sharedWorkspace().frontmostApplication() # returns always python window_title = app_name = 'Unknown' curr_pid = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationProcessIdentifier'] options = kCGWindowListOptionOnScreenOnly window_list = CGWindowListCopyWindowInfo(options, kCGNullWindowID) try: window = [ w for w in window_list if curr_pid == w['kCGWindowOwnerPID'] ][0] except IndexError: pass else: window_title = window.get('kCGWindowName', window_title) app_name = window.get('kCGWindowOwnerName', app_name) return (app_name, window_title)
def find_window_geometry_by_name(appName): workspace = NSWorkspace.sharedWorkspace() runningApps = workspace.runningApplications() for app in runningApps: #if app.isActive(): if app.localizedName() == appName: #print ('one more', app.localizedName()) options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) for window in windowList: if window['kCGWindowOwnerName'] == app.localizedName(): #print(window.getKeys_) kCGWindowBounds = window['kCGWindowBounds'] #print(kCGWindowBounds) # height = kCGWindowBounds['Height'] # width = kCGWindowBounds['Width'] # X = kCGWindowBounds['X'] # Y = kCGWindowBounds['Y'] return kCGWindowBounds #(X, Y, height, width) break break
def __current_active_app(self, con): activeAppName = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] strokes = 0 ''' mouse = Controller() stokes=0 if not mouse.position ==self.pos: stokes+=1 self.pos= mouse.position with keyboard.Events() as events: # Block at most one second try: start_time = time.time() event = events.get(1.0) total_time = (time.time() - start_time) print(total_time) time.sleep(1-total_time) if event: strokes=1 except: stokes=0 ''' cur = con.cursor() query = '''SELECT P_name FROM Processes WHERE P_name=?''' check = cur.execute(query, (activeAppName, )) print(type(check.fetchone())) if isinstance((check.fetchone()), tuple): print('updated' + activeAppName) update_Process(con, activeAppName, strokes) elif not isinstance((check.fetchone()), tuple): insert_Process(con, activeAppName, 1, strokes) print('added' + activeAppName)
def main(): prev_app = None while True: app = NSWorkspace.sharedWorkspace().activeApplication() if prev_app is None: prev_app = app if app != prev_app: pids = get_pids(prev_app) logger.debug('Suspending %s (%s)', pids, prev_app['NSApplicationName']) map(SUSPENDED.add, pids) map(lambda x: os.kill(x, signal.SIGSTOP), pids) pids = get_pids(app) logger.debug('Resuming %s (%s)', pids, app['NSApplicationName']) map(SUSPENDED.discard, pids) map(lambda x: os.kill(x, signal.SIGCONT), pids) # sometimes it won't work from the first time map(lambda x: os.kill(x, signal.SIGCONT), pids) prev_app = app time.sleep(0.5)
def setup_event_loop(self): if NSWorkspace is None: self.notificationCenter = None self.handler = None log.warn("event loop not started") return ws = NSWorkspace.sharedWorkspace() self.notificationCenter = ws.notificationCenter() self.handler = NotificationHandler.new() if self.client: self.handler.sleep_callback = self.client.suspend self.handler.wake_callback = self.client.resume else: self.handler.sleep_callback = None self.handler.wake_callback = None self.notificationCenter.addObserver_selector_name_object_( self.handler, "handleSleepNotification:", AppKit.NSWorkspaceWillSleepNotification, None) self.notificationCenter.addObserver_selector_name_object_( self.handler, "handleWakeNotification:", AppKit.NSWorkspaceDidWakeNotification, None) log("starting console event loop with notifcation center=%s and handler=%s", self.notificationCenter, self.handler)
def helperPath(): fileMergeIdentifier = 'com.apple.FileMerge' xcodeIdentifier = 'com.apple.dt.Xcode' fileMergeXcodeHelperPath = 'Contents/Developer/usr/bin/opendiff' fileMergeSystemHelperPath = '/usr/bin/opendiff' fileMergeDevHelperPath = '/Developer/usr/bin/opendiff' xcodePath = NSWorkspace.sharedWorkspace( ).absolutePathForAppBundleWithIdentifier_(xcodeIdentifier) fileMergePath = os.path.join(xcodePath, fileMergeXcodeHelperPath) helperPath = None if NSFileManager.defaultManager().fileExistsAtPath_(fileMergePath) == True: helperPath = fileMergePath elif NSFileManager.defaultManager().fileExistsAtPath_( fileMergeSystemHelperPath) == True: helperPath = fileMergeSystemHelperPath elif NSFileManager.defaultManager().fileExistsAtPath_( fileMergeDevHelperPath) == True: helperPath = fileMergeDevHelperPath return helperPath
def init_bar(): launchedApps = NSWorkspace.sharedWorkspace().launchedApplications() appNames = [ app['NSApplicationName'] for app in launchedApps ] print('Launched apps:', appNames) desiredApps = set() teststring = "hello world" rumpsClass = \ '''class AwesomeStatusBarApp(rumps.App): ''' menuItemString =\ ''' @rumps.clicked(%s) def onoff%d(self, sender): sender.state = not sender.state print(teststring) if sender.state: desiredApps.add(%s) ''' for i, launchedApp in enumerate(launchedApps): appStr = 'launchedApp[%d]' % i appNameStr = '\'%s\'' % launchedApp['NSApplicationName'] rumpsClass += menuItemString % (appNameStr, i, appStr) #print(rumpsClass) return rumpsClass
def main(): parser = argparse.ArgumentParser(description="Utility to print, set, or " + "check the path to image being used as " + "the desktop background image. By " + "default, prints the path to the " + "current desktop background image.") parser.add_argument( "-v", "--verbose", action="store_true", help="print verbose debugging information", default=False, ) group = parser.add_mutually_exclusive_group() group.add_argument( "-s", "--set-background-image", dest="newBackgroundImagePath", required=False, help="path to the new background image to set. A zero " + "exit code indicates no errors occurred.", default=None, ) group.add_argument( "-c", "--check-background-image", dest="checkBackgroundImagePath", required=False, help="check if the provided background image path " + "matches the provided path. A zero exit code " + "indicates the paths match.", default=None, ) args = parser.parse_args() # Using logging for verbose output if args.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.CRITICAL) logger = logging.getLogger("desktopImage") # Print what we're going to do if args.checkBackgroundImagePath is not None: logger.debug("checking provided desktop image %s matches current " "image" % args.checkBackgroundImagePath) elif args.newBackgroundImagePath is not None: logger.debug("setting image to %s " % args.newBackgroundImagePath) else: logger.debug("retrieving desktop image path") focussedScreen = NSScreen.mainScreen() if not focussedScreen: raise RuntimeError("mainScreen error") ws = NSWorkspace.sharedWorkspace() if not ws: raise RuntimeError("sharedWorkspace error") # If we're just checking the image path, check it and then return. # A successful exit code (0) indicates the paths match. if args.checkBackgroundImagePath is not None: # Get existing desktop image path and resolve it existingImageURL = getCurrentDesktopImageURL(focussedScreen, ws, logger) existingImagePath = existingImageURL.path() existingImagePathReal = os.path.realpath(existingImagePath) logger.debug("existing desktop image: %s" % existingImagePath) logger.debug("existing desktop image realpath: %s" % existingImagePath) # Resolve the path we're going to check checkImagePathReal = os.path.realpath(args.checkBackgroundImagePath) logger.debug("check desktop image: %s" % args.checkBackgroundImagePath) logger.debug("check desktop image realpath: %s" % checkImagePathReal) if existingImagePathReal == checkImagePathReal: print("desktop image path matches provided path") return True print("desktop image path does NOT match provided path") return False # Log the current desktop image if args.verbose: existingImageURL = getCurrentDesktopImageURL(focussedScreen, ws, logger) logger.debug("existing desktop image: %s" % existingImageURL.path()) # Set the desktop image if args.newBackgroundImagePath is not None: newImagePath = args.newBackgroundImagePath if not os.path.exists(newImagePath): logger.critical("%s does not exist" % newImagePath) return False if not os.access(newImagePath, os.R_OK): logger.critical("%s is not readable" % newImagePath) return False logger.debug("new desktop image to set: %s" % newImagePath) newImageURL = NSURL.fileURLWithPath_(newImagePath) logger.debug("new desktop image URL to set: %s" % newImageURL) status = False (status, error) = ws.setDesktopImageURL_forScreen_options_error_( newImageURL, focussedScreen, None, None) if not status: raise RuntimeError("setDesktopImageURL error") # Print the current desktop image imageURL = getCurrentDesktopImageURL(focussedScreen, ws, logger) imagePath = imageURL.path() imagePathReal = os.path.realpath(imagePath) logger.debug("updated desktop image URL: %s" % imageURL) logger.debug("updated desktop image path: %s" % imagePath) logger.debug("updated desktop image path (resolved): %s" % imagePathReal) print(imagePathReal) return True
def onInit(self, showSplash=True, testMode=False): """This is launched immediately *after* the app initialises with wx :Parameters: testMode: bool """ self.SetAppName('PsychoPy3') if showSplash: #showSplash: # show splash screen splashFile = os.path.join(self.prefs.paths['resources'], 'psychopySplash.png') splashImage = wx.Image(name=splashFile) splashImage.ConvertAlphaToMask() splash = AS.AdvancedSplash( None, bitmap=splashImage.ConvertToBitmap(), timeout=3000, agwStyle=AS.AS_TIMEOUT | AS.AS_CENTER_ON_SCREEN, ) # transparency? w, h = splashImage.GetSize() splash.SetTextPosition((int(340), h - 30)) splash.SetText( _translate("Copyright (C) 2020 OpenScienceTools.org")) else: splash = None # SLOW IMPORTS - these need to be imported after splash screen starts # but then that they end up being local so keep track in self from psychopy.compatibility import checkCompatibility # import coder and builder here but only use them later from psychopy.app import coder, builder, runner, dialogs if '--firstrun' in sys.argv: del sys.argv[sys.argv.index('--firstrun')] self.firstRun = True if 'lastVersion' not in self.prefs.appData: # must be before 1.74.00 last = self.prefs.appData['lastVersion'] = '1.73.04' self.firstRun = True else: last = self.prefs.appData['lastVersion'] if self.firstRun and not self.testMode: pass # setup links for URLs # on a mac, don't exit when the last frame is deleted, just show menu if sys.platform == 'darwin': self.menuFrame = MenuFrame(parent=None, app=self) # fetch prev files if that's the preference if self.prefs.coder['reloadPrevFiles']: scripts = self.prefs.appData['coder']['prevFiles'] else: scripts = [] appKeys = list(self.prefs.appData['builder'].keys()) if self.prefs.builder['reloadPrevExp'] and ('prevFiles' in appKeys): exps = self.prefs.appData['builder']['prevFiles'] else: exps = [] runlist = [] self.dpi = int(wx.GetDisplaySize()[0] / float(wx.GetDisplaySizeMM()[0]) * 25.4) if not (50 < self.dpi < 120): self.dpi = 80 # dpi was unreasonable, make one up if sys.platform == 'win32': # wx.SYS_DEFAULT_GUI_FONT is default GUI font in Win32 self._mainFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) else: self._mainFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) try: self._codeFont = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT) except wx._core.wxAssertionError: # if no SYS_ANSI_FIXED_FONT then try generic FONTFAMILY_MODERN self._codeFont = wx.Font(self._mainFont.GetPointSize(), wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) # that gets most of the properties of _codeFont but the FaceName # FaceName is set in the setting of the theme: self.theme = self.prefs.app['theme'] # removed Aug 2017: on newer versions of wx (at least on mac) # this looks too big # if hasattr(self._mainFont, 'Larger'): # # Font.Larger is available since wyPython version 2.9.1 # # PsychoPy still supports 2.8 (see ensureMinimal above) # self._mainFont = self._mainFont.Larger() # self._codeFont.SetPointSize( # self._mainFont.GetPointSize()) # unify font size # create both frame for coder/builder as necess if splash: splash.SetText(_translate(" Creating frames...")) # Parse incoming call parser = argparse.ArgumentParser(prog=self) parser.add_argument('--builder', dest='builder', action="store_true") parser.add_argument('-b', dest='builder', action="store_true") parser.add_argument('--coder', dest='coder', action="store_true") parser.add_argument('-c', dest='coder', action="store_true") parser.add_argument('--runner', dest='runner', action="store_true") parser.add_argument('-r', dest='runner', action="store_true") view, args = parser.parse_known_args(sys.argv) print(args) # Check from filetype if any windows need to be open if any(arg.endswith('.psyexp') for arg in args): view.builder = True exps = [file for file in args if file.endswith('.psyexp')] if any(arg.endswith('.psyrun') for arg in args): view.runner = True runlist = [file for file in args if file.endswith('.psyrun')] # If still no window specified, use default from prefs if not any( getattr(view, key) for key in ['builder', 'coder', 'runner']): if self.prefs.app['defaultView'] in view: setattr(view, self.prefs.app['defaultView'], True) elif self.prefs.app['defaultView'] == 'all': view.builder = True view.coder = True view.runner = True # Create windows if view.runner: self.showRunner(fileList=runlist) if view.coder: self.showCoder(fileList=scripts) if view.builder: self.showBuilder(fileList=exps) # if darwin, check for inaccessible keyboard if sys.platform == 'darwin': from psychopy.hardware import keyboard if keyboard.macPrefsBad: title = _translate("Mac keyboard security") if platform.mac_ver()[0] < '10.15': settingName = 'Accessibility' setting = 'Privacy_Accessibility' else: setting = 'Privacy_ListenEvent' settingName = 'Input Monitoring' msg = _translate( "To use high-precision keyboard timing you should " "enable {} for PsychoPy in System Preferences. " "Shall we go there (and you can drag PsychoPy app into " "the box)?").format(settingName) dlg = dialogs.MessageDialog(title=title, message=msg, type='Query') resp = dlg.ShowModal() if resp == wx.ID_YES: from AppKit import NSWorkspace from Foundation import NSURL sys_pref_link = ('x-apple.systempreferences:' 'com.apple.preference.security?' '{}'.format(setting)) # create workspace object workspace = NSWorkspace.sharedWorkspace() # Open System Preference workspace.openURL_(NSURL.URLWithString_(sys_pref_link)) # send anonymous info to www.psychopy.org/usage.php # please don't disable this, it's important for PsychoPy's development self._latestAvailableVersion = None self.updater = None self.news = None self.tasks = None prefsConn = self.prefs.connections ok, msg = checkCompatibility(last, self.version, self.prefs, fix=True) # tell the user what has changed if not ok and not self.firstRun and not self.testMode: title = _translate("Compatibility information") dlg = dialogs.MessageDialog(parent=None, message=msg, type='Info', title=title) dlg.ShowModal() if (self.prefs.app['showStartupTips'] and not self.testMode and not blockTips): tipFile = os.path.join(self.prefs.paths['resources'], _translate("tips.txt")) tipIndex = self.prefs.appData['tipIndex'] if parse_version(wx.__version__) >= parse_version('4.0.0a1'): tp = wx.adv.CreateFileTipProvider(tipFile, tipIndex) showTip = wx.adv.ShowTip(None, tp) else: tp = wx.CreateFileTipProvider(tipFile, tipIndex) showTip = wx.ShowTip(None, tp) self.prefs.appData['tipIndex'] = tp.GetCurrentTip() self.prefs.saveAppData() self.prefs.app['showStartupTips'] = showTip self.prefs.saveUserPrefs() self.Bind(wx.EVT_IDLE, self.onIdle) # doing this once subsequently enables the app to open & switch among # wx-windows on some platforms (Mac 10.9.4) with wx-3.0: v = parse_version if sys.platform == 'darwin': if v('3.0') <= v(wx.version()) < v('4.0'): _Showgui_Hack() # returns ~immediately, no display # focus stays in never-land, so bring back to the app: if prefs.app['defaultView'] in [ 'all', 'builder', 'coder', 'runner' ]: self.showBuilder() else: self.showCoder() # after all windows are created (so errors flushed) create output self._appLoaded = True if self.coder: self.coder.setOutputWindow() # takes control of sys.stdout # flush any errors to the last run log file logging.flush() sys.stdout.flush() # we wanted debug mode while loading but safe to go back to info mode if not self.prefs.app['debugMode']: logging.console.setLevel(logging.INFO) # Runner captures standard streams until program closed if self.runner and not self.testMode: sys.stdout = self.runner.stdOut sys.stderr = self.runner.stdOut return True
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) self.workspace = NSWorkspace.sharedWorkspace() AppHelper.runEventLoop()
def show(self): BlinkLogger().log_debug('Show %s' % self) self.active = True if self.captureSession is None: # Find a video camera device = self.getDevice() if not device: return self.captureSession = AVCaptureSession.alloc().init() if self.captureSession.canSetSessionPreset_( AVCaptureSessionPresetHigh): self.captureSession.setSessionPreset_( AVCaptureSessionPresetHigh) NSWorkspace.sharedWorkspace().notificationCenter( ).addObserver_selector_name_object_( self, "computerDidWake:", NSWorkspaceDidWakeNotification, None) NSWorkspace.sharedWorkspace().notificationCenter( ).addObserver_selector_name_object_( self, "computerWillSleep:", NSWorkspaceWillSleepNotification, None) max_resolution = (0, 0) BlinkLogger().log_debug( "%s camera provides %d formats" % (device.localizedName(), len(device.formats()))) for desc in device.formats(): m = self.resolution_re.match(repr(desc)) if m: data = m.groupdict() width = int(data['width']) height = int(data['height']) BlinkLogger().log_debug( "Supported resolution: %dx%d %.2f" % (width, height, width / float(height))) if width > max_resolution[0]: max_resolution = (width, height) width, height = max_resolution if width == 0 or height == 0: width = 1280 height = 720 BlinkLogger().log_info( "Error: %s camera does not provide any supported video format" % device.localizedName()) else: if NSApp.delegate( ).contactsWindowController.sessionControllersManager.isMediaTypeSupported( 'video'): BlinkLogger().log_info( "Opened %s camera at %0.fx%0.f resolution" % (SIPApplication.video_device.real_name, width, height)) self.aspect_ratio = width / float( height) if width > height else height / float(width) self.captureDeviceInput = AVCaptureDeviceInput.alloc( ).initWithDevice_error_(device, None) if self.captureDeviceInput: try: self.captureSession.addInput_(self.captureDeviceInput[0]) except ValueError as e: BlinkLogger().log_info( 'Failed to add camera input to capture session: %s' % str(e)) return else: BlinkLogger().log_info('Failed to aquire input %s' % self) return self.setWantsLayer_(True) self.videoPreviewLayer = AVCaptureVideoPreviewLayer.alloc( ).initWithSession_(self.captureSession) self.layer().addSublayer_(self.videoPreviewLayer) self.videoPreviewLayer.setFrame_(self.layer().bounds()) self.videoPreviewLayer.setAutoresizingMask_( kCALayerWidthSizable | kCALayerHeightSizable) self.videoPreviewLayer.setBackgroundColor_( CGColorGetConstantColor(kCGColorBlack)) self.videoPreviewLayer.setVideoGravity_( AVLayerVideoGravityResizeAspectFill) self.videoPreviewLayer.setCornerRadius_(5.0) self.videoPreviewLayer.setMasksToBounds_(True) self.setMirroring() self.stillImageOutput = AVCaptureStillImageOutput.new() pixelFormat = NSNumber.numberWithInt_(kCVPixelFormatType_32BGRA) self.stillImageOutput.setOutputSettings_( NSDictionary.dictionaryWithObject_forKey_( pixelFormat, kCVPixelBufferPixelFormatTypeKey)) self.captureSession.addOutput_(self.stillImageOutput) if self.captureSession and self.videoPreviewLayer: BlinkLogger().log_info('Start aquire local video %s' % self) self.videoPreviewLayer.setBackgroundColor_( NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 0, 0.4)) self.captureSession.startRunning()
def donateButtonPressed_(self, sender): NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_("https://paypal.com"))
def url_to_name(url): string_list = url.split('/') return string_list[2] try: activeList.initialize_me() except Exception: print('No json') try: while True: previous_site = "" new_window_name = (NSWorkspace.sharedWorkspace().activeApplication() ['NSApplicationName']) if new_window_name == 'Google Chrome': textOfMyScript = """tell app "google chrome" to get the url of the active tab of window 1""" s = NSAppleScript.initWithSource_(NSAppleScript.alloc(), textOfMyScript) results, err = s.executeAndReturnError_(None) new_window_name = url_to_name(results.stringValue()) if active_window_name != new_window_name: print(active_window_name) activity_name = active_window_name if not first_time: end_time = datetime.datetime.now() time_entry = TimeEntry(start_time, end_time, 0, 0, 0, 0)
continue ext = filename_extension(file) for method in self._writers: if method.file_extension() and ext != method.file_extension(): f = antiformat(f'[steel_blue3]{file}[/]') warn( f"Method [cyan2]{method.name()}[/] can't be used on {f}" ) else: method.write_link(file, record.link) # Misc. utilities # ............................................................................. _WORKSPACE = NSWorkspace.sharedWorkspace() # The code below is based in part on code posted by user "kuzzoooroo" on # 2014-01-23 to Stack Overflow at https://stackoverflow.com/a/21245832/743730 def file_is_alias(item): '''Returns True if the given "item" is a macOS Alias file.''' # mac alias files test positive as files but negative as links. if path.islink(item) or not path.isfile(item): return False uti, err = _WORKSPACE.typeOfFile_error_(path.realpath(item), None) if err: return False else: return uti == "com.apple.alias-file"
#!/usr/bin/python try: from AppKit import NSWorkspace except ImportError: print "Can't import AppKit -- maybe you're running python from brew?" print "Try running with Apple's /usr/bin/python instead." exit(1) from datetime import datetime from time import sleep 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 '%s: %s [%s]' % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), active_app['NSApplicationName'], active_app['NSApplicationPath']) sleep(1)
from AppKit import NSWorkspace import time open_window = "" while True: new_window = ( NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']) if open_window != new_window: open_window = new_window print(open_window) time.sleep(10)
def remove_app(bundle_ids): '''Removes bundle_ids from Notification Center database''' conn, curs = connect_to_db() for bundle_id in bundle_ids: if not bundleid_exists(bundle_id): print >> sys.stderr, ( "WARNING: %s not in Notification Center" % bundle_id) else: curs.execute("DELETE from app_info where bundleid IS '%s'" % (bundle_id)) commit_changes(conn) kill_notification_center() def set_flags(flags, bundle_id): '''Sets Notification Center flags for bundle_id''' conn, curs = connect_to_db() curs.execute("UPDATE app_info SET flags='%s' where bundleid='%s'" % (flags, bundle_id)) commit_changes(conn) def bundleid_exists(bundle_id): '''Returns a boolean telling us if the bundle_id is in the database.''' conn, curs = connect_to_db() curs.execute("SELECT bundleid from app_info WHERE bundleid IS '%s'" % bundle_id) matching_ids = [row[0] for row in curs.fetchall()] conn.close() return len(matching_ids) > 0 def get_matching_ids(match_string): '''Returns any bundle_ids matching the match_string''' conn, curs = connect_to_db() curs.execute("SELECT bundleid from app_info WHERE bundleid LIKE '%s'" % match_string) matching_ids = [row[0] for row in curs.fetchall()] conn.close() return matching_ids def get_flags(bundle_id): '''Returns flags for bundle_id''' conn, curs = connect_to_db() curs.execute("SELECT flags from app_info where bundleid='%s'" % (bundle_id)) try: flags = curs.fetchall()[0][0] except IndexError: flags = 0 conn.close() return int(flags) def get_show_count(bundle_id): '''Returns number of items to show in Notification Center for bundle_id''' conn, curs = connect_to_db() curs.execute("SELECT show_count from app_info where bundleid='%s'" % (bundle_id)) try: flags = curs.fetchall()[0][0] except IndexError: flags = 0 conn.close() return int(flags) def remove_system_center(): '''Sets alert style to 'none'' for all bundle_ids starting with _SYSTEM_CENTER_:. Not convinced this is a great idea, but there it is...''' set_alert('none', get_matching_ids('_SYSTEM_CENTER_:%')) 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 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 # flags are bits in a 16 bit(?) data structureDONT_SHOW_IN_CENTER = 1 << 0BADGE_ICONS = 1 << 1SOUNDS = 1 << 2BANNER_STYLE = 1 << 3ALERT_STYLE = 1 << 4UNKNOWN_5 = 1 << 5UNKNOWN_6 = 1 << 6UNKNOWN_7 = 1 << 7UNKNOWN_8 = 1 << 8UNKNOWN_9 = 1 << 9UNKNOWN_10 = 1 << 10UNKNOWN_11 = 1 << 11SUPPRESS_NOTIFICATIONS_ON_LOCKSCREEN = 1 << 12SHOW_PREVIEWS_ALWAYS = 1 << 13SUPPRESS_MESSAGE_PREVIEWS = 1 << 14UNKNOWN_15 = 1 << 15 def error_and_exit_if_not_bundle_exists(bundle_id): '''Print an error and exit if bundle_id doesn't exist.''' if not bundleid_exists(bundle_id): print >> sys.stderr, "%s not in Notification Center" % bundle_id exit(1) def get_alert_style(bundle_id): '''Print the alert style for bundle_id''' error_and_exit_if_not_bundle_exists(bundle_id) current_flags = get_flags(bundle_id) if current_flags & ALERT_STYLE: print "alerts" elif current_flags & BANNER_STYLE: print "banners" else: print "none" def get_show_on_lock_screen(bundle_id): '''Print state of "Show notifications on lock screen"''' error_and_exit_if_not_bundle_exists(bundle_id) current_flags = get_flags(bundle_id) if current_flags & SUPPRESS_NOTIFICATIONS_ON_LOCKSCREEN: print 'false' else: print 'true' def get_badge_app_icon(bundle_id): '''Print state of "Badge app icon"''' error_and_exit_if_not_bundle_exists(bundle_id) current_flags = get_flags(bundle_id) if current_flags & BADGE_ICONS: print 'true' else: print 'false' def get_notification_sound(bundle_id): '''Print state of "Play sound for notifications"''' error_and_exit_if_not_bundle_exists(bundle_id) current_flags = get_flags(bundle_id) if current_flags & SOUNDS: print 'true' else: print 'false'
def reveal_file(self, sender): workspace = NSWorkspace.sharedWorkspace() workspace.selectFile_inFileViewerRootedAtPath_(self.filepath, os.path.dirname(self.filepath))
from playsound import playsound try: import speech_recognition as speech except: system('pip3 install SpeechRecognition') import speech_recognition as speech try: from pynput import keyboard except: system('pip3 install pynput') from pynput import keyboard if name == "posix": from AppKit import NSWorkspace get_foreground_window = lambda: 1 if NSWorkspace.sharedWorkspace( ).activeApplication()['NSApplicationProcessIdentifier' ] == whatsapp_obj.return_pid() else 0 elif name == "nt": try: import win32gui except: system('pip3 install win32gui') import win32gui get_foreground_window = lambda: 1 if 'whatsapp' in win32gui.GetWindowText( win32gui.GetForegroundWindow()).lower( ) else 0 #check if web whatsapp is in foreground to trigger shortcuts get_keys = lambda: load(open('data/keys.keyfile', 'rb'))
def helpButtonPressed_(self, sender): # open help url NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_("Attribution"))
def _ED_is_running(self): for x in NSWorkspace.sharedWorkspace().runningApplications(): if x.bundleIdentifier() == 'uk.co.frontier.EliteDangerous': return True else: return False
#!/usr/bin/python # # DeltaWalker Launch and Merge script # Copyright (c) Zennaware GmbH, 2012. All rights reserved. # from AppKit import NSWorkspace import sys import os bundle_identifier = 'com.deltopia.deltawalker' helper_path = 'Contents/MacOS/DeltaWalker' app_path = NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier_(bundle_identifier) if app_path is None: error = 'Application with the bundle identifier "%s" does not exist' % (bundle_identifier) raise ValueError(error) os.system('"%s" "%s" "%s" "%s" -merged="%s"' % (os.path.join(app_path, helper_path), sys.argv[1], sys.argv[3], sys.argv[5], sys.argv[7]))
def active_app(self): """ :return: Name of active application. """ return NSWorkspace.sharedWorkspace() \ .activeApplication()['NSApplicationName']
#!/usr/bin/python # Prints current window focus. # See: https://apple.stackexchange.com/q/169277/22781 from AppKit import NSWorkspace import time workspace = NSWorkspace.sharedWorkspace() active_app = workspace.activeApplication()['NSApplicationName'] print('Active focus: ' + active_app) while True: time.sleep(1) prev_app = active_app print(workspace.activeApplication()['NSApplicationProcessIdentifier']) active_app = workspace.activeApplication()['NSApplicationName'] if prev_app != active_app: print('Focus changed to: ' + active_app)
def find_application_name(): """ Returns active app_name """ return NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName']
def is_cloudapp_installed(): bundle = "com.linebreak.CloudAppMacOSX" from AppKit import NSWorkspace return NSWorkspace.sharedWorkspace( ).absolutePathForAppBundleWithIdentifier_(bundle) != None
def on_release(key): active_app_name = NSWorkspace.sharedWorkspace().activeApplication( )['NSApplicationName'] key_logger.info('{0}, released, {1}'.format(key, active_app_name))
#!/usr/bin/python # Prints current active window. # See: https://stackoverflow.com/q/373020/55075 from AppKit import NSWorkspace active_app_name = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName() print(active_app_name)
import os import sys def packageIncludesKSDiff(path): bundle = NSBundle.bundleWithPath_(path) version = bundle.objectForInfoDictionaryKey_("CFBundleShortVersionString") if StrictVersion(version) >= StrictVersion('2.0.0'): return False else: return True path = NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier_( 'com.blackpixel.kaleidoscope') if path is None: path = NSWorkspace.sharedWorkspace( ).absolutePathForAppBundleWithIdentifier_('com.madebysofa.kaleidoscope') if packageIncludesKSDiff(path): path = os.path.join(path, 'Contents/MacOS/ksdiff') else: path = '/usr/local/bin/ksdiff' exists = NSFileManager.defaultManager().fileExistsAtPath_(path) if exists == False: raise ValueError('Unable to locate the ksdiff command line tool at %s' % path)