1 from enigma import eRCInput, getPrevAsciiCode
2 from Tools.NumericalTextInput import NumericalTextInput
3 from Tools.Directories import resolveFilename, SCOPE_CONFIG, fileExists
4 from copy import copy as copy_copy
5 from os import path as os_path
6 from time import localtime, strftime
8 # ConfigElement, the base class of all ConfigElements.
11 # value the current value, usefully encoded.
12 # usually a property which retrieves _value,
13 # and maybe does some reformatting
14 # _value the value as it's going to be saved in the configfile,
15 # though still in non-string form.
16 # this is the object which is actually worked on.
17 # default the initial value. If _value is equal to default,
18 # it will not be stored in the config file
19 # saved_value is a text representation of _value, stored in the config file
21 # and has (at least) the following methods:
22 # save() stores _value into saved_value,
23 # (or stores 'None' if it should not be stored)
24 # load() loads _value from saved_value, or loads
25 # the default if saved_value is 'None' (default)
28 class ConfigElement(object):
30 self.saved_value = None
31 self.save_forced = False
32 self.save_disabled = False
33 self.__notifiers = { }
34 self.__notifiers_final = { }
37 def getNotifiers(self):
38 return [func for (func, val, call_on_save_and_cancel) in self.__notifiers.itervalues()]
40 def setNotifiers(self, val):
41 print "just readonly access to notifiers is allowed! append/remove doesnt work anymore! please use addNotifier, removeNotifier, clearNotifiers"
43 notifiers = property(getNotifiers, setNotifiers)
45 def getNotifiersFinal(self):
46 return [func for (func, val, call_on_save_and_cancel) in self.__notifiers_final.itervalues()]
48 def setNotifiersFinal(self, val):
49 print "just readonly access to notifiers_final is allowed! append/remove doesnt work anymore! please use addNotifier, removeNotifier, clearNotifiers"
51 notifiers_final = property(getNotifiersFinal, setNotifiersFinal)
53 # you need to override this to do input validation
54 def setValue(self, value):
61 value = property(getValue, setValue)
63 # you need to override this if self.value is not a string
64 def fromstring(self, value):
67 # you can overide this for fancy default handling
71 self.value = self.default
73 self.value = self.fromstring(sv)
75 def tostring(self, value):
78 # you need to override this if str(self.value) doesn't work
80 if self.save_disabled or (self.value == self.default and not self.save_forced):
81 self.saved_value = None
83 self.saved_value = self.tostring(self.value)
84 self.changed(save_or_cancel=True)
85 self.changedFinal(save_or_cancel=True)
89 self.changed(save_or_cancel=True)
90 self.changedFinal(save_or_cancel=True)
94 if sv is None and self.value == self.default:
96 return self.tostring(self.value) != sv
98 def changed(self, save_or_cancel=False):
99 for (func, val) in self.__notifiers.iteritems():
100 if (val[2] and save_or_cancel) or (save_or_cancel == False and val[1] != self.value):
101 self.__notifiers[func] = (val[0], self.value, val[2])
104 def changedFinal(self, save_or_cancel=False):
105 for (func, val) in self.__notifiers_final.iteritems():
106 if (val[2] and save_or_cancel) or (save_or_cancel == False and val[1] != self.value):
107 self.__notifiers_final[func] = (val[0], self.value, val[2])
110 # immediate_feedback = True means call notifier on every value CHANGE
111 # immediate_feedback = False means call notifier on leave the config element (up/down) when value have CHANGED
112 # call_on_save_or_cancel = True means call notifier always on save/cancel.. even when value have not changed
113 def addNotifier(self, notifier, initial_call = True, immediate_feedback = True, call_on_save_or_cancel = False):
114 assert callable(notifier), "notifiers must be callable"
115 if immediate_feedback:
116 self.__notifiers[str(notifier)] = (notifier, self.value, call_on_save_or_cancel)
118 self.__notifiers_final[str(notifier)] = (notifier, self.value, call_on_save_or_cancel)
120 # do we want to call the notifier
121 # - at all when adding it? (yes, though optional)
122 # - when the default is active? (yes)
123 # - when no value *yet* has been set,
124 # because no config has ever been read (currently yes)
125 # (though that's not so easy to detect.
126 # the entry could just be new.)
130 def removeNotifier(self, notifier):
131 del self.__notifiers[str(notifier)]
133 def clearNotifiers(self):
134 self.__notifiers = { }
136 def disableSave(self):
137 self.save_disabled = True
139 def __call__(self, selected):
140 return self.getMulti(selected)
142 def onSelect(self, session):
145 def onDeselect(self, session):
158 KEY_NUMBERS = range(12, 12+10)
162 def getKeyNumber(key):
163 assert key in KEY_NUMBERS
166 class choicesList(object): # XXX: we might want a better name for this
170 def __init__(self, choices, type = None):
171 self.choices = choices
173 if isinstance(choices, list):
174 self.type = choicesList.LIST_TYPE_LIST
175 elif isinstance(choices, dict):
176 self.type = choicesList.LIST_TYPE_DICT
178 assert False, "choices must be dict or list!"
183 if self.type == choicesList.LIST_TYPE_LIST:
184 ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
186 ret = self.choices.keys()
190 if self.type == choicesList.LIST_TYPE_LIST:
191 ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
194 return iter(ret or [""])
197 return len(self.choices) or 1
199 def updateItemDescription(self, index, descr):
200 if self.type == choicesList.LIST_TYPE_LIST:
201 orig = self.choices[index]
202 assert isinstance(orig, tuple)
203 self.choices[index] = (orig[0], descr)
205 key = self.choices.keys()[index]
206 self.choices[key] = descr
208 def __getitem__(self, index):
209 if self.type == choicesList.LIST_TYPE_LIST:
210 ret = self.choices[index]
211 if isinstance(ret, tuple):
214 return self.choices.keys()[index]
216 def index(self, value):
217 return self.__list__().index(value)
219 def __setitem__(self, index, value):
220 if self.type == choicesList.LIST_TYPE_LIST:
221 orig = self.choices[index]
222 if isinstance(orig, tuple):
223 self.choices[index] = (value, orig[1])
225 self.choices[index] = value
227 key = self.choices.keys()[index]
228 orig = self.choices[key]
229 del self.choices[key]
230 self.choices[value] = orig
233 choices = self.choices
236 if self.type is choicesList.LIST_TYPE_LIST:
238 if isinstance(default, tuple):
241 default = choices.keys()[0]
244 class descriptionList(choicesList): # XXX: we might want a better name for this
246 if self.type == choicesList.LIST_TYPE_LIST:
247 ret = [not isinstance(x, tuple) and x or x[1] for x in self.choices]
249 ret = self.choices.values()
253 return iter(self.__list__())
255 def __getitem__(self, index):
256 if self.type == choicesList.LIST_TYPE_LIST:
257 for x in self.choices:
258 if isinstance(x, tuple):
263 return str(index) # Fallback!
265 return str(self.choices.get(index, ""))
267 def __setitem__(self, index, value):
268 if self.type == choicesList.LIST_TYPE_LIST:
269 i = self.index(index)
270 orig = self.choices[i]
271 if isinstance(orig, tuple):
272 self.choices[i] = (orig[0], value)
274 self.choices[i] = value
276 self.choices[index] = value
279 # ConfigSelection is a "one of.."-type.
280 # it has the "choices", usually a list, which contains
281 # (id, desc)-tuples (or just only the ids, in case the id
282 # will be used as description)
284 # all ids MUST be plain strings.
286 class ConfigSelection(ConfigElement):
287 def __init__(self, choices, default = None):
288 ConfigElement.__init__(self)
289 self.choices = choicesList(choices)
292 default = self.choices.default()
295 self.default = self._value = default
297 def setChoices(self, choices, default = None):
298 self.choices = choicesList(choices)
301 default = self.choices.default()
302 self.default = default
304 if self.value not in self.choices:
307 def setValue(self, value):
308 if value in self.choices:
311 self._value = self.default
315 def tostring(self, val):
321 def setCurrentText(self, text):
322 i = self.choices.index(self.value)
323 self.choices[i] = text
324 self._descr = self.description[text] = text
327 value = property(getValue, setValue)
330 return self.choices.index(self.value)
332 index = property(getIndex)
335 def handleKey(self, key):
336 nchoices = len(self.choices)
337 i = self.choices.index(self.value)
339 self.value = self.choices[(i + nchoices - 1) % nchoices]
340 elif key == KEY_RIGHT:
341 self.value = self.choices[(i + 1) % nchoices]
342 elif key == KEY_HOME:
343 self.value = self.choices[0]
345 self.value = self.choices[nchoices - 1]
347 def selectNext(self):
348 nchoices = len(self.choices)
349 i = self.choices.index(self.value)
350 self.value = self.choices[(i + 1) % nchoices]
353 if self._descr is not None:
355 descr = self._descr = self.description[self.value]
360 def getMulti(self, selected):
361 if self._descr is not None:
364 descr = self._descr = self.description[self.value]
366 return ("text", _(descr))
367 return ("text", descr)
370 def getHTML(self, id):
372 for v in self.choices:
373 descr = self.description[v]
375 checked = 'checked="checked" '
378 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + descr + "</input></br>\n"
381 def unsafeAssign(self, value):
382 # setValue does check if value is in choices. This is safe enough.
385 description = property(lambda self: descriptionList(self.choices.choices, self.choices.type))
389 # several customized versions exist for different
392 boolean_descriptions = {False: "false", True: "true"}
393 class ConfigBoolean(ConfigElement):
394 def __init__(self, default = False, descriptions = boolean_descriptions):
395 ConfigElement.__init__(self)
396 self.descriptions = descriptions
397 self.value = self.default = default
399 def handleKey(self, key):
400 if key in (KEY_LEFT, KEY_RIGHT):
401 self.value = not self.value
402 elif key == KEY_HOME:
408 descr = self.descriptions[self.value]
413 def getMulti(self, selected):
414 descr = self.descriptions[self.value]
416 return ("text", _(descr))
417 return ("text", descr)
419 def tostring(self, value):
425 def fromstring(self, val):
431 def getHTML(self, id):
433 checked = ' checked="checked"'
436 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
438 # this is FLAWED. and must be fixed.
439 def unsafeAssign(self, value):
445 yes_no_descriptions = {False: _("no"), True: _("yes")}
446 class ConfigYesNo(ConfigBoolean):
447 def __init__(self, default = False):
448 ConfigBoolean.__init__(self, default = default, descriptions = yes_no_descriptions)
450 on_off_descriptions = {False: _("off"), True: _("on")}
451 class ConfigOnOff(ConfigBoolean):
452 def __init__(self, default = False):
453 ConfigBoolean.__init__(self, default = default, descriptions = on_off_descriptions)
455 enable_disable_descriptions = {False: _("disable"), True: _("enable")}
456 class ConfigEnableDisable(ConfigBoolean):
457 def __init__(self, default = False):
458 ConfigBoolean.__init__(self, default = default, descriptions = enable_disable_descriptions)
460 class ConfigDateTime(ConfigElement):
461 def __init__(self, default, formatstring, increment = 86400):
462 ConfigElement.__init__(self)
463 self.increment = increment
464 self.formatstring = formatstring
465 self.value = self.default = int(default)
467 def handleKey(self, key):
469 self.value = self.value - self.increment
470 elif key == KEY_RIGHT:
471 self.value = self.value + self.increment
472 elif key == KEY_HOME or key == KEY_END:
473 self.value = self.default
476 return strftime(self.formatstring, localtime(self.value))
478 def getMulti(self, selected):
479 return ("text", strftime(self.formatstring, localtime(self.value)))
481 def fromstring(self, val):
484 # *THE* mighty config element class
486 # allows you to store/edit a sequence of values.
487 # can be used for IP-addresses, dates, plain integers, ...
488 # several helper exist to ease this up a bit.
490 class ConfigSequence(ConfigElement):
491 def __init__(self, seperator, limits, default, censor_char = ""):
492 ConfigElement.__init__(self)
493 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
494 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
495 #assert isinstance(default, list), "default must be a list"
496 #assert isinstance(default[0], int), "list must contain numbers"
497 #assert len(default) == len(limits), "length must match"
500 self.seperator = seperator
502 self.censor_char = censor_char
504 self.default = default
505 self.value = copy_copy(default)
506 self.endNotifier = None
511 for i in self._value:
512 max_pos += len(str(self.limits[num][1]))
514 if self._value[num] < self.limits[num][0]:
515 self._value[num] = self.limits[num][0]
517 if self._value[num] > self.limits[num][1]:
518 self._value[num] = self.limits[num][1]
522 if self.marked_pos >= max_pos:
524 for x in self.endNotifier:
526 self.marked_pos = max_pos - 1
528 if self.marked_pos < 0:
531 def validatePos(self):
532 if self.marked_pos < 0:
535 total_len = sum([len(str(x[1])) for x in self.limits])
537 if self.marked_pos >= total_len:
538 self.marked_pos = total_len - 1
540 def addEndNotifier(self, notifier):
541 if self.endNotifier is None:
542 self.endNotifier = []
543 self.endNotifier.append(notifier)
545 def handleKey(self, key):
550 elif key == KEY_RIGHT:
554 elif key == KEY_HOME:
561 for i in self._value:
562 max_pos += len(str(self.limits[num][1]))
564 self.marked_pos = max_pos - 1
567 elif key in KEY_NUMBERS or key == KEY_ASCII:
569 code = getPrevAsciiCode()
570 if code < 48 or code > 57:
574 number = getKeyNumber(key)
576 block_len = [len(str(x[1])) for x in self.limits]
577 total_len = sum(block_len)
581 block_len_total = [0, ]
583 pos += block_len[blocknumber]
584 block_len_total.append(pos)
585 if pos - 1 >= self.marked_pos:
590 # length of numberblock
591 number_len = len(str(self.limits[blocknumber][1]))
593 # position in the block
594 posinblock = self.marked_pos - block_len_total[blocknumber]
596 oldvalue = self._value[blocknumber]
597 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
598 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
600 self._value[blocknumber] = newvalue
608 mPos = self.marked_pos
610 for i in self._value:
611 if value: #fixme no heading separator possible
612 value += self.seperator
613 if mPos >= len(value) - 1:
615 if self.censor_char == "":
616 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
618 value += (self.censor_char * len(str(self.limits[num][1])))
623 (value, mPos) = self.genText()
626 def getMulti(self, selected):
627 (value, mPos) = self.genText()
628 # only mark cursor when we are selected
629 # (this code is heavily ink optimized!)
631 return ("mtext"[1-selected:], value, [mPos])
633 return ("text", value)
635 def tostring(self, val):
636 return self.seperator.join([self.saveSingle(x) for x in val])
638 def saveSingle(self, v):
641 def fromstring(self, value):
642 return [int(x) for x in value.split(self.seperator)]
644 ip_limits = [(0,255),(0,255),(0,255),(0,255)]
645 class ConfigIP(ConfigSequence):
646 def __init__(self, default, auto_jump = False):
647 ConfigSequence.__init__(self, seperator = ".", limits = ip_limits, default = default)
648 self.block_len = [len(str(x[1])) for x in self.limits]
649 self.marked_block = 0
650 self.overwrite = True
651 self.auto_jump = auto_jump
653 def handleKey(self, key):
655 if self.marked_block > 0:
656 self.marked_block -= 1
657 self.overwrite = True
659 elif key == KEY_RIGHT:
660 if self.marked_block < len(self.limits)-1:
661 self.marked_block += 1
662 self.overwrite = True
664 elif key == KEY_HOME:
665 self.marked_block = 0
666 self.overwrite = True
669 self.marked_block = len(self.limits)-1
670 self.overwrite = True
672 elif key in KEY_NUMBERS or key == KEY_ASCII:
674 code = getPrevAsciiCode()
675 if code < 48 or code > 57:
679 number = getKeyNumber(key)
680 oldvalue = self._value[self.marked_block]
683 self._value[self.marked_block] = number
684 self.overwrite = False
687 newvalue = oldvalue + number
688 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
689 self.handleKey(KEY_RIGHT)
693 self._value[self.marked_block] = newvalue
695 if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
696 self.handleKey(KEY_RIGHT)
704 for i in self._value:
705 block_strlen.append(len(str(i)))
707 value += self.seperator
709 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
710 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
711 mBlock = range(leftPos, rightPos)
712 return (value, mBlock)
714 def getMulti(self, selected):
715 (value, mBlock) = self.genText()
717 return ("mtext"[1-selected:], value, mBlock)
719 return ("text", value)
721 def getHTML(self, id):
722 # we definitely don't want leading zeros
723 return '.'.join(["%d" % d for d in self.value])
725 mac_limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)]
726 class ConfigMAC(ConfigSequence):
727 def __init__(self, default):
728 ConfigSequence.__init__(self, seperator = ":", limits = mac_limits, default = default)
730 class ConfigPosition(ConfigSequence):
731 def __init__(self, default, args):
732 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
734 clock_limits = [(0,23),(0,59)]
735 class ConfigClock(ConfigSequence):
736 def __init__(self, default):
737 t = localtime(default)
738 ConfigSequence.__init__(self, seperator = ":", limits = clock_limits, default = [t.tm_hour, t.tm_min])
741 # Check if Minutes maxed out
742 if self._value[1] == 59:
743 # Increment Hour, reset Minutes
744 if self._value[0] < 23:
756 # Check if Minutes is minimum
757 if self._value[1] == 0:
758 # Decrement Hour, set Minutes to 59
759 if self._value[0] > 0:
770 integer_limits = (0, 9999999999)
771 class ConfigInteger(ConfigSequence):
772 def __init__(self, default, limits = integer_limits):
773 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
775 # you need to override this to do input validation
776 def setValue(self, value):
777 self._value = [value]
781 return self._value[0]
783 value = property(getValue, setValue)
785 def fromstring(self, value):
788 def tostring(self, value):
791 class ConfigPIN(ConfigInteger):
792 def __init__(self, default, len = 4, censor = ""):
793 assert isinstance(default, int), "ConfigPIN default must be an integer"
796 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
802 class ConfigFloat(ConfigSequence):
803 def __init__(self, default, limits):
804 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
807 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
809 float = property(getFloat)
811 # an editable text...
812 class ConfigText(ConfigElement, NumericalTextInput):
813 def __init__(self, default = "", fixed_size = True, visible_width = False):
814 ConfigElement.__init__(self)
815 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
818 self.allmarked = (default != "")
819 self.fixed_size = fixed_size
820 self.visible_width = visible_width
822 self.overwrite = fixed_size
823 self.help_window = None
824 self.value = self.default = default
825 self._keyboardMode = 0
827 def validateMarker(self):
828 textlen = len(self.text)
830 if self.marked_pos > textlen-1:
831 self.marked_pos = textlen-1
833 if self.marked_pos > textlen:
834 self.marked_pos = textlen
835 if self.marked_pos < 0:
837 if self.visible_width:
838 if self.marked_pos < self.offset:
839 self.offset = self.marked_pos
840 if self.marked_pos >= self.offset + self.visible_width:
841 if self.marked_pos == textlen:
842 self.offset = self.marked_pos - self.visible_width
844 self.offset = self.marked_pos - self.visible_width + 1
845 if self.offset > 0 and self.offset + self.visible_width > textlen:
846 self.offset = max(0, len - self.visible_width)
848 def insertChar(self, ch, pos, owr):
849 if owr or self.overwrite:
850 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
851 elif self.fixed_size:
852 self.text = self.text[0:pos] + ch + self.text[pos:-1]
854 self.text = self.text[0:pos] + ch + self.text[pos:]
856 def deleteChar(self, pos):
857 if not self.fixed_size:
858 self.text = self.text[0:pos] + self.text[pos + 1:]
860 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
862 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
864 def deleteAllChars(self):
866 self.text = " " * len(self.text)
871 def handleKey(self, key):
872 # this will no change anything on the value itself
873 # so we can handle it here in gui element
874 if key == KEY_DELETE:
877 self.deleteAllChars()
878 self.allmarked = False
880 self.deleteChar(self.marked_pos)
881 if self.fixed_size and self.overwrite:
883 elif key == KEY_BACKSPACE:
886 self.deleteAllChars()
887 self.allmarked = False
888 elif self.marked_pos > 0:
889 self.deleteChar(self.marked_pos-1)
890 if not self.fixed_size and self.offset > 0:
893 elif key == KEY_LEFT:
896 self.marked_pos = len(self.text)
897 self.allmarked = False
900 elif key == KEY_RIGHT:
904 self.allmarked = False
907 elif key == KEY_HOME:
909 self.allmarked = False
913 self.allmarked = False
914 self.marked_pos = len(self.text)
915 elif key == KEY_TOGGLEOW:
917 self.overwrite = not self.overwrite
918 elif key == KEY_ASCII:
920 newChar = unichr(getPrevAsciiCode())
921 if not self.useableChars or newChar in self.useableChars:
923 self.deleteAllChars()
924 self.allmarked = False
925 self.insertChar(newChar, self.marked_pos, False)
927 elif key in KEY_NUMBERS:
928 owr = self.lastKey == getKeyNumber(key)
929 newChar = self.getKey(getKeyNumber(key))
931 self.deleteAllChars()
932 self.allmarked = False
933 self.insertChar(newChar, self.marked_pos, owr)
934 elif key == KEY_TIMEOUT:
937 self.help_window.update(self)
941 self.help_window.update(self)
942 self.validateMarker()
947 self.validateMarker()
951 return self.text.encode("utf-8")
953 def setValue(self, val):
955 self.text = val.decode("utf-8")
956 except UnicodeDecodeError:
957 self.text = val.decode("utf-8", "ignore")
961 value = property(getValue, setValue)
962 _value = property(getValue, setValue)
965 return self.text.encode("utf-8")
967 def getMulti(self, selected):
968 if self.visible_width:
970 mark = range(0, min(self.visible_width, len(self.text)))
972 mark = [self.marked_pos-self.offset]
973 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
976 mark = range(0, len(self.text))
978 mark = [self.marked_pos]
979 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
981 def onSelect(self, session):
982 self.allmarked = (self.value != "")
983 self._keyboardMode = eRCInput.getInstance().getKeyboardMode()
984 eRCInput.getInstance().setKeyboardMode(eRCInput.kmAscii)
985 if session is not None:
986 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
987 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
988 self.help_window.show()
990 def onDeselect(self, session):
991 eRCInput.getInstance().setKeyboardMode(self._keyboardMode)
995 session.deleteDialog(self.help_window)
996 self.help_window = None
997 ConfigElement.onDeselect(self, session)
999 def getHTML(self, id):
1000 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
1002 def unsafeAssign(self, value):
1003 self.value = str(value)
1005 class ConfigPassword(ConfigText):
1006 def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
1007 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1008 self.censor_char = censor
1011 def getMulti(self, selected):
1012 mtext, text, mark = ConfigText.getMulti(self, selected)
1014 text = len(text) * self.censor_char
1015 return (mtext, text, mark)
1017 def onSelect(self, session):
1018 ConfigText.onSelect(self, session)
1021 def onDeselect(self, session):
1022 ConfigText.onDeselect(self, session)
1025 # lets the user select between [min, min+stepwidth, min+(stepwidth*2)..., maxval] with maxval <= max depending
1027 # min, max, stepwidth, default are int values
1028 # wraparound: pressing RIGHT key at max value brings you to min value and vice versa if set to True
1029 class ConfigSelectionNumber(ConfigSelection):
1030 def __init__(self, min, max, stepwidth, default = None, wraparound = False):
1031 self.wraparound = wraparound
1034 default = str(default)
1038 choices.append(str(step))
1041 ConfigSelection.__init__(self, choices, default)
1044 return int(ConfigSelection.getValue(self))
1046 def setValue(self, val):
1047 ConfigSelection.setValue(self, str(val))
1049 def handleKey(self, key):
1050 if not self.wraparound:
1051 if key == KEY_RIGHT:
1052 if len(self.choices) == (self.choices.index(self.value) + 1):
1055 if self.choices.index(self.value) == 0:
1057 ConfigSelection.handleKey(self, key)
1059 class ConfigNumber(ConfigText):
1060 def __init__(self, default = 0):
1061 ConfigText.__init__(self, str(default), fixed_size = False)
1064 return int(self.text)
1066 def setValue(self, val):
1067 self.text = str(val)
1070 value = property(getValue, setValue)
1071 _value = property(getValue, setValue)
1073 def isChanged(self):
1074 sv = self.saved_value
1075 strv = self.tostring(self.value)
1076 if sv is None and strv == self.default:
1081 pos = len(self.text) - self.marked_pos
1082 self.text = self.text.lstrip("0")
1085 if pos > len(self.text):
1088 self.marked_pos = len(self.text) - pos
1090 def handleKey(self, key):
1091 if key in KEY_NUMBERS or key == KEY_ASCII:
1092 if key == KEY_ASCII:
1093 ascii = getPrevAsciiCode()
1094 if not (48 <= ascii <= 57):
1097 ascii = getKeyNumber(key) + 48
1098 newChar = unichr(ascii)
1100 self.deleteAllChars()
1101 self.allmarked = False
1102 self.insertChar(newChar, self.marked_pos, False)
1103 self.marked_pos += 1
1105 ConfigText.handleKey(self, key)
1108 def onSelect(self, session):
1109 self.allmarked = (self.value != "")
1110 self._keyboardMode = eRCInput.getInstance().getKeyboardMode()
1112 class ConfigSearchText(ConfigText):
1113 def __init__(self, default = "", fixed_size = False, visible_width = False):
1114 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1115 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = True)
1117 class ConfigDirectory(ConfigText):
1118 def __init__(self, default="", visible_width=60):
1119 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
1121 def handleKey(self, key):
1128 return ConfigText.getValue(self)
1130 def setValue(self, val):
1133 ConfigText.setValue(self, val)
1135 def getMulti(self, selected):
1137 return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
1139 return ConfigText.getMulti(self, selected)
1141 def onSelect(self, session):
1142 self.allmarked = (self.value != "")
1143 self._keyboardMode = eRCInput.getInstance().getKeyboardMode()
1146 class ConfigSlider(ConfigElement):
1147 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
1148 ConfigElement.__init__(self)
1149 self.value = self.default = default
1150 self.min = limits[0]
1151 self.max = limits[1]
1152 self.increment = increment
1154 def checkValues(self):
1155 if self.value < self.min:
1156 self.value = self.min
1158 if self.value > self.max:
1159 self.value = self.max
1161 def handleKey(self, key):
1163 self.value -= self.increment
1164 elif key == KEY_RIGHT:
1165 self.value += self.increment
1166 elif key == KEY_HOME:
1167 self.value = self.min
1168 elif key == KEY_END:
1169 self.value = self.max
1175 return "%d / %d" % (self.value, self.max)
1177 def getMulti(self, selected):
1179 return ("slider", self.value, self.max)
1181 def fromstring(self, value):
1184 # a satlist. in fact, it's a ConfigSelection.
1185 class ConfigSatlist(ConfigSelection):
1186 def __init__(self, list, default = None):
1187 if default is not None:
1188 default = str(default)
1189 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1191 def getOrbitalPosition(self):
1192 if self.value == "":
1194 return int(self.value)
1196 orbital_position = property(getOrbitalPosition)
1198 class ConfigSet(ConfigElement):
1199 def __init__(self, choices, default = []):
1200 ConfigElement.__init__(self)
1201 if isinstance(choices, list):
1203 self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
1205 assert False, "ConfigSet choices must be a list!"
1210 self.default = default
1211 self.value = default[:]
1213 def toggleChoice(self, choice):
1216 value.remove(choice)
1218 value.append(choice)
1222 def handleKey(self, key):
1223 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1225 self.toggleChoice(self.choices[self.pos])
1226 elif key == KEY_LEFT:
1228 self.pos = len(self.choices)-1
1231 elif key == KEY_RIGHT:
1232 if self.pos >= len(self.choices)-1:
1236 elif key in (KEY_HOME, KEY_END):
1239 def genString(self, lst):
1242 res += self.description[x]+" "
1246 return self.genString(self.value)
1248 def getMulti(self, selected):
1249 if not selected or self.pos == -1:
1250 return ("text", self.genString(self.value))
1253 ch = self.choices[self.pos]
1254 mem = ch in self.value
1259 val1 = self.genString(tmp[:ind])
1260 val2 = " "+self.genString(tmp[ind+1:])
1262 chstr = " "+self.description[ch]+" "
1264 chstr = "("+self.description[ch]+")"
1265 len_val1 = len(val1)
1266 return ("mtext", val1+chstr+val2, range(len_val1, len_val1 + len(chstr)))
1268 def onDeselect(self, session):
1270 ConfigElement.onDeselect(self, session)
1272 def tostring(self, value):
1275 def fromstring(self, val):
1278 description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
1280 class ConfigLocations(ConfigElement):
1281 def __init__(self, default = [], visible_width = False):
1282 ConfigElement.__init__(self)
1283 self.visible_width = visible_width
1285 self.default = default
1287 self.mountpoints = []
1288 self.value = default[:]
1290 def setValue(self, value):
1291 locations = self.locations
1292 loc = [x[0] for x in locations if x[3]]
1293 add = [x for x in value if not x in loc]
1294 diff = add + [x for x in loc if not x in value]
1295 locations = [x for x in locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1296 locations.sort(key = lambda x: x[0])
1297 self.locations = locations
1301 self.checkChangedMountpoints()
1302 locations = self.locations
1305 return [x[0] for x in locations if x[3]]
1307 value = property(getValue, setValue)
1309 def tostring(self, value):
1312 def fromstring(self, val):
1316 sv = self.saved_value
1320 tmp = self.fromstring(sv)
1321 locations = [[x, None, False, False] for x in tmp]
1322 self.refreshMountpoints()
1324 if fileExists(x[0]):
1325 x[1] = self.getMountpoint(x[0])
1327 self.locations = locations
1330 locations = self.locations
1331 if self.save_disabled or not locations:
1332 self.saved_value = None
1334 self.saved_value = self.tostring([x[0] for x in locations])
1336 def isChanged(self):
1337 sv = self.saved_value
1338 locations = self.locations
1339 if val is None and not locations:
1341 return self.tostring([x[0] for x in locations]) != sv
1343 def addedMount(self, mp):
1344 for x in self.locations:
1347 elif x[1] == None and fileExists(x[0]):
1348 x[1] = self.getMountpoint(x[0])
1351 def removedMount(self, mp):
1352 for x in self.locations:
1356 def refreshMountpoints(self):
1357 self.mountpoints = [p.mountpoint for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1358 self.mountpoints.sort(key = lambda x: -len(x))
1360 def checkChangedMountpoints(self):
1361 oldmounts = self.mountpoints
1362 self.refreshMountpoints()
1363 newmounts = self.mountpoints
1364 if oldmounts == newmounts:
1367 if not x in newmounts:
1368 self.removedMount(x)
1370 if not x in oldmounts:
1373 def getMountpoint(self, file):
1374 file = os_path.realpath(file)+"/"
1375 for m in self.mountpoints:
1376 if file.startswith(m):
1380 def handleKey(self, key):
1384 self.pos = len(self.value)-1
1385 elif key == KEY_RIGHT:
1387 if self.pos >= len(self.value):
1389 elif key in (KEY_HOME, KEY_END):
1393 return " ".join(self.value)
1395 def getMulti(self, selected):
1397 valstr = " ".join(self.value)
1398 if self.visible_width and len(valstr) > self.visible_width:
1399 return ("text", valstr[0:self.visible_width])
1401 return ("text", valstr)
1407 for val in self.value:
1410 valstr += str(val)+" "
1414 if self.visible_width and len(valstr) > self.visible_width:
1415 if ind1+1 < self.visible_width/2:
1418 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1419 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1421 return ("mtext", valstr, range(ind1,ind2))
1423 def onDeselect(self, session):
1425 ConfigElement.onDeselect(self, session)
1428 class ConfigNothing(ConfigSelection):
1430 ConfigSelection.__init__(self, choices = [("","")])
1432 # until here, 'saved_value' always had to be a *string*.
1433 # now, in ConfigSubsection, and only there, saved_value
1434 # is a dict, essentially forming a tree.
1436 # config.foo.bar=True
1437 # config.foobar=False
1440 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1443 class ConfigSubsectionContent(object):
1446 # we store a backup of the loaded configuration
1447 # data in self.stored_values, to be able to deploy
1448 # them when a new config element will be added,
1449 # so non-default values are instantly available
1451 # A list, for example:
1452 # config.dipswitches = ConfigSubList()
1453 # config.dipswitches.append(ConfigYesNo())
1454 # config.dipswitches.append(ConfigYesNo())
1455 # config.dipswitches.append(ConfigYesNo())
1456 class ConfigSubList(list, object):
1459 self.stored_values = {}
1469 def getSavedValue(self):
1471 for i, val in enumerate(self):
1472 sv = val.saved_value
1477 def setSavedValue(self, values):
1478 self.stored_values = dict(values)
1479 for (key, val) in self.stored_values.items():
1480 if int(key) < len(self):
1481 self[int(key)].saved_value = val
1483 saved_value = property(getSavedValue, setSavedValue)
1485 def append(self, item):
1487 list.append(self, item)
1488 if i in self.stored_values:
1489 item.saved_value = self.stored_values[i]
1493 return dict([(str(index), value) for index, value in enumerate(self)])
1495 # same as ConfigSubList, just as a dictionary.
1496 # care must be taken that the 'key' has a proper
1497 # str() method, because it will be used in the config
1499 class ConfigSubDict(dict, object):
1502 self.stored_values = {}
1505 for x in self.values():
1509 for x in self.values():
1512 def getSavedValue(self):
1514 for (key, val) in self.items():
1515 sv = val.saved_value
1520 def setSavedValue(self, values):
1521 self.stored_values = dict(values)
1522 for (key, val) in self.items():
1523 if str(key) in self.stored_values:
1524 val.saved_value = self.stored_values[str(key)]
1526 saved_value = property(getSavedValue, setSavedValue)
1528 def __setitem__(self, key, item):
1529 dict.__setitem__(self, key, item)
1530 if str(key) in self.stored_values:
1531 item.saved_value = self.stored_values[str(key)]
1537 # Like the classes above, just with a more "native"
1540 # some evil stuff must be done to allow instant
1541 # loading of added elements. this is why this class
1544 # we need the 'content' because we overwrite
1546 # If you don't understand this, try adding
1547 # __setattr__ to a usual exisiting class and you will.
1548 class ConfigSubsection(object):
1550 self.__dict__["content"] = ConfigSubsectionContent()
1551 self.content.items = { }
1552 self.content.stored_values = { }
1554 def __setattr__(self, name, value):
1555 if name == "saved_value":
1556 return self.setSavedValue(value)
1557 assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1558 content = self.content
1559 content.items[name] = value
1560 x = content.stored_values.get(name, None)
1562 #print "ok, now we have a new item,", name, "and have the following value for it:", x
1563 value.saved_value = x
1566 def __getattr__(self, name):
1567 return self.content.items[name]
1569 def getSavedValue(self):
1570 res = self.content.stored_values
1571 for (key, val) in self.content.items.items():
1572 sv = val.saved_value
1579 def setSavedValue(self, values, append = False):
1580 values = dict(values)
1583 self.content.stored_values.update(values)
1585 self.content.stored_values = values
1587 self.content.stored_values = values
1588 for (key, val) in self.content.items.items():
1589 value = values.get(key, None)
1590 if value is not None:
1591 val.saved_value = value
1593 saved_value = property(getSavedValue, setSavedValue)
1596 for x in self.content.items.values():
1600 for x in self.content.items.values():
1604 return self.content.items
1606 # the root config object, which also can "pickle" (=serialize)
1607 # down the whole config tree.
1609 # we try to keep non-existing config entries, to apply them whenever
1610 # a new config entry is added to a subsection
1611 # also, non-existing config entries will be saved, so they won't be
1612 # lost when a config entry disappears.
1613 class Config(ConfigSubsection):
1615 ConfigSubsection.__init__(self)
1617 def pickle_this(self, prefix, topickle, result):
1618 for (key, val) in topickle.items():
1619 name = '.'.join((prefix, key))
1620 if isinstance(val, dict):
1621 self.pickle_this(name, val, result)
1622 elif isinstance(val, tuple):
1623 result += [name, '=', val[0], '\n']
1625 result += [name, '=', val, '\n']
1629 self.pickle_this("config", self.saved_value, result)
1630 return ''.join(result)
1632 def unpickle(self, lines, base_file=True, append = False):
1635 if not l or l[0] == '#':
1640 val = l[n+1:].strip()
1642 names = name.split('.')
1643 # if val.find(' ') != -1:
1644 # val = val[:val.find(' ')]
1648 for n in names[:-1]:
1649 base = base.setdefault(n, {})
1651 base[names[-1]] = val
1653 if not base_file: # not the initial config file..
1654 #update config.x.y.value when exist
1656 configEntry = eval(name)
1657 if configEntry is not None:
1658 configEntry.value = val
1659 except (SyntaxError, KeyError):
1662 # we inherit from ConfigSubsection, so ...
1663 #object.__setattr__(self, "saved_value", tree["config"])
1664 if "config" in tree:
1665 self.setSavedValue(tree["config"], append)
1667 def saveToFile(self, filename):
1668 text = self.pickle()
1670 f = open(filename, "w")
1674 print "Config: Couldn't write %s" % filename
1676 def loadFromFile(self, filename, base_file=False, append = False):
1677 f = open(filename, "r")
1678 self.unpickle(f.readlines(), base_file, append)
1682 config.misc = ConfigSubsection()
1685 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1689 config.loadFromFile(self.CONFIG_FILE, True)
1691 print "unable to load config (%s), assuming defaults..." % str(e)
1695 config.saveToFile(self.CONFIG_FILE)
1697 def __resolveValue(self, pickles, cmap):
1699 if cmap.has_key(key):
1700 if len(pickles) > 1:
1701 return self.__resolveValue(pickles[1:], cmap[key].dict())
1703 return str(cmap[key].value)
1706 def getResolvedKey(self, key):
1707 names = key.split('.')
1709 if names[0] == "config":
1710 ret=self.__resolveValue(names[1:], config.content.items)
1711 if ret and len(ret):
1715 def NoSave(element):
1716 element.disableSave()
1719 configfile = ConfigFile()
1722 from Components.Harddisk import harddiskmanager
1724 def getConfigListEntry(*args):
1725 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1728 def updateConfigElement(element, newelement):
1729 newelement.value = element.value
1735 #config.bla = ConfigSubsection()
1736 #config.bla.test = ConfigYesNo()
1737 #config.nim = ConfigSubList()
1738 #config.nim.append(ConfigSubsection())
1739 #config.nim[0].bla = ConfigYesNo()
1740 #config.nim.append(ConfigSubsection())
1741 #config.nim[1].bla = ConfigYesNo()
1742 #config.nim[1].blub = ConfigYesNo()
1743 #config.arg = ConfigSubDict()
1744 #config.arg["Hello"] = ConfigYesNo()
1746 #config.arg["Hello"].handleKey(KEY_RIGHT)
1747 #config.arg["Hello"].handleKey(KEY_RIGHT)
1749 ##config.saved_value
1753 #print config.pickle()