root/branch/PacketManipulator/PM/Manager/PreferenceManager.py @ 3456

Revision 3456, 6.2 kB (checked in by nopper, 5 years ago)

Moving all into PM directory to best fit for setup.py

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    str        : '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.type = 'str'
42        self.converter = str
43        self.cbs = []
44
45        for k, v in TYPES.items():
46            if isinstance(value, k):
47                self.type = v
48                self.converter = k
49                break
50
51        self._value = self.converter(value)
52
53    def connect(self, callback, call=True):
54        self.cbs.append(callback)
55
56        if call:
57            callback(self.value)
58
59    def disconnect(self, callback):
60        if callback in self.cbs:
61            self.cbs.remove(callback)
62
63    def get_value(self):
64        assert isinstance(self._value, self.converter)
65        return self._value
66
67    def set_value(self, val):
68        # Check type?
69        if not isinstance(val, self.converter):
70            val = self.converter(val)
71
72        for cb in self.cbs:
73            # Lock if a callback returns True
74            if cb(val):
75                print "set_value(): Ignoring change"
76                return
77
78        print "set_value(): %s = %s" % (self, val)
79        self._value = val
80
81    def __repr__(self):
82        return "(%s)" % self._value
83
84    value = property(get_value, set_value)
85
86class PreferenceLoader(handler.ContentHandler):
87    def __init__(self, outfile):
88        self.outfile = outfile
89        self.options = {}
90
91    def startElement(self, name, attrs):
92        if name in ('bool', 'int', 'float', \
93                    'str', 'list', 'tuple'):
94
95            opt_name = None
96            opt_value = None
97
98            for attr in attrs.keys():
99                if attr == 'id':
100                    opt_name = attrs.get(attr)
101                if attr == 'value':
102                    opt_value = attrs.get(attr)
103           
104            try:
105                if name == 'bool':
106                    if opt_value.lower() == 'true' or opt_value == '1':
107                        opt_value = True
108                    else:
109                        opt_value = False
110                elif name == 'int':
111                    opt_value = int(opt_value)
112                elif name == 'float':
113                    opt_value = float(opt_value)
114                elif name == 'list':
115                    opt_value = opt_value.split(",")
116                    opt_value = filter(None, opt_value)
117                elif name == 'tuple':
118                    opt_value = opt_value.split(",")
119                    opt_value = filter(None, opt_value)
120                    opt_value = tuple(opt_value)
121            except:
122                return
123
124            if opt_name != None and opt_value != None:
125                self.options[opt_name] = Option(opt_value)
126
127class PreferenceWriter:
128    def __init__(self, fname, options):
129        output = open(fname, 'w')
130        self.writer = XMLGenerator(output, 'utf-8')
131        self.writer.startDocument()
132        self.writer.startElementNS((None, 'PacketManipulator'), 'PacketManipulator', {})
133
134        for key, option in options.items():
135
136            attr_vals = {
137                (None, u'id') : key,
138                (None, u'value') : str(option.value)
139            }
140
141            attr_qnames = {
142                (None, u'id') : u'id',
143                (None, u'value') : u'value'
144            }
145
146            attrs = AttributesNSImpl(attr_vals, attr_qnames)
147            self.writer.startElementNS((None, str(option.type)), str(option.type), attrs)
148            self.writer.endElementNS((None, str(option.type)), str(option.type))
149
150        self.writer.endElementNS((None, 'PacketManipulator'), 'PacketManipulator')
151        self.writer.endDocument()
152        output.close()
153
154class Prefs(Singleton):
155    options = {
156        'gui.docking' : True,
157        'gui.maintab.sniffview.font' : 'Monospace 10',
158        'gui.maintab.sniffview.usecolors' : False,
159        'gui.maintab.hexview.font' : 'Monospace 10',
160        'gui.maintab.hexview.bpl' : 16,
161
162        'gui.statustab.font' : 'Monospace 10',
163       
164        'gui.views.protocol_selector_tab' : True,
165        'gui.views.property_tab' : True,
166        'gui.views.status_tab' : True,
167        'gui.views.operations_tab' : True,
168        'gui.views.vte_tab' : False,
169        'gui.views.hack_tab' : False,
170        'gui.views.console_tab' : False,
171
172        'backend.system' : 'scapy',
173        'backend.scapy.interface' : ''
174    }
175
176    def __init__(self):
177        self.fname = 'pm-prefs.xml'
178       
179        try:
180            opts = self.load_options()
181            self.options.update(self.load_options())
182        except Exception:
183            pass
184
185        diff_dict = {}
186        for name, opt in self.options.items():
187            if not isinstance(opt, Option):
188                diff_dict[name] = Option(opt)
189
190        self.options.update(diff_dict)
191
192    def load_options(self):
193        handler = PreferenceLoader(sys.stdout)
194        parser = make_parser()
195        parser.setContentHandler(handler)
196        parser.parse(self.fname)
197
198        return handler.options
199
200    def write_options(self):
201        writer = PreferenceWriter(self.fname, self.options)
202
203    def __getitem__(self, x):
204        return self.options[x]
205
206if __name__ == "__main__":
207    Prefs().load_options('test.xml')
208
Note: See TracBrowser for help on using the browser.