[billreminder] Borrowing GConf handler classes from the conduit project.



commit ca33034ef351c098f586a2c7f571344efc3e8580
Author: Og B. Maciel <ogmaciel gnome org>
Date:   Wed Dec 30 18:16:56 2009 -0500

    Borrowing GConf handler classes from the conduit project.

 src/lib/Settings.py      |  135 +++++++++++++++++++++++++++++++++
 src/lib/SettingsGConf.py |  185 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 320 insertions(+), 0 deletions(-)
---
diff --git a/src/lib/Settings.py b/src/lib/Settings.py
new file mode 100644
index 0000000..e6a8c65
--- /dev/null
+++ b/src/lib/Settings.py
@@ -0,0 +1,135 @@
+"""
+Stores application settings
+
+Part of this code copied from Gimmie (c) Alex Gravely
+
+Copyright: John Stowers, 2006
+License: GPLv2
+"""
+import gobject
+
+#these dicts are used for mapping config setting types to type names
+#and back again (isnt python cool...)
+TYPE_TO_TYPE_NAME = {
+    int     :   "int",
+    bool    :   "bool",
+    str     :   "string",
+    list    :   "list"
+}
+STRING_TO_TYPE = {
+    "int"       :   lambda x: int(x),
+    "bool"      :   lambda x: string_to_bool(x),
+    "string"    :   lambda x: str(x),
+    "list"      :   lambda x: string_to_list(x)
+}
+TYPE_TO_STRING = {
+    int     :   lambda x: str(x),
+    bool    :   lambda x: str(x),
+    str     :   lambda x: str(x),
+    list    :   lambda x: list_to_string(x)
+}
+
+def string_to_bool(stringy):
+    #Because bool("False") doesnt work as expected when restoring strings
+    if stringy == "True":
+        return True
+    else:
+        return False
+    
+def list_to_string(listy):
+    s = ""
+    if type(listy) is list:
+        s = ",".join(listy) #cool
+    return s
+    
+def string_to_list(string, listInternalVtype=str):
+    l = string.split(",")
+    internalTypeName = TYPE_TO_TYPE_NAME[listInternalVtype]
+    for i in range(0, len(l)):
+        l[i] = STRING_TO_TYPE[internalTypeName](l[i])
+    return l
+
+class Settings(gobject.GObject):
+    """
+    Class for storing conduit.GLOBALS.settings. Keys of type str, bool, int, 
+    and list of strings supported at this stage.
+    
+    Also stores the special proxy settings.
+    """
+    __gsignals__ = {
+        'changed' : (gobject.SIGNAL_RUN_LAST | gobject.SIGNAL_DETAILED, gobject.TYPE_NONE, ()),
+    }
+
+    #Default values for conduit settings
+    DEFAULTS = {
+        'startup_delay'             :   1,              #How long to wait before starting the backend
+        'start_in_tray'             :   False,          #Show the application start minimized
+        'show_startup_notification' :   True,
+        'show_pay_notification',    :   True,
+        'show_before_alarm'         :   True,
+        'show_due_alarm'            :   True,
+        'show_alarm'                :   True,
+        'notification_days_limit'   :   15,
+        'use_alert_dialog'          :   False,
+        'show_alarm_before_days'    :   3,
+        'show_alarm_at_time'        :   '13:00',
+        'interval'                  :   60,
+        'window_position_x'         :   0,
+        'window_position_y'         :   0,
+        'window_width'              :   550,
+        'window_height'             :   300,
+        'show_toolbar'              :   False,
+        'show_menubar'              :   False,
+        'show_paid_bills'           :   2,
+        'due_date'                  :   0,
+    }
+
+    def __init__(self, **kwargs):
+        gobject.GObject.__init__(self)
+
+        #you can override the settings implementation at runtime
+        #for testing purposes only
+        try:
+            from lib.defs import SETTINGS_IMPL
+        except Exception, e:
+            SETTINGS_IMPL = 'GConf'
+
+        implName = kwargs.get("implName", conduit.SETTINGS_IMPL)
+        if implName == "GConf":
+            import SettingsGConf as SettingsImpl
+        else:
+            raise Exception("Settings Implementation %s Not Supported" % implName)
+
+        self._settings = SettingsImpl.SettingsImpl(
+            defaults=self.DEFAULTS, changedCb=self._key_changed)
+
+    def _key_changed(self, key):
+        self.emit('changed::%s' % key)
+
+    def set_overrides(self, **overrides):
+        """
+        Sets values of settings that only exist for this setting, and are
+        never saved, nor updated.
+        """
+        self._settings.set_overrides(**overrides)
+
+    def get(self, key, **kwargs):
+        """
+        Returns the value of the key or the default value if the key is 
+        not yet stored
+        """
+        return self._settings.get(key, **kwargs)
+
+    def set(self, key, value, **kwargs):
+        """
+        Sets the key to value.
+        """
+        return self._settings.set(key, value, **kwargs)
+
+    def save(self):
+        """
+        Performs any necessary tasks to ensure settings are saved between sessions
+        """
+        self._settings.save()
+
+
diff --git a/src/lib/SettingsGConf.py b/src/lib/SettingsGConf.py
new file mode 100644
index 0000000..1f2312f
--- /dev/null
+++ b/src/lib/SettingsGConf.py
@@ -0,0 +1,185 @@
+import re
+import os
+
+try:
+    import gconf
+except ImportError:
+    from gnome import gconf
+
+import conduit.platform
+
+import logging
+log = logging.getLogger("Settings")
+    
+class SettingsImpl(conduit.platform.Settings):
+    """
+    Settings implementation which stores settings in GConf
+    """
+    
+    CONDUIT_GCONF_DIR = "/apps/conduit/"
+    VALID_KEY_TYPES = (bool, str, int, list, tuple)
+    
+    def __init__(self, defaults, changedCb):
+        conduit.platform.Settings.__init__(self, defaults, changedCb)
+
+        self._client = gconf.client_get_default()
+        self._client.add_dir(self.CONDUIT_GCONF_DIR[:-1], gconf.CLIENT_PRELOAD_RECURSIVE)  
+        self._notifications = []
+
+    def _fix_key(self, key):
+        """
+        Appends the CONDUIT_GCONF_PREFIX to the key if needed
+        
+        @param key: The key to check
+        @type key: C{string}
+        @returns: The fixed key
+        @rtype: C{string}
+        """
+        if not key.startswith(self.CONDUIT_GCONF_DIR):
+            return self.CONDUIT_GCONF_DIR + key
+        else:
+            return key
+            
+    def _key_changed(self, client, cnxn_id, entry, data=None):
+        """
+        Callback when a gconf key changes
+        """
+        key = self._fix_key(entry.key)
+        self._changedCb(key)
+        
+    def get(self, key, default=None):
+        """
+        Returns the value of the key or the default value if the key is 
+        not yet in gconf
+        """
+        #check if the setting has been overridden for this session
+        if key in self._overrides:
+            try:
+                #try and cast to correct type
+                return type(self._defaults[key])(self._overrides[key])
+            except:
+                return self._overrides[key]
+
+        #function arguments override defaults
+        if default == None:
+            default = self._defaults.get(key, None)
+        vtype = type(default)
+
+        #we now have a valid key and type
+        if default == None:
+            log.warn("Unknown key: %s, must specify default value" % key)
+            return None
+
+        if vtype not in self.VALID_KEY_TYPES:
+            log.warn("Invalid key type: %s" % vtype)
+            return None
+
+        #for gconf refer to the full key path
+        key = self._fix_key(key)
+
+        if key not in self._notifications:
+            self._client.notify_add(key, self._key_changed)
+            self._notifications.append(key)
+        
+        value = self._client.get(key)
+        if not value:
+            self.set(key, default)
+            return default
+
+        if vtype is bool:
+            return value.get_bool()
+        elif vtype is str:
+            return value.get_string()
+        elif vtype is int:
+            return value.get_int()
+        elif vtype in (list, tuple):
+            l = []
+            for i in value.get_list():
+                l.append(i.get_string())
+            return l
+            
+        log.warn("Unknown gconf key: %s" % key)
+        return None
+
+    def set(self, key, value):
+        """
+        Sets the key value in gconf and connects adds a signal 
+        which is fired if the key changes
+        """
+        #overidden settings only apply for this session, and are
+        #not set
+        if key in self._overrides:
+            return True
+
+        log.debug("Settings %s -> %s" % (key, value))
+        if key in self._defaults:
+            vtype = type(self._defaults[key])
+        else:
+            vtype = type(value)
+
+        if vtype not in self.VALID_KEY_TYPES:
+            log.warn("Invalid key type: %s" % vtype)
+            return False
+
+        #for gconf refer to the full key path
+        key = self._fix_key(key)
+
+        if vtype is bool:
+            self._client.set_bool(key, value)
+        elif vtype is str:
+            self._client.set_string(key, value)
+        elif vtype is int:
+            self._client.set_int(key, value)
+        elif vtype in (list, tuple):
+            #Save every value as a string
+            strvalues = [str(i) for i in value]
+            self._client.set_list(key, gconf.VALUE_STRING, strvalues)
+
+        return True
+        
+    def proxy_enabled(self):
+        """
+        @returns: True if the user has specified a http proxy via
+        the http_proxy environment variable, or in gconf
+        """
+        return os.environ.has_key("http_proxy") or \
+                self._client.get_bool("/system/http_proxy/use_http_proxy")
+        
+    def get_proxy(self):
+        """
+        Returns the details of the configured http proxy. 
+        The http_proxy environment variable overrides the GNOME setting
+        @returns: host,port,user,password
+        """
+        if self.proxy_enabled():
+            #env vars have preference
+            if os.environ.has_key("http_proxy"):
+                #re taken from python boto
+                pattern = re.compile(
+                    '(?:http://)?' \
+                    '(?:(?P<user>\w+):(?P<pass>.*)@)?' \
+                    '(?P<host>[\w\-\.]+)' \
+                    '(?::(?P<port>\d+))?'
+                )
+                match = pattern.match(os.environ['http_proxy'])
+                if match:
+                    return (match.group('host'),
+                            int(match.group('port')),
+                            match.group('user'),
+                            match.group('pass'))
+            #now try gconf
+            if self._client.get_bool("/system/http_proxy/use_authentication"):
+                return (self._client.get_string("/system/http_proxy/host"),
+                        self._client.get_int("/system/http_proxy/port"),
+                        self._client.get_string("/system/http_proxy/authentication_user"),
+                        self._client.get_string("/system/http_proxy/authentication_password"))
+            else:
+                return (self._client.get_string("/system/http_proxy/host"),
+                        self._client.get_int("/system/http_proxy/port"),
+                        "",
+                        "")
+
+        return ("",0,"","")
+
+
+



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]