diff --git a/rumps/__init__.py b/rumps/__init__.py index 5be784f..9659456 100644 --- a/rumps/__init__.py +++ b/rumps/__init__.py @@ -23,4 +23,4 @@ __copyright__ = 'Copyright 2017 Jared Suttles' from .rumps import (separator, debug_mode, alert, notification, application_support, timers, quit_application, timer, - clicked, notifications, MenuItem, Timer, Window, App) + clicked, notifications, MenuItem, Timer, Window, App, Preferences) diff --git a/rumps/rumps.py b/rumps/rumps.py index f14a003..0500d8d 100644 --- a/rumps/rumps.py +++ b/rumps/rumps.py @@ -25,11 +25,15 @@ import inspect import os -import pickle import sys import traceback import weakref +try: + import cPickle as pickle +except ImportError: + import pickle as pickle + from collections import Mapping, Iterable from .utils import ListDict from .compat import text_type, string_types, iteritems @@ -212,6 +216,13 @@ def application_support(name): return app_support_path +def preferences_path(name): + home_dir = os.path.join(os.path.expanduser("~"), name) + if not os.path.exists(home_dir): + os.makedirs(home_dir) + return os.path.join(home_dir, "{}.prefs".format(name.lower().replace(" ", "").strip())) + + def timers(): """Return a list of all :class:`rumps.Timer` objects. These can be active or inactive.""" return list(_TIMERS) @@ -1026,6 +1037,29 @@ def callback_(cls, nsmenuitem): _log(traceback.format_exc()) +class Preferences(object): + """ + Provides access to a folder in the user's home directory, as well as a pickled key-value file. + :param name: the name of the application. + :param path: a path to the folder being used to store the preferences file. + """ + + def __init__(self, name, path=None): + self._path = path if path else preferences_path(name) + self._preferences = {} + if os.path.exists(self._path): + with open(self._path, "rb") as file: + self._preferences = pickle.load(file) + + def get(self, key, default=None): + return self._preferences.get(key, default) + + def set(self, key, value): + self._preferences[key] = value + with open(self._path, "wb") as file: + pickle.dump(self._preferences, file, 2) + print("Set preference %s to %s" % (key, repr(value))) + class App(object): """Represents the statusbar application. @@ -1064,6 +1098,7 @@ def __init__(self, name, title=None, icon=None, template=None, menu=None, quit_b if menu is not None: self.menu = menu self._application_support = application_support(self._name) + self.preferences = Preferences(self._name) # Properties #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -