parental control:
[enigma2.git] / lib / python / Components / config.py
1 import time
2 from Tools.NumericalTextInput import NumericalTextInput
3 from Tools.Directories import resolveFilename, SCOPE_CONFIG
4 import copy
5
6
7 # ConfigElement, the base class of all ConfigElements.
8
9 # it stores:
10 #   value    the current value, usefully encoded.
11 #            usually a property which retrieves _value,
12 #            and maybe does some reformatting
13 #   _value   the value as it's going to be saved in the configfile,
14 #            though still in non-string form.
15 #            this is the object which is actually worked on.
16 #   default  the initial value. If _value is equal to default,
17 #            it will not be stored in the config file
18 #   saved_value is a text representation of _value, stored in the config file
19 #
20 # and has (at least) the following methods:
21 #   save()   stores _value into saved_value, 
22 #            (or stores 'None' if it should not be stored)
23 #   load()   loads _value from saved_value, or loads
24 #            the default if saved_value is 'None' (default)
25 #            or invalid.
26 #
27 class ConfigElement(object):
28         def __init__(self):
29
30                 object.__init__(self)
31                 self.saved_value = None
32                 self.save_disabled = False
33                 self.notifiers = []
34                 self.enabled = True
35
36         # you need to override this to do input validation
37         def setValue(self, value):
38                 self._value = value
39                 self.changed()
40
41         def getValue(self):
42                 return self._value
43         
44         value = property(getValue, setValue)
45
46         # you need to override this if self.value is not a string
47         def fromstring(self, value):
48                 return value
49
50         # you can overide this for fancy default handling
51         def load(self):
52                 if self.saved_value is None:
53                         self.value = self.default
54                 else:
55                         self.value = self.fromstring(self.saved_value)
56
57         def tostring(self, value):
58                 return str(value)
59
60         # you need to override this if str(self.value) doesn't work
61         def save(self):
62                 if self.save_disabled or self.value == self.default:
63                         self.saved_value = None
64                 else:
65                         self.saved_value = self.tostring(self.value)
66
67         def cancel(self):
68                 self.load()
69
70         def isChanged(self):
71                 if self.saved_value is None and self.value == self.default:
72                         return False
73                 return self.tostring(self.value) != self.saved_value
74
75         def changed(self):
76                 for x in self.notifiers:
77                         x(self)
78                         
79         def addNotifier(self, notifier, initial_call = True):
80                 assert callable(notifier), "notifiers must be callable"
81                 self.notifiers.append(notifier)
82
83                 # CHECKME:
84                 # do we want to call the notifier
85                 #  - at all when adding it? (yes, though optional)
86                 #  - when the default is active? (yes)
87                 #  - when no value *yet* has been set,
88                 #    because no config has ever been read (currently yes)
89                 #    (though that's not so easy to detect.
90                 #     the entry could just be new.)
91                 if initial_call:
92                         notifier(self)
93
94         def disableSave(self):
95                 self.save_disabled = True
96
97         def __call__(self, selected):
98                 return self.getMulti(selected)
99
100         def helpWindow(self):
101                 return None
102
103 KEY_LEFT = 0
104 KEY_RIGHT = 1
105 KEY_OK = 2
106 KEY_DELETE = 3
107 KEY_TIMEOUT = 4
108 KEY_NUMBERS = range(12, 12+10)
109 KEY_0 = 12
110 KEY_9 = 12+9
111
112 def getKeyNumber(key):
113         assert key in KEY_NUMBERS
114         return key - KEY_0
115
116 #
117 # ConfigSelection is a "one of.."-type.
118 # it has the "choices", usually a list, which contains
119 # (id, desc)-tuples (or just only the ids, in case the id
120 # will be used as description)
121 #
122 # all ids MUST be plain strings.
123 #
124 class ConfigSelection(ConfigElement):
125         def __init__(self, choices, default = None):
126                 ConfigElement.__init__(self)
127                 self.choices = []
128                 self.description = {}
129                 
130                 if isinstance(choices, list):
131                         for x in choices:
132                                 if isinstance(x, tuple):
133                                         self.choices.append(x[0])
134                                         self.description[x[0]] = x[1]
135                                 else:
136                                         self.choices.append(x)
137                                         self.description[x] = x
138                 elif isinstance(choices, dict):
139                         for (key, val) in choices.items():
140                                 self.choices.append(key)
141                                 self.description[key] = val
142                 else:
143                         assert False, "ConfigSelection choices must be dict or list!"
144                 
145                 #assert len(self.choices), "you can't have an empty configselection"
146                 if len(self.choices) == 0:
147                         self.choices = [""]
148                         self.description[""] = ""
149
150                 if default is None:
151                         default = self.choices[0]
152
153                 assert default in self.choices, "default must be in choice list, but " + repr(default) + " is not!"
154                 for x in self.choices:
155                         assert isinstance(x, str), "ConfigSelection choices must be strings"
156                 
157                 self.value = self.default = default
158
159         def setValue(self, value):
160                 if value in self.choices:
161                         self._value = value
162                 else:
163                         self._value = self.default
164                 
165                 self.changed()
166
167         def tostring(self, val):
168                 return val
169
170         def getValue(self):
171                 return self._value
172
173         def setCurrentText(self, text):
174                 i = self.choices.index(self.value)
175                 del self.description[self.choices[i]]
176                 self.choices[i] = text
177                 self.description[text] = text
178                 self._value = text
179
180         value = property(getValue, setValue)
181         
182         def getIndex(self):
183                 return self.choices.index(self.value)
184         
185         index = property(getIndex)
186
187         # GUI
188         def handleKey(self, key):
189                 nchoices = len(self.choices)
190                 i = self.choices.index(self.value)
191                 if key == KEY_LEFT:
192                         self.value = self.choices[(i + nchoices - 1) % nchoices]
193                 elif key == KEY_RIGHT:
194                         self.value = self.choices[(i + 1) % nchoices]
195
196         def getText(self):
197                 descr = self.description[self.value]
198                 if len(descr):
199                         return _(descr)
200                 return descr
201
202         def getMulti(self, selected):
203                 descr = self.description[self.value]
204                 if len(descr):
205                         return ("text", _(descr))
206                 return ("text", descr)
207
208         # HTML
209         def getHTML(self, id):
210                 res = ""
211                 for v in self.choices:
212                         if self.value == v:
213                                 checked = 'checked="checked" '
214                         else:
215                                 checked = ''
216                         res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n"
217                 return res;
218
219         def unsafeAssign(self, value):
220                 # setValue does check if value is in choices. This is safe enough.
221                 self.value = value
222
223 # a binary decision.
224 #
225 # several customized versions exist for different
226 # descriptions.
227 #
228 class ConfigBoolean(ConfigElement):
229         def __init__(self, default = False, descriptions = {False: "false", True: "true"}):
230                 ConfigElement.__init__(self)
231                 self.descriptions = descriptions
232                 self.value = self.default = default
233         def handleKey(self, key):
234                 if key in [KEY_LEFT, KEY_RIGHT]:
235                         self.value = not self.value
236
237         def getText(self):
238                 descr = self.descriptions[self.value]
239                 if len(descr):
240                         return _(descr)
241                 return descr
242
243         def getMulti(self, selected):
244                 descr = self.descriptions[self.value]
245                 if len(descr):
246                         return ("text", _(descr))
247                 return ("text", descr)
248
249         def tostring(self, value):
250                 if not value:
251                         return "false"
252                 else:
253                         return "true"
254
255         def fromstring(self, val):
256                 if val == "true":
257                         return True
258                 else:
259                         return False
260
261         def getHTML(self, id):
262                 if self.value:
263                         checked = ' checked="checked"'
264                 else:
265                         checked = ''
266                 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
267
268         # this is FLAWED. and must be fixed.
269         def unsafeAssign(self, value):
270                 if value == "1":
271                         self.value = True
272                 else:
273                         self.value = False
274
275 class ConfigYesNo(ConfigBoolean):
276         def __init__(self, default = False):
277                 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")})
278
279 class ConfigOnOff(ConfigBoolean):
280         def __init__(self, default = False):
281                 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")})
282
283 class ConfigEnableDisable(ConfigBoolean):
284         def __init__(self, default = False):
285                 ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")})
286
287 class ConfigDateTime(ConfigElement):
288         def __init__(self, default, formatstring, increment = 86400):
289                 ConfigElement.__init__(self)
290                 self.increment = increment
291                 self.formatstring = formatstring
292                 self.value = self.default = int(default)
293
294         def handleKey(self, key):
295                 if key == KEY_LEFT:
296                         self.value = self.value - self.increment
297                 if key == KEY_RIGHT:
298                         self.value = self.value + self.increment
299
300         def getText(self):
301                 return time.strftime(self.formatstring, time.localtime(self.value))
302
303         def getMulti(self, selected):
304                 return ("text", time.strftime(self.formatstring, time.localtime(self.value)))
305
306         def fromstring(self, val):
307                 return int(val)
308
309 # *THE* mighty config element class
310 #
311 # allows you to store/edit a sequence of values.
312 # can be used for IP-addresses, dates, plain integers, ...
313 # several helper exist to ease this up a bit.
314 #
315 class ConfigSequence(ConfigElement):
316         def __init__(self, seperator, limits, censor_char = "", default = None):
317                 ConfigElement.__init__(self)
318                 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
319                 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
320                 #assert isinstance(default, list), "default must be a list"
321                 #assert isinstance(default[0], int), "list must contain numbers"
322                 #assert len(default) == len(limits), "length must match"
323
324                 self.marked_pos = 0
325                 self.seperator = seperator
326                 self.limits = limits
327                 self.censor_char = censor_char
328                 
329                 self.default = default
330                 self.value = copy.copy(default)
331                 
332                 self.endNotifier = []
333
334         def validate(self):
335                 max_pos = 0
336                 num = 0
337                 for i in self._value:
338                         max_pos += len(str(self.limits[num][1]))
339
340                         while self._value[num] < self.limits[num][0]:
341                                 self._value[num] += 1
342
343                         while self._value[num] > self.limits[num][1]:
344                                 self._value[num] -= 1
345
346                         num += 1
347
348                 if self.marked_pos >= max_pos:
349                         for x in self.endNotifier:
350                                 x(self)
351                         self.marked_pos = max_pos - 1
352
353                 if self.marked_pos < 0:
354                         self.marked_pos = 0
355
356         def validatePos(self):
357                 if self.marked_pos < 0:
358                         self.marked_pos = 0
359                         
360                 total_len = sum([len(str(x[1])) for x in self.limits])
361
362                 if self.marked_pos >= total_len:
363                         self.marked_pos = total_len - 1
364                         
365         def addEndNotifier(self, notifier):
366                 self.endNotifier.append(notifier)
367
368         def handleKey(self, key):
369                 if key == KEY_LEFT:
370                         self.marked_pos -= 1
371                         self.validatePos()
372
373                 if key == KEY_RIGHT:
374                         self.marked_pos += 1
375                         self.validatePos()
376                 
377                 if key in KEY_NUMBERS:
378                         block_len = []
379                         for x in self.limits:
380                                 block_len.append(len(str(x[1])))
381                         
382                         total_len = sum(block_len)
383
384                         pos = 0
385                         blocknumber = 0
386                         block_len_total = [0, ]
387                         for x in block_len:
388                                 pos += block_len[blocknumber]
389                                 block_len_total.append(pos)
390                                 if pos - 1 >= self.marked_pos:
391                                         pass
392                                 else:
393                                         blocknumber += 1
394
395                         number = getKeyNumber(key)
396                         
397                         # length of numberblock
398                         number_len = len(str(self.limits[blocknumber][1]))
399
400                         # position in the block
401                         posinblock = self.marked_pos - block_len_total[blocknumber]
402                         
403                         oldvalue = self._value[blocknumber]
404                         olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
405                         newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
406                         
407                         self._value[blocknumber] = newvalue
408                         self.marked_pos += 1
409                 
410                         self.validate()
411                         self.changed()
412         
413         def genText(self):
414                 value = ""
415                 mPos = self.marked_pos
416                 num = 0;
417                 for i in self._value:
418                         if len(value):  #fixme no heading separator possible
419                                 value += self.seperator
420                                 if mPos >= len(value) - 1:
421                                         mPos += 1
422
423                         if self.censor_char == "":
424                                 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
425                         else:
426                                 value += (self.censor_char * len(str(self.limits[num][1])))
427                         num += 1
428                 return (value, mPos)
429                 
430         def getText(self):
431                 (value, mPos) = self.genText()
432                 return value
433         
434         def getMulti(self, selected):
435                 (value, mPos) = self.genText()
436                         # only mark cursor when we are selected
437                         # (this code is heavily ink optimized!)
438                 if self.enabled:
439                         return ("mtext"[1-selected:], value, [mPos])
440                 else:
441                         return ("text", value)
442
443         def tostring(self, val):
444                 return self.seperator.join([self.saveSingle(x) for x in val])
445         
446         def saveSingle(self, v):
447                 return str(v)
448
449         def fromstring(self, value):
450                 return [int(x) for x in value.split(self.seperator)]
451
452 class ConfigIP(ConfigSequence):
453         def __init__(self, default):
454                 ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
455         
456         def getHTML(self, id):
457                 # we definitely don't want leading zeros
458                 return '.'.join(["%d" % d for d in self.value])
459
460 class ConfigMAC(ConfigSequence):
461         def __init__(self, default):
462                 ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
463
464 class ConfigPosition(ConfigSequence):
465         def __init__(self, default, args):
466                 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
467
468 class ConfigClock(ConfigSequence):
469         def __init__(self, default):
470                 import time
471                 t = time.localtime(default)
472                 ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
473
474 class ConfigInteger(ConfigSequence):
475         def __init__(self, default, limits = (0, 10000000000)):
476                 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
477         
478         # you need to override this to do input validation
479         def setValue(self, value):
480                 self._value = [value]
481                 self.changed()
482
483         def getValue(self):
484                 return self._value[0]
485         
486         value = property(getValue, setValue)
487
488         def fromstring(self, value):
489                 return int(value)
490
491         def tostring(self, value):
492                 return str(value)
493
494 class ConfigPIN(ConfigInteger):
495         def __init__(self, default, len = 4, censor = ""):
496                 assert isinstance(default, int), "ConfigPIN default must be an integer"
497                 if default == -1:
498                         default = "aaaa"
499                 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
500                 self.len = len
501
502         def getLength(self):
503                 return self.len
504
505 class ConfigFloat(ConfigSequence):
506         def __init__(self, default, limits):
507                 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
508
509         def getFloat(self):
510                 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
511
512         float = property(getFloat)
513
514 # an editable text...
515 class ConfigText(ConfigElement, NumericalTextInput):
516         def __init__(self, default = "", fixed_size = True):
517                 ConfigElement.__init__(self)
518                 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
519                 
520                 self.marked_pos = 0
521                 self.fixed_size = fixed_size
522
523                 self.value = self.default = default
524
525         def validateMarker(self):
526                 if self.marked_pos >= len(self.text):
527                         self.marked_pos = len(self.text) - 1
528                 if self.marked_pos < 0:
529                         self.marked_pos = 0
530
531         #def nextEntry(self):
532         #       self.vals[1](self.getConfigPath())
533
534         def handleKey(self, key):
535                 # this will no change anything on the value itself
536                 # so we can handle it here in gui element
537                 if key == KEY_DELETE:
538                         self.text = self.text[0:self.marked_pos] + self.text[self.marked_pos + 1:]
539                 elif key == KEY_LEFT:
540                         self.marked_pos -= 1
541                 elif key == KEY_RIGHT:
542                         self.marked_pos += 1
543                         self.maybeExpand()
544                 elif key in KEY_NUMBERS:
545                         number = self.getKey(getKeyNumber(key))
546                         self.text = self.text[0:self.marked_pos] + unicode(number) + self.text[self.marked_pos + 1:]
547                 elif key == KEY_TIMEOUT:
548                         self.timeout()
549                         return
550
551                 self.validateMarker()
552                 self.changed()
553
554         def maybeExpand(self):
555                 if not self.fixed_size:
556                         if self.marked_pos >= len(self.text):
557                                 self.text = self.text.ljust(len(self.text) + 1)
558
559         def nextFunc(self):
560                 self.marked_pos += 1
561                 self.maybeExpand()
562                 self.validateMarker()
563                 self.changed()
564
565         def getValue(self):
566                 return self.text.encode("utf-8")
567                 
568         def setValue(self, val):
569                 try:
570                         self.text = val.decode("utf-8")
571                 except UnicodeDecodeError:
572                         self.text = val
573                         print "Broken UTF8!"
574
575         value = property(getValue, setValue)
576         _value = property(getValue, setValue)
577
578         def getText(self):
579                 return self.value
580
581         def getMulti(self, selected):
582                 return ("mtext"[1-selected:], self.value, [self.marked_pos])
583
584         def helpWindow(self):
585                 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
586                 return (NumericalTextInputHelpDialog,self)
587
588         def getHTML(self, id):
589                 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
590
591         def unsafeAssign(self, value):
592                 self.value = str(value)
593
594 # a slider.
595 class ConfigSlider(ConfigElement):
596         def __init__(self, default = 0, increment = 1, limits = (0, 100)):
597                 ConfigElement.__init__(self)
598                 self.value = self.default = default
599                 self.min = limits[0]
600                 self.max = limits[1]
601                 self.increment = increment
602
603         def checkValues(self):
604                 if self.value < self.min:
605                         self.value = self.min
606
607                 if self.value > self.max:
608                         self.value = self.max
609
610         def handleKey(self, key):
611                 if key == KEY_LEFT:
612                         self.value -= self.increment
613                 elif key == KEY_RIGHT:
614                         self.value += self.increment
615                 else:
616                         return
617
618                 self.checkValues()
619                 self.changed()
620
621         def getText(self):
622                 return "%d / %d" % (self.value, self.max)
623
624         def getMulti(self, selected):
625                 self.checkValues()
626                 return ("slider", self.value, self.max)
627
628         def fromstring(self, value):
629                 return int(value)
630
631 # a satlist. in fact, it's a ConfigSelection.
632 class ConfigSatlist(ConfigSelection):
633         def __init__(self, list, default = None):
634                 if default is not None:
635                         default = str(default)
636                 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
637
638         def getOrbitalPosition(self):
639                 if self.value == "":
640                         return None
641                 return int(self.value)
642         
643         orbital_position = property(getOrbitalPosition)
644
645 # nothing.
646 class ConfigNothing(ConfigSelection):
647         def __init__(self):
648                 ConfigSelection.__init__(self, choices = [""])
649
650 # until here, 'saved_value' always had to be a *string*.
651 # now, in ConfigSubsection, and only there, saved_value
652 # is a dict, essentially forming a tree.
653 #
654 # config.foo.bar=True
655 # config.foobar=False
656 #
657 # turns into:
658 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
659 #
660
661
662 class ConfigSubsectionContent(object):
663         pass
664
665 # we store a backup of the loaded configuration
666 # data in self.stored_values, to be able to deploy
667 # them when a new config element will be added,
668 # so non-default values are instantly available
669
670 # A list, for example:
671 # config.dipswitches = ConfigSubList()
672 # config.dipswitches.append(ConfigYesNo())
673 # config.dipswitches.append(ConfigYesNo())
674 # config.dipswitches.append(ConfigYesNo())
675 class ConfigSubList(list, object):
676         def __init__(self):
677                 object.__init__(self)
678                 list.__init__(self)
679                 self.stored_values = {}
680
681         def save(self):
682                 for x in self:
683                         x.save()
684         
685         def load(self):
686                 for x in self:
687                         x.load()
688
689         def getSavedValue(self):
690                 res = {}
691                 for i in range(len(self)):
692                         sv = self[i].saved_value
693                         if sv is not None:
694                                 res[str(i)] = sv
695                 return res
696
697         def setSavedValue(self, values):
698                 self.stored_values = dict(values)
699                 for (key, val) in self.stored_values.items():
700                         if int(key) < len(self):
701                                 self[int(key)].saved_value = val
702
703         saved_value = property(getSavedValue, setSavedValue)
704         
705         def append(self, item):
706                 i = str(len(self))
707                 list.append(self, item)
708                 if i in self.stored_values:
709                         item.saved_value = self.stored_values[i]
710                         item.load()
711
712         def dict(self):
713                 res = dict()
714                 for index in range(len(self)):
715                         res[str(index)] = self[index]
716                 return res
717
718 # same as ConfigSubList, just as a dictionary.
719 # care must be taken that the 'key' has a proper
720 # str() method, because it will be used in the config
721 # file.
722 class ConfigSubDict(dict, object):
723         def __init__(self):
724                 object.__init__(self)
725                 dict.__init__(self)
726                 self.stored_values = {}
727
728         def save(self):
729                 for x in self.values():
730                         x.save()
731         
732         def load(self):
733                 for x in self.values():
734                         x.load()
735
736         def getSavedValue(self):
737                 res = {}
738                 for (key, val) in self.items():
739                         if val.saved_value is not None:
740                                 res[str(key)] = val.saved_value
741                 return res
742
743         def setSavedValue(self, values):
744                 self.stored_values = dict(values)
745                 for (key, val) in self.items():
746                         if str(key) in self.stored_values:
747                                 val = self.stored_values[str(key)]
748
749         saved_value = property(getSavedValue, setSavedValue)
750
751         def __setitem__(self, key, item):
752                 dict.__setitem__(self, key, item)
753                 if str(key) in self.stored_values:
754                         item.saved_value = self.stored_values[str(key)]
755                         item.load()
756
757         def dict(self):
758                 return self
759
760 # Like the classes above, just with a more "native"
761 # syntax.
762 #
763 # some evil stuff must be done to allow instant
764 # loading of added elements. this is why this class
765 # is so complex.
766 #
767 # we need the 'content' because we overwrite 
768 # __setattr__.
769 # If you don't understand this, try adding
770 # __setattr__ to a usual exisiting class and you will.
771 class ConfigSubsection(object):
772         def __init__(self):
773                 object.__init__(self)
774                 self.__dict__["content"] = ConfigSubsectionContent()
775                 self.content.items = { }
776                 self.content.stored_values = { }
777         
778         def __setattr__(self, name, value):
779                 if name == "saved_value":
780                         return self.setSavedValue(value)
781                 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"
782                 self.content.items[name] = value
783                 if name in self.content.stored_values:
784                         #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
785                         value.saved_value = self.content.stored_values[name]
786                         value.load()
787
788         def __getattr__(self, name):
789                 return self.content.items[name]
790
791         def getSavedValue(self):
792                 res = self.content.stored_values
793                 for (key, val) in self.content.items.items():
794                         if val.saved_value is not None:
795                                 res[key] = val.saved_value
796                         elif key in res:
797                                 del res[key]
798                                 
799                 return res
800
801         def setSavedValue(self, values):
802                 values = dict(values)
803                 
804                 self.content.stored_values = values
805                 
806                 for (key, val) in self.content.items.items():
807                         if key in values:
808                                 val.setSavedValue(values[key])
809
810         saved_value = property(getSavedValue, setSavedValue)
811
812         def save(self):
813                 for x in self.content.items.values():
814                         x.save()
815
816         def load(self):
817                 for x in self.content.items.values():
818                         x.load()
819
820         def dict(self):
821                 return self.content.items
822
823 # the root config object, which also can "pickle" (=serialize)
824 # down the whole config tree.
825 #
826 # we try to keep non-existing config entries, to apply them whenever
827 # a new config entry is added to a subsection
828 # also, non-existing config entries will be saved, so they won't be
829 # lost when a config entry disappears.
830 class Config(ConfigSubsection):
831         def __init__(self):
832                 ConfigSubsection.__init__(self)
833
834         def pickle_this(self, prefix, topickle, result):
835                 for (key, val) in topickle.items():
836                         name = prefix + "." + key
837                         
838                         if isinstance(val, dict):
839                                 self.pickle_this(name, val, result)
840                         elif isinstance(val, tuple):
841                                 result.append(name + "=" + val[0]) # + " ; " + val[1])
842                         else:
843                                 result.append(name + "=" + val)
844
845         def pickle(self):
846                 result = [ ]
847                 self.pickle_this("config", self.saved_value, result)
848                 return '\n'.join(result) + "\n"
849
850         def unpickle(self, lines):
851                 tree = { }
852                 for l in lines:
853                         if not len(l) or l[0] == '#':
854                                 continue
855                         
856                         n = l.find('=')
857                         val = l[n+1:].strip()
858
859                         names = l[:n].split('.')
860 #                       if val.find(' ') != -1:
861 #                               val = val[:val.find(' ')]
862
863                         base = tree
864                         
865                         for n in names[:-1]:
866                                 base = base.setdefault(n, {})
867                         
868                         base[names[-1]] = val
869
870                 # we inherit from ConfigSubsection, so ...
871                 #object.__setattr__(self, "saved_value", tree["config"])
872                 if "config" in tree:
873                         self.setSavedValue(tree["config"])
874
875         def saveToFile(self, filename):
876                 f = open(filename, "w")
877                 f.write(self.pickle())
878                 f.close()
879
880         def loadFromFile(self, filename):
881                 f = open(filename, "r")
882                 self.unpickle(f.readlines())
883                 f.close()
884
885 config = Config()
886 config.misc = ConfigSubsection()
887
888 class ConfigFile:
889         CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
890
891         def load(self):
892                 try:
893                         config.loadFromFile(self.CONFIG_FILE)
894                 except IOError, e:
895                         print "unable to load config (%s), assuming defaults..." % str(e)
896         
897         def save(self):
898 #               config.save()
899                 config.saveToFile(self.CONFIG_FILE)
900         
901         def __resolveValue(self, pickles, cmap):
902                 if cmap.has_key(pickles[0]):
903                         if len(pickles) > 1:
904                                 return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
905                         else:
906                                 return str(cmap[pickles[0]].value)
907                 return None
908         
909         def getResolvedKey(self, key):
910                 names = key.split('.')
911                 if len(names) > 1:
912                         if names[0] == "config":
913                                 ret=self.__resolveValue(names[1:], config.content.items)
914                                 if ret and len(ret):
915                                         return ret
916                 print "getResolvedKey", key, "failed !! (Typo??)"
917                 return ""
918
919 def NoSave(element):
920         element.disableSave()
921         return element
922
923 configfile = ConfigFile()
924
925 configfile.load()
926
927 def getConfigListEntry(*args):
928         assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
929         return args
930
931 #def _(x):
932 #       return x
933 #
934 #config.bla = ConfigSubsection()
935 #config.bla.test = ConfigYesNo()
936 #config.nim = ConfigSubList()
937 #config.nim.append(ConfigSubsection())
938 #config.nim[0].bla = ConfigYesNo()
939 #config.nim.append(ConfigSubsection())
940 #config.nim[1].bla = ConfigYesNo()
941 #config.nim[1].blub = ConfigYesNo()
942 #config.arg = ConfigSubDict()
943 #config.arg["Hello"] = ConfigYesNo()
944 #
945 #config.arg["Hello"].handleKey(KEY_RIGHT)
946 #config.arg["Hello"].handleKey(KEY_RIGHT)
947 #
948 ##config.saved_value
949 #
950 ##configfile.save()
951 #config.save()
952 #print config.pickle()