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)
29 class ConfigElement(object):
32 self.saved_value = None
33 self.last_value = None
34 self.save_disabled = False
36 self.notifiers_final = []
38 self.callNotifiersOnSaveAndCancel = False
40 # you need to override this to do input validation
41 def setValue(self, value):
48 value = property(getValue, setValue)
50 # you need to override this if self.value is not a string
51 def fromstring(self, value):
54 # you can overide this for fancy default handling
58 self.value = self.default
60 self.value = self.fromstring(sv)
62 def tostring(self, value):
65 # you need to override this if str(self.value) doesn't work
67 if self.save_disabled or self.value == self.default:
68 self.saved_value = None
70 self.saved_value = self.tostring(self.value)
71 if self.callNotifiersOnSaveAndCancel:
76 if self.callNotifiersOnSaveAndCancel:
81 if sv is None and self.value == self.default:
83 return self.tostring(self.value) != sv
86 for x in self.notifiers:
89 def changedFinal(self):
90 for x in self.notifiers_final:
93 def addNotifier(self, notifier, initial_call = True, immediate_feedback = True):
94 assert callable(notifier), "notifiers must be callable"
95 if immediate_feedback:
96 self.notifiers.append(notifier)
98 self.notifiers_final.append(notifier)
100 # do we want to call the notifier
101 # - at all when adding it? (yes, though optional)
102 # - when the default is active? (yes)
103 # - when no value *yet* has been set,
104 # because no config has ever been read (currently yes)
105 # (though that's not so easy to detect.
106 # the entry could just be new.)
110 def disableSave(self):
111 self.save_disabled = True
113 def __call__(self, selected):
114 return self.getMulti(selected)
116 def onSelect(self, session):
119 def onDeselect(self, session):
120 if not self.last_value == self.value:
122 self.last_value = self.value
134 KEY_NUMBERS = range(12, 12+10)
138 def getKeyNumber(key):
139 assert key in KEY_NUMBERS
142 class choicesList(object): # XXX: we might want a better name for this
146 def __init__(self, choices, type = None):
147 object.__init__(self)
148 self.choices = choices
150 if isinstance(choices, list):
151 self.type = choicesList.LIST_TYPE_LIST
152 elif isinstance(choices, dict):
153 self.type = choicesList.LIST_TYPE_DICT
155 assert False, "choices must be dict or list!"
160 if self.type == choicesList.LIST_TYPE_LIST:
161 ret = [isinstance(x, tuple) and x[0] or x for x in self.choices]
163 ret = self.choices.keys()
167 if self.type == choicesList.LIST_TYPE_LIST:
168 ret = [isinstance(x, tuple) and x[0] or x for x in self.choices]
171 return iter(ret or [""])
174 return len(self.choices) or 1
176 def __getitem__(self, index):
177 if self.type == choicesList.LIST_TYPE_LIST:
178 ret = self.choices[index]
179 if isinstance(ret, tuple):
182 return self.choices.keys()[index]
184 def index(self, value):
185 return self.__list__().index(value)
187 def __setitem__(self, index, value):
188 if self.type == choicesList.LIST_TYPE_LIST:
189 orig = self.choices[index]
190 if isinstance(orig, tuple):
191 self.choices[index] = (value, orig[1])
193 self.choices[index] = value
195 key = self.choices.keys()[index]
196 orig = self.choices[key]
197 del self.choices[key]
198 self.choices[value] = orig
201 if self.type is choicesList.LIST_TYPE_LIST:
202 default = self.choices[0]
203 if isinstance(default, tuple):
206 default = self.choices.keys()[0]
209 class descriptionList(choicesList): # XXX: we might want a better name for this
211 if self.type == choicesList.LIST_TYPE_LIST:
212 ret = [isinstance(x, tuple) and x[1] or x for x in self.choices]
214 ret = self.choices.values()
218 return iter(self.__list__())
220 def __getitem__(self, index):
221 if self.type == choicesList.LIST_TYPE_LIST:
222 for x in self.choices:
223 if isinstance(x, tuple):
228 return str(index) # Fallback!
230 return str(self.choices.get(index, ""))
232 def __setitem__(self, index, value):
233 if self.type == choicesList.LIST_TYPE_LIST:
234 i = self.index(index)
235 orig = self.choices[i]
236 if isinstance(orig, tuple):
237 self.choices[i] = (orig[0], value)
239 self.choices[i] = value
241 self.choices[index] = value
244 # ConfigSelection is a "one of.."-type.
245 # it has the "choices", usually a list, which contains
246 # (id, desc)-tuples (or just only the ids, in case the id
247 # will be used as description)
249 # all ids MUST be plain strings.
251 class ConfigSelection(ConfigElement):
252 def __init__(self, choices, default = None):
253 ConfigElement.__init__(self)
254 self.choices = choicesList(choices)
257 default = self.choices.default()
259 self.default = self._value = self.last_value = default
262 def setChoices(self, choices, default = None):
263 self.choices = choicesList(choices)
266 default = self.choices.default()
268 if self.value not in self.choices:
271 def setValue(self, value):
272 if value in self.choices:
275 self._value = self.default
278 def tostring(self, val):
284 def setCurrentText(self, text):
285 i = self.choices.index(self.value)
286 self.choices[i] = text
287 self.description[text] = text
290 value = property(getValue, setValue)
293 return self.choices.index(self.value)
295 index = property(getIndex)
298 def handleKey(self, key):
299 nchoices = len(self.choices)
300 i = self.choices.index(self.value)
302 self.value = self.choices[(i + nchoices - 1) % nchoices]
303 elif key == KEY_RIGHT:
304 self.value = self.choices[(i + 1) % nchoices]
305 elif key == KEY_HOME:
306 self.value = self.choices[0]
308 self.value = self.choices[nchoices - 1]
310 def selectNext(self):
311 nchoices = len(self.choices)
312 i = self.choices.index(self.value)
313 self.value = self.choices[(i + 1) % nchoices]
316 descr = self.description[self.value]
321 def getMulti(self, selected):
322 descr = self.description[self.value]
324 return ("text", _(descr))
325 return ("text", descr)
328 def getHTML(self, id):
330 for v in self.choices:
331 descr = self.description[v]
333 checked = 'checked="checked" '
336 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + descr + "</input></br>\n"
339 def unsafeAssign(self, value):
340 # setValue does check if value is in choices. This is safe enough.
343 description = property(lambda self: descriptionList(self.choices.choices, self.choices.type))
347 # several customized versions exist for different
350 boolean_descriptions = {False: "false", True: "true"}
351 class ConfigBoolean(ConfigElement):
352 def __init__(self, default = False, descriptions = boolean_descriptions):
353 ConfigElement.__init__(self)
354 self.descriptions = descriptions
355 self.value = self.last_value = self.default = default
357 def handleKey(self, key):
358 if key in [KEY_LEFT, KEY_RIGHT]:
359 self.value = not self.value
360 elif key == KEY_HOME:
366 descr = self.descriptions[self.value]
371 def getMulti(self, selected):
372 descr = self.descriptions[self.value]
374 return ("text", _(descr))
375 return ("text", descr)
377 def tostring(self, value):
383 def fromstring(self, val):
389 def getHTML(self, id):
391 checked = ' checked="checked"'
394 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
396 # this is FLAWED. and must be fixed.
397 def unsafeAssign(self, value):
403 def onDeselect(self, session):
404 if not self.last_value == self.value:
406 self.last_value = self.value
408 yes_no_descriptions = {False: _("no"), True: _("yes")}
409 class ConfigYesNo(ConfigBoolean):
410 def __init__(self, default = False):
411 ConfigBoolean.__init__(self, default = default, descriptions = yes_no_descriptions)
413 on_off_descriptions = {False: _("off"), True: _("on")}
414 class ConfigOnOff(ConfigBoolean):
415 def __init__(self, default = False):
416 ConfigBoolean.__init__(self, default = default, descriptions = on_off_descriptions)
418 enable_disable_descriptions = {False: _("disable"), True: _("enable")}
419 class ConfigEnableDisable(ConfigBoolean):
420 def __init__(self, default = False):
421 ConfigBoolean.__init__(self, default = default, descriptions = enable_disable_descriptions)
423 class ConfigDateTime(ConfigElement):
424 def __init__(self, default, formatstring, increment = 86400):
425 ConfigElement.__init__(self)
426 self.increment = increment
427 self.formatstring = formatstring
428 self.value = self.last_value = self.default = int(default)
430 def handleKey(self, key):
432 self.value = self.value - self.increment
433 elif key == KEY_RIGHT:
434 self.value = self.value + self.increment
435 elif key == KEY_HOME or key == KEY_END:
436 self.value = self.default
439 return strftime(self.formatstring, localtime(self.value))
441 def getMulti(self, selected):
442 return ("text", strftime(self.formatstring, localtime(self.value)))
444 def fromstring(self, val):
447 # *THE* mighty config element class
449 # allows you to store/edit a sequence of values.
450 # can be used for IP-addresses, dates, plain integers, ...
451 # several helper exist to ease this up a bit.
453 class ConfigSequence(ConfigElement):
454 def __init__(self, seperator, limits, default, censor_char = ""):
455 ConfigElement.__init__(self)
456 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
457 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
458 #assert isinstance(default, list), "default must be a list"
459 #assert isinstance(default[0], int), "list must contain numbers"
460 #assert len(default) == len(limits), "length must match"
463 self.seperator = seperator
465 self.censor_char = censor_char
467 self.last_value = self.default = default
468 self.value = copy_copy(default)
469 self.endNotifier = None
474 for i in self._value:
475 max_pos += len(str(self.limits[num][1]))
477 if self._value[num] < self.limits[num][0]:
478 self._value[num] = self.limits[num][0]
480 if self._value[num] > self.limits[num][1]:
481 self._value[num] = self.limits[num][1]
485 if self.marked_pos >= max_pos:
487 for x in self.endNotifier:
489 self.marked_pos = max_pos - 1
491 if self.marked_pos < 0:
494 def validatePos(self):
495 if self.marked_pos < 0:
498 total_len = sum([len(str(x[1])) for x in self.limits])
500 if self.marked_pos >= total_len:
501 self.marked_pos = total_len - 1
503 def addEndNotifier(self, notifier):
504 if endNotifier is None:
506 self.endNotifier.append(notifier)
508 def handleKey(self, key):
524 for i in self._value:
525 max_pos += len(str(self.limits[num][1]))
527 self.marked_pos = max_pos - 1
530 if key in KEY_NUMBERS or key == KEY_ASCII:
532 code = getPrevAsciiCode()
533 if code < 48 or code > 57:
537 number = getKeyNumber(key)
540 for x in self.limits:
541 block_len.append(len(str(x[1])))
543 total_len = sum(block_len)
547 block_len_total = [0, ]
549 pos += block_len[blocknumber]
550 block_len_total.append(pos)
551 if pos - 1 >= self.marked_pos:
556 # length of numberblock
557 number_len = len(str(self.limits[blocknumber][1]))
559 # position in the block
560 posinblock = self.marked_pos - block_len_total[blocknumber]
562 oldvalue = self._value[blocknumber]
563 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
564 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
566 self._value[blocknumber] = newvalue
574 mPos = self.marked_pos
576 for i in self._value:
577 if len(value): #fixme no heading separator possible
578 value += self.seperator
579 if mPos >= len(value) - 1:
581 if self.censor_char == "":
582 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
584 value += (self.censor_char * len(str(self.limits[num][1])))
589 (value, mPos) = self.genText()
592 def getMulti(self, selected):
593 (value, mPos) = self.genText()
594 # only mark cursor when we are selected
595 # (this code is heavily ink optimized!)
597 return ("mtext"[1-selected:], value, [mPos])
599 return ("text", value)
601 def tostring(self, val):
602 return self.seperator.join([self.saveSingle(x) for x in val])
604 def saveSingle(self, v):
607 def fromstring(self, value):
608 return [int(x) for x in value.split(self.seperator)]
610 def onDeselect(self, session):
611 if self.last_value != self._value:
613 self.last_value = copy_copy(self._value)
615 ip_limits = [(0,255),(0,255),(0,255),(0,255)]
616 class ConfigIP(ConfigSequence):
617 def __init__(self, default, auto_jump = False):
618 ConfigSequence.__init__(self, seperator = ".", limits = ip_limits, default = default)
620 for x in self.limits:
621 self.block_len.append(len(str(x[1])))
622 self.marked_block = 0
623 self.overwrite = True
624 self.auto_jump = auto_jump
626 def handleKey(self, key):
629 if self.marked_block > 0:
630 self.marked_block -= 1
631 self.overwrite = True
634 if self.marked_block < len(self.limits)-1:
635 self.marked_block += 1
636 self.overwrite = True
639 self.marked_block = 0
640 self.overwrite = True
643 self.marked_block = len(self.limits)-1
644 self.overwrite = True
646 if key in KEY_NUMBERS or key == KEY_ASCII:
648 code = getPrevAsciiCode()
649 if code < 48 or code > 57:
653 number = getKeyNumber(key)
654 oldvalue = self._value[self.marked_block]
657 self._value[self.marked_block] = number
658 self.overwrite = False
661 newvalue = oldvalue + number
662 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
663 self.handleKey(KEY_RIGHT)
667 self._value[self.marked_block] = newvalue
669 if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
670 self.handleKey(KEY_RIGHT)
678 for i in self._value:
679 block_strlen.append(len(str(i)))
681 value += self.seperator
683 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
684 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
685 mBlock = range(leftPos, rightPos)
686 return (value, mBlock)
688 def getMulti(self, selected):
689 (value, mBlock) = self.genText()
691 return ("mtext"[1-selected:], value, mBlock)
693 return ("text", value)
695 def getHTML(self, id):
696 # we definitely don't want leading zeros
697 return '.'.join(["%d" % d for d in self.value])
699 mac_limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)]
700 class ConfigMAC(ConfigSequence):
701 def __init__(self, default):
702 ConfigSequence.__init__(self, seperator = ":", limits = mac_limits, default = default)
704 class ConfigPosition(ConfigSequence):
705 def __init__(self, default, args):
706 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
708 clock_limits = [(0,23),(0,59)]
709 class ConfigClock(ConfigSequence):
710 def __init__(self, default):
711 t = localtime(default)
712 ConfigSequence.__init__(self, seperator = ":", limits = clock_limits, default = [t.tm_hour, t.tm_min])
715 # Check if Minutes maxed out
716 if self._value[1] == 59:
717 # Increment Hour, reset Minutes
718 if self._value[0] < 23:
730 # Check if Minutes is minimum
731 if self._value[1] == 0:
732 # Decrement Hour, set Minutes to 59
733 if self._value[0] > 0:
744 integer_limits = (0, 9999999999)
745 class ConfigInteger(ConfigSequence):
746 def __init__(self, default, limits = integer_limits):
747 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
749 # you need to override this to do input validation
750 def setValue(self, value):
751 self._value = [value]
755 return self._value[0]
757 value = property(getValue, setValue)
759 def fromstring(self, value):
762 def tostring(self, value):
765 class ConfigPIN(ConfigInteger):
766 def __init__(self, default, len = 4, censor = ""):
767 assert isinstance(default, int), "ConfigPIN default must be an integer"
770 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
776 class ConfigFloat(ConfigSequence):
777 def __init__(self, default, limits):
778 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
781 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
783 float = property(getFloat)
785 # an editable text...
786 class ConfigText(ConfigElement, NumericalTextInput):
787 def __init__(self, default = "", fixed_size = True, visible_width = False):
788 ConfigElement.__init__(self)
789 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
792 self.allmarked = (default != "")
793 self.fixed_size = fixed_size
794 self.visible_width = visible_width
796 self.overwrite = fixed_size
797 self.help_window = None
798 self.value = self.last_value = self.default = default
800 def validateMarker(self):
802 if self.marked_pos > len(self.text)-1:
803 self.marked_pos = len(self.text)-1
805 if self.marked_pos > len(self.text):
806 self.marked_pos = len(self.text)
807 if self.marked_pos < 0:
809 if self.visible_width:
810 if self.marked_pos < self.offset:
811 self.offset = self.marked_pos
812 if self.marked_pos >= self.offset + self.visible_width:
813 if self.marked_pos == len(self.text):
814 self.offset = self.marked_pos - self.visible_width
816 self.offset = self.marked_pos - self.visible_width + 1
817 if self.offset > 0 and self.offset + self.visible_width > len(self.text):
818 self.offset = max(0, len(self.text) - self.visible_width)
820 def insertChar(self, ch, pos, owr):
821 if owr or self.overwrite:
822 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
823 elif self.fixed_size:
824 self.text = self.text[0:pos] + ch + self.text[pos:-1]
826 self.text = self.text[0:pos] + ch + self.text[pos:]
828 def deleteChar(self, pos):
829 if not self.fixed_size:
830 self.text = self.text[0:pos] + self.text[pos + 1:]
832 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
834 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
836 def deleteAllChars(self):
838 self.text = " " * len(self.text)
843 def handleKey(self, key):
844 # this will no change anything on the value itself
845 # so we can handle it here in gui element
846 if key == KEY_DELETE:
849 self.deleteAllChars()
850 self.allmarked = False
852 self.deleteChar(self.marked_pos)
853 if self.fixed_size and self.overwrite:
855 elif key == KEY_BACKSPACE:
858 self.deleteAllChars()
859 self.allmarked = False
860 elif self.marked_pos > 0:
861 self.deleteChar(self.marked_pos-1)
862 if not self.fixed_size and self.offset > 0:
865 elif key == KEY_LEFT:
868 self.marked_pos = len(self.text)
869 self.allmarked = False
872 elif key == KEY_RIGHT:
876 self.allmarked = False
879 elif key == KEY_HOME:
881 self.allmarked = False
885 self.allmarked = False
886 self.marked_pos = len(self.text)
887 elif key == KEY_TOGGLEOW:
889 self.overwrite = not self.overwrite
890 elif key == KEY_ASCII:
892 newChar = unichr(getPrevAsciiCode())
894 self.deleteAllChars()
895 self.allmarked = False
896 self.insertChar(newChar, self.marked_pos, False)
898 elif key in KEY_NUMBERS:
899 owr = self.lastKey == getKeyNumber(key)
900 newChar = self.getKey(getKeyNumber(key))
902 self.deleteAllChars()
903 self.allmarked = False
904 self.insertChar(newChar, self.marked_pos, owr)
905 elif key == KEY_TIMEOUT:
908 self.help_window.update(self)
912 self.help_window.update(self)
913 self.validateMarker()
918 self.validateMarker()
922 return self.text.encode("utf-8")
924 def setValue(self, val):
926 self.text = val.decode("utf-8")
927 except UnicodeDecodeError:
928 self.text = val.decode("utf-8", "ignore")
931 value = property(getValue, setValue)
932 _value = property(getValue, setValue)
935 return self.text.encode("utf-8")
937 def getMulti(self, selected):
938 if self.visible_width:
940 mark = range(0, min(self.visible_width, len(self.text)))
942 mark = [self.marked_pos-self.offset]
943 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
946 mark = range(0, len(self.text))
948 mark = [self.marked_pos]
949 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
951 def onSelect(self, session):
952 self.allmarked = (self.value != "")
953 if session is not None:
954 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
955 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
956 self.help_window.show()
958 def onDeselect(self, session):
962 session.deleteDialog(self.help_window)
963 self.help_window = None
964 if not self.last_value == self.value:
966 self.last_value = self.value
968 def getHTML(self, id):
969 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
971 def unsafeAssign(self, value):
972 self.value = str(value)
974 class ConfigPassword(ConfigText):
975 def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
976 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
977 self.censor_char = censor
980 def getMulti(self, selected):
981 mtext, text, mark = ConfigText.getMulti(self, selected)
983 text = len(text) * self.censor_char
984 return (mtext, text, mark)
986 def onSelect(self, session):
987 ConfigText.onSelect(self, session)
990 def onDeselect(self, session):
991 ConfigText.onDeselect(self, session)
994 class ConfigNumber(ConfigText):
995 def __init__(self, default = 0):
996 ConfigText.__init__(self, str(default), fixed_size = False)
999 return int(self.text)
1001 def setValue(self, val):
1002 self.text = str(val)
1004 value = property(getValue, setValue)
1005 _value = property(getValue, setValue)
1008 pos = len(self.text) - self.marked_pos
1009 self.text = self.text.lstrip("0")
1012 if pos > len(self.text):
1015 self.marked_pos = len(self.text) - pos
1017 def handleKey(self, key):
1018 if key in KEY_NUMBERS or key == KEY_ASCII:
1019 if key == KEY_ASCII:
1020 ascii = getPrevAsciiCode()
1021 if not (48 <= ascii <= 57):
1024 ascii = getKeyNumber(key) + 48
1025 newChar = unichr(ascii)
1027 self.deleteAllChars()
1028 self.allmarked = False
1029 self.insertChar(newChar, self.marked_pos, False)
1030 self.marked_pos += 1
1032 ConfigText.handleKey(self, key)
1035 def onSelect(self, session):
1036 self.allmarked = (self.value != "")
1038 def onDeselect(self, session):
1041 if not self.last_value == self.value:
1043 self.last_value = self.value
1045 class ConfigSearchText(ConfigText):
1046 def __init__(self, default = "", fixed_size = False, visible_width = False):
1047 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1048 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = True)
1050 class ConfigDirectory(ConfigText):
1051 def __init__(self, default="", visible_width=60):
1052 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
1053 def handleKey(self, key):
1059 return ConfigText.getValue(self)
1060 def setValue(self, val):
1063 ConfigText.setValue(self, val)
1064 def getMulti(self, selected):
1066 return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
1068 return ConfigText.getMulti(self, selected)
1071 class ConfigSlider(ConfigElement):
1072 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
1073 ConfigElement.__init__(self)
1074 self.value = self.last_value = self.default = default
1075 self.min = limits[0]
1076 self.max = limits[1]
1077 self.increment = increment
1079 def checkValues(self):
1080 if self.value < self.min:
1081 self.value = self.min
1083 if self.value > self.max:
1084 self.value = self.max
1086 def handleKey(self, key):
1088 self.value -= self.increment
1089 elif key == KEY_RIGHT:
1090 self.value += self.increment
1091 elif key == KEY_HOME:
1092 self.value = self.min
1093 elif key == KEY_END:
1094 self.value = self.max
1100 return "%d / %d" % (self.value, self.max)
1102 def getMulti(self, selected):
1104 return ("slider", self.value, self.max)
1106 def fromstring(self, value):
1109 # a satlist. in fact, it's a ConfigSelection.
1110 class ConfigSatlist(ConfigSelection):
1111 def __init__(self, list, default = None):
1112 if default is not None:
1113 default = str(default)
1114 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1116 def getOrbitalPosition(self):
1117 if self.value == "":
1119 return int(self.value)
1121 orbital_position = property(getOrbitalPosition)
1123 class ConfigSet(ConfigElement):
1124 def __init__(self, choices, default = []):
1125 ConfigElement.__init__(self)
1126 if isinstance(choices, list):
1128 self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
1130 assert False, "ConfigSet choices must be a list!"
1135 self.last_value = self.default = default
1136 self.value = default[:]
1138 def toggleChoice(self, choice):
1139 if choice in self.value:
1140 self.value.remove(choice)
1142 self.value.append(choice)
1146 def handleKey(self, key):
1147 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1149 self.toggleChoice(self.choices[self.pos])
1150 elif key == KEY_LEFT:
1153 self.pos = len(self.choices)-1
1154 elif key == KEY_RIGHT:
1156 if self.pos >= len(self.choices):
1158 elif key in [KEY_HOME, KEY_END]:
1161 def genString(self, lst):
1164 res += self.description[x]+" "
1168 return self.genString(self.value)
1170 def getMulti(self, selected):
1171 if not selected or self.pos == -1:
1172 return ("text", self.genString(self.value))
1175 ch = self.choices[self.pos]
1176 mem = ch in self.value
1181 val1 = self.genString(tmp[:ind])
1182 val2 = " "+self.genString(tmp[ind+1:])
1184 chstr = " "+self.description[ch]+" "
1186 chstr = "("+self.description[ch]+")"
1187 return ("mtext", val1+chstr+val2, range(len(val1),len(val1)+len(chstr)))
1189 def onDeselect(self, session):
1191 if not self.last_value == self.value:
1193 self.last_value = self.value[:]
1195 def tostring(self, value):
1198 def fromstring(self, val):
1201 description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
1203 class ConfigLocations(ConfigElement):
1204 def __init__(self, default = [], visible_width = False):
1205 ConfigElement.__init__(self)
1206 self.visible_width = visible_width
1208 self.default = default
1210 self.mountpoints = []
1211 harddiskmanager.on_partition_list_change.append(self.mountpointsChanged)
1212 self.value = default+[]
1214 def setValue(self, value):
1215 loc = [x[0] for x in self.locations if x[3]]
1216 add = [x for x in value if not x in loc]
1217 diff = add + [x for x in loc if not x in value]
1218 self.locations = [x for x in self.locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1219 self.locations.sort(key = lambda x: x[0])
1223 self.checkChangedMountpoints()
1224 for x in self.locations:
1226 return [x[0] for x in self.locations if x[3]]
1228 value = property(getValue, setValue)
1230 def tostring(self, value):
1233 def fromstring(self, val):
1237 sv = self.saved_value
1241 tmp = self.fromstring(sv)
1242 self.locations = [[x, None, False, False] for x in tmp]
1243 self.refreshMountpoints()
1244 for x in self.locations:
1245 if os_path.exists(x[0]):
1246 x[1] = self.getMountpoint(x[0])
1250 if self.save_disabled or self.locations == []:
1251 self.saved_value = None
1253 self.saved_value = self.tostring([x[0] for x in self.locations])
1255 def isChanged(self):
1256 sv = self.saved_value
1257 if val is None and self.locations == []:
1259 return self.tostring([x[0] for x in self.locations]) != sv
1261 def mountpointsChanged(self, action, dev):
1262 print "Mounts changed: ", action, dev
1263 mp = dev.mountpoint+"/"
1266 elif action == "remove":
1267 self.removedMount(mp)
1268 self.refreshMountpoints()
1270 def addedMount(self, mp):
1271 for x in self.locations:
1274 elif x[1] == None and os_path.exists(x[0]):
1275 x[1] = self.getMountpoint(x[0])
1278 def removedMount(self, mp):
1279 for x in self.locations:
1283 def refreshMountpoints(self):
1284 self.mountpoints = [p.mountpoint + "/" for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1285 self.mountpoints.sort(key = lambda x: -len(x))
1287 def checkChangedMountpoints(self):
1288 oldmounts = self.mountpoints
1289 self.refreshMountpoints()
1290 if oldmounts == self.mountpoints:
1293 if not x in self.mountpoints:
1294 self.removedMount(x)
1295 for x in self.mountpoints:
1296 if not x in oldmounts:
1299 def getMountpoint(self, file):
1300 file = os_path.realpath(file)+"/"
1301 for m in self.mountpoints:
1302 if file.startswith(m):
1306 def handleKey(self, key):
1310 self.pos = len(self.value)-1
1311 elif key == KEY_RIGHT:
1313 if self.pos >= len(self.value):
1315 elif key in [KEY_HOME, KEY_END]:
1319 return " ".join(self.value)
1321 def getMulti(self, selected):
1323 valstr = " ".join(self.value)
1324 if self.visible_width and len(valstr) > self.visible_width:
1325 return ("text", valstr[0:self.visible_width])
1327 return ("text", valstr)
1333 for val in self.value:
1336 valstr += str(val)+" "
1340 if self.visible_width and len(valstr) > self.visible_width:
1341 if ind1+1 < self.visible_width/2:
1344 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1345 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1347 return ("mtext", valstr, range(ind1,ind2))
1349 def onDeselect(self, session):
1353 class ConfigNothing(ConfigSelection):
1355 ConfigSelection.__init__(self, choices = [""])
1357 # until here, 'saved_value' always had to be a *string*.
1358 # now, in ConfigSubsection, and only there, saved_value
1359 # is a dict, essentially forming a tree.
1361 # config.foo.bar=True
1362 # config.foobar=False
1365 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1369 class ConfigSubsectionContent(object):
1372 # we store a backup of the loaded configuration
1373 # data in self.stored_values, to be able to deploy
1374 # them when a new config element will be added,
1375 # so non-default values are instantly available
1377 # A list, for example:
1378 # config.dipswitches = ConfigSubList()
1379 # config.dipswitches.append(ConfigYesNo())
1380 # config.dipswitches.append(ConfigYesNo())
1381 # config.dipswitches.append(ConfigYesNo())
1382 class ConfigSubList(list, object):
1384 object.__init__(self)
1386 self.stored_values = {}
1396 def getSavedValue(self):
1398 for i in range(len(self)):
1399 sv = self[i].saved_value
1404 def setSavedValue(self, values):
1405 self.stored_values = dict(values)
1406 for (key, val) in self.stored_values.items():
1407 if int(key) < len(self):
1408 self[int(key)].saved_value = val
1410 saved_value = property(getSavedValue, setSavedValue)
1412 def append(self, item):
1414 list.append(self, item)
1415 if i in self.stored_values:
1416 item.saved_value = self.stored_values[i]
1420 return dict([(str(index), value) for index, value in self.enumerate()])
1422 # same as ConfigSubList, just as a dictionary.
1423 # care must be taken that the 'key' has a proper
1424 # str() method, because it will be used in the config
1426 class ConfigSubDict(dict, object):
1428 object.__init__(self)
1430 self.stored_values = {}
1433 for x in self.values():
1437 for x in self.values():
1440 def getSavedValue(self):
1442 for (key, val) in self.items():
1443 sv = val.saved_value
1448 def setSavedValue(self, values):
1449 self.stored_values = dict(values)
1450 for (key, val) in self.items():
1451 if str(key) in self.stored_values:
1452 val = self.stored_values[str(key)]
1454 saved_value = property(getSavedValue, setSavedValue)
1456 def __setitem__(self, key, item):
1457 dict.__setitem__(self, key, item)
1458 if str(key) in self.stored_values:
1459 item.saved_value = self.stored_values[str(key)]
1465 # Like the classes above, just with a more "native"
1468 # some evil stuff must be done to allow instant
1469 # loading of added elements. this is why this class
1472 # we need the 'content' because we overwrite
1474 # If you don't understand this, try adding
1475 # __setattr__ to a usual exisiting class and you will.
1476 class ConfigSubsection(object):
1478 object.__init__(self)
1479 self.__dict__["content"] = ConfigSubsectionContent()
1480 self.content.items = { }
1481 self.content.stored_values = { }
1483 def __setattr__(self, name, value):
1484 if name == "saved_value":
1485 return self.setSavedValue(value)
1486 assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1487 self.content.items[name] = value
1488 x = self.content.stored_values.get(name, None)
1490 #print "ok, now we have a new item,", name, "and have the following value for it:", x
1491 value.saved_value = x
1494 def __getattr__(self, name):
1495 return self.content.items[name]
1497 def getSavedValue(self):
1498 res = self.content.stored_values
1499 for (key, val) in self.content.items.items():
1500 sv = val.saved_value
1507 def setSavedValue(self, values):
1508 values = dict(values)
1509 self.content.stored_values = values
1510 for (key, val) in self.content.items.items():
1511 value = values.get(key, None)
1512 if value is not None:
1513 val.saved_value = value
1515 saved_value = property(getSavedValue, setSavedValue)
1518 for x in self.content.items.values():
1522 for x in self.content.items.values():
1526 return self.content.items
1528 # the root config object, which also can "pickle" (=serialize)
1529 # down the whole config tree.
1531 # we try to keep non-existing config entries, to apply them whenever
1532 # a new config entry is added to a subsection
1533 # also, non-existing config entries will be saved, so they won't be
1534 # lost when a config entry disappears.
1535 class Config(ConfigSubsection):
1537 ConfigSubsection.__init__(self)
1539 def pickle_this(self, prefix, topickle, result):
1540 for (key, val) in topickle.items():
1541 name = ''.join((prefix, '.', key))
1542 if isinstance(val, dict):
1543 self.pickle_this(name, val, result)
1544 elif isinstance(val, tuple):
1545 result += [name, '=', val[0], '\n']
1547 result += [name, '=', val, '\n']
1551 self.pickle_this("config", self.saved_value, result)
1552 return ''.join(result)
1554 def unpickle(self, lines):
1557 if not len(l) or l[0] == '#':
1561 val = l[n+1:].strip()
1563 names = l[:n].split('.')
1564 # if val.find(' ') != -1:
1565 # val = val[:val.find(' ')]
1569 for n in names[:-1]:
1570 base = base.setdefault(n, {})
1572 base[names[-1]] = val
1574 # we inherit from ConfigSubsection, so ...
1575 #object.__setattr__(self, "saved_value", tree["config"])
1576 if "config" in tree:
1577 self.setSavedValue(tree["config"])
1579 def saveToFile(self, filename):
1580 f = open(filename, "w")
1581 f.write(self.pickle())
1584 def loadFromFile(self, filename):
1585 f = open(filename, "r")
1586 self.unpickle(f.readlines())
1590 config.misc = ConfigSubsection()
1593 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1597 config.loadFromFile(self.CONFIG_FILE)
1599 print "unable to load config (%s), assuming defaults..." % str(e)
1603 config.saveToFile(self.CONFIG_FILE)
1605 def __resolveValue(self, pickles, cmap):
1606 if cmap.has_key(pickles[0]):
1607 if len(pickles) > 1:
1608 return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
1610 return str(cmap[pickles[0]].value)
1613 def getResolvedKey(self, key):
1614 names = key.split('.')
1616 if names[0] == "config":
1617 ret=self.__resolveValue(names[1:], config.content.items)
1618 if ret and len(ret):
1620 print "getResolvedKey", key, "failed !! (Typo??)"
1623 def NoSave(element):
1624 element.disableSave()
1627 configfile = ConfigFile()
1631 def getConfigListEntry(*args):
1632 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1635 def updateConfigElement(element, newelement):
1636 newelement.value = element.value
1642 #config.bla = ConfigSubsection()
1643 #config.bla.test = ConfigYesNo()
1644 #config.nim = ConfigSubList()
1645 #config.nim.append(ConfigSubsection())
1646 #config.nim[0].bla = ConfigYesNo()
1647 #config.nim.append(ConfigSubsection())
1648 #config.nim[1].bla = ConfigYesNo()
1649 #config.nim[1].blub = ConfigYesNo()
1650 #config.arg = ConfigSubDict()
1651 #config.arg["Hello"] = ConfigYesNo()
1653 #config.arg["Hello"].handleKey(KEY_RIGHT)
1654 #config.arg["Hello"].handleKey(KEY_RIGHT)
1656 ##config.saved_value
1660 #print config.pickle()