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 for x in self.notifiers:
74 def addNotifier(self, notifier):
75 assert callable(notifier), "notifiers must be callable"
76 self.notifiers.append(notifier)
79 # do we want to call the notifier
80 # - at all when adding it? (yes)
81 # - when the default is active? (yes)
82 # - when no value *yet* has been set,
83 # because no config has ever been read (currently yes)
84 # (though that's not so easy to detect.
85 # the entry could just be new.)
88 def disableSave(self):
89 self.save_disabled = True
91 def __call__(self, selected):
92 return self.getMulti(selected)
102 KEY_NUMBERS = range(12, 12+10)
106 def getKeyNumber(key):
107 assert key in KEY_NUMBERS
111 # ConfigSelection is a "one of.."-type.
112 # it has the "choices", usually a list, which contains
113 # (id, desc)-tuples (or just only the ids, in case the id
114 # will be used as description)
116 # all ids MUST be plain strings.
118 class ConfigSelection(ConfigElement):
119 def __init__(self, choices, default = None):
120 ConfigElement.__init__(self)
122 self.description = {}
124 if isinstance(choices, list):
126 if isinstance(x, tuple):
127 self.choices.append(x[0])
128 self.description[x[0]] = x[1]
130 self.choices.append(x)
131 self.description[x] = x
132 elif isinstance(choices, dict):
133 for (key, val) in choices.items():
134 self.choices.append(key)
135 self.description[key] = val
137 assert False, "ConfigSelection choices must be dict or list!"
139 #assert len(self.choices), "you can't have an empty configselection"
140 if len(self.choices) == 0:
142 self.description[""] = ""
145 default = self.choices[0]
147 assert default in self.choices, "default must be in choice list, but " + repr(default) + " is not!"
148 for x in self.choices:
149 assert isinstance(x, str), "ConfigSelection choices must be strings"
151 self.value = self.default = default
153 def setValue(self, value):
154 if value in self.choices:
157 self._value = self.default
161 def tostring(self, val):
167 value = property(getValue, setValue)
170 return self.choices.index(self.value)
172 index = property(getIndex)
175 def handleKey(self, key):
176 nchoices = len(self.choices)
177 i = self.choices.index(self.value)
179 self.value = self.choices[(i + nchoices - 1) % nchoices]
180 elif key == KEY_RIGHT:
181 self.value = self.choices[(i + 1) % nchoices]
183 def getMulti(self, selected):
184 return ("text", self.description[self.value])
187 def getHTML(self, id):
189 for v in self.choices:
191 checked = 'checked="checked" '
194 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n"
197 def unsafeAssign(self, value):
198 # setValue does check if value is in choices. This is safe enough.
203 # several customized versions exist for different
206 class ConfigBoolean(ConfigElement):
207 def __init__(self, default = False, descriptions = {False: "false", True: "true"}):
208 ConfigElement.__init__(self)
209 self.descriptions = descriptions
210 self.value = self.default = default
211 def handleKey(self, key):
212 if key in [KEY_LEFT, KEY_RIGHT]:
213 self.value = not self.value
215 def getMulti(self, selected):
216 return ("text", _(self.descriptions[self.value]))
218 def tostring(self, value):
224 def fromstring(self, val):
230 def getHTML(self, id):
232 checked = ' checked="checked"'
235 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
237 # this is FLAWED. and must be fixed.
238 def unsafeAssign(self, value):
244 class ConfigYesNo(ConfigBoolean):
245 def __init__(self, default = False):
246 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")})
248 class ConfigOnOff(ConfigBoolean):
249 def __init__(self, default = False):
250 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")})
252 class ConfigEnableDisable(ConfigBoolean):
253 def __init__(self, default = False):
254 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")})
256 class ConfigDateTime(ConfigElement):
257 def __init__(self, default, formatstring, increment = 86400):
258 ConfigElement.__init__(self)
259 self.increment = increment
260 self.formatstring = formatstring
261 self.value = self.default = int(default)
263 def handleKey(self, key):
265 self.value = self.value - self.increment
267 self.value = self.value + self.increment
269 def getMulti(self, selected):
270 return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
272 def fromstring(self, val):
275 # *THE* mighty config element class
277 # allows you to store/edit a sequence of values.
278 # can be used for IP-addresses, dates, plain integers, ...
279 # several helper exist to ease this up a bit.
281 class ConfigSequence(ConfigElement):
282 def __init__(self, seperator, limits, censor_char = "", default = None):
283 ConfigElement.__init__(self)
284 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
285 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
286 #assert isinstance(default, list), "default must be a list"
287 #assert isinstance(default[0], int), "list must contain numbers"
288 #assert len(default) == len(limits), "length must match"
291 self.seperator = seperator
293 self.censor_char = censor_char
295 self.default = default
296 self.value = copy.copy(default)
301 for i in self._value:
302 max_pos += len(str(self.limits[num][1]))
304 while self._value[num] < self.limits[num][0]:
307 while self._value[num] > self.limits[num][1]:
308 self._value[num] -= 1
312 if self.marked_pos >= max_pos:
313 self.marked_pos = max_pos - 1
315 if self.marked_pos < 0:
318 def validatePos(self):
319 if self.marked_pos < 0:
322 total_len = sum([len(str(x[1])) for x in self.limits])
324 if self.marked_pos >= total_len:
325 self.marked_pos = total_len - 1
327 def handleKey(self, key):
336 if key in KEY_NUMBERS:
338 for x in self.limits:
339 block_len.append(len(str(x[1])))
341 total_len = sum(block_len)
345 block_len_total = [0, ]
347 pos += block_len[blocknumber]
348 block_len_total.append(pos)
349 if pos - 1 >= self.marked_pos:
354 number = getKeyNumber(key)
356 # length of numberblock
357 number_len = len(str(self.limits[blocknumber][1]))
359 # position in the block
360 posinblock = self.marked_pos - block_len_total[blocknumber]
362 oldvalue = self._value[blocknumber]
363 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
364 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
366 self._value[blocknumber] = newvalue
372 def getMulti(self, selected):
374 mPos = self.marked_pos
376 for i in self._value:
377 if len(value): #fixme no heading separator possible
378 value += self.seperator
379 if mPos >= len(value) - 1:
382 if self.censor_char == "":
383 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
385 value += (self.censor_char * len(str(self.limits[num][1])))
388 # only mark cursor when we are selected
389 # (this code is heavily ink optimized!)
391 return ("mtext"[1-selected:], value, [mPos])
393 return ("text", value)
395 def tostring(self, val):
396 return self.seperator.join([self.saveSingle(x) for x in val])
398 def saveSingle(self, v):
401 def fromstring(self, value):
402 return [int(x) for x in self.saved_value.split(self.seperator)]
404 class ConfigIP(ConfigSequence):
405 def __init__(self, default):
406 ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
408 class ConfigMAC(ConfigSequence):
409 def __init__(self, default):
410 ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
412 class ConfigPosition(ConfigSequence):
413 def __init__(self, default, args):
414 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
416 class ConfigClock(ConfigSequence):
417 def __init__(self, default):
418 ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = default)
420 class ConfigInteger(ConfigSequence):
421 def __init__(self, default, limits):
422 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
424 # you need to override this to do input validation
425 def setValue(self, value):
426 self._value = [value]
430 return self._value[0]
432 value = property(getValue, setValue)
434 def fromstring(self, value):
437 def tostring(self, value):
440 class ConfigPIN(ConfigInteger):
441 def __init__(self, default, len = 4, censor = ""):
442 assert isinstance(default, int), "ConfigPIN default must be an integer"
443 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
449 class ConfigFloat(ConfigSequence):
450 def __init__(self, default, limits):
451 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
454 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
456 float = property(getFloat)
458 # an editable text...
459 class ConfigText(ConfigElement, NumericalTextInput):
460 def __init__(self, default = "", fixed_size = True):
461 ConfigElement.__init__(self)
462 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
465 self.fixed_size = fixed_size
467 self.value = self.default = default
469 def validateMarker(self):
470 if self.marked_pos < 0:
472 if self.marked_pos >= len(self.text):
473 self.marked_pos = len(self.text) - 1
475 #def nextEntry(self):
476 # self.vals[1](self.getConfigPath())
478 def handleKey(self, key):
479 # this will no change anything on the value itself
480 # so we can handle it here in gui element
481 if key == KEY_DELETE:
482 self.text = self.text[0:self.marked_pos] + self.text[self.marked_pos + 1:]
483 elif key == KEY_LEFT:
485 elif key == KEY_RIGHT:
487 if not self.fixed_size:
488 if self.marked_pos >= len(self.text):
489 self.text = self.text.ljust(len(self.text) + 1)
490 elif key in KEY_NUMBERS:
491 number = self.getKey(getKeyNumber(key))
492 self.text = self.text[0:self.marked_pos] + str(number) + self.text[self.marked_pos + 1:]
493 elif key == KEY_TIMEOUT:
497 self.validateMarker()
502 self.validateMarker()
506 return self.text.encode("utf-8")
508 def setValue(self, val):
510 self.text = val.decode("utf-8")
511 except UnicodeDecodeError:
515 value = property(getValue, setValue)
516 _value = property(getValue, setValue)
518 def getMulti(self, selected):
519 return ("mtext"[1-selected:], self.value, [self.marked_pos])
521 def helpWindow(self):
522 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
523 return (NumericalTextInputHelpDialog,self)
525 def getHTML(self, id):
526 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
528 def unsafeAssign(self, value):
529 self.value = str(value)
532 class ConfigSlider(ConfigElement):
533 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
534 ConfigElement.__init__(self)
535 self.value = self.default = default
538 self.increment = increment
540 def checkValues(self):
541 if self.value < self.min:
542 self.value = self.min
544 if self.value > self.max:
545 self.value = self.max
547 def handleKey(self, key):
549 self.value -= self.increment
550 elif key == KEY_RIGHT:
551 self.value += self.increment
558 def getMulti(self, selected):
560 return ("slider", self.value, self.max)
562 def fromstring(self, value):
565 # a satlist. in fact, it's a ConfigSelection.
566 class ConfigSatlist(ConfigSelection):
567 def __init__(self, list, default = None):
568 if default is not None:
569 default = str(default)
570 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc) in list], default = default)
572 def getOrbitalPosition(self):
575 return int(self.value)
577 orbital_position = property(getOrbitalPosition)
580 class ConfigNothing(ConfigSelection):
582 ConfigSelection.__init__(self, choices = [""])
584 # until here, 'saved_value' always had to be a *string*.
585 # now, in ConfigSubsection, and only there, saved_value
586 # is a dict, essentially forming a tree.
588 # config.foo.bar=True
589 # config.foobar=False
592 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
596 class ConfigSubsectionContent(object):
599 # we store a backup of the loaded configuration
600 # data in self.stored_values, to be able to deploy
601 # them when a new config element will be added,
602 # so non-default values are instantly available
604 # A list, for example:
605 # config.dipswitches = ConfigSubList()
606 # config.dipswitches.append(ConfigYesNo())
607 # config.dipswitches.append(ConfigYesNo())
608 # config.dipswitches.append(ConfigYesNo())
609 class ConfigSubList(list, object):
611 object.__init__(self)
613 self.stored_values = {}
623 def getSavedValue(self):
625 for i in range(len(self)):
626 sv = self[i].saved_value
631 def setSavedValue(self, values):
632 self.stored_values = dict(values)
633 for (key, val) in self.stored_values.items():
634 if int(key) < len(self):
635 self[int(key)].saved_value = val
637 saved_value = property(getSavedValue, setSavedValue)
639 def append(self, item):
641 list.append(self, item)
642 if i in self.stored_values:
643 item.saved_value = self.stored_values[i]
646 # same as ConfigSubList, just as a dictionary.
647 # care must be taken that the 'key' has a proper
648 # str() method, because it will be used in the config
650 class ConfigSubDict(dict, object):
652 object.__init__(self)
654 self.stored_values = {}
657 for x in self.values():
661 for x in self.values():
664 def getSavedValue(self):
666 for (key, val) in self.items():
667 if val.saved_value is not None:
668 res[str(key)] = val.saved_value
671 def setSavedValue(self, values):
672 self.stored_values = dict(values)
673 for (key, val) in self.items():
674 if str(key) in self.stored_values:
675 val = self.stored_values[str(key)]
677 saved_value = property(getSavedValue, setSavedValue)
679 def __setitem__(self, key, item):
680 dict.__setitem__(self, key, item)
681 if str(key) in self.stored_values:
682 item.saved_value = self.stored_values[str(key)]
685 # Like the classes above, just with a more "native"
688 # some evil stuff must be done to allow instant
689 # loading of added elements. this is why this class
692 # we need the 'content' because we overwrite
694 # If you don't understand this, try adding
695 # __setattr__ to a usual exisiting class and you will.
696 class ConfigSubsection(object):
698 object.__init__(self)
699 self.__dict__["content"] = ConfigSubsectionContent()
700 self.content.items = { }
701 self.content.stored_values = { }
703 def __setattr__(self, name, value):
704 if name == "saved_value":
705 return self.setSavedValue(value)
706 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"
707 self.content.items[name] = value
708 if name in self.content.stored_values:
709 #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
710 value.saved_value = self.content.stored_values[name]
713 def __getattr__(self, name):
714 return self.content.items[name]
716 def getSavedValue(self):
717 res = self.content.stored_values
718 for (key, val) in self.content.items.items():
719 if val.saved_value is not None:
720 res[key] = val.saved_value
726 def setSavedValue(self, values):
727 values = dict(values)
729 self.content.stored_values = values
731 for (key, val) in self.content.items.items():
733 val.setSavedValue(values[key])
735 saved_value = property(getSavedValue, setSavedValue)
738 for x in self.content.items.values():
742 for x in self.content.items.values():
745 # the root config object, which also can "pickle" (=serialize)
746 # down the whole config tree.
748 # we try to keep non-existing config entries, to apply them whenever
749 # a new config entry is added to a subsection
750 # also, non-existing config entries will be saved, so they won't be
751 # lost when a config entry disappears.
752 class Config(ConfigSubsection):
754 ConfigSubsection.__init__(self)
756 def pickle_this(self, prefix, topickle, result):
757 for (key, val) in topickle.items():
758 name = prefix + "." + key
760 if isinstance(val, dict):
761 self.pickle_this(name, val, result)
762 elif isinstance(val, tuple):
763 result.append(name + "=" + val[0]) # + " ; " + val[1])
765 result.append(name + "=" + val)
769 self.pickle_this("config", self.saved_value, result)
770 return '\n'.join(result) + "\n"
772 def unpickle(self, lines):
775 if not len(l) or l[0] == '#':
779 val = l[n+1:].strip()
781 names = l[:n].split('.')
782 # if val.find(' ') != -1:
783 # val = val[:val.find(' ')]
788 base = base.setdefault(n, {})
790 base[names[-1]] = val
792 # we inherit from ConfigSubsection, so ...
793 #object.__setattr__(self, "saved_value", tree["config"])
794 self.setSavedValue(tree["config"])
796 def saveToFile(self, filename):
797 f = open(filename, "w")
798 f.write(self.pickle())
801 def loadFromFile(self, filename):
802 f = open(filename, "r")
803 self.unpickle(f.readlines())
807 config.misc = ConfigSubsection()
810 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "config2")
814 config.loadFromFile(self.CONFIG_FILE)
816 print "unable to load config (%s), assuming defaults..." % str(e)
820 config.saveToFile(self.CONFIG_FILE)
822 def getResolvedKey(self, key):
826 element.disableSave()
829 configfile = ConfigFile()
833 def getConfigListEntry(desc, config):
834 return (desc, config)
839 #config.bla = ConfigSubsection()
840 #config.bla.test = ConfigYesNo()
841 #config.nim = ConfigSubList()
842 #config.nim.append(ConfigSubsection())
843 #config.nim[0].bla = ConfigYesNo()
844 #config.nim.append(ConfigSubsection())
845 #config.nim[1].bla = ConfigYesNo()
846 #config.nim[1].blub = ConfigYesNo()
847 #config.arg = ConfigSubDict()
848 #config.arg["Hello"] = ConfigYesNo()
850 #config.arg["Hello"].handleKey(KEY_RIGHT)
851 #config.arg["Hello"].handleKey(KEY_RIGHT)
857 #print config.pickle()