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.save_forced = False
33 self.last_value = None
34 self.save_disabled = False
35 self.__notifiers = None
36 self.__notifiers_final = None
38 self.callNotifiersOnSaveAndCancel = False
40 def getNotifiers(self):
41 if self.__notifiers is None:
42 self.__notifiers = [ ]
43 return self.__notifiers
45 def setNotifiers(self, val):
46 self.__notifiers = val
48 notifiers = property(getNotifiers, setNotifiers)
50 def getNotifiersFinal(self):
51 if self.__notifiers_final is None:
52 self.__notifiers_final = [ ]
53 return self.__notifiers_final
55 def setNotifiersFinal(self, val):
56 self.__notifiers_final = val
58 notifiers_final = property(getNotifiersFinal, setNotifiersFinal)
60 # you need to override this to do input validation
61 def setValue(self, value):
68 value = property(getValue, setValue)
70 # you need to override this if self.value is not a string
71 def fromstring(self, value):
74 # you can overide this for fancy default handling
78 self.value = self.default
80 self.value = self.fromstring(sv)
82 def tostring(self, value):
85 # you need to override this if str(self.value) doesn't work
87 if self.save_disabled or (self.value == self.default and not self.save_forced):
88 self.saved_value = None
90 self.saved_value = self.tostring(self.value)
91 if self.callNotifiersOnSaveAndCancel:
96 if self.callNotifiersOnSaveAndCancel:
100 sv = self.saved_value
101 if sv is None and self.value == self.default:
103 return self.tostring(self.value) != sv
107 for x in self.notifiers:
110 def changedFinal(self):
111 if self.__notifiers_final:
112 for x in self.notifiers_final:
115 def addNotifier(self, notifier, initial_call = True, immediate_feedback = True):
116 assert callable(notifier), "notifiers must be callable"
117 if immediate_feedback:
118 self.notifiers.append(notifier)
120 self.notifiers_final.append(notifier)
122 # do we want to call the notifier
123 # - at all when adding it? (yes, though optional)
124 # - when the default is active? (yes)
125 # - when no value *yet* has been set,
126 # because no config has ever been read (currently yes)
127 # (though that's not so easy to detect.
128 # the entry could just be new.)
132 def disableSave(self):
133 self.save_disabled = True
135 def __call__(self, selected):
136 return self.getMulti(selected)
138 def onSelect(self, session):
141 def onDeselect(self, session):
142 if not self.last_value == self.value:
144 self.last_value = self.value
156 KEY_NUMBERS = range(12, 12+10)
160 def getKeyNumber(key):
161 assert key in KEY_NUMBERS
164 class choicesList(object): # XXX: we might want a better name for this
168 def __init__(self, choices, type = None):
169 self.choices = choices
171 if isinstance(choices, list):
172 self.type = choicesList.LIST_TYPE_LIST
173 elif isinstance(choices, dict):
174 self.type = choicesList.LIST_TYPE_DICT
176 assert False, "choices must be dict or list!"
181 if self.type == choicesList.LIST_TYPE_LIST:
182 ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
184 ret = self.choices.keys()
188 if self.type == choicesList.LIST_TYPE_LIST:
189 ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
192 return iter(ret or [""])
195 return len(self.choices) or 1
197 def __getitem__(self, index):
198 if self.type == choicesList.LIST_TYPE_LIST:
199 ret = self.choices[index]
200 if isinstance(ret, tuple):
203 return self.choices.keys()[index]
205 def index(self, value):
206 return self.__list__().index(value)
208 def __setitem__(self, index, value):
209 if self.type == choicesList.LIST_TYPE_LIST:
210 orig = self.choices[index]
211 if isinstance(orig, tuple):
212 self.choices[index] = (value, orig[1])
214 self.choices[index] = value
216 key = self.choices.keys()[index]
217 orig = self.choices[key]
218 del self.choices[key]
219 self.choices[value] = orig
222 choices = self.choices
225 if self.type is choicesList.LIST_TYPE_LIST:
227 if isinstance(default, tuple):
230 default = choices.keys()[0]
233 class descriptionList(choicesList): # XXX: we might want a better name for this
235 if self.type == choicesList.LIST_TYPE_LIST:
236 ret = [not isinstance(x, tuple) and x or x[1] for x in self.choices]
238 ret = self.choices.values()
242 return iter(self.__list__())
244 def __getitem__(self, index):
245 if self.type == choicesList.LIST_TYPE_LIST:
246 for x in self.choices:
247 if isinstance(x, tuple):
252 return str(index) # Fallback!
254 return str(self.choices.get(index, ""))
256 def __setitem__(self, index, value):
257 if self.type == choicesList.LIST_TYPE_LIST:
258 i = self.index(index)
259 orig = self.choices[i]
260 if isinstance(orig, tuple):
261 self.choices[i] = (orig[0], value)
263 self.choices[i] = value
265 self.choices[index] = value
268 # ConfigSelection is a "one of.."-type.
269 # it has the "choices", usually a list, which contains
270 # (id, desc)-tuples (or just only the ids, in case the id
271 # will be used as description)
273 # all ids MUST be plain strings.
275 class ConfigSelection(ConfigElement):
276 def __init__(self, choices, default = None):
277 ConfigElement.__init__(self)
278 self.choices = choicesList(choices)
281 default = self.choices.default()
284 self.default = self._value = self.last_value = default
286 def setChoices(self, choices, default = None):
287 self.choices = choicesList(choices)
290 default = self.choices.default()
291 self.default = default
293 if self.value not in self.choices:
296 def setValue(self, value):
297 if value in self.choices:
300 self._value = self.default
304 def tostring(self, val):
310 def setCurrentText(self, text):
311 i = self.choices.index(self.value)
312 self.choices[i] = text
313 self._descr = self.description[text] = text
316 value = property(getValue, setValue)
319 return self.choices.index(self.value)
321 index = property(getIndex)
324 def handleKey(self, key):
325 nchoices = len(self.choices)
326 i = self.choices.index(self.value)
328 self.value = self.choices[(i + nchoices - 1) % nchoices]
329 elif key == KEY_RIGHT:
330 self.value = self.choices[(i + 1) % nchoices]
331 elif key == KEY_HOME:
332 self.value = self.choices[0]
334 self.value = self.choices[nchoices - 1]
336 def selectNext(self):
337 nchoices = len(self.choices)
338 i = self.choices.index(self.value)
339 self.value = self.choices[(i + 1) % nchoices]
342 if self._descr is not None:
344 descr = self._descr = self.description[self.value]
349 def getMulti(self, selected):
350 if self._descr is not None:
353 descr = self._descr = self.description[self.value]
355 return ("text", _(descr))
356 return ("text", descr)
359 def getHTML(self, id):
361 for v in self.choices:
362 descr = self.description[v]
364 checked = 'checked="checked" '
367 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + descr + "</input></br>\n"
370 def unsafeAssign(self, value):
371 # setValue does check if value is in choices. This is safe enough.
374 description = property(lambda self: descriptionList(self.choices.choices, self.choices.type))
378 # several customized versions exist for different
381 boolean_descriptions = {False: "false", True: "true"}
382 class ConfigBoolean(ConfigElement):
383 def __init__(self, default = False, descriptions = boolean_descriptions):
384 ConfigElement.__init__(self)
385 self.descriptions = descriptions
386 self.value = self.last_value = self.default = default
388 def handleKey(self, key):
389 if key in (KEY_LEFT, KEY_RIGHT):
390 self.value = not self.value
391 elif key == KEY_HOME:
397 descr = self.descriptions[self.value]
402 def getMulti(self, selected):
403 descr = self.descriptions[self.value]
405 return ("text", _(descr))
406 return ("text", descr)
408 def tostring(self, value):
414 def fromstring(self, val):
420 def getHTML(self, id):
422 checked = ' checked="checked"'
425 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
427 # this is FLAWED. and must be fixed.
428 def unsafeAssign(self, value):
434 def onDeselect(self, session):
435 if not self.last_value == self.value:
437 self.last_value = self.value
439 yes_no_descriptions = {False: _("no"), True: _("yes")}
440 class ConfigYesNo(ConfigBoolean):
441 def __init__(self, default = False):
442 ConfigBoolean.__init__(self, default = default, descriptions = yes_no_descriptions)
444 on_off_descriptions = {False: _("off"), True: _("on")}
445 class ConfigOnOff(ConfigBoolean):
446 def __init__(self, default = False):
447 ConfigBoolean.__init__(self, default = default, descriptions = on_off_descriptions)
449 enable_disable_descriptions = {False: _("disable"), True: _("enable")}
450 class ConfigEnableDisable(ConfigBoolean):
451 def __init__(self, default = False):
452 ConfigBoolean.__init__(self, default = default, descriptions = enable_disable_descriptions)
454 class ConfigDateTime(ConfigElement):
455 def __init__(self, default, formatstring, increment = 86400):
456 ConfigElement.__init__(self)
457 self.increment = increment
458 self.formatstring = formatstring
459 self.value = self.last_value = self.default = int(default)
461 def handleKey(self, key):
463 self.value = self.value - self.increment
464 elif key == KEY_RIGHT:
465 self.value = self.value + self.increment
466 elif key == KEY_HOME or key == KEY_END:
467 self.value = self.default
470 return strftime(self.formatstring, localtime(self.value))
472 def getMulti(self, selected):
473 return ("text", strftime(self.formatstring, localtime(self.value)))
475 def fromstring(self, val):
478 # *THE* mighty config element class
480 # allows you to store/edit a sequence of values.
481 # can be used for IP-addresses, dates, plain integers, ...
482 # several helper exist to ease this up a bit.
484 class ConfigSequence(ConfigElement):
485 def __init__(self, seperator, limits, default, censor_char = ""):
486 ConfigElement.__init__(self)
487 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
488 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
489 #assert isinstance(default, list), "default must be a list"
490 #assert isinstance(default[0], int), "list must contain numbers"
491 #assert len(default) == len(limits), "length must match"
494 self.seperator = seperator
496 self.censor_char = censor_char
498 self.last_value = self.default = default
499 self.value = copy_copy(default)
500 self.endNotifier = None
505 for i in self._value:
506 max_pos += len(str(self.limits[num][1]))
508 if self._value[num] < self.limits[num][0]:
509 self._value[num] = self.limits[num][0]
511 if self._value[num] > self.limits[num][1]:
512 self._value[num] = self.limits[num][1]
516 if self.marked_pos >= max_pos:
518 for x in self.endNotifier:
520 self.marked_pos = max_pos - 1
522 if self.marked_pos < 0:
525 def validatePos(self):
526 if self.marked_pos < 0:
529 total_len = sum([len(str(x[1])) for x in self.limits])
531 if self.marked_pos >= total_len:
532 self.marked_pos = total_len - 1
534 def addEndNotifier(self, notifier):
535 if self.endNotifier is None:
536 self.endNotifier = []
537 self.endNotifier.append(notifier)
539 def handleKey(self, key):
544 elif key == KEY_RIGHT:
548 elif key == KEY_HOME:
555 for i in self._value:
556 max_pos += len(str(self.limits[num][1]))
558 self.marked_pos = max_pos - 1
561 elif key in KEY_NUMBERS or key == KEY_ASCII:
563 code = getPrevAsciiCode()
564 if code < 48 or code > 57:
568 number = getKeyNumber(key)
570 block_len = [len(str(x[1])) for x in self.limits]
571 total_len = sum(block_len)
575 block_len_total = [0, ]
577 pos += block_len[blocknumber]
578 block_len_total.append(pos)
579 if pos - 1 >= self.marked_pos:
584 # length of numberblock
585 number_len = len(str(self.limits[blocknumber][1]))
587 # position in the block
588 posinblock = self.marked_pos - block_len_total[blocknumber]
590 oldvalue = self._value[blocknumber]
591 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
592 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
594 self._value[blocknumber] = newvalue
602 mPos = self.marked_pos
604 for i in self._value:
605 if value: #fixme no heading separator possible
606 value += self.seperator
607 if mPos >= len(value) - 1:
609 if self.censor_char == "":
610 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
612 value += (self.censor_char * len(str(self.limits[num][1])))
617 (value, mPos) = self.genText()
620 def getMulti(self, selected):
621 (value, mPos) = self.genText()
622 # only mark cursor when we are selected
623 # (this code is heavily ink optimized!)
625 return ("mtext"[1-selected:], value, [mPos])
627 return ("text", value)
629 def tostring(self, val):
630 return self.seperator.join([self.saveSingle(x) for x in val])
632 def saveSingle(self, v):
635 def fromstring(self, value):
636 return [int(x) for x in value.split(self.seperator)]
638 def onDeselect(self, session):
639 if self.last_value != self._value:
641 self.last_value = copy_copy(self._value)
643 ip_limits = [(0,255),(0,255),(0,255),(0,255)]
644 class ConfigIP(ConfigSequence):
645 def __init__(self, default, auto_jump = False):
646 ConfigSequence.__init__(self, seperator = ".", limits = ip_limits, default = default)
647 self.block_len = [len(str(x[1])) for x in self.limits]
648 self.marked_block = 0
649 self.overwrite = True
650 self.auto_jump = auto_jump
652 def handleKey(self, key):
654 if self.marked_block > 0:
655 self.marked_block -= 1
656 self.overwrite = True
658 elif key == KEY_RIGHT:
659 if self.marked_block < len(self.limits)-1:
660 self.marked_block += 1
661 self.overwrite = True
663 elif key == KEY_HOME:
664 self.marked_block = 0
665 self.overwrite = True
668 self.marked_block = len(self.limits)-1
669 self.overwrite = True
671 elif key in KEY_NUMBERS or key == KEY_ASCII:
673 code = getPrevAsciiCode()
674 if code < 48 or code > 57:
678 number = getKeyNumber(key)
679 oldvalue = self._value[self.marked_block]
682 self._value[self.marked_block] = number
683 self.overwrite = False
686 newvalue = oldvalue + number
687 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
688 self.handleKey(KEY_RIGHT)
692 self._value[self.marked_block] = newvalue
694 if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
695 self.handleKey(KEY_RIGHT)
703 for i in self._value:
704 block_strlen.append(len(str(i)))
706 value += self.seperator
708 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
709 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
710 mBlock = range(leftPos, rightPos)
711 return (value, mBlock)
713 def getMulti(self, selected):
714 (value, mBlock) = self.genText()
716 return ("mtext"[1-selected:], value, mBlock)
718 return ("text", value)
720 def getHTML(self, id):
721 # we definitely don't want leading zeros
722 return '.'.join(["%d" % d for d in self.value])
724 mac_limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)]
725 class ConfigMAC(ConfigSequence):
726 def __init__(self, default):
727 ConfigSequence.__init__(self, seperator = ":", limits = mac_limits, default = default)
729 class ConfigPosition(ConfigSequence):
730 def __init__(self, default, args):
731 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
733 clock_limits = [(0,23),(0,59)]
734 class ConfigClock(ConfigSequence):
735 def __init__(self, default):
736 t = localtime(default)
737 ConfigSequence.__init__(self, seperator = ":", limits = clock_limits, default = [t.tm_hour, t.tm_min])
740 # Check if Minutes maxed out
741 if self._value[1] == 59:
742 # Increment Hour, reset Minutes
743 if self._value[0] < 23:
755 # Check if Minutes is minimum
756 if self._value[1] == 0:
757 # Decrement Hour, set Minutes to 59
758 if self._value[0] > 0:
769 integer_limits = (0, 9999999999)
770 class ConfigInteger(ConfigSequence):
771 def __init__(self, default, limits = integer_limits):
772 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
774 # you need to override this to do input validation
775 def setValue(self, value):
776 self._value = [value]
780 return self._value[0]
782 value = property(getValue, setValue)
784 def fromstring(self, value):
787 def tostring(self, value):
790 class ConfigPIN(ConfigInteger):
791 def __init__(self, default, len = 4, censor = ""):
792 assert isinstance(default, int), "ConfigPIN default must be an integer"
795 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
801 class ConfigFloat(ConfigSequence):
802 def __init__(self, default, limits):
803 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
806 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
808 float = property(getFloat)
810 # an editable text...
811 class ConfigText(ConfigElement, NumericalTextInput):
812 def __init__(self, default = "", fixed_size = True, visible_width = False):
813 ConfigElement.__init__(self)
814 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
817 self.allmarked = (default != "")
818 self.fixed_size = fixed_size
819 self.visible_width = visible_width
821 self.overwrite = fixed_size
822 self.help_window = None
823 self.value = self.last_value = self.default = default
825 def validateMarker(self):
826 textlen = len(self.text)
828 if self.marked_pos > textlen-1:
829 self.marked_pos = textlen-1
831 if self.marked_pos > textlen:
832 self.marked_pos = textlen
833 if self.marked_pos < 0:
835 if self.visible_width:
836 if self.marked_pos < self.offset:
837 self.offset = self.marked_pos
838 if self.marked_pos >= self.offset + self.visible_width:
839 if self.marked_pos == textlen:
840 self.offset = self.marked_pos - self.visible_width
842 self.offset = self.marked_pos - self.visible_width + 1
843 if self.offset > 0 and self.offset + self.visible_width > textlen:
844 self.offset = max(0, len - self.visible_width)
846 def insertChar(self, ch, pos, owr):
847 if owr or self.overwrite:
848 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
849 elif self.fixed_size:
850 self.text = self.text[0:pos] + ch + self.text[pos:-1]
852 self.text = self.text[0:pos] + ch + self.text[pos:]
854 def deleteChar(self, pos):
855 if not self.fixed_size:
856 self.text = self.text[0:pos] + self.text[pos + 1:]
858 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
860 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
862 def deleteAllChars(self):
864 self.text = " " * len(self.text)
869 def handleKey(self, key):
870 # this will no change anything on the value itself
871 # so we can handle it here in gui element
872 if key == KEY_DELETE:
875 self.deleteAllChars()
876 self.allmarked = False
878 self.deleteChar(self.marked_pos)
879 if self.fixed_size and self.overwrite:
881 elif key == KEY_BACKSPACE:
884 self.deleteAllChars()
885 self.allmarked = False
886 elif self.marked_pos > 0:
887 self.deleteChar(self.marked_pos-1)
888 if not self.fixed_size and self.offset > 0:
891 elif key == KEY_LEFT:
894 self.marked_pos = len(self.text)
895 self.allmarked = False
898 elif key == KEY_RIGHT:
902 self.allmarked = False
905 elif key == KEY_HOME:
907 self.allmarked = False
911 self.allmarked = False
912 self.marked_pos = len(self.text)
913 elif key == KEY_TOGGLEOW:
915 self.overwrite = not self.overwrite
916 elif key == KEY_ASCII:
918 newChar = unichr(getPrevAsciiCode())
919 if not self.useableChars or newChar in self.useableChars:
921 self.deleteAllChars()
922 self.allmarked = False
923 self.insertChar(newChar, self.marked_pos, False)
925 elif key in KEY_NUMBERS:
926 owr = self.lastKey == getKeyNumber(key)
927 newChar = self.getKey(getKeyNumber(key))
929 self.deleteAllChars()
930 self.allmarked = False
931 self.insertChar(newChar, self.marked_pos, owr)
932 elif key == KEY_TIMEOUT:
935 self.help_window.update(self)
939 self.help_window.update(self)
940 self.validateMarker()
945 self.validateMarker()
949 return self.text.encode("utf-8")
951 def setValue(self, val):
953 self.text = val.decode("utf-8")
954 except UnicodeDecodeError:
955 self.text = val.decode("utf-8", "ignore")
958 value = property(getValue, setValue)
959 _value = property(getValue, setValue)
962 return self.text.encode("utf-8")
964 def getMulti(self, selected):
965 if self.visible_width:
967 mark = range(0, min(self.visible_width, len(self.text)))
969 mark = [self.marked_pos-self.offset]
970 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
973 mark = range(0, len(self.text))
975 mark = [self.marked_pos]
976 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
978 def onSelect(self, session):
979 self.allmarked = (self.value != "")
980 if session is not None:
981 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
982 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
983 self.help_window.show()
985 def onDeselect(self, session):
989 session.deleteDialog(self.help_window)
990 self.help_window = None
991 if not self.last_value == self.value:
993 self.last_value = self.value
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)
1065 value = property(getValue, setValue)
1066 _value = property(getValue, setValue)
1068 def isChanged(self):
1069 sv = self.saved_value
1070 strv = self.tostring(self.value)
1071 if sv is None and strv == self.default:
1076 pos = len(self.text) - self.marked_pos
1077 self.text = self.text.lstrip("0")
1080 if pos > len(self.text):
1083 self.marked_pos = len(self.text) - pos
1085 def handleKey(self, key):
1086 if key in KEY_NUMBERS or key == KEY_ASCII:
1087 if key == KEY_ASCII:
1088 ascii = getPrevAsciiCode()
1089 if not (48 <= ascii <= 57):
1092 ascii = getKeyNumber(key) + 48
1093 newChar = unichr(ascii)
1095 self.deleteAllChars()
1096 self.allmarked = False
1097 self.insertChar(newChar, self.marked_pos, False)
1098 self.marked_pos += 1
1100 ConfigText.handleKey(self, key)
1103 def onSelect(self, session):
1104 self.allmarked = (self.value != "")
1106 def onDeselect(self, session):
1109 if not self.last_value == self.value:
1111 self.last_value = self.value
1113 class ConfigSearchText(ConfigText):
1114 def __init__(self, default = "", fixed_size = False, visible_width = False):
1115 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1116 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = True)
1118 class ConfigDirectory(ConfigText):
1119 def __init__(self, default="", visible_width=60):
1120 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
1122 def handleKey(self, key):
1129 return ConfigText.getValue(self)
1131 def setValue(self, val):
1134 ConfigText.setValue(self, val)
1136 def getMulti(self, selected):
1138 return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
1140 return ConfigText.getMulti(self, selected)
1142 def onSelect(self, session):
1143 self.allmarked = (self.value != "")
1146 class ConfigSlider(ConfigElement):
1147 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
1148 ConfigElement.__init__(self)
1149 self.value = self.last_value = self.default = default
1150 self.min = limits[0]
1151 self.max = limits[1]
1152 self.increment = increment
1154 def checkValues(self):
1155 if self.value < self.min:
1156 self.value = self.min
1158 if self.value > self.max:
1159 self.value = self.max
1161 def handleKey(self, key):
1163 self.value -= self.increment
1164 elif key == KEY_RIGHT:
1165 self.value += self.increment
1166 elif key == KEY_HOME:
1167 self.value = self.min
1168 elif key == KEY_END:
1169 self.value = self.max
1175 return "%d / %d" % (self.value, self.max)
1177 def getMulti(self, selected):
1179 return ("slider", self.value, self.max)
1181 def fromstring(self, value):
1184 # a satlist. in fact, it's a ConfigSelection.
1185 class ConfigSatlist(ConfigSelection):
1186 def __init__(self, list, default = None):
1187 if default is not None:
1188 default = str(default)
1189 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1191 def getOrbitalPosition(self):
1192 if self.value == "":
1194 return int(self.value)
1196 orbital_position = property(getOrbitalPosition)
1198 class ConfigSet(ConfigElement):
1199 def __init__(self, choices, default = []):
1200 ConfigElement.__init__(self)
1201 if isinstance(choices, list):
1203 self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
1205 assert False, "ConfigSet choices must be a list!"
1210 self.last_value = self.default = default
1211 self.value = default[:]
1213 def toggleChoice(self, choice):
1216 value.remove(choice)
1218 value.append(choice)
1222 def handleKey(self, key):
1223 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1225 self.toggleChoice(self.choices[self.pos])
1226 elif key == KEY_LEFT:
1228 self.pos = len(self.choices)-1
1231 elif key == KEY_RIGHT:
1232 if self.pos >= len(self.choices)-1:
1236 elif key in (KEY_HOME, KEY_END):
1239 def genString(self, lst):
1242 res += self.description[x]+" "
1246 return self.genString(self.value)
1248 def getMulti(self, selected):
1249 if not selected or self.pos == -1:
1250 return ("text", self.genString(self.value))
1253 ch = self.choices[self.pos]
1254 mem = ch in self.value
1259 val1 = self.genString(tmp[:ind])
1260 val2 = " "+self.genString(tmp[ind+1:])
1262 chstr = " "+self.description[ch]+" "
1264 chstr = "("+self.description[ch]+")"
1265 len_val1 = len(val1)
1266 return ("mtext", val1+chstr+val2, range(len_val1, len_val1 + len(chstr)))
1268 def onDeselect(self, session):
1270 if not self.last_value == self.value:
1272 self.last_value = self.value[:]
1274 def tostring(self, value):
1277 def fromstring(self, val):
1280 description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
1282 class ConfigLocations(ConfigElement):
1283 def __init__(self, default = [], visible_width = False):
1284 ConfigElement.__init__(self)
1285 self.visible_width = visible_width
1287 self.default = default
1289 self.mountpoints = []
1290 self.value = default[:]
1292 def setValue(self, value):
1293 locations = self.locations
1294 loc = [x[0] for x in locations if x[3]]
1295 add = [x for x in value if not x in loc]
1296 diff = add + [x for x in loc if not x in value]
1297 locations = [x for x in locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1298 locations.sort(key = lambda x: x[0])
1299 self.locations = locations
1303 self.checkChangedMountpoints()
1304 locations = self.locations
1307 return [x[0] for x in locations if x[3]]
1309 value = property(getValue, setValue)
1311 def tostring(self, value):
1314 def fromstring(self, val):
1318 sv = self.saved_value
1322 tmp = self.fromstring(sv)
1323 locations = [[x, None, False, False] for x in tmp]
1324 self.refreshMountpoints()
1326 if fileExists(x[0]):
1327 x[1] = self.getMountpoint(x[0])
1329 self.locations = locations
1332 locations = self.locations
1333 if self.save_disabled or not locations:
1334 self.saved_value = None
1336 self.saved_value = self.tostring([x[0] for x in locations])
1338 def isChanged(self):
1339 sv = self.saved_value
1340 locations = self.locations
1341 if val is None and not locations:
1343 return self.tostring([x[0] for x in locations]) != sv
1345 def addedMount(self, mp):
1346 for x in self.locations:
1349 elif x[1] == None and fileExists(x[0]):
1350 x[1] = self.getMountpoint(x[0])
1353 def removedMount(self, mp):
1354 for x in self.locations:
1358 def refreshMountpoints(self):
1359 self.mountpoints = [p.mountpoint for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1360 self.mountpoints.sort(key = lambda x: -len(x))
1362 def checkChangedMountpoints(self):
1363 oldmounts = self.mountpoints
1364 self.refreshMountpoints()
1365 newmounts = self.mountpoints
1366 if oldmounts == newmounts:
1369 if not x in newmounts:
1370 self.removedMount(x)
1372 if not x in oldmounts:
1375 def getMountpoint(self, file):
1376 file = os_path.realpath(file)+"/"
1377 for m in self.mountpoints:
1378 if file.startswith(m):
1382 def handleKey(self, key):
1386 self.pos = len(self.value)-1
1387 elif key == KEY_RIGHT:
1389 if self.pos >= len(self.value):
1391 elif key in (KEY_HOME, KEY_END):
1395 return " ".join(self.value)
1397 def getMulti(self, selected):
1399 valstr = " ".join(self.value)
1400 if self.visible_width and len(valstr) > self.visible_width:
1401 return ("text", valstr[0:self.visible_width])
1403 return ("text", valstr)
1409 for val in self.value:
1412 valstr += str(val)+" "
1416 if self.visible_width and len(valstr) > self.visible_width:
1417 if ind1+1 < self.visible_width/2:
1420 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1421 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1423 return ("mtext", valstr, range(ind1,ind2))
1425 def onDeselect(self, session):
1429 class ConfigNothing(ConfigSelection):
1431 ConfigSelection.__init__(self, choices = [("","")])
1433 # until here, 'saved_value' always had to be a *string*.
1434 # now, in ConfigSubsection, and only there, saved_value
1435 # is a dict, essentially forming a tree.
1437 # config.foo.bar=True
1438 # config.foobar=False
1441 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1444 class ConfigSubsectionContent(object):
1447 # we store a backup of the loaded configuration
1448 # data in self.stored_values, to be able to deploy
1449 # them when a new config element will be added,
1450 # so non-default values are instantly available
1452 # A list, for example:
1453 # config.dipswitches = ConfigSubList()
1454 # config.dipswitches.append(ConfigYesNo())
1455 # config.dipswitches.append(ConfigYesNo())
1456 # config.dipswitches.append(ConfigYesNo())
1457 class ConfigSubList(list, object):
1460 self.stored_values = {}
1470 def getSavedValue(self):
1472 for i, val in enumerate(self):
1473 sv = val.saved_value
1478 def setSavedValue(self, values):
1479 self.stored_values = dict(values)
1480 for (key, val) in self.stored_values.items():
1481 if int(key) < len(self):
1482 self[int(key)].saved_value = val
1484 saved_value = property(getSavedValue, setSavedValue)
1486 def append(self, item):
1488 list.append(self, item)
1489 if i in self.stored_values:
1490 item.saved_value = self.stored_values[i]
1494 return dict([(str(index), value) for index, value in enumerate(self)])
1496 # same as ConfigSubList, just as a dictionary.
1497 # care must be taken that the 'key' has a proper
1498 # str() method, because it will be used in the config
1500 class ConfigSubDict(dict, object):
1503 self.stored_values = {}
1506 for x in self.values():
1510 for x in self.values():
1513 def getSavedValue(self):
1515 for (key, val) in self.items():
1516 sv = val.saved_value
1521 def setSavedValue(self, values):
1522 self.stored_values = dict(values)
1523 for (key, val) in self.items():
1524 if str(key) in self.stored_values:
1525 val.saved_value = self.stored_values[str(key)]
1527 saved_value = property(getSavedValue, setSavedValue)
1529 def __setitem__(self, key, item):
1530 dict.__setitem__(self, key, item)
1531 if str(key) in self.stored_values:
1532 item.saved_value = self.stored_values[str(key)]
1538 # Like the classes above, just with a more "native"
1541 # some evil stuff must be done to allow instant
1542 # loading of added elements. this is why this class
1545 # we need the 'content' because we overwrite
1547 # If you don't understand this, try adding
1548 # __setattr__ to a usual exisiting class and you will.
1549 class ConfigSubsection(object):
1551 self.__dict__["content"] = ConfigSubsectionContent()
1552 self.content.items = { }
1553 self.content.stored_values = { }
1555 def __setattr__(self, name, value):
1556 if name == "saved_value":
1557 return self.setSavedValue(value)
1558 assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1559 content = self.content
1560 content.items[name] = value
1561 x = content.stored_values.get(name, None)
1563 #print "ok, now we have a new item,", name, "and have the following value for it:", x
1564 value.saved_value = x
1567 def __getattr__(self, name):
1568 return self.content.items[name]
1570 def getSavedValue(self):
1571 res = self.content.stored_values
1572 for (key, val) in self.content.items.items():
1573 sv = val.saved_value
1580 def setSavedValue(self, values):
1581 values = dict(values)
1582 self.content.stored_values = values
1583 for (key, val) in self.content.items.items():
1584 value = values.get(key, None)
1585 if value is not None:
1586 val.saved_value = value
1588 saved_value = property(getSavedValue, setSavedValue)
1591 for x in self.content.items.values():
1595 for x in self.content.items.values():
1599 return self.content.items
1601 # the root config object, which also can "pickle" (=serialize)
1602 # down the whole config tree.
1604 # we try to keep non-existing config entries, to apply them whenever
1605 # a new config entry is added to a subsection
1606 # also, non-existing config entries will be saved, so they won't be
1607 # lost when a config entry disappears.
1608 class Config(ConfigSubsection):
1610 ConfigSubsection.__init__(self)
1612 def pickle_this(self, prefix, topickle, result):
1613 for (key, val) in topickle.items():
1614 name = '.'.join((prefix, key))
1615 if isinstance(val, dict):
1616 self.pickle_this(name, val, result)
1617 elif isinstance(val, tuple):
1618 result += [name, '=', val[0], '\n']
1620 result += [name, '=', val, '\n']
1624 self.pickle_this("config", self.saved_value, result)
1625 return ''.join(result)
1627 def unpickle(self, lines, base_file=True):
1630 if not l or l[0] == '#':
1635 val = l[n+1:].strip()
1637 names = name.split('.')
1638 # if val.find(' ') != -1:
1639 # val = val[:val.find(' ')]
1643 for n in names[:-1]:
1644 base = base.setdefault(n, {})
1646 base[names[-1]] = val
1648 if not base_file: # not the initial config file..
1649 #update config.x.y.value when exist
1651 configEntry = eval(name)
1652 if configEntry is not None:
1653 configEntry.value = val
1654 except (SyntaxError, KeyError):
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, base_file=False):
1669 f = open(filename, "r")
1670 self.unpickle(f.readlines(), base_file)
1674 config.misc = ConfigSubsection()
1677 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1681 config.loadFromFile(self.CONFIG_FILE, True)
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()