1 from enigma import eRCInput, getPrevAsciiCode
2 from Tools.NumericalTextInput import NumericalTextInput
3 from Tools.Directories import resolveFilename, SCOPE_CONFIG, fileExists
4 from Tools.IO import saveFile
5 from copy import copy as copy_copy
6 from os import path as os_path
7 from time import localtime, strftime
9 # ConfigElement, the base class of all ConfigElements.
12 # value the current value, usefully encoded.
13 # usually a property which retrieves _value,
14 # and maybe does some reformatting
15 # _value the value as it's going to be saved in the configfile,
16 # though still in non-string form.
17 # this is the object which is actually worked on.
18 # default the initial value. If _value is equal to default,
19 # it will not be stored in the config file
20 # saved_value is a text representation of _value, stored in the config file
22 # and has (at least) the following methods:
23 # save() stores _value into saved_value,
24 # (or stores 'None' if it should not be stored)
25 # load() loads _value from saved_value, or loads
26 # the default if saved_value is 'None' (default)
29 class ConfigElement(object):
31 self.saved_value = None
32 self.save_forced = False
33 self.save_disabled = False
34 self.__notifiers = { }
35 self.__notifiers_final = { }
38 def getNotifiers(self):
39 return [func for (func, val, call_on_save_and_cancel) in self.__notifiers.itervalues()]
41 def setNotifiers(self, val):
42 print "just readonly access to notifiers is allowed! append/remove doesnt work anymore! please use addNotifier, removeNotifier, clearNotifiers"
44 notifiers = property(getNotifiers, setNotifiers)
46 def getNotifiersFinal(self):
47 return [func for (func, val, call_on_save_and_cancel) in self.__notifiers_final.itervalues()]
49 def setNotifiersFinal(self, val):
50 print "just readonly access to notifiers_final is allowed! append/remove doesnt work anymore! please use addNotifier, removeNotifier, clearNotifiers"
52 notifiers_final = property(getNotifiersFinal, setNotifiersFinal)
54 # you need to override this to do input validation
55 def setValue(self, value):
62 value = property(getValue, setValue)
64 # you need to override this if self.value is not a string
65 def fromstring(self, value):
68 # you can overide this for fancy default handling
72 self.value = self.default
74 self.value = self.fromstring(sv)
76 def tostring(self, value):
79 # you need to override this if str(self.value) doesn't work
81 if self.save_disabled or (self.value == self.default and not self.save_forced):
82 self.saved_value = None
84 self.saved_value = self.tostring(self.value)
85 self.changed(save_or_cancel=True)
86 self.changedFinal(save_or_cancel=True)
90 self.changed(save_or_cancel=True)
91 self.changedFinal(save_or_cancel=True)
95 if sv is None and self.value == self.default:
97 return self.tostring(self.value) != sv
99 def changed(self, save_or_cancel=False):
100 for (func, val) in self.__notifiers.iteritems():
101 if (val[2] and save_or_cancel) or (save_or_cancel == False and val[1] != self.value):
102 self.__notifiers[func] = (val[0], self.value, val[2])
105 def changedFinal(self, save_or_cancel=False):
106 for (func, val) in self.__notifiers_final.iteritems():
107 if (val[2] and save_or_cancel) or (save_or_cancel == False and val[1] != self.value):
108 self.__notifiers_final[func] = (val[0], self.value, val[2])
111 # immediate_feedback = True means call notifier on every value CHANGE
112 # immediate_feedback = False means call notifier on leave the config element (up/down) when value have CHANGED
113 # call_on_save_or_cancel = True means call notifier always on save/cancel.. even when value have not changed
114 def addNotifier(self, notifier, initial_call = True, immediate_feedback = True, call_on_save_or_cancel = False):
115 assert callable(notifier), "notifiers must be callable"
116 if immediate_feedback:
117 self.__notifiers[str(notifier)] = (notifier, self.value, call_on_save_or_cancel)
119 self.__notifiers_final[str(notifier)] = (notifier, self.value, call_on_save_or_cancel)
121 # do we want to call the notifier
122 # - at all when adding it? (yes, though optional)
123 # - when the default is active? (yes)
124 # - when no value *yet* has been set,
125 # because no config has ever been read (currently yes)
126 # (though that's not so easy to detect.
127 # the entry could just be new.)
131 def removeNotifier(self, notifier):
132 del self.__notifiers[str(notifier)]
134 def clearNotifiers(self):
135 self.__notifiers = { }
137 def disableSave(self):
138 self.save_disabled = True
140 def __call__(self, selected):
141 return self.getMulti(selected)
143 def onSelect(self, session):
146 def onDeselect(self, session):
159 KEY_NUMBERS = range(12, 12+10)
163 def getKeyNumber(key):
164 assert key in KEY_NUMBERS
167 class choicesList(object): # XXX: we might want a better name for this
171 def __init__(self, choices, type = None):
172 self.choices = choices
174 if isinstance(choices, list):
175 self.type = choicesList.LIST_TYPE_LIST
176 elif isinstance(choices, dict):
177 self.type = choicesList.LIST_TYPE_DICT
179 assert False, "choices must be dict or list!"
184 if self.type == choicesList.LIST_TYPE_LIST:
185 ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
187 ret = self.choices.keys()
191 if self.type == choicesList.LIST_TYPE_LIST:
192 ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
195 return iter(ret or [""])
198 return len(self.choices) or 1
200 def updateItemDescription(self, index, descr):
201 if self.type == choicesList.LIST_TYPE_LIST:
202 orig = self.choices[index]
203 assert isinstance(orig, tuple)
204 self.choices[index] = (orig[0], descr)
206 key = self.choices.keys()[index]
207 self.choices[key] = descr
209 def __getitem__(self, index):
210 if self.type == choicesList.LIST_TYPE_LIST:
211 ret = self.choices[index]
212 if isinstance(ret, tuple):
215 return self.choices.keys()[index]
217 def index(self, value):
218 return self.__list__().index(value)
220 def __setitem__(self, index, value):
221 if self.type == choicesList.LIST_TYPE_LIST:
222 orig = self.choices[index]
223 if isinstance(orig, tuple):
224 self.choices[index] = (value, orig[1])
226 self.choices[index] = value
228 key = self.choices.keys()[index]
229 orig = self.choices[key]
230 del self.choices[key]
231 self.choices[value] = orig
234 choices = self.choices
237 if self.type is choicesList.LIST_TYPE_LIST:
239 if isinstance(default, tuple):
242 default = choices.keys()[0]
245 class descriptionList(choicesList): # XXX: we might want a better name for this
247 if self.type == choicesList.LIST_TYPE_LIST:
248 ret = [not isinstance(x, tuple) and x or x[1] for x in self.choices]
250 ret = self.choices.values()
254 return iter(self.__list__())
256 def __getitem__(self, index):
257 if self.type == choicesList.LIST_TYPE_LIST:
258 for x in self.choices:
259 if isinstance(x, tuple):
264 return str(index) # Fallback!
266 return str(self.choices.get(index, ""))
268 def __setitem__(self, index, value):
269 if self.type == choicesList.LIST_TYPE_LIST:
270 i = self.index(index)
271 orig = self.choices[i]
272 if isinstance(orig, tuple):
273 self.choices[i] = (orig[0], value)
275 self.choices[i] = value
277 self.choices[index] = value
280 # ConfigSelection is a "one of.."-type.
281 # it has the "choices", usually a list, which contains
282 # (id, desc)-tuples (or just only the ids, in case the id
283 # will be used as description)
285 # all ids MUST be plain strings.
287 class ConfigSelection(ConfigElement):
288 def __init__(self, choices, default = None):
289 ConfigElement.__init__(self)
290 self.choices = choicesList(choices)
293 default = self.choices.default()
296 self.default = self._value = default
298 def setChoices(self, choices, default = None):
299 self.choices = choicesList(choices)
302 default = self.choices.default()
303 self.default = default
305 if self.value not in self.choices:
308 def getChoices(self):
309 return self.choices.choices
311 def setValue(self, value):
312 if value in self.choices:
315 self._value = self.default
319 def tostring(self, val):
325 def setCurrentText(self, text):
326 i = self.choices.index(self.value)
327 self.choices[i] = text
328 self._descr = self.description[text] = text
331 value = property(getValue, setValue)
334 return self.choices.index(self.value)
336 index = property(getIndex)
339 def handleKey(self, key):
340 nchoices = len(self.choices)
341 i = self.choices.index(self.value)
343 self.value = self.choices[(i + nchoices - 1) % nchoices]
344 elif key == KEY_RIGHT:
345 self.value = self.choices[(i + 1) % nchoices]
346 elif key == KEY_HOME:
347 self.value = self.choices[0]
349 self.value = self.choices[nchoices - 1]
351 def selectNext(self):
352 nchoices = len(self.choices)
353 i = self.choices.index(self.value)
354 self.value = self.choices[(i + 1) % nchoices]
357 if self._descr is not None:
359 descr = self._descr = self.description[self.value]
364 def getMulti(self, selected):
365 if self._descr is not None:
368 descr = self._descr = self.description[self.value]
370 return ("text", _(descr))
371 return ("text", descr)
374 def getHTML(self, id):
376 for v in self.choices:
377 descr = self.description[v]
379 checked = 'checked="checked" '
382 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + descr + "</input></br>\n"
385 def unsafeAssign(self, value):
386 # setValue does check if value is in choices. This is safe enough.
389 description = property(lambda self: descriptionList(self.choices.choices, self.choices.type))
393 # several customized versions exist for different
396 boolean_descriptions = {False: "false", True: "true"}
397 class ConfigBoolean(ConfigElement):
398 def __init__(self, default = False, descriptions = boolean_descriptions):
399 ConfigElement.__init__(self)
400 self.descriptions = descriptions
401 self.value = self.default = default
403 def handleKey(self, key):
404 if key in (KEY_LEFT, KEY_RIGHT):
405 self.value = not self.value
406 elif key == KEY_HOME:
412 descr = self.descriptions[self.value]
417 def getMulti(self, selected):
418 descr = self.descriptions[self.value]
420 return ("text", _(descr))
421 return ("text", descr)
423 def tostring(self, value):
429 def fromstring(self, val):
435 def getHTML(self, id):
437 checked = ' checked="checked"'
440 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
442 # this is FLAWED. and must be fixed.
443 def unsafeAssign(self, value):
449 yes_no_descriptions = {False: _("no"), True: _("yes")}
450 class ConfigYesNo(ConfigBoolean):
451 def __init__(self, default = False):
452 ConfigBoolean.__init__(self, default = default, descriptions = yes_no_descriptions)
454 on_off_descriptions = {False: _("off"), True: _("on")}
455 class ConfigOnOff(ConfigBoolean):
456 def __init__(self, default = False):
457 ConfigBoolean.__init__(self, default = default, descriptions = on_off_descriptions)
459 enable_disable_descriptions = {False: _("disable"), True: _("enable")}
460 class ConfigEnableDisable(ConfigBoolean):
461 def __init__(self, default = False):
462 ConfigBoolean.__init__(self, default = default, descriptions = enable_disable_descriptions)
464 class ConfigDateTime(ConfigElement):
465 def __init__(self, default, formatstring, increment = 86400):
466 ConfigElement.__init__(self)
467 self.increment = increment
468 self.formatstring = formatstring
469 self.value = self.default = int(default)
471 def handleKey(self, key):
473 self.value = self.value - self.increment
474 elif key == KEY_RIGHT:
475 self.value = self.value + self.increment
476 elif key == KEY_HOME or key == KEY_END:
477 self.value = self.default
480 return strftime(self.formatstring, localtime(self.value))
482 def getMulti(self, selected):
483 return ("text", strftime(self.formatstring, localtime(self.value)))
485 def fromstring(self, val):
488 # *THE* mighty config element class
490 # allows you to store/edit a sequence of values.
491 # can be used for IP-addresses, dates, plain integers, ...
492 # several helper exist to ease this up a bit.
494 class ConfigSequence(ConfigElement):
495 def __init__(self, seperator, limits, default, censor_char = ""):
496 ConfigElement.__init__(self)
497 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
498 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
499 #assert isinstance(default, list), "default must be a list"
500 #assert isinstance(default[0], int), "list must contain numbers"
501 #assert len(default) == len(limits), "length must match"
504 self.seperator = seperator
506 self.censor_char = censor_char
508 self.default = default
509 self.value = copy_copy(default)
510 self.endNotifier = None
515 for i in self._value:
516 max_pos += len(str(self.limits[num][1]))
518 if self._value[num] < self.limits[num][0]:
519 self._value[num] = self.limits[num][0]
521 if self._value[num] > self.limits[num][1]:
522 self._value[num] = self.limits[num][1]
526 if self.marked_pos >= max_pos:
528 for x in self.endNotifier:
530 self.marked_pos = max_pos - 1
532 if self.marked_pos < 0:
535 def validatePos(self):
536 if self.marked_pos < 0:
539 total_len = sum([len(str(x[1])) for x in self.limits])
541 if self.marked_pos >= total_len:
542 self.marked_pos = total_len - 1
544 def addEndNotifier(self, notifier):
545 if self.endNotifier is None:
546 self.endNotifier = []
547 self.endNotifier.append(notifier)
549 def handleKey(self, key):
554 elif key == KEY_RIGHT:
558 elif key == KEY_HOME:
565 for i in self._value:
566 max_pos += len(str(self.limits[num][1]))
568 self.marked_pos = max_pos - 1
571 elif key in KEY_NUMBERS or key == KEY_ASCII:
573 code = getPrevAsciiCode()
574 if code < 48 or code > 57:
578 number = getKeyNumber(key)
580 block_len = [len(str(x[1])) for x in self.limits]
581 total_len = sum(block_len)
585 block_len_total = [0, ]
587 pos += block_len[blocknumber]
588 block_len_total.append(pos)
589 if pos - 1 >= self.marked_pos:
594 # length of numberblock
595 number_len = len(str(self.limits[blocknumber][1]))
597 # position in the block
598 posinblock = self.marked_pos - block_len_total[blocknumber]
600 oldvalue = self._value[blocknumber]
601 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
602 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
604 self._value[blocknumber] = newvalue
612 mPos = self.marked_pos
614 for i in self._value:
615 if value: #fixme no heading separator possible
616 value += self.seperator
617 if mPos >= len(value) - 1:
619 if self.censor_char == "":
620 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
622 value += (self.censor_char * len(str(self.limits[num][1])))
627 (value, mPos) = self.genText()
630 def getMulti(self, selected):
631 (value, mPos) = self.genText()
632 # only mark cursor when we are selected
633 # (this code is heavily ink optimized!)
635 return ("mtext"[1-selected:], value, [mPos])
637 return ("text", value)
639 def tostring(self, val):
640 return self.seperator.join([self.saveSingle(x) for x in val])
642 def saveSingle(self, v):
645 def fromstring(self, value):
646 return [int(x) for x in value.split(self.seperator)]
648 ip_limits = [(0,255),(0,255),(0,255),(0,255)]
649 class ConfigIP(ConfigSequence):
650 def __init__(self, default, auto_jump = False):
651 ConfigSequence.__init__(self, seperator = ".", limits = ip_limits, default = default)
652 self.block_len = [len(str(x[1])) for x in self.limits]
653 self.marked_block = 0
654 self.overwrite = True
655 self.auto_jump = auto_jump
657 def handleKey(self, key):
659 if self.marked_block > 0:
660 self.marked_block -= 1
661 self.overwrite = True
663 elif key == KEY_RIGHT:
664 if self.marked_block < len(self.limits)-1:
665 self.marked_block += 1
666 self.overwrite = True
668 elif key == KEY_HOME:
669 self.marked_block = 0
670 self.overwrite = True
673 self.marked_block = len(self.limits)-1
674 self.overwrite = True
676 elif key in KEY_NUMBERS or key == KEY_ASCII:
678 code = getPrevAsciiCode()
679 if code < 48 or code > 57:
683 number = getKeyNumber(key)
684 oldvalue = self._value[self.marked_block]
687 self._value[self.marked_block] = number
688 self.overwrite = False
691 newvalue = oldvalue + number
692 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
693 self.handleKey(KEY_RIGHT)
697 self._value[self.marked_block] = newvalue
699 if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
700 self.handleKey(KEY_RIGHT)
708 for i in self._value:
709 block_strlen.append(len(str(i)))
711 value += self.seperator
713 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
714 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
715 mBlock = range(leftPos, rightPos)
716 return (value, mBlock)
718 def getMulti(self, selected):
719 (value, mBlock) = self.genText()
721 return ("mtext"[1-selected:], value, mBlock)
723 return ("text", value)
725 def getHTML(self, id):
726 # we definitely don't want leading zeros
727 return '.'.join(["%d" % d for d in self.value])
729 mac_limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)]
730 class ConfigMAC(ConfigSequence):
731 def __init__(self, default):
732 ConfigSequence.__init__(self, seperator = ":", limits = mac_limits, default = default)
734 class ConfigPosition(ConfigSequence):
735 def __init__(self, default, args):
736 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
738 clock_limits = [(0,23),(0,59)]
739 class ConfigClock(ConfigSequence):
740 def __init__(self, default):
741 t = localtime(default)
742 ConfigSequence.__init__(self, seperator = ":", limits = clock_limits, default = [t.tm_hour, t.tm_min])
745 # Check if Minutes maxed out
746 if self._value[1] == 59:
747 # Increment Hour, reset Minutes
748 if self._value[0] < 23:
760 # Check if Minutes is minimum
761 if self._value[1] == 0:
762 # Decrement Hour, set Minutes to 59
763 if self._value[0] > 0:
774 integer_limits = (0, 9999999999)
775 class ConfigInteger(ConfigSequence):
776 def __init__(self, default, limits = integer_limits):
777 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
779 # you need to override this to do input validation
780 def setValue(self, value):
781 self._value = [value]
785 return self._value[0]
787 value = property(getValue, setValue)
789 def fromstring(self, value):
792 def tostring(self, value):
795 class ConfigPIN(ConfigInteger):
796 def __init__(self, default, len = 4, censor = ""):
797 assert isinstance(default, int), "ConfigPIN default must be an integer"
800 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
806 class ConfigFloat(ConfigSequence):
807 def __init__(self, default, limits):
808 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
811 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
813 float = property(getFloat)
815 # an editable text...
816 class ConfigText(ConfigElement, NumericalTextInput):
817 def __init__(self, default = "", fixed_size = True, visible_width = False):
818 ConfigElement.__init__(self)
819 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
822 self.allmarked = (default != "")
823 self.fixed_size = fixed_size
824 self.visible_width = visible_width
826 self.overwrite = fixed_size
827 self.help_window = None
828 self.value = self.default = default
829 self._keyboardMode = 0
831 def validateMarker(self):
832 textlen = len(self.text)
834 if self.marked_pos > textlen-1:
835 self.marked_pos = textlen-1
837 if self.marked_pos > textlen:
838 self.marked_pos = textlen
839 if self.marked_pos < 0:
841 if self.visible_width:
842 if self.marked_pos < self.offset:
843 self.offset = self.marked_pos
844 if self.marked_pos >= self.offset + self.visible_width:
845 if self.marked_pos == textlen:
846 self.offset = self.marked_pos - self.visible_width
848 self.offset = self.marked_pos - self.visible_width + 1
849 if self.offset > 0 and self.offset + self.visible_width > textlen:
850 self.offset = max(0, len - self.visible_width)
852 def insertChar(self, ch, pos, owr):
853 if owr or self.overwrite:
854 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
855 elif self.fixed_size:
856 self.text = self.text[0:pos] + ch + self.text[pos:-1]
858 self.text = self.text[0:pos] + ch + self.text[pos:]
860 def deleteChar(self, pos):
861 if not self.fixed_size:
862 self.text = self.text[0:pos] + self.text[pos + 1:]
864 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
866 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
868 def deleteAllChars(self):
870 self.text = " " * len(self.text)
875 def handleKey(self, key):
876 # this will no change anything on the value itself
877 # so we can handle it here in gui element
878 if key == KEY_DELETE:
881 self.deleteAllChars()
882 self.allmarked = False
884 self.deleteChar(self.marked_pos)
885 if self.fixed_size and self.overwrite:
887 elif key == KEY_BACKSPACE:
890 self.deleteAllChars()
891 self.allmarked = False
892 elif self.marked_pos > 0:
893 self.deleteChar(self.marked_pos-1)
894 if not self.fixed_size and self.offset > 0:
897 elif key == KEY_LEFT:
900 self.marked_pos = len(self.text)
901 self.allmarked = False
904 elif key == KEY_RIGHT:
908 self.allmarked = False
911 elif key == KEY_HOME:
913 self.allmarked = False
917 self.allmarked = False
918 self.marked_pos = len(self.text)
919 elif key == KEY_TOGGLEOW:
921 self.overwrite = not self.overwrite
922 elif key == KEY_ASCII:
924 newChar = unichr(getPrevAsciiCode())
925 if not self.useableChars or newChar in self.useableChars:
927 self.deleteAllChars()
928 self.allmarked = False
929 self.insertChar(newChar, self.marked_pos, False)
931 elif key in KEY_NUMBERS:
932 owr = self.lastKey == getKeyNumber(key)
933 newChar = self.getKey(getKeyNumber(key))
935 self.deleteAllChars()
936 self.allmarked = False
937 self.insertChar(newChar, self.marked_pos, owr)
938 elif key == KEY_TIMEOUT:
941 self.help_window.update(self)
945 self.help_window.update(self)
946 self.validateMarker()
951 self.validateMarker()
955 return self.text.encode("utf-8")
957 def setValue(self, val):
959 self.text = val.decode("utf-8")
960 except UnicodeDecodeError:
961 self.text = val.decode("utf-8", "ignore")
965 value = property(getValue, setValue)
966 _value = property(getValue, setValue)
969 return self.text.encode("utf-8")
971 def getMulti(self, selected):
972 if self.visible_width:
974 mark = range(0, min(self.visible_width, len(self.text)))
976 mark = [self.marked_pos-self.offset]
977 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
980 mark = range(0, len(self.text))
982 mark = [self.marked_pos]
983 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
985 def onSelect(self, session):
986 self.allmarked = (self.value != "")
987 self._keyboardMode = eRCInput.getInstance().getKeyboardMode()
988 eRCInput.getInstance().setKeyboardMode(eRCInput.kmAscii)
989 if session is not None:
990 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
991 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
992 self.help_window.show()
994 def onDeselect(self, session):
995 eRCInput.getInstance().setKeyboardMode(self._keyboardMode)
999 session.deleteDialog(self.help_window)
1000 self.help_window = None
1001 ConfigElement.onDeselect(self, session)
1003 def getHTML(self, id):
1004 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
1006 def unsafeAssign(self, value):
1007 self.value = str(value)
1009 class ConfigPassword(ConfigText):
1010 def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
1011 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1012 self.censor_char = censor
1015 def getMulti(self, selected):
1016 mtext, text, mark = ConfigText.getMulti(self, selected)
1018 text = len(text) * self.censor_char
1019 return (mtext, text, mark)
1021 def onSelect(self, session):
1022 ConfigText.onSelect(self, session)
1025 def onDeselect(self, session):
1026 ConfigText.onDeselect(self, session)
1029 # lets the user select between [min, min+stepwidth, min+(stepwidth*2)..., maxval] with maxval <= max depending
1031 # min, max, stepwidth, default are int values
1032 # wraparound: pressing RIGHT key at max value brings you to min value and vice versa if set to True
1033 class ConfigSelectionNumber(ConfigSelection):
1034 def __init__(self, min, max, stepwidth, default = None, wraparound = False):
1035 self.wraparound = wraparound
1038 default = str(default)
1042 choices.append(str(step))
1045 ConfigSelection.__init__(self, choices, default)
1048 return int(ConfigSelection.getValue(self))
1050 def setValue(self, val):
1051 ConfigSelection.setValue(self, str(val))
1053 def handleKey(self, key):
1054 if not self.wraparound:
1055 if key == KEY_RIGHT:
1056 if len(self.choices) == (self.choices.index(self.value) + 1):
1059 if self.choices.index(self.value) == 0:
1061 ConfigSelection.handleKey(self, key)
1063 class ConfigNumber(ConfigText):
1064 def __init__(self, default = 0):
1065 ConfigText.__init__(self, str(default), fixed_size = False)
1068 return int(self.text)
1070 def setValue(self, val):
1071 self.text = str(val)
1074 value = property(getValue, setValue)
1075 _value = property(getValue, setValue)
1077 def isChanged(self):
1078 sv = self.saved_value
1079 strv = self.tostring(self.value)
1080 if sv is None and strv == self.default:
1085 pos = len(self.text) - self.marked_pos
1086 self.text = self.text.lstrip("0")
1089 if pos > len(self.text):
1092 self.marked_pos = len(self.text) - pos
1094 def handleKey(self, key):
1095 if key in KEY_NUMBERS or key == KEY_ASCII:
1096 if key == KEY_ASCII:
1097 ascii = getPrevAsciiCode()
1098 if not (48 <= ascii <= 57):
1101 ascii = getKeyNumber(key) + 48
1102 newChar = unichr(ascii)
1104 self.deleteAllChars()
1105 self.allmarked = False
1106 self.insertChar(newChar, self.marked_pos, False)
1107 self.marked_pos += 1
1109 ConfigText.handleKey(self, key)
1112 def onSelect(self, session):
1113 self.allmarked = (self.value != "")
1114 self._keyboardMode = eRCInput.getInstance().getKeyboardMode()
1116 class ConfigSearchText(ConfigText):
1117 def __init__(self, default = "", fixed_size = False, visible_width = False, special_chars = ""):
1118 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1119 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = special_chars)
1121 class ConfigDirectory(ConfigText):
1122 def __init__(self, default="", visible_width=60):
1123 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
1125 def handleKey(self, key):
1132 return ConfigText.getValue(self)
1134 def setValue(self, val):
1137 ConfigText.setValue(self, val)
1139 def getMulti(self, selected):
1141 return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
1143 return ConfigText.getMulti(self, selected)
1145 def onSelect(self, session):
1146 self.allmarked = (self.value != "")
1147 self._keyboardMode = eRCInput.getInstance().getKeyboardMode()
1150 class ConfigSlider(ConfigElement):
1151 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
1152 ConfigElement.__init__(self)
1153 self.value = self.default = default
1154 self.min = limits[0]
1155 self.max = limits[1]
1156 self.increment = increment
1158 def checkValues(self):
1159 if self.value < self.min:
1160 self.value = self.min
1162 if self.value > self.max:
1163 self.value = self.max
1165 def handleKey(self, key):
1167 self.value -= self.increment
1168 elif key == KEY_RIGHT:
1169 self.value += self.increment
1170 elif key == KEY_HOME:
1171 self.value = self.min
1172 elif key == KEY_END:
1173 self.value = self.max
1179 return "%d / %d" % (self.value, self.max)
1181 def getMulti(self, selected):
1183 return ("slider", self.value, self.max)
1185 def fromstring(self, value):
1188 # a satlist. in fact, it's a ConfigSelection.
1189 class ConfigSatlist(ConfigSelection):
1190 def __init__(self, list, default = None):
1191 if default is not None:
1192 default = str(default)
1193 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1195 def getOrbitalPosition(self):
1196 if self.value == "":
1198 return int(self.value)
1200 orbital_position = property(getOrbitalPosition)
1202 class ConfigSet(ConfigElement):
1203 def __init__(self, choices, default = []):
1204 ConfigElement.__init__(self)
1205 if isinstance(choices, list):
1207 self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
1209 assert False, "ConfigSet choices must be a list!"
1214 self.default = default
1215 self.value = default[:]
1217 def toggleChoice(self, choice):
1220 value.remove(choice)
1222 value.append(choice)
1226 def handleKey(self, key):
1227 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1229 self.toggleChoice(self.choices[self.pos])
1230 elif key == KEY_LEFT:
1232 self.pos = len(self.choices)-1
1235 elif key == KEY_RIGHT:
1236 if self.pos >= len(self.choices)-1:
1240 elif key in (KEY_HOME, KEY_END):
1243 def genString(self, lst):
1246 res += self.description[x]+" "
1250 return self.genString(self.value)
1252 def getMulti(self, selected):
1253 if not selected or self.pos == -1:
1254 return ("text", self.genString(self.value))
1257 ch = self.choices[self.pos]
1258 mem = ch in self.value
1263 val1 = self.genString(tmp[:ind])
1264 val2 = " "+self.genString(tmp[ind+1:])
1266 chstr = " "+self.description[ch]+" "
1268 chstr = "("+self.description[ch]+")"
1269 len_val1 = len(val1)
1270 return ("mtext", val1+chstr+val2, range(len_val1, len_val1 + len(chstr)))
1272 def onDeselect(self, session):
1274 ConfigElement.onDeselect(self, session)
1276 def tostring(self, value):
1279 def fromstring(self, val):
1282 description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
1284 class ConfigLocations(ConfigElement):
1285 def __init__(self, default = [], visible_width = False):
1286 ConfigElement.__init__(self)
1287 self.visible_width = visible_width
1289 self.default = default
1291 self.mountpoints = []
1292 self.value = default[:]
1294 def setValue(self, value):
1295 locations = self.locations
1296 loc = [x[0] for x in locations if x[3]]
1297 add = [x for x in value if not x in loc]
1298 diff = add + [x for x in loc if not x in value]
1299 locations = [x for x in locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1300 locations.sort(key = lambda x: x[0])
1301 self.locations = locations
1305 self.checkChangedMountpoints()
1306 locations = self.locations
1309 return [x[0] for x in locations if x[3]]
1311 value = property(getValue, setValue)
1313 def tostring(self, value):
1316 def fromstring(self, val):
1320 sv = self.saved_value
1324 tmp = self.fromstring(sv)
1325 locations = [[x, None, False, False] for x in tmp]
1326 self.refreshMountpoints()
1328 if fileExists(x[0]):
1329 x[1] = self.getMountpoint(x[0])
1331 self.locations = locations
1334 locations = self.locations
1335 if self.save_disabled or not locations:
1336 self.saved_value = None
1338 self.saved_value = self.tostring([x[0] for x in locations])
1340 def isChanged(self):
1341 sv = self.saved_value
1342 locations = self.locations
1343 if val is None and not locations:
1345 return self.tostring([x[0] for x in locations]) != sv
1347 def addedMount(self, mp):
1348 for x in self.locations:
1351 elif x[1] == None and fileExists(x[0]):
1352 x[1] = self.getMountpoint(x[0])
1355 def removedMount(self, mp):
1356 for x in self.locations:
1360 def refreshMountpoints(self):
1361 self.mountpoints = [p.mountpoint for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1362 self.mountpoints.sort(key = lambda x: -len(x))
1364 def checkChangedMountpoints(self):
1365 oldmounts = self.mountpoints
1366 self.refreshMountpoints()
1367 newmounts = self.mountpoints
1368 if oldmounts == newmounts:
1371 if not x in newmounts:
1372 self.removedMount(x)
1374 if not x in oldmounts:
1377 def getMountpoint(self, file):
1378 file = os_path.realpath(file)+"/"
1379 for m in self.mountpoints:
1380 if file.startswith(m):
1384 def handleKey(self, key):
1388 self.pos = len(self.value)-1
1389 elif key == KEY_RIGHT:
1391 if self.pos >= len(self.value):
1393 elif key in (KEY_HOME, KEY_END):
1397 return " ".join(self.value)
1399 def getMulti(self, selected):
1401 valstr = " ".join(self.value)
1402 if self.visible_width and len(valstr) > self.visible_width:
1403 return ("text", valstr[0:self.visible_width])
1405 return ("text", valstr)
1411 for val in self.value:
1414 valstr += str(val)+" "
1418 if self.visible_width and len(valstr) > self.visible_width:
1419 if ind1+1 < self.visible_width/2:
1422 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1423 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1425 return ("mtext", valstr, range(ind1,ind2))
1427 def onDeselect(self, session):
1429 ConfigElement.onDeselect(self, session)
1432 class ConfigNothing(ConfigSelection):
1434 ConfigSelection.__init__(self, choices = [("","")])
1436 # until here, 'saved_value' always had to be a *string*.
1437 # now, in ConfigSubsection, and only there, saved_value
1438 # is a dict, essentially forming a tree.
1440 # config.foo.bar=True
1441 # config.foobar=False
1444 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1447 class ConfigSubsectionContent(object):
1450 # we store a backup of the loaded configuration
1451 # data in self.stored_values, to be able to deploy
1452 # them when a new config element will be added,
1453 # so non-default values are instantly available
1455 # A list, for example:
1456 # config.dipswitches = ConfigSubList()
1457 # config.dipswitches.append(ConfigYesNo())
1458 # config.dipswitches.append(ConfigYesNo())
1459 # config.dipswitches.append(ConfigYesNo())
1460 class ConfigSubList(list, object):
1463 self.stored_values = {}
1473 def getSavedValue(self):
1475 for i, val in enumerate(self):
1476 sv = val.saved_value
1481 def setSavedValue(self, values):
1482 self.stored_values = dict(values)
1483 for (key, val) in self.stored_values.items():
1484 if int(key) < len(self):
1485 self[int(key)].saved_value = val
1487 saved_value = property(getSavedValue, setSavedValue)
1489 def append(self, item):
1491 list.append(self, item)
1492 if i in self.stored_values:
1493 item.saved_value = self.stored_values[i]
1497 return dict([(str(index), value) for index, value in enumerate(self)])
1499 # same as ConfigSubList, just as a dictionary.
1500 # care must be taken that the 'key' has a proper
1501 # str() method, because it will be used in the config
1503 class ConfigSubDict(dict, object):
1506 self.stored_values = {}
1509 for x in self.values():
1513 for x in self.values():
1516 def getSavedValue(self):
1518 for (key, val) in self.items():
1519 sv = val.saved_value
1524 def setSavedValue(self, values):
1525 self.stored_values = dict(values)
1526 for (key, val) in self.items():
1527 if str(key) in self.stored_values:
1528 val.saved_value = self.stored_values[str(key)]
1530 saved_value = property(getSavedValue, setSavedValue)
1532 def __setitem__(self, key, item):
1533 dict.__setitem__(self, key, item)
1534 if str(key) in self.stored_values:
1535 item.saved_value = self.stored_values[str(key)]
1541 # Like the classes above, just with a more "native"
1544 # some evil stuff must be done to allow instant
1545 # loading of added elements. this is why this class
1548 # we need the 'content' because we overwrite
1550 # If you don't understand this, try adding
1551 # __setattr__ to a usual exisiting class and you will.
1552 class ConfigSubsection(object):
1554 self.__dict__["content"] = ConfigSubsectionContent()
1555 self.content.items = { }
1556 self.content.stored_values = { }
1558 def __setattr__(self, name, value):
1559 if name == "saved_value":
1560 return self.setSavedValue(value)
1561 assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1562 content = self.content
1563 content.items[name] = value
1564 x = content.stored_values.get(name, None)
1566 #print "ok, now we have a new item,", name, "and have the following value for it:", x
1567 value.saved_value = x
1570 def __getattr__(self, name):
1571 return self.content.items[name]
1573 def getSavedValue(self):
1574 res = self.content.stored_values
1575 for (key, val) in self.content.items.items():
1576 sv = val.saved_value
1583 def setSavedValue(self, values, append = False):
1584 values = dict(values)
1587 self.content.stored_values.update(values)
1589 self.content.stored_values = values
1591 self.content.stored_values = values
1592 for (key, val) in self.content.items.items():
1593 value = values.get(key, None)
1594 if value is not None:
1595 val.saved_value = value
1597 saved_value = property(getSavedValue, setSavedValue)
1600 for x in self.content.items.values():
1604 for x in self.content.items.values():
1608 return self.content.items
1610 # the root config object, which also can "pickle" (=serialize)
1611 # down the whole config tree.
1613 # we try to keep non-existing config entries, to apply them whenever
1614 # a new config entry is added to a subsection
1615 # also, non-existing config entries will be saved, so they won't be
1616 # lost when a config entry disappears.
1617 class Config(ConfigSubsection):
1619 ConfigSubsection.__init__(self)
1621 def pickle_this(self, prefix, topickle, result):
1622 for (key, val) in topickle.items():
1623 name = '.'.join((prefix, key))
1624 if isinstance(val, dict):
1625 self.pickle_this(name, val, result)
1626 elif isinstance(val, tuple):
1627 result += [name, '=', val[0], '\n']
1629 result += [name, '=', val, '\n']
1633 self.pickle_this("config", self.saved_value, result)
1634 return ''.join(result)
1636 def unpickle(self, lines, base_file=True, append = False):
1639 if not l or l[0] == '#':
1644 val = l[n+1:].strip()
1646 names = name.split('.')
1647 # if val.find(' ') != -1:
1648 # val = val[:val.find(' ')]
1652 for n in names[:-1]:
1653 base = base.setdefault(n, {})
1655 base[names[-1]] = val
1657 if not base_file: # not the initial config file..
1658 #update config.x.y.value when exist
1660 configEntry = eval(name)
1661 if configEntry is not None:
1662 configEntry.value = val
1663 except (SyntaxError, KeyError):
1666 # we inherit from ConfigSubsection, so ...
1667 #object.__setattr__(self, "saved_value", tree["config"])
1668 if "config" in tree:
1669 self.setSavedValue(tree["config"], append)
1671 def saveToFile(self, filename):
1672 saveFile(filename, self.pickle())
1674 def loadFromFile(self, filename, base_file=False, append = False):
1675 f = open(filename, "r")
1676 self.unpickle(f.readlines(), base_file, append)
1680 config.misc = ConfigSubsection()
1683 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1687 config.loadFromFile(self.CONFIG_FILE, True)
1689 print "unable to load config (%s), assuming defaults..." % str(e)
1693 config.saveToFile(self.CONFIG_FILE)
1695 def __resolveValue(self, pickles, cmap):
1697 if cmap.has_key(key):
1698 if len(pickles) > 1:
1699 return self.__resolveValue(pickles[1:], cmap[key].dict())
1701 return str(cmap[key].value)
1704 def getResolvedKey(self, key):
1705 names = key.split('.')
1707 if names[0] == "config":
1708 ret=self.__resolveValue(names[1:], config.content.items)
1709 if ret and len(ret):
1713 def NoSave(element):
1714 element.disableSave()
1717 configfile = ConfigFile()
1720 from Components.Harddisk import harddiskmanager
1722 def getConfigListEntry(*args):
1723 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1726 def updateConfigElement(element, newelement):
1727 newelement.value = element.value
1733 #config.bla = ConfigSubsection()
1734 #config.bla.test = ConfigYesNo()
1735 #config.nim = ConfigSubList()
1736 #config.nim.append(ConfigSubsection())
1737 #config.nim[0].bla = ConfigYesNo()
1738 #config.nim.append(ConfigSubsection())
1739 #config.nim[1].bla = ConfigYesNo()
1740 #config.nim[1].blub = ConfigYesNo()
1741 #config.arg = ConfigSubDict()
1742 #config.arg["Hello"] = ConfigYesNo()
1744 #config.arg["Hello"].handleKey(KEY_RIGHT)
1745 #config.arg["Hello"].handleKey(KEY_RIGHT)
1747 ##config.saved_value
1751 #print config.pickle()