1 from enigma import getPrevAsciiCode
2 from Tools.NumericalTextInput import NumericalTextInput
3 from Tools.Directories import resolveFilename, SCOPE_CONFIG
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)
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 notifiers = property(getNotifiers)
46 def getNotifiersFinal(self):
47 if self.__notifiers_final is None:
48 self.__notifiers_final = [ ]
49 return self.__notifiers_final
51 notifiers_final = property(getNotifiersFinal)
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:
81 self.saved_value = None
83 self.saved_value = self.tostring(self.value)
84 if self.callNotifiersOnSaveAndCancel:
89 if self.callNotifiersOnSaveAndCancel:
94 if sv is None and self.value == self.default:
96 return self.tostring(self.value) != sv
100 for x in self.notifiers:
103 def changedFinal(self):
104 if self.__notifiers_final:
105 for x in self.notifiers_final:
108 def addNotifier(self, notifier, initial_call = True, immediate_feedback = True):
109 assert callable(notifier), "notifiers must be callable"
110 if immediate_feedback:
111 self.notifiers.append(notifier)
113 self.notifiers_final.append(notifier)
115 # do we want to call the notifier
116 # - at all when adding it? (yes, though optional)
117 # - when the default is active? (yes)
118 # - when no value *yet* has been set,
119 # because no config has ever been read (currently yes)
120 # (though that's not so easy to detect.
121 # the entry could just be new.)
125 def disableSave(self):
126 self.save_disabled = True
128 def __call__(self, selected):
129 return self.getMulti(selected)
131 def onSelect(self, session):
134 def onDeselect(self, session):
135 if not self.last_value == self.value:
137 self.last_value = self.value
149 KEY_NUMBERS = range(12, 12+10)
153 def getKeyNumber(key):
154 assert key in KEY_NUMBERS
157 class choicesList: # XXX: we might want a better name for this
161 def __init__(self, choices, type = None):
162 self.choices = choices
164 if isinstance(choices, list):
165 self.type = choicesList.LIST_TYPE_LIST
166 elif isinstance(choices, dict):
167 self.type = choicesList.LIST_TYPE_DICT
169 assert False, "choices must be dict or list!"
174 if self.type == choicesList.LIST_TYPE_LIST:
175 ret = [isinstance(x, tuple) and x[0] or x for x in self.choices]
177 ret = self.choices.keys()
181 if self.type == choicesList.LIST_TYPE_LIST:
182 ret = [isinstance(x, tuple) and x[0] or x for x in self.choices]
185 return iter(ret or [""])
188 return len(self.choices) or 1
190 def __getitem__(self, index):
191 if self.type == choicesList.LIST_TYPE_LIST:
192 ret = self.choices[index]
193 if isinstance(ret, tuple):
196 return self.choices.keys()[index]
198 def index(self, value):
199 return self.__list__().index(value)
201 def __setitem__(self, index, value):
202 if self.type == choicesList.LIST_TYPE_LIST:
203 orig = self.choices[index]
204 if isinstance(orig, tuple):
205 self.choices[index] = (value, orig[1])
207 self.choices[index] = value
209 key = self.choices.keys()[index]
210 orig = self.choices[key]
211 del self.choices[key]
212 self.choices[value] = orig
215 choices = self.choices
218 if self.type is choicesList.LIST_TYPE_LIST:
220 if isinstance(default, tuple):
223 default = choices.keys()[0]
226 class descriptionList(choicesList): # XXX: we might want a better name for this
228 if self.type == choicesList.LIST_TYPE_LIST:
229 ret = [isinstance(x, tuple) and x[1] or x for x in self.choices]
231 ret = self.choices.values()
235 return iter(self.__list__())
237 def __getitem__(self, index):
238 if self.type == choicesList.LIST_TYPE_LIST:
239 for x in self.choices:
240 if isinstance(x, tuple):
245 return str(index) # Fallback!
247 return str(self.choices.get(index, ""))
249 def __setitem__(self, index, value):
250 if self.type == choicesList.LIST_TYPE_LIST:
251 i = self.index(index)
252 orig = self.choices[i]
253 if isinstance(orig, tuple):
254 self.choices[i] = (orig[0], value)
256 self.choices[i] = value
258 self.choices[index] = value
261 # ConfigSelection is a "one of.."-type.
262 # it has the "choices", usually a list, which contains
263 # (id, desc)-tuples (or just only the ids, in case the id
264 # will be used as description)
266 # all ids MUST be plain strings.
268 class ConfigSelection(ConfigElement):
269 def __init__(self, choices, default = None):
270 ConfigElement.__init__(self)
271 self.choices = choicesList(choices)
274 default = self.choices.default()
276 self.default = self._value = self.last_value = default
279 def setChoices(self, choices, default = None):
280 self.choices = choicesList(choices)
283 default = self.choices.default()
285 if self.value not in self.choices:
288 def setValue(self, value):
289 if value in self.choices:
292 self._value = self.default
295 def tostring(self, val):
301 def setCurrentText(self, text):
302 i = self.choices.index(self.value)
303 self.choices[i] = text
304 self.description[text] = text
307 value = property(getValue, setValue)
310 return self.choices.index(self.value)
312 index = property(getIndex)
315 def handleKey(self, key):
316 nchoices = len(self.choices)
317 i = self.choices.index(self.value)
319 self.value = self.choices[(i + nchoices - 1) % nchoices]
320 elif key == KEY_RIGHT:
321 self.value = self.choices[(i + 1) % nchoices]
322 elif key == KEY_HOME:
323 self.value = self.choices[0]
325 self.value = self.choices[nchoices - 1]
327 def selectNext(self):
328 nchoices = len(self.choices)
329 i = self.choices.index(self.value)
330 self.value = self.choices[(i + 1) % nchoices]
333 descr = self.description[self.value]
338 def getMulti(self, selected):
339 descr = self.description[self.value]
341 return ("text", _(descr))
342 return ("text", descr)
345 def getHTML(self, id):
347 for v in self.choices:
348 descr = self.description[v]
350 checked = 'checked="checked" '
353 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + descr + "</input></br>\n"
356 def unsafeAssign(self, value):
357 # setValue does check if value is in choices. This is safe enough.
360 description = property(lambda self: descriptionList(self.choices.choices, self.choices.type))
364 # several customized versions exist for different
367 boolean_descriptions = {False: "false", True: "true"}
368 class ConfigBoolean(ConfigElement):
369 def __init__(self, default = False, descriptions = boolean_descriptions):
370 ConfigElement.__init__(self)
371 self.descriptions = descriptions
372 self.value = self.last_value = self.default = default
374 def handleKey(self, key):
375 if key in [KEY_LEFT, KEY_RIGHT]:
376 self.value = not self.value
377 elif key == KEY_HOME:
383 descr = self.descriptions[self.value]
388 def getMulti(self, selected):
389 descr = self.descriptions[self.value]
391 return ("text", _(descr))
392 return ("text", descr)
394 def tostring(self, value):
400 def fromstring(self, val):
406 def getHTML(self, id):
408 checked = ' checked="checked"'
411 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
413 # this is FLAWED. and must be fixed.
414 def unsafeAssign(self, value):
420 def onDeselect(self, session):
421 if not self.last_value == self.value:
423 self.last_value = self.value
425 yes_no_descriptions = {False: _("no"), True: _("yes")}
426 class ConfigYesNo(ConfigBoolean):
427 def __init__(self, default = False):
428 ConfigBoolean.__init__(self, default = default, descriptions = yes_no_descriptions)
430 on_off_descriptions = {False: _("off"), True: _("on")}
431 class ConfigOnOff(ConfigBoolean):
432 def __init__(self, default = False):
433 ConfigBoolean.__init__(self, default = default, descriptions = on_off_descriptions)
435 enable_disable_descriptions = {False: _("disable"), True: _("enable")}
436 class ConfigEnableDisable(ConfigBoolean):
437 def __init__(self, default = False):
438 ConfigBoolean.__init__(self, default = default, descriptions = enable_disable_descriptions)
440 class ConfigDateTime(ConfigElement):
441 def __init__(self, default, formatstring, increment = 86400):
442 ConfigElement.__init__(self)
443 self.increment = increment
444 self.formatstring = formatstring
445 self.value = self.last_value = self.default = int(default)
447 def handleKey(self, key):
449 self.value = self.value - self.increment
450 elif key == KEY_RIGHT:
451 self.value = self.value + self.increment
452 elif key == KEY_HOME or key == KEY_END:
453 self.value = self.default
456 return strftime(self.formatstring, localtime(self.value))
458 def getMulti(self, selected):
459 return ("text", strftime(self.formatstring, localtime(self.value)))
461 def fromstring(self, val):
464 # *THE* mighty config element class
466 # allows you to store/edit a sequence of values.
467 # can be used for IP-addresses, dates, plain integers, ...
468 # several helper exist to ease this up a bit.
470 class ConfigSequence(ConfigElement):
471 def __init__(self, seperator, limits, default, censor_char = ""):
472 ConfigElement.__init__(self)
473 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
474 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
475 #assert isinstance(default, list), "default must be a list"
476 #assert isinstance(default[0], int), "list must contain numbers"
477 #assert len(default) == len(limits), "length must match"
480 self.seperator = seperator
482 self.censor_char = censor_char
484 self.last_value = self.default = default
485 self.value = copy_copy(default)
486 self.endNotifier = None
491 for i in self._value:
492 max_pos += len(str(self.limits[num][1]))
494 if self._value[num] < self.limits[num][0]:
495 self._value[num] = self.limits[num][0]
497 if self._value[num] > self.limits[num][1]:
498 self._value[num] = self.limits[num][1]
502 if self.marked_pos >= max_pos:
504 for x in self.endNotifier:
506 self.marked_pos = max_pos - 1
508 if self.marked_pos < 0:
511 def validatePos(self):
512 if self.marked_pos < 0:
515 total_len = sum([len(str(x[1])) for x in self.limits])
517 if self.marked_pos >= total_len:
518 self.marked_pos = total_len - 1
520 def addEndNotifier(self, notifier):
521 if endNotifier is None:
523 self.endNotifier.append(notifier)
525 def handleKey(self, key):
541 for i in self._value:
542 max_pos += len(str(self.limits[num][1]))
544 self.marked_pos = max_pos - 1
547 if key in KEY_NUMBERS or key == KEY_ASCII:
549 code = getPrevAsciiCode()
550 if code < 48 or code > 57:
554 number = getKeyNumber(key)
557 for x in self.limits:
558 block_len.append(len(str(x[1])))
560 total_len = sum(block_len)
564 block_len_total = [0, ]
566 pos += block_len[blocknumber]
567 block_len_total.append(pos)
568 if pos - 1 >= self.marked_pos:
573 # length of numberblock
574 number_len = len(str(self.limits[blocknumber][1]))
576 # position in the block
577 posinblock = self.marked_pos - block_len_total[blocknumber]
579 oldvalue = self._value[blocknumber]
580 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
581 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
583 self._value[blocknumber] = newvalue
591 mPos = self.marked_pos
593 for i in self._value:
594 if value: #fixme no heading separator possible
595 value += self.seperator
596 if mPos >= len(value) - 1:
598 if self.censor_char == "":
599 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
601 value += (self.censor_char * len(str(self.limits[num][1])))
606 (value, mPos) = self.genText()
609 def getMulti(self, selected):
610 (value, mPos) = self.genText()
611 # only mark cursor when we are selected
612 # (this code is heavily ink optimized!)
614 return ("mtext"[1-selected:], value, [mPos])
616 return ("text", value)
618 def tostring(self, val):
619 return self.seperator.join([self.saveSingle(x) for x in val])
621 def saveSingle(self, v):
624 def fromstring(self, value):
625 return [int(x) for x in value.split(self.seperator)]
627 def onDeselect(self, session):
628 if self.last_value != self._value:
630 self.last_value = copy_copy(self._value)
632 ip_limits = [(0,255),(0,255),(0,255),(0,255)]
633 class ConfigIP(ConfigSequence):
634 def __init__(self, default, auto_jump = False):
635 ConfigSequence.__init__(self, seperator = ".", limits = ip_limits, default = default)
637 for x in self.limits:
638 self.block_len.append(len(str(x[1])))
639 self.marked_block = 0
640 self.overwrite = True
641 self.auto_jump = auto_jump
643 def handleKey(self, key):
646 if self.marked_block > 0:
647 self.marked_block -= 1
648 self.overwrite = True
651 if self.marked_block < len(self.limits)-1:
652 self.marked_block += 1
653 self.overwrite = True
656 self.marked_block = 0
657 self.overwrite = True
660 self.marked_block = len(self.limits)-1
661 self.overwrite = True
663 if key in KEY_NUMBERS or key == KEY_ASCII:
665 code = getPrevAsciiCode()
666 if code < 48 or code > 57:
670 number = getKeyNumber(key)
671 oldvalue = self._value[self.marked_block]
674 self._value[self.marked_block] = number
675 self.overwrite = False
678 newvalue = oldvalue + number
679 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
680 self.handleKey(KEY_RIGHT)
684 self._value[self.marked_block] = newvalue
686 if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
687 self.handleKey(KEY_RIGHT)
695 for i in self._value:
696 block_strlen.append(len(str(i)))
698 value += self.seperator
700 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
701 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
702 mBlock = range(leftPos, rightPos)
703 return (value, mBlock)
705 def getMulti(self, selected):
706 (value, mBlock) = self.genText()
708 return ("mtext"[1-selected:], value, mBlock)
710 return ("text", value)
712 def getHTML(self, id):
713 # we definitely don't want leading zeros
714 return '.'.join(["%d" % d for d in self.value])
716 mac_limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)]
717 class ConfigMAC(ConfigSequence):
718 def __init__(self, default):
719 ConfigSequence.__init__(self, seperator = ":", limits = mac_limits, default = default)
721 class ConfigPosition(ConfigSequence):
722 def __init__(self, default, args):
723 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
725 clock_limits = [(0,23),(0,59)]
726 class ConfigClock(ConfigSequence):
727 def __init__(self, default):
728 t = localtime(default)
729 ConfigSequence.__init__(self, seperator = ":", limits = clock_limits, default = [t.tm_hour, t.tm_min])
732 # Check if Minutes maxed out
733 if self._value[1] == 59:
734 # Increment Hour, reset Minutes
735 if self._value[0] < 23:
747 # Check if Minutes is minimum
748 if self._value[1] == 0:
749 # Decrement Hour, set Minutes to 59
750 if self._value[0] > 0:
761 integer_limits = (0, 9999999999)
762 class ConfigInteger(ConfigSequence):
763 def __init__(self, default, limits = integer_limits):
764 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
766 # you need to override this to do input validation
767 def setValue(self, value):
768 self._value = [value]
772 return self._value[0]
774 value = property(getValue, setValue)
776 def fromstring(self, value):
779 def tostring(self, value):
782 class ConfigPIN(ConfigInteger):
783 def __init__(self, default, len = 4, censor = ""):
784 assert isinstance(default, int), "ConfigPIN default must be an integer"
787 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
793 class ConfigFloat(ConfigSequence):
794 def __init__(self, default, limits):
795 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
798 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
800 float = property(getFloat)
802 # an editable text...
803 class ConfigText(ConfigElement, NumericalTextInput):
804 def __init__(self, default = "", fixed_size = True, visible_width = False):
805 ConfigElement.__init__(self)
806 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
809 self.allmarked = (default != "")
810 self.fixed_size = fixed_size
811 self.visible_width = visible_width
813 self.overwrite = fixed_size
814 self.help_window = None
815 self.value = self.last_value = self.default = default
817 def validateMarker(self):
819 if self.marked_pos > len(self.text)-1:
820 self.marked_pos = len(self.text)-1
822 if self.marked_pos > len(self.text):
823 self.marked_pos = len(self.text)
824 if self.marked_pos < 0:
826 if self.visible_width:
827 if self.marked_pos < self.offset:
828 self.offset = self.marked_pos
829 if self.marked_pos >= self.offset + self.visible_width:
830 if self.marked_pos == len(self.text):
831 self.offset = self.marked_pos - self.visible_width
833 self.offset = self.marked_pos - self.visible_width + 1
834 if self.offset > 0 and self.offset + self.visible_width > len(self.text):
835 self.offset = max(0, len(self.text) - self.visible_width)
837 def insertChar(self, ch, pos, owr):
838 if owr or self.overwrite:
839 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
840 elif self.fixed_size:
841 self.text = self.text[0:pos] + ch + self.text[pos:-1]
843 self.text = self.text[0:pos] + ch + self.text[pos:]
845 def deleteChar(self, pos):
846 if not self.fixed_size:
847 self.text = self.text[0:pos] + self.text[pos + 1:]
849 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
851 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
853 def deleteAllChars(self):
855 self.text = " " * len(self.text)
860 def handleKey(self, key):
861 # this will no change anything on the value itself
862 # so we can handle it here in gui element
863 if key == KEY_DELETE:
866 self.deleteAllChars()
867 self.allmarked = False
869 self.deleteChar(self.marked_pos)
870 if self.fixed_size and self.overwrite:
872 elif key == KEY_BACKSPACE:
875 self.deleteAllChars()
876 self.allmarked = False
877 elif self.marked_pos > 0:
878 self.deleteChar(self.marked_pos-1)
879 if not self.fixed_size and self.offset > 0:
882 elif key == KEY_LEFT:
885 self.marked_pos = len(self.text)
886 self.allmarked = False
889 elif key == KEY_RIGHT:
893 self.allmarked = False
896 elif key == KEY_HOME:
898 self.allmarked = False
902 self.allmarked = False
903 self.marked_pos = len(self.text)
904 elif key == KEY_TOGGLEOW:
906 self.overwrite = not self.overwrite
907 elif key == KEY_ASCII:
909 newChar = unichr(getPrevAsciiCode())
911 self.deleteAllChars()
912 self.allmarked = False
913 self.insertChar(newChar, self.marked_pos, False)
915 elif key in KEY_NUMBERS:
916 owr = self.lastKey == getKeyNumber(key)
917 newChar = self.getKey(getKeyNumber(key))
919 self.deleteAllChars()
920 self.allmarked = False
921 self.insertChar(newChar, self.marked_pos, owr)
922 elif key == KEY_TIMEOUT:
925 self.help_window.update(self)
929 self.help_window.update(self)
930 self.validateMarker()
935 self.validateMarker()
939 return self.text.encode("utf-8")
941 def setValue(self, val):
943 self.text = val.decode("utf-8")
944 except UnicodeDecodeError:
945 self.text = val.decode("utf-8", "ignore")
948 value = property(getValue, setValue)
949 _value = property(getValue, setValue)
952 return self.text.encode("utf-8")
954 def getMulti(self, selected):
955 if self.visible_width:
957 mark = range(0, min(self.visible_width, len(self.text)))
959 mark = [self.marked_pos-self.offset]
960 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
963 mark = range(0, len(self.text))
965 mark = [self.marked_pos]
966 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
968 def onSelect(self, session):
969 self.allmarked = (self.value != "")
970 if session is not None:
971 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
972 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
973 self.help_window.show()
975 def onDeselect(self, session):
979 session.deleteDialog(self.help_window)
980 self.help_window = None
981 if not self.last_value == self.value:
983 self.last_value = self.value
985 def getHTML(self, id):
986 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
988 def unsafeAssign(self, value):
989 self.value = str(value)
991 class ConfigPassword(ConfigText):
992 def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
993 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
994 self.censor_char = censor
997 def getMulti(self, selected):
998 mtext, text, mark = ConfigText.getMulti(self, selected)
1000 text = len(text) * self.censor_char
1001 return (mtext, text, mark)
1003 def onSelect(self, session):
1004 ConfigText.onSelect(self, session)
1007 def onDeselect(self, session):
1008 ConfigText.onDeselect(self, session)
1011 class ConfigNumber(ConfigText):
1012 def __init__(self, default = 0):
1013 ConfigText.__init__(self, str(default), fixed_size = False)
1016 return int(self.text)
1018 def setValue(self, val):
1019 self.text = str(val)
1021 value = property(getValue, setValue)
1022 _value = property(getValue, setValue)
1025 pos = len(self.text) - self.marked_pos
1026 self.text = self.text.lstrip("0")
1029 if pos > len(self.text):
1032 self.marked_pos = len(self.text) - pos
1034 def handleKey(self, key):
1035 if key in KEY_NUMBERS or key == KEY_ASCII:
1036 if key == KEY_ASCII:
1037 ascii = getPrevAsciiCode()
1038 if not (48 <= ascii <= 57):
1041 ascii = getKeyNumber(key) + 48
1042 newChar = unichr(ascii)
1044 self.deleteAllChars()
1045 self.allmarked = False
1046 self.insertChar(newChar, self.marked_pos, False)
1047 self.marked_pos += 1
1049 ConfigText.handleKey(self, key)
1052 def onSelect(self, session):
1053 self.allmarked = (self.value != "")
1055 def onDeselect(self, session):
1058 if not self.last_value == self.value:
1060 self.last_value = self.value
1062 class ConfigSearchText(ConfigText):
1063 def __init__(self, default = "", fixed_size = False, visible_width = False):
1064 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1065 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = True)
1067 class ConfigDirectory(ConfigText):
1068 def __init__(self, default="", visible_width=60):
1069 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
1070 def handleKey(self, key):
1076 return ConfigText.getValue(self)
1077 def setValue(self, val):
1080 ConfigText.setValue(self, val)
1081 def getMulti(self, selected):
1083 return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
1085 return ConfigText.getMulti(self, selected)
1088 class ConfigSlider(ConfigElement):
1089 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
1090 ConfigElement.__init__(self)
1091 self.value = self.last_value = self.default = default
1092 self.min = limits[0]
1093 self.max = limits[1]
1094 self.increment = increment
1096 def checkValues(self):
1097 if self.value < self.min:
1098 self.value = self.min
1100 if self.value > self.max:
1101 self.value = self.max
1103 def handleKey(self, key):
1105 self.value -= self.increment
1106 elif key == KEY_RIGHT:
1107 self.value += self.increment
1108 elif key == KEY_HOME:
1109 self.value = self.min
1110 elif key == KEY_END:
1111 self.value = self.max
1117 return "%d / %d" % (self.value, self.max)
1119 def getMulti(self, selected):
1121 return ("slider", self.value, self.max)
1123 def fromstring(self, value):
1126 # a satlist. in fact, it's a ConfigSelection.
1127 class ConfigSatlist(ConfigSelection):
1128 def __init__(self, list, default = None):
1129 if default is not None:
1130 default = str(default)
1131 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1133 def getOrbitalPosition(self):
1134 if self.value == "":
1136 return int(self.value)
1138 orbital_position = property(getOrbitalPosition)
1140 class ConfigSet(ConfigElement):
1141 def __init__(self, choices, default = []):
1142 ConfigElement.__init__(self)
1143 if isinstance(choices, list):
1145 self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
1147 assert False, "ConfigSet choices must be a list!"
1152 self.last_value = self.default = default
1153 self.value = default[:]
1155 def toggleChoice(self, choice):
1156 if choice in self.value:
1157 self.value.remove(choice)
1159 self.value.append(choice)
1163 def handleKey(self, key):
1164 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1166 self.toggleChoice(self.choices[self.pos])
1167 elif key == KEY_LEFT:
1170 self.pos = len(self.choices)-1
1171 elif key == KEY_RIGHT:
1173 if self.pos >= len(self.choices):
1175 elif key in [KEY_HOME, KEY_END]:
1178 def genString(self, lst):
1181 res += self.description[x]+" "
1185 return self.genString(self.value)
1187 def getMulti(self, selected):
1188 if not selected or self.pos == -1:
1189 return ("text", self.genString(self.value))
1192 ch = self.choices[self.pos]
1193 mem = ch in self.value
1198 val1 = self.genString(tmp[:ind])
1199 val2 = " "+self.genString(tmp[ind+1:])
1201 chstr = " "+self.description[ch]+" "
1203 chstr = "("+self.description[ch]+")"
1204 return ("mtext", val1+chstr+val2, range(len(val1),len(val1)+len(chstr)))
1206 def onDeselect(self, session):
1208 if not self.last_value == self.value:
1210 self.last_value = self.value[:]
1212 def tostring(self, value):
1215 def fromstring(self, val):
1218 description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
1220 class ConfigLocations(ConfigElement):
1221 def __init__(self, default = [], visible_width = False):
1222 ConfigElement.__init__(self)
1223 self.visible_width = visible_width
1225 self.default = default
1227 self.mountpoints = []
1228 harddiskmanager.on_partition_list_change.append(self.mountpointsChanged)
1229 self.value = default+[]
1231 def setValue(self, value):
1232 loc = [x[0] for x in self.locations if x[3]]
1233 add = [x for x in value if not x in loc]
1234 diff = add + [x for x in loc if not x in value]
1235 self.locations = [x for x in self.locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1236 self.locations.sort(key = lambda x: x[0])
1240 self.checkChangedMountpoints()
1241 for x in self.locations:
1243 return [x[0] for x in self.locations if x[3]]
1245 value = property(getValue, setValue)
1247 def tostring(self, value):
1250 def fromstring(self, val):
1254 sv = self.saved_value
1258 tmp = self.fromstring(sv)
1259 self.locations = [[x, None, False, False] for x in tmp]
1260 self.refreshMountpoints()
1261 for x in self.locations:
1262 if os_path.exists(x[0]):
1263 x[1] = self.getMountpoint(x[0])
1267 if self.save_disabled or self.locations == []:
1268 self.saved_value = None
1270 self.saved_value = self.tostring([x[0] for x in self.locations])
1272 def isChanged(self):
1273 sv = self.saved_value
1274 if val is None and self.locations == []:
1276 return self.tostring([x[0] for x in self.locations]) != sv
1278 def mountpointsChanged(self, action, dev):
1279 print "Mounts changed: ", action, dev
1280 mp = dev.mountpoint+"/"
1283 elif action == "remove":
1284 self.removedMount(mp)
1285 self.refreshMountpoints()
1287 def addedMount(self, mp):
1288 for x in self.locations:
1291 elif x[1] == None and os_path.exists(x[0]):
1292 x[1] = self.getMountpoint(x[0])
1295 def removedMount(self, mp):
1296 for x in self.locations:
1300 def refreshMountpoints(self):
1301 self.mountpoints = [p.mountpoint + "/" for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1302 self.mountpoints.sort(key = lambda x: -len(x))
1304 def checkChangedMountpoints(self):
1305 oldmounts = self.mountpoints
1306 self.refreshMountpoints()
1307 if oldmounts == self.mountpoints:
1310 if not x in self.mountpoints:
1311 self.removedMount(x)
1312 for x in self.mountpoints:
1313 if not x in oldmounts:
1316 def getMountpoint(self, file):
1317 file = os_path.realpath(file)+"/"
1318 for m in self.mountpoints:
1319 if file.startswith(m):
1323 def handleKey(self, key):
1327 self.pos = len(self.value)-1
1328 elif key == KEY_RIGHT:
1330 if self.pos >= len(self.value):
1332 elif key in [KEY_HOME, KEY_END]:
1336 return " ".join(self.value)
1338 def getMulti(self, selected):
1340 valstr = " ".join(self.value)
1341 if self.visible_width and len(valstr) > self.visible_width:
1342 return ("text", valstr[0:self.visible_width])
1344 return ("text", valstr)
1350 for val in self.value:
1353 valstr += str(val)+" "
1357 if self.visible_width and len(valstr) > self.visible_width:
1358 if ind1+1 < self.visible_width/2:
1361 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1362 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1364 return ("mtext", valstr, range(ind1,ind2))
1366 def onDeselect(self, session):
1370 class ConfigNothing(ConfigSelection):
1372 ConfigSelection.__init__(self, choices = [""])
1374 # until here, 'saved_value' always had to be a *string*.
1375 # now, in ConfigSubsection, and only there, saved_value
1376 # is a dict, essentially forming a tree.
1378 # config.foo.bar=True
1379 # config.foobar=False
1382 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1385 class ConfigSubsectionContent:
1388 # we store a backup of the loaded configuration
1389 # data in self.stored_values, to be able to deploy
1390 # them when a new config element will be added,
1391 # so non-default values are instantly available
1393 # A list, for example:
1394 # config.dipswitches = ConfigSubList()
1395 # config.dipswitches.append(ConfigYesNo())
1396 # config.dipswitches.append(ConfigYesNo())
1397 # config.dipswitches.append(ConfigYesNo())
1398 class ConfigSubList(list):
1401 self.stored_values = {}
1411 def getSavedValue(self):
1413 for i in range(len(self)):
1414 sv = self[i].saved_value
1419 def setSavedValue(self, values):
1420 self.stored_values = dict(values)
1421 for (key, val) in self.stored_values.items():
1422 if int(key) < len(self):
1423 self[int(key)].saved_value = val
1425 saved_value = property(getSavedValue, setSavedValue)
1427 def append(self, item):
1429 list.append(self, item)
1430 if i in self.stored_values:
1431 item.saved_value = self.stored_values[i]
1435 return dict([(str(index), value) for index, value in self.enumerate()])
1437 # same as ConfigSubList, just as a dictionary.
1438 # care must be taken that the 'key' has a proper
1439 # str() method, because it will be used in the config
1441 class ConfigSubDict(dict):
1444 self.stored_values = {}
1447 for x in self.values():
1451 for x in self.values():
1454 def getSavedValue(self):
1456 for (key, val) in self.items():
1457 sv = val.saved_value
1462 def setSavedValue(self, values):
1463 self.stored_values = dict(values)
1464 for (key, val) in self.items():
1465 if str(key) in self.stored_values:
1466 val = self.stored_values[str(key)]
1468 saved_value = property(getSavedValue, setSavedValue)
1470 def __setitem__(self, key, item):
1471 dict.__setitem__(self, key, item)
1472 if str(key) in self.stored_values:
1473 item.saved_value = self.stored_values[str(key)]
1479 # Like the classes above, just with a more "native"
1482 # some evil stuff must be done to allow instant
1483 # loading of added elements. this is why this class
1486 # we need the 'content' because we overwrite
1488 # If you don't understand this, try adding
1489 # __setattr__ to a usual exisiting class and you will.
1490 class ConfigSubsection:
1492 self.__dict__["content"] = ConfigSubsectionContent()
1493 self.content.items = { }
1494 self.content.stored_values = { }
1496 def __setattr__(self, name, value):
1497 if name == "saved_value":
1498 return self.setSavedValue(value)
1499 assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1500 content = self.content
1501 content.items[name] = value
1502 x = content.stored_values.get(name, None)
1504 #print "ok, now we have a new item,", name, "and have the following value for it:", x
1505 value.saved_value = x
1508 def __getattr__(self, name):
1509 return self.content.items[name]
1511 def getSavedValue(self):
1512 res = self.content.stored_values
1513 for (key, val) in self.content.items.items():
1514 sv = val.saved_value
1521 def setSavedValue(self, values):
1522 values = dict(values)
1523 self.content.stored_values = values
1524 for (key, val) in self.content.items.items():
1525 value = values.get(key, None)
1526 if value is not None:
1527 val.saved_value = value
1529 saved_value = property(getSavedValue, setSavedValue)
1532 for x in self.content.items.values():
1536 for x in self.content.items.values():
1540 return self.content.items
1542 # the root config object, which also can "pickle" (=serialize)
1543 # down the whole config tree.
1545 # we try to keep non-existing config entries, to apply them whenever
1546 # a new config entry is added to a subsection
1547 # also, non-existing config entries will be saved, so they won't be
1548 # lost when a config entry disappears.
1549 class Config(ConfigSubsection):
1551 ConfigSubsection.__init__(self)
1553 def pickle_this(self, prefix, topickle, result):
1554 for (key, val) in topickle.items():
1555 name = ''.join((prefix, '.', key))
1556 if isinstance(val, dict):
1557 self.pickle_this(name, val, result)
1558 elif isinstance(val, tuple):
1559 result += [name, '=', val[0], '\n']
1561 result += [name, '=', val, '\n']
1565 self.pickle_this("config", self.saved_value, result)
1566 return ''.join(result)
1568 def unpickle(self, lines):
1571 if not l or l[0] == '#':
1575 val = l[n+1:].strip()
1577 names = l[:n].split('.')
1578 # if val.find(' ') != -1:
1579 # val = val[:val.find(' ')]
1583 for n in names[:-1]:
1584 base = base.setdefault(n, {})
1586 base[names[-1]] = val
1588 # we inherit from ConfigSubsection, so ...
1589 #object.__setattr__(self, "saved_value", tree["config"])
1590 if "config" in tree:
1591 self.setSavedValue(tree["config"])
1593 def saveToFile(self, filename):
1594 f = open(filename, "w")
1595 f.write(self.pickle())
1598 def loadFromFile(self, filename):
1599 f = open(filename, "r")
1600 self.unpickle(f.readlines())
1604 config.misc = ConfigSubsection()
1607 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1611 config.loadFromFile(self.CONFIG_FILE)
1613 print "unable to load config (%s), assuming defaults..." % str(e)
1617 config.saveToFile(self.CONFIG_FILE)
1619 def __resolveValue(self, pickles, cmap):
1620 if cmap.has_key(pickles[0]):
1621 if len(pickles) > 1:
1622 return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
1624 return str(cmap[pickles[0]].value)
1627 def getResolvedKey(self, key):
1628 names = key.split('.')
1630 if names[0] == "config":
1631 ret=self.__resolveValue(names[1:], config.content.items)
1632 if ret and len(ret):
1634 print "getResolvedKey", key, "failed !! (Typo??)"
1637 def NoSave(element):
1638 element.disableSave()
1641 configfile = ConfigFile()
1645 def getConfigListEntry(*args):
1646 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1649 def updateConfigElement(element, newelement):
1650 newelement.value = element.value
1656 #config.bla = ConfigSubsection()
1657 #config.bla.test = ConfigYesNo()
1658 #config.nim = ConfigSubList()
1659 #config.nim.append(ConfigSubsection())
1660 #config.nim[0].bla = ConfigYesNo()
1661 #config.nim.append(ConfigSubsection())
1662 #config.nim[1].bla = ConfigYesNo()
1663 #config.nim[1].blub = ConfigYesNo()
1664 #config.arg = ConfigSubDict()
1665 #config.arg["Hello"] = ConfigYesNo()
1667 #config.arg["Hello"].handleKey(KEY_RIGHT)
1668 #config.arg["Hello"].handleKey(KEY_RIGHT)
1670 ##config.saved_value
1674 #print config.pickle()