add possibility to get frontend type and frontend number
[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         def validate(self):
333                 max_pos = 0
334                 num = 0
335                 for i in self._value:
336                         max_pos += len(str(self.limits[num][1]))
337
338                         while self._value[num] < self.limits[num][0]:
339                                 self._value[num] += 1
340
341                         while self._value[num] > self.limits[num][1]:
342                                 self._value[num] -= 1
343
344                         num += 1
345
346                 if self.marked_pos >= max_pos:
347                         self.marked_pos = max_pos - 1
348
349                 if self.marked_pos < 0:
350                         self.marked_pos = 0
351
352         def validatePos(self):
353                 if self.marked_pos < 0:
354                         self.marked_pos = 0
355                         
356                 total_len = sum([len(str(x[1])) for x in self.limits])
357
358                 if self.marked_pos >= total_len:
359                         self.marked_pos = total_len - 1
360
361         def handleKey(self, key):
362                 if key == KEY_LEFT:
363                         self.marked_pos -= 1
364                         self.validatePos()
365
366                 if key == KEY_RIGHT:
367                         self.marked_pos += 1
368                         self.validatePos()
369                 
370                 if key in KEY_NUMBERS:
371                         block_len = []
372                         for x in self.limits:
373                                 block_len.append(len(str(x[1])))
374                         
375                         total_len = sum(block_len)
376
377                         pos = 0
378                         blocknumber = 0
379                         block_len_total = [0, ]
380                         for x in block_len:
381                                 pos += block_len[blocknumber]
382                                 block_len_total.append(pos)
383                                 if pos - 1 >= self.marked_pos:
384                                         pass
385                                 else:
386                                         blocknumber += 1
387
388                         number = getKeyNumber(key)
389                         
390                         # length of numberblock
391                         number_len = len(str(self.limits[blocknumber][1]))
392
393                         # position in the block
394                         posinblock = self.marked_pos - block_len_total[blocknumber]
395                         
396                         oldvalue = self._value[blocknumber]
397                         olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
398                         newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
399                         
400                         self._value[blocknumber] = newvalue
401                         self.marked_pos += 1
402                 
403                         self.validate()
404                         self.changed()
405         
406         def genText(self):
407                 value = ""
408                 mPos = self.marked_pos
409                 num = 0;
410                 for i in self._value:
411                         if len(value):  #fixme no heading separator possible
412                                 value += self.seperator
413                                 if mPos >= len(value) - 1:
414                                         mPos += 1
415
416                         if self.censor_char == "":
417                                 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
418                         else:
419                                 value += (self.censor_char * len(str(self.limits[num][1])))
420                         num += 1
421                 return (value, mPos)
422                 
423         def getText(self):
424                 (value, mPos) = self.genText()
425                 return value
426         
427         def getMulti(self, selected):
428                 (value, mPos) = self.genText()
429                         # only mark cursor when we are selected
430                         # (this code is heavily ink optimized!)
431                 if self.enabled:
432                         return ("mtext"[1-selected:], value, [mPos])
433                 else:
434                         return ("text", value)
435
436         def tostring(self, val):
437                 return self.seperator.join([self.saveSingle(x) for x in val])
438         
439         def saveSingle(self, v):
440                 return str(v)
441
442         def fromstring(self, value):
443                 return [int(x) for x in value.split(self.seperator)]
444
445 class ConfigIP(ConfigSequence):
446         def __init__(self, default):
447                 ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default)
448         
449         def getHTML(self, id):
450                 # we definitely don't want leading zeros
451                 return '.'.join(["%d" % d for d in self.value])
452
453 class ConfigMAC(ConfigSequence):
454         def __init__(self, default):
455                 ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default)
456
457 class ConfigPosition(ConfigSequence):
458         def __init__(self, default, args):
459                 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
460
461 class ConfigClock(ConfigSequence):
462         def __init__(self, default):
463                 import time
464                 t = time.localtime(default)
465                 ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = [t.tm_hour, t.tm_min])
466
467 class ConfigInteger(ConfigSequence):
468         def __init__(self, default, limits = (0, 10000000000)):
469                 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
470         
471         # you need to override this to do input validation
472         def setValue(self, value):
473                 self._value = [value]
474                 self.changed()
475
476         def getValue(self):
477                 return self._value[0]
478         
479         value = property(getValue, setValue)
480
481         def fromstring(self, value):
482                 return int(value)
483
484         def tostring(self, value):
485                 return str(value)
486
487 class ConfigPIN(ConfigInteger):
488         def __init__(self, default, len = 4, censor = ""):
489                 assert isinstance(default, int), "ConfigPIN default must be an integer"
490                 if default == -1:
491                         default = "aaaa"
492                 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
493                 self.len = len
494
495         def getLength(self):
496                 return self.len
497
498 class ConfigFloat(ConfigSequence):
499         def __init__(self, default, limits):
500                 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
501
502         def getFloat(self):
503                 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
504
505         float = property(getFloat)
506
507 # an editable text...
508 class ConfigText(ConfigElement, NumericalTextInput):
509         def __init__(self, default = "", fixed_size = True):
510                 ConfigElement.__init__(self)
511                 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
512                 
513                 self.marked_pos = 0
514                 self.fixed_size = fixed_size
515
516                 self.value = self.default = default
517
518         def validateMarker(self):
519                 if self.marked_pos >= len(self.text):
520                         self.marked_pos = len(self.text) - 1
521                 if self.marked_pos < 0:
522                         self.marked_pos = 0
523
524         #def nextEntry(self):
525         #       self.vals[1](self.getConfigPath())
526
527         def handleKey(self, key):
528                 # this will no change anything on the value itself
529                 # so we can handle it here in gui element
530                 if key == KEY_DELETE:
531                         self.text = self.text[0:self.marked_pos] + self.text[self.marked_pos + 1:]
532                 elif key == KEY_LEFT:
533                         self.marked_pos -= 1
534                 elif key == KEY_RIGHT:
535                         self.marked_pos += 1
536                         self.maybeExpand()
537                 elif key in KEY_NUMBERS:
538                         number = self.getKey(getKeyNumber(key))
539                         self.text = self.text[0:self.marked_pos] + unicode(number) + self.text[self.marked_pos + 1:]
540                 elif key == KEY_TIMEOUT:
541                         self.timeout()
542                         return
543
544                 self.validateMarker()
545                 self.changed()
546
547         def maybeExpand(self):
548                 if not self.fixed_size:
549                         if self.marked_pos >= len(self.text):
550                                 self.text = self.text.ljust(len(self.text) + 1)
551
552         def nextFunc(self):
553                 self.marked_pos += 1
554                 self.maybeExpand()
555                 self.validateMarker()
556                 self.changed()
557
558         def getValue(self):
559                 return self.text.encode("utf-8")
560                 
561         def setValue(self, val):
562                 try:
563                         self.text = val.decode("utf-8")
564                 except UnicodeDecodeError:
565                         self.text = val
566                         print "Broken UTF8!"
567
568         value = property(getValue, setValue)
569         _value = property(getValue, setValue)
570
571         def getText(self):
572                 return self.value
573
574         def getMulti(self, selected):
575                 return ("mtext"[1-selected:], self.value, [self.marked_pos])
576
577         def helpWindow(self):
578                 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
579                 return (NumericalTextInputHelpDialog,self)
580
581         def getHTML(self, id):
582                 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
583
584         def unsafeAssign(self, value):
585                 self.value = str(value)
586
587 # a slider.
588 class ConfigSlider(ConfigElement):
589         def __init__(self, default = 0, increment = 1, limits = (0, 100)):
590                 ConfigElement.__init__(self)
591                 self.value = self.default = default
592                 self.min = limits[0]
593                 self.max = limits[1]
594                 self.increment = increment
595
596         def checkValues(self):
597                 if self.value < self.min:
598                         self.value = self.min
599
600                 if self.value > self.max:
601                         self.value = self.max
602
603         def handleKey(self, key):
604                 if key == KEY_LEFT:
605                         self.value -= self.increment
606                 elif key == KEY_RIGHT:
607                         self.value += self.increment
608                 else:
609                         return
610
611                 self.checkValues()
612                 self.changed()
613
614         def getText(self):
615                 return "%d / %d" % (self.value, self.max)
616
617         def getMulti(self, selected):
618                 self.checkValues()
619                 return ("slider", self.value, self.max)
620
621         def fromstring(self, value):
622                 return int(value)
623
624 # a satlist. in fact, it's a ConfigSelection.
625 class ConfigSatlist(ConfigSelection):
626         def __init__(self, list, default = None):
627                 if default is not None:
628                         default = str(default)
629                 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc) in list], default = default)
630
631         def getOrbitalPosition(self):
632                 if self.value == "":
633                         return None
634                 return int(self.value)
635         
636         orbital_position = property(getOrbitalPosition)
637
638 # nothing.
639 class ConfigNothing(ConfigSelection):
640         def __init__(self):
641                 ConfigSelection.__init__(self, choices = [""])
642
643 # until here, 'saved_value' always had to be a *string*.
644 # now, in ConfigSubsection, and only there, saved_value
645 # is a dict, essentially forming a tree.
646 #
647 # config.foo.bar=True
648 # config.foobar=False
649 #
650 # turns into:
651 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
652 #
653
654
655 class ConfigSubsectionContent(object):
656         pass
657
658 # we store a backup of the loaded configuration
659 # data in self.stored_values, to be able to deploy
660 # them when a new config element will be added,
661 # so non-default values are instantly available
662
663 # A list, for example:
664 # config.dipswitches = ConfigSubList()
665 # config.dipswitches.append(ConfigYesNo())
666 # config.dipswitches.append(ConfigYesNo())
667 # config.dipswitches.append(ConfigYesNo())
668 class ConfigSubList(list, object):
669         def __init__(self):
670                 object.__init__(self)
671                 list.__init__(self)
672                 self.stored_values = {}
673
674         def save(self):
675                 for x in self:
676                         x.save()
677         
678         def load(self):
679                 for x in self:
680                         x.load()
681
682         def getSavedValue(self):
683                 res = {}
684                 for i in range(len(self)):
685                         sv = self[i].saved_value
686                         if sv is not None:
687                                 res[str(i)] = sv
688                 return res
689
690         def setSavedValue(self, values):
691                 self.stored_values = dict(values)
692                 for (key, val) in self.stored_values.items():
693                         if int(key) < len(self):
694                                 self[int(key)].saved_value = val
695
696         saved_value = property(getSavedValue, setSavedValue)
697         
698         def append(self, item):
699                 i = str(len(self))
700                 list.append(self, item)
701                 if i in self.stored_values:
702                         item.saved_value = self.stored_values[i]
703                         item.load()
704
705         def dict(self):
706                 res = dict()
707                 for index in range(len(self)):
708                         res[str(index)] = self[index]
709                 return res
710
711 # same as ConfigSubList, just as a dictionary.
712 # care must be taken that the 'key' has a proper
713 # str() method, because it will be used in the config
714 # file.
715 class ConfigSubDict(dict, object):
716         def __init__(self):
717                 object.__init__(self)
718                 dict.__init__(self)
719                 self.stored_values = {}
720
721         def save(self):
722                 for x in self.values():
723                         x.save()
724         
725         def load(self):
726                 for x in self.values():
727                         x.load()
728
729         def getSavedValue(self):
730                 res = {}
731                 for (key, val) in self.items():
732                         if val.saved_value is not None:
733                                 res[str(key)] = val.saved_value
734                 return res
735
736         def setSavedValue(self, values):
737                 self.stored_values = dict(values)
738                 for (key, val) in self.items():
739                         if str(key) in self.stored_values:
740                                 val = self.stored_values[str(key)]
741
742         saved_value = property(getSavedValue, setSavedValue)
743
744         def __setitem__(self, key, item):
745                 dict.__setitem__(self, key, item)
746                 if str(key) in self.stored_values:
747                         item.saved_value = self.stored_values[str(key)]
748                         item.load()
749
750         def dict(self):
751                 return self
752
753 # Like the classes above, just with a more "native"
754 # syntax.
755 #
756 # some evil stuff must be done to allow instant
757 # loading of added elements. this is why this class
758 # is so complex.
759 #
760 # we need the 'content' because we overwrite 
761 # __setattr__.
762 # If you don't understand this, try adding
763 # __setattr__ to a usual exisiting class and you will.
764 class ConfigSubsection(object):
765         def __init__(self):
766                 object.__init__(self)
767                 self.__dict__["content"] = ConfigSubsectionContent()
768                 self.content.items = { }
769                 self.content.stored_values = { }
770         
771         def __setattr__(self, name, value):
772                 if name == "saved_value":
773                         return self.setSavedValue(value)
774                 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"
775                 self.content.items[name] = value
776                 if name in self.content.stored_values:
777                         #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
778                         value.saved_value = self.content.stored_values[name]
779                         value.load()
780
781         def __getattr__(self, name):
782                 return self.content.items[name]
783
784         def getSavedValue(self):
785                 res = self.content.stored_values
786                 for (key, val) in self.content.items.items():
787                         if val.saved_value is not None:
788                                 res[key] = val.saved_value
789                         elif key in res:
790                                 del res[key]
791                                 
792                 return res
793
794         def setSavedValue(self, values):
795                 values = dict(values)
796                 
797                 self.content.stored_values = values
798                 
799                 for (key, val) in self.content.items.items():
800                         if key in values:
801                                 val.setSavedValue(values[key])
802
803         saved_value = property(getSavedValue, setSavedValue)
804
805         def save(self):
806                 for x in self.content.items.values():
807                         x.save()
808
809         def load(self):
810                 for x in self.content.items.values():
811                         x.load()
812
813         def dict(self):
814                 return self.content.items
815
816 # the root config object, which also can "pickle" (=serialize)
817 # down the whole config tree.
818 #
819 # we try to keep non-existing config entries, to apply them whenever
820 # a new config entry is added to a subsection
821 # also, non-existing config entries will be saved, so they won't be
822 # lost when a config entry disappears.
823 class Config(ConfigSubsection):
824         def __init__(self):
825                 ConfigSubsection.__init__(self)
826
827         def pickle_this(self, prefix, topickle, result):
828                 for (key, val) in topickle.items():
829                         name = prefix + "." + key
830                         
831                         if isinstance(val, dict):
832                                 self.pickle_this(name, val, result)
833                         elif isinstance(val, tuple):
834                                 result.append(name + "=" + val[0]) # + " ; " + val[1])
835                         else:
836                                 result.append(name + "=" + val)
837
838         def pickle(self):
839                 result = [ ]
840                 self.pickle_this("config", self.saved_value, result)
841                 return '\n'.join(result) + "\n"
842
843         def unpickle(self, lines):
844                 tree = { }
845                 for l in lines:
846                         if not len(l) or l[0] == '#':
847                                 continue
848                         
849                         n = l.find('=')
850                         val = l[n+1:].strip()
851
852                         names = l[:n].split('.')
853 #                       if val.find(' ') != -1:
854 #                               val = val[:val.find(' ')]
855
856                         base = tree
857                         
858                         for n in names[:-1]:
859                                 base = base.setdefault(n, {})
860                         
861                         base[names[-1]] = val
862
863                 # we inherit from ConfigSubsection, so ...
864                 #object.__setattr__(self, "saved_value", tree["config"])
865                 if "config" in tree:
866                         self.setSavedValue(tree["config"])
867
868         def saveToFile(self, filename):
869                 f = open(filename, "w")
870                 f.write(self.pickle())
871                 f.close()
872
873         def loadFromFile(self, filename):
874                 f = open(filename, "r")
875                 self.unpickle(f.readlines())
876                 f.close()
877
878 config = Config()
879 config.misc = ConfigSubsection()
880
881 class ConfigFile:
882         CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
883
884         def load(self):
885                 try:
886                         config.loadFromFile(self.CONFIG_FILE)
887                 except IOError, e:
888                         print "unable to load config (%s), assuming defaults..." % str(e)
889         
890         def save(self):
891 #               config.save()
892                 config.saveToFile(self.CONFIG_FILE)
893         
894         def __resolveValue(self, pickles, cmap):
895                 if cmap.has_key(pickles[0]):
896                         if len(pickles) > 1:
897                                 return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
898                         else:
899                                 return str(cmap[pickles[0]].value)
900                 return None
901         
902         def getResolvedKey(self, key):
903                 names = key.split('.')
904                 if len(names) > 1:
905                         if names[0] == "config":
906                                 ret=self.__resolveValue(names[1:], config.content.items)
907                                 if ret and len(ret):
908                                         return ret
909                 print "getResolvedKey", key, "failed !! (Typo??)"
910                 return ""
911
912 def NoSave(element):
913         element.disableSave()
914         return element
915
916 configfile = ConfigFile()
917
918 configfile.load()
919
920 def getConfigListEntry(*args):
921         assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
922         return args
923
924 #def _(x):
925 #       return x
926 #
927 #config.bla = ConfigSubsection()
928 #config.bla.test = ConfigYesNo()
929 #config.nim = ConfigSubList()
930 #config.nim.append(ConfigSubsection())
931 #config.nim[0].bla = ConfigYesNo()
932 #config.nim.append(ConfigSubsection())
933 #config.nim[1].bla = ConfigYesNo()
934 #config.nim[1].blub = ConfigYesNo()
935 #config.arg = ConfigSubDict()
936 #config.arg["Hello"] = ConfigYesNo()
937 #
938 #config.arg["Hello"].handleKey(KEY_RIGHT)
939 #config.arg["Hello"].handleKey(KEY_RIGHT)
940 #
941 ##config.saved_value
942 #
943 ##configfile.save()
944 #config.save()
945 #print config.pickle()