2 from enigma import getPrevAsciiCode
3 from Tools.NumericalTextInput import NumericalTextInput
4 from Tools.Directories import resolveFilename, SCOPE_CONFIG
8 # ConfigElement, the base class of all ConfigElements.
11 # value the current value, usefully encoded.
12 # usually a property which retrieves _value,
13 # and maybe does some reformatting
14 # _value the value as it's going to be saved in the configfile,
15 # though still in non-string form.
16 # this is the object which is actually worked on.
17 # default the initial value. If _value is equal to default,
18 # it will not be stored in the config file
19 # saved_value is a text representation of _value, stored in the config file
21 # and has (at least) the following methods:
22 # save() stores _value into saved_value,
23 # (or stores 'None' if it should not be stored)
24 # load() loads _value from saved_value, or loads
25 # the default if saved_value is 'None' (default)
28 class ConfigElement(object):
32 self.saved_value = None
33 self.save_disabled = False
37 # you need to override this to do input validation
38 def setValue(self, value):
45 value = property(getValue, setValue)
47 # you need to override this if self.value is not a string
48 def fromstring(self, value):
51 # you can overide this for fancy default handling
53 if self.saved_value is None:
54 self.value = self.default
56 self.value = self.fromstring(self.saved_value)
58 def tostring(self, value):
61 # you need to override this if str(self.value) doesn't work
63 if self.save_disabled or self.value == self.default:
64 self.saved_value = None
66 self.saved_value = self.tostring(self.value)
72 if self.saved_value is None and self.value == self.default:
74 return self.tostring(self.value) != self.saved_value
77 for x in self.notifiers:
80 def addNotifier(self, notifier, initial_call = True):
81 assert callable(notifier), "notifiers must be callable"
82 self.notifiers.append(notifier)
85 # do we want to call the notifier
86 # - at all when adding it? (yes, though optional)
87 # - when the default is active? (yes)
88 # - when no value *yet* has been set,
89 # because no config has ever been read (currently yes)
90 # (though that's not so easy to detect.
91 # the entry could just be new.)
95 def disableSave(self):
96 self.save_disabled = True
98 def __call__(self, selected):
99 return self.getMulti(selected)
101 def onSelect(self, session):
104 def onDeselect(self, session):
117 KEY_NUMBERS = range(12, 12+10)
121 def getKeyNumber(key):
122 assert key in KEY_NUMBERS
126 # ConfigSelection is a "one of.."-type.
127 # it has the "choices", usually a list, which contains
128 # (id, desc)-tuples (or just only the ids, in case the id
129 # will be used as description)
131 # all ids MUST be plain strings.
133 class ConfigSelection(ConfigElement):
134 def __init__(self, choices, default = None):
135 ConfigElement.__init__(self)
137 self.setChoices(choices, default)
139 def setChoices(self, choices, default = None):
141 self.description = {}
143 if isinstance(choices, list):
145 if isinstance(x, tuple):
146 self.choices.append(x[0])
147 self.description[x[0]] = x[1]
149 self.choices.append(x)
150 self.description[x] = x
151 elif isinstance(choices, dict):
152 for (key, val) in choices.items():
153 self.choices.append(key)
154 self.description[key] = val
156 assert False, "ConfigSelection choices must be dict or list!"
158 #assert len(self.choices), "you can't have an empty configselection"
159 if len(self.choices) == 0:
161 self.description[""] = ""
164 default = self.choices[0]
166 assert default in self.choices, "default must be in choice list, but " + repr(default) + " is not!"
167 for x in self.choices:
168 assert isinstance(x, str), "ConfigSelection choices must be strings"
170 self.default = default
172 if self.value == None or not self.value in self.choices:
175 def setValue(self, value):
176 if value in self.choices:
179 self._value = self.default
183 def tostring(self, val):
189 def setCurrentText(self, text):
190 i = self.choices.index(self.value)
191 del self.description[self.choices[i]]
192 self.choices[i] = text
193 self.description[text] = text
196 value = property(getValue, setValue)
199 return self.choices.index(self.value)
201 index = property(getIndex)
204 def handleKey(self, key):
205 nchoices = len(self.choices)
206 i = self.choices.index(self.value)
208 self.value = self.choices[(i + nchoices - 1) % nchoices]
209 elif key == KEY_RIGHT:
210 self.value = self.choices[(i + 1) % nchoices]
211 elif key == KEY_HOME:
212 self.value = self.choices[0]
214 self.value = self.choices[nchoices - 1]
217 descr = self.description[self.value]
222 def getMulti(self, selected):
223 descr = self.description[self.value]
225 return ("text", _(descr))
226 return ("text", descr)
229 def getHTML(self, id):
231 for v in self.choices:
233 checked = 'checked="checked" '
236 res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n"
239 def unsafeAssign(self, value):
240 # setValue does check if value is in choices. This is safe enough.
245 # several customized versions exist for different
248 class ConfigBoolean(ConfigElement):
249 def __init__(self, default = False, descriptions = {False: "false", True: "true"}):
250 ConfigElement.__init__(self)
251 self.descriptions = descriptions
252 self.value = self.default = default
253 def handleKey(self, key):
254 if key in [KEY_LEFT, KEY_RIGHT]:
255 self.value = not self.value
256 elif key == KEY_HOME:
262 descr = self.descriptions[self.value]
267 def getMulti(self, selected):
268 descr = self.descriptions[self.value]
270 return ("text", _(descr))
271 return ("text", descr)
273 def tostring(self, value):
279 def fromstring(self, val):
285 def getHTML(self, id):
287 checked = ' checked="checked"'
290 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
292 # this is FLAWED. and must be fixed.
293 def unsafeAssign(self, value):
299 class ConfigYesNo(ConfigBoolean):
300 def __init__(self, default = False):
301 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")})
303 class ConfigOnOff(ConfigBoolean):
304 def __init__(self, default = False):
305 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")})
307 class ConfigEnableDisable(ConfigBoolean):
308 def __init__(self, default = False):
309 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")})
311 class ConfigDateTime(ConfigElement):
312 def __init__(self, default, formatstring, increment = 86400):
313 ConfigElement.__init__(self)
314 self.increment = increment
315 self.formatstring = formatstring
316 self.value = self.default = int(default)
318 def handleKey(self, key):
320 self.value = self.value - self.increment
321 elif key == KEY_RIGHT:
322 self.value = self.value + self.increment
323 elif key == KEY_HOME or key == KEY_END:
324 self.value = self.default
327 return time.strftime(self.formatstring, time.localtime(self.value))
329 def getMulti(self, selected):
330 return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
332 def fromstring(self, val):
335 # *THE* mighty config element class
337 # allows you to store/edit a sequence of values.
338 # can be used for IP-addresses, dates, plain integers, ...
339 # several helper exist to ease this up a bit.
341 class ConfigSequence(ConfigElement):
342 def __init__(self, seperator, limits, censor_char = "", default = None):
343 ConfigElement.__init__(self)
344 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
345 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
346 #assert isinstance(default, list), "default must be a list"
347 #assert isinstance(default[0], int), "list must contain numbers"
348 #assert len(default) == len(limits), "length must match"
351 self.seperator = seperator
353 self.censor_char = censor_char
355 self.default = default
356 self.value = copy.copy(default)
358 self.endNotifier = []
363 for i in self._value:
364 max_pos += len(str(self.limits[num][1]))
366 if self._value[num] < self.limits[num][0]:
367 self._value[num] = self.limits[num][0]
369 if self._value[num] > self.limits[num][1]:
370 self._value[num] = self.limits[num][1]
374 if self.marked_pos >= max_pos:
375 for x in self.endNotifier:
377 self.marked_pos = max_pos - 1
379 if self.marked_pos < 0:
382 def validatePos(self):
383 if self.marked_pos < 0:
386 total_len = sum([len(str(x[1])) for x in self.limits])
388 if self.marked_pos >= total_len:
389 self.marked_pos = total_len - 1
391 def addEndNotifier(self, notifier):
392 self.endNotifier.append(notifier)
394 def handleKey(self, key):
410 for i in self._value:
411 max_pos += len(str(self.limits[num][1]))
413 self.marked_pos = max_pos - 1
416 if key in KEY_NUMBERS or key == KEY_ASCII:
418 code = getPrevAsciiCode()
419 if code < 48 or code > 57:
423 number = getKeyNumber(key)
426 for x in self.limits:
427 block_len.append(len(str(x[1])))
429 total_len = sum(block_len)
433 block_len_total = [0, ]
435 pos += block_len[blocknumber]
436 block_len_total.append(pos)
437 if pos - 1 >= self.marked_pos:
442 # length of numberblock
443 number_len = len(str(self.limits[blocknumber][1]))
445 # position in the block
446 posinblock = self.marked_pos - block_len_total[blocknumber]
448 oldvalue = self._value[blocknumber]
449 olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
450 newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
452 self._value[blocknumber] = newvalue
460 mPos = self.marked_pos
462 for i in self._value:
463 if len(value): #fixme no heading separator possible
464 value += self.seperator
465 if mPos >= len(value) - 1:
468 if self.censor_char == "":
469 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
471 value += (self.censor_char * len(str(self.limits[num][1])))
476 (value, mPos) = self.genText()
479 def getMulti(self, selected):
480 (value, mPos) = self.genText()
481 # only mark cursor when we are selected
482 # (this code is heavily ink optimized!)
484 return ("mtext"[1-selected:], value, [mPos])
486 return ("text", value)
488 def tostring(self, val):
489 return self.seperator.join([self.saveSingle(x) for x in val])
491 def saveSingle(self, v):
494 def fromstring(self, value):
495 return [int(x) for x in value.split(self.seperator)]
497 class ConfigIP(ConfigSequence):
498 def __init__(self, default):
499 ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
501 def getHTML(self, id):
502 # we definitely don't want leading zeros
503 return '.'.join(["%d" % d for d in self.value])
505 class ConfigMAC(ConfigSequence):
506 def __init__(self, default):
507 ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
509 class ConfigPosition(ConfigSequence):
510 def __init__(self, default, args):
511 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
513 class ConfigClock(ConfigSequence):
514 def __init__(self, default):
516 t = time.localtime(default)
517 ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
519 class ConfigInteger(ConfigSequence):
520 def __init__(self, default, limits = (0, 9999999999)):
521 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
523 # you need to override this to do input validation
524 def setValue(self, value):
525 self._value = [value]
529 return self._value[0]
531 value = property(getValue, setValue)
533 def fromstring(self, value):
536 def tostring(self, value):
539 class ConfigPIN(ConfigInteger):
540 def __init__(self, default, len = 4, censor = ""):
541 assert isinstance(default, int), "ConfigPIN default must be an integer"
544 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
550 class ConfigFloat(ConfigSequence):
551 def __init__(self, default, limits):
552 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
555 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
557 float = property(getFloat)
559 # an editable text...
560 class ConfigText(ConfigElement, NumericalTextInput):
561 def __init__(self, default = "", fixed_size = True, visible_width = False):
562 ConfigElement.__init__(self)
563 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
566 self.allmarked = (default != "")
567 self.fixed_size = fixed_size
568 self.visible_width = visible_width
570 self.overwrite = fixed_size
571 self.help_window = None
572 self.value = self.default = default
574 def validateMarker(self):
576 if self.marked_pos > len(self.text)-1:
577 self.marked_pos = len(self.text)-1
579 if self.marked_pos > len(self.text):
580 self.marked_pos = len(self.text)
581 if self.marked_pos < 0:
583 if self.visible_width:
584 if self.marked_pos < self.offset:
585 self.offset = self.marked_pos
586 if self.marked_pos >= self.offset + self.visible_width:
587 if self.marked_pos == len(self.text):
588 self.offset = self.marked_pos - self.visible_width
590 self.offset = self.marked_pos - self.visible_width + 1
591 if self.offset > 0 and self.offset + self.visible_width > len(self.text):
592 self.offset = max(0, len(self.text) - self.visible_width)
594 def insertChar(self, ch, pos, owr):
595 if owr or self.overwrite:
596 self.text = self.text[0:pos] + ch + self.text[pos + 1:]
597 elif self.fixed_size:
598 self.text = self.text[0:pos] + ch + self.text[pos:-1]
600 self.text = self.text[0:pos] + ch + self.text[pos:]
602 def deleteChar(self, pos):
603 if not self.fixed_size:
604 self.text = self.text[0:pos] + self.text[pos + 1:]
606 self.text = self.text[0:pos] + " " + self.text[pos + 1:]
608 self.text = self.text[0:pos] + self.text[pos + 1:] + " "
610 def deleteAllChars(self):
612 self.text = " " * len(self.text)
617 def handleKey(self, key):
618 # this will no change anything on the value itself
619 # so we can handle it here in gui element
620 if key == KEY_DELETE:
623 self.deleteAllChars()
624 self.allmarked = False
626 self.deleteChar(self.marked_pos)
627 if self.fixed_size and self.overwrite:
629 elif key == KEY_BACKSPACE:
632 self.deleteAllChars()
633 self.allmarked = False
634 elif self.marked_pos > 0:
635 self.deleteChar(self.marked_pos-1)
636 if not self.fixed_size and self.offset > 0:
639 elif key == KEY_LEFT:
642 self.marked_pos = len(self.text)
643 self.allmarked = False
646 elif key == KEY_RIGHT:
650 self.allmarked = False
653 elif key == KEY_HOME:
655 self.allmarked = False
659 self.allmarked = False
660 self.marked_pos = len(self.text)
661 elif key == KEY_TOGGLEOW:
663 self.overwrite = not self.overwrite
664 elif key == KEY_ASCII:
666 newChar = unichr(getPrevAsciiCode())
668 self.deleteAllChars()
669 self.allmarked = False
670 self.insertChar(newChar, self.marked_pos, False)
672 elif key in KEY_NUMBERS:
673 owr = self.lastKey == getKeyNumber(key)
674 newChar = self.getKey(getKeyNumber(key))
676 self.deleteAllChars()
677 self.allmarked = False
678 self.insertChar(newChar, self.marked_pos, owr)
679 elif key == KEY_TIMEOUT:
682 self.help_window.update(self)
686 self.help_window.update(self)
687 self.validateMarker()
692 self.validateMarker()
696 return self.text.encode("utf-8")
698 def setValue(self, val):
700 self.text = val.decode("utf-8")
701 except UnicodeDecodeError:
705 value = property(getValue, setValue)
706 _value = property(getValue, setValue)
709 return self.text.encode("utf-8")
711 def getMulti(self, selected):
712 if self.visible_width:
714 mark = range(0, min(self.visible_width, len(self.text)))
716 mark = [self.marked_pos-self.offset]
717 return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
720 mark = range(0, len(self.text))
722 mark = [self.marked_pos]
723 return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
725 def onSelect(self, session):
726 self.allmarked = (self.value != "")
727 if session is not None:
728 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
729 self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
730 self.help_window.show()
732 def onDeselect(self, session):
736 session.deleteDialog(self.help_window)
737 self.help_window = None
739 def getHTML(self, id):
740 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
742 def unsafeAssign(self, value):
743 self.value = str(value)
745 class ConfigNumber(ConfigText):
746 def __init__(self, default = 0):
747 ConfigText.__init__(self, str(default), fixed_size = False)
750 return int(self.text)
752 def setValue(self, val):
755 value = property(getValue, setValue)
756 _value = property(getValue, setValue)
759 pos = len(self.text) - self.marked_pos
760 self.text = self.text.lstrip("0")
763 if pos > len(self.text):
766 self.marked_pos = len(self.text) - pos
768 def handleKey(self, key):
769 if key in KEY_NUMBERS or key == KEY_ASCII:
771 ascii = getPrevAsciiCode()
772 if not (48 <= ascii <= 57):
775 ascii = getKeyNumber(key) + 48
776 newChar = unichr(ascii)
778 self.deleteAllChars()
779 self.allmarked = False
780 self.insertChar(newChar, self.marked_pos, False)
783 ConfigText.handleKey(self, key)
786 def onSelect(self, session):
787 self.allmarked = (self.value != "")
789 def onDeselect(self, session):
794 class ConfigSlider(ConfigElement):
795 def __init__(self, default = 0, increment = 1, limits = (0, 100)):
796 ConfigElement.__init__(self)
797 self.value = self.default = default
800 self.increment = increment
802 def checkValues(self):
803 if self.value < self.min:
804 self.value = self.min
806 if self.value > self.max:
807 self.value = self.max
809 def handleKey(self, key):
811 self.value -= self.increment
812 elif key == KEY_RIGHT:
813 self.value += self.increment
814 elif key == KEY_HOME:
815 self.value = self.min
817 self.value = self.max
825 return "%d / %d" % (self.value, self.max)
827 def getMulti(self, selected):
829 return ("slider", self.value, self.max)
831 def fromstring(self, value):
834 # a satlist. in fact, it's a ConfigSelection.
835 class ConfigSatlist(ConfigSelection):
836 def __init__(self, list, default = None):
837 if default is not None:
838 default = str(default)
839 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
841 def getOrbitalPosition(self):
844 return int(self.value)
846 orbital_position = property(getOrbitalPosition)
849 class ConfigNothing(ConfigSelection):
851 ConfigSelection.__init__(self, choices = [""])
853 # until here, 'saved_value' always had to be a *string*.
854 # now, in ConfigSubsection, and only there, saved_value
855 # is a dict, essentially forming a tree.
857 # config.foo.bar=True
858 # config.foobar=False
861 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
865 class ConfigSubsectionContent(object):
868 # we store a backup of the loaded configuration
869 # data in self.stored_values, to be able to deploy
870 # them when a new config element will be added,
871 # so non-default values are instantly available
873 # A list, for example:
874 # config.dipswitches = ConfigSubList()
875 # config.dipswitches.append(ConfigYesNo())
876 # config.dipswitches.append(ConfigYesNo())
877 # config.dipswitches.append(ConfigYesNo())
878 class ConfigSubList(list, object):
880 object.__init__(self)
882 self.stored_values = {}
892 def getSavedValue(self):
894 for i in range(len(self)):
895 sv = self[i].saved_value
900 def setSavedValue(self, values):
901 self.stored_values = dict(values)
902 for (key, val) in self.stored_values.items():
903 if int(key) < len(self):
904 self[int(key)].saved_value = val
906 saved_value = property(getSavedValue, setSavedValue)
908 def append(self, item):
910 list.append(self, item)
911 if i in self.stored_values:
912 item.saved_value = self.stored_values[i]
917 for index in range(len(self)):
918 res[str(index)] = self[index]
921 # same as ConfigSubList, just as a dictionary.
922 # care must be taken that the 'key' has a proper
923 # str() method, because it will be used in the config
925 class ConfigSubDict(dict, object):
927 object.__init__(self)
929 self.stored_values = {}
932 for x in self.values():
936 for x in self.values():
939 def getSavedValue(self):
941 for (key, val) in self.items():
942 if val.saved_value is not None:
943 res[str(key)] = val.saved_value
946 def setSavedValue(self, values):
947 self.stored_values = dict(values)
948 for (key, val) in self.items():
949 if str(key) in self.stored_values:
950 val = self.stored_values[str(key)]
952 saved_value = property(getSavedValue, setSavedValue)
954 def __setitem__(self, key, item):
955 dict.__setitem__(self, key, item)
956 if str(key) in self.stored_values:
957 item.saved_value = self.stored_values[str(key)]
963 # Like the classes above, just with a more "native"
966 # some evil stuff must be done to allow instant
967 # loading of added elements. this is why this class
970 # we need the 'content' because we overwrite
972 # If you don't understand this, try adding
973 # __setattr__ to a usual exisiting class and you will.
974 class ConfigSubsection(object):
976 object.__init__(self)
977 self.__dict__["content"] = ConfigSubsectionContent()
978 self.content.items = { }
979 self.content.stored_values = { }
981 def __setattr__(self, name, value):
982 if name == "saved_value":
983 return self.setSavedValue(value)
984 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"
985 self.content.items[name] = value
986 if name in self.content.stored_values:
987 #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
988 value.saved_value = self.content.stored_values[name]
991 def __getattr__(self, name):
992 return self.content.items[name]
994 def getSavedValue(self):
995 res = self.content.stored_values
996 for (key, val) in self.content.items.items():
997 if val.saved_value is not None:
998 res[key] = val.saved_value
1004 def setSavedValue(self, values):
1005 values = dict(values)
1007 self.content.stored_values = values
1009 for (key, val) in self.content.items.items():
1011 val.saved_value = values[key]
1013 saved_value = property(getSavedValue, setSavedValue)
1016 for x in self.content.items.values():
1020 for x in self.content.items.values():
1024 return self.content.items
1026 class ConfigSet(ConfigElement):
1027 def __init__(self, choices, default = []):
1028 ConfigElement.__init__(self)
1030 self.description = {}
1031 if isinstance(choices, list):
1034 if isinstance(x, tuple):
1035 self.choices.append(x[0])
1036 self.description[x[0]] = str(x[1])
1038 self.choices.append(x)
1039 self.description[x] = str(x)
1041 assert False, "ConfigSet choices must be a list!"
1042 if len(self.choices) == 0:
1044 self.description[""] = ""
1049 self.default = default
1050 self.value = default+[]
1052 def toggleChoice(self, choice):
1053 if choice in self.value:
1054 self.value.remove(choice)
1056 self.value.append(choice)
1059 def handleKey(self, key):
1060 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1062 self.toggleChoice(self.choices[self.pos])
1063 elif key == KEY_LEFT:
1066 self.pos = len(self.choices)-1
1067 elif key == KEY_RIGHT:
1069 if self.pos >= len(self.choices):
1071 elif key in [KEY_HOME, KEY_END]:
1074 def genString(self, lst):
1077 res += self.description[x]+" "
1081 return self.genString(self.value)
1083 def getMulti(self, selected):
1084 if not selected or self.pos == -1:
1085 return ("text", self.genString(self.value))
1088 ch = self.choices[self.pos]
1089 mem = ch in self.value
1094 val1 = self.genString(tmp[:ind])
1095 val2 = " "+self.genString(tmp[ind+1:])
1097 chstr = " "+self.description[ch]+" "
1099 chstr = "("+self.description[ch]+")"
1100 return ("mtext", val1+chstr+val2, range(len(val1),len(val1)+len(chstr)))
1102 def onDeselect(self, session):
1106 def tostring(self, value):
1109 def fromstring(self, val):
1113 # the root config object, which also can "pickle" (=serialize)
1114 # down the whole config tree.
1116 # we try to keep non-existing config entries, to apply them whenever
1117 # a new config entry is added to a subsection
1118 # also, non-existing config entries will be saved, so they won't be
1119 # lost when a config entry disappears.
1120 class Config(ConfigSubsection):
1122 ConfigSubsection.__init__(self)
1124 def pickle_this(self, prefix, topickle, result):
1125 for (key, val) in topickle.items():
1126 name = prefix + "." + key
1128 if isinstance(val, dict):
1129 self.pickle_this(name, val, result)
1130 elif isinstance(val, tuple):
1131 result.append(name + "=" + val[0]) # + " ; " + val[1])
1133 result.append(name + "=" + val)
1137 self.pickle_this("config", self.saved_value, result)
1138 return '\n'.join(result) + "\n"
1140 def unpickle(self, lines):
1143 if not len(l) or l[0] == '#':
1147 val = l[n+1:].strip()
1149 names = l[:n].split('.')
1150 # if val.find(' ') != -1:
1151 # val = val[:val.find(' ')]
1155 for n in names[:-1]:
1156 base = base.setdefault(n, {})
1158 base[names[-1]] = val
1160 # we inherit from ConfigSubsection, so ...
1161 #object.__setattr__(self, "saved_value", tree["config"])
1162 if "config" in tree:
1163 self.setSavedValue(tree["config"])
1165 def saveToFile(self, filename):
1166 f = open(filename, "w")
1167 f.write(self.pickle())
1170 def loadFromFile(self, filename):
1171 f = open(filename, "r")
1172 self.unpickle(f.readlines())
1176 config.misc = ConfigSubsection()
1179 CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1183 config.loadFromFile(self.CONFIG_FILE)
1185 print "unable to load config (%s), assuming defaults..." % str(e)
1189 config.saveToFile(self.CONFIG_FILE)
1191 def __resolveValue(self, pickles, cmap):
1192 if cmap.has_key(pickles[0]):
1193 if len(pickles) > 1:
1194 return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
1196 return str(cmap[pickles[0]].value)
1199 def getResolvedKey(self, key):
1200 names = key.split('.')
1202 if names[0] == "config":
1203 ret=self.__resolveValue(names[1:], config.content.items)
1204 if ret and len(ret):
1206 print "getResolvedKey", key, "failed !! (Typo??)"
1209 def NoSave(element):
1210 element.disableSave()
1213 configfile = ConfigFile()
1217 def getConfigListEntry(*args):
1218 assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1224 #config.bla = ConfigSubsection()
1225 #config.bla.test = ConfigYesNo()
1226 #config.nim = ConfigSubList()
1227 #config.nim.append(ConfigSubsection())
1228 #config.nim[0].bla = ConfigYesNo()
1229 #config.nim.append(ConfigSubsection())
1230 #config.nim[1].bla = ConfigYesNo()
1231 #config.nim[1].blub = ConfigYesNo()
1232 #config.arg = ConfigSubDict()
1233 #config.arg["Hello"] = ConfigYesNo()
1235 #config.arg["Hello"].handleKey(KEY_RIGHT)
1236 #config.arg["Hello"].handleKey(KEY_RIGHT)
1238 ##config.saved_value
1242 #print config.pickle()