1 from enigma import 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
826 def validateMarker(self):
827 textlen = len(self.text)
829 if self.marked_pos > textlen-1:
830 self.marked_pos = textlen-1
832 if self.marked_pos > textlen:
833 self.marked_pos = textlen
834 if self.marked_pos < 0:
836 if self.visible_width:
837 if self.marked_pos < self.offset:
838 self.offset = self.marked_pos
839 if self.marked_pos >= self.offset + self.visible_width:
840 if self.marked_pos == textlen:
841 self.offset = self.marked_pos - self.visible_width
843 self.offset = self.marked_pos - self.visible_width + 1
844 if self.offset > 0 and self.offset + self.visible_width > textlen:
845 self.offset = max(0, len - self.visible_width)
847 def insertChar(self, ch, pos, owr):
848 if owr or self.overwrite:
849 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
850 elif self.fixed_size:
851 self.text = self.text[0:pos] + ch + self.text[pos:-1]
853 self.text = self.text[0:pos] + ch + self.text[pos:]
855 def deleteChar(self, pos):
856 if not self.fixed_size:
857 self.text = self.text[0:pos] + self.text[pos + 1:]
859 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
861 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
863 def deleteAllChars(self):
865 self.text = " " * len(self.text)
870 def handleKey(self, key):
871 # this will no change anything on the value itself
872 # so we can handle it here in gui element
873 if key == KEY_DELETE:
876 self.deleteAllChars()
877 self.allmarked = False
879 self.deleteChar(self.marked_pos)
880 if self.fixed_size and self.overwrite:
882 elif key == KEY_BACKSPACE:
885 self.deleteAllChars()
886 self.allmarked = False
887 elif self.marked_pos > 0:
888 self.deleteChar(self.marked_pos-1)
889 if not self.fixed_size and self.offset > 0:
892 elif key == KEY_LEFT:
895 self.marked_pos = len(self.text)
896 self.allmarked = False
899 elif key == KEY_RIGHT:
903 self.allmarked = False
906 elif key == KEY_HOME:
908 self.allmarked = False
912 self.allmarked = False
913 self.marked_pos = len(self.text)
914 elif key == KEY_TOGGLEOW:
916 self.overwrite = not self.overwrite
917 elif key == KEY_ASCII:
919 newChar = unichr(getPrevAsciiCode())
920 if not self.useableChars or newChar in self.useableChars:
922 self.deleteAllChars()
923 self.allmarked = False
924 self.insertChar(newChar, self.marked_pos, False)
926 elif key in KEY_NUMBERS:
927 owr = self.lastKey == getKeyNumber(key)
928 newChar = self.getKey(getKeyNumber(key))
930 self.deleteAllChars()
931 self.allmarked = False
932 self.insertChar(newChar, self.marked_pos, owr)
933 elif key == KEY_TIMEOUT:
936 self.help_window.update(self)
940 self.help_window.update(self)
941 self.validateMarker()
946 self.validateMarker()
950 return self.text.encode("utf-8")
952 def setValue(self, val):
954 self.text = val.decode("utf-8")
955 except UnicodeDecodeError:
956 self.text = val.decode("utf-8", "ignore")
960 value = property(getValue, setValue)
961 _value = property(getValue, setValue)
964 return self.text.encode("utf-8")
966 def getMulti(self, selected):
967 if self.visible_width:
969 mark = range(0, min(self.visible_width, len(self.text)))
971 mark = [self.marked_pos-self.offset]
972 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
975 mark = range(0, len(self.text))
977 mark = [self.marked_pos]
978 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
980 def onSelect(self, session):
981 self.allmarked = (self.value != "")
982 if session is not None:
983 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
984 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
985 self.help_window.show()
987 def onDeselect(self, session):
991 session.deleteDialog(self.help_window)
992 self.help_window = None
993 ConfigElement.onDeselect(self, session)
995 def getHTML(self, id):
996 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
998 def unsafeAssign(self, value):
999 self.value = str(value)
1001 class ConfigPassword(ConfigText):
1002 def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
1003 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1004 self.censor_char = censor
1007 def getMulti(self, selected):
1008 mtext, text, mark = ConfigText.getMulti(self, selected)
1010 text = len(text) * self.censor_char
1011 return (mtext, text, mark)
1013 def onSelect(self, session):
1014 ConfigText.onSelect(self, session)
1017 def onDeselect(self, session):
1018 ConfigText.onDeselect(self, session)
1021 # lets the user select between [min, min+stepwidth, min+(stepwidth*2)..., maxval] with maxval <= max depending
1023 # min, max, stepwidth, default are int values
1024 # wraparound: pressing RIGHT key at max value brings you to min value and vice versa if set to True
1025 class ConfigSelectionNumber(ConfigSelection):
1026 def __init__(self, min, max, stepwidth, default = None, wraparound = False):
1027 self.wraparound = wraparound
1030 default = str(default)
1034 choices.append(str(step))
1037 ConfigSelection.__init__(self, choices, default)
1040 return int(ConfigSelection.getValue(self))
1042 def setValue(self, val):
1043 ConfigSelection.setValue(self, str(val))
1045 def handleKey(self, key):
1046 if not self.wraparound:
1047 if key == KEY_RIGHT:
1048 if len(self.choices) == (self.choices.index(self.value) + 1):
1051 if self.choices.index(self.value) == 0:
1053 ConfigSelection.handleKey(self, key)
1055 class ConfigNumber(ConfigText):
1056 def __init__(self, default = 0):
1057 ConfigText.__init__(self, str(default), fixed_size = False)
1060 return int(self.text)
1062 def setValue(self, val):
1063 self.text = str(val)
1066 value = property(getValue, setValue)
1067 _value = property(getValue, setValue)
1069 def isChanged(self):
1070 sv = self.saved_value
1071 strv = self.tostring(self.value)
1072 if sv is None and strv == self.default:
1077 pos = len(self.text) - self.marked_pos
1078 self.text = self.text.lstrip("0")
1081 if pos > len(self.text):
1084 self.marked_pos = len(self.text) - pos
1086 def handleKey(self, key):
1087 if key in KEY_NUMBERS or key == KEY_ASCII:
1088 if key == KEY_ASCII:
1089 ascii = getPrevAsciiCode()
1090 if not (48 <= ascii <= 57):
1093 ascii = getKeyNumber(key) + 48
1094 newChar = unichr(ascii)
1096 self.deleteAllChars()
1097 self.allmarked = False
1098 self.insertChar(newChar, self.marked_pos, False)
1099 self.marked_pos += 1
1101 ConfigText.handleKey(self, key)
1104 def onSelect(self, session):
1105 self.allmarked = (self.value != "")
1107 class ConfigSearchText(ConfigText):
1108 def __init__(self, default = "", fixed_size = False, visible_width = False):
1109 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1110 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = True)
1112 class ConfigDirectory(ConfigText):
1113 def __init__(self, default="", visible_width=60):
1114 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
1116 def handleKey(self, key):
1123 return ConfigText.getValue(self)
1125 def setValue(self, val):
1128 ConfigText.setValue(self, val)
1130 def getMulti(self, selected):
1132 return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
1134 return ConfigText.getMulti(self, selected)
1136 def onSelect(self, session):
1137 self.allmarked = (self.value != "")
1140 class ConfigSlider(ConfigElement):
1141 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
1142 ConfigElement.__init__(self)
1143 self.value = self.default = default
1144 self.min = limits[0]
1145 self.max = limits[1]
1146 self.increment = increment
1148 def checkValues(self):
1149 if self.value < self.min:
1150 self.value = self.min
1152 if self.value > self.max:
1153 self.value = self.max
1155 def handleKey(self, key):
1157 self.value -= self.increment
1158 elif key == KEY_RIGHT:
1159 self.value += self.increment
1160 elif key == KEY_HOME:
1161 self.value = self.min
1162 elif key == KEY_END:
1163 self.value = self.max
1169 return "%d / %d" % (self.value, self.max)
1171 def getMulti(self, selected):
1173 return ("slider", self.value, self.max)
1175 def fromstring(self, value):
1178 # a satlist. in fact, it's a ConfigSelection.
1179 class ConfigSatlist(ConfigSelection):
1180 def __init__(self, list, default = None):
1181 if default is not None:
1182 default = str(default)
1183 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1185 def getOrbitalPosition(self):
1186 if self.value == "":
1188 return int(self.value)
1190 orbital_position = property(getOrbitalPosition)
1192 class ConfigSet(ConfigElement):
1193 def __init__(self, choices, default = []):
1194 ConfigElement.__init__(self)
1195 if isinstance(choices, list):
1197 self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
1199 assert False, "ConfigSet choices must be a list!"
1204 self.default = default
1205 self.value = default[:]
1207 def toggleChoice(self, choice):
1210 value.remove(choice)
1212 value.append(choice)
1216 def handleKey(self, key):
1217 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1219 self.toggleChoice(self.choices[self.pos])
1220 elif key == KEY_LEFT:
1222 self.pos = len(self.choices)-1
1225 elif key == KEY_RIGHT:
1226 if self.pos >= len(self.choices)-1:
1230 elif key in (KEY_HOME, KEY_END):
1233 def genString(self, lst):
1236 res += self.description[x]+" "
1240 return self.genString(self.value)
1242 def getMulti(self, selected):
1243 if not selected or self.pos == -1:
1244 return ("text", self.genString(self.value))
1247 ch = self.choices[self.pos]
1248 mem = ch in self.value
1253 val1 = self.genString(tmp[:ind])
1254 val2 = " "+self.genString(tmp[ind+1:])
1256 chstr = " "+self.description[ch]+" "
1258 chstr = "("+self.description[ch]+")"
1259 len_val1 = len(val1)
1260 return ("mtext", val1+chstr+val2, range(len_val1, len_val1 + len(chstr)))
1262 def onDeselect(self, session):
1264 ConfigElement.onDeselect(self, session)
1266 def tostring(self, value):
1269 def fromstring(self, val):
1272 description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
1274 class ConfigLocations(ConfigElement):
1275 def __init__(self, default = [], visible_width = False):
1276 ConfigElement.__init__(self)
1277 self.visible_width = visible_width
1279 self.default = default
1281 self.mountpoints = []
1282 self.value = default[:]
1284 def setValue(self, value):
1285 locations = self.locations
1286 loc = [x[0] for x in locations if x[3]]
1287 add = [x for x in value if not x in loc]
1288 diff = add + [x for x in loc if not x in value]
1289 locations = [x for x in locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1290 locations.sort(key = lambda x: x[0])
1291 self.locations = locations
1295 self.checkChangedMountpoints()
1296 locations = self.locations
1299 return [x[0] for x in locations if x[3]]
1301 value = property(getValue, setValue)
1303 def tostring(self, value):
1306 def fromstring(self, val):
1310 sv = self.saved_value
1314 tmp = self.fromstring(sv)
1315 locations = [[x, None, False, False] for x in tmp]
1316 self.refreshMountpoints()
1318 if fileExists(x[0]):
1319 x[1] = self.getMountpoint(x[0])
1321 self.locations = locations
1324 locations = self.locations
1325 if self.save_disabled or not locations:
1326 self.saved_value = None
1328 self.saved_value = self.tostring([x[0] for x in locations])
1330 def isChanged(self):
1331 sv = self.saved_value
1332 locations = self.locations
1333 if val is None and not locations:
1335 return self.tostring([x[0] for x in locations]) != sv
1337 def addedMount(self, mp):
1338 for x in self.locations:
1341 elif x[1] == None and fileExists(x[0]):
1342 x[1] = self.getMountpoint(x[0])
1345 def removedMount(self, mp):
1346 for x in self.locations:
1350 def refreshMountpoints(self):
1351 self.mountpoints = [p.mountpoint for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1352 self.mountpoints.sort(key = lambda x: -len(x))
1354 def checkChangedMountpoints(self):
1355 oldmounts = self.mountpoints
1356 self.refreshMountpoints()
1357 newmounts = self.mountpoints
1358 if oldmounts == newmounts:
1361 if not x in newmounts:
1362 self.removedMount(x)
1364 if not x in oldmounts:
1367 def getMountpoint(self, file):
1368 file = os_path.realpath(file)+"/"
1369 for m in self.mountpoints:
1370 if file.startswith(m):
1374 def handleKey(self, key):
1378 self.pos = len(self.value)-1
1379 elif key == KEY_RIGHT:
1381 if self.pos >= len(self.value):
1383 elif key in (KEY_HOME, KEY_END):
1387 return " ".join(self.value)
1389 def getMulti(self, selected):
1391 valstr = " ".join(self.value)
1392 if self.visible_width and len(valstr) > self.visible_width:
1393 return ("text", valstr[0:self.visible_width])
1395 return ("text", valstr)
1401 for val in self.value:
1404 valstr += str(val)+" "
1408 if self.visible_width and len(valstr) > self.visible_width:
1409 if ind1+1 < self.visible_width/2:
1412 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1413 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1415 return ("mtext", valstr, range(ind1,ind2))
1417 def onDeselect(self, session):
1419 ConfigElement.onDeselect(self, session)
1422 class ConfigNothing(ConfigSelection):
1424 ConfigSelection.__init__(self, choices = [("","")])
1426 # until here, 'saved_value' always had to be a *string*.
1427 # now, in ConfigSubsection, and only there, saved_value
1428 # is a dict, essentially forming a tree.
1430 # config.foo.bar=True
1431 # config.foobar=False
1434 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1437 class ConfigSubsectionContent(object):
1440 # we store a backup of the loaded configuration
1441 # data in self.stored_values, to be able to deploy
1442 # them when a new config element will be added,
1443 # so non-default values are instantly available
1445 # A list, for example:
1446 # config.dipswitches = ConfigSubList()
1447 # config.dipswitches.append(ConfigYesNo())
1448 # config.dipswitches.append(ConfigYesNo())
1449 # config.dipswitches.append(ConfigYesNo())
1450 class ConfigSubList(list, object):
1453 self.stored_values = {}
1463 def getSavedValue(self):
1465 for i, val in enumerate(self):
1466 sv = val.saved_value
1471 def setSavedValue(self, values):
1472 self.stored_values = dict(values)
1473 for (key, val) in self.stored_values.items():
1474 if int(key) < len(self):
1475 self[int(key)].saved_value = val
1477 saved_value = property(getSavedValue, setSavedValue)
1479 def append(self, item):
1481 list.append(self, item)
1482 if i in self.stored_values:
1483 item.saved_value = self.stored_values[i]
1487 return dict([(str(index), value) for index, value in enumerate(self)])
1489 # same as ConfigSubList, just as a dictionary.
1490 # care must be taken that the 'key' has a proper
1491 # str() method, because it will be used in the config
1493 class ConfigSubDict(dict, object):
1496 self.stored_values = {}
1499 for x in self.values():
1503 for x in self.values():
1506 def getSavedValue(self):
1508 for (key, val) in self.items():
1509 sv = val.saved_value
1514 def setSavedValue(self, values):
1515 self.stored_values = dict(values)
1516 for (key, val) in self.items():
1517 if str(key) in self.stored_values:
1518 val.saved_value = self.stored_values[str(key)]
1520 saved_value = property(getSavedValue, setSavedValue)
1522 def __setitem__(self, key, item):
1523 dict.__setitem__(self, key, item)
1524 if str(key) in self.stored_values:
1525 item.saved_value = self.stored_values[str(key)]
1531 # Like the classes above, just with a more "native"
1534 # some evil stuff must be done to allow instant
1535 # loading of added elements. this is why this class
1538 # we need the 'content' because we overwrite
1540 # If you don't understand this, try adding
1541 # __setattr__ to a usual exisiting class and you will.
1542 class ConfigSubsection(object):
1544 self.__dict__["content"] = ConfigSubsectionContent()
1545 self.content.items = { }
1546 self.content.stored_values = { }
1548 def __setattr__(self, name, value):
1549 if name == "saved_value":
1550 return self.setSavedValue(value)
1551 assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1552 content = self.content
1553 content.items[name] = value
1554 x = content.stored_values.get(name, None)
1556 #print "ok, now we have a new item,", name, "and have the following value for it:", x
1557 value.saved_value = x
1560 def __getattr__(self, name):
1561 return self.content.items[name]
1563 def getSavedValue(self):
1564 res = self.content.stored_values
1565 for (key, val) in self.content.items.items():
1566 sv = val.saved_value
1573 def setSavedValue(self, values):
1574 values = dict(values)
1575 self.content.stored_values = values
1576 for (key, val) in self.content.items.items():
1577 value = values.get(key, None)
1578 if value is not None:
1579 val.saved_value = value
1581 saved_value = property(getSavedValue, setSavedValue)
1584 for x in self.content.items.values():
1588 for x in self.content.items.values():
1592 return self.content.items
1594 # the root config object, which also can "pickle" (=serialize)
1595 # down the whole config tree.
1597 # we try to keep non-existing config entries, to apply them whenever
1598 # a new config entry is added to a subsection
1599 # also, non-existing config entries will be saved, so they won't be
1600 # lost when a config entry disappears.
1601 class Config(ConfigSubsection):
1603 ConfigSubsection.__init__(self)
1605 def pickle_this(self, prefix, topickle, result):
1606 for (key, val) in topickle.items():
1607 name = '.'.join((prefix, key))
1608 if isinstance(val, dict):
1609 self.pickle_this(name, val, result)
1610 elif isinstance(val, tuple):
1611 result += [name, '=', val[0], '\n']
1613 result += [name, '=', val, '\n']
1617 self.pickle_this("config", self.saved_value, result)
1618 return ''.join(result)
1620 def unpickle(self, lines, base_file=True):
1623 if not l or l[0] == '#':
1628 val = l[n+1:].strip()
1630 names = name.split('.')
1631 # if val.find(' ') != -1:
1632 # val = val[:val.find(' ')]
1636 for n in names[:-1]:
1637 base = base.setdefault(n, {})
1639 base[names[-1]] = val
1641 if not base_file: # not the initial config file..
1642 #update config.x.y.value when exist
1644 configEntry = eval(name)
1645 if configEntry is not None:
1646 configEntry.value = val
1647 except (SyntaxError, KeyError):
1650 # we inherit from ConfigSubsection, so ...
1651 #object.__setattr__(self, "saved_value", tree["config"])
1652 if "config" in tree:
1653 self.setSavedValue(tree["config"])
1655 def saveToFile(self, filename):
1656 text = self.pickle()
1658 f = open(filename, "w")
1662 print "Config: Couldn't write %s" % filename
1664 def loadFromFile(self, filename, base_file=False):
1665 f = open(filename, "r")
1666 self.unpickle(f.readlines(), base_file)
1670 config.misc = ConfigSubsection()
1673 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1677 config.loadFromFile(self.CONFIG_FILE, True)
1679 print "unable to load config (%s), assuming defaults..." % str(e)
1683 config.saveToFile(self.CONFIG_FILE)
1685 def __resolveValue(self, pickles, cmap):
1687 if cmap.has_key(key):
1688 if len(pickles) > 1:
1689 return self.__resolveValue(pickles[1:], cmap[key].dict())
1691 return str(cmap[key].value)
1694 def getResolvedKey(self, key):
1695 names = key.split('.')
1697 if names[0] == "config":
1698 ret=self.__resolveValue(names[1:], config.content.items)
1699 if ret and len(ret):
1701 print "getResolvedKey", key, "failed !! (Typo??)"
1704 def NoSave(element):
1705 element.disableSave()
1708 configfile = ConfigFile()
1711 from Components.Harddisk import harddiskmanager
1713 def getConfigListEntry(*args):
1714 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1717 def updateConfigElement(element, newelement):
1718 newelement.value = element.value
1724 #config.bla = ConfigSubsection()
1725 #config.bla.test = ConfigYesNo()
1726 #config.nim = ConfigSubList()
1727 #config.nim.append(ConfigSubsection())
1728 #config.nim[0].bla = ConfigYesNo()
1729 #config.nim.append(ConfigSubsection())
1730 #config.nim[1].bla = ConfigYesNo()
1731 #config.nim[1].blub = ConfigYesNo()
1732 #config.arg = ConfigSubDict()
1733 #config.arg["Hello"] = ConfigYesNo()
1735 #config.arg["Hello"].handleKey(KEY_RIGHT)
1736 #config.arg["Hello"].handleKey(KEY_RIGHT)
1738 ##config.saved_value
1742 #print config.pickle()