root/branch/PacketManipulator/Manager/PreferenceManager.py @ 3361

Revision 3361, 4.7 kB (checked in by nopper, 5 years ago)

Forget about Manager folder (preference stuff)

Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (C) 2008 Adriano Monteiro Marques
4#
5# Author: Francesco Piccinno <stack.box@gmail.com>
6#
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
21import sys
22
23from xml.sax import handler, make_parser
24from xml.sax.saxutils import XMLGenerator
25from xml.sax.xmlreader import AttributesNSImpl
26
27from Atoms import Singleton
28
29TYPES = {
30    basestring : 'str',
31    bool       : 'bool',
32    dict       : 'dict',
33    float      : 'float',
34    int        : 'int',
35    list       : 'list',
36    tuple      : 'tuple'
37}
38
39class Option(object):
40    def __init__(self, value, default=None):
41        self._value = value
42        self.type = 'str'
43        self.converter = str
44        self.cbs = []
45
46        for k, v in TYPES.items():
47            if isinstance(value, k):
48                self.type = v
49                self.converter = k
50                break
51
52    def connect(self, callback, call=True):
53        self.cbs.append(callback)
54
55        if call:
56            callback(self.value)
57
58    def disconnect(self, callback):
59        if callback in self.cbs:
60            self.cbs.remove(callback)
61
62    def get_value(self):
63        return self._value
64
65    def set_value(self, val):
66        # Check type?
67        if not isinstance(val, self.converter):
68            val = self.converter(val)
69
70        for cb in self.cbs:
71            # Lock if a callback returns True
72            if cb(val):
73                print "set_value(): Ignoring change"
74                return
75
76        print "set_value(): %s = %s" % (self, val)
77        self._value = val
78
79    def __repr__(self):
80        return "(%s)" % self._value
81
82    value = property(get_value, set_value)
83
84class PreferenceLoader(handler.ContentHandler):
85    def __init__(self, outfile):
86        self.outfile = outfile
87        self.options = {}
88
89    def startElement(self, name, attrs):
90        if name in ('bool', 'int', 'float', \
91                    'str', 'list', 'tuple'):
92
93            opt_name = None
94            opt_value = None
95
96            for attr in attrs.keys():
97                if attr == 'id':
98                    opt_name = attrs.get(attr)
99                if attr == 'value':
100                    opt_value = attrs.get(attr)
101
102            if opt_name != None and opt_value != None:
103                self.options[opt_name] = Option(opt_value)
104
105class PreferenceWriter:
106    def __init__(self, fname, options):
107        output = open(fname, 'w')
108        self.writer = XMLGenerator(output, 'utf-8')
109        self.writer.startDocument()
110
111        for key, option in options.items():
112
113            attr_vals = {
114                (None, u'id') : key,
115                (None, u'value') : option.value
116            }
117
118            attr_qnames = {
119                (None, u'id') : u'id',
120                (None, u'value') : u'value'
121            }
122
123            attrs = AttributesNSImpl(attr_vals, attr_qnames)
124            self.writer.startElementNS((None, option.type), option.type, attrs)
125            self.writer.endElementNS((None, option.type), option.type)
126
127        self.writer.endDocument()
128        output.close()
129
130class Prefs(Singleton):
131    options = {
132        'gui.docking' : True,
133        'gui.maintab.hexview.font' : 'Monospace 10',
134        'gui.maintab.hexview.bpl' : 16,
135
136        'backend.system' : 'umpa',
137    }
138
139    def __init__(self):
140        self.fname = 'pm-prefs.xml'
141       
142        try:
143            opts = self.load_options()
144            self.options.update(self.load_options())
145        except Exception:
146            pass
147
148        diff_dict = {}
149        for name, opt in self.options.items():
150            if not isinstance(opt, Option):
151                diff_dict[name] = Option(opt)
152
153        self.options.update(diff_dict)
154
155    def load_options(self):
156        handler = PreferenceLoader(sys.stdout)
157        parser = make_parser()
158        parser.setContentHandler(handler)
159        parser.parse(self.fname)
160
161        return handler.options
162
163    def write_options(self):
164        writer = PreferenceWriter(self.fname, self.options)
165
166    def __getitem__(self, x):
167        return self.options[x]
168
169if __name__ == "__main__":
170    Prefs().load_options('test.xml')
171
Note: See TracBrowser for help on using the browser.