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 descr = self.description[self.value]
202 def getMulti(self, selected):
203 descr = self.description[self.value]
205 return ("text", _(descr))
206 return ("text", descr)
209 def getHTML(self, id):
211 for v in self.choices:
213 checked = 'checked="checked" '
216 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n"
219 def unsafeAssign(self, value):
220 # setValue does check if value is in choices. This is safe enough.
225 # several customized versions exist for different
228 class ConfigBoolean(ConfigElement):
229 def __init__(self, default = False, descriptions = {False: "false", True: "true"}):
230 ConfigElement.__init__(self)
231 self.descriptions = descriptions
232 self.value = self.default = default
233 def handleKey(self, key):
234 if key in [KEY_LEFT, KEY_RIGHT]:
235 self.value = not self.value
238 descr = self.descriptions[self.value]
243 def getMulti(self, selected):
244 descr = self.descriptions[self.value]
246 return ("text", _(descr))
247 return ("text", descr)
249 def tostring(self, value):
255 def fromstring(self, val):
261 def getHTML(self, id):
263 checked = ' checked="checked"'
266 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
268 # this is FLAWED. and must be fixed.
269 def unsafeAssign(self, value):
275 class ConfigYesNo(ConfigBoolean):
276 def __init__(self, default = False):
277 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")})
279 class ConfigOnOff(ConfigBoolean):
280 def __init__(self, default = False):
281 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")})
283 class ConfigEnableDisable(ConfigBoolean):
284 def __init__(self, default = False):
285 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")})
287 class ConfigDateTime(ConfigElement):
288 def __init__(self, default, formatstring, increment = 86400):
289 ConfigElement.__init__(self)
290 self.increment = increment
291 self.formatstring = formatstring
292 self.value = self.default = int(default)
294 def handleKey(self, key):
296 self.value = self.value - self.increment
298 self.value = self.value + self.increment
301 return time.strftime(self.formatstring, time.localtime(self.value))
303 def getMulti(self, selected):
304 return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
306 def fromstring(self, val):
309 # *THE* mighty config element class
311 # allows you to store/edit a sequence of values.
312 # can be used for IP-addresses, dates, plain integers, ...
313 # several helper exist to ease this up a bit.
315 class ConfigSequence(ConfigElement):
316 def __init__(self, seperator, limits, censor_char = "", default = None):
317 ConfigElement.__init__(self)
318 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
319 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
320 #assert isinstance(default, list), "default must be a list"
321 #assert isinstance(default[0], int), "list must contain numbers"
322 #assert len(default) == len(limits), "length must match"
325 self.seperator = seperator
327 self.censor_char = censor_char
329 self.default = default
330 self.value = copy.copy(default)
335 for i in self._value:
336 max_pos += len(str(self.limits[num][1]))
338 while self._value[num] < self.limits[num][0]:
339 self._value[num] += 1
341 while self._value[num] > self.limits[num][1]:
342 self._value[num] -= 1
346 if self.marked_pos >= max_pos:
347 self.marked_pos = max_pos - 1
349 if self.marked_pos < 0:
352 def validatePos(self):
353 if self.marked_pos < 0:
356 total_len = sum([len(str(x[1])) for x in self.limits])
358 if self.marked_pos >= total_len:
359 self.marked_pos = total_len - 1
361 def handleKey(self, key):
370 if key in KEY_NUMBERS:
372 for x in self.limits:
373 block_len.append(len(str(x[1])))
375 total_len = sum(block_len)
379 block_len_total = [0, ]
381 pos += block_len[blocknumber]
382 block_len_total.append(pos)
383 if pos - 1 >= self.marked_pos:
388 number = getKeyNumber(key)
390 # length of numberblock
391 number_len = len(str(self.limits[blocknumber][1]))
393 # position in the block
394 posinblock = self.marked_pos - block_len_total[blocknumber]
396 oldvalue = self._value[blocknumber]
397 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
398 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
400 self._value[blocknumber] = newvalue
408 mPos = self.marked_pos
410 for i in self._value:
411 if len(value): #fixme no heading separator possible
412 value += self.seperator
413 if mPos >= len(value) - 1:
416 if self.censor_char == "":
417 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
419 value += (self.censor_char * len(str(self.limits[num][1])))
424 (value, mPos) = self.genText()
427 def getMulti(self, selected):
428 (value, mPos) = self.genText()
429 # only mark cursor when we are selected
430 # (this code is heavily ink optimized!)
432 return ("mtext"[1-selected:], value, [mPos])
434 return ("text", value)
436 def tostring(self, val):
437 return self.seperator.join([self.saveSingle(x) for x in val])
439 def saveSingle(self, v):
442 def fromstring(self, value):
443 return [int(x) for x in self.saved_value.split(self.seperator)]
445 class ConfigIP(ConfigSequence):
446 def __init__(self, default):
447 ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
449 class ConfigMAC(ConfigSequence):
450 def __init__(self, default):
451 ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
453 class ConfigPosition(ConfigSequence):
454 def __init__(self, default, args):
455 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
457 class ConfigClock(ConfigSequence):
458 def __init__(self, default):
460 t = time.localtime(default)
461 ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
463 class ConfigInteger(ConfigSequence):
464 def __init__(self, default, limits = (0, 10000000000)):
465 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
467 # you need to override this to do input validation
468 def setValue(self, value):
469 self._value = [value]
473 return self._value[0]
475 value = property(getValue, setValue)
477 def fromstring(self, value):
480 def tostring(self, value):
483 class ConfigPIN(ConfigInteger):
484 def __init__(self, default, len = 4, censor = ""):
485 assert isinstance(default, int), "ConfigPIN default must be an integer"
488 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
494 class ConfigFloat(ConfigSequence):
495 def __init__(self, default, limits):
496 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
499 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
501 float = property(getFloat)
503 # an editable text...
504 class ConfigText(ConfigElement, NumericalTextInput):
505 def __init__(self, default = "", fixed_size = True):
506 ConfigElement.__init__(self)
507 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
510 self.fixed_size = fixed_size
512 self.value = self.default = default
514 def validateMarker(self):
515 if self.marked_pos >= len(self.text):
516 self.marked_pos = len(self.text) - 1
517 if self.marked_pos < 0:
520 #def nextEntry(self):
521 # self.vals[1](self.getConfigPath())
523 def handleKey(self, key):
524 # this will no change anything on the value itself
525 # so we can handle it here in gui element
526 if key == KEY_DELETE:
527 self.text = self.text[0:self.marked_pos] + self.text[self.marked_pos + 1:]
528 elif key == KEY_LEFT:
530 elif key == KEY_RIGHT:
533 elif key in KEY_NUMBERS:
534 number = self.getKey(getKeyNumber(key))
535 self.text = self.text[0:self.marked_pos] + unicode(number) + self.text[self.marked_pos + 1:]
536 elif key == KEY_TIMEOUT:
540 self.validateMarker()
543 def maybeExpand(self):
544 if not self.fixed_size:
545 if self.marked_pos >= len(self.text):
546 self.text = self.text.ljust(len(self.text) + 1)
551 self.validateMarker()
555 return self.text.encode("utf-8")
557 def setValue(self, val):
559 self.text = val.decode("utf-8")
560 except UnicodeDecodeError:
564 value = property(getValue, setValue)
565 _value = property(getValue, setValue)
570 def getMulti(self, selected):
571 return ("mtext"[1-selected:], self.value, [self.marked_pos])
573 def helpWindow(self):
574 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
575 return (NumericalTextInputHelpDialog,self)
577 def getHTML(self, id):
578 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
580 def unsafeAssign(self, value):
581 self.value = str(value)
584 class ConfigSlider(ConfigElement):
585 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
586 ConfigElement.__init__(self)
587 self.value = self.default = default
590 self.increment = increment
592 def checkValues(self):
593 if self.value < self.min:
594 self.value = self.min
596 if self.value > self.max:
597 self.value = self.max
599 def handleKey(self, key):
601 self.value -= self.increment
602 elif key == KEY_RIGHT:
603 self.value += self.increment
611 return "%d / %d" % (self.value, self.max)
613 def getMulti(self, selected):
615 return ("slider", self.value, self.max)
617 def fromstring(self, value):
620 # a satlist. in fact, it's a ConfigSelection.
621 class ConfigSatlist(ConfigSelection):
622 def __init__(self, list, default = None):
623 if default is not None:
624 default = str(default)
625 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc) in list], default = default)
627 def getOrbitalPosition(self):
630 return int(self.value)
632 orbital_position = property(getOrbitalPosition)
635 class ConfigNothing(ConfigSelection):
637 ConfigSelection.__init__(self, choices = [""])
639 # until here, 'saved_value' always had to be a *string*.
640 # now, in ConfigSubsection, and only there, saved_value
641 # is a dict, essentially forming a tree.
643 # config.foo.bar=True
644 # config.foobar=False
647 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
651 class ConfigSubsectionContent(object):
654 # we store a backup of the loaded configuration
655 # data in self.stored_values, to be able to deploy
656 # them when a new config element will be added,
657 # so non-default values are instantly available
659 # A list, for example:
660 # config.dipswitches = ConfigSubList()
661 # config.dipswitches.append(ConfigYesNo())
662 # config.dipswitches.append(ConfigYesNo())
663 # config.dipswitches.append(ConfigYesNo())
664 class ConfigSubList(list, object):
666 object.__init__(self)
668 self.stored_values = {}
678 def getSavedValue(self):
680 for i in range(len(self)):
681 sv = self[i].saved_value
686 def setSavedValue(self, values):
687 self.stored_values = dict(values)
688 for (key, val) in self.stored_values.items():
689 if int(key) < len(self):
690 self[int(key)].saved_value = val
692 saved_value = property(getSavedValue, setSavedValue)
694 def append(self, item):
696 list.append(self, item)
697 if i in self.stored_values:
698 item.saved_value = self.stored_values[i]
703 for index in range(len(self)):
704 res[str(index)] = self[index]
707 # same as ConfigSubList, just as a dictionary.
708 # care must be taken that the 'key' has a proper
709 # str() method, because it will be used in the config
711 class ConfigSubDict(dict, object):
713 object.__init__(self)
715 self.stored_values = {}
718 for x in self.values():
722 for x in self.values():
725 def getSavedValue(self):
727 for (key, val) in self.items():
728 if val.saved_value is not None:
729 res[str(key)] = val.saved_value
732 def setSavedValue(self, values):
733 self.stored_values = dict(values)
734 for (key, val) in self.items():
735 if str(key) in self.stored_values:
736 val = self.stored_values[str(key)]
738 saved_value = property(getSavedValue, setSavedValue)
740 def __setitem__(self, key, item):
741 dict.__setitem__(self, key, item)
742 if str(key) in self.stored_values:
743 item.saved_value = self.stored_values[str(key)]
749 # Like the classes above, just with a more "native"
752 # some evil stuff must be done to allow instant
753 # loading of added elements. this is why this class
756 # we need the 'content' because we overwrite
758 # If you don't understand this, try adding
759 # __setattr__ to a usual exisiting class and you will.
760 class ConfigSubsection(object):
762 object.__init__(self)
763 self.__dict__["content"] = ConfigSubsectionContent()
764 self.content.items = { }
765 self.content.stored_values = { }
767 def __setattr__(self, name, value):
768 if name == "saved_value":
769 return self.setSavedValue(value)
770 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"
771 self.content.items[name] = value
772 if name in self.content.stored_values:
773 #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
774 value.saved_value = self.content.stored_values[name]
777 def __getattr__(self, name):
778 return self.content.items[name]
780 def getSavedValue(self):
781 res = self.content.stored_values
782 for (key, val) in self.content.items.items():
783 if val.saved_value is not None:
784 res[key] = val.saved_value
790 def setSavedValue(self, values):
791 values = dict(values)
793 self.content.stored_values = values
795 for (key, val) in self.content.items.items():
797 val.setSavedValue(values[key])
799 saved_value = property(getSavedValue, setSavedValue)
802 for x in self.content.items.values():
806 for x in self.content.items.values():
810 return self.content.items
812 # the root config object, which also can "pickle" (=serialize)
813 # down the whole config tree.
815 # we try to keep non-existing config entries, to apply them whenever
816 # a new config entry is added to a subsection
817 # also, non-existing config entries will be saved, so they won't be
818 # lost when a config entry disappears.
819 class Config(ConfigSubsection):
821 ConfigSubsection.__init__(self)
823 def pickle_this(self, prefix, topickle, result):
824 for (key, val) in topickle.items():
825 name = prefix + "." + key
827 if isinstance(val, dict):
828 self.pickle_this(name, val, result)
829 elif isinstance(val, tuple):
830 result.append(name + "=" + val[0]) # + " ; " + val[1])
832 result.append(name + "=" + val)
836 self.pickle_this("config", self.saved_value, result)
837 return '\n'.join(result) + "\n"
839 def unpickle(self, lines):
842 if not len(l) or l[0] == '#':
846 val = l[n+1:].strip()
848 names = l[:n].split('.')
849 # if val.find(' ') != -1:
850 # val = val[:val.find(' ')]
855 base = base.setdefault(n, {})
857 base[names[-1]] = val
859 # we inherit from ConfigSubsection, so ...
860 #object.__setattr__(self, "saved_value", tree["config"])
862 self.setSavedValue(tree["config"])
864 def saveToFile(self, filename):
865 f = open(filename, "w")
866 f.write(self.pickle())
869 def loadFromFile(self, filename):
870 f = open(filename, "r")
871 self.unpickle(f.readlines())
875 config.misc = ConfigSubsection()
878 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
882 config.loadFromFile(self.CONFIG_FILE)
884 print "unable to load config (%s), assuming defaults..." % str(e)
888 config.saveToFile(self.CONFIG_FILE)
890 def __resolveValue(self, pickles, cmap):
891 if cmap.has_key(pickles[0]):
893 return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
895 return str(cmap[pickles[0]].value)
898 def getResolvedKey(self, key):
899 names = key.split('.')
901 if names[0] == "config":
902 ret=self.__resolveValue(names[1:], config.content.items)
905 print "getResolvedKey", key, "failed !! (Typo??)"
909 element.disableSave()
912 configfile = ConfigFile()
916 def getConfigListEntry(*args):
917 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
923 #config.bla = ConfigSubsection()
924 #config.bla.test = ConfigYesNo()
925 #config.nim = ConfigSubList()
926 #config.nim.append(ConfigSubsection())
927 #config.nim[0].bla = ConfigYesNo()
928 #config.nim.append(ConfigSubsection())
929 #config.nim[1].bla = ConfigYesNo()
930 #config.nim[1].blub = ConfigYesNo()
931 #config.arg = ConfigSubDict()
932 #config.arg["Hello"] = ConfigYesNo()
934 #config.arg["Hello"].handleKey(KEY_RIGHT)
935 #config.arg["Hello"].handleKey(KEY_RIGHT)
941 #print config.pickle()