def toggle(self): if self.visible(): self.hide() NSUserDefaults.standardUserDefaults().setValue_forKey_(False, "ShowMyVideo") else: NSUserDefaults.standardUserDefaults().setBool_forKey_(True, "ShowMyVideo") self.show()
def windowResized(self, window): posSize = self.w.getPosSize() Height = posSize[3] if Height > self.closedWindowHeight and self.isResizing is False: print "set new Height", Height NSUserDefaults.standardUserDefaults().setInteger_forKey_(Height, "ToucheWindowHeight") self.windowHeight = Height
def set_selfcontrol_setting(key, value, username): """ sets a single default setting of SelfControl for the provied username """ NSUserDefaults.resetStandardUserDefaults() originalUID = os.geteuid() os.seteuid(getpwnam(username).pw_uid) CFPreferencesSetAppValue(key, value, "org.eyebeam.SelfControl") CFPreferencesAppSynchronize("org.eyebeam.SelfControl") NSUserDefaults.resetStandardUserDefaults() os.seteuid(originalUID)
def performDrag(self): if not self.currentLocation: return newOrigin = self.frame().origin offset_x = self.initialLocation.x - self.initialOrigin.x offset_y = self.initialLocation.y - self.initialOrigin.y newOrigin.x = self.currentLocation.x - offset_x newOrigin.y = self.currentLocation.y - offset_y if newOrigin.x < 10: newOrigin.x = 10 if newOrigin.y < 10: newOrigin.y = 10 if self.window().delegate().full_screen: parentFrame = NSScreen.mainScreen().visibleFrame() else: parentFrame = self.window().frame() if newOrigin.x > parentFrame.size.width - 10 - self.frame().size.width: newOrigin.x = parentFrame.size.width - 10 - self.frame().size.width if newOrigin.y > parentFrame.size.height - 30 - self.frame( ).size.height: newOrigin.y = parentFrame.size.height - 30 - self.frame( ).size.height if ((newOrigin.y + self.frame().size.height) > (parentFrame.origin.y + parentFrame.size.height)): newOrigin.y = parentFrame.origin.y + (parentFrame.size.height - self.frame().size.height) if abs(newOrigin.x - self.window().delegate().myVideoViewTL.frame().origin.x) > abs( newOrigin.x - self.window().delegate().myVideoViewTR.frame().origin.x): letter2 = "R" else: letter2 = "L" if abs(newOrigin.y - self.window().delegate().myVideoViewTL.frame().origin.y) > abs( newOrigin.y - self.window().delegate().myVideoViewBL.frame().origin.y): letter1 = "B" else: letter1 = "T" finalFrame = "myVideoView" + letter1 + letter2 self.start_origin = newOrigin self.final_origin = getattr(self.window().delegate(), finalFrame).frame().origin NSUserDefaults.standardUserDefaults().setValue_forKey_( letter1 + letter2, "MyVideoCorner") self.setFrameOrigin_(newOrigin)
def setCurrentHeight_(self, newHeight): """ Sets a new height for the Palette section. """ try: if newHeight >= self.minHeight() and newHeight <= self.maxHeight(): NSUserDefaults.standardUserDefaults().setInteger_forKey_(newHeight, self.dialogName + ".ViewHeight") except: self.logError(traceback.format_exc())
def get_selfcontrol_settings(username): """ returns all default settings of SelfControl for the provided username """ NSUserDefaults.resetStandardUserDefaults() originalUID = os.geteuid() os.seteuid(getpwnam(username).pw_uid) defaults = NSUserDefaults.standardUserDefaults() defaults.addSuiteNamed_("org.eyebeam.SelfControl") defaults.synchronize() result = defaults.dictionaryRepresentation() NSUserDefaults.resetStandardUserDefaults() os.seteuid(originalUID) return result
def LoadPreferences( self ): try: NSUserDefaults.standardUserDefaults().registerDefaults_( { "save.DemoInstancesGenerator.name": "Demo", "save.DemoInstancesGenerator.glyphs": "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z zero one two three four five seven eight period comma space hyphen b.calt f.calt h.calt k.calt l.calt f_t t_t A-cy Be-cy Ve-cy Ge-cy De-cy Ie-cy Io-cy Zhe-cy Ze-cy Ii-cy Iishort-cy Ka-cy El-cy Em-cy En-cy O-cy Pe-cy Er-cy Es-cy Te-cy U-cy Ef-cy Ha-cy Tse-cy Che-cy Sha-cy Shcha-cy Yeru-cy Softsign-cy Ereversed-cy Iu-cy Ia-cy a-cy be-cy ve-cy ge-cy de-cy ie-cy io-cy zhe-cy ze-cy ii-cy iishort-cy ka-cy el-cy em-cy en-cy o-cy pe-cy er-cy es-cy te-cy u-cy ef-cy ha-cy tse-cy che-cy sha-cy shcha-cy yeru-cy softsign-cy ereversed-cy iu-cy ia-cy .notdef ", } ) self.w.name.set( Glyphs.defaults["save.DemoInstancesGenerator.name"] ) self.w.glyphs.set( Glyphs.defaults["save.DemoInstancesGenerator.glyphs"] ) except: return False return True
def AppConfigWork(self): self.appconf_found.setText( hasAppConf(unicode(self.path_input.text())) and "Yes" or "No") if isValidLogPath(unicode(self.path_input.text())): if hasVerboseLogging(unicode(self.path_input.text())): self.verbose_enabled.setText("Yes") self.verbose_button.setEnabled(False) else: self.verbose_enabled.setText("No") self.verbose_button.setEnabled(True) else: self.verbose_enabled.setText("No") self.verbose_button.setEnabled(False) # Give advice on Mac users' Keyboard preferences if platform == 'darwin': self.appconf.setText(appconf) self.advice.setStyleSheet("font-size: 12pt;") # Adjust advice depending on whether users have to press F10 or fn-F10 try: from Foundation import NSUserDefaults, NSGlobalDomain screenshotkey = NSUserDefaults.standardUserDefaults( ).persistentDomainForName_(NSGlobalDomain)[ "com.apple.keyboard.fnState"] and 'F10' or 'fn-F10' except: screenshotkey = 'fn-F10' # Default setting, assuming an Apple keyboard # Advise if F10 is bound to a keyboard shortcut shortcutissue = '' try: # http://krypted.com/mac-os-x/defaults-symbolichotkeys/ for k, v in NSUserDefaults.standardUserDefaults( ).persistentDomainForName_("com.apple.symbolichotkeys")[ "AppleSymbolicHotKeys"].iteritems(): if v['enabled'] and v['value']['parameters'][ 1] == 109 and v['value']['parameters'][2] == 0: if k == '33': # F10 was the default binding for "App Exposé" under OSX 10.6 shortcutissue = '<p>The F10 key is currently assigned to the shortcut “Application windows”. You will need to remove this assignment in  → System Preferences → <a href="file:/System/Library/PreferencePanes/Expose.prefPane/">Mission Control</a>.</p>' else: shortcutissue = '<p>The F10 key is currently assigned to a keyboard shortcut. You will need to disable or remove this assignment in  → System Preferences → <a href="file:/System/Library/PreferencePanes/Keyboard.prefPane/">Keyboard</a> → Shortcuts.</p>' break except: pass else: screenshotkey = 'F10' shortcutissue = '' self.advice.setText(self.advice.text().replace( '%1', screenshotkey).replace('%2', shortcutissue))
def snapToCorner(self): newOrigin = self.frame().origin if abs(newOrigin.x - self.window().delegate().myVideoViewTL.frame().origin.x) > abs(newOrigin.x - self.window().delegate().myVideoViewTR.frame().origin.x): letter2 = "R" else: letter2 = "L" if abs(newOrigin.y - self.window().delegate().myVideoViewTL.frame().origin.y) > abs(newOrigin.y - self.window().delegate().myVideoViewBL.frame().origin.y): letter1 = "B" else: letter1 = "T" finalFrame = "myVideoView" + letter1 + letter2 self.setFrameOrigin_(getattr(self.window().delegate(), finalFrame).frame().origin) NSUserDefaults.standardUserDefaults().setValue_forKey_(letter1 + letter2, "MyVideoCorner")
def __init__(self): major, minor = platform.mac_ver()[0].split('.')[0:2] if NSApp.delegate().applicationName in ('Blink Lite', 'SIP2SIP'): return if (int(major) == 10 and int(minor) >= 7) or int(major) > 10: self.notification_center = NotificationCenter() enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled") if enabled is None: NSUserDefaults.standardUserDefaults().setObject_forKey_("Enabled", "iCloudSyncEnabled") self.start() elif enabled == "Enabled" : self.start() NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "userDefaultsDidChange:", "NSUserDefaultsDidChangeNotification", NSUserDefaults.standardUserDefaults())
def applicationDidFinishLaunching_(self, notification): #activate logging with ToggleProxy -logging 1 self.shouldLog = NSUserDefaults.standardUserDefaults().boolForKey_("logging") # load icon files self.active_image = NSImage.imageNamed_("StatusBarImage") self.inactive_image = NSImage.imageNamed_("StatusBarImage-inactive") self.no_network_image = NSImage.imageNamed_("StatusBarImage-noNetwork") self.active_image.setTemplate_(True) self.inactive_image.setTemplate_(True) self.no_network_image.setTemplate_(True) # make status bar item self.statusitem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) self.statusitem.retain() self.statusitem.setHighlightMode_(False) self.statusitem.setEnabled_(True) # insert a menu into the status bar item self.menu = NSMenu.alloc().init() self.statusitem.setMenu_(self.menu) # open connection to the dynamic (configuration) store self.store = SCDynamicStoreCreate(None, "name.klep.toggleproxy", self.dynamicStoreCallback, None) self.prefDict = SCNetworkProtocolGetConfiguration(SCNetworkServiceCopyProtocol(self.service, kSCNetworkProtocolTypeProxies)) self.constructMenu() self.watchForProxyOrIpChanges() self.updateUI() self.setEnvVariables()
def _menu_bar_icon(run_or_pause): """0 for 'running' icon and 1 for 'paused' icon""" mode = NSUserDefaults.standardUserDefaults().stringForKey_( 'AppleInterfaceStyle') black = ['menu_bar_64_black_running.png', 'menu_bar_64_black_paused.png'] white = ['menu_bar_64_white_running.png', 'menu_bar_64_white_paused.png'] return white[run_or_pause] if not mode else black[run_or_pause]
def pre_appdata_use_startup(appdata_path): preload_dlls(unhandled_exc_handler) try: DOMAIN = NSString.alloc().initWithString_('com.apple.LaunchServices') KEYS = (NSString.alloc().initWithString_('LSArchitecturesForX86_64'), NSString.alloc().initWithString_('LSArchitecturesForX86_64v2')) APP = NSString.alloc().initWithString_('com.getdropbox.dropbox') UserDefaults = NSUserDefaults.standardUserDefaults() launchServices = UserDefaults.persistentDomainForName_(DOMAIN) if launchServices: for key in KEYS: apps = launchServices.objectForKey_(key) if apps and apps.get(APP): apps.removeObjectForKey_(APP) UserDefaults.setObject_forKey_(apps, key) UserDefaults.setPersistentDomain_forName_(launchServices, DOMAIN) UserDefaults.synchronize() report_bad_assumption("User had 'Open using Rosetta' set.") except Exception: unhandled_exc_handler() if MAC_VERSION <= LEOPARD: try: psn = ProcessSerialNumber() Carbon.GetCurrentProcess(psn) TRACE('On Leopard or lower: PSN is %r', (psn.lowLongOfPSN, psn.highLongOfPSN)) except Exception: unhandled_exc_handler() return arch.fixperms.check_and_fix_permissions(appdata_path)
def init(self): if self: NSBundle.loadNibNamed_owner_("EnrollmentWindow", self) icloud_sync_enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled") self.syncWithiCloudCheckbox.setHidden_(not icloud_sync_enabled) self.selectRadio_(self.radioMatrix) if not SIPManager().validateAddAccountAction(): self.nextButton.setEnabled_(False) self.purchaseProLabel.setHidden_(False) if NSApp.delegate().contactsWindowController.first_run: NotificationCenter().add_observer(self, name='SIPAccountManagerDidAddAccount') if NSApp.delegate().allowed_domains: self.allowed_domains = NSApp.delegate().allowed_domains self.syncWithiCloudCheckbox.setHidden_(True) self.syncWithiCloudCheckbox.setState_(NSOffState) self.domainButton.setHidden_(True) self.addressText.cell().setPlaceholderString_('user@' + self.allowed_domains[0]) if not NSApp.delegate().icloud_enabled: self.syncWithiCloudCheckbox.setHidden_(True) return self
def LoadPreferences( self ): try: NSUserDefaults.standardUserDefaults().registerDefaults_( { "com.mekkablue.FindAndReplaceInInstanceParameters.availableParameters": "0", "com.mekkablue.FindAndReplaceInInstanceParameters.find": "", "com.mekkablue.FindAndReplaceInInstanceParameters.replace": "" } ) self.w.find.set( Glyphs.defaults["com.mekkablue.FindAndReplaceInInstanceParameters.find"] ) self.w.replace.set( Glyphs.defaults["com.mekkablue.FindAndReplaceInInstanceParameters.replace"] ) self.w.availableParameters.set( Glyphs.defaults["com.mekkablue.FindAndReplaceInInstanceParameters.availableParameters"] ) except: return False return True
def awakeFromNib(self): defaults = NSUserDefaults.standardUserDefaults() def default(k, v, typeCheck=None): rval = defaults.objectForKey_(k) if typeCheck is not None and rval is not None: try: rval = typeCheck(rval) except TypeError: NSLog( "%s failed type check %s with value %s", k, typeCheck.__name__, rval, ) rval = None if rval is None: defaults.setObject_forKey_(v, k) rval = v return rval self.host = default("AsyncPythonInterpreterInterpreterHost", "127.0.0.1", str) self.port = default("AsyncPythonInterpreterInterpreterPort", 0, int) self.interpreterPath = default("AsyncPythonInterpreterInterpreterPath", "/usr/bin/python", str) self.scriptPath = (type(self).bundleForClass().pathForResource_ofType_( "tcpinterpreter", "py"))
def __init__(self): self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname) if not isdir(self.app_dir): mkdir(self.app_dir) self.plugin_dir = join(self.app_dir, 'plugins') if not isdir(self.plugin_dir): mkdir(self.plugin_dir) self.home = expanduser('~') self.respath = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable), pardir, 'Resources')) or dirname(__file__) if not getattr(sys, 'frozen', False): # Don't use Python's settings if interactive self.bundle = 'uk.org.marginal.%s' % appname.lower() NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.bundle self.bundle = NSBundle.mainBundle().bundleIdentifier() self.defaults = NSUserDefaults.standardUserDefaults() settings = self.defaults.persistentDomainForName_(self.bundle) or {} self.settings = dict(settings) # Check out_dir exists if not self.get('outdir') or not isdir(self.get('outdir')): self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0])
def show(self): BlinkLogger().log_debug('Show %s' % self) aspect_ratio = self.videoView.aspect_ratio self.visible = True self.videoView.show() if self.close_timer is not None and self.close_timer.isValid(): self.close_timer.invalidate() self.close_timer = None self.window().setAlphaValue_(ALPHA) userdef = NSUserDefaults.standardUserDefaults() savedFrame = userdef.stringForKey_(self.window().frameAutosaveName()) if savedFrame: x, y, w, h = str(savedFrame).split()[:4] frame = NSMakeRect(int(x), int(y), int(w), int(h)) self.window().setFrame_display_(frame, True) frame = self.window().frame() currentSize = frame.size scaledSize = currentSize if aspect_ratio is not None: scaledSize.height = scaledSize.width / aspect_ratio frame.size = scaledSize self.window().setFrame_display_animate_(frame, True, False) self.window().orderFront_(None)
def init(self): if self: NSBundle.loadNibNamed_owner_("EnrollmentWindow", self) icloud_sync_enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled") self.syncWithiCloudCheckbox.setHidden_(not icloud_sync_enabled) self.selectRadio_(self.radioMatrix) if not SIPManager().validateAddAccountAction(): self.nextButton.setEnabled_(False) self.purchaseProLabel.setHidden_(False) if NSApp.delegate().contactsWindowController.first_run: NotificationCenter().add_observer(self, name='SIPAccountManagerDidAddAccount') if NSApp.delegate().applicationName == 'SIP2SIP': self.allowed_domains = ['sip2sip.info'] self.syncWithiCloudCheckbox.setHidden_(True) self.syncWithiCloudCheckbox.setState_(NSOffState) self.domainButton.setHidden_(True) self.addressText.cell().setPlaceholderString_('*****@*****.**') if NSApp.delegate().applicationName == 'Blink': self.syncWithiCloudCheckbox.setHidden_(True) return self
def __init__(self): self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname) if not isdir(self.app_dir): mkdir(self.app_dir) self.plugin_dir = join(self.app_dir, 'plugins') if not isdir(self.plugin_dir): mkdir(self.plugin_dir) self.internal_plugin_dir = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable.decode(sys.getfilesystemencoding())), pardir, 'Library', 'plugins')) or join(dirname(__file__), 'plugins') self.default_journal_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], 'Frontier Developments', 'Elite Dangerous') self.default_interaction_dir = join(self.default_journal_dir, 'CommanderHistory') self.home = expanduser('~') self.respath = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable.decode(sys.getfilesystemencoding())), pardir, 'Resources')) or dirname(__file__) if not getattr(sys, 'frozen', False): # Don't use Python's settings if interactive self.identifier = 'uk.org.marginal.%s' % appname.lower() NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.identifier else: self.identifier = NSBundle.mainBundle().bundleIdentifier() self.defaults = NSUserDefaults.standardUserDefaults() self.settings = dict(self.defaults.persistentDomainForName_(self.identifier) or {}) # make writeable # Check out_dir exists if not self.get('outdir') or not isdir(self.get('outdir')): self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0])
def macos_set_correct_icon(self): if Platform.current() == Platform.MACOS: if (NSUserDefaults.standardUserDefaults().stringForKey_( "AppleInterfaceStyle") == "Dark"): self.setIcon(self.c.gui.systray_icon_dark) else: self.setIcon(self.c.gui.systray_icon_light)
def __init__(self, ud=None): if ud is None: from Foundation import NSUserDefaults self.ud = NSUserDefaults.standardUserDefaults() else: self.ud = ud
def userDefaultsDidChange_(self, notification): enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled") if enabled == "Enabled": if self.cloud_storage is None: self.start() self.sync() elif self.cloud_storage is not None: self.stop()
def LoadPreferences(self): try: NSUserDefaults.standardUserDefaults().registerDefaults_({ "save.TextFilter.inpt": "", "save.TextFilter.outpt": "", "save.TextFilter.glyphs": "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z . , space", }) self.w.inpt.set(Glyphs.defaults["save.TextFilter.inpt"]) self.w.outpt.set(Glyphs.defaults["save.TextFilter.outpt"]) self.w.glyphs.set(Glyphs.defaults["save.TextFilter.glyphs"]) except: return False return True
def observe(self, domain, key): self.domain = domain self.key = key if self: self.defaults = NSUserDefaults.alloc().initWithSuiteName_( self.domain) self.defaults.addObserver_forKeyPath_options_context_( self, self.key, NSKeyValueObservingOptionNew, None) return self
def current_them() -> str: """Get the current OS them.""" try: theme = NSUserDefaults.standardUserDefaults().stringForKey_( "AppleInterfaceStyle") except Exception: return "" else: return theme.lower()
def applicationWillTerminate_(self, notification): """When the application intends to terminate, kill all running commands and persist the configuration.""" print "Application is terminating" ds=self.table.dataSource() defaults=NSUserDefaults.standardUserDefaults() defaults.setObject_forKey_(ds.toArray(), "cmds") for cmd in self.pids.values(): cmd.stopRunning()
def userDefaultsDidChange_(self, notification): enabled = NSUserDefaults.standardUserDefaults().stringForKey_( "iCloudSyncEnabled") if enabled == "Enabled": if self.cloud_storage is None: self.start() self.sync() elif self.cloud_storage is not None: self.stop()
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 AppConfigWork(self): self.appconf_found.setText(hasAppConf(unicode(self.path_input.text())) and "Yes" or "No") if isValidLogPath(unicode(self.path_input.text())): if hasVerboseLogging(unicode(self.path_input.text())): self.verbose_enabled.setText("Yes") self.verbose_button.setEnabled(False) else: self.verbose_enabled.setText("No") self.verbose_button.setEnabled(True) else: self.verbose_enabled.setText("No") self.verbose_button.setEnabled(False) # Give advice on Mac users' Keyboard preferences if platform=='darwin': self.appconf.setText(appconf) self.advice.setStyleSheet("font-size: 12pt;") # Adjust advice depending on whether users have to press F10 or fn-F10 try: from Foundation import NSUserDefaults, NSGlobalDomain screenshotkey = NSUserDefaults.standardUserDefaults().persistentDomainForName_(NSGlobalDomain)["com.apple.keyboard.fnState"] and 'F10' or 'fn-F10' except: screenshotkey = 'fn-F10' # Default setting, assuming an Apple keyboard # Advise if F10 is bound to a keyboard shortcut shortcutissue = '' try: # http://krypted.com/mac-os-x/defaults-symbolichotkeys/ for k, v in NSUserDefaults.standardUserDefaults().persistentDomainForName_("com.apple.symbolichotkeys")["AppleSymbolicHotKeys"].iteritems(): if v['enabled'] and v['value']['parameters'][1] == 109 and v['value']['parameters'][2] == 0: if k == '33': # F10 was the default binding for "App Exposé" under OSX 10.6 shortcutissue = '<p>The F10 key is currently assigned to the shortcut “Application windows”. You will need to remove this assignment in  → System Preferences → <a href="file:/System/Library/PreferencePanes/Expose.prefPane/">Mission Control</a>.</p>' else: shortcutissue = '<p>The F10 key is currently assigned to a keyboard shortcut. You will need to disable or remove this assignment in  → System Preferences → <a href="file:/System/Library/PreferencePanes/Keyboard.prefPane/">Keyboard</a> → Shortcuts.</p>' break except: pass else: screenshotkey = 'F10' shortcutissue = '' self.advice.setText(self.advice.text().replace('%1', screenshotkey).replace('%2', shortcutissue))
def currentHeight(self): """ The current height of the Palette section. Used for storing the current resized state. If you have a fixed height, you can also return the height in pixels """ try: # return 150 return NSUserDefaults.standardUserDefaults().integerForKey_(self.dialogName + ".ViewHeight") except: self.logError(traceback.format_exc())
def interface_style(): """Return current platform interface style (light or dark).""" try: # currently only works on macOS from Foundation import NSUserDefaults as NSUD except ImportError: return None style = NSUD.standardUserDefaults().stringForKey_("AppleInterfaceStyle") if style == "Dark": return "dark" else: return "light"
def uses_dark_mode(): """ This function detects if we are running in dark mode (e.g. macOS dark mode). Returns None if the interface style cannot be determined, otherwise a boolean. """ if sys.platform == 'darwin': from Foundation import NSUserDefaults stdud = NSUserDefaults.standardUserDefaults() return stdud.stringForKey_("AppleInterfaceStyle") == "Dark" return None
def initDefaults(self): defaults=NSUserDefaults.standardUserDefaults() ob=defaults.objectForKey_("cmds") if ob is not None: ds=self.table.dataSource() ds.loadArray(ob) for cmd in ds.cmds: if cmd.shouldBeRunning(): self.performSelector_withObject_afterDelay_('runCommand:', cmd, 0.0) self.table.reloadData()
def load_settings(): """ Load zen coding's settings, combined with user-defined snippets """ # First, check if the user even wants this to happen defaults = NSUserDefaults.standardUserDefaults() convert_to_zen = defaults.boolForKey_('TEAConvertUserSnippetsToZen') if convert_to_zen: orig_date = os.path.getmtime(plist_path) need_reload = globals()['_prev_settings'] is None # Does our cache path exist and is writable? cache_dir_exists = os.path.isdir(cache_folder) if not cache_dir_exists: # Attempt to create the cache folder try: os.makedirs(cache_folder, 0755) cache_dir_exists = True except os.error: NSLog('TEA Error: Cannot create zen coding cache path for user snippets') # In worst case scenario, we can't read or write to the cache file # so we'll need to read from preferences every time # This variable tracks the user snippets in case of that eventuality _data = None # check if cached file exists and up-to-date if cache_dir_exists and (not os.path.exists(cache_file) or \ os.path.getmtime(cache_file) < orig_date): # need to reparse and cache data _data = _read_settings_from_app() try: fp = open(cache_file, 'wb') pickle.dump(_data, fp) fp.close() except IOError: NSLog('TEA Error: Zen user snippets cache file is not writable') need_reload = True if need_reload: try: fp = open(cache_file, 'rb') user_settings = pickle.load(fp) fp.close() except IOError: NSLog('TEA Error: Zen user snippets cache file is not readable') user_settings = _data globals()['_prev_settings'] = stparser.get_settings(user_settings) return globals()['_prev_settings'] else: # They don't want to load in user snippets as zen snippets return stparser.get_settings()
def add_replacements_to_defaults(): defaults = NSUserDefaults.standardUserDefaults() replacements = defaults.objectForKey_('NSUserDictionaryReplacementItems').mutableCopy() existing = set( x['replace'] for x in replacements ) for key,value in my_replacements(): if not key in existing: replacements.append({'replace': key, 'with' : value, 'on' : 1}) defaults.setObject_forKey_inDomain_(replacements, 'NSUserDictionaryReplacementItems', NSGlobalDomain) defaults.synchronize()
def __init__(self): NSUserDefaults.standardUserDefaults().registerDefaults_({"ToucheWindowHeight":340}) self.windowHeight = NSUserDefaults.standardUserDefaults().integerForKey_("ToucheWindowHeight") self.minWindowHeight = 340 if self.windowHeight < self.minWindowHeight: self.windowHeight = self.minWindowHeight self.closedWindowHeight = 100 self.w = FloatingWindow((180, self.windowHeight), u'Touché!', minSize=(180,340), maxSize=(250,898)) self.w.bind("resize", self.windowResized) self.isResizing = False p = 10 w = 160 # options self.w.options = Group((0, 0, 180, 220)) buttons = { "checkSelBtn": {"text": "Check selected glyphs", "callback": self.checkSel, "y": p}, } for button, data in buttons.iteritems(): setattr(self.w.options, button, Button((p, data["y"], w - 22, 22), data["text"], callback=data["callback"], sizeStyle="small")) self.w.options.zeroCheck = CheckBox((p, 35, w, 20), "Ignore zero-width glyphs", value=True, sizeStyle="small") self.w.options.progress = ProgressSpinner((w - 8, 13, 16, 16), sizeStyle="small") # results self.w.results = Group((0, 220, 180, -0)) self.w.results.show(False) textBoxes = {"stats": -34, "result": -18} for box, y in textBoxes.iteritems(): setattr(self.w.results, box, TextBox((p, y, w, 14), "", sizeStyle="small")) # list and preview self.w.outputList = List((0,58,-0,-40), [{"left glyph": "", "right glyph": ""}], columnDescriptions=[{"title": "left glyph", "width": 90}, {"title": "right glyph"}], showColumnTitles=False, allowsMultipleSelection=False, enableDelete=False, selectionCallback=self.showPair) self.w.outputList._setColumnAutoresizing() self._resizeWindow(False) self.w.open()
def LoadPreferences( self ): try: ''' MAKE DEFAULTS DICT TO INJECT INTO NSUserDefaults ''' collectedDefaults = {} collectedDefaults["%s.glyphInput" % self.vID] = "a" collectedDefaults["%s.skipComponentCheck" % self.vID] = "True" collectedDefaults["%s.skipKGMembersCheck" % self.vID] = "True" collectedDefaults["%s.skipAlreadyKernedLeftCheck" % self.vID] = "False" collectedDefaults["%s.skipAlreadyKernedRightCheck" % self.vID] = "False" collectedDefaults["%s.pointSize" % self.vID] = "250" collectedDefaults["%s.deactivateReporterUI" % self.vID] = "True" collectedDefaults["%s.separateTabsUI" % self.vID] = "False" collectedDefaults["%s.UINotes" % self.vID] = "None" for i, thisCat in enumerate(self.catToSkipUI): collectedDefaults["%s.skipCategory%s" % (self.vID, str(i+1) ) ] = "False" # print collectedDefaults NSUserDefaults.standardUserDefaults().registerDefaults_( collectedDefaults ) ''' SET THE UI ELEMENTS WITH VALUES FROM THE PREFERENCES ''' if self.Glyphs.defaults["%s.glyphInput" % self.vID] in self.allGlyphsInFont: self.w.glyphInput.set( self.Glyphs.defaults["%s.glyphInput" % self.vID] ) else: self.w.glyphInput.set( self.firstGlyphInFont ) # allGlyphsInFont[0] # Fallback Layer if user switched from one font to another and the stored glyph is not available self.w.skipComponentCheck.set( self.Glyphs.defaults["%s.skipComponentCheck" % self.vID] ) self.w.skipKGMembersCheck.set( self.Glyphs.defaults["%s.skipKGMembersCheck" % self.vID] ) self.w.skipAlreadyKernedLeftCheck.set( self.Glyphs.defaults["%s.skipAlreadyKernedLeftCheck" % self.vID] ) self.w.skipAlreadyKernedRightCheck.set( self.Glyphs.defaults["%s.skipAlreadyKernedRightCheck" % self.vID] ) for i, thisCat in enumerate(self.catToSkipUI): exec('self.w.skipCategory%i.set( self.Glyphs.defaults["%s.skipCategory%s"] )' % (i+1, self.vID, i+1) ) self.w.pointSize.set( self.Glyphs.defaults["%s.pointSize" % self.vID] ) self.w.deactivateReporterUI.set( self.Glyphs.defaults["%s.deactivateReporterUI" % self.vID] ) self.w.separateTabsUI.set( self.Glyphs.defaults["%s.separateTabsUI" % self.vID] ) self.d.UINotes.set( self.Glyphs.defaults["%s.UINotes" % self.vID] ) except: print traceback.format_exc() return False return True
def main(): prefs_version = "0.1" parser = argparse.ArgumentParser() parser.add_argument("app_id", metavar="APP_ID", help="the app identifier or preference domain") parser.add_argument( "keys", nargs="*", metavar="KEY", help= "preference keys to show. When no key is given all values will be shown" ) parser.add_argument('--version', help='prints the version', action='version', version=prefs_version) parser.add_argument( "-g", "--globals", action="store_true", help="show values from GlobalPreferences files as well") parser.add_argument("-V", "--value", action="store_true", help="show only the value, no other information") parser.add_argument("-p", "--path", action="store_true", help="print path to plist file instead of domain") args = parser.parse_args() app_id = args.app_id showGlobals = args.globals if len(args.keys) == 0: app_defaults = NSUserDefaults.alloc().initWithSuiteName_(app_id) keys = app_defaults.dictionaryRepresentation().keys() else: keys = args.keys # set showGlobals regardless so all keys will be shown showGlobals = True for key in keys: if args.value: print repr(get_pref_value(app_id, key)) else: print_detail(app_id, key, showGlobals, args.path)
def session_didGenerateLoginCredentials_forUserName_(self, session, credentials, username): NSLog("storing credentials: %@", credentials) defaults = NSUserDefaults.standardUserDefaults() storedCredentials = defaults.valueForKey_("SpotifyUsers") if storedCredentials is None: storedCredentials = {} else: storedCredentials = storedCredentials.mutableCopy() storedCredentials[username] = credentials storedCredentials["DEFAULT_USER"] = username defaults.setValue_forKey_(storedCredentials, "SpotifyUsers")
def set_user_interface_language(code): if platform == 'mac': from Foundation import NSAutoreleasePool, NSString, NSUserDefaults arp = NSAutoreleasePool.alloc().init() s = NSString.alloc().initWithString_(APPLE_LANGUAGES) defaults = NSUserDefaults.standardUserDefaults() if code == '': TRACE('Setting language defaults to system language.') defaults.removeObjectForKey_(s) else: TRACE('Updating language defaults to %r.', code) defaults.setObject_forKey_([code], s) defaults.synchronize()
def __init__(self): self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname) if not isdir(self.app_dir): mkdir(self.app_dir) self.bundle = getattr(sys, 'frozen', False) and NSBundle.mainBundle().bundleIdentifier() or 'uk.org.marginal.%s' % appname.lower() # Don't use Python's settings if interactive self.defaults = NSUserDefaults.standardUserDefaults() settings = self.defaults.persistentDomainForName_(self.bundle) or {} self.settings = dict(settings) # Check out_dir exists if not self.get('outdir') or not isdir(self.get('outdir')): self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0])
def alert(title=None, message='', ok=None, cancel=None, other=None, icon_path=None): """Generate a simple alert window. .. versionchanged:: 0.2.0 Providing a `cancel` string will set the button text rather than only using text "Cancel". `title` is no longer a required parameter. .. versionchanged:: 0.3.0 Add `other` button functionality as well as `icon_path` to change the alert icon. :param title: the text positioned at the top of the window in larger font. If ``None``, a default localized title is used. If not ``None`` or a string, will use the string representation of the object. :param message: the text positioned below the `title` in smaller font. If not a string, will use the string representation of the object. :param ok: the text for the "ok" button. Must be either a string or ``None``. If ``None``, a default localized button title will be used. :param cancel: the text for the "cancel" button. If a string, the button will have that text. If `cancel` evaluates to ``True``, will create a button with text "Cancel". Otherwise, this button will not be created. :param other: the text for the "other" button. If a string, the button will have that text. Otherwise, this button will not be created. :param icon_path: a path to an image. If ``None``, the applications icon is used. :return: a number representing the button pressed. The "ok" button is ``1`` and "cancel" is ``0``. """ message = text_type(message) message = message.replace('%', '%%') if title is not None: title = text_type(title) _internal.require_string_or_none(ok) if not isinstance(cancel, string_types): cancel = 'Cancel' if cancel else None alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_( title, ok, cancel, other, message) if NSUserDefaults.standardUserDefaults().stringForKey_( 'AppleInterfaceStyle') == 'Dark': alert.window().setAppearance_( AppKit.NSAppearance.appearanceNamed_( 'NSAppearanceNameVibrantDark')) alert.setAlertStyle_(0) # informational style if icon_path is not None: icon = _nsimage_from_file(icon_path) alert.setIcon_(icon) _log('alert opened with message: {0}, title: {1}'.format( repr(message), repr(title))) return alert.runModal()
def write_defaults(domain, key, value): # Returns whether the key in the domain is updated from Foundation import NSUserDefaults defaults = NSUserDefaults.standardUserDefaults() defaults_for_domain = defaults.persistentDomainForName_(domain) if not defaults_for_domain: return False old_value = defaults_for_domain.get(key) if old_value == value: return False mutable_defaults_for_domain = defaults_for_domain.mutableCopy() mutable_defaults_for_domain[key] = value defaults.setPersistentDomain_forName_(mutable_defaults_for_domain, domain) defaults.synchronize() return True
def setWallpaper(self, filename): self._logger.debug("set wallpaper to {0}".format(filename)) self.UserDefaults = NSUserDefaults.standardUserDefaults() self.deskTop = self.UserDefaults.persistentDomainForName_("com.apple.desktop") self.bgs = self.deskTop.objectForKey_("Background").objectForKey_('spaces').objectForKey_('') for bg in self.bgs: try: value = self.bgs[bg]["ImageFilePath"] if value: self.bgs[bg]["ImageFilePath"] = filename self.bgs[bg]["NewImageFilePath"] = filename except KeyError: print("error") self.saveUserDefaults() self.refreshDock()
def applicationDidFinishLaunching_(self, _): currentVersion = NSBundle.mainBundle().infoDictionary()["CFBundleVersion"] NSLog("Starting Yaybu version %s" % currentVersion) userDefaults = NSUserDefaults.standardUserDefaults() lastVersion = userDefaults.stringForKey_("version") if not lastVersion: NSLog("Detected that this is a first run!") self.applicationFirstRun() if not lastVersion or lastVersion != currentVersion: NSLog("Version changed from %s to %s" % (lastVersion, currentVersion)) self.applicationVersionChanged(lastVersion, currentVersion) userDefaults.setObject_forKey_(currentVersion, "version")
def init(self): self = super(VideoMirrorWindowController, self).init() if self: NSBundle.loadNibNamed_owner_("VideoMirrowWindow", self) userdef = NSUserDefaults.standardUserDefaults() savedFrame = userdef.stringForKey_("NSWindow Frame MirrorWindow") if savedFrame: x, y, w, h = str(savedFrame).split()[:4] frame = NSMakeRect(int(x), int(y), int(w), int(h)) self.window.setFrame_display_(frame, True) self.window.setAlphaValue_(0.9) return self
def _mac_get_system_languages(): assert platform == 'mac' from Foundation import NSAutoreleasePool, NSString, NSUserDefaults arp = NSAutoreleasePool.alloc().init() s = NSString.alloc().initWithString_(APPLE_LANGUAGES) try: from pymac.helpers.core import get_preference langs = list(get_preference('com.apple.systempreferences', APPLE_LANGUAGES)) TRACE('_mac_get_system_languages real: %r', langs) return langs except Exception: unhandled_exc_handler() langs = NSUserDefaults.standardUserDefaults().get(s) TRACE('_mac_get_system_languages from user: %r', langs) return langs
def read(bundle): ''' Read the defaults for the given application bundle identifier. bundle A reverse-dns style name of the application bundle id to read. .. code-block:: bash salt '*' plist.read com.apple.Finder ''' defaults = NSUserDefaults.standardUserDefaults() defaults.addSuiteNamed_(bundle) contents = defaults.dictionaryRepresentation() return contents
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 login_saved_credentials(self): defaults = NSUserDefaults.standardUserDefaults() storedCredentials = defaults.valueForKey_("SpotifyUsers") if not storedCredentials: return False if not "DEFAULT_USER" in storedCredentials: return False username = storedCredentials["DEFAULT_USER"] credentials = storedCredentials[username] if not credentials: return False SPSession.sharedSession().attemptLoginWithUserName_existingCredential_(username, credentials) return True
def _convert_user_snippets_to_zen_settings(): defaults = NSUserDefaults.standardUserDefaults() snippets = defaults.objectForKey_('UserSnippets1.0') if snippets is not None: snips = {} abbrs = {} for item in snippets: if 'snippetString' in item and 'title' in item: abbr_name = 'triggerString' in item and item[ 'triggerString'] or item['title'] if re_full_tag.match(item['snippetString']): abbrs[abbr_name] = item['snippetString'] else: snips[abbr_name] = item['snippetString'] return {'common': {'snippets': snips, 'abbreviations': abbrs}} return None
def run(self): """Launch the window. :class:`rumps.Window` instances can be reused to retrieve user input as many times as needed. :return: a :class:`rumps.rumps.Response` object that contains the text and the button clicked as an integer. """ _log(self) if NSUserDefaults.standardUserDefaults().stringForKey_( 'AppleInterfaceStyle') == 'Dark': self._alert.window().setAppearance_( AppKit.NSAppearance.appearanceNamed_( 'NSAppearanceNameVibrantDark')) clicked = self._alert.runModal() % 999 if clicked > 2 and self._cancel: clicked -= 1 self._textfield.validateEditing() text = self._textfield.stringValue() self.default_text = self._default_text # reset default text return Response(clicked, text)