2 from Tools.NumericalTextInput import NumericalTextInput
3 from Tools.Directories import resolveFilename, SCOPE_CONFIG
7 # ConfigElement, the base class of all ConfigElements.
10 # value the current value, usefully encoded.
11 # usually a property which retrieves _value,
12 # and maybe does some reformatting
13 # _value the value as it's going to be saved in the configfile,
14 # though still in non-string form.
15 # this is the object which is actually worked on.
16 # default the initial value. If _value is equal to default,
17 # it will not be stored in the config file
18 # saved_value is a text representation of _value, stored in the config file
20 # and has (at least) the following methods:
21 # save() stores _value into saved_value,
22 # (or stores 'None' if it should not be stored)
23 # load() loads _value from saved_value, or loads
24 # the default if saved_value is 'None' (default)
27 class ConfigElement(object):
31 self.saved_value = None
32 self.save_disabled = False
36 # you need to override this to do input validation
37 def setValue(self, value):
44 value = property(getValue, setValue)
46 # you need to override this if self.value is not a string
47 def fromstring(self, value):
50 # you can overide this for fancy default handling
52 if self.saved_value is None:
53 self.value = self.default
55 self.value = self.fromstring(self.saved_value)
57 def tostring(self, value):
60 # you need to override this if str(self.value) doesn't work
62 if self.save_disabled or self.value == self.default:
63 self.saved_value = None
65 self.saved_value = self.tostring(self.value)
71 if self.saved_value is None and self.value == self.default:
73 return self.tostring(self.value) != self.saved_value
76 for x in self.notifiers:
79 def addNotifier(self, notifier, initial_call = True):
80 assert callable(notifier), "notifiers must be callable"
81 self.notifiers.append(notifier)
84 # do we want to call the notifier
85 # - at all when adding it? (yes, though optional)
86 # - when the default is active? (yes)
87 # - when no value *yet* has been set,
88 # because no config has ever been read (currently yes)
89 # (though that's not so easy to detect.
90 # the entry could just be new.)
94 def disableSave(self):
95 self.save_disabled = True
97 def __call__(self, selected):
98 return self.getMulti(selected)
100 def helpWindow(self):
108 KEY_NUMBERS = range(12, 12+10)
112 def getKeyNumber(key):
113 assert key in KEY_NUMBERS
117 # ConfigSelection is a "one of.."-type.
118 # it has the "choices", usually a list, which contains
119 # (id, desc)-tuples (or just only the ids, in case the id
120 # will be used as description)
122 # all ids MUST be plain strings.
124 class ConfigSelection(ConfigElement):
125 def __init__(self, choices, default = None):
126 ConfigElement.__init__(self)
128 self.description = {}
130 if isinstance(choices, list):
132 if isinstance(x, tuple):
133 self.choices.append(x[0])
134 self.description[x[0]] = x[1]
136 self.choices.append(x)
137 self.description[x] = x
138 elif isinstance(choices, dict):
139 for (key, val) in choices.items():
140 self.choices.append(key)
141 self.description[key] = val
143 assert False, "ConfigSelection choices must be dict or list!"
145 #assert len(self.choices), "you can't have an empty configselection"
146 if len(self.choices) == 0:
148 self.description[""] = ""
151 default = self.choices[0]
153 assert default in self.choices, "default must be in choice list, but " + repr(default) + " is not!"
154 for x in self.choices:
155 assert isinstance(x, str), "ConfigSelection choices must be strings"
157 self.value = self.default = default
159 def setValue(self, value):
160 if value in self.choices:
163 self._value = self.default
167 def tostring(self, val):
173 def setCurrentText(self, text):
174 i = self.choices.index(self.value)
175 del self.description[self.choices[i]]
176 self.choices[i] = text
177 self.description[text] = text
180 value = property(getValue, setValue)
183 return self.choices.index(self.value)
185 index = property(getIndex)
188 def handleKey(self, key):
189 nchoices = len(self.choices)
190 i = self.choices.index(self.value)
192 self.value = self.choices[(i + nchoices - 1) % nchoices]
193 elif key == KEY_RIGHT:
194 self.value = self.choices[(i + 1) % nchoices]
197 return _(self.description[self.value])
199 def getMulti(self, selected):
200 return ("text", _(self.description[self.value]))
203 def getHTML(self, id):
205 for v in self.choices:
207 checked = 'checked="checked" '
210 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n"
213 def unsafeAssign(self, value):
214 # setValue does check if value is in choices. This is safe enough.
219 # several customized versions exist for different
222 class ConfigBoolean(ConfigElement):
223 def __init__(self, default = False, descriptions = {False: "false", True: "true"}):
224 ConfigElement.__init__(self)
225 self.descriptions = descriptions
226 self.value = self.default = default
227 def handleKey(self, key):
228 if key in [KEY_LEFT, KEY_RIGHT]:
229 self.value = not self.value
232 return _(self.descriptions[self.value])
234 def getMulti(self, selected):
235 return ("text", _(self.descriptions[self.value]))
237 def tostring(self, value):
243 def fromstring(self, val):
249 def getHTML(self, id):
251 checked = ' checked="checked"'
254 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
256 # this is FLAWED. and must be fixed.
257 def unsafeAssign(self, value):
263 class ConfigYesNo(ConfigBoolean):
264 def __init__(self, default = False):
265 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")})
267 class ConfigOnOff(ConfigBoolean):
268 def __init__(self, default = False):
269 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")})
271 class ConfigEnableDisable(ConfigBoolean):
272 def __init__(self, default = False):
273 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")})
275 class ConfigDateTime(ConfigElement):
276 def __init__(self, default, formatstring, increment = 86400):
277 ConfigElement.__init__(self)
278 self.increment = increment
279 self.formatstring = formatstring
280 self.value = self.default = int(default)
282 def handleKey(self, key):
284 self.value = self.value - self.increment
286 self.value = self.value + self.increment
290 return time.strftime(self.formatstring, time.localtime(self.value))
292 def getMulti(self, selected):
293 return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
295 def fromstring(self, val):
298 # *THE* mighty config element class
300 # allows you to store/edit a sequence of values.
301 # can be used for IP-addresses, dates, plain integers, ...
302 # several helper exist to ease this up a bit.
304 class ConfigSequence(ConfigElement):
305 def __init__(self, seperator, limits, censor_char = "", default = None):
306 ConfigElement.__init__(self)
307 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
308 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
309 #assert isinstance(default, list), "default must be a list"
310 #assert isinstance(default[0], int), "list must contain numbers"
311 #assert len(default) == len(limits), "length must match"
314 self.seperator = seperator
316 self.censor_char = censor_char
318 self.default = default
319 self.value = copy.copy(default)
324 for i in self._value:
325 max_pos += len(str(self.limits[num][1]))
327 while self._value[num] < self.limits[num][0]:
330 while self._value[num] > self.limits[num][1]:
331 self._value[num] -= 1
335 if self.marked_pos >= max_pos:
336 self.marked_pos = max_pos - 1
338 if self.marked_pos < 0:
341 def validatePos(self):
342 if self.marked_pos < 0:
345 total_len = sum([len(str(x[1])) for x in self.limits])
347 if self.marked_pos >= total_len:
348 self.marked_pos = total_len - 1
350 def handleKey(self, key):
359 if key in KEY_NUMBERS:
361 for x in self.limits:
362 block_len.append(len(str(x[1])))
364 total_len = sum(block_len)
368 block_len_total = [0, ]
370 pos += block_len[blocknumber]
371 block_len_total.append(pos)
372 if pos - 1 >= self.marked_pos:
377 number = getKeyNumber(key)
379 # length of numberblock
380 number_len = len(str(self.limits[blocknumber][1]))
382 # position in the block
383 posinblock = self.marked_pos - block_len_total[blocknumber]
385 oldvalue = self._value[blocknumber]
386 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
387 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
389 self._value[blocknumber] = newvalue
397 mPos = self.marked_pos
399 for i in self._value:
400 if len(value): #fixme no heading separator possible
401 value += self.seperator
402 if mPos >= len(value) - 1:
405 if self.censor_char == "":
406 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
408 value += (self.censor_char * len(str(self.limits[num][1])))
413 (value, mPos) = self.genText()
416 def getMulti(self, selected):
417 (value, mPos) = self.genText()
418 # only mark cursor when we are selected
419 # (this code is heavily ink optimized!)
421 return ("mtext"[1-selected:], value, [mPos])
423 return ("text", value)
425 def tostring(self, val):
426 return self.seperator.join([self.saveSingle(x) for x in val])
428 def saveSingle(self, v):
431 def fromstring(self, value):
432 return [int(x) for x in self.saved_value.split(self.seperator)]
434 class ConfigIP(ConfigSequence):
435 def __init__(self, default):
436 ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
438 class ConfigMAC(ConfigSequence):
439 def __init__(self, default):
440 ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
442 class ConfigPosition(ConfigSequence):
443 def __init__(self, default, args):
444 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
446 class ConfigClock(ConfigSequence):
447 def __init__(self, default):
449 t = time.localtime(default)
450 ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
452 class ConfigInteger(ConfigSequence):
453 def __init__(self, default, limits = (0, 10000000000)):
454 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
456 # you need to override this to do input validation
457 def setValue(self, value):
458 self._value = [value]
462 return self._value[0]
464 value = property(getValue, setValue)
466 def fromstring(self, value):
469 def tostring(self, value):
472 class ConfigPIN(ConfigInteger):
473 def __init__(self, default, len = 4, censor = ""):
474 assert isinstance(default, int), "ConfigPIN default must be an integer"
477 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
483 class ConfigFloat(ConfigSequence):
484 def __init__(self, default, limits):
485 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
488 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
490 float = property(getFloat)
492 # an editable text...
493 class ConfigText(ConfigElement, NumericalTextInput):
494 def __init__(self, default = "", fixed_size = True):
495 ConfigElement.__init__(self)
496 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
499 self.fixed_size = fixed_size
501 self.value = self.default = default
503 def validateMarker(self):
504 if self.marked_pos < 0:
506 if self.marked_pos >= len(self.text):
507 self.marked_pos = len(self.text) - 1
509 #def nextEntry(self):
510 # self.vals[1](self.getConfigPath())
512 def handleKey(self, key):
513 # this will no change anything on the value itself
514 # so we can handle it here in gui element
515 if key == KEY_DELETE:
516 self.text = self.text[0:self.marked_pos] + self.text[self.marked_pos + 1:]
517 elif key == KEY_LEFT:
519 elif key == KEY_RIGHT:
521 if not self.fixed_size:
522 if self.marked_pos >= len(self.text):
523 self.text = self.text.ljust(len(self.text) + 1)
524 elif key in KEY_NUMBERS:
525 number = self.getKey(getKeyNumber(key))
526 self.text = self.text[0:self.marked_pos] + unicode(number) + self.text[self.marked_pos + 1:]
527 elif key == KEY_TIMEOUT:
531 self.validateMarker()
536 self.validateMarker()
540 return self.text.encode("utf-8")
542 def setValue(self, val):
544 self.text = val.decode("utf-8")
545 except UnicodeDecodeError:
549 value = property(getValue, setValue)
550 _value = property(getValue, setValue)
555 def getMulti(self, selected):
556 return ("mtext"[1-selected:], self.value, [self.marked_pos])
558 def helpWindow(self):
559 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
560 return (NumericalTextInputHelpDialog,self)
562 def getHTML(self, id):
563 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
565 def unsafeAssign(self, value):
566 self.value = str(value)
569 class ConfigSlider(ConfigElement):
570 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
571 ConfigElement.__init__(self)
572 self.value = self.default = default
575 self.increment = increment
577 def checkValues(self):
578 if self.value < self.min:
579 self.value = self.min
581 if self.value > self.max:
582 self.value = self.max
584 def handleKey(self, key):
586 self.value -= self.increment
587 elif key == KEY_RIGHT:
588 self.value += self.increment
596 return "%d / %d" % (self.value, self.max)
598 def getMulti(self, selected):
600 return ("slider", self.value, self.max)
602 def fromstring(self, value):
605 # a satlist. in fact, it's a ConfigSelection.
606 class ConfigSatlist(ConfigSelection):
607 def __init__(self, list, default = None):
608 if default is not None:
609 default = str(default)
610 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc) in list], default = default)
612 def getOrbitalPosition(self):
615 return int(self.value)
617 orbital_position = property(getOrbitalPosition)
620 class ConfigNothing(ConfigSelection):
622 ConfigSelection.__init__(self, choices = [""])
624 # until here, 'saved_value' always had to be a *string*.
625 # now, in ConfigSubsection, and only there, saved_value
626 # is a dict, essentially forming a tree.
628 # config.foo.bar=True
629 # config.foobar=False
632 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
636 class ConfigSubsectionContent(object):
639 # we store a backup of the loaded configuration
640 # data in self.stored_values, to be able to deploy
641 # them when a new config element will be added,
642 # so non-default values are instantly available
644 # A list, for example:
645 # config.dipswitches = ConfigSubList()
646 # config.dipswitches.append(ConfigYesNo())
647 # config.dipswitches.append(ConfigYesNo())
648 # config.dipswitches.append(ConfigYesNo())
649 class ConfigSubList(list, object):
651 object.__init__(self)
653 self.stored_values = {}
663 def getSavedValue(self):
665 for i in range(len(self)):
666 sv = self[i].saved_value
671 def setSavedValue(self, values):
672 self.stored_values = dict(values)
673 for (key, val) in self.stored_values.items():
674 if int(key) < len(self):
675 self[int(key)].saved_value = val
677 saved_value = property(getSavedValue, setSavedValue)
679 def append(self, item):
681 list.append(self, item)
682 if i in self.stored_values:
683 item.saved_value = self.stored_values[i]
686 # same as ConfigSubList, just as a dictionary.
687 # care must be taken that the 'key' has a proper
688 # str() method, because it will be used in the config
690 class ConfigSubDict(dict, object):
692 object.__init__(self)
694 self.stored_values = {}
697 for x in self.values():
701 for x in self.values():
704 def getSavedValue(self):
706 for (key, val) in self.items():
707 if val.saved_value is not None:
708 res[str(key)] = val.saved_value
711 def setSavedValue(self, values):
712 self.stored_values = dict(values)
713 for (key, val) in self.items():
714 if str(key) in self.stored_values:
715 val = self.stored_values[str(key)]
717 saved_value = property(getSavedValue, setSavedValue)
719 def __setitem__(self, key, item):
720 dict.__setitem__(self, key, item)
721 if str(key) in self.stored_values:
722 item.saved_value = self.stored_values[str(key)]
725 # Like the classes above, just with a more "native"
728 # some evil stuff must be done to allow instant
729 # loading of added elements. this is why this class
732 # we need the 'content' because we overwrite
734 # If you don't understand this, try adding
735 # __setattr__ to a usual exisiting class and you will.
736 class ConfigSubsection(object):
738 object.__init__(self)
739 self.__dict__["content"] = ConfigSubsectionContent()
740 self.content.items = { }
741 self.content.stored_values = { }
743 def __setattr__(self, name, value):
744 if name == "saved_value":
745 return self.setSavedValue(value)
746 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"
747 self.content.items[name] = value
748 if name in self.content.stored_values:
749 #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
750 value.saved_value = self.content.stored_values[name]
753 def __getattr__(self, name):
754 return self.content.items[name]
756 def getSavedValue(self):
757 res = self.content.stored_values
758 for (key, val) in self.content.items.items():
759 if val.saved_value is not None:
760 res[key] = val.saved_value
766 def setSavedValue(self, values):
767 values = dict(values)
769 self.content.stored_values = values
771 for (key, val) in self.content.items.items():
773 val.setSavedValue(values[key])
775 saved_value = property(getSavedValue, setSavedValue)
778 for x in self.content.items.values():
782 for x in self.content.items.values():
785 # the root config object, which also can "pickle" (=serialize)
786 # down the whole config tree.
788 # we try to keep non-existing config entries, to apply them whenever
789 # a new config entry is added to a subsection
790 # also, non-existing config entries will be saved, so they won't be
791 # lost when a config entry disappears.
792 class Config(ConfigSubsection):
794 ConfigSubsection.__init__(self)
796 def pickle_this(self, prefix, topickle, result):
797 for (key, val) in topickle.items():
798 name = prefix + "." + key
800 if isinstance(val, dict):
801 self.pickle_this(name, val, result)
802 elif isinstance(val, tuple):
803 result.append(name + "=" + val[0]) # + " ; " + val[1])
805 result.append(name + "=" + val)
809 self.pickle_this("config", self.saved_value, result)
810 return '\n'.join(result) + "\n"
812 def unpickle(self, lines):
815 if not len(l) or l[0] == '#':
819 val = l[n+1:].strip()
821 names = l[:n].split('.')
822 # if val.find(' ') != -1:
823 # val = val[:val.find(' ')]
828 base = base.setdefault(n, {})
830 base[names[-1]] = val
832 # we inherit from ConfigSubsection, so ...
833 #object.__setattr__(self, "saved_value", tree["config"])
835 self.setSavedValue(tree["config"])
837 def saveToFile(self, filename):
838 f = open(filename, "w")
839 f.write(self.pickle())
842 def loadFromFile(self, filename):
843 f = open(filename, "r")
844 self.unpickle(f.readlines())
848 config.misc = ConfigSubsection()
851 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
855 config.loadFromFile(self.CONFIG_FILE)
857 print "unable to load config (%s), assuming defaults..." % str(e)
861 config.saveToFile(self.CONFIG_FILE)
863 def __resolveValue(self, pickles, cmap):
864 if cmap.has_key(pickles[0]):
866 return self.__resolveValue(pickles[1:], cmap[pickles[0]].content.items)
868 return str(cmap[pickles[0]].value)
871 def getResolvedKey(self, key):
872 names = key.split('.')
874 if names[0] == "config":
875 ret=self.__resolveValue(names[1:], config.content.items)
878 print "getResolvedKey", key, "failed !! (Typo??)"
882 element.disableSave()
885 configfile = ConfigFile()
889 def getConfigListEntry(desc, config):
890 return (desc, config)
895 #config.bla = ConfigSubsection()
896 #config.bla.test = ConfigYesNo()
897 #config.nim = ConfigSubList()
898 #config.nim.append(ConfigSubsection())
899 #config.nim[0].bla = ConfigYesNo()
900 #config.nim.append(ConfigSubsection())
901 #config.nim[1].bla = ConfigYesNo()
902 #config.nim[1].blub = ConfigYesNo()
903 #config.arg = ConfigSubDict()
904 #config.arg["Hello"] = ConfigYesNo()
906 #config.arg["Hello"].handleKey(KEY_RIGHT)
907 #config.arg["Hello"].handleKey(KEY_RIGHT)
913 #print config.pickle()