def set_pref(pref_name, pref_value): """Sets a preference, See prefs.py for details""" CFPreferencesSetValue(pref_name, pref_value, BUNDLE_ID, kCFPreferencesAnyUser, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize(BUNDLE_ID) print "set pref" try: CFPreferencesSetValue(pref_name, pref_value, BUNDLE_ID, kCFPreferencesAnyUser, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize(BUNDLE_ID) except Exception: pass
def set_pref(pref_name, pref_value): """ Sets a preference """ # pylint: disable=E0602 CFPreferencesSetAppValue(pref_name, pref_value, BUNDLE_ID) CFPreferencesAppSynchronize(BUNDLE_ID)
def disable_fde_autologin(): '''Disables autologin to the unlocking user's account on a FileVault- encrypted machines.''' # See https://support.apple.com/en-us/HT202842 # We attempt to store the original value of com.apple.loginwindow # DisableFDEAutoLogin so if the local admin has set it to True for #reasons # we don't inadvertently clear it when clearing bootstrap mode # is OriginalDisableFDEAutoLogin already set? If so, bootstrap mode was # already enabled, and never properly cleared. Don't stomp on it. original_value = CFPreferencesCopyValue('OriginalDisableFDEAutoLogin', 'com.apple.loginwindow', kCFPreferencesAnyUser, kCFPreferencesCurrentHost) if not original_value: # get the current value of DisableFDEAutoLogin if any original_value = CFPreferencesCopyValue('DisableFDEAutoLogin', 'com.apple.loginwindow', kCFPreferencesAnyUser, kCFPreferencesCurrentHost) if not original_value: # we need a way to record the original value was not set, # and we can't store None... original_value = '<not set>' # store it so we can restore it later CFPreferencesSetValue('OriginalDisableFDEAutoLogin', original_value, 'com.apple.loginwindow', kCFPreferencesAnyUser, kCFPreferencesCurrentHost) # set com.apple.loginwindow DisableFDEAutoLogin to True CFPreferencesSetValue('DisableFDEAutoLogin', True, 'com.apple.loginwindow', kCFPreferencesAnyUser, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize('com.apple.loginwindow')
def __init__(self): """Create a new Preferences object from the current settings. Examples: >>> preferences = Preferences() >>> keys = ['latexViewer', 'latexEngine', 'latexUselatexmk', ... 'latexVerbose', 'latexDebug', 'latexAutoView', ... 'latexKeepLogWin', 'latexEngineOptions'] >>> all([key in preferences.prefs for key in keys]) True """ tm_identifier = getenv('TM_APP_IDENTIFIER', 'com.macromates.textmate') CFPreferencesAppSynchronize(tm_identifier) self.default_values = { 'latexAutoView': 1, 'latexEngine': "pdflatex", 'latexEngineOptions': "", 'latexVerbose': 0, 'latexUselatexmk': 1, 'latexViewer': "TextMate", 'latexKeepLogWin': 1, 'latexDebug': 0, } self.prefs = self.default_values.copy() for key in self.prefs: preference_value = CFPreferencesCopyAppValue(key, tm_identifier) if preference_value is not None: self.prefs[key] = preference_value
def save(self): """Saves our (modified) Dock preferences.""" # unload Dock launchd job so we can make our changes unmolested subprocess.call(["/bin/launchctl", "unload", self._DOCK_LAUNCHAGENT_FILE]) for key in self._SECTIONS: try: CFPreferencesSetAppValue(key, self.items[key], self._DOMAIN) except Exception: raise DockError for key in self._MUTABLE_KEYS: if getattr(self, key.replace("-", "_")) is not None: try: CFPreferencesSetAppValue( key.replace("_", "-"), getattr(self, key.replace("-", "_")), self._DOMAIN, ) except Exception: raise DockError if not CFPreferencesAppSynchronize(self._DOMAIN): raise DockError # restart the Dock subprocess.call(["/bin/launchctl", "load", self._DOCK_LAUNCHAGENT_FILE]) subprocess.call(["/bin/launchctl", "start", self._DOCK_LAUNCHAGENT_ID])
def __setitem__(self, pref_name, pref_value): """Sets a preference. if the user is kCFPreferencesCurrentUser, the preference actually gets written at the 'ByHost' level due to the use of kCFPreferencesCurrentHost""" CFPreferencesSetValue(pref_name, pref_value, self.bundle_id, self.user, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize(self.bundle_id)
def save(self): '''saves our (modified) Dock preferences''' # unload Dock launchd job so we can make our changes unmolested subprocess.call( ['/bin/launchctl', 'unload', self._DOCK_LAUNCHAGENT_FILE]) for key in self._SECTIONS: try: CFPreferencesSetAppValue(key, self.items[key], self._DOMAIN) except Exception: raise DockError for key in self._MUTABLE_KEYS: if getattr(self, key): try: CFPreferencesSetAppValue(key.replace('_', '-'), getattr(self, key), self._DOMAIN) except Exception: raise DockError if not CFPreferencesAppSynchronize(self._DOMAIN): raise DockError # restart the Dock subprocess.call( ['/bin/launchctl', 'load', self._DOCK_LAUNCHAGENT_FILE]) subprocess.call(['/bin/launchctl', 'start', self._DOCK_LAUNCHAGENT_ID])
def set_pref(pref_name, pref_value, bundleid=BUNDLE_ID): """Set a preference, writing it to ~/Library/Preferences/.""" try: CFPreferencesSetValue(pref_name, pref_value, bundleid, kCFPreferencesCurrentUser, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize(BUNDLE_ID) except BaseException: pass
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 reload_prefs(): """Uses CFPreferencesAppSynchronize(BUNDLE_ID) to make sure we have the latest prefs. Call this if you have modified /Library/Preferences/MunkiReport.plist or /var/root/Library/Preferences/MunkiReport.plist directly """ CFPreferencesAppSynchronize(BUNDLE_ID)
def write_pref(key, value): # NSLog('Setting "{0}" to "{1}"'.format(key, value)) CFPreferencesSetAppValue(key, value, kCFPreferencesCurrentApplication) if not CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication): d = PyDialog.AlertDialog( 'Something went wrong...', 'Unable to save preference: "{0}"'.format(key)) d.display() NSLog('ERROR: unable to save user preferences!')
def add_receipt(yo_args): """Add a receipt to current user's receipt preferences. Args: yo_args (list of str): Arguments to yo app as for a subprocess. """ receipts = get_receipts() receipts[repr(yo_args)] = NSDate.alloc().init() CFPreferencesSetAppValue("DeliveryReceipts", receipts, BUNDLE_ID) CFPreferencesAppSynchronize(BUNDLE_ID)
def main(argv=None): if argv is None: argv = sys.argv try: if not dockutilExists(): print "dockutil not found" print "Get it from https://github.com/kcrawford/dockutil" print "or run \"git clone https://github.com/kcrawford/dockutil.git\"" return 1 confirmation = raw_input("Are you sure? y/n: ").lower() if confirmation == 'y': print "Continuing..." elif confirmation == '' or confirmation == 'n': raise Usage("Exiting...") else: print 'Please enter y or n.' return 1 # Start with an empty Dock removeEverything( restartDock=False ); # Add standard Apple apps for anApp in appleApps: dockutilAdd(anApp, None) #print "Added %s" % anApp # Add more Apple apps for anApp in appleAppsWithVaryingNames: if os.path.exists(anApp["path"]): dockutilAdd(anApp["path"], anApp["args"]) #print "Added %s" % anApp["path"] else: print "Skipped %s" % anApp["path"] # Add 3rd party apps for anApp in thirdPartyApps: if os.path.exists(anApp["path"]) or anApp["forced"]: dockutilAdd(anApp["path"], anApp["args"]) #print "Added %s" % anApp["path"] else: print "Skipped %s" % anApp["path"] # Add folders addFolders() # Write all pending changes to permanent storage CFPreferencesAppSynchronize('com.apple.dock') print "Done. You might want to restart Dock by running \"killall Dock\"" except Usage, err: print >> sys.stderr, str(err.msg) return 2
def set_pref(pref_name, pref_value): """Sets a preference, writing it to /Library/Preferences/ManagedInstalls.plist. This should normally be used only for 'bookkeeping' values; values that control the behavior of munki may be overridden elsewhere (by MCX, for example)""" try: CFPreferencesSetValue(pref_name, pref_value, BUNDLE_ID, kCFPreferencesAnyUser, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize(BUNDLE_ID) except BaseException: pass
def save(self): """saves our (modified) TouchBar preferences""" for key in self._SECTIONS: try: CFPreferencesSetAppValue(key, self.items[key], self._DOMAIN) except Exception: raise TouchBarError if not CFPreferencesAppSynchronize(self._DOMAIN): raise TouchBarError # restart the TouchBar subprocess.call(["/usr/bin/killall", "ControlStrip"])
def setupSoftwareUpdateCheck(): '''Set defaults for root user and current host. Needed for Leopard.''' CFPreferencesSetValue('AgreedToLicenseAgreement', True, 'com.apple.SoftwareUpdate', kCFPreferencesCurrentUser, kCFPreferencesCurrentHost) CFPreferencesSetValue('AutomaticDownload', True, 'com.apple.SoftwareUpdate', kCFPreferencesCurrentUser, kCFPreferencesCurrentHost) CFPreferencesSetValue('LaunchAppInBackground', True, 'com.apple.SoftwareUpdate', kCFPreferencesCurrentUser, kCFPreferencesCurrentHost) if not CFPreferencesAppSynchronize('com.apple.SoftwareUpdate'): munkicommon.display_warning( 'Error setting com.apple.SoftwareUpdate ByHost preferences')
def set_pref(pref_name, pref_value): """Sets a Sal preference. The preference file on disk is located at /Library/Preferences/com.github.salopensource.sal.plist. This should normally be used only for 'bookkeeping' values; values that control the behavior of munki may be overridden elsewhere (by MCX, for example) """ try: CFPreferencesSetValue(pref_name, pref_value, BUNDLE_ID, kCFPreferencesAnyUser, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize(BUNDLE_ID) except Exception: pass
def main(argv=None): if argv is None: argv = sys.argv try: if not dockutilExists(): print("dockutil not found") print("Get it from https://github.com/kcrawford/dockutil") print( "or run \"git clone https://github.com/kcrawford/dockutil.git\"" ) return 1 # Start with an empty Dock removeEverything(restartDock=False) # Add standard Apple apps for anApp in appleApps: dockutilAdd(anApp, None) #print("Added %s" % anApp) # Add more Apple apps for anApp in appleAppsWithVaryingNames: if os.path.exists(anApp["path"]): dockutilAdd(anApp["path"], anApp["args"]) #print("Added %s" % anApp["path"]) else: print("Skipped %s" % anApp["path"]) # Add 3rd party apps for anApp in thirdPartyApps: if os.path.exists(anApp["path"]) or anApp["forced"]: dockutilAdd(anApp["path"], anApp["args"]) #print("Added %s" % anApp["path"]) else: print("Skipped %s" % anApp["path"]) # Add folders addFolders() # Write all pending changes to permanent storage CFPreferencesAppSynchronize('com.apple.dock') # Restart Dock restartDock() except Usage as err: print(str(err.msg), file=sys.stderr) return 2
def reset_fde_autologin(): '''Resets the state of com.apple.loginwindow DisableFDEAutoLogin to its value before we set it to True''' # get the previous value of DisableFDEAutoLogin if any original_value = CFPreferencesCopyValue( 'OriginalDisableFDEAutoLogin', 'com.apple.loginwindow', kCFPreferencesAnyUser, kCFPreferencesCurrentHost) if original_value == '<not set>': original_value = None # reset DisableFDEAutoLogin to original value (if original_value is None, # the key gets deleted) CFPreferencesSetValue( 'DisableFDEAutoLogin', original_value, 'com.apple.loginwindow', kCFPreferencesAnyUser, kCFPreferencesCurrentHost) # delete the OriginalDisableFDEAutoLogin key CFPreferencesSetValue( 'OriginalDisableFDEAutoLogin', None, 'com.apple.loginwindow', kCFPreferencesAnyUser, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize('com.apple.loginwindow')
def configure(prompt_list): """Gets configuration options and saves them to preferences store""" darwin_vers = int(os.uname()[2].split('.')[0]) edited_prefs = {} for (key, prompt) in prompt_list: newvalue = raw_input_with_default('%15s: ' % prompt, pref(key)) if darwin_vers == 10: # old behavior in SL: hitting return gives you an empty string, # and means accept the default value. edited_prefs[key] = newvalue or pref(key) or '' else: # just use the edited value as-is edited_prefs[key] = newvalue if FOUNDATION_SUPPORT: for key, value in edited_prefs.items(): try: CFPreferencesSetAppValue(key, value, BUNDLE_ID) except BaseException: print >> sys.stderr, 'Could not save configuration!' raise ConfigurationSaveError # remove repo_path if it exists since we don't use that # any longer (except for backwards compatibility) and we don't # want it getting out of sync with the repo_url CFPreferencesSetAppValue('repo_path', None, BUNDLE_ID) CFPreferencesAppSynchronize(BUNDLE_ID) else: try: existing_prefs = plistlib.readPlist(PREFSPATH) existing_prefs.update(edited_prefs) # remove repo_path if it exists since we don't use that # any longer (except for backwards compatibility) and we don't # want it getting out of sync with the repo_url if 'repo_path' in existing_prefs: del existing_prefs['repo_path'] plistlib.writePlist(existing_prefs, PREFSPATH) except (IOError, OSError, ExpatError): print >> sys.stderr, ('Could not save configuration to %s' % PREFSPATH) raise ConfigurationSaveError
def schedule_notification(args): """Schedule a notification to be delivered to users""" # Get the arguments from the system-level preferences (i.e. # /Library/Preferences/com.sheagcraig.yo.plist). This precludes us # from using the _slightly_ shorter CFPreferencesCopyAppValue. notifications = CFPreferencesCopyValue("Notifications", BUNDLE_ID, kCFPreferencesAnyUser, kCFPreferencesAnyHost) # We get an immutable NSCFDictionary back from CFPreferences, so # copy it to a mutable python dict. notifications = dict(notifications) if notifications else {} # Convert args to string representation of a python list for later # reconversion back to python. notifications[repr(args)] = NSDate.alloc().init() CFPreferencesSetValue("Notifications", notifications, BUNDLE_ID, kCFPreferencesAnyUser, kCFPreferencesAnyHost) # Use the simpler `AppSynchroniize`; it seems to flush all changes, # despite having to use the primitive methods above. CFPreferencesAppSynchronize(BUNDLE_ID)
def save_user_defaults(prefs): """Write the user preferences for Recipe Robot back to disk. Args: prefs (dict): The dictionary containing a key/value pair for Recipe Robot preferences. """ # Clean up non Recipe Robot related keys that were accidentally collected from the # global preferences by prior versions of Recipe Robot. cfprefs_keylist = CFPreferencesCopyKeyList( BUNDLE_ID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost ) if cfprefs_keylist: external_keys = [x for x in cfprefs_keylist if x not in PREFERENCE_KEYS] for ext_key in external_keys: CFPreferencesSetAppValue(ext_key, None, BUNDLE_ID) # Save latest values for all Recipe Robot keys. for key in PREFERENCE_KEYS: if prefs.get(key): CFPreferencesSetAppValue(key, prefs[key], BUNDLE_ID) CFPreferencesAppSynchronize(BUNDLE_ID)
else: # if no prefs key for this version, create the key as an empty dict # for us to add the EULA key to print "No existing key for '%s', creating new dict" % version final_prefs[version] = {} if 'EULAAccepted' not in final_prefs[version]: print "No EULAAccepted key present, adding to '%s'" % version final_prefs[version]['EULAAccepted'] = True # We could print out all the prefs here # print final_prefs # Note: this seems odd that we might have Objective-C dict types # in some keys and Python dict types in others, but PyObjC massages # this for us and in the end we're using a standard system API to # set the preference # finally, the equivalent of `defaults write` this new pref we've assembled CFPreferencesSetMultiple( final_prefs, # 1. our dictionary of keys/values to set [], # 2. a list of keys to _remove_ 'com.adobe.Reader', # 3. the domain kCFPreferencesCurrentUser, # 4. current- or any-user (ie. ~/L/P or /L/P) kCFPreferencesAnyHost # 5. current- or any-host (ie. ByHost or not) ) # not required on 10.8 and higher unless you need to synchronously # read com.adobe.Reader prefs from another process/app CFPreferencesAppSynchronize('com.adobe.Reader')
#!/usr/bin/python from Foundation import CFPreferencesSetAppValue, \ CFPreferencesAppSynchronize app_id = "com.apple.screenSaver" CFPreferencesSetAppValue("idleTime", 600, app_id) CFPreferencesAppSynchronize(app_id)
def reload_prefs(): """Uses CFPreferencesAppSynchronize(BUNDLE_ID) to make sure we have the latest prefs. Call this if another process may have modified ManagedInstalls.plist, this needs to be run after returning from MunkiStatus""" CFPreferencesAppSynchronize(BUNDLE_ID)
#!/usr/bin/python # Add Favorite Servers to the "Connect to Server" dialog box # Last modified July 23, 2015 - Burlison import subprocess, sys from Foundation import CFPreferencesAppSynchronize, \ CFPreferencesCopyAppValue, \ CFPreferencesSetMultiple, \ kCFPreferencesAnyHost, \ kCFPreferencesCurrentUser prefs={'favoriteservers': {'Controller': 'CustomListItems', 'CustomListItems': [{'Name': 'smb://011-ctemac2', 'URL': 'smb://011-ctemac2'}]}} CFPreferencesSetMultiple( prefs, [], 'com.apple.sidebarlists', kCFPreferencesCurrentUser, kCFPreferencesAnyHost ) CFPreferencesAppSynchronize('com.apple.sidebarlists') command = ['/usr/bin/killall', 'Finder'] subprocess.call(command)
def clear_scheduled_notifications(): """Clear all scheduled notifications""" CFPreferencesSetValue( "Notifications", {}, BUNDLE_ID, kCFPreferencesAnyUser, kCFPreferencesAnyHost) CFPreferencesAppSynchronize(BUNDLE_ID)
def __setitem__(self, pref_name, pref_value): CFPreferencesSetValue(pref_name, pref_value, self.bundle_id, self.user, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize(self.bundle_id)
def write_preference(key, value, bundle): """Write a preference key from a preference domain.""" CFPreferencesSetValue(key, value, bundle, kCFPreferencesAnyUser, kCFPreferencesCurrentHost) CFPreferencesAppSynchronize(bundle) return