2 from enigma import getPrevAsciiCode
3 from Tools.NumericalTextInput import NumericalTextInput
4 from Tools.Directories import resolveFilename, SCOPE_CONFIG
5 from Components.Harddisk import harddiskmanager
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):
33 self.saved_value = None
34 self.last_value = None
35 self.save_disabled = False
37 self.notifiers_final = []
39 self.callNotifiersOnSaveAndCancel = False
41 # you need to override this to do input validation
42 def setValue(self, value):
49 value = property(getValue, setValue)
51 # you need to override this if self.value is not a string
52 def fromstring(self, value):
55 # you can overide this for fancy default handling
59 self.value = self.default
61 self.value = self.fromstring(sv)
63 def tostring(self, value):
66 # you need to override this if str(self.value) doesn't work
68 if self.save_disabled or self.value == self.default:
69 self.saved_value = None
71 self.saved_value = self.tostring(self.value)
72 if self.callNotifiersOnSaveAndCancel:
77 if self.callNotifiersOnSaveAndCancel:
82 if sv is None and self.value == self.default:
84 return self.tostring(self.value) != sv
87 for x in self.notifiers:
90 def changedFinal(self):
91 for x in self.notifiers_final:
94 def addNotifier(self, notifier, initial_call = True, immediate_feedback = True):
95 assert callable(notifier), "notifiers must be callable"
96 if immediate_feedback:
97 self.notifiers.append(notifier)
99 self.notifiers_final.append(notifier)
101 # do we want to call the notifier
102 # - at all when adding it? (yes, though optional)
103 # - when the default is active? (yes)
104 # - when no value *yet* has been set,
105 # because no config has ever been read (currently yes)
106 # (though that's not so easy to detect.
107 # the entry could just be new.)
111 def disableSave(self):
112 self.save_disabled = True
114 def __call__(self, selected):
115 return self.getMulti(selected)
117 def onSelect(self, session):
120 def onDeselect(self, session):
121 if not self.last_value == self.value:
123 self.last_value = self.value
135 KEY_NUMBERS = range(12, 12+10)
139 def getKeyNumber(key):
140 assert key in KEY_NUMBERS
144 # ConfigSelection is a "one of.."-type.
145 # it has the "choices", usually a list, which contains
146 # (id, desc)-tuples (or just only the ids, in case the id
147 # will be used as description)
149 # all ids MUST be plain strings.
151 class ConfigSelection(ConfigElement):
152 def __init__(self, choices, default = None):
153 ConfigElement.__init__(self)
155 self.setChoices(choices, default)
156 self.last_value = self._value
158 def setChoices(self, choices, default = None):
160 self.description = {}
162 if isinstance(choices, list):
164 if isinstance(x, tuple):
165 self.choices.append(x[0])
166 self.description[x[0]] = x[1]
168 self.choices.append(x)
169 self.description[x] = x
170 elif isinstance(choices, dict):
171 for (key, val) in choices.items():
172 self.choices.append(key)
173 self.description[key] = val
175 assert False, "ConfigSelection choices must be dict or list!"
177 #assert len(self.choices), "you can't have an empty configselection"
178 if len(self.choices) == 0:
180 self.description[""] = ""
183 default = self.choices[0]
185 assert default in self.choices, "default must be in choice list, but " + repr(default) + " is not!"
186 for x in self.choices:
187 assert isinstance(x, str), "ConfigSelection choices must be strings"
189 self.default = default
191 if self.value == None or not self.value in self.choices:
194 def setValue(self, value):
195 if value in self.choices:
198 self._value = self.default
202 def tostring(self, val):
208 def setCurrentText(self, text):
209 i = self.choices.index(self.value)
210 del self.description[self.choices[i]]
211 self.choices[i] = text
212 self.description[text] = text
215 value = property(getValue, setValue)
218 return self.choices.index(self.value)
220 index = property(getIndex)
223 def handleKey(self, key):
224 nchoices = len(self.choices)
225 i = self.choices.index(self.value)
227 self.value = self.choices[(i + nchoices - 1) % nchoices]
228 elif key == KEY_RIGHT:
229 self.value = self.choices[(i + 1) % nchoices]
230 elif key == KEY_HOME:
231 self.value = self.choices[0]
233 self.value = self.choices[nchoices - 1]
235 def selectNext(self):
236 nchoices = len(self.choices)
237 i = self.choices.index(self.value)
238 self.value = self.choices[(i + 1) % nchoices]
241 descr = self.description[self.value]
246 def getMulti(self, selected):
247 descr = self.description[self.value]
249 return ("text", _(descr))
250 return ("text", descr)
253 def getHTML(self, id):
255 for v in self.choices:
257 checked = 'checked="checked" '
260 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n"
263 def unsafeAssign(self, value):
264 # setValue does check if value is in choices. This is safe enough.
269 # several customized versions exist for different
272 class ConfigBoolean(ConfigElement):
273 def __init__(self, default = False, descriptions = {False: "false", True: "true"}):
274 ConfigElement.__init__(self)
275 self.descriptions = descriptions
276 self.value = self.last_value = self.default = default
278 def handleKey(self, key):
279 if key in [KEY_LEFT, KEY_RIGHT]:
280 self.value = not self.value
281 elif key == KEY_HOME:
287 descr = self.descriptions[self.value]
292 def getMulti(self, selected):
293 descr = self.descriptions[self.value]
295 return ("text", _(descr))
296 return ("text", descr)
298 def tostring(self, value):
304 def fromstring(self, val):
310 def getHTML(self, id):
312 checked = ' checked="checked"'
315 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
317 # this is FLAWED. and must be fixed.
318 def unsafeAssign(self, value):
324 def onDeselect(self, session):
325 if not self.last_value == self.value:
327 self.last_value = self.value
329 class ConfigYesNo(ConfigBoolean):
330 def __init__(self, default = False):
331 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")})
333 class ConfigOnOff(ConfigBoolean):
334 def __init__(self, default = False):
335 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")})
337 class ConfigEnableDisable(ConfigBoolean):
338 def __init__(self, default = False):
339 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")})
341 class ConfigDateTime(ConfigElement):
342 def __init__(self, default, formatstring, increment = 86400):
343 ConfigElement.__init__(self)
344 self.increment = increment
345 self.formatstring = formatstring
346 self.value = self.last_value = self.default = int(default)
348 def handleKey(self, key):
350 self.value = self.value - self.increment
351 elif key == KEY_RIGHT:
352 self.value = self.value + self.increment
353 elif key == KEY_HOME or key == KEY_END:
354 self.value = self.default
357 return time.strftime(self.formatstring, time.localtime(self.value))
359 def getMulti(self, selected):
360 return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
362 def fromstring(self, val):
365 # *THE* mighty config element class
367 # allows you to store/edit a sequence of values.
368 # can be used for IP-addresses, dates, plain integers, ...
369 # several helper exist to ease this up a bit.
371 class ConfigSequence(ConfigElement):
372 def __init__(self, seperator, limits, censor_char = "", default = None):
373 ConfigElement.__init__(self)
374 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
375 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
376 #assert isinstance(default, list), "default must be a list"
377 #assert isinstance(default[0], int), "list must contain numbers"
378 #assert len(default) == len(limits), "length must match"
381 self.seperator = seperator
383 self.censor_char = censor_char
385 self.default = default
386 self.value = copy.copy(default)
387 self.last_value = copy.copy(default)
389 self.endNotifier = []
394 for i in self._value:
395 max_pos += len(str(self.limits[num][1]))
397 if self._value[num] < self.limits[num][0]:
398 self._value[num] = self.limits[num][0]
400 if self._value[num] > self.limits[num][1]:
401 self._value[num] = self.limits[num][1]
405 if self.marked_pos >= max_pos:
406 for x in self.endNotifier:
408 self.marked_pos = max_pos - 1
410 if self.marked_pos < 0:
413 def validatePos(self):
414 if self.marked_pos < 0:
417 total_len = sum([len(str(x[1])) for x in self.limits])
419 if self.marked_pos >= total_len:
420 self.marked_pos = total_len - 1
422 def addEndNotifier(self, notifier):
423 self.endNotifier.append(notifier)
425 def handleKey(self, key):
441 for i in self._value:
442 max_pos += len(str(self.limits[num][1]))
444 self.marked_pos = max_pos - 1
447 if key in KEY_NUMBERS or key == KEY_ASCII:
449 code = getPrevAsciiCode()
450 if code < 48 or code > 57:
454 number = getKeyNumber(key)
457 for x in self.limits:
458 block_len.append(len(str(x[1])))
460 total_len = sum(block_len)
464 block_len_total = [0, ]
466 pos += block_len[blocknumber]
467 block_len_total.append(pos)
468 if pos - 1 >= self.marked_pos:
473 # length of numberblock
474 number_len = len(str(self.limits[blocknumber][1]))
476 # position in the block
477 posinblock = self.marked_pos - block_len_total[blocknumber]
479 oldvalue = self._value[blocknumber]
480 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
481 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
483 self._value[blocknumber] = newvalue
491 mPos = self.marked_pos
493 for i in self._value:
494 if len(value): #fixme no heading separator possible
495 value += self.seperator
496 if mPos >= len(value) - 1:
499 if self.censor_char == "":
500 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
502 value += (self.censor_char * len(str(self.limits[num][1])))
507 (value, mPos) = self.genText()
510 def getMulti(self, selected):
511 (value, mPos) = self.genText()
512 # only mark cursor when we are selected
513 # (this code is heavily ink optimized!)
515 return ("mtext"[1-selected:], value, [mPos])
517 return ("text", value)
519 def tostring(self, val):
520 return self.seperator.join([self.saveSingle(x) for x in val])
522 def saveSingle(self, v):
525 def fromstring(self, value):
526 return [int(x) for x in value.split(self.seperator)]
528 def onDeselect(self, session):
529 if not self.last_value == self._value:
531 self.last_value = copy.copy(self._value)
533 class ConfigIP(ConfigSequence):
534 def __init__(self, default, auto_jump = False):
535 ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
537 for x in self.limits:
538 self.block_len.append(len(str(x[1])))
539 self.marked_block = 0
540 self.overwrite = True
541 self.auto_jump = auto_jump
543 def handleKey(self, key):
546 if self.marked_block > 0:
547 self.marked_block -= 1
548 self.overwrite = True
551 if self.marked_block < len(self.limits)-1:
552 self.marked_block += 1
553 self.overwrite = True
556 self.marked_block = 0
557 self.overwrite = True
560 self.marked_block = len(self.limits)-1
561 self.overwrite = True
563 if key in KEY_NUMBERS or key == KEY_ASCII:
565 code = getPrevAsciiCode()
566 if code < 48 or code > 57:
570 number = getKeyNumber(key)
571 oldvalue = self._value[self.marked_block]
574 self._value[self.marked_block] = number
575 self.overwrite = False
578 newvalue = oldvalue + number
579 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
580 self.handleKey(KEY_RIGHT)
584 self._value[self.marked_block] = newvalue
586 if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
587 self.handleKey(KEY_RIGHT)
595 for i in self._value:
596 block_strlen.append(len(str(i)))
598 value += self.seperator
600 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
601 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
602 mBlock = range(leftPos, rightPos)
603 return (value, mBlock)
605 def getMulti(self, selected):
606 (value, mBlock) = self.genText()
608 return ("mtext"[1-selected:], value, mBlock)
610 return ("text", value)
612 def getHTML(self, id):
613 # we definitely don't want leading zeros
614 return '.'.join(["%d" % d for d in self.value])
616 class ConfigMAC(ConfigSequence):
617 def __init__(self, default):
618 ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
620 class ConfigPosition(ConfigSequence):
621 def __init__(self, default, args):
622 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
624 class ConfigClock(ConfigSequence):
625 def __init__(self, default):
627 t = time.localtime(default)
628 ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
631 # Check if Minutes maxed out
632 if self._value[1] == 59:
633 # Check if Hours not maxed out
634 if self._value[0] < 23:
635 # Increment Hour, reset Minutes to 0
645 # Check if Minutes is minimum
646 if self._value[1] == 0:
647 # Check if Hour is greater than 0
648 if self._value[0] > 0:
649 # Decrement Hour, set Minutes to 59
658 class ConfigInteger(ConfigSequence):
659 def __init__(self, default, limits = (0, 9999999999)):
660 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
662 # you need to override this to do input validation
663 def setValue(self, value):
664 self._value = [value]
668 return self._value[0]
670 value = property(getValue, setValue)
672 def fromstring(self, value):
675 def tostring(self, value):
678 class ConfigPIN(ConfigInteger):
679 def __init__(self, default, len = 4, censor = ""):
680 assert isinstance(default, int), "ConfigPIN default must be an integer"
683 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
689 class ConfigFloat(ConfigSequence):
690 def __init__(self, default, limits):
691 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
694 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
696 float = property(getFloat)
698 # an editable text...
699 class ConfigText(ConfigElement, NumericalTextInput):
700 def __init__(self, default = "", fixed_size = True, visible_width = False):
701 ConfigElement.__init__(self)
702 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
705 self.allmarked = (default != "")
706 self.fixed_size = fixed_size
707 self.visible_width = visible_width
709 self.overwrite = fixed_size
710 self.help_window = None
711 self.value = self.last_value = self.default = default
713 def validateMarker(self):
715 if self.marked_pos > len(self.text)-1:
716 self.marked_pos = len(self.text)-1
718 if self.marked_pos > len(self.text):
719 self.marked_pos = len(self.text)
720 if self.marked_pos < 0:
722 if self.visible_width:
723 if self.marked_pos < self.offset:
724 self.offset = self.marked_pos
725 if self.marked_pos >= self.offset + self.visible_width:
726 if self.marked_pos == len(self.text):
727 self.offset = self.marked_pos - self.visible_width
729 self.offset = self.marked_pos - self.visible_width + 1
730 if self.offset > 0 and self.offset + self.visible_width > len(self.text):
731 self.offset = max(0, len(self.text) - self.visible_width)
733 def insertChar(self, ch, pos, owr):
734 if owr or self.overwrite:
735 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
736 elif self.fixed_size:
737 self.text = self.text[0:pos] + ch + self.text[pos:-1]
739 self.text = self.text[0:pos] + ch + self.text[pos:]
741 def deleteChar(self, pos):
742 if not self.fixed_size:
743 self.text = self.text[0:pos] + self.text[pos + 1:]
745 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
747 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
749 def deleteAllChars(self):
751 self.text = " " * len(self.text)
756 def handleKey(self, key):
757 # this will no change anything on the value itself
758 # so we can handle it here in gui element
759 if key == KEY_DELETE:
762 self.deleteAllChars()
763 self.allmarked = False
765 self.deleteChar(self.marked_pos)
766 if self.fixed_size and self.overwrite:
768 elif key == KEY_BACKSPACE:
771 self.deleteAllChars()
772 self.allmarked = False
773 elif self.marked_pos > 0:
774 self.deleteChar(self.marked_pos-1)
775 if not self.fixed_size and self.offset > 0:
778 elif key == KEY_LEFT:
781 self.marked_pos = len(self.text)
782 self.allmarked = False
785 elif key == KEY_RIGHT:
789 self.allmarked = False
792 elif key == KEY_HOME:
794 self.allmarked = False
798 self.allmarked = False
799 self.marked_pos = len(self.text)
800 elif key == KEY_TOGGLEOW:
802 self.overwrite = not self.overwrite
803 elif key == KEY_ASCII:
805 newChar = unichr(getPrevAsciiCode())
807 self.deleteAllChars()
808 self.allmarked = False
809 self.insertChar(newChar, self.marked_pos, False)
811 elif key in KEY_NUMBERS:
812 owr = self.lastKey == getKeyNumber(key)
813 newChar = self.getKey(getKeyNumber(key))
815 self.deleteAllChars()
816 self.allmarked = False
817 self.insertChar(newChar, self.marked_pos, owr)
818 elif key == KEY_TIMEOUT:
821 self.help_window.update(self)
825 self.help_window.update(self)
826 self.validateMarker()
831 self.validateMarker()
835 return self.text.encode("utf-8")
837 def setValue(self, val):
839 self.text = val.decode("utf-8")
840 except UnicodeDecodeError:
841 self.text = val.decode("utf-8", "ignore")
844 value = property(getValue, setValue)
845 _value = property(getValue, setValue)
848 return self.text.encode("utf-8")
850 def getMulti(self, selected):
851 if self.visible_width:
853 mark = range(0, min(self.visible_width, len(self.text)))
855 mark = [self.marked_pos-self.offset]
856 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
859 mark = range(0, len(self.text))
861 mark = [self.marked_pos]
862 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
864 def onSelect(self, session):
865 self.allmarked = (self.value != "")
866 if session is not None:
867 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
868 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
869 self.help_window.show()
871 def onDeselect(self, session):
875 session.deleteDialog(self.help_window)
876 self.help_window = None
877 if not self.last_value == self.value:
879 self.last_value = self.value
881 def getHTML(self, id):
882 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
884 def unsafeAssign(self, value):
885 self.value = str(value)
887 class ConfigPassword(ConfigText):
888 def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
889 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
890 self.censor_char = censor
893 def getMulti(self, selected):
894 mtext, text, mark = ConfigText.getMulti(self, selected)
896 text = len(text) * self.censor_char
897 return (mtext, text, mark)
899 def onSelect(self, session):
900 ConfigText.onSelect(self, session)
903 def onDeselect(self, session):
904 ConfigText.onDeselect(self, session)
907 class ConfigNumber(ConfigText):
908 def __init__(self, default = 0):
909 ConfigText.__init__(self, str(default), fixed_size = False)
912 return int(self.text)
914 def setValue(self, val):
917 value = property(getValue, setValue)
918 _value = property(getValue, setValue)
921 pos = len(self.text) - self.marked_pos
922 self.text = self.text.lstrip("0")
925 if pos > len(self.text):
928 self.marked_pos = len(self.text) - pos
930 def handleKey(self, key):
931 if key in KEY_NUMBERS or key == KEY_ASCII:
933 ascii = getPrevAsciiCode()
934 if not (48 <= ascii <= 57):
937 ascii = getKeyNumber(key) + 48
938 newChar = unichr(ascii)
940 self.deleteAllChars()
941 self.allmarked = False
942 self.insertChar(newChar, self.marked_pos, False)
945 ConfigText.handleKey(self, key)
948 def onSelect(self, session):
949 self.allmarked = (self.value != "")
951 def onDeselect(self, session):
954 if not self.last_value == self.value:
956 self.last_value = self.value
958 class ConfigSearchText(ConfigText):
959 def __init__(self, default = "", fixed_size = False, visible_width = False):
960 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
961 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = True)
963 class ConfigDirectory(ConfigText):
964 def __init__(self, default="", visible_width=60):
965 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
966 def handleKey(self, key):
972 return ConfigText.getValue(self)
973 def setValue(self, val):
976 ConfigText.setValue(self, val)
977 def getMulti(self, selected):
979 return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
981 return ConfigText.getMulti(self, selected)
984 class ConfigSlider(ConfigElement):
985 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
986 ConfigElement.__init__(self)
987 self.value = self.last_value = self.default = default
990 self.increment = increment
992 def checkValues(self):
993 if self.value < self.min:
994 self.value = self.min
996 if self.value > self.max:
997 self.value = self.max
999 def handleKey(self, key):
1001 self.value -= self.increment
1002 elif key == KEY_RIGHT:
1003 self.value += self.increment
1004 elif key == KEY_HOME:
1005 self.value = self.min
1006 elif key == KEY_END:
1007 self.value = self.max
1013 return "%d / %d" % (self.value, self.max)
1015 def getMulti(self, selected):
1017 return ("slider", self.value, self.max)
1019 def fromstring(self, value):
1022 # a satlist. in fact, it's a ConfigSelection.
1023 class ConfigSatlist(ConfigSelection):
1024 def __init__(self, list, default = None):
1025 if default is not None:
1026 default = str(default)
1027 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1029 def getOrbitalPosition(self):
1030 if self.value == "":
1032 return int(self.value)
1034 orbital_position = property(getOrbitalPosition)
1036 class ConfigSet(ConfigElement):
1037 def __init__(self, choices, default = []):
1038 ConfigElement.__init__(self)
1040 self.description = {}
1041 if isinstance(choices, list):
1044 if isinstance(x, tuple):
1045 self.choices.append(x[0])
1046 self.description[x[0]] = str(x[1])
1048 self.choices.append(x)
1049 self.description[x] = str(x)
1051 assert False, "ConfigSet choices must be a list!"
1052 if len(self.choices) == 0:
1054 self.description[""] = ""
1059 self.last_value = self.default = default
1060 self.value = default+[]
1062 def toggleChoice(self, choice):
1063 if choice in self.value:
1064 self.value.remove(choice)
1066 self.value.append(choice)
1070 def handleKey(self, key):
1071 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1073 self.toggleChoice(self.choices[self.pos])
1074 elif key == KEY_LEFT:
1077 self.pos = len(self.choices)-1
1078 elif key == KEY_RIGHT:
1080 if self.pos >= len(self.choices):
1082 elif key in [KEY_HOME, KEY_END]:
1085 def genString(self, lst):
1088 res += self.description[x]+" "
1092 return self.genString(self.value)
1094 def getMulti(self, selected):
1095 if not selected or self.pos == -1:
1096 return ("text", self.genString(self.value))
1099 ch = self.choices[self.pos]
1100 mem = ch in self.value
1105 val1 = self.genString(tmp[:ind])
1106 val2 = " "+self.genString(tmp[ind+1:])
1108 chstr = " "+self.description[ch]+" "
1110 chstr = "("+self.description[ch]+")"
1111 return ("mtext", val1+chstr+val2, range(len(val1),len(val1)+len(chstr)))
1113 def onDeselect(self, session):
1115 if not self.last_value == self.value:
1117 self.last_value = self.value+[]
1119 def tostring(self, value):
1122 def fromstring(self, val):
1125 class ConfigLocations(ConfigElement):
1126 def __init__(self, default = [], visible_width = False):
1127 ConfigElement.__init__(self)
1128 self.visible_width = visible_width
1130 self.default = default
1132 self.mountpoints = []
1133 harddiskmanager.on_partition_list_change.append(self.mountpointsChanged)
1134 self.value = default+[]
1136 def setValue(self, value):
1137 loc = [x[0] for x in self.locations if x[3]]
1138 add = [x for x in value if not x in loc]
1139 diff = add + [x for x in loc if not x in value]
1140 self.locations = [x for x in self.locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1141 self.locations.sort(key = lambda x: x[0])
1145 self.checkChangedMountpoints()
1146 for x in self.locations:
1148 return [x[0] for x in self.locations if x[3]]
1150 value = property(getValue, setValue)
1152 def tostring(self, value):
1155 def fromstring(self, val):
1159 sv = self.saved_value
1163 tmp = self.fromstring(sv)
1164 self.locations = [[x, None, False, False] for x in tmp]
1165 self.refreshMountpoints()
1166 for x in self.locations:
1167 if os.path.exists(x[0]):
1168 x[1] = self.getMountpoint(x[0])
1172 if self.save_disabled or self.locations == []:
1173 self.saved_value = None
1175 self.saved_value = self.tostring([x[0] for x in self.locations])
1177 def isChanged(self):
1178 sv = self.saved_value
1179 if val is None and self.locations == []:
1181 return self.tostring([x[0] for x in self.locations]) != sv
1183 def mountpointsChanged(self, action, dev):
1184 print "Mounts changed: ", action, dev
1185 mp = dev.mountpoint+"/"
1188 elif action == "remove":
1189 self.removedMount(mp)
1190 self.refreshMountpoints()
1192 def addedMount(self, mp):
1193 for x in self.locations:
1196 elif x[1] == None and os.path.exists(x[0]):
1197 x[1] = self.getMountpoint(x[0])
1200 def removedMount(self, mp):
1201 for x in self.locations:
1205 def refreshMountpoints(self):
1206 self.mountpoints = [p.mountpoint + "/" for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1207 self.mountpoints.sort(key = lambda x: -len(x))
1209 def checkChangedMountpoints(self):
1210 oldmounts = self.mountpoints
1211 self.refreshMountpoints()
1212 if oldmounts == self.mountpoints:
1215 if not x in self.mountpoints:
1216 self.removedMount(x)
1217 for x in self.mountpoints:
1218 if not x in oldmounts:
1221 def getMountpoint(self, file):
1222 file = os.path.realpath(file)+"/"
1223 for m in self.mountpoints:
1224 if file.startswith(m):
1228 def handleKey(self, key):
1232 self.pos = len(self.value)-1
1233 elif key == KEY_RIGHT:
1235 if self.pos >= len(self.value):
1237 elif key in [KEY_HOME, KEY_END]:
1241 return " ".join(self.value)
1243 def getMulti(self, selected):
1245 valstr = " ".join(self.value)
1246 if self.visible_width and len(valstr) > self.visible_width:
1247 return ("text", valstr[0:self.visible_width])
1249 return ("text", valstr)
1255 for val in self.value:
1258 valstr += str(val)+" "
1262 if self.visible_width and len(valstr) > self.visible_width:
1263 if ind1+1 < self.visible_width/2:
1266 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1267 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1269 return ("mtext", valstr, range(ind1,ind2))
1271 def onDeselect(self, session):
1275 class ConfigNothing(ConfigSelection):
1277 ConfigSelection.__init__(self, choices = [""])
1279 # until here, 'saved_value' always had to be a *string*.
1280 # now, in ConfigSubsection, and only there, saved_value
1281 # is a dict, essentially forming a tree.
1283 # config.foo.bar=True
1284 # config.foobar=False
1287 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1291 class ConfigSubsectionContent(object):
1294 # we store a backup of the loaded configuration
1295 # data in self.stored_values, to be able to deploy
1296 # them when a new config element will be added,
1297 # so non-default values are instantly available
1299 # A list, for example:
1300 # config.dipswitches = ConfigSubList()
1301 # config.dipswitches.append(ConfigYesNo())
1302 # config.dipswitches.append(ConfigYesNo())
1303 # config.dipswitches.append(ConfigYesNo())
1304 class ConfigSubList(list, object):
1306 object.__init__(self)
1308 self.stored_values = {}
1318 def getSavedValue(self):
1320 for i in range(len(self)):
1321 sv = self[i].saved_value
1326 def setSavedValue(self, values):
1327 self.stored_values = dict(values)
1328 for (key, val) in self.stored_values.items():
1329 if int(key) < len(self):
1330 self[int(key)].saved_value = val
1332 saved_value = property(getSavedValue, setSavedValue)
1334 def append(self, item):
1336 list.append(self, item)
1337 if i in self.stored_values:
1338 item.saved_value = self.stored_values[i]
1343 for index in range(len(self)):
1344 res[str(index)] = self[index]
1347 # same as ConfigSubList, just as a dictionary.
1348 # care must be taken that the 'key' has a proper
1349 # str() method, because it will be used in the config
1351 class ConfigSubDict(dict, object):
1353 object.__init__(self)
1355 self.stored_values = {}
1358 for x in self.values():
1362 for x in self.values():
1365 def getSavedValue(self):
1367 for (key, val) in self.items():
1368 sv = val.saved_value
1373 def setSavedValue(self, values):
1374 self.stored_values = dict(values)
1375 for (key, val) in self.items():
1376 if str(key) in self.stored_values:
1377 val = self.stored_values[str(key)]
1379 saved_value = property(getSavedValue, setSavedValue)
1381 def __setitem__(self, key, item):
1382 dict.__setitem__(self, key, item)
1383 if str(key) in self.stored_values:
1384 item.saved_value = self.stored_values[str(key)]
1390 # Like the classes above, just with a more "native"
1393 # some evil stuff must be done to allow instant
1394 # loading of added elements. this is why this class
1397 # we need the 'content' because we overwrite
1399 # If you don't understand this, try adding
1400 # __setattr__ to a usual exisiting class and you will.
1401 class ConfigSubsection(object):
1403 object.__init__(self)
1404 self.__dict__["content"] = ConfigSubsectionContent()
1405 self.content.items = { }
1406 self.content.stored_values = { }
1408 def __setattr__(self, name, value):
1409 if name == "saved_value":
1410 return self.setSavedValue(value)
1411 assert isinstance(value, ConfigSubsection) or isinstance(value, ConfigElement) or isinstance(value, ConfigSubList) or isinstance(value, ConfigSubDict), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1412 self.content.items[name] = value
1413 if name in self.content.stored_values:
1414 #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
1415 value.saved_value = self.content.stored_values[name]
1418 def __getattr__(self, name):
1419 return self.content.items[name]
1421 def getSavedValue(self):
1422 res = self.content.stored_values
1423 for (key, val) in self.content.items.items():
1424 sv = val.saved_value
1431 def setSavedValue(self, values):
1432 values = dict(values)
1434 self.content.stored_values = values
1436 for (key, val) in self.content.items.items():
1438 val.saved_value = values[key]
1440 saved_value = property(getSavedValue, setSavedValue)
1443 for x in self.content.items.values():
1447 for x in self.content.items.values():
1451 return self.content.items
1453 # the root config object, which also can "pickle" (=serialize)
1454 # down the whole config tree.
1456 # we try to keep non-existing config entries, to apply them whenever
1457 # a new config entry is added to a subsection
1458 # also, non-existing config entries will be saved, so they won't be
1459 # lost when a config entry disappears.
1460 class Config(ConfigSubsection):
1462 ConfigSubsection.__init__(self)
1464 def pickle_this(self, prefix, topickle, result):
1465 for (key, val) in topickle.items():
1466 name = prefix + "." + key
1468 if isinstance(val, dict):
1469 self.pickle_this(name, val, result)
1470 elif isinstance(val, tuple):
1471 result.append(name + "=" + val[0]) # + " ; " + val[1])
1473 result.append(name + "=" + val)
1477 self.pickle_this("config", self.saved_value, result)
1478 return '\n'.join(result) + "\n"
1480 def unpickle(self, lines):
1483 if not len(l) or l[0] == '#':
1487 val = l[n+1:].strip()
1489 names = l[:n].split('.')
1490 # if val.find(' ') != -1:
1491 # val = val[:val.find(' ')]
1495 for n in names[:-1]:
1496 base = base.setdefault(n, {})
1498 base[names[-1]] = val
1500 # we inherit from ConfigSubsection, so ...
1501 #object.__setattr__(self, "saved_value", tree["config"])
1502 if "config" in tree:
1503 self.setSavedValue(tree["config"])
1505 def saveToFile(self, filename):
1506 f = open(filename, "w")
1507 f.write(self.pickle())
1510 def loadFromFile(self, filename):
1511 f = open(filename, "r")
1512 self.unpickle(f.readlines())
1516 config.misc = ConfigSubsection()
1519 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1523 config.loadFromFile(self.CONFIG_FILE)
1525 print "unable to load config (%s), assuming defaults..." % str(e)
1529 config.saveToFile(self.CONFIG_FILE)
1531 def __resolveValue(self, pickles, cmap):
1532 if cmap.has_key(pickles[0]):
1533 if len(pickles) > 1:
1534 return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
1536 return str(cmap[pickles[0]].value)
1539 def getResolvedKey(self, key):
1540 names = key.split('.')
1542 if names[0] == "config":
1543 ret=self.__resolveValue(names[1:], config.content.items)
1544 if ret and len(ret):
1546 print "getResolvedKey", key, "failed !! (Typo??)"
1549 def NoSave(element):
1550 element.disableSave()
1553 configfile = ConfigFile()
1557 def getConfigListEntry(*args):
1558 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1561 def updateConfigElement(element, newelement):
1562 newelement.value = element.value
1568 #config.bla = ConfigSubsection()
1569 #config.bla.test = ConfigYesNo()
1570 #config.nim = ConfigSubList()
1571 #config.nim.append(ConfigSubsection())
1572 #config.nim[0].bla = ConfigYesNo()
1573 #config.nim.append(ConfigSubsection())
1574 #config.nim[1].bla = ConfigYesNo()
1575 #config.nim[1].blub = ConfigYesNo()
1576 #config.arg = ConfigSubDict()
1577 #config.arg["Hello"] = ConfigYesNo()
1579 #config.arg["Hello"].handleKey(KEY_RIGHT)
1580 #config.arg["Hello"].handleKey(KEY_RIGHT)
1582 ##config.saved_value
1586 #print config.pickle()