another useless fix
[enigma2.git] / lib / python / Components / config.py
index b5a0bbbdba8049a1a93c7e9996827f95b6fb2b44..7df6e762f7c3df5d0fa86e54d3b31c91acfb253e 100644 (file)
@@ -1,6 +1,7 @@
 import time
 from Tools.NumericalTextInput import NumericalTextInput
 from Tools.Directories import resolveFilename, SCOPE_CONFIG
+import copy
 
 
 # ConfigElement, the base class of all ConfigElements.
@@ -25,6 +26,7 @@ from Tools.Directories import resolveFilename, SCOPE_CONFIG
 #
 class ConfigElement(object):
        def __init__(self):
+
                object.__init__(self)
                self.saved_value = None
                self.save_disabled = False
@@ -65,14 +67,30 @@ class ConfigElement(object):
        def cancel(self):
                self.load()
 
+       def isChanged(self):
+               if self.saved_value is None and self.value == self.default:
+                       return False
+               return self.tostring(self.value) != self.saved_value
+
        def changed(self):
                for x in self.notifiers:
                        x(self)
                        
-       def addNotifier(self, notifier):
+       def addNotifier(self, notifier, initial_call = True):
                assert callable(notifier), "notifiers must be callable"
                self.notifiers.append(notifier)
 
+               # CHECKME:
+               # do we want to call the notifier
+               #  - at all when adding it? (yes, though optional)
+               #  - when the default is active? (yes)
+               #  - when no value *yet* has been set,
+               #    because no config has ever been read (currently yes)
+               #    (though that's not so easy to detect.
+               #     the entry could just be new.)
+               if initial_call:
+                       notifier(self)
+
        def disableSave(self):
                self.save_disabled = True
 
@@ -124,7 +142,10 @@ class ConfigSelection(ConfigElement):
                else:
                        assert False, "ConfigSelection choices must be dict or list!"
                
-               assert len(self.choices), "you can't have an empty configselection"
+               #assert len(self.choices), "you can't have an empty configselection"
+               if len(self.choices) == 0:
+                       self.choices = [""]
+                       self.description[""] = ""
 
                if default is None:
                        default = self.choices[0]
@@ -144,11 +165,18 @@ class ConfigSelection(ConfigElement):
                self.changed()
 
        def tostring(self, val):
-               return (val, ','.join(self.choices))
+               return val
 
        def getValue(self):
                return self._value
 
+       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._value = text
+
        value = property(getValue, setValue)
        
        def getIndex(self):
@@ -164,12 +192,18 @@ class ConfigSelection(ConfigElement):
                        self.value = self.choices[(i + nchoices - 1) % nchoices]
                elif key == KEY_RIGHT:
                        self.value = self.choices[(i + 1) % nchoices]
-               elif key == KEY_TIMEOUT:
-                       self.timeout()
-                       return
+
+       def getText(self):
+               descr = self.description[self.value]
+               if len(descr):
+                       return _(descr)
+               return descr
 
        def getMulti(self, selected):
-               return ("text", self.description[self.value])
+               descr = self.description[self.value]
+               if len(descr):
+                       return ("text", _(descr))
+               return ("text", descr)
 
        # HTML
        def getHTML(self, id):
@@ -200,10 +234,19 @@ class ConfigBoolean(ConfigElement):
                if key in [KEY_LEFT, KEY_RIGHT]:
                        self.value = not self.value
 
+       def getText(self):
+               descr = self.descriptions[self.value]
+               if len(descr):
+                       return _(descr)
+               return descr
+
        def getMulti(self, selected):
-               return ("text", _(self.descriptions[self.value]))
+               descr = self.descriptions[self.value]
+               if len(descr):
+                       return ("text", _(descr))
+               return ("text", descr)
 
-       def tostring(self, value):
+       def tostring(self, value):
                if not value:
                        return "false"
                else:
@@ -254,6 +297,9 @@ class ConfigDateTime(ConfigElement):
                if key == KEY_RIGHT:
                        self.value = self.value + self.increment
 
+       def getText(self):
+               return time.strftime(self.formatstring, time.localtime(self.value))
+
        def getMulti(self, selected):
                return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
 
@@ -280,7 +326,8 @@ class ConfigSequence(ConfigElement):
                self.limits = limits
                self.censor_char = censor_char
                
-               self.value = self.default = default
+               self.default = default
+               self.value = copy.copy(default)
 
        def validate(self):
                max_pos = 0
@@ -289,7 +336,7 @@ class ConfigSequence(ConfigElement):
                        max_pos += len(str(self.limits[num][1]))
 
                        while self._value[num] < self.limits[num][0]:
-                               self.value[num] += 1
+                               self._value[num] += 1
 
                        while self._value[num] > self.limits[num][1]:
                                self._value[num] -= 1
@@ -321,7 +368,6 @@ class ConfigSequence(ConfigElement):
                        self.validatePos()
                
                if key in KEY_NUMBERS:
-                       print "is number"
                        block_len = []
                        for x in self.limits:
                                block_len.append(len(str(x[1])))
@@ -356,10 +402,8 @@ class ConfigSequence(ConfigElement):
                
                        self.validate()
                        self.changed()
-                       
-                       print "res:", self._value
-
-       def getMulti(self, selected):
+       
+       def genText(self):
                value = ""
                mPos = self.marked_pos
                num = 0;
@@ -372,9 +416,16 @@ class ConfigSequence(ConfigElement):
                        if self.censor_char == "":
                                value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
                        else:
-                               value += (self.censorChar * len(str(self.limits[num][1])))
+                               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
                        # (this code is heavily ink optimized!)
                if self.enabled:
@@ -389,11 +440,15 @@ class ConfigSequence(ConfigElement):
                return str(v)
 
        def fromstring(self, value):
-               return [int(x) for x in self.saved_value.split(self.seperator)]
+               return [int(x) for x in value.split(self.seperator)]
 
 class ConfigIP(ConfigSequence):
        def __init__(self, default):
                ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
+       
+       def getHTML(self, id):
+               # we definitely don't want leading zeros
+               return '.'.join(["%d" % d for d in self.value])
 
 class ConfigMAC(ConfigSequence):
        def __init__(self, default):
@@ -405,10 +460,12 @@ class ConfigPosition(ConfigSequence):
 
 class ConfigClock(ConfigSequence):
        def __init__(self, default):
-               ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = default)
+               import time
+               t = time.localtime(default)
+               ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
 
 class ConfigInteger(ConfigSequence):
-       def __init__(self, default, limits):
+       def __init__(self, default, limits = (0, 10000000000)):
                ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
        
        # you need to override this to do input validation
@@ -427,9 +484,16 @@ class ConfigInteger(ConfigSequence):
        def tostring(self, value):
                return str(value)
 
-class ConfigPIN(ConfigSequence):
+class ConfigPIN(ConfigInteger):
        def __init__(self, default, len = 4, censor = ""):
-               ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = [default])
+               assert isinstance(default, int), "ConfigPIN default must be an integer"
+               if default == -1:
+                       default = "aaaa"
+               ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
+               self.len = len
+
+       def getLength(self):
+               return self.len
 
 class ConfigFloat(ConfigSequence):
        def __init__(self, default, limits):
@@ -452,10 +516,10 @@ class ConfigText(ConfigElement, NumericalTextInput):
                self.value = self.default = default
 
        def validateMarker(self):
-               if self.marked_pos < 0:
-                       self.marked_pos = 0
                if self.marked_pos >= len(self.text):
                        self.marked_pos = len(self.text) - 1
+               if self.marked_pos < 0:
+                       self.marked_pos = 0
 
        #def nextEntry(self):
        #       self.vals[1](self.getConfigPath())
@@ -469,12 +533,10 @@ class ConfigText(ConfigElement, NumericalTextInput):
                        self.marked_pos -= 1
                elif key == KEY_RIGHT:
                        self.marked_pos += 1
-                       if not self.fixed_size:
-                               if self.marked_pos >= len(self.text):
-                                       self.text = self.text.ljust(len(self.text) + 1)
+                       self.maybeExpand()
                elif key in KEY_NUMBERS:
                        number = self.getKey(getKeyNumber(key))
-                       self.text = self.text[0:self.marked_pos] + str(number) + self.text[self.marked_pos + 1:]
+                       self.text = self.text[0:self.marked_pos] + unicode(number) + self.text[self.marked_pos + 1:]
                elif key == KEY_TIMEOUT:
                        self.timeout()
                        return
@@ -482,8 +544,14 @@ class ConfigText(ConfigElement, NumericalTextInput):
                self.validateMarker()
                self.changed()
 
+       def maybeExpand(self):
+               if not self.fixed_size:
+                       if self.marked_pos >= len(self.text):
+                               self.text = self.text.ljust(len(self.text) + 1)
+
        def nextFunc(self):
                self.marked_pos += 1
+               self.maybeExpand()
                self.validateMarker()
                self.changed()
 
@@ -500,12 +568,13 @@ class ConfigText(ConfigElement, NumericalTextInput):
        value = property(getValue, setValue)
        _value = property(getValue, setValue)
 
+       def getText(self):
+               return self.value
+
        def getMulti(self, selected):
                return ("mtext"[1-selected:], self.value, [self.marked_pos])
 
        def helpWindow(self):
-               print "helpWindow for text!"
-
                from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
                return (NumericalTextInputHelpDialog,self)
 
@@ -542,6 +611,9 @@ class ConfigSlider(ConfigElement):
                self.checkValues()
                self.changed()
 
+       def getText(self):
+               return "%d / %d" % (self.value, self.max)
+
        def getMulti(self, selected):
                self.checkValues()
                return ("slider", self.value, self.max)
@@ -554,17 +626,17 @@ class ConfigSatlist(ConfigSelection):
        def __init__(self, list, default = None):
                if default is not None:
                        default = str(default)
-               if list == [ ]:
-                       list = [0, "N/A"]
                ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc) in list], default = default)
 
        def getOrbitalPosition(self):
+               if self.value == "":
+                       return None
                return int(self.value)
        
        orbital_position = property(getOrbitalPosition)
 
 # nothing.
-class ConfigDummy(ConfigSelection):
+class ConfigNothing(ConfigSelection):
        def __init__(self):
                ConfigSelection.__init__(self, choices = [""])
 
@@ -624,12 +696,18 @@ class ConfigSubList(list, object):
        saved_value = property(getSavedValue, setSavedValue)
        
        def append(self, item):
-               list.append(self, item)
                i = str(len(self))
+               list.append(self, item)
                if i in self.stored_values:
                        item.saved_value = self.stored_values[i]
                        item.load()
 
+       def dict(self):
+               res = dict()
+               for index in range(len(self)):
+                       res[str(index)] = self[index]
+               return res
+
 # same as ConfigSubList, just as a dictionary.
 # care must be taken that the 'key' has a proper
 # str() method, because it will be used in the config
@@ -669,6 +747,9 @@ class ConfigSubDict(dict, object):
                        item.saved_value = self.stored_values[str(key)]
                        item.load()
 
+       def dict(self):
+               return self
+
 # Like the classes above, just with a more "native"
 # syntax.
 #
@@ -690,6 +771,7 @@ class ConfigSubsection(object):
        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]
@@ -704,6 +786,9 @@ class ConfigSubsection(object):
                for (key, val) in self.content.items.items():
                        if val.saved_value is not None:
                                res[key] = val.saved_value
+                       elif key in res:
+                               del res[key]
+                               
                return res
 
        def setSavedValue(self, values):
@@ -725,6 +810,9 @@ class ConfigSubsection(object):
                for x in self.content.items.values():
                        x.load()
 
+       def dict(self):
+               return self.content.items
+
 # the root config object, which also can "pickle" (=serialize)
 # down the whole config tree.
 #
@@ -774,7 +862,8 @@ class Config(ConfigSubsection):
 
                # we inherit from ConfigSubsection, so ...
                #object.__setattr__(self, "saved_value", tree["config"])
-               self.setSavedValue(tree["config"])
+               if "config" in tree:
+                       self.setSavedValue(tree["config"])
 
        def saveToFile(self, filename):
                f = open(filename, "w")
@@ -790,7 +879,7 @@ config = Config()
 config.misc = ConfigSubsection()
 
 class ConfigFile:
-       CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "config2")
+       CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
 
        def load(self):
                try:
@@ -799,11 +888,26 @@ class ConfigFile:
                        print "unable to load config (%s), assuming defaults..." % str(e)
        
        def save(self):
-               config.save()
+#              config.save()
                config.saveToFile(self.CONFIG_FILE)
        
+       def __resolveValue(self, pickles, cmap):
+               if cmap.has_key(pickles[0]):
+                       if len(pickles) > 1:
+                               return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
+                       else:
+                               return str(cmap[pickles[0]].value)
+               return None
+       
        def getResolvedKey(self, key):
-               return None # FIXME
+               names = key.split('.')
+               if len(names) > 1:
+                       if names[0] == "config":
+                               ret=self.__resolveValue(names[1:], config.content.items)
+                               if ret and len(ret):
+                                       return ret
+               print "getResolvedKey", key, "failed !! (Typo??)"
+               return ""
 
 def NoSave(element):
        element.disableSave()
@@ -813,8 +917,9 @@ configfile = ConfigFile()
 
 configfile.load()
 
-def getConfigListEntry(desc, config):
-       return (desc, config)
+def getConfigListEntry(*args):
+       assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
+       return args
 
 #def _(x):
 #      return x