~ubuntu-branches/ubuntu/precise/gnome-games/precise-proposed

« back to all changes in this revision

Viewing changes to glchess/src/lib/config.py

  • Committer: Package Import Robot
  • Author(s): Rodrigo Moya
  • Date: 2011-05-30 13:32:04 UTC
  • mfrom: (1.3.4)
  • mto: (163.1.3 precise)
  • mto: This revision was merged to the branch mainline in revision 143.
  • Revision ID: package-import@ubuntu.com-20110530133204-celaq1v1dsxc48q1
Tags: upstream-3.0.2
ImportĀ upstreamĀ versionĀ 3.0.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- coding: utf-8 -*-
2
 
from defaults import *
3
 
 
4
 
try:
5
 
    import gconf
6
 
    import gobject
7
 
except ImportError:
8
 
    haveGConfSupport = False
9
 
    _notifiers = {}
10
 
    _values = {}
11
 
 
12
 
    import xml.dom.minidom
13
 
    document = None
14
 
    try:
15
 
        document = xml.dom.minidom.parse(CONFIG_FILE)
16
 
    except IOError:
17
 
        pass
18
 
    except xml.parsers.expat.ExpatError:
19
 
        print 'Configuration at ' + CONFIG_FILE + ' is invalid, ignoring'
20
 
    else:
21
 
        print 'Loading configuration from ' + CONFIG_FILE
22
 
 
23
 
    def _bool(string):
24
 
        return string == 'True'
25
 
        
26
 
    valueTypes = {'int': int, 'bool': _bool, 'float': float, 'str': str}
27
 
    
28
 
    if document is not None:
29
 
        elements = document.getElementsByTagName('config')
30
 
        
31
 
        for e in elements:
32
 
            for n in e.getElementsByTagName('value'):
33
 
                try:
34
 
                    name = n.attributes['name'].nodeValue
35
 
                except KeyError:
36
 
                    continue
37
 
                try:
38
 
                    valueType = n.attributes['type'].nodeValue
39
 
                except KeyError:
40
 
                    continue
41
 
                if len(n.childNodes) != 1 or n.childNodes[0].nodeType != n.TEXT_NODE:
42
 
                    continue
43
 
                valueString = n.childNodes[0].nodeValue
44
 
                
45
 
                try:
46
 
                    value = valueTypes[valueType](valueString)
47
 
                except KeyError:
48
 
                    continue
49
 
 
50
 
                _values[name] = value
51
 
 
52
 
else:
53
 
    haveGConfSupport = True
54
 
    _GCONF_DIR = '/apps/glchess/'
55
 
    _config = gconf.client_get_default()
56
 
    try:
57
 
        _config.add_dir(_GCONF_DIR[:-1], gconf.CLIENT_PRELOAD_NONE)
58
 
    except gobject.GError:
59
 
        pass
60
 
    
61
 
    _gconfGetFunction = {gconf.VALUE_BOOL: gconf.Value.get_bool,
62
 
                         gconf.VALUE_FLOAT: gconf.Value.get_float,
63
 
                         gconf.VALUE_INT: gconf.Value.get_int,
64
 
                         gconf.VALUE_STRING: gconf.Value.get_string}
65
 
                         
66
 
    _gconfSetFunction = {bool:    _config.set_bool,
67
 
                         float:   _config.set_float,
68
 
                         int:     _config.set_int,
69
 
                         str:     _config.set_string,
70
 
                         unicode: _config.set_string}
71
 
              
72
 
# Config default values
73
 
_defaults = {'show_toolbar':                     True,
74
 
             'show_history':                     True,
75
 
             'maximised':                        False,
76
 
             'fullscreen':                       False,
77
 
             'piece_style':                      'simple',
78
 
             'show_3d':                          False,
79
 
             'show_3d_smooth':                   False,             
80
 
             'show_move_hints':                  True,
81
 
             'move_format':                      'human',
82
 
             'promotion_type':                   'queen',
83
 
             'board_view':                       'human',
84
 
             'show_comments':                    False,
85
 
             'show_numbering':                   False,
86
 
             'enable_networking':                True,
87
 
             'load_directory':                   '',
88
 
             'save_directory':                   '',
89
 
             'new_game_dialog/move_time':        0,
90
 
             'new_game_dialog/white/type':       '',
91
 
             'new_game_dialog/white/difficulty': '',
92
 
             'new_game_dialog/black/type':       '',
93
 
             'new_game_dialog/black/difficulty': ''}
94
 
 
95
 
class Error(Exception):
96
 
    """Exception for configuration use"""
97
 
    pass
98
 
 
99
 
def get(name):
100
 
    """Get a configuration value.
101
 
    
102
 
    'name' is the name of the value to get (string).
103
 
    
104
 
    Raises an Error exception if the value does not exist.
105
 
    """
106
 
    if haveGConfSupport:
107
 
        try:
108
 
            entry = _config.get(_GCONF_DIR + name)
109
 
        except gobject.GError:
110
 
            entry = None
111
 
        
112
 
        if entry is None:
113
 
            try:
114
 
                return _defaults[name]
115
 
            except KeyError:
116
 
                raise Error('No config value: ' + repr(name))
117
 
 
118
 
        try:
119
 
            function = _gconfGetFunction[entry.type]
120
 
        except KeyError:
121
 
            raise Error('Unknown value type')
122
 
        
123
 
        return function(entry)
124
 
        
125
 
    else:
126
 
        try:
127
 
            return _values[name]
128
 
        except KeyError:
129
 
            try:
130
 
                return _defaults[name]
131
 
            except KeyError:
132
 
                raise Error('No config value: ' + repr(name))
133
 
 
134
 
def set(name, value):
135
 
    """Set a configuration value.
136
 
    
137
 
    'name' is the name of the value to set (string).
138
 
    'value' is the value to set to (int, str, float, bool).
139
 
    """
140
 
    if haveGConfSupport:
141
 
        try:
142
 
            function = _gconfSetFunction[type(value)]
143
 
        except KeyError:
144
 
            raise TypeError('Only config values of type: int, str, float, bool supported')
145
 
        else:
146
 
            try:
147
 
                function(_GCONF_DIR + name, value)
148
 
            except gobject.GError:
149
 
                pass
150
 
 
151
 
    else:
152
 
        # Debounce
153
 
        try:
154
 
            oldValue = _values[name]
155
 
        except KeyError:
156
 
            pass
157
 
        else:
158
 
            if oldValue == value:
159
 
                return
160
 
        
161
 
        # Use new value and notify watchers
162
 
        _values[name] = value
163
 
        try:
164
 
            watchers = _notifiers[name]
165
 
        except KeyError:
166
 
            pass
167
 
        else:
168
 
            for func in watchers:
169
 
                func(name, value)
170
 
                
171
 
        # Save configuration
172
 
        _save()
173
 
        
174
 
def default(name):
175
 
    set(name, _defaults[name])
176
 
                
177
 
def _watch(client, _, entry, (function, name)):
178
 
    value = get(name)
179
 
    function(name, value)
180
 
 
181
 
def watch(name, function):
182
 
    """
183
 
    """
184
 
    if haveGConfSupport:
185
 
        try:
186
 
            _config.notify_add(_GCONF_DIR + name, _watch, (function, name))
187
 
        except gobject.GError:
188
 
            pass
189
 
    else:
190
 
        try:
191
 
            watchers = _notifiers[name]
192
 
        except KeyError:
193
 
            watchers = _notifiers[name] = []            
194
 
        watchers.append(function)
195
 
 
196
 
def _save():
197
 
    """Save the current configuration"""
198
 
    if haveGConfSupport:
199
 
        return
200
 
    
201
 
    document = xml.dom.minidom.Document()
202
 
    
203
 
    e = document.createComment('Automatically generated by glChess, do not edit!')
204
 
    document.appendChild(e)
205
 
    
206
 
    root = document.createElement('config')
207
 
    document.appendChild(root)
208
 
    
209
 
    valueNames = {int: 'int', bool: 'bool', float: 'float', str: 'str', unicode: 'str'}
210
 
 
211
 
    names = _values.keys()
212
 
    names.sort()
213
 
    for name in names:
214
 
        value = _values[name]
215
 
        e = document.createElement('value')
216
 
        root.appendChild(e)
217
 
        e.setAttribute('name', name)
218
 
        e.setAttribute('type', valueNames[type(value)])
219
 
        valueElement = document.createTextNode(str(value))
220
 
        e.appendChild(valueElement)
221
 
 
222
 
    try:
223
 
        f = file(CONFIG_FILE, 'w')
224
 
    except IOError:
225
 
        pass
226
 
    else:
227
 
        document.writexml(f)
228
 
        f.close()