prefs.py 7.68 KB
Newer Older
Stephen Kennedy's avatar
Stephen Kennedy committed
1
### Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
steve9000's avatar
steve9000 committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation; either version 2 of the License, or
### (at your option) any later version.

### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
### GNU General Public License for more details.

### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

17 18
"""Module to help implement 'instant-apply' preferences.

19
Usage:
20

21 22 23 24 25
import prefs
defaults = {
    "colour" : prefs.Value(prefs.STRING, "red")
    "size" : prefs.Value(prefs.INT, 10)
}
26

27 28 29
p = prefs.Preferences("/apps/myapp", defaults)
# use variables as if they were normal attributes.
draw(p.colour, p.size)
30
# settings are persistent
31
p.color = "blue"
32

33
"""
steve9000's avatar
steve9000 committed
34

35 36 37 38
import os
import sys


39 40 41
class Value(object):
    """Represents a settable preference.
    """
42

43
    __slots__ = ["type", "default", "current"]
44

45 46
    def __init__(self, t, d):
        """Create a value.
47

48 49 50 51 52 53
        t : a string : one of ("bool", "int", "string")
        d : the default value, also the initial value
        """
        self.type = t
        self.default = d
        self.current = d
steve9000's avatar
steve9000 committed
54

55 56 57 58 59 60 61 62 63 64
# types of values allowed
BOOL = "bool"
INT = "int"
STRING = "string"
FLOAT = "float"
# LIST = "list"
# PAIR = "pair"

##

65 66
class GConfPreferences(object):
    """Persistent preferences object that handles preferences via gconf.
67 68 69 70 71 72 73 74 75 76 77 78 79

    Example:
    import prefs
    defaults = {"spacing": prefs.Value(prefs.INT, 4),
                "font": prefs.Value(prefs.STRING, "monospace") }
    p = prefs.Prefs("myapp", defaults)
    print p.font
    p.font = "sans" # written to gconf too
    p2 = prefs.Prefs("myapp", defaults)
    print p.font # prints "sans"
    """

    def __init__(self, rootkey, initial):
80 81
        """Create a preferences object.

82 83 84
        Settings are initialised with 'initial' and then overriden
        from values in the gconf database if available.

85
        rootkey : the root gconf key where the values will be stored
86
        initial : a dictionary of string to Value objects.
87 88 89 90
        """
        self.__dict__["_gconf"] = gconf.client_get_default()
        self.__dict__["_listeners"] = []
        self.__dict__["_rootkey"] = rootkey
91
        self.__dict__["_prefs"] = initial
92
        self._gconf.add_dir(rootkey, gconf.CLIENT_PRELOAD_NONE)
steve9000's avatar
steve9000 committed
93
        self._gconf.notify_add(rootkey, self._on_preference_changed)
94 95
        for key, value in self._prefs.items():
            gval = self._gconf.get_without_default("%s/%s" % (rootkey, key) )
96
            if gval is not None:
97
                value.current = getattr( gval, "get_%s" % value.type )()
98

steve9000's avatar
steve9000 committed
99
    def __getattr__(self, attr):
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        return self._prefs[attr].current

    def get_default(self, attr):
        return self._prefs[attr].default

    def __setattr__(self, attr, val):
        value = self._prefs[attr]
        if value.current != val:
            value.current = val
            setfunc = getattr(self._gconf, "set_%s" % value.type)
            setfunc("%s/%s" % (self._rootkey, attr), val)
            try:
                for l in self._listeners:
                    l(attr,val)
            except StopIteration:
                pass
116

steve9000's avatar
steve9000 committed
117
    def _on_preference_changed(self, client, timestamp, entry, extra):
118
        attr = entry.key[entry.key.rfind("/") + 1:]
119 120 121 122 123
        try:
            valuestruct = self._prefs[attr]
        except KeyError: # unknown key, we don't care about it
            pass
        else:
124
            if entry.value is not None: # value has changed
125 126 127 128 129
                newval = getattr(entry.value, "get_%s" % valuestruct.type)()
                setattr( self, attr, newval)
            else: # value has been deleted
                setattr( self, attr, valuestruct.default )

steve9000's avatar
steve9000 committed
130
    def notify_add(self, callback):
131 132 133 134 135 136 137
        """Register a callback to be called when a preference changes.

        callback : a callable object which take two parameters, 'attr' the
                   name of the attribute changed and 'val' the new value.
        """
        self._listeners.append(callback)

138 139 140 141 142
    def dump(self):
        """Print all preferences.
        """
        for k,v in self._prefs.items():
            print k, v.type, v.current
steve9000's avatar
steve9000 committed
143

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

class ConfigParserPreferences(object):
    """Persistent preferences object that handles preferences via ConfigParser.

    This preferences implementation is provided as a fallback for gconf-less
    platforms. The ConfigParser library is included in Python and should be
    available everywhere. The biggest drawbacks to this backend are lack of
    access to desktop-wide settings, and lack of external change notification.
    """

    def __init__(self, rootkey, initial):
        """Create a preferences object.

        Settings are initialised with 'initial' and then overriden
        from values in the ConfigParser database if available.

        rootkey : unused (retained for compatibility with existing gconf API)
        initial : a dictionary of string to Value objects.
        """
        self.__dict__["_parser"] = ConfigParser.SafeConfigParser()
        self.__dict__["_listeners"] = []
        self.__dict__["_prefs"] = initial
        self.__dict__["_type_mappings"] = {
            BOOL   : self._parser.getboolean,
            INT    : self._parser.getint,
            STRING : self._parser.get,
            FLOAT  : self._parser.getfloat
        }

        if sys.platform == "win32":
            pref_dir = os.path.join(os.getenv("APPDATA"), "Meld")
        else:
            pref_dir = os.path.join(os.path.expanduser("~"), ".meld")

        if not os.path.exists(pref_dir):
            os.makedirs(pref_dir)

        self.__dict__["_file_path"] = os.path.join(pref_dir, "meldrc.ini")

        try:
            config_file = open(self._file_path, "r")
            try:
                self._parser.readfp(config_file)
            finally:
                config_file.close()
        except IOError:
            pass

        for key, value in self._prefs.items():
            if self._parser.has_option("DEFAULT", key):
                value.current = self._type_mappings[value.type]("DEFAULT", key)

    def __getattr__(self, attr):
        return self._prefs[attr].current

    def get_default(self, attr):
        return self._prefs[attr].default

    def __setattr__(self, attr, val):
        value = self._prefs[attr]
        if value.current != val:
            value.current = val
            self._parser.set(None, attr, str(val))

            try:
                fp = open(self._file_path, "w")
                try:
                    self._parser.write(fp)
                finally:
                    fp.close()
            except IOError:
                pass

            try:
                for l in self._listeners:
                    l(attr, val)
            except StopIteration:
                pass

    def notify_add(self, callback):
        """Register a callback to be called when a preference changes.

        callback : a callable object which take two parameters, 'attr' the
                   name of the attribute changed and 'val' the new value.
        """
        self._listeners.append(callback)

    def dump(self):
        """Print all preferences.
        """
        for k,v in self._prefs.items():
            print k, v.type, v.current

# Prefer gconf, falling back to ConfigParser
try:
    import gconf
    Preferences = GConfPreferences
except ImportError:
    import ConfigParser
    Preferences = ConfigParserPreferences