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

Revision 3499, 6.3 kB (checked in by nopper, 5 years ago)

docstrings

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