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"
188 self.default = default
190 if self.value == None or not self.value in self.choices:
193 def setValue(self, value):
194 if value in self.choices:
197 self._value = self.default
201 def tostring(self, val):
207 def setCurrentText(self, text):
208 i = self.choices.index(self.value)
209 del self.description[self.choices[i]]
210 self.choices[i] = text
211 self.description[text] = text
214 value = property(getValue, setValue)
217 return self.choices.index(self.value)
219 index = property(getIndex)
222 def handleKey(self, key):
223 nchoices = len(self.choices)
224 i = self.choices.index(self.value)
226 self.value = self.choices[(i + nchoices - 1) % nchoices]
227 elif key == KEY_RIGHT:
228 self.value = self.choices[(i + 1) % nchoices]
229 elif key == KEY_HOME:
230 self.value = self.choices[0]
232 self.value = self.choices[nchoices - 1]
234 def selectNext(self):
235 nchoices = len(self.choices)
236 i = self.choices.index(self.value)
237 self.value = self.choices[(i + 1) % nchoices]
240 descr = self.description[self.value]
245 def getMulti(self, selected):
246 descr = self.description[self.value]
248 return ("text", _(descr))
249 return ("text", descr)
252 def getHTML(self, id):
254 for v in self.choices:
256 checked = 'checked="checked" '
259 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n"
262 def unsafeAssign(self, value):
263 # setValue does check if value is in choices. This is safe enough.
268 # several customized versions exist for different
271 class ConfigBoolean(ConfigElement):
272 def __init__(self, default = False, descriptions = {False: "false", True: "true"}):
273 ConfigElement.__init__(self)
274 self.descriptions = descriptions
275 self.value = self.last_value = self.default = default
277 def handleKey(self, key):
278 if key in [KEY_LEFT, KEY_RIGHT]:
279 self.value = not self.value
280 elif key == KEY_HOME:
286 descr = self.descriptions[self.value]
291 def getMulti(self, selected):
292 descr = self.descriptions[self.value]
294 return ("text", _(descr))
295 return ("text", descr)
297 def tostring(self, value):
303 def fromstring(self, val):
309 def getHTML(self, id):
311 checked = ' checked="checked"'
314 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
316 # this is FLAWED. and must be fixed.
317 def unsafeAssign(self, value):
323 def onDeselect(self, session):
324 if not self.last_value == self.value:
326 self.last_value = self.value
328 class ConfigYesNo(ConfigBoolean):
329 def __init__(self, default = False):
330 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")})
332 class ConfigOnOff(ConfigBoolean):
333 def __init__(self, default = False):
334 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")})
336 class ConfigEnableDisable(ConfigBoolean):
337 def __init__(self, default = False):
338 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")})
340 class ConfigDateTime(ConfigElement):
341 def __init__(self, default, formatstring, increment = 86400):
342 ConfigElement.__init__(self)
343 self.increment = increment
344 self.formatstring = formatstring
345 self.value = self.last_value = self.default = int(default)
347 def handleKey(self, key):
349 self.value = self.value - self.increment
350 elif key == KEY_RIGHT:
351 self.value = self.value + self.increment
352 elif key == KEY_HOME or key == KEY_END:
353 self.value = self.default
356 return time.strftime(self.formatstring, time.localtime(self.value))
358 def getMulti(self, selected):
359 return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
361 def fromstring(self, val):
364 # *THE* mighty config element class
366 # allows you to store/edit a sequence of values.
367 # can be used for IP-addresses, dates, plain integers, ...
368 # several helper exist to ease this up a bit.
370 class ConfigSequence(ConfigElement):
371 def __init__(self, seperator, limits, censor_char = "", default = None):
372 ConfigElement.__init__(self)
373 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
374 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
375 #assert isinstance(default, list), "default must be a list"
376 #assert isinstance(default[0], int), "list must contain numbers"
377 #assert len(default) == len(limits), "length must match"
380 self.seperator = seperator
382 self.censor_char = censor_char
384 self.default = default
385 self.value = copy.copy(default)
386 self.last_value = copy.copy(default)
388 self.endNotifier = []
393 for i in self._value:
394 max_pos += len(str(self.limits[num][1]))
396 if self._value[num] < self.limits[num][0]:
397 self._value[num] = self.limits[num][0]
399 if self._value[num] > self.limits[num][1]:
400 self._value[num] = self.limits[num][1]
404 if self.marked_pos >= max_pos:
405 for x in self.endNotifier:
407 self.marked_pos = max_pos - 1
409 if self.marked_pos < 0:
412 def validatePos(self):
413 if self.marked_pos < 0:
416 total_len = sum([len(str(x[1])) for x in self.limits])
418 if self.marked_pos >= total_len:
419 self.marked_pos = total_len - 1
421 def addEndNotifier(self, notifier):
422 self.endNotifier.append(notifier)
424 def handleKey(self, key):
440 for i in self._value:
441 max_pos += len(str(self.limits[num][1]))
443 self.marked_pos = max_pos - 1
446 if key in KEY_NUMBERS or key == KEY_ASCII:
448 code = getPrevAsciiCode()
449 if code < 48 or code > 57:
453 number = getKeyNumber(key)
456 for x in self.limits:
457 block_len.append(len(str(x[1])))
459 total_len = sum(block_len)
463 block_len_total = [0, ]
465 pos += block_len[blocknumber]
466 block_len_total.append(pos)
467 if pos - 1 >= self.marked_pos:
472 # length of numberblock
473 number_len = len(str(self.limits[blocknumber][1]))
475 # position in the block
476 posinblock = self.marked_pos - block_len_total[blocknumber]
478 oldvalue = self._value[blocknumber]
479 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
480 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
482 self._value[blocknumber] = newvalue
490 mPos = self.marked_pos
492 for i in self._value:
493 if len(value): #fixme no heading separator possible
494 value += self.seperator
495 if mPos >= len(value) - 1:
498 if self.censor_char == "":
499 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
501 value += (self.censor_char * len(str(self.limits[num][1])))
506 (value, mPos) = self.genText()
509 def getMulti(self, selected):
510 (value, mPos) = self.genText()
511 # only mark cursor when we are selected
512 # (this code is heavily ink optimized!)
514 return ("mtext"[1-selected:], value, [mPos])
516 return ("text", value)
518 def tostring(self, val):
519 return self.seperator.join([self.saveSingle(x) for x in val])
521 def saveSingle(self, v):
524 def fromstring(self, value):
525 return [int(x) for x in value.split(self.seperator)]
527 def onDeselect(self, session):
528 if not self.last_value == self._value:
530 self.last_value = copy.copy(self._value)
532 class ConfigIP(ConfigSequence):
533 def __init__(self, default, auto_jump = False):
534 ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
536 for x in self.limits:
537 self.block_len.append(len(str(x[1])))
538 self.marked_block = 0
539 self.overwrite = True
540 self.auto_jump = auto_jump
542 def handleKey(self, key):
545 if self.marked_block > 0:
546 self.marked_block -= 1
547 self.overwrite = True
550 if self.marked_block < len(self.limits)-1:
551 self.marked_block += 1
552 self.overwrite = True
555 self.marked_block = 0
556 self.overwrite = True
559 self.marked_block = len(self.limits)-1
560 self.overwrite = True
562 if key in KEY_NUMBERS or key == KEY_ASCII:
564 code = getPrevAsciiCode()
565 if code < 48 or code > 57:
569 number = getKeyNumber(key)
570 oldvalue = self._value[self.marked_block]
573 self._value[self.marked_block] = number
574 self.overwrite = False
577 newvalue = oldvalue + number
578 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
579 self.handleKey(KEY_RIGHT)
583 self._value[self.marked_block] = newvalue
585 if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
586 self.handleKey(KEY_RIGHT)
594 for i in self._value:
595 block_strlen.append(len(str(i)))
597 value += self.seperator
599 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
600 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
601 mBlock = range(leftPos, rightPos)
602 return (value, mBlock)
604 def getMulti(self, selected):
605 (value, mBlock) = self.genText()
607 return ("mtext"[1-selected:], value, mBlock)
609 return ("text", value)
611 def getHTML(self, id):
612 # we definitely don't want leading zeros
613 return '.'.join(["%d" % d for d in self.value])
615 class ConfigMAC(ConfigSequence):
616 def __init__(self, default):
617 ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
619 class ConfigPosition(ConfigSequence):
620 def __init__(self, default, args):
621 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
623 class ConfigClock(ConfigSequence):
624 def __init__(self, default):
626 t = time.localtime(default)
627 ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
630 # Check if Minutes maxed out
631 if self._value[1] == 59:
632 # Increment Hour, reset Minutes
633 if self._value[0] < 23:
645 # Check if Minutes is minimum
646 if self._value[1] == 0:
647 # Decrement Hour, set Minutes to 59
648 if self._value[0] > 0:
659 class ConfigInteger(ConfigSequence):
660 def __init__(self, default, limits = (0, 9999999999)):
661 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
663 # you need to override this to do input validation
664 def setValue(self, value):
665 self._value = [value]
669 return self._value[0]
671 value = property(getValue, setValue)
673 def fromstring(self, value):
676 def tostring(self, value):
679 class ConfigPIN(ConfigInteger):
680 def __init__(self, default, len = 4, censor = ""):
681 assert isinstance(default, int), "ConfigPIN default must be an integer"
684 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
690 class ConfigFloat(ConfigSequence):
691 def __init__(self, default, limits):
692 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
695 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
697 float = property(getFloat)
699 # an editable text...
700 class ConfigText(ConfigElement, NumericalTextInput):
701 def __init__(self, default = "", fixed_size = True, visible_width = False):
702 ConfigElement.__init__(self)
703 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
706 self.allmarked = (default != "")
707 self.fixed_size = fixed_size
708 self.visible_width = visible_width
710 self.overwrite = fixed_size
711 self.help_window = None
712 self.value = self.last_value = self.default = default
714 def validateMarker(self):
716 if self.marked_pos > len(self.text)-1:
717 self.marked_pos = len(self.text)-1
719 if self.marked_pos > len(self.text):
720 self.marked_pos = len(self.text)
721 if self.marked_pos < 0:
723 if self.visible_width:
724 if self.marked_pos < self.offset:
725 self.offset = self.marked_pos
726 if self.marked_pos >= self.offset + self.visible_width:
727 if self.marked_pos == len(self.text):
728 self.offset = self.marked_pos - self.visible_width
730 self.offset = self.marked_pos - self.visible_width + 1
731 if self.offset > 0 and self.offset + self.visible_width > len(self.text):
732 self.offset = max(0, len(self.text) - self.visible_width)
734 def insertChar(self, ch, pos, owr):
735 if owr or self.overwrite:
736 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
737 elif self.fixed_size:
738 self.text = self.text[0:pos] + ch + self.text[pos:-1]
740 self.text = self.text[0:pos] + ch + self.text[pos:]
742 def deleteChar(self, pos):
743 if not self.fixed_size:
744 self.text = self.text[0:pos] + self.text[pos + 1:]
746 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
748 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
750 def deleteAllChars(self):
752 self.text = " " * len(self.text)
757 def handleKey(self, key):
758 # this will no change anything on the value itself
759 # so we can handle it here in gui element
760 if key == KEY_DELETE:
763 self.deleteAllChars()
764 self.allmarked = False
766 self.deleteChar(self.marked_pos)
767 if self.fixed_size and self.overwrite:
769 elif key == KEY_BACKSPACE:
772 self.deleteAllChars()
773 self.allmarked = False
774 elif self.marked_pos > 0:
775 self.deleteChar(self.marked_pos-1)
776 if not self.fixed_size and self.offset > 0:
779 elif key == KEY_LEFT:
782 self.marked_pos = len(self.text)
783 self.allmarked = False
786 elif key == KEY_RIGHT:
790 self.allmarked = False
793 elif key == KEY_HOME:
795 self.allmarked = False
799 self.allmarked = False
800 self.marked_pos = len(self.text)
801 elif key == KEY_TOGGLEOW:
803 self.overwrite = not self.overwrite
804 elif key == KEY_ASCII:
806 newChar = unichr(getPrevAsciiCode())
808 self.deleteAllChars()
809 self.allmarked = False
810 self.insertChar(newChar, self.marked_pos, False)
812 elif key in KEY_NUMBERS:
813 owr = self.lastKey == getKeyNumber(key)
814 newChar = self.getKey(getKeyNumber(key))
816 self.deleteAllChars()
817 self.allmarked = False
818 self.insertChar(newChar, self.marked_pos, owr)
819 elif key == KEY_TIMEOUT:
822 self.help_window.update(self)
826 self.help_window.update(self)
827 self.validateMarker()
832 self.validateMarker()
836 return self.text.encode("utf-8")
838 def setValue(self, val):
840 self.text = val.decode("utf-8")
841 except UnicodeDecodeError:
842 self.text = val.decode("utf-8", "ignore")
845 value = property(getValue, setValue)
846 _value = property(getValue, setValue)
849 return self.text.encode("utf-8")
851 def getMulti(self, selected):
852 if self.visible_width:
854 mark = range(0, min(self.visible_width, len(self.text)))
856 mark = [self.marked_pos-self.offset]
857 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
860 mark = range(0, len(self.text))
862 mark = [self.marked_pos]
863 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
865 def onSelect(self, session):
866 self.allmarked = (self.value != "")
867 if session is not None:
868 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
869 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
870 self.help_window.show()
872 def onDeselect(self, session):
876 session.deleteDialog(self.help_window)
877 self.help_window = None
878 if not self.last_value == self.value:
880 self.last_value = self.value
882 def getHTML(self, id):
883 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
885 def unsafeAssign(self, value):
886 self.value = str(value)
888 class ConfigPassword(ConfigText):
889 def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
890 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
891 self.censor_char = censor
894 def getMulti(self, selected):
895 mtext, text, mark = ConfigText.getMulti(self, selected)
897 text = len(text) * self.censor_char
898 return (mtext, text, mark)
900 def onSelect(self, session):
901 ConfigText.onSelect(self, session)
904 def onDeselect(self, session):
905 ConfigText.onDeselect(self, session)
908 class ConfigNumber(ConfigText):
909 def __init__(self, default = 0):
910 ConfigText.__init__(self, str(default), fixed_size = False)
913 return int(self.text)
915 def setValue(self, val):
918 value = property(getValue, setValue)
919 _value = property(getValue, setValue)
922 pos = len(self.text) - self.marked_pos
923 self.text = self.text.lstrip("0")
926 if pos > len(self.text):
929 self.marked_pos = len(self.text) - pos
931 def handleKey(self, key):
932 if key in KEY_NUMBERS or key == KEY_ASCII:
934 ascii = getPrevAsciiCode()
935 if not (48 <= ascii <= 57):
938 ascii = getKeyNumber(key) + 48
939 newChar = unichr(ascii)
941 self.deleteAllChars()
942 self.allmarked = False
943 self.insertChar(newChar, self.marked_pos, False)
946 ConfigText.handleKey(self, key)
949 def onSelect(self, session):
950 self.allmarked = (self.value != "")
952 def onDeselect(self, session):
955 if not self.last_value == self.value:
957 self.last_value = self.value
959 class ConfigSearchText(ConfigText):
960 def __init__(self, default = "", fixed_size = False, visible_width = False):
961 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
962 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = True)
964 class ConfigDirectory(ConfigText):
965 def __init__(self, default="", visible_width=60):
966 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
967 def handleKey(self, key):
973 return ConfigText.getValue(self)
974 def setValue(self, val):
977 ConfigText.setValue(self, val)
978 def getMulti(self, selected):
980 return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
982 return ConfigText.getMulti(self, selected)
985 class ConfigSlider(ConfigElement):
986 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
987 ConfigElement.__init__(self)
988 self.value = self.last_value = self.default = default
991 self.increment = increment
993 def checkValues(self):
994 if self.value < self.min:
995 self.value = self.min
997 if self.value > self.max:
998 self.value = self.max
1000 def handleKey(self, key):
1002 self.value -= self.increment
1003 elif key == KEY_RIGHT:
1004 self.value += self.increment
1005 elif key == KEY_HOME:
1006 self.value = self.min
1007 elif key == KEY_END:
1008 self.value = self.max
1014 return "%d / %d" % (self.value, self.max)
1016 def getMulti(self, selected):
1018 return ("slider", self.value, self.max)
1020 def fromstring(self, value):
1023 # a satlist. in fact, it's a ConfigSelection.
1024 class ConfigSatlist(ConfigSelection):
1025 def __init__(self, list, default = None):
1026 if default is not None:
1027 default = str(default)
1028 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1030 def getOrbitalPosition(self):
1031 if self.value == "":
1033 return int(self.value)
1035 orbital_position = property(getOrbitalPosition)
1037 class ConfigSet(ConfigElement):
1038 def __init__(self, choices, default = []):
1039 ConfigElement.__init__(self)
1041 self.description = {}
1042 if isinstance(choices, list):
1045 if isinstance(x, tuple):
1046 self.choices.append(x[0])
1047 self.description[x[0]] = str(x[1])
1049 self.choices.append(x)
1050 self.description[x] = str(x)
1052 assert False, "ConfigSet choices must be a list!"
1053 if len(self.choices) == 0:
1055 self.description[""] = ""
1060 self.last_value = self.default = default
1061 self.value = default+[]
1063 def toggleChoice(self, choice):
1064 if choice in self.value:
1065 self.value.remove(choice)
1067 self.value.append(choice)
1071 def handleKey(self, key):
1072 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1074 self.toggleChoice(self.choices[self.pos])
1075 elif key == KEY_LEFT:
1078 self.pos = len(self.choices)-1
1079 elif key == KEY_RIGHT:
1081 if self.pos >= len(self.choices):
1083 elif key in [KEY_HOME, KEY_END]:
1086 def genString(self, lst):
1089 res += self.description[x]+" "
1093 return self.genString(self.value)
1095 def getMulti(self, selected):
1096 if not selected or self.pos == -1:
1097 return ("text", self.genString(self.value))
1100 ch = self.choices[self.pos]
1101 mem = ch in self.value
1106 val1 = self.genString(tmp[:ind])
1107 val2 = " "+self.genString(tmp[ind+1:])
1109 chstr = " "+self.description[ch]+" "
1111 chstr = "("+self.description[ch]+")"
1112 return ("mtext", val1+chstr+val2, range(len(val1),len(val1)+len(chstr)))
1114 def onDeselect(self, session):
1116 if not self.last_value == self.value:
1118 self.last_value = self.value+[]
1120 def tostring(self, value):
1123 def fromstring(self, val):
1126 class ConfigLocations(ConfigElement):
1127 def __init__(self, default = [], visible_width = False):
1128 ConfigElement.__init__(self)
1129 self.visible_width = visible_width
1131 self.default = default
1133 self.mountpoints = []
1134 harddiskmanager.on_partition_list_change.append(self.mountpointsChanged)
1135 self.value = default+[]
1137 def setValue(self, value):
1138 loc = [x[0] for x in self.locations if x[3]]
1139 add = [x for x in value if not x in loc]
1140 diff = add + [x for x in loc if not x in value]
1141 self.locations = [x for x in self.locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1142 self.locations.sort(key = lambda x: x[0])
1146 self.checkChangedMountpoints()
1147 for x in self.locations:
1149 return [x[0] for x in self.locations if x[3]]
1151 value = property(getValue, setValue)
1153 def tostring(self, value):
1156 def fromstring(self, val):
1160 sv = self.saved_value
1164 tmp = self.fromstring(sv)
1165 self.locations = [[x, None, False, False] for x in tmp]
1166 self.refreshMountpoints()
1167 for x in self.locations:
1168 if os.path.exists(x[0]):
1169 x[1] = self.getMountpoint(x[0])
1173 if self.save_disabled or self.locations == []:
1174 self.saved_value = None
1176 self.saved_value = self.tostring([x[0] for x in self.locations])
1178 def isChanged(self):
1179 sv = self.saved_value
1180 if val is None and self.locations == []:
1182 return self.tostring([x[0] for x in self.locations]) != sv
1184 def mountpointsChanged(self, action, dev):
1185 print "Mounts changed: ", action, dev
1186 mp = dev.mountpoint+"/"
1189 elif action == "remove":
1190 self.removedMount(mp)
1191 self.refreshMountpoints()
1193 def addedMount(self, mp):
1194 for x in self.locations:
1197 elif x[1] == None and os.path.exists(x[0]):
1198 x[1] = self.getMountpoint(x[0])
1201 def removedMount(self, mp):
1202 for x in self.locations:
1206 def refreshMountpoints(self):
1207 self.mountpoints = [p.mountpoint + "/" for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1208 self.mountpoints.sort(key = lambda x: -len(x))
1210 def checkChangedMountpoints(self):
1211 oldmounts = self.mountpoints
1212 self.refreshMountpoints()
1213 if oldmounts == self.mountpoints:
1216 if not x in self.mountpoints:
1217 self.removedMount(x)
1218 for x in self.mountpoints:
1219 if not x in oldmounts:
1222 def getMountpoint(self, file):
1223 file = os.path.realpath(file)+"/"
1224 for m in self.mountpoints:
1225 if file.startswith(m):
1229 def handleKey(self, key):
1233 self.pos = len(self.value)-1
1234 elif key == KEY_RIGHT:
1236 if self.pos >= len(self.value):
1238 elif key in [KEY_HOME, KEY_END]:
1242 return " ".join(self.value)
1244 def getMulti(self, selected):
1246 valstr = " ".join(self.value)
1247 if self.visible_width and len(valstr) > self.visible_width:
1248 return ("text", valstr[0:self.visible_width])
1250 return ("text", valstr)
1256 for val in self.value:
1259 valstr += str(val)+" "
1263 if self.visible_width and len(valstr) > self.visible_width:
1264 if ind1+1 < self.visible_width/2:
1267 off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1268 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1270 return ("mtext", valstr, range(ind1,ind2))
1272 def onDeselect(self, session):
1276 class ConfigNothing(ConfigSelection):
1278 ConfigSelection.__init__(self, choices = [""])
1280 # until here, 'saved_value' always had to be a *string*.
1281 # now, in ConfigSubsection, and only there, saved_value
1282 # is a dict, essentially forming a tree.
1284 # config.foo.bar=True
1285 # config.foobar=False
1288 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1292 class ConfigSubsectionContent(object):
1295 # we store a backup of the loaded configuration
1296 # data in self.stored_values, to be able to deploy
1297 # them when a new config element will be added,
1298 # so non-default values are instantly available
1300 # A list, for example:
1301 # config.dipswitches = ConfigSubList()
1302 # config.dipswitches.append(ConfigYesNo())
1303 # config.dipswitches.append(ConfigYesNo())
1304 # config.dipswitches.append(ConfigYesNo())
1305 class ConfigSubList(list, object):
1307 object.__init__(self)
1309 self.stored_values = {}
1319 def getSavedValue(self):
1321 for i in range(len(self)):
1322 sv = self[i].saved_value
1327 def setSavedValue(self, values):
1328 self.stored_values = dict(values)
1329 for (key, val) in self.stored_values.items():
1330 if int(key) < len(self):
1331 self[int(key)].saved_value = val
1333 saved_value = property(getSavedValue, setSavedValue)
1335 def append(self, item):
1337 list.append(self, item)
1338 if i in self.stored_values:
1339 item.saved_value = self.stored_values[i]
1344 for index in range(len(self)):
1345 res[str(index)] = self[index]
1348 # same as ConfigSubList, just as a dictionary.
1349 # care must be taken that the 'key' has a proper
1350 # str() method, because it will be used in the config
1352 class ConfigSubDict(dict, object):
1354 object.__init__(self)
1356 self.stored_values = {}
1359 for x in self.values():
1363 for x in self.values():
1366 def getSavedValue(self):
1368 for (key, val) in self.items():
1369 sv = val.saved_value
1374 def setSavedValue(self, values):
1375 self.stored_values = dict(values)
1376 for (key, val) in self.items():
1377 if str(key) in self.stored_values:
1378 val = self.stored_values[str(key)]
1380 saved_value = property(getSavedValue, setSavedValue)
1382 def __setitem__(self, key, item):
1383 dict.__setitem__(self, key, item)
1384 if str(key) in self.stored_values:
1385 item.saved_value = self.stored_values[str(key)]
1391 # Like the classes above, just with a more "native"
1394 # some evil stuff must be done to allow instant
1395 # loading of added elements. this is why this class
1398 # we need the 'content' because we overwrite
1400 # If you don't understand this, try adding
1401 # __setattr__ to a usual exisiting class and you will.
1402 class ConfigSubsection(object):
1404 object.__init__(self)
1405 self.__dict__["content"] = ConfigSubsectionContent()
1406 self.content.items = { }
1407 self.content.stored_values = { }
1409 def __setattr__(self, name, value):
1410 if name == "saved_value":
1411 return self.setSavedValue(value)
1412 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"
1413 self.content.items[name] = value
1414 if name in self.content.stored_values:
1415 #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
1416 value.saved_value = self.content.stored_values[name]
1419 def __getattr__(self, name):
1420 return self.content.items[name]
1422 def getSavedValue(self):
1423 res = self.content.stored_values
1424 for (key, val) in self.content.items.items():
1425 sv = val.saved_value
1432 def setSavedValue(self, values):
1433 values = dict(values)
1435 self.content.stored_values = values
1437 for (key, val) in self.content.items.items():
1439 val.saved_value = values[key]
1441 saved_value = property(getSavedValue, setSavedValue)
1444 for x in self.content.items.values():
1448 for x in self.content.items.values():
1452 return self.content.items
1454 # the root config object, which also can "pickle" (=serialize)
1455 # down the whole config tree.
1457 # we try to keep non-existing config entries, to apply them whenever
1458 # a new config entry is added to a subsection
1459 # also, non-existing config entries will be saved, so they won't be
1460 # lost when a config entry disappears.
1461 class Config(ConfigSubsection):
1463 ConfigSubsection.__init__(self)
1465 def pickle_this(self, prefix, topickle, result):
1466 for (key, val) in topickle.items():
1467 name = prefix + "." + key
1469 if isinstance(val, dict):
1470 self.pickle_this(name, val, result)
1471 elif isinstance(val, tuple):
1472 result.append(name + "=" + val[0]) # + " ; " + val[1])
1474 result.append(name + "=" + val)
1478 self.pickle_this("config", self.saved_value, result)
1479 return '\n'.join(result) + "\n"
1481 def unpickle(self, lines):
1484 if not len(l) or l[0] == '#':
1488 val = l[n+1:].strip()
1490 names = l[:n].split('.')
1491 # if val.find(' ') != -1:
1492 # val = val[:val.find(' ')]
1496 for n in names[:-1]:
1497 base = base.setdefault(n, {})
1499 base[names[-1]] = val
1501 # we inherit from ConfigSubsection, so ...
1502 #object.__setattr__(self, "saved_value", tree["config"])
1503 if "config" in tree:
1504 self.setSavedValue(tree["config"])
1506 def saveToFile(self, filename):
1507 f = open(filename, "w")
1508 f.write(self.pickle())
1511 def loadFromFile(self, filename):
1512 f = open(filename, "r")
1513 self.unpickle(f.readlines())
1517 config.misc = ConfigSubsection()
1520 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1524 config.loadFromFile(self.CONFIG_FILE)
1526 print "unable to load config (%s), assuming defaults..." % str(e)
1530 config.saveToFile(self.CONFIG_FILE)
1532 def __resolveValue(self, pickles, cmap):
1533 if cmap.has_key(pickles[0]):
1534 if len(pickles) > 1:
1535 return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
1537 return str(cmap[pickles[0]].value)
1540 def getResolvedKey(self, key):
1541 names = key.split('.')
1543 if names[0] == "config":
1544 ret=self.__resolveValue(names[1:], config.content.items)
1545 if ret and len(ret):
1547 print "getResolvedKey", key, "failed !! (Typo??)"
1550 def NoSave(element):
1551 element.disableSave()
1554 configfile = ConfigFile()
1558 def getConfigListEntry(*args):
1559 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1562 def updateConfigElement(element, newelement):
1563 newelement.value = element.value
1569 #config.bla = ConfigSubsection()
1570 #config.bla.test = ConfigYesNo()
1571 #config.nim = ConfigSubList()
1572 #config.nim.append(ConfigSubsection())
1573 #config.nim[0].bla = ConfigYesNo()
1574 #config.nim.append(ConfigSubsection())
1575 #config.nim[1].bla = ConfigYesNo()
1576 #config.nim[1].blub = ConfigYesNo()
1577 #config.arg = ConfigSubDict()
1578 #config.arg["Hello"] = ConfigYesNo()
1580 #config.arg["Hello"].handleKey(KEY_RIGHT)
1581 #config.arg["Hello"].handleKey(KEY_RIGHT)
1583 ##config.saved_value
1587 #print config.pickle()