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.save_disabled = False
38 # you need to override this to do input validation
39 def setValue(self, value):
46 value = property(getValue, setValue)
48 # you need to override this if self.value is not a string
49 def fromstring(self, value):
52 # you can overide this for fancy default handling
56 self.value = self.default
58 self.value = self.fromstring(sv)
60 def tostring(self, value):
63 # you need to override this if str(self.value) doesn't work
65 if self.save_disabled or self.value == self.default:
66 self.saved_value = None
68 self.saved_value = self.tostring(self.value)
75 if sv is None and self.value == self.default:
77 return self.tostring(self.value) != sv
80 for x in self.notifiers:
83 def addNotifier(self, notifier, initial_call = True):
84 assert callable(notifier), "notifiers must be callable"
85 self.notifiers.append(notifier)
88 # do we want to call the notifier
89 # - at all when adding it? (yes, though optional)
90 # - when the default is active? (yes)
91 # - when no value *yet* has been set,
92 # because no config has ever been read (currently yes)
93 # (though that's not so easy to detect.
94 # the entry could just be new.)
98 def disableSave(self):
99 self.save_disabled = True
101 def __call__(self, selected):
102 return self.getMulti(selected)
104 def onSelect(self, session):
107 def onDeselect(self, session):
120 KEY_NUMBERS = range(12, 12+10)
124 def getKeyNumber(key):
125 assert key in KEY_NUMBERS
129 # ConfigSelection is a "one of.."-type.
130 # it has the "choices", usually a list, which contains
131 # (id, desc)-tuples (or just only the ids, in case the id
132 # will be used as description)
134 # all ids MUST be plain strings.
136 class ConfigSelection(ConfigElement):
137 def __init__(self, choices, default = None):
138 ConfigElement.__init__(self)
140 self.setChoices(choices, default)
142 def setChoices(self, choices, default = None):
144 self.description = {}
146 if isinstance(choices, list):
148 if isinstance(x, tuple):
149 self.choices.append(x[0])
150 self.description[x[0]] = x[1]
152 self.choices.append(x)
153 self.description[x] = x
154 elif isinstance(choices, dict):
155 for (key, val) in choices.items():
156 self.choices.append(key)
157 self.description[key] = val
159 assert False, "ConfigSelection choices must be dict or list!"
161 #assert len(self.choices), "you can't have an empty configselection"
162 if len(self.choices) == 0:
164 self.description[""] = ""
167 default = self.choices[0]
169 assert default in self.choices, "default must be in choice list, but " + repr(default) + " is not!"
170 for x in self.choices:
171 assert isinstance(x, str), "ConfigSelection choices must be strings"
173 self.default = default
175 if self.value == None or not self.value in self.choices:
178 def setValue(self, value):
179 if value in self.choices:
182 self._value = self.default
186 def tostring(self, val):
192 def setCurrentText(self, text):
193 i = self.choices.index(self.value)
194 del self.description[self.choices[i]]
195 self.choices[i] = text
196 self.description[text] = text
199 value = property(getValue, setValue)
202 return self.choices.index(self.value)
204 index = property(getIndex)
207 def handleKey(self, key):
208 nchoices = len(self.choices)
209 i = self.choices.index(self.value)
211 self.value = self.choices[(i + nchoices - 1) % nchoices]
212 elif key == KEY_RIGHT:
213 self.value = self.choices[(i + 1) % nchoices]
214 elif key == KEY_HOME:
215 self.value = self.choices[0]
217 self.value = self.choices[nchoices - 1]
219 def selectNext(self):
220 nchoices = len(self.choices)
221 i = self.choices.index(self.value)
222 self.value = self.choices[(i + 1) % nchoices]
225 descr = self.description[self.value]
230 def getMulti(self, selected):
231 descr = self.description[self.value]
233 return ("text", _(descr))
234 return ("text", descr)
237 def getHTML(self, id):
239 for v in self.choices:
241 checked = 'checked="checked" '
244 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n"
247 def unsafeAssign(self, value):
248 # setValue does check if value is in choices. This is safe enough.
253 # several customized versions exist for different
256 class ConfigBoolean(ConfigElement):
257 def __init__(self, default = False, descriptions = {False: "false", True: "true"}):
258 ConfigElement.__init__(self)
259 self.descriptions = descriptions
260 self.value = self.default = default
261 def handleKey(self, key):
262 if key in [KEY_LEFT, KEY_RIGHT]:
263 self.value = not self.value
264 elif key == KEY_HOME:
270 descr = self.descriptions[self.value]
275 def getMulti(self, selected):
276 descr = self.descriptions[self.value]
278 return ("text", _(descr))
279 return ("text", descr)
281 def tostring(self, value):
287 def fromstring(self, val):
293 def getHTML(self, id):
295 checked = ' checked="checked"'
298 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
300 # this is FLAWED. and must be fixed.
301 def unsafeAssign(self, value):
307 class ConfigYesNo(ConfigBoolean):
308 def __init__(self, default = False):
309 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")})
311 class ConfigOnOff(ConfigBoolean):
312 def __init__(self, default = False):
313 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")})
315 class ConfigEnableDisable(ConfigBoolean):
316 def __init__(self, default = False):
317 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")})
319 class ConfigDateTime(ConfigElement):
320 def __init__(self, default, formatstring, increment = 86400):
321 ConfigElement.__init__(self)
322 self.increment = increment
323 self.formatstring = formatstring
324 self.value = self.default = int(default)
326 def handleKey(self, key):
328 self.value = self.value - self.increment
329 elif key == KEY_RIGHT:
330 self.value = self.value + self.increment
331 elif key == KEY_HOME or key == KEY_END:
332 self.value = self.default
335 return time.strftime(self.formatstring, time.localtime(self.value))
337 def getMulti(self, selected):
338 return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
340 def fromstring(self, val):
343 # *THE* mighty config element class
345 # allows you to store/edit a sequence of values.
346 # can be used for IP-addresses, dates, plain integers, ...
347 # several helper exist to ease this up a bit.
349 class ConfigSequence(ConfigElement):
350 def __init__(self, seperator, limits, censor_char = "", default = None):
351 ConfigElement.__init__(self)
352 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
353 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
354 #assert isinstance(default, list), "default must be a list"
355 #assert isinstance(default[0], int), "list must contain numbers"
356 #assert len(default) == len(limits), "length must match"
359 self.seperator = seperator
361 self.censor_char = censor_char
363 self.default = default
364 self.value = copy.copy(default)
366 self.endNotifier = []
371 for i in self._value:
372 max_pos += len(str(self.limits[num][1]))
374 if self._value[num] < self.limits[num][0]:
375 self._value[num] = self.limits[num][0]
377 if self._value[num] > self.limits[num][1]:
378 self._value[num] = self.limits[num][1]
382 if self.marked_pos >= max_pos:
383 for x in self.endNotifier:
385 self.marked_pos = max_pos - 1
387 if self.marked_pos < 0:
390 def validatePos(self):
391 if self.marked_pos < 0:
394 total_len = sum([len(str(x[1])) for x in self.limits])
396 if self.marked_pos >= total_len:
397 self.marked_pos = total_len - 1
399 def addEndNotifier(self, notifier):
400 self.endNotifier.append(notifier)
402 def handleKey(self, key):
418 for i in self._value:
419 max_pos += len(str(self.limits[num][1]))
421 self.marked_pos = max_pos - 1
424 if key in KEY_NUMBERS or key == KEY_ASCII:
426 code = getPrevAsciiCode()
427 if code < 48 or code > 57:
431 number = getKeyNumber(key)
434 for x in self.limits:
435 block_len.append(len(str(x[1])))
437 total_len = sum(block_len)
441 block_len_total = [0, ]
443 pos += block_len[blocknumber]
444 block_len_total.append(pos)
445 if pos - 1 >= self.marked_pos:
450 # length of numberblock
451 number_len = len(str(self.limits[blocknumber][1]))
453 # position in the block
454 posinblock = self.marked_pos - block_len_total[blocknumber]
456 oldvalue = self._value[blocknumber]
457 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
458 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
460 self._value[blocknumber] = newvalue
468 mPos = self.marked_pos
470 for i in self._value:
471 if len(value): #fixme no heading separator possible
472 value += self.seperator
473 if mPos >= len(value) - 1:
476 if self.censor_char == "":
477 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
479 value += (self.censor_char * len(str(self.limits[num][1])))
484 (value, mPos) = self.genText()
487 def getMulti(self, selected):
488 (value, mPos) = self.genText()
489 # only mark cursor when we are selected
490 # (this code is heavily ink optimized!)
492 return ("mtext"[1-selected:], value, [mPos])
494 return ("text", value)
496 def tostring(self, val):
497 return self.seperator.join([self.saveSingle(x) for x in val])
499 def saveSingle(self, v):
502 def fromstring(self, value):
503 return [int(x) for x in value.split(self.seperator)]
505 class ConfigIP(ConfigSequence):
506 def __init__(self, default, auto_jump = False):
507 ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
509 for x in self.limits:
510 self.block_len.append(len(str(x[1])))
511 self.marked_block = 0
512 self.overwrite = True
513 self.auto_jump = auto_jump
515 def handleKey(self, key):
517 if self.marked_block > 0:
518 self.marked_block -= 1
519 self.overwrite = True
522 if self.marked_block < len(self.limits)-1:
523 self.marked_block += 1
524 self.overwrite = True
527 self.marked_block = 0
528 self.overwrite = True
531 self.marked_block = len(self.limits)-1
532 self.overwrite = True
534 if key in KEY_NUMBERS:
535 number = getKeyNumber(key)
536 oldvalue = self._value[self.marked_block]
539 self._value[self.marked_block] = number
540 self.overwrite = False
543 newvalue = oldvalue + number
544 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
545 self.handleKey(KEY_RIGHT)
549 self._value[self.marked_block] = newvalue
551 if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
552 self.handleKey(KEY_RIGHT)
560 for i in self._value:
561 block_strlen.append(len(str(i)))
563 value += self.seperator
565 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
566 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
567 mBlock = range(leftPos, rightPos)
568 return (value, mBlock)
570 def getMulti(self, selected):
571 (value, mBlock) = self.genText()
573 return ("mtext"[1-selected:], value, mBlock)
575 return ("text", value)
577 def getHTML(self, id):
578 # we definitely don't want leading zeros
579 return '.'.join(["%d" % d for d in self.value])
581 class ConfigMAC(ConfigSequence):
582 def __init__(self, default):
583 ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
585 class ConfigPosition(ConfigSequence):
586 def __init__(self, default, args):
587 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
589 class ConfigClock(ConfigSequence):
590 def __init__(self, default):
592 t = time.localtime(default)
593 ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
595 class ConfigInteger(ConfigSequence):
596 def __init__(self, default, limits = (0, 9999999999)):
597 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
599 # you need to override this to do input validation
600 def setValue(self, value):
601 self._value = [value]
605 return self._value[0]
607 value = property(getValue, setValue)
609 def fromstring(self, value):
612 def tostring(self, value):
615 class ConfigPIN(ConfigInteger):
616 def __init__(self, default, len = 4, censor = ""):
617 assert isinstance(default, int), "ConfigPIN default must be an integer"
620 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
626 class ConfigFloat(ConfigSequence):
627 def __init__(self, default, limits):
628 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
631 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
633 float = property(getFloat)
635 # an editable text...
636 class ConfigText(ConfigElement, NumericalTextInput):
637 def __init__(self, default = "", fixed_size = True, visible_width = False):
638 ConfigElement.__init__(self)
639 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
642 self.allmarked = (default != "")
643 self.fixed_size = fixed_size
644 self.visible_width = visible_width
646 self.overwrite = fixed_size
647 self.help_window = None
648 self.value = self.default = default
650 def validateMarker(self):
652 if self.marked_pos > len(self.text)-1:
653 self.marked_pos = len(self.text)-1
655 if self.marked_pos > len(self.text):
656 self.marked_pos = len(self.text)
657 if self.marked_pos < 0:
659 if self.visible_width:
660 if self.marked_pos < self.offset:
661 self.offset = self.marked_pos
662 if self.marked_pos >= self.offset + self.visible_width:
663 if self.marked_pos == len(self.text):
664 self.offset = self.marked_pos - self.visible_width
666 self.offset = self.marked_pos - self.visible_width + 1
667 if self.offset > 0 and self.offset + self.visible_width > len(self.text):
668 self.offset = max(0, len(self.text) - self.visible_width)
670 def insertChar(self, ch, pos, owr):
671 if owr or self.overwrite:
672 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
673 elif self.fixed_size:
674 self.text = self.text[0:pos] + ch + self.text[pos:-1]
676 self.text = self.text[0:pos] + ch + self.text[pos:]
678 def deleteChar(self, pos):
679 if not self.fixed_size:
680 self.text = self.text[0:pos] + self.text[pos + 1:]
682 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
684 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
686 def deleteAllChars(self):
688 self.text = " " * len(self.text)
693 def handleKey(self, key):
694 # this will no change anything on the value itself
695 # so we can handle it here in gui element
696 if key == KEY_DELETE:
699 self.deleteAllChars()
700 self.allmarked = False
702 self.deleteChar(self.marked_pos)
703 if self.fixed_size and self.overwrite:
705 elif key == KEY_BACKSPACE:
708 self.deleteAllChars()
709 self.allmarked = False
710 elif self.marked_pos > 0:
711 self.deleteChar(self.marked_pos-1)
712 if not self.fixed_size and self.offset > 0:
715 elif key == KEY_LEFT:
718 self.marked_pos = len(self.text)
719 self.allmarked = False
722 elif key == KEY_RIGHT:
726 self.allmarked = False
729 elif key == KEY_HOME:
731 self.allmarked = False
735 self.allmarked = False
736 self.marked_pos = len(self.text)
737 elif key == KEY_TOGGLEOW:
739 self.overwrite = not self.overwrite
740 elif key == KEY_ASCII:
742 newChar = unichr(getPrevAsciiCode())
744 self.deleteAllChars()
745 self.allmarked = False
746 self.insertChar(newChar, self.marked_pos, False)
748 elif key in KEY_NUMBERS:
749 owr = self.lastKey == getKeyNumber(key)
750 newChar = self.getKey(getKeyNumber(key))
752 self.deleteAllChars()
753 self.allmarked = False
754 self.insertChar(newChar, self.marked_pos, owr)
755 elif key == KEY_TIMEOUT:
758 self.help_window.update(self)
762 self.help_window.update(self)
763 self.validateMarker()
768 self.validateMarker()
772 return self.text.encode("utf-8")
774 def setValue(self, val):
776 self.text = val.decode("utf-8")
777 except UnicodeDecodeError:
781 value = property(getValue, setValue)
782 _value = property(getValue, setValue)
785 return self.text.encode("utf-8")
787 def getMulti(self, selected):
788 if self.visible_width:
790 mark = range(0, min(self.visible_width, len(self.text)))
792 mark = [self.marked_pos-self.offset]
793 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
796 mark = range(0, len(self.text))
798 mark = [self.marked_pos]
799 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
801 def onSelect(self, session):
802 self.allmarked = (self.value != "")
803 if session is not None:
804 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
805 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
806 self.help_window.show()
808 def onDeselect(self, session):
812 session.deleteDialog(self.help_window)
813 self.help_window = None
815 def getHTML(self, id):
816 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
818 def unsafeAssign(self, value):
819 self.value = str(value)
821 class ConfigPassword(ConfigText):
822 def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
823 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
824 self.censor_char = censor
827 def getMulti(self, selected):
828 mtext, text, mark = ConfigText.getMulti(self, selected)
830 text = len(text) * self.censor_char
831 return (mtext, text, mark)
833 def onSelect(self, session):
834 ConfigText.onSelect(self, session)
837 def onDeselect(self, session):
838 ConfigText.onDeselect(self, session)
841 class ConfigNumber(ConfigText):
842 def __init__(self, default = 0):
843 ConfigText.__init__(self, str(default), fixed_size = False)
846 return int(self.text)
848 def setValue(self, val):
851 value = property(getValue, setValue)
852 _value = property(getValue, setValue)
855 pos = len(self.text) - self.marked_pos
856 self.text = self.text.lstrip("0")
859 if pos > len(self.text):
862 self.marked_pos = len(self.text) - pos
864 def handleKey(self, key):
865 if key in KEY_NUMBERS or key == KEY_ASCII:
867 ascii = getPrevAsciiCode()
868 if not (48 <= ascii <= 57):
871 ascii = getKeyNumber(key) + 48
872 newChar = unichr(ascii)
874 self.deleteAllChars()
875 self.allmarked = False
876 self.insertChar(newChar, self.marked_pos, False)
879 ConfigText.handleKey(self, key)
882 def onSelect(self, session):
883 self.allmarked = (self.value != "")
885 def onDeselect(self, session):
890 class ConfigSlider(ConfigElement):
891 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
892 ConfigElement.__init__(self)
893 self.value = self.default = default
896 self.increment = increment
898 def checkValues(self):
899 if self.value < self.min:
900 self.value = self.min
902 if self.value > self.max:
903 self.value = self.max
905 def handleKey(self, key):
907 self.value -= self.increment
908 elif key == KEY_RIGHT:
909 self.value += self.increment
910 elif key == KEY_HOME:
911 self.value = self.min
913 self.value = self.max
919 return "%d / %d" % (self.value, self.max)
921 def getMulti(self, selected):
923 return ("slider", self.value, self.max)
925 def fromstring(self, value):
928 # a satlist. in fact, it's a ConfigSelection.
929 class ConfigSatlist(ConfigSelection):
930 def __init__(self, list, default = None):
931 if default is not None:
932 default = str(default)
933 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
935 def getOrbitalPosition(self):
938 return int(self.value)
940 orbital_position = property(getOrbitalPosition)
942 class ConfigSet(ConfigElement):
943 def __init__(self, choices, default = []):
944 ConfigElement.__init__(self)
946 self.description = {}
947 if isinstance(choices, list):
950 if isinstance(x, tuple):
951 self.choices.append(x[0])
952 self.description[x[0]] = str(x[1])
954 self.choices.append(x)
955 self.description[x] = str(x)
957 assert False, "ConfigSet choices must be a list!"
958 if len(self.choices) == 0:
960 self.description[""] = ""
965 self.default = default
966 self.value = default+[]
968 def toggleChoice(self, choice):
969 if choice in self.value:
970 self.value.remove(choice)
972 self.value.append(choice)
975 def handleKey(self, key):
976 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
978 self.toggleChoice(self.choices[self.pos])
979 elif key == KEY_LEFT:
982 self.pos = len(self.choices)-1
983 elif key == KEY_RIGHT:
985 if self.pos >= len(self.choices):
987 elif key in [KEY_HOME, KEY_END]:
990 def genString(self, lst):
993 res += self.description[x]+" "
997 return self.genString(self.value)
999 def getMulti(self, selected):
1000 if not selected or self.pos == -1:
1001 return ("text", self.genString(self.value))
1004 ch = self.choices[self.pos]
1005 mem = ch in self.value
1010 val1 = self.genString(tmp[:ind])
1011 val2 = " "+self.genString(tmp[ind+1:])
1013 chstr = " "+self.description[ch]+" "
1015 chstr = "("+self.description[ch]+")"
1016 return ("mtext", val1+chstr+val2, range(len(val1),len(val1)+len(chstr)))
1018 def onDeselect(self, session):
1022 def tostring(self, value):
1025 def fromstring(self, val):
1028 class ConfigLocations(ConfigElement):
1029 def __init__(self, default = [], visible_width = False):
1030 ConfigElement.__init__(self)
1031 self.visible_width = visible_width
1033 self.default = default
1035 self.mountpoints = []
1036 harddiskmanager.on_partition_list_change.append(self.mountpointsChanged)
1038 def setValue(self, value):
1039 loc = [x[0] for x in self.locations if x[3]]
1040 add = [x for x in value if not x in loc]
1041 diff = add + [x for x in loc if not x in value]
1042 self.locations = [x for x in self.locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1043 self.locations.sort(key = lambda x: x[0])
1047 self.checkChangedMountpoints()
1048 for x in self.locations:
1050 return [x[0] for x in self.locations if x[3]]
1052 value = property(getValue, setValue)
1054 def tostring(self, value):
1057 def fromstring(self, val):
1061 sv = self.saved_value
1065 tmp = self.fromstring(sv)
1066 self.locations = [[x, None, False, False] for x in tmp]
1067 self.refreshMountpoints()
1068 for x in self.locations:
1069 if os.path.exists(x[0]):
1070 x[1] = self.getMountpoint(x[0])
1074 if self.save_disabled or self.locations == []:
1075 self.saved_value = None
1077 self.saved_value = self.tostring([x[0] for x in self.locations])
1079 def isChanged(self):
1080 sv = self.saved_value
1081 if val is None and self.locations == []:
1083 return self.tostring([x[0] for x in self.locations]) != sv
1085 def mountpointsChanged(self, action, dev):
1086 print "Mounts changed: ", action, dev
1087 mp = dev.mountpoint+"/"
1090 elif action == "remove":
1091 self.removedMount(mp)
1092 self.refreshMountpoints()
1094 def addedMount(self, mp):
1095 for x in self.locations:
1098 elif x[1] == None and os.path.exists(x[0]):
1099 x[1] = self.getMountpoint(x[0])
1102 def removedMount(self, mp):
1103 for x in self.locations:
1107 def refreshMountpoints(self):
1108 self.mountpoints = [p.mountpoint + "/" for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1109 self.mountpoints.sort(key = lambda x: -len(x))
1111 def checkChangedMountpoints(self):
1112 oldmounts = self.mountpoints
1113 self.refreshMountpoints()
1114 if oldmounts == self.mountpoints:
1117 if not x in self.mountpoints:
1118 self.removedMount(x)
1119 for x in self.mountpoints:
1120 if not x in oldmounts:
1123 def getMountpoint(self, file):
1124 file = os.path.realpath(file)+"/"
1125 for m in self.mountpoints:
1126 if file.startswith(m):
1130 def handleKey(self, key):
1134 self.pos = len(self.value)-1
1135 elif key == KEY_RIGHT:
1137 if self.pos >= len(self.value):
1139 elif key in [KEY_HOME, KEY_END]:
1143 return " ".join(self.value)
1145 def getMulti(self, selected):
1147 valstr = " ".join(self.value)
1148 if self.visible_width and len(valstr) > self.visible_width:
1149 return ("text", valstr[0:self.visible_width])
1151 return ("text", valstr)
1157 for val in self.value:
1160 valstr += str(val)+" "
1164 if self.visible_width and len(valstr) > self.visible_width:
1165 if ind1+1 < self.visible_width/2:
1168 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1169 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1171 return ("mtext", valstr, range(ind1,ind2))
1173 def onDeselect(self, session):
1177 class ConfigNothing(ConfigSelection):
1179 ConfigSelection.__init__(self, choices = [""])
1181 # until here, 'saved_value' always had to be a *string*.
1182 # now, in ConfigSubsection, and only there, saved_value
1183 # is a dict, essentially forming a tree.
1185 # config.foo.bar=True
1186 # config.foobar=False
1189 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1193 class ConfigSubsectionContent(object):
1196 # we store a backup of the loaded configuration
1197 # data in self.stored_values, to be able to deploy
1198 # them when a new config element will be added,
1199 # so non-default values are instantly available
1201 # A list, for example:
1202 # config.dipswitches = ConfigSubList()
1203 # config.dipswitches.append(ConfigYesNo())
1204 # config.dipswitches.append(ConfigYesNo())
1205 # config.dipswitches.append(ConfigYesNo())
1206 class ConfigSubList(list, object):
1208 object.__init__(self)
1210 self.stored_values = {}
1220 def getSavedValue(self):
1222 for i in range(len(self)):
1223 sv = self[i].saved_value
1228 def setSavedValue(self, values):
1229 self.stored_values = dict(values)
1230 for (key, val) in self.stored_values.items():
1231 if int(key) < len(self):
1232 self[int(key)].saved_value = val
1234 saved_value = property(getSavedValue, setSavedValue)
1236 def append(self, item):
1238 list.append(self, item)
1239 if i in self.stored_values:
1240 item.saved_value = self.stored_values[i]
1245 for index in range(len(self)):
1246 res[str(index)] = self[index]
1249 # same as ConfigSubList, just as a dictionary.
1250 # care must be taken that the 'key' has a proper
1251 # str() method, because it will be used in the config
1253 class ConfigSubDict(dict, object):
1255 object.__init__(self)
1257 self.stored_values = {}
1260 for x in self.values():
1264 for x in self.values():
1267 def getSavedValue(self):
1269 for (key, val) in self.items():
1270 sv = val.saved_value
1275 def setSavedValue(self, values):
1276 self.stored_values = dict(values)
1277 for (key, val) in self.items():
1278 if str(key) in self.stored_values:
1279 val = self.stored_values[str(key)]
1281 saved_value = property(getSavedValue, setSavedValue)
1283 def __setitem__(self, key, item):
1284 dict.__setitem__(self, key, item)
1285 if str(key) in self.stored_values:
1286 item.saved_value = self.stored_values[str(key)]
1292 # Like the classes above, just with a more "native"
1295 # some evil stuff must be done to allow instant
1296 # loading of added elements. this is why this class
1299 # we need the 'content' because we overwrite
1301 # If you don't understand this, try adding
1302 # __setattr__ to a usual exisiting class and you will.
1303 class ConfigSubsection(object):
1305 object.__init__(self)
1306 self.__dict__["content"] = ConfigSubsectionContent()
1307 self.content.items = { }
1308 self.content.stored_values = { }
1310 def __setattr__(self, name, value):
1311 if name == "saved_value":
1312 return self.setSavedValue(value)
1313 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"
1314 self.content.items[name] = value
1315 if name in self.content.stored_values:
1316 #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
1317 value.saved_value = self.content.stored_values[name]
1320 def __getattr__(self, name):
1321 return self.content.items[name]
1323 def getSavedValue(self):
1324 res = self.content.stored_values
1325 for (key, val) in self.content.items.items():
1326 sv = val.saved_value
1333 def setSavedValue(self, values):
1334 values = dict(values)
1336 self.content.stored_values = values
1338 for (key, val) in self.content.items.items():
1340 val.saved_value = values[key]
1342 saved_value = property(getSavedValue, setSavedValue)
1345 for x in self.content.items.values():
1349 for x in self.content.items.values():
1353 return self.content.items
1355 # the root config object, which also can "pickle" (=serialize)
1356 # down the whole config tree.
1358 # we try to keep non-existing config entries, to apply them whenever
1359 # a new config entry is added to a subsection
1360 # also, non-existing config entries will be saved, so they won't be
1361 # lost when a config entry disappears.
1362 class Config(ConfigSubsection):
1364 ConfigSubsection.__init__(self)
1366 def pickle_this(self, prefix, topickle, result):
1367 for (key, val) in topickle.items():
1368 name = prefix + "." + key
1370 if isinstance(val, dict):
1371 self.pickle_this(name, val, result)
1372 elif isinstance(val, tuple):
1373 result.append(name + "=" + val[0]) # + " ; " + val[1])
1375 result.append(name + "=" + val)
1379 self.pickle_this("config", self.saved_value, result)
1380 return '\n'.join(result) + "\n"
1382 def unpickle(self, lines):
1385 if not len(l) or l[0] == '#':
1389 val = l[n+1:].strip()
1391 names = l[:n].split('.')
1392 # if val.find(' ') != -1:
1393 # val = val[:val.find(' ')]
1397 for n in names[:-1]:
1398 base = base.setdefault(n, {})
1400 base[names[-1]] = val
1402 # we inherit from ConfigSubsection, so ...
1403 #object.__setattr__(self, "saved_value", tree["config"])
1404 if "config" in tree:
1405 self.setSavedValue(tree["config"])
1407 def saveToFile(self, filename):
1408 f = open(filename, "w")
1409 f.write(self.pickle())
1412 def loadFromFile(self, filename):
1413 f = open(filename, "r")
1414 self.unpickle(f.readlines())
1418 config.misc = ConfigSubsection()
1421 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1425 config.loadFromFile(self.CONFIG_FILE)
1427 print "unable to load config (%s), assuming defaults..." % str(e)
1431 config.saveToFile(self.CONFIG_FILE)
1433 def __resolveValue(self, pickles, cmap):
1434 if cmap.has_key(pickles[0]):
1435 if len(pickles) > 1:
1436 return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
1438 return str(cmap[pickles[0]].value)
1441 def getResolvedKey(self, key):
1442 names = key.split('.')
1444 if names[0] == "config":
1445 ret=self.__resolveValue(names[1:], config.content.items)
1446 if ret and len(ret):
1448 print "getResolvedKey", key, "failed !! (Typo??)"
1451 def NoSave(element):
1452 element.disableSave()
1455 configfile = ConfigFile()
1459 def getConfigListEntry(*args):
1460 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1463 def updateConfigElement(element, newelement):
1464 newelement.value = element.value
1470 #config.bla = ConfigSubsection()
1471 #config.bla.test = ConfigYesNo()
1472 #config.nim = ConfigSubList()
1473 #config.nim.append(ConfigSubsection())
1474 #config.nim[0].bla = ConfigYesNo()
1475 #config.nim.append(ConfigSubsection())
1476 #config.nim[1].bla = ConfigYesNo()
1477 #config.nim[1].blub = ConfigYesNo()
1478 #config.arg = ConfigSubDict()
1479 #config.arg["Hello"] = ConfigYesNo()
1481 #config.arg["Hello"].handleKey(KEY_RIGHT)
1482 #config.arg["Hello"].handleKey(KEY_RIGHT)
1484 ##config.saved_value
1488 #print config.pickle()