1 from enigma import getPrevAsciiCode
2 from Tools.NumericalTextInput import NumericalTextInput
3 from Tools.Directories import resolveFilename, SCOPE_CONFIG, fileExists
4 from Components.Harddisk import harddiskmanager
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.last_value = None
33 self.save_disabled = False
34 self.__notifiers = None
35 self.__notifiers_final = None
37 self.callNotifiersOnSaveAndCancel = False
39 def getNotifiers(self):
40 if self.__notifiers is None:
41 self.__notifiers = [ ]
42 return self.__notifiers
44 def setNotifiers(self, val):
45 self.__notifiers = val
47 notifiers = property(getNotifiers, setNotifiers)
49 def getNotifiersFinal(self):
50 if self.__notifiers_final is None:
51 self.__notifiers_final = [ ]
52 return self.__notifiers_final
54 def setNotifiersFinal(self, val):
55 self.__notifiers_final = val
57 notifiers_final = property(getNotifiersFinal, setNotifiersFinal)
59 # you need to override this to do input validation
60 def setValue(self, value):
67 value = property(getValue, setValue)
69 # you need to override this if self.value is not a string
70 def fromstring(self, value):
73 # you can overide this for fancy default handling
77 self.value = self.default
79 self.value = self.fromstring(sv)
81 def tostring(self, value):
84 # you need to override this if str(self.value) doesn't work
86 if self.save_disabled or self.value == self.default:
87 self.saved_value = None
89 self.saved_value = self.tostring(self.value)
90 if self.callNotifiersOnSaveAndCancel:
95 if self.callNotifiersOnSaveAndCancel:
100 if sv is None and self.value == self.default:
102 return self.tostring(self.value) != sv
106 for x in self.notifiers:
109 def changedFinal(self):
110 if self.__notifiers_final:
111 for x in self.notifiers_final:
114 def addNotifier(self, notifier, initial_call = True, immediate_feedback = True):
115 assert callable(notifier), "notifiers must be callable"
116 if immediate_feedback:
117 self.notifiers.append(notifier)
119 self.notifiers_final.append(notifier)
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 disableSave(self):
132 self.save_disabled = True
134 def __call__(self, selected):
135 return self.getMulti(selected)
137 def onSelect(self, session):
140 def onDeselect(self, session):
141 if not self.last_value == self.value:
143 self.last_value = self.value
155 KEY_NUMBERS = range(12, 12+10)
159 def getKeyNumber(key):
160 assert key in KEY_NUMBERS
163 class choicesList(object): # XXX: we might want a better name for this
167 def __init__(self, choices, type = None):
168 self.choices = choices
170 if isinstance(choices, list):
171 self.type = choicesList.LIST_TYPE_LIST
172 elif isinstance(choices, dict):
173 self.type = choicesList.LIST_TYPE_DICT
175 assert False, "choices must be dict or list!"
180 if self.type == choicesList.LIST_TYPE_LIST:
181 ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
183 ret = self.choices.keys()
187 if self.type == choicesList.LIST_TYPE_LIST:
188 ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
191 return iter(ret or [""])
194 return len(self.choices) or 1
196 def __getitem__(self, index):
197 if self.type == choicesList.LIST_TYPE_LIST:
198 ret = self.choices[index]
199 if isinstance(ret, tuple):
202 return self.choices.keys()[index]
204 def index(self, value):
205 return self.__list__().index(value)
207 def __setitem__(self, index, value):
208 if self.type == choicesList.LIST_TYPE_LIST:
209 orig = self.choices[index]
210 if isinstance(orig, tuple):
211 self.choices[index] = (value, orig[1])
213 self.choices[index] = value
215 key = self.choices.keys()[index]
216 orig = self.choices[key]
217 del self.choices[key]
218 self.choices[value] = orig
221 choices = self.choices
224 if self.type is choicesList.LIST_TYPE_LIST:
226 if isinstance(default, tuple):
229 default = choices.keys()[0]
232 class descriptionList(choicesList): # XXX: we might want a better name for this
234 if self.type == choicesList.LIST_TYPE_LIST:
235 ret = [not isinstance(x, tuple) and x or x[1] for x in self.choices]
237 ret = self.choices.values()
241 return iter(self.__list__())
243 def __getitem__(self, index):
244 if self.type == choicesList.LIST_TYPE_LIST:
245 for x in self.choices:
246 if isinstance(x, tuple):
251 return str(index) # Fallback!
253 return str(self.choices.get(index, ""))
255 def __setitem__(self, index, value):
256 if self.type == choicesList.LIST_TYPE_LIST:
257 i = self.index(index)
258 orig = self.choices[i]
259 if isinstance(orig, tuple):
260 self.choices[i] = (orig[0], value)
262 self.choices[i] = value
264 self.choices[index] = value
267 # ConfigSelection is a "one of.."-type.
268 # it has the "choices", usually a list, which contains
269 # (id, desc)-tuples (or just only the ids, in case the id
270 # will be used as description)
272 # all ids MUST be plain strings.
274 class ConfigSelection(ConfigElement):
275 def __init__(self, choices, default = None):
276 ConfigElement.__init__(self)
277 self.choices = choicesList(choices)
280 default = self.choices.default()
283 self.default = self._value = self.last_value = default
285 def setChoices(self, choices, default = None):
286 self.choices = choicesList(choices)
289 default = self.choices.default()
290 self.default = default
292 if self.value not in self.choices:
295 def setValue(self, value):
296 if value in self.choices:
299 self._value = self.default
303 def tostring(self, val):
309 def setCurrentText(self, text):
310 i = self.choices.index(self.value)
311 self.choices[i] = text
312 self._descr = self.description[text] = text
315 value = property(getValue, setValue)
318 return self.choices.index(self.value)
320 index = property(getIndex)
323 def handleKey(self, key):
324 nchoices = len(self.choices)
325 i = self.choices.index(self.value)
327 self.value = self.choices[(i + nchoices - 1) % nchoices]
328 elif key == KEY_RIGHT:
329 self.value = self.choices[(i + 1) % nchoices]
330 elif key == KEY_HOME:
331 self.value = self.choices[0]
333 self.value = self.choices[nchoices - 1]
335 def selectNext(self):
336 nchoices = len(self.choices)
337 i = self.choices.index(self.value)
338 self.value = self.choices[(i + 1) % nchoices]
341 if self._descr is not None:
343 descr = self._descr = self.description[self.value]
348 def getMulti(self, selected):
349 if self._descr is not None:
352 descr = self._descr = self.description[self.value]
354 return ("text", _(descr))
355 return ("text", descr)
358 def getHTML(self, id):
360 for v in self.choices:
361 descr = self.description[v]
363 checked = 'checked="checked" '
366 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + descr + "</input></br>\n"
369 def unsafeAssign(self, value):
370 # setValue does check if value is in choices. This is safe enough.
373 description = property(lambda self: descriptionList(self.choices.choices, self.choices.type))
377 # several customized versions exist for different
380 boolean_descriptions = {False: "false", True: "true"}
381 class ConfigBoolean(ConfigElement):
382 def __init__(self, default = False, descriptions = boolean_descriptions):
383 ConfigElement.__init__(self)
384 self.descriptions = descriptions
385 self.value = self.last_value = self.default = default
387 def handleKey(self, key):
388 if key in (KEY_LEFT, KEY_RIGHT):
389 self.value = not self.value
390 elif key == KEY_HOME:
396 descr = self.descriptions[self.value]
401 def getMulti(self, selected):
402 descr = self.descriptions[self.value]
404 return ("text", _(descr))
405 return ("text", descr)
407 def tostring(self, value):
413 def fromstring(self, val):
419 def getHTML(self, id):
421 checked = ' checked="checked"'
424 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
426 # this is FLAWED. and must be fixed.
427 def unsafeAssign(self, value):
433 def onDeselect(self, session):
434 if not self.last_value == self.value:
436 self.last_value = self.value
438 yes_no_descriptions = {False: _("no"), True: _("yes")}
439 class ConfigYesNo(ConfigBoolean):
440 def __init__(self, default = False):
441 ConfigBoolean.__init__(self, default = default, descriptions = yes_no_descriptions)
443 on_off_descriptions = {False: _("off"), True: _("on")}
444 class ConfigOnOff(ConfigBoolean):
445 def __init__(self, default = False):
446 ConfigBoolean.__init__(self, default = default, descriptions = on_off_descriptions)
448 enable_disable_descriptions = {False: _("disable"), True: _("enable")}
449 class ConfigEnableDisable(ConfigBoolean):
450 def __init__(self, default = False):
451 ConfigBoolean.__init__(self, default = default, descriptions = enable_disable_descriptions)
453 class ConfigDateTime(ConfigElement):
454 def __init__(self, default, formatstring, increment = 86400):
455 ConfigElement.__init__(self)
456 self.increment = increment
457 self.formatstring = formatstring
458 self.value = self.last_value = self.default = int(default)
460 def handleKey(self, key):
462 self.value = self.value - self.increment
463 elif key == KEY_RIGHT:
464 self.value = self.value + self.increment
465 elif key == KEY_HOME or key == KEY_END:
466 self.value = self.default
469 return strftime(self.formatstring, localtime(self.value))
471 def getMulti(self, selected):
472 return ("text", strftime(self.formatstring, localtime(self.value)))
474 def fromstring(self, val):
477 # *THE* mighty config element class
479 # allows you to store/edit a sequence of values.
480 # can be used for IP-addresses, dates, plain integers, ...
481 # several helper exist to ease this up a bit.
483 class ConfigSequence(ConfigElement):
484 def __init__(self, seperator, limits, default, censor_char = ""):
485 ConfigElement.__init__(self)
486 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
487 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
488 #assert isinstance(default, list), "default must be a list"
489 #assert isinstance(default[0], int), "list must contain numbers"
490 #assert len(default) == len(limits), "length must match"
493 self.seperator = seperator
495 self.censor_char = censor_char
497 self.last_value = self.default = default
498 self.value = copy_copy(default)
499 self.endNotifier = None
504 for i in self._value:
505 max_pos += len(str(self.limits[num][1]))
507 if self._value[num] < self.limits[num][0]:
508 self._value[num] = self.limits[num][0]
510 if self._value[num] > self.limits[num][1]:
511 self._value[num] = self.limits[num][1]
515 if self.marked_pos >= max_pos:
517 for x in self.endNotifier:
519 self.marked_pos = max_pos - 1
521 if self.marked_pos < 0:
524 def validatePos(self):
525 if self.marked_pos < 0:
528 total_len = sum([len(str(x[1])) for x in self.limits])
530 if self.marked_pos >= total_len:
531 self.marked_pos = total_len - 1
533 def addEndNotifier(self, notifier):
534 if self.endNotifier is None:
535 self.endNotifier = []
536 self.endNotifier.append(notifier)
538 def handleKey(self, key):
543 elif key == KEY_RIGHT:
547 elif key == KEY_HOME:
554 for i in self._value:
555 max_pos += len(str(self.limits[num][1]))
557 self.marked_pos = max_pos - 1
560 elif key in KEY_NUMBERS or key == KEY_ASCII:
562 code = getPrevAsciiCode()
563 if code < 48 or code > 57:
567 number = getKeyNumber(key)
569 block_len = [len(str(x[1])) for x in self.limits]
570 total_len = sum(block_len)
574 block_len_total = [0, ]
576 pos += block_len[blocknumber]
577 block_len_total.append(pos)
578 if pos - 1 >= self.marked_pos:
583 # length of numberblock
584 number_len = len(str(self.limits[blocknumber][1]))
586 # position in the block
587 posinblock = self.marked_pos - block_len_total[blocknumber]
589 oldvalue = self._value[blocknumber]
590 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
591 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
593 self._value[blocknumber] = newvalue
601 mPos = self.marked_pos
603 for i in self._value:
604 if value: #fixme no heading separator possible
605 value += self.seperator
606 if mPos >= len(value) - 1:
608 if self.censor_char == "":
609 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
611 value += (self.censor_char * len(str(self.limits[num][1])))
616 (value, mPos) = self.genText()
619 def getMulti(self, selected):
620 (value, mPos) = self.genText()
621 # only mark cursor when we are selected
622 # (this code is heavily ink optimized!)
624 return ("mtext"[1-selected:], value, [mPos])
626 return ("text", value)
628 def tostring(self, val):
629 return self.seperator.join([self.saveSingle(x) for x in val])
631 def saveSingle(self, v):
634 def fromstring(self, value):
635 return [int(x) for x in value.split(self.seperator)]
637 def onDeselect(self, session):
638 if self.last_value != self._value:
640 self.last_value = copy_copy(self._value)
642 ip_limits = [(0,255),(0,255),(0,255),(0,255)]
643 class ConfigIP(ConfigSequence):
644 def __init__(self, default, auto_jump = False):
645 ConfigSequence.__init__(self, seperator = ".", limits = ip_limits, default = default)
646 self.block_len = [len(str(x[1])) for x in self.limits]
647 self.marked_block = 0
648 self.overwrite = True
649 self.auto_jump = auto_jump
651 def handleKey(self, key):
653 if self.marked_block > 0:
654 self.marked_block -= 1
655 self.overwrite = True
657 elif key == KEY_RIGHT:
658 if self.marked_block < len(self.limits)-1:
659 self.marked_block += 1
660 self.overwrite = True
662 elif key == KEY_HOME:
663 self.marked_block = 0
664 self.overwrite = True
667 self.marked_block = len(self.limits)-1
668 self.overwrite = True
670 elif key in KEY_NUMBERS or key == KEY_ASCII:
672 code = getPrevAsciiCode()
673 if code < 48 or code > 57:
677 number = getKeyNumber(key)
678 oldvalue = self._value[self.marked_block]
681 self._value[self.marked_block] = number
682 self.overwrite = False
685 newvalue = oldvalue + number
686 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
687 self.handleKey(KEY_RIGHT)
691 self._value[self.marked_block] = newvalue
693 if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
694 self.handleKey(KEY_RIGHT)
702 for i in self._value:
703 block_strlen.append(len(str(i)))
705 value += self.seperator
707 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
708 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
709 mBlock = range(leftPos, rightPos)
710 return (value, mBlock)
712 def getMulti(self, selected):
713 (value, mBlock) = self.genText()
715 return ("mtext"[1-selected:], value, mBlock)
717 return ("text", value)
719 def getHTML(self, id):
720 # we definitely don't want leading zeros
721 return '.'.join(["%d" % d for d in self.value])
723 mac_limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)]
724 class ConfigMAC(ConfigSequence):
725 def __init__(self, default):
726 ConfigSequence.__init__(self, seperator = ":", limits = mac_limits, default = default)
728 class ConfigPosition(ConfigSequence):
729 def __init__(self, default, args):
730 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
732 clock_limits = [(0,23),(0,59)]
733 class ConfigClock(ConfigSequence):
734 def __init__(self, default):
735 t = localtime(default)
736 ConfigSequence.__init__(self, seperator = ":", limits = clock_limits, default = [t.tm_hour, t.tm_min])
739 # Check if Minutes maxed out
740 if self._value[1] == 59:
741 # Increment Hour, reset Minutes
742 if self._value[0] < 23:
754 # Check if Minutes is minimum
755 if self._value[1] == 0:
756 # Decrement Hour, set Minutes to 59
757 if self._value[0] > 0:
768 integer_limits = (0, 9999999999)
769 class ConfigInteger(ConfigSequence):
770 def __init__(self, default, limits = integer_limits):
771 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
773 # you need to override this to do input validation
774 def setValue(self, value):
775 self._value = [value]
779 return self._value[0]
781 value = property(getValue, setValue)
783 def fromstring(self, value):
786 def tostring(self, value):
789 class ConfigPIN(ConfigInteger):
790 def __init__(self, default, len = 4, censor = ""):
791 assert isinstance(default, int), "ConfigPIN default must be an integer"
794 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
800 class ConfigFloat(ConfigSequence):
801 def __init__(self, default, limits):
802 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
805 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
807 float = property(getFloat)
809 # an editable text...
810 class ConfigText(ConfigElement, NumericalTextInput):
811 def __init__(self, default = "", fixed_size = True, visible_width = False):
812 ConfigElement.__init__(self)
813 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
816 self.allmarked = (default != "")
817 self.fixed_size = fixed_size
818 self.visible_width = visible_width
820 self.overwrite = fixed_size
821 self.help_window = None
822 self.value = self.last_value = self.default = default
824 def validateMarker(self):
825 textlen = len(self.text)
827 if self.marked_pos > textlen-1:
828 self.marked_pos = textlen-1
830 if self.marked_pos > textlen:
831 self.marked_pos = textlen
832 if self.marked_pos < 0:
834 if self.visible_width:
835 if self.marked_pos < self.offset:
836 self.offset = self.marked_pos
837 if self.marked_pos >= self.offset + self.visible_width:
838 if self.marked_pos == textlen:
839 self.offset = self.marked_pos - self.visible_width
841 self.offset = self.marked_pos - self.visible_width + 1
842 if self.offset > 0 and self.offset + self.visible_width > textlen:
843 self.offset = max(0, len - self.visible_width)
845 def insertChar(self, ch, pos, owr):
846 if owr or self.overwrite:
847 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
848 elif self.fixed_size:
849 self.text = self.text[0:pos] + ch + self.text[pos:-1]
851 self.text = self.text[0:pos] + ch + self.text[pos:]
853 def deleteChar(self, pos):
854 if not self.fixed_size:
855 self.text = self.text[0:pos] + self.text[pos + 1:]
857 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
859 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
861 def deleteAllChars(self):
863 self.text = " " * len(self.text)
868 def handleKey(self, key):
869 # this will no change anything on the value itself
870 # so we can handle it here in gui element
871 if key == KEY_DELETE:
874 self.deleteAllChars()
875 self.allmarked = False
877 self.deleteChar(self.marked_pos)
878 if self.fixed_size and self.overwrite:
880 elif key == KEY_BACKSPACE:
883 self.deleteAllChars()
884 self.allmarked = False
885 elif self.marked_pos > 0:
886 self.deleteChar(self.marked_pos-1)
887 if not self.fixed_size and self.offset > 0:
890 elif key == KEY_LEFT:
893 self.marked_pos = len(self.text)
894 self.allmarked = False
897 elif key == KEY_RIGHT:
901 self.allmarked = False
904 elif key == KEY_HOME:
906 self.allmarked = False
910 self.allmarked = False
911 self.marked_pos = len(self.text)
912 elif key == KEY_TOGGLEOW:
914 self.overwrite = not self.overwrite
915 elif key == KEY_ASCII:
917 newChar = unichr(getPrevAsciiCode())
918 if not self.useableChars or newChar in self.useableChars:
920 self.deleteAllChars()
921 self.allmarked = False
922 self.insertChar(newChar, self.marked_pos, False)
924 elif key in KEY_NUMBERS:
925 owr = self.lastKey == getKeyNumber(key)
926 newChar = self.getKey(getKeyNumber(key))
928 self.deleteAllChars()
929 self.allmarked = False
930 self.insertChar(newChar, self.marked_pos, owr)
931 elif key == KEY_TIMEOUT:
934 self.help_window.update(self)
938 self.help_window.update(self)
939 self.validateMarker()
944 self.validateMarker()
948 return self.text.encode("utf-8")
950 def setValue(self, val):
952 self.text = val.decode("utf-8")
953 except UnicodeDecodeError:
954 self.text = val.decode("utf-8", "ignore")
957 value = property(getValue, setValue)
958 _value = property(getValue, setValue)
961 return self.text.encode("utf-8")
963 def getMulti(self, selected):
964 if self.visible_width:
966 mark = range(0, min(self.visible_width, len(self.text)))
968 mark = [self.marked_pos-self.offset]
969 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
972 mark = range(0, len(self.text))
974 mark = [self.marked_pos]
975 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
977 def onSelect(self, session):
978 self.allmarked = (self.value != "")
979 if session is not None:
980 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
981 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
982 self.help_window.show()
984 def onDeselect(self, session):
988 session.deleteDialog(self.help_window)
989 self.help_window = None
990 if not self.last_value == self.value:
992 self.last_value = self.value
994 def getHTML(self, id):
995 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
997 def unsafeAssign(self, value):
998 self.value = str(value)
1000 class ConfigPassword(ConfigText):
1001 def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
1002 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1003 self.censor_char = censor
1006 def getMulti(self, selected):
1007 mtext, text, mark = ConfigText.getMulti(self, selected)
1009 text = len(text) * self.censor_char
1010 return (mtext, text, mark)
1012 def onSelect(self, session):
1013 ConfigText.onSelect(self, session)
1016 def onDeselect(self, session):
1017 ConfigText.onDeselect(self, session)
1020 # lets the user select between [min, min+stepwidth, min+(stepwidth*2)..., maxval] with maxval <= max depending
1022 # min, max, stepwidth, default are int values
1023 # wraparound: pressing RIGHT key at max value brings you to min value and vice versa if set to True
1024 class ConfigSelectionNumber(ConfigSelection):
1025 def __init__(self, min, max, stepwidth, default = None, wraparound = False):
1026 self.wraparound = wraparound
1029 default = str(default)
1033 choices.append(str(step))
1036 ConfigSelection.__init__(self, choices, default)
1039 return int(self.text)
1041 def setValue(self, val):
1042 self.text = str(val)
1044 def handleKey(self, key):
1045 if not self.wraparound:
1046 if key == KEY_RIGHT:
1047 if len(self.choices) == (self.choices.index(self.value) + 1):
1050 if self.choices.index(self.value) == 0:
1052 ConfigSelection.handleKey(self, key)
1056 class ConfigNumber(ConfigText):
1057 def __init__(self, default = 0):
1058 ConfigText.__init__(self, str(default), fixed_size = False)
1061 return int(self.text)
1063 def setValue(self, val):
1064 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 def onDeselect(self, session):
1110 if not self.last_value == self.value:
1112 self.last_value = self.value
1114 class ConfigSearchText(ConfigText):
1115 def __init__(self, default = "", fixed_size = False, visible_width = False):
1116 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1117 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = True)
1119 class ConfigDirectory(ConfigText):
1120 def __init__(self, default="", visible_width=60):
1121 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
1123 def handleKey(self, key):
1130 return ConfigText.getValue(self)
1132 def setValue(self, val):
1135 ConfigText.setValue(self, val)
1137 def getMulti(self, selected):
1139 return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
1141 return ConfigText.getMulti(self, selected)
1144 class ConfigSlider(ConfigElement):
1145 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
1146 ConfigElement.__init__(self)
1147 self.value = self.last_value = self.default = default
1148 self.min = limits[0]
1149 self.max = limits[1]
1150 self.increment = increment
1152 def checkValues(self):
1153 if self.value < self.min:
1154 self.value = self.min
1156 if self.value > self.max:
1157 self.value = self.max
1159 def handleKey(self, key):
1161 self.value -= self.increment
1162 elif key == KEY_RIGHT:
1163 self.value += self.increment
1164 elif key == KEY_HOME:
1165 self.value = self.min
1166 elif key == KEY_END:
1167 self.value = self.max
1173 return "%d / %d" % (self.value, self.max)
1175 def getMulti(self, selected):
1177 return ("slider", self.value, self.max)
1179 def fromstring(self, value):
1182 # a satlist. in fact, it's a ConfigSelection.
1183 class ConfigSatlist(ConfigSelection):
1184 def __init__(self, list, default = None):
1185 if default is not None:
1186 default = str(default)
1187 self._satList = list
1188 choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list]
1190 ConfigSelection.__init__(self, choices = choices, default = default)
1192 # use this function to get the orbital position, don't rely on .index
1193 def getOrbitalPosition(self):
1194 if self.value == "":
1196 return int(self.value)
1198 def getSatList(self):
1199 return self._satList
1202 return self.satList[self.index]
1204 satList = property(getSatList)
1206 orbital_position = property(getOrbitalPosition)
1208 class ConfigSet(ConfigElement):
1209 def __init__(self, choices, default = []):
1210 ConfigElement.__init__(self)
1211 if isinstance(choices, list):
1213 self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
1215 assert False, "ConfigSet choices must be a list!"
1220 self.last_value = self.default = default
1221 self.value = default[:]
1223 def toggleChoice(self, choice):
1226 value.remove(choice)
1228 value.append(choice)
1232 def handleKey(self, key):
1233 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1235 self.toggleChoice(self.choices[self.pos])
1236 elif key == KEY_LEFT:
1238 self.pos = len(self.choices)-1
1241 elif key == KEY_RIGHT:
1242 if self.pos >= len(self.choices)-1:
1246 elif key in (KEY_HOME, KEY_END):
1249 def genString(self, lst):
1252 res += self.description[x]+" "
1256 return self.genString(self.value)
1258 def getMulti(self, selected):
1259 if not selected or self.pos == -1:
1260 return ("text", self.genString(self.value))
1263 ch = self.choices[self.pos]
1264 mem = ch in self.value
1269 val1 = self.genString(tmp[:ind])
1270 val2 = " "+self.genString(tmp[ind+1:])
1272 chstr = " "+self.description[ch]+" "
1274 chstr = "("+self.description[ch]+")"
1275 len_val1 = len(val1)
1276 return ("mtext", val1+chstr+val2, range(len_val1, len_val1 + len(chstr)))
1278 def onDeselect(self, session):
1280 if not self.last_value == self.value:
1282 self.last_value = self.value[:]
1284 def tostring(self, value):
1287 def fromstring(self, val):
1290 description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
1292 class ConfigLocations(ConfigElement):
1293 def __init__(self, default = [], visible_width = False):
1294 ConfigElement.__init__(self)
1295 self.visible_width = visible_width
1297 self.default = default
1299 self.mountpoints = []
1300 self.value = default[:]
1302 def setValue(self, value):
1303 locations = self.locations
1304 loc = [x[0] for x in locations if x[3]]
1305 add = [x for x in value if not x in loc]
1306 diff = add + [x for x in loc if not x in value]
1307 locations = [x for x in locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1308 locations.sort(key = lambda x: x[0])
1309 self.locations = locations
1313 self.checkChangedMountpoints()
1314 locations = self.locations
1317 return [x[0] for x in locations if x[3]]
1319 value = property(getValue, setValue)
1321 def tostring(self, value):
1324 def fromstring(self, val):
1328 sv = self.saved_value
1332 tmp = self.fromstring(sv)
1333 locations = [[x, None, False, False] for x in tmp]
1334 self.refreshMountpoints()
1336 if fileExists(x[0]):
1337 x[1] = self.getMountpoint(x[0])
1339 self.locations = locations
1342 locations = self.locations
1343 if self.save_disabled or not locations:
1344 self.saved_value = None
1346 self.saved_value = self.tostring([x[0] for x in locations])
1348 def isChanged(self):
1349 sv = self.saved_value
1350 locations = self.locations
1351 if val is None and not locations:
1353 return self.tostring([x[0] for x in locations]) != sv
1355 def addedMount(self, mp):
1356 for x in self.locations:
1359 elif x[1] == None and fileExists(x[0]):
1360 x[1] = self.getMountpoint(x[0])
1363 def removedMount(self, mp):
1364 for x in self.locations:
1368 def refreshMountpoints(self):
1369 self.mountpoints = [p.mountpoint for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1370 self.mountpoints.sort(key = lambda x: -len(x))
1372 def checkChangedMountpoints(self):
1373 oldmounts = self.mountpoints
1374 self.refreshMountpoints()
1375 newmounts = self.mountpoints
1376 if oldmounts == newmounts:
1379 if not x in newmounts:
1380 self.removedMount(x)
1382 if not x in oldmounts:
1385 def getMountpoint(self, file):
1386 file = os_path.realpath(file)+"/"
1387 for m in self.mountpoints:
1388 if file.startswith(m):
1392 def handleKey(self, key):
1396 self.pos = len(self.value)-1
1397 elif key == KEY_RIGHT:
1399 if self.pos >= len(self.value):
1401 elif key in (KEY_HOME, KEY_END):
1405 return " ".join(self.value)
1407 def getMulti(self, selected):
1409 valstr = " ".join(self.value)
1410 if self.visible_width and len(valstr) > self.visible_width:
1411 return ("text", valstr[0:self.visible_width])
1413 return ("text", valstr)
1419 for val in self.value:
1422 valstr += str(val)+" "
1426 if self.visible_width and len(valstr) > self.visible_width:
1427 if ind1+1 < self.visible_width/2:
1430 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1431 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1433 return ("mtext", valstr, range(ind1,ind2))
1435 def onDeselect(self, session):
1439 class ConfigNothing(ConfigSelection):
1441 ConfigSelection.__init__(self, choices = [("","")])
1443 # until here, 'saved_value' always had to be a *string*.
1444 # now, in ConfigSubsection, and only there, saved_value
1445 # is a dict, essentially forming a tree.
1447 # config.foo.bar=True
1448 # config.foobar=False
1451 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1454 class ConfigSubsectionContent(object):
1457 # we store a backup of the loaded configuration
1458 # data in self.stored_values, to be able to deploy
1459 # them when a new config element will be added,
1460 # so non-default values are instantly available
1462 # A list, for example:
1463 # config.dipswitches = ConfigSubList()
1464 # config.dipswitches.append(ConfigYesNo())
1465 # config.dipswitches.append(ConfigYesNo())
1466 # config.dipswitches.append(ConfigYesNo())
1467 class ConfigSubList(list, object):
1470 self.stored_values = {}
1480 def getSavedValue(self):
1482 for i, val in enumerate(self):
1483 sv = val.saved_value
1488 def setSavedValue(self, values):
1489 self.stored_values = dict(values)
1490 for (key, val) in self.stored_values.items():
1491 if int(key) < len(self):
1492 self[int(key)].saved_value = val
1494 saved_value = property(getSavedValue, setSavedValue)
1496 def append(self, item):
1498 list.append(self, item)
1499 if i in self.stored_values:
1500 item.saved_value = self.stored_values[i]
1504 return dict([(str(index), value) for index, value in enumerate(self)])
1506 # same as ConfigSubList, just as a dictionary.
1507 # care must be taken that the 'key' has a proper
1508 # str() method, because it will be used in the config
1510 class ConfigSubDict(dict, object):
1513 self.stored_values = {}
1516 for x in self.values():
1520 for x in self.values():
1523 def getSavedValue(self):
1525 for (key, val) in self.items():
1526 sv = val.saved_value
1531 def setSavedValue(self, values):
1532 self.stored_values = dict(values)
1533 for (key, val) in self.items():
1534 if str(key) in self.stored_values:
1535 val.saved_value = self.stored_values[str(key)]
1537 saved_value = property(getSavedValue, setSavedValue)
1539 def __setitem__(self, key, item):
1540 dict.__setitem__(self, key, item)
1541 if str(key) in self.stored_values:
1542 item.saved_value = self.stored_values[str(key)]
1548 # Like the classes above, just with a more "native"
1551 # some evil stuff must be done to allow instant
1552 # loading of added elements. this is why this class
1555 # we need the 'content' because we overwrite
1557 # If you don't understand this, try adding
1558 # __setattr__ to a usual exisiting class and you will.
1559 class ConfigSubsection(object):
1561 self.__dict__["content"] = ConfigSubsectionContent()
1562 self.content.items = { }
1563 self.content.stored_values = { }
1565 def __setattr__(self, name, value):
1566 if name == "saved_value":
1567 return self.setSavedValue(value)
1568 assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1569 content = self.content
1570 content.items[name] = value
1571 x = content.stored_values.get(name, None)
1573 #print "ok, now we have a new item,", name, "and have the following value for it:", x
1574 value.saved_value = x
1577 def __getattr__(self, name):
1578 return self.content.items[name]
1580 def getSavedValue(self):
1581 res = self.content.stored_values
1582 for (key, val) in self.content.items.items():
1583 sv = val.saved_value
1590 def setSavedValue(self, values):
1591 values = dict(values)
1592 self.content.stored_values = values
1593 for (key, val) in self.content.items.items():
1594 value = values.get(key, None)
1595 if value is not None:
1596 val.saved_value = value
1598 saved_value = property(getSavedValue, setSavedValue)
1601 for x in self.content.items.values():
1605 for x in self.content.items.values():
1609 return self.content.items
1611 # the root config object, which also can "pickle" (=serialize)
1612 # down the whole config tree.
1614 # we try to keep non-existing config entries, to apply them whenever
1615 # a new config entry is added to a subsection
1616 # also, non-existing config entries will be saved, so they won't be
1617 # lost when a config entry disappears.
1618 class Config(ConfigSubsection):
1620 ConfigSubsection.__init__(self)
1622 def pickle_this(self, prefix, topickle, result):
1623 for (key, val) in topickle.items():
1624 name = '.'.join((prefix, key))
1625 if isinstance(val, dict):
1626 self.pickle_this(name, val, result)
1627 elif isinstance(val, tuple):
1628 result += [name, '=', val[0], '\n']
1630 result += [name, '=', val, '\n']
1634 self.pickle_this("config", self.saved_value, result)
1635 return ''.join(result)
1637 def unpickle(self, lines):
1640 if not l or l[0] == '#':
1644 val = l[n+1:].strip()
1646 names = l[:n].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 # we inherit from ConfigSubsection, so ...
1658 #object.__setattr__(self, "saved_value", tree["config"])
1659 if "config" in tree:
1660 self.setSavedValue(tree["config"])
1662 def saveToFile(self, filename):
1663 text = self.pickle()
1664 f = open(filename, "w")
1668 def loadFromFile(self, filename):
1669 f = open(filename, "r")
1670 self.unpickle(f.readlines())
1674 config.misc = ConfigSubsection()
1677 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1681 config.loadFromFile(self.CONFIG_FILE)
1683 print "unable to load config (%s), assuming defaults..." % str(e)
1687 config.saveToFile(self.CONFIG_FILE)
1689 def __resolveValue(self, pickles, cmap):
1691 if cmap.has_key(key):
1692 if len(pickles) > 1:
1693 return self.__resolveValue(pickles[1:], cmap[key].dict())
1695 return str(cmap[key].value)
1698 def getResolvedKey(self, key):
1699 names = key.split('.')
1701 if names[0] == "config":
1702 ret=self.__resolveValue(names[1:], config.content.items)
1703 if ret and len(ret):
1705 print "getResolvedKey", key, "failed !! (Typo??)"
1708 def NoSave(element):
1709 element.disableSave()
1712 configfile = ConfigFile()
1716 def getConfigListEntry(*args):
1717 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1720 def updateConfigElement(element, newelement):
1721 newelement.value = element.value
1727 #config.bla = ConfigSubsection()
1728 #config.bla.test = ConfigYesNo()
1729 #config.nim = ConfigSubList()
1730 #config.nim.append(ConfigSubsection())
1731 #config.nim[0].bla = ConfigYesNo()
1732 #config.nim.append(ConfigSubsection())
1733 #config.nim[1].bla = ConfigYesNo()
1734 #config.nim[1].blub = ConfigYesNo()
1735 #config.arg = ConfigSubDict()
1736 #config.arg["Hello"] = ConfigYesNo()
1738 #config.arg["Hello"].handleKey(KEY_RIGHT)
1739 #config.arg["Hello"].handleKey(KEY_RIGHT)
1741 ##config.saved_value
1745 #print config.pickle()