~ubuntu-branches/ubuntu/lucid/meld/lucid

« back to all changes in this revision

Viewing changes to prefs.py

  • Committer: Bazaar Package Importer
  • Author(s): Ross Burton
  • Date: 2009-06-02 10:00:20 UTC
  • mfrom: (1.2.9 upstream) (2.1.5 squeeze)
  • Revision ID: james.westby@ubuntu.com-20090602100020-jb5wlixbu8xws29a
Tags: 1.3.0-1
* New upstream release (Closes: #528327)
  - Copy/paste behaviour fixes (Closes: #523576)
  - Dotfiles and removals handled in darcs (Closes: #509069)
  - Can handle Mercurial repos (Closes: #428843)
  - Up/Down patch used to skip changes (Closes: #511027)
  - Handle last line when highlighting properly (Closes: #465804)
* Update message and depends for new python-gtksourceview2 package
* Resync makefile.patch
* Remove python-gnome dependency

Show diffs side-by-side

added added

removed removed

Lines of Context:
27
27
p = prefs.Preferences("/apps/myapp", defaults)
28
28
# use variables as if they were normal attributes.
29
29
draw(p.colour, p.size)
30
 
# settings are persistent. (saved in gconf)
 
30
# settings are persistent
31
31
p.color = "blue"
32
32
 
33
33
"""
34
34
 
 
35
import os
 
36
import sys
 
37
 
 
38
 
35
39
class Value(object):
36
40
    """Represents a settable preference.
37
41
    """
48
52
        self.default = d
49
53
        self.current = d
50
54
 
51
 
# maybe fall back to ConfigParser if gconf is unavailable.
52
 
import gconf
53
 
 
54
55
# types of values allowed
55
56
BOOL = "bool"
56
57
INT = "int"
61
62
 
62
63
##
63
64
 
64
 
class Preferences(object):
65
 
    """Persistent preferences object.
 
65
class GConfPreferences(object):
 
66
    """Persistent preferences object that handles preferences via gconf.
66
67
 
67
68
    Example:
68
69
    import prefs
114
115
                pass
115
116
 
116
117
    def _on_preference_changed(self, client, timestamp, entry, extra):
117
 
        attr = entry.key[ entry.key.rindex("/")+1 : ]
 
118
        attr = entry.key[entry.key.rfind("/") + 1:]
118
119
        try:
119
120
            valuestruct = self._prefs[attr]
120
121
        except KeyError: # unknown key, we don't care about it
140
141
        for k,v in self._prefs.items():
141
142
            print k, v.type, v.current
142
143
 
 
144
 
 
145
class ConfigParserPreferences(object):
 
146
    """Persistent preferences object that handles preferences via ConfigParser.
 
147
 
 
148
    This preferences implementation is provided as a fallback for gconf-less
 
149
    platforms. The ConfigParser library is included in Python and should be
 
150
    available everywhere. The biggest drawbacks to this backend are lack of
 
151
    access to desktop-wide settings, and lack of external change notification.
 
152
    """
 
153
 
 
154
    def __init__(self, rootkey, initial):
 
155
        """Create a preferences object.
 
156
 
 
157
        Settings are initialised with 'initial' and then overriden
 
158
        from values in the ConfigParser database if available.
 
159
 
 
160
        rootkey : unused (retained for compatibility with existing gconf API)
 
161
        initial : a dictionary of string to Value objects.
 
162
        """
 
163
        self.__dict__["_parser"] = ConfigParser.SafeConfigParser()
 
164
        self.__dict__["_listeners"] = []
 
165
        self.__dict__["_prefs"] = initial
 
166
        self.__dict__["_type_mappings"] = {
 
167
            BOOL   : self._parser.getboolean,
 
168
            INT    : self._parser.getint,
 
169
            STRING : self._parser.get,
 
170
            FLOAT  : self._parser.getfloat
 
171
        }
 
172
 
 
173
        if sys.platform == "win32":
 
174
            pref_dir = os.path.join(os.getenv("APPDATA"), "Meld")
 
175
        else:
 
176
            pref_dir = os.path.join(os.path.expanduser("~"), ".meld")
 
177
 
 
178
        if not os.path.exists(pref_dir):
 
179
            os.makedirs(pref_dir)
 
180
 
 
181
        self.__dict__["_file_path"] = os.path.join(pref_dir, "meldrc.ini")
 
182
 
 
183
        try:
 
184
            config_file = open(self._file_path, "r")
 
185
            try:
 
186
                self._parser.readfp(config_file)
 
187
            finally:
 
188
                config_file.close()
 
189
        except IOError:
 
190
            pass
 
191
 
 
192
        for key, value in self._prefs.items():
 
193
            if self._parser.has_option("DEFAULT", key):
 
194
                value.current = self._type_mappings[value.type]("DEFAULT", key)
 
195
 
 
196
    def __getattr__(self, attr):
 
197
        return self._prefs[attr].current
 
198
 
 
199
    def get_default(self, attr):
 
200
        return self._prefs[attr].default
 
201
 
 
202
    def __setattr__(self, attr, val):
 
203
        value = self._prefs[attr]
 
204
        if value.current != val:
 
205
            value.current = val
 
206
            self._parser.set(None, attr, str(val))
 
207
 
 
208
            try:
 
209
                fp = open(self._file_path, "w")
 
210
                try:
 
211
                    self._parser.write(fp)
 
212
                finally:
 
213
                    fp.close()
 
214
            except IOError:
 
215
                pass
 
216
 
 
217
            try:
 
218
                for l in self._listeners:
 
219
                    l(attr, val)
 
220
            except StopIteration:
 
221
                pass
 
222
 
 
223
    def notify_add(self, callback):
 
224
        """Register a callback to be called when a preference changes.
 
225
 
 
226
        callback : a callable object which take two parameters, 'attr' the
 
227
                   name of the attribute changed and 'val' the new value.
 
228
        """
 
229
        self._listeners.append(callback)
 
230
 
 
231
    def dump(self):
 
232
        """Print all preferences.
 
233
        """
 
234
        for k,v in self._prefs.items():
 
235
            print k, v.type, v.current
 
236
 
 
237
# Prefer gconf, falling back to ConfigParser
 
238
try:
 
239
    import gconf
 
240
    Preferences = GConfPreferences
 
241
except ImportError:
 
242
    import ConfigParser
 
243
    Preferences = ConfigParserPreferences
 
244