servicedvbrecord.cpp: add sanity check for tags
[enigma2.git] / lib / python / Components / config.py
index 1efb8a56f42b827e6e7631dc60f6fb82de6bd2a7..4df02d5d6aa3ca2c3962340501a4d4b73b6ec4e1 100755 (executable)
@@ -1,10 +1,10 @@
-import time
 from enigma import getPrevAsciiCode
 from Tools.NumericalTextInput import NumericalTextInput
 from Tools.Directories import resolveFilename, SCOPE_CONFIG
 from Components.Harddisk import harddiskmanager
-import copy
-import os
+from copy import copy as copy_copy
+from os import path as os_path
+from time import localtime, strftime
 
 # ConfigElement, the base class of all ConfigElements.
 
@@ -20,7 +20,7 @@ import os
 #   saved_value is a text representation of _value, stored in the config file
 #
 # and has (at least) the following methods:
-#   save()   stores _value into saved_value, 
+#   save()   stores _value into saved_value,
 #            (or stores 'None' if it should not be stored)
 #   load()   loads _value from saved_value, or loads
 #            the default if saved_value is 'None' (default)
@@ -28,16 +28,34 @@ import os
 #
 class ConfigElement(object):
        def __init__(self):
-
-               object.__init__(self)
                self.saved_value = None
                self.last_value = None
                self.save_disabled = False
-               self.notifiers = []
-               self.notifiers_final = []
+               self.__notifiers = None
+               self.__notifiers_final = None
                self.enabled = True
                self.callNotifiersOnSaveAndCancel = False
 
+       def getNotifiers(self):
+               if self.__notifiers is None:
+                       self.__notifiers = [ ]
+               return self.__notifiers
+
+       def setNotifiers(self, val):
+               self.__notifiers = val
+
+       notifiers = property(getNotifiers, setNotifiers)
+
+       def getNotifiersFinal(self):
+               if self.__notifiers_final is None:
+                       self.__notifiers_final = [ ]
+               return self.__notifiers_final
+
+       def setNotifiersFinal(self, val):
+               self.__notifiers_final = val
+
+       notifiers_final = property(getNotifiersFinal, setNotifiersFinal)
+
        # you need to override this to do input validation
        def setValue(self, value):
                self._value = value
@@ -45,7 +63,7 @@ class ConfigElement(object):
 
        def getValue(self):
                return self._value
-       
+
        value = property(getValue, setValue)
 
        # you need to override this if self.value is not a string
@@ -84,13 +102,15 @@ class ConfigElement(object):
                return self.tostring(self.value) != sv
 
        def changed(self):
-               for x in self.notifiers:
-                       x(self)
-                       
+               if self.__notifiers:
+                       for x in self.notifiers:
+                               x(self)
+
        def changedFinal(self):
-               for x in self.notifiers_final:
-                       x(self)
-                       
+               if self.__notifiers_final:
+                       for x in self.notifiers_final:
+                               x(self)
+
        def addNotifier(self, notifier, initial_call = True, immediate_feedback = True):
                assert callable(notifier), "notifiers must be callable"
                if immediate_feedback:
@@ -140,6 +160,109 @@ def getKeyNumber(key):
        assert key in KEY_NUMBERS
        return key - KEY_0
 
+class choicesList(object): # XXX: we might want a better name for this
+       LIST_TYPE_LIST = 1
+       LIST_TYPE_DICT = 2
+
+       def __init__(self, choices, type = None):
+               self.choices = choices
+               if type is None:
+                       if isinstance(choices, list):
+                               self.type = choicesList.LIST_TYPE_LIST
+                       elif isinstance(choices, dict):
+                               self.type = choicesList.LIST_TYPE_DICT
+                       else:
+                               assert False, "choices must be dict or list!"
+               else:
+                       self.type = type
+
+       def __list__(self):
+               if self.type == choicesList.LIST_TYPE_LIST:
+                       ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
+               else:
+                       ret = self.choices.keys()
+               return ret or [""]
+
+       def __iter__(self):
+               if self.type == choicesList.LIST_TYPE_LIST:
+                       ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
+               else:
+                       ret = self.choices
+               return iter(ret or [""])
+
+       def __len__(self):
+               return len(self.choices) or 1
+
+       def __getitem__(self, index):
+               if self.type == choicesList.LIST_TYPE_LIST:
+                       ret = self.choices[index]
+                       if isinstance(ret, tuple):
+                               ret = ret[0]
+                       return ret
+               return self.choices.keys()[index]
+
+       def index(self, value):
+               return self.__list__().index(value)
+
+       def __setitem__(self, index, value):
+               if self.type == choicesList.LIST_TYPE_LIST:
+                       orig = self.choices[index]
+                       if isinstance(orig, tuple):
+                               self.choices[index] = (value, orig[1])
+                       else:
+                               self.choices[index] = value
+               else:
+                       key = self.choices.keys()[index]
+                       orig = self.choices[key]
+                       del self.choices[key]
+                       self.choices[value] = orig
+
+       def default(self):
+               choices = self.choices
+               if not choices:
+                       return ""
+               if self.type is choicesList.LIST_TYPE_LIST:
+                       default = choices[0]
+                       if isinstance(default, tuple):
+                               default = default[0]
+               else:
+                       default = choices.keys()[0]
+               return default
+
+class descriptionList(choicesList): # XXX: we might want a better name for this
+       def __list__(self):
+               if self.type == choicesList.LIST_TYPE_LIST:
+                       ret = [not isinstance(x, tuple) and x or x[1] for x in self.choices]
+               else:
+                       ret = self.choices.values()
+               return ret or [""]
+
+       def __iter__(self):
+               return iter(self.__list__())
+
+       def __getitem__(self, index):
+               if self.type == choicesList.LIST_TYPE_LIST:
+                       for x in self.choices:
+                               if isinstance(x, tuple):
+                                       if x[0] == index:
+                                               return str(x[1])
+                               elif x == index:
+                                       return str(x)
+                       return str(index) # Fallback!
+               else:
+                       return str(self.choices.get(index, ""))
+
+       def __setitem__(self, index, value):
+               if self.type == choicesList.LIST_TYPE_LIST:
+                       i = self.index(index)
+                       orig = self.choices[i]
+                       if isinstance(orig, tuple):
+                               self.choices[i] = (orig[0], value)
+                       else:
+                               self.choices[i] = value
+               else:
+                       self.choices[index] = value
+
 #
 # ConfigSelection is a "one of.."-type.
 # it has the "choices", usually a list, which contains
@@ -151,44 +274,22 @@ def getKeyNumber(key):
 class ConfigSelection(ConfigElement):
        def __init__(self, choices, default = None):
                ConfigElement.__init__(self)
-               self._value = None
-               self.setChoices(choices, default)
-               self.last_value = self._value
+               self.choices = choicesList(choices)
+
+               if default is None:
+                       default = self.choices.default()
+
+               self._descr = None
+               self.default = self._value = self.last_value = default
 
        def setChoices(self, choices, default = None):
-               self.choices = []
-               self.description = {}
-               
-               if isinstance(choices, list):
-                       for x in choices:
-                               if isinstance(x, tuple):
-                                       self.choices.append(x[0])
-                                       self.description[x[0]] = x[1]
-                               else:
-                                       self.choices.append(x)
-                                       self.description[x] = x
-               elif isinstance(choices, dict):
-                       for (key, val) in choices.items():
-                               self.choices.append(key)
-                               self.description[key] = val
-               else:
-                       assert False, "ConfigSelection choices must be dict or list!"
-               
-               #assert len(self.choices), "you can't have an empty configselection"
-               if len(self.choices) == 0:
-                       self.choices = [""]
-                       self.description[""] = ""
+               self.choices = choicesList(choices)
 
                if default is None:
-                       default = self.choices[0]
-
-               assert default in self.choices, "default must be in choice list, but " + repr(default) + " is not!"
-               for x in self.choices:
-                       assert isinstance(x, str), "ConfigSelection choices must be strings"
-               
+                       default = self.choices.default()
                self.default = default
 
-               if self.value == None or not self.value in self.choices:
+               if self.value not in self.choices:
                        self.value = default
 
        def setValue(self, value):
@@ -196,7 +297,7 @@ class ConfigSelection(ConfigElement):
                        self._value = value
                else:
                        self._value = self.default
-               
+               self._descr = None
                self.changed()
 
        def tostring(self, val):
@@ -207,16 +308,15 @@ class ConfigSelection(ConfigElement):
 
        def setCurrentText(self, text):
                i = self.choices.index(self.value)
-               del self.description[self.choices[i]]
                self.choices[i] = text
-               self.description[text] = text
+               self._descr = self.description[text] = text
                self._value = text
 
        value = property(getValue, setValue)
-       
+
        def getIndex(self):
                return self.choices.index(self.value)
-       
+
        index = property(getIndex)
 
        # GUI
@@ -231,21 +331,26 @@ class ConfigSelection(ConfigElement):
                        self.value = self.choices[0]
                elif key == KEY_END:
                        self.value = self.choices[nchoices - 1]
-                       
+
        def selectNext(self):
                nchoices = len(self.choices)
                i = self.choices.index(self.value)
                self.value = self.choices[(i + 1) % nchoices]
 
        def getText(self):
-               descr = self.description[self.value]
-               if len(descr):
+               if self._descr is not None:
+                       return self._descr
+               descr = self._descr = self.description[self.value]
+               if descr:
                        return _(descr)
                return descr
 
        def getMulti(self, selected):
-               descr = self.description[self.value]
-               if len(descr):
+               if self._descr is not None:
+                       descr = self._descr
+               else:
+                       descr = self._descr = self.description[self.value]
+               if descr:
                        return ("text", _(descr))
                return ("text", descr)
 
@@ -253,30 +358,34 @@ class ConfigSelection(ConfigElement):
        def getHTML(self, id):
                res = ""
                for v in self.choices:
+                       descr = self.description[v]
                        if self.value == v:
                                checked = 'checked="checked" '
                        else:
                                checked = ''
-                       res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n"
+                       res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + descr + "</input></br>\n"
                return res;
 
        def unsafeAssign(self, value):
                # setValue does check if value is in choices. This is safe enough.
                self.value = value
 
+       description = property(lambda self: descriptionList(self.choices.choices, self.choices.type))
+
 # a binary decision.
 #
 # several customized versions exist for different
 # descriptions.
 #
+boolean_descriptions = {False: "false", True: "true"}
 class ConfigBoolean(ConfigElement):
-       def __init__(self, default = False, descriptions = {False: "false", True: "true"}):
+       def __init__(self, default = False, descriptions = boolean_descriptions):
                ConfigElement.__init__(self)
                self.descriptions = descriptions
                self.value = self.last_value = self.default = default
 
        def handleKey(self, key):
-               if key in [KEY_LEFT, KEY_RIGHT]:
+               if key in (KEY_LEFT, KEY_RIGHT):
                        self.value = not self.value
                elif key == KEY_HOME:
                        self.value = False
@@ -285,13 +394,13 @@ class ConfigBoolean(ConfigElement):
 
        def getText(self):
                descr = self.descriptions[self.value]
-               if len(descr):
+               if descr:
                        return _(descr)
                return descr
 
        def getMulti(self, selected):
                descr = self.descriptions[self.value]
-               if len(descr):
+               if descr:
                        return ("text", _(descr))
                return ("text", descr)
 
@@ -326,17 +435,20 @@ class ConfigBoolean(ConfigElement):
                        self.changedFinal()
                        self.last_value = self.value
 
+yes_no_descriptions = {False: _("no"), True: _("yes")}
 class ConfigYesNo(ConfigBoolean):
        def __init__(self, default = False):
-               ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")})
+               ConfigBoolean.__init__(self, default = default, descriptions = yes_no_descriptions)
 
+on_off_descriptions = {False: _("off"), True: _("on")}
 class ConfigOnOff(ConfigBoolean):
        def __init__(self, default = False):
-               ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")})
+               ConfigBoolean.__init__(self, default = default, descriptions = on_off_descriptions)
 
+enable_disable_descriptions = {False: _("disable"), True: _("enable")}
 class ConfigEnableDisable(ConfigBoolean):
        def __init__(self, default = False):
-               ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")})
+               ConfigBoolean.__init__(self, default = default, descriptions = enable_disable_descriptions)
 
 class ConfigDateTime(ConfigElement):
        def __init__(self, default, formatstring, increment = 86400):
@@ -354,10 +466,10 @@ class ConfigDateTime(ConfigElement):
                        self.value = self.default
 
        def getText(self):
-               return time.strftime(self.formatstring, time.localtime(self.value))
+               return strftime(self.formatstring, localtime(self.value))
 
        def getMulti(self, selected):
-               return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
+               return ("text", strftime(self.formatstring, localtime(self.value)))
 
        def fromstring(self, val):
                return int(val)
@@ -369,7 +481,7 @@ class ConfigDateTime(ConfigElement):
 # several helper exist to ease this up a bit.
 #
 class ConfigSequence(ConfigElement):
-       def __init__(self, seperator, limits, censor_char = "", default = None):
+       def __init__(self, seperator, limits, default, censor_char = ""):
                ConfigElement.__init__(self)
                assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
                assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
@@ -381,12 +493,10 @@ class ConfigSequence(ConfigElement):
                self.seperator = seperator
                self.limits = limits
                self.censor_char = censor_char
-               
-               self.default = default
-               self.value = copy.copy(default)
-               self.last_value = copy.copy(default)
-               
-               self.endNotifier = []
+
+               self.last_value = self.default = default
+               self.value = copy_copy(default)
+               self.endNotifier = None
 
        def validate(self):
                max_pos = 0
@@ -403,8 +513,9 @@ class ConfigSequence(ConfigElement):
                        num += 1
 
                if self.marked_pos >= max_pos:
-                       for x in self.endNotifier:
-                               x(self)
+                       if self.endNotifier:
+                               for x in self.endNotifier:
+                                       x(self)
                        self.marked_pos = max_pos - 1
 
                if self.marked_pos < 0:
@@ -413,13 +524,15 @@ class ConfigSequence(ConfigElement):
        def validatePos(self):
                if self.marked_pos < 0:
                        self.marked_pos = 0
-                       
+
                total_len = sum([len(str(x[1])) for x in self.limits])
 
                if self.marked_pos >= total_len:
                        self.marked_pos = total_len - 1
-                       
+
        def addEndNotifier(self, notifier):
+               if self.endNotifier is None:
+                       self.endNotifier = []
                self.endNotifier.append(notifier)
 
        def handleKey(self, key):
@@ -427,15 +540,15 @@ class ConfigSequence(ConfigElement):
                        self.marked_pos -= 1
                        self.validatePos()
 
-               if key == KEY_RIGHT:
+               elif key == KEY_RIGHT:
                        self.marked_pos += 1
                        self.validatePos()
-               
-               if key == KEY_HOME:
+
+               elif key == KEY_HOME:
                        self.marked_pos = 0
                        self.validatePos()
 
-               if key == KEY_END:
+               elif key == KEY_END:
                        max_pos = 0
                        num = 0
                        for i in self._value:
@@ -443,8 +556,8 @@ class ConfigSequence(ConfigElement):
                                num += 1
                        self.marked_pos = max_pos - 1
                        self.validatePos()
-               
-               if key in KEY_NUMBERS or key == KEY_ASCII:
+
+               elif key in KEY_NUMBERS or key == KEY_ASCII:
                        if key == KEY_ASCII:
                                code = getPrevAsciiCode()
                                if code < 48 or code > 57:
@@ -452,11 +565,8 @@ class ConfigSequence(ConfigElement):
                                number = code - 48
                        else:
                                number = getKeyNumber(key)
-                       
-                       block_len = []
-                       for x in self.limits:
-                               block_len.append(len(str(x[1])))
-                       
+
+                       block_len = [len(str(x[1])) for x in self.limits]
                        total_len = sum(block_len)
 
                        pos = 0
@@ -475,38 +585,37 @@ class ConfigSequence(ConfigElement):
 
                        # position in the block
                        posinblock = self.marked_pos - block_len_total[blocknumber]
-                       
+
                        oldvalue = self._value[blocknumber]
                        olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
                        newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
-                       
+
                        self._value[blocknumber] = newvalue
                        self.marked_pos += 1
-               
+
                        self.validate()
                        self.changed()
-       
+
        def genText(self):
                value = ""
                mPos = self.marked_pos
                num = 0;
                for i in self._value:
-                       if len(value):  #fixme no heading separator possible
+                       if value:       #fixme no heading separator possible
                                value += self.seperator
                                if mPos >= len(value) - 1:
                                        mPos += 1
-
                        if self.censor_char == "":
                                value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
                        else:
                                value += (self.censor_char * len(str(self.limits[num][1])))
                        num += 1
                return (value, mPos)
-               
+
        def getText(self):
                (value, mPos) = self.genText()
                return value
-       
+
        def getMulti(self, selected):
                (value, mPos) = self.genText()
                        # only mark cursor when we are selected
@@ -518,7 +627,7 @@ class ConfigSequence(ConfigElement):
 
        def tostring(self, val):
                return self.seperator.join([self.saveSingle(x) for x in val])
-       
+
        def saveSingle(self, v):
                return str(v)
 
@@ -526,53 +635,51 @@ class ConfigSequence(ConfigElement):
                return [int(x) for x in value.split(self.seperator)]
 
        def onDeselect(self, session):
-               if not self.last_value == self._value:
+               if self.last_value != self._value:
                        self.changedFinal()
-                       self.last_value = copy.copy(self._value)
+                       self.last_value = copy_copy(self._value)
 
+ip_limits = [(0,255),(0,255),(0,255),(0,255)]
 class ConfigIP(ConfigSequence):
        def __init__(self, default, auto_jump = False):
-               ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
-               self.block_len = []
-               for x in self.limits:
-                       self.block_len.append(len(str(x[1])))
+               ConfigSequence.__init__(self, seperator = ".", limits = ip_limits, default = default)
+               self.block_len = [len(str(x[1])) for x in self.limits]
                self.marked_block = 0
                self.overwrite = True
                self.auto_jump = auto_jump
 
        def handleKey(self, key):
-               
                if key == KEY_LEFT:
                        if self.marked_block > 0:
                                self.marked_block -= 1
                        self.overwrite = True
 
-               if key == KEY_RIGHT:
+               elif key == KEY_RIGHT:
                        if self.marked_block < len(self.limits)-1:
                                self.marked_block += 1
                        self.overwrite = True
 
-               if key == KEY_HOME:
+               elif key == KEY_HOME:
                        self.marked_block = 0
                        self.overwrite = True
 
-               if key == KEY_END:
+               elif key == KEY_END:
                        self.marked_block = len(self.limits)-1
                        self.overwrite = True
 
-               if key in KEY_NUMBERS or key == KEY_ASCII:
+               elif key in KEY_NUMBERS or key == KEY_ASCII:
                        if key == KEY_ASCII:
                                code = getPrevAsciiCode()
                                if code < 48 or code > 57:
                                        return
                                number = code - 48
-                       else:   
+                       else:
                                number = getKeyNumber(key)
                        oldvalue = self._value[self.marked_block]
-                       
+
                        if self.overwrite:
                                self._value[self.marked_block] = number
-                               self.overwrite = False          
+                               self.overwrite = False
                        else:
                                oldvalue *= 10
                                newvalue = oldvalue + number
@@ -593,15 +700,15 @@ class ConfigIP(ConfigSequence):
                value = ""
                block_strlen = []
                for i in self._value:
-                       block_strlen.append(len(str(i)))        
-                       if len(value):
+                       block_strlen.append(len(str(i)))
+                       if value:
                                value += self.seperator
                        value += str(i)
                leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
                rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
                mBlock = range(leftPos, rightPos)
                return (value, mBlock)
-       
+
        def getMulti(self, selected):
                (value, mBlock) = self.genText()
                if self.enabled:
@@ -613,28 +720,30 @@ class ConfigIP(ConfigSequence):
                # we definitely don't want leading zeros
                return '.'.join(["%d" % d for d in self.value])
 
+mac_limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)]
 class ConfigMAC(ConfigSequence):
        def __init__(self, default):
-               ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
+               ConfigSequence.__init__(self, seperator = ":", limits = mac_limits, default = default)
 
 class ConfigPosition(ConfigSequence):
        def __init__(self, default, args):
                ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
 
+clock_limits = [(0,23),(0,59)]
 class ConfigClock(ConfigSequence):
        def __init__(self, default):
-               import time
-               t = time.localtime(default)
-               ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
+               t = localtime(default)
+               ConfigSequence.__init__(self, seperator = ":", limits = clock_limits, default = [t.tm_hour, t.tm_min])
 
        def increment(self):
                # Check if Minutes maxed out
                if self._value[1] == 59:
-                       # Check if Hours not maxed out
+                       # Increment Hour, reset Minutes
                        if self._value[0] < 23:
-                               # Increment Hour, reset Minutes to 0
                                self._value[0] += 1
-                               self._value[1] = 0
+                       else:
+                               self._value[0] = 0
+                       self._value[1] = 0
                else:
                        # Increment Minutes
                        self._value[1] += 1
@@ -644,21 +753,23 @@ class ConfigClock(ConfigSequence):
        def decrement(self):
                # Check if Minutes is minimum
                if self._value[1] == 0:
-                       # Check if Hour is greater than 0
+                       # Decrement Hour, set Minutes to 59
                        if self._value[0] > 0:
-                               # Decrement Hour, set Minutes to 59
                                self._value[0] -= 1
-                               self._value[1] = 59
+                       else:
+                               self._value[0] = 23
+                       self._value[1] = 59
                else:
                        # Decrement Minutes
                        self._value[1] -= 1
                # Trigger change
                self.changed()
 
+integer_limits = (0, 9999999999)
 class ConfigInteger(ConfigSequence):
-       def __init__(self, default, limits = (0, 9999999999)):
+       def __init__(self, default, limits = integer_limits):
                ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
-       
+
        # you need to override this to do input validation
        def setValue(self, value):
                self._value = [value]
@@ -666,7 +777,7 @@ class ConfigInteger(ConfigSequence):
 
        def getValue(self):
                return self._value[0]
-       
+
        value = property(getValue, setValue)
 
        def fromstring(self, value):
@@ -700,7 +811,7 @@ class ConfigText(ConfigElement, NumericalTextInput):
        def __init__(self, default = "", fixed_size = True, visible_width = False):
                ConfigElement.__init__(self)
                NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
-               
+
                self.marked_pos = 0
                self.allmarked = (default != "")
                self.fixed_size = fixed_size
@@ -711,24 +822,25 @@ class ConfigText(ConfigElement, NumericalTextInput):
                self.value = self.last_value = self.default = default
 
        def validateMarker(self):
+               textlen = len(self.text)
                if self.fixed_size:
-                       if self.marked_pos > len(self.text)-1:
-                               self.marked_pos = len(self.text)-1
+                       if self.marked_pos > textlen-1:
+                               self.marked_pos = textlen-1
                else:
-                       if self.marked_pos > len(self.text):
-                               self.marked_pos = len(self.text)
+                       if self.marked_pos > textlen:
+                               self.marked_pos = textlen
                if self.marked_pos < 0:
                        self.marked_pos = 0
                if self.visible_width:
                        if self.marked_pos < self.offset:
                                self.offset = self.marked_pos
                        if self.marked_pos >= self.offset + self.visible_width:
-                               if self.marked_pos == len(self.text):
+                               if self.marked_pos == textlen:
                                        self.offset = self.marked_pos - self.visible_width
                                else:
                                        self.offset = self.marked_pos - self.visible_width + 1
-                       if self.offset > 0 and self.offset + self.visible_width > len(self.text):
-                               self.offset = max(0, len(self.text) - self.visible_width)
+                       if self.offset > 0 and self.offset + self.visible_width > textlen:
+                               self.offset = max(0, len - self.visible_width)
 
        def insertChar(self, ch, pos, owr):
                if owr or self.overwrite:
@@ -895,7 +1007,7 @@ class ConfigPassword(ConfigText):
                if self.hidden:
                        text = len(text) * self.censor_char
                return (mtext, text, mark)
-                       
+
        def onSelect(self, session):
                ConfigText.onSelect(self, session)
                self.hidden = False
@@ -910,13 +1022,20 @@ class ConfigNumber(ConfigText):
 
        def getValue(self):
                return int(self.text)
-               
+
        def setValue(self, val):
                self.text = str(val)
 
        value = property(getValue, setValue)
        _value = property(getValue, setValue)
 
+       def isChanged(self):
+               sv = self.saved_value
+               strv = self.tostring(self.value)
+               if sv is None and strv == self.default:
+                       return False
+               return strv != sv
+
        def conform(self):
                pos = len(self.text) - self.marked_pos
                self.text = self.text.lstrip("0")
@@ -963,17 +1082,21 @@ class ConfigSearchText(ConfigText):
 class ConfigDirectory(ConfigText):
        def __init__(self, default="", visible_width=60):
                ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
+
        def handleKey(self, key):
                pass
+
        def getValue(self):
                if self.text == "":
                        return None
                else:
                        return ConfigText.getValue(self)
+
        def setValue(self, val):
                if val == None:
                        val = ""
                ConfigText.setValue(self, val)
+
        def getMulti(self, selected):
                if self.text == "":
                        return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
@@ -1030,41 +1153,31 @@ class ConfigSatlist(ConfigSelection):
                if self.value == "":
                        return None
                return int(self.value)
-       
+
        orbital_position = property(getOrbitalPosition)
 
 class ConfigSet(ConfigElement):
        def __init__(self, choices, default = []):
                ConfigElement.__init__(self)
-               self.choices = []
-               self.description = {}
                if isinstance(choices, list):
                        choices.sort()
-                       for x in choices:
-                               if isinstance(x, tuple):
-                                       self.choices.append(x[0])
-                                       self.description[x[0]] = str(x[1])
-                               else:
-                                       self.choices.append(x)
-                                       self.description[x] = str(x)
+                       self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
                else:
                        assert False, "ConfigSet choices must be a list!"
-               if len(self.choices) == 0:
-                       self.choices = [""]
-                       self.description[""] = ""
                if default is None:
                        default = []
                self.pos = -1
                default.sort()
                self.last_value = self.default = default
-               self.value = default+[]
+               self.value = default[:]
 
        def toggleChoice(self, choice):
-               if choice in self.value:
-                       self.value.remove(choice)
+               value = self.value
+               if choice in value:
+                       value.remove(choice)
                else:
-                       self.value.append(choice)
-                       self.value.sort()
+                       value.append(choice)
+                       value.sort()
                self.changed()
 
        def handleKey(self, key):
@@ -1072,14 +1185,16 @@ class ConfigSet(ConfigElement):
                        if self.pos != -1:
                                self.toggleChoice(self.choices[self.pos])
                elif key == KEY_LEFT:
-                       self.pos -= 1
-                       if self.pos < -1:
-                           self.pos = len(self.choices)-1
+                       if self.pos < 0:
+                               self.pos = len(self.choices)-1
+                       else:
+                               self.pos -= 1
                elif key == KEY_RIGHT:
-                       self.pos += 1
-                       if self.pos >= len(self.choices):
-                           self.pos = -1
-               elif key in [KEY_HOME, KEY_END]:
+                       if self.pos >= len(self.choices)-1:
+                               self.pos = -1
+                       else:
+                               self.pos += 1
+               elif key in (KEY_HOME, KEY_END):
                        self.pos = -1
 
        def genString(self, lst):
@@ -1095,7 +1210,7 @@ class ConfigSet(ConfigElement):
                if not selected or self.pos == -1:
                        return ("text", self.genString(self.value))
                else:
-                       tmp = self.value+[]
+                       tmp = self.value[:]
                        ch = self.choices[self.pos]
                        mem = ch in self.value
                        if not mem:
@@ -1108,20 +1223,23 @@ class ConfigSet(ConfigElement):
                                chstr = " "+self.description[ch]+" "
                        else:
                                chstr = "("+self.description[ch]+")"
-                       return ("mtext", val1+chstr+val2, range(len(val1),len(val1)+len(chstr)))
+                       len_val1 = len(val1)
+                       return ("mtext", val1+chstr+val2, range(len_val1, len_val1 + len(chstr)))
 
        def onDeselect(self, session):
                self.pos = -1
                if not self.last_value == self.value:
                        self.changedFinal()
-                       self.last_value = self.value+[]
-               
+                       self.last_value = self.value[:]
+
        def tostring(self, value):
                return str(value)
 
        def fromstring(self, val):
                return eval(val)
 
+       description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
+
 class ConfigLocations(ConfigElement):
        def __init__(self, default = [], visible_width = False):
                ConfigElement.__init__(self)
@@ -1131,22 +1249,25 @@ class ConfigLocations(ConfigElement):
                self.locations = []
                self.mountpoints = []
                harddiskmanager.on_partition_list_change.append(self.mountpointsChanged)
-               self.value = default+[]
+               self.value = default[:]
 
        def setValue(self, value):
-               loc = [x[0] for x in self.locations if x[3]]
+               locations = self.locations
+               loc = [x[0] for x in locations if x[3]]
                add = [x for x in value if not x in loc]
                diff = add + [x for x in loc if not x in value]
-               self.locations = [x for x in self.locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
-               self.locations.sort(key = lambda x: x[0])
+               locations = [x for x in locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
+               locations.sort(key = lambda x: x[0])
+               self.locations = locations
                self.changed()
 
        def getValue(self):
                self.checkChangedMountpoints()
-               for x in self.locations:
+               locations = self.locations
+               for x in locations:
                        x[3] = x[2]
-               return [x[0] for x in self.locations if x[3]]
-       
+               return [x[0] for x in locations if x[3]]
+
        value = property(getValue, setValue)
 
        def tostring(self, value):
@@ -1161,24 +1282,27 @@ class ConfigLocations(ConfigElement):
                        tmp = self.default
                else:
                        tmp = self.fromstring(sv)
-               self.locations = [[x, None, False, False] for x in tmp]
+               locations = [[x, None, False, False] for x in tmp]
                self.refreshMountpoints()
-               for x in self.locations:
-                       if os.path.exists(x[0]):
+               for x in locations:
+                       if os_path.exists(x[0]):
                                x[1] = self.getMountpoint(x[0])
                                x[2] = True
+               self.locations = locations
 
        def save(self):
-               if self.save_disabled or self.locations == []:
+               locations = self.locations
+               if self.save_disabled or not locations:
                        self.saved_value = None
                else:
-                       self.saved_value = self.tostring([x[0] for x in self.locations])
+                       self.saved_value = self.tostring([x[0] for x in locations])
 
        def isChanged(self):
                sv = self.saved_value
-               if val is None and self.locations == []:
+               locations = self.locations
+               if val is None and not locations:
                        return False
-               return self.tostring([x[0] for x in self.locations]) != sv
+               return self.tostring([x[0] for x in locations]) != sv
 
        def mountpointsChanged(self, action, dev):
                print "Mounts changed: ", action, dev
@@ -1193,7 +1317,7 @@ class ConfigLocations(ConfigElement):
                for x in self.locations:
                        if x[1] == mp:
                                x[2] = True
-                       elif x[1] == None and os.path.exists(x[0]):
+                       elif x[1] == None and os_path.exists(x[0]):
                                x[1] = self.getMountpoint(x[0])
                                x[2] = True
 
@@ -1201,7 +1325,7 @@ class ConfigLocations(ConfigElement):
                for x in self.locations:
                        if x[1] == mp:
                                x[2] = False
-               
+
        def refreshMountpoints(self):
                self.mountpoints = [p.mountpoint + "/" for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
                self.mountpoints.sort(key = lambda x: -len(x))
@@ -1209,17 +1333,18 @@ class ConfigLocations(ConfigElement):
        def checkChangedMountpoints(self):
                oldmounts = self.mountpoints
                self.refreshMountpoints()
-               if oldmounts == self.mountpoints:
+               newmounts = self.mountpoints
+               if oldmounts == newmounts:
                        return
                for x in oldmounts:
-                       if not x in self.mountpoints:
+                       if not x in newmounts:
                                self.removedMount(x)
-               for x in self.mountpoints:
+               for x in newmounts:
                        if not x in oldmounts:
                                self.addedMount(x)
 
        def getMountpoint(self, file):
-               file = os.path.realpath(file)+"/"
+               file = os_path.realpath(file)+"/"
                for m in self.mountpoints:
                        if file.startswith(m):
                                return m
@@ -1229,12 +1354,12 @@ class ConfigLocations(ConfigElement):
                if key == KEY_LEFT:
                        self.pos -= 1
                        if self.pos < -1:
-                           self.pos = len(self.value)-1
+                               self.pos = len(self.value)-1
                elif key == KEY_RIGHT:
                        self.pos += 1
                        if self.pos >= len(self.value):
-                           self.pos = -1
-               elif key in [KEY_HOME, KEY_END]:
+                               self.pos = -1
+               elif key in (KEY_HOME, KEY_END):
                        self.pos = -1
 
        def getText(self):
@@ -1270,11 +1395,11 @@ class ConfigLocations(ConfigElement):
 
        def onDeselect(self, session):
                self.pos = -1
-               
+
 # nothing.
 class ConfigNothing(ConfigSelection):
        def __init__(self):
-               ConfigSelection.__init__(self, choices = [""])
+               ConfigSelection.__init__(self, choices = [("","")])
 
 # until here, 'saved_value' always had to be a *string*.
 # now, in ConfigSubsection, and only there, saved_value
@@ -1287,7 +1412,6 @@ class ConfigNothing(ConfigSelection):
 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
 #
 
-
 class ConfigSubsectionContent(object):
        pass
 
@@ -1303,22 +1427,21 @@ class ConfigSubsectionContent(object):
 # config.dipswitches.append(ConfigYesNo())
 class ConfigSubList(list, object):
        def __init__(self):
-               object.__init__(self)
                list.__init__(self)
                self.stored_values = {}
 
        def save(self):
                for x in self:
                        x.save()
-       
+
        def load(self):
                for x in self:
                        x.load()
 
        def getSavedValue(self):
-               res = {}
-               for i in range(len(self)):
-                       sv = self[i].saved_value
+               res = { }
+               for i, val in enumerate(self):
+                       sv = val.saved_value
                        if sv is not None:
                                res[str(i)] = sv
                return res
@@ -1339,10 +1462,7 @@ class ConfigSubList(list, object):
                        item.load()
 
        def dict(self):
-               res = dict()
-               for index in range(len(self)):
-                       res[str(index)] = self[index]
-               return res
+               return dict([(str(index), value) for index, value in enumerate(self)])
 
 # same as ConfigSubList, just as a dictionary.
 # care must be taken that the 'key' has a proper
@@ -1350,14 +1470,13 @@ class ConfigSubList(list, object):
 # file.
 class ConfigSubDict(dict, object):
        def __init__(self):
-               object.__init__(self)
                dict.__init__(self)
                self.stored_values = {}
 
        def save(self):
                for x in self.values():
                        x.save()
-       
+
        def load(self):
                for x in self.values():
                        x.load()
@@ -1394,25 +1513,26 @@ class ConfigSubDict(dict, object):
 # loading of added elements. this is why this class
 # is so complex.
 #
-# we need the 'content' because we overwrite 
+# we need the 'content' because we overwrite
 # __setattr__.
 # If you don't understand this, try adding
 # __setattr__ to a usual exisiting class and you will.
 class ConfigSubsection(object):
        def __init__(self):
-               object.__init__(self)
                self.__dict__["content"] = ConfigSubsectionContent()
                self.content.items = { }
                self.content.stored_values = { }
-       
+
        def __setattr__(self, name, value):
                if name == "saved_value":
                        return self.setSavedValue(value)
-               assert isinstance(value, ConfigSubsection) or isinstance(value, ConfigElement) or isinstance(value, ConfigSubList) or isinstance(value, ConfigSubDict), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
-               self.content.items[name] = value
-               if name in self.content.stored_values:
-                       #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
-                       value.saved_value = self.content.stored_values[name]
+               assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
+               content = self.content
+               content.items[name] = value
+               x = content.stored_values.get(name, None)
+               if x is not None:
+                       #print "ok, now we have a new item,", name, "and have the following value for it:", x
+                       value.saved_value = x
                        value.load()
 
        def __getattr__(self, name):
@@ -1430,12 +1550,11 @@ class ConfigSubsection(object):
 
        def setSavedValue(self, values):
                values = dict(values)
-               
                self.content.stored_values = values
-
                for (key, val) in self.content.items.items():
-                       if key in values:
-                               val.saved_value = values[key]
+                       value = values.get(key, None)
+                       if value is not None:
+                               val.saved_value = value
 
        saved_value = property(getSavedValue, setSavedValue)
 
@@ -1463,26 +1582,25 @@ class Config(ConfigSubsection):
 
        def pickle_this(self, prefix, topickle, result):
                for (key, val) in topickle.items():
-                       name = prefix + "." + key
-                       
+                       name = '.'.join((prefix, key))
                        if isinstance(val, dict):
                                self.pickle_this(name, val, result)
                        elif isinstance(val, tuple):
-                               result.append(name + "=" + val[0]) # + " ; " + val[1])
+                               result += [name, '=', val[0], '\n']
                        else:
-                               result.append(name + "=" + val)
+                               result += [name, '=', val, '\n']
 
        def pickle(self):
-               result = [ ]
+               result = []
                self.pickle_this("config", self.saved_value, result)
-               return '\n'.join(result) + "\n"
+               return ''.join(result)
 
        def unpickle(self, lines):
                tree = { }
                for l in lines:
-                       if not len(l) or l[0] == '#':
+                       if not l or l[0] == '#':
                                continue
-                       
+
                        n = l.find('=')
                        val = l[n+1:].strip()
 
@@ -1491,10 +1609,10 @@ class Config(ConfigSubsection):
 #                              val = val[:val.find(' ')]
 
                        base = tree
-                       
+
                        for n in names[:-1]:
                                base = base.setdefault(n, {})
-                       
+
                        base[names[-1]] = val
 
                # we inherit from ConfigSubsection, so ...
@@ -1503,8 +1621,9 @@ class Config(ConfigSubsection):
                        self.setSavedValue(tree["config"])
 
        def saveToFile(self, filename):
+               text = self.pickle()
                f = open(filename, "w")
-               f.write(self.pickle())
+               f.write(text)
                f.close()
 
        def loadFromFile(self, filename):
@@ -1523,19 +1642,20 @@ class ConfigFile:
                        config.loadFromFile(self.CONFIG_FILE)
                except IOError, e:
                        print "unable to load config (%s), assuming defaults..." % str(e)
-       
+
        def save(self):
 #              config.save()
                config.saveToFile(self.CONFIG_FILE)
-       
+
        def __resolveValue(self, pickles, cmap):
-               if cmap.has_key(pickles[0]):
+               key = pickles[0]
+               if cmap.has_key(key):
                        if len(pickles) > 1:
-                               return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
+                               return self.__resolveValue(pickles[1:], cmap[key].dict())
                        else:
-                               return str(cmap[pickles[0]].value)
+                               return str(cmap[key].value)
                return None
-       
+
        def getResolvedKey(self, key):
                names = key.split('.')
                if len(names) > 1: