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