check ConfigPIN default
[vuplus_dvbapp] / 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.censorChar * 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(ConfigSequence):
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
445 class ConfigFloat(ConfigSequence):
446         def __init__(self, default, limits):
447                 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
448
449         def getFloat(self):
450                 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
451
452         float = property(getFloat)
453
454 # an editable text...
455 class ConfigText(ConfigElement, NumericalTextInput):
456         def __init__(self, default = "", fixed_size = True):
457                 ConfigElement.__init__(self)
458                 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
459                 
460                 self.marked_pos = 0
461                 self.fixed_size = fixed_size
462
463                 self.value = self.default = default
464
465         def validateMarker(self):
466                 if self.marked_pos < 0:
467                         self.marked_pos = 0
468                 if self.marked_pos >= len(self.text):
469                         self.marked_pos = len(self.text) - 1
470
471         #def nextEntry(self):
472         #       self.vals[1](self.getConfigPath())
473
474         def handleKey(self, key):
475                 # this will no change anything on the value itself
476                 # so we can handle it here in gui element
477                 if key == KEY_DELETE:
478                         self.text = self.text[0:self.marked_pos] + self.text[self.marked_pos + 1:]
479                 elif key == KEY_LEFT:
480                         self.marked_pos -= 1
481                 elif key == KEY_RIGHT:
482                         self.marked_pos += 1
483                         if not self.fixed_size:
484                                 if self.marked_pos >= len(self.text):
485                                         self.text = self.text.ljust(len(self.text) + 1)
486                 elif key in KEY_NUMBERS:
487                         number = self.getKey(getKeyNumber(key))
488                         self.text = self.text[0:self.marked_pos] + str(number) + self.text[self.marked_pos + 1:]
489                 elif key == KEY_TIMEOUT:
490                         self.timeout()
491                         return
492
493                 self.validateMarker()
494                 self.changed()
495
496         def nextFunc(self):
497                 self.marked_pos += 1
498                 self.validateMarker()
499                 self.changed()
500
501         def getValue(self):
502                 return self.text.encode("utf-8")
503                 
504         def setValue(self, val):
505                 try:
506                         self.text = val.decode("utf-8")
507                 except UnicodeDecodeError:
508                         self.text = val
509                         print "Broken UTF8!"
510
511         value = property(getValue, setValue)
512         _value = property(getValue, setValue)
513
514         def getMulti(self, selected):
515                 return ("mtext"[1-selected:], self.value, [self.marked_pos])
516
517         def helpWindow(self):
518                 from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
519                 return (NumericalTextInputHelpDialog,self)
520
521         def getHTML(self, id):
522                 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
523
524         def unsafeAssign(self, value):
525                 self.value = str(value)
526
527 # a slider.
528 class ConfigSlider(ConfigElement):
529         def __init__(self, default = 0, increment = 1, limits = (0, 100)):
530                 ConfigElement.__init__(self)
531                 self.value = self.default = default
532                 self.min = limits[0]
533                 self.max = limits[1]
534                 self.increment = increment
535
536         def checkValues(self):
537                 if self.value < self.min:
538                         self.value = self.min
539
540                 if self.value > self.max:
541                         self.value = self.max
542
543         def handleKey(self, key):
544                 if key == KEY_LEFT:
545                         self.value -= self.increment
546                 elif key == KEY_RIGHT:
547                         self.value += self.increment
548                 else:
549                         return
550
551                 self.checkValues()
552                 self.changed()
553
554         def getMulti(self, selected):
555                 self.checkValues()
556                 return ("slider", self.value, self.max)
557
558         def fromstring(self, value):
559                 return int(value)
560
561 # a satlist. in fact, it's a ConfigSelection.
562 class ConfigSatlist(ConfigSelection):
563         def __init__(self, list, default = None):
564                 if default is not None:
565                         default = str(default)
566                 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc) in list], default = default)
567
568         def getOrbitalPosition(self):
569                 if self.value == "":
570                         return None
571                 return int(self.value)
572         
573         orbital_position = property(getOrbitalPosition)
574
575 # nothing.
576 class ConfigNothing(ConfigSelection):
577         def __init__(self):
578                 ConfigSelection.__init__(self, choices = [""])
579
580 # until here, 'saved_value' always had to be a *string*.
581 # now, in ConfigSubsection, and only there, saved_value
582 # is a dict, essentially forming a tree.
583 #
584 # config.foo.bar=True
585 # config.foobar=False
586 #
587 # turns into:
588 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
589 #
590
591
592 class ConfigSubsectionContent(object):
593         pass
594
595 # we store a backup of the loaded configuration
596 # data in self.stored_values, to be able to deploy
597 # them when a new config element will be added,
598 # so non-default values are instantly available
599
600 # A list, for example:
601 # config.dipswitches = ConfigSubList()
602 # config.dipswitches.append(ConfigYesNo())
603 # config.dipswitches.append(ConfigYesNo())
604 # config.dipswitches.append(ConfigYesNo())
605 class ConfigSubList(list, object):
606         def __init__(self):
607                 object.__init__(self)
608                 list.__init__(self)
609                 self.stored_values = {}
610
611         def save(self):
612                 for x in self:
613                         x.save()
614         
615         def load(self):
616                 for x in self:
617                         x.load()
618
619         def getSavedValue(self):
620                 res = {}
621                 for i in range(len(self)):
622                         sv = self[i].saved_value
623                         if sv is not None:
624                                 res[str(i)] = sv
625                 return res
626
627         def setSavedValue(self, values):
628                 self.stored_values = dict(values)
629                 for (key, val) in self.stored_values.items():
630                         if int(key) < len(self):
631                                 self[int(key)].saved_value = val
632
633         saved_value = property(getSavedValue, setSavedValue)
634         
635         def append(self, item):
636                 i = str(len(self))
637                 list.append(self, item)
638                 if i in self.stored_values:
639                         item.saved_value = self.stored_values[i]
640                         item.load()
641
642 # same as ConfigSubList, just as a dictionary.
643 # care must be taken that the 'key' has a proper
644 # str() method, because it will be used in the config
645 # file.
646 class ConfigSubDict(dict, object):
647         def __init__(self):
648                 object.__init__(self)
649                 dict.__init__(self)
650                 self.stored_values = {}
651
652         def save(self):
653                 for x in self.values():
654                         x.save()
655         
656         def load(self):
657                 for x in self.values():
658                         x.load()
659
660         def getSavedValue(self):
661                 res = {}
662                 for (key, val) in self.items():
663                         if val.saved_value is not None:
664                                 res[str(key)] = val.saved_value
665                 return res
666
667         def setSavedValue(self, values):
668                 self.stored_values = dict(values)
669                 for (key, val) in self.items():
670                         if str(key) in self.stored_values:
671                                 val = self.stored_values[str(key)]
672
673         saved_value = property(getSavedValue, setSavedValue)
674
675         def __setitem__(self, key, item):
676                 dict.__setitem__(self, key, item)
677                 if str(key) in self.stored_values:
678                         item.saved_value = self.stored_values[str(key)]
679                         item.load()
680
681 # Like the classes above, just with a more "native"
682 # syntax.
683 #
684 # some evil stuff must be done to allow instant
685 # loading of added elements. this is why this class
686 # is so complex.
687 #
688 # we need the 'content' because we overwrite 
689 # __setattr__.
690 # If you don't understand this, try adding
691 # __setattr__ to a usual exisiting class and you will.
692 class ConfigSubsection(object):
693         def __init__(self):
694                 object.__init__(self)
695                 self.__dict__["content"] = ConfigSubsectionContent()
696                 self.content.items = { }
697                 self.content.stored_values = { }
698         
699         def __setattr__(self, name, value):
700                 if name == "saved_value":
701                         return self.setSavedValue(value)
702                 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"
703                 self.content.items[name] = value
704                 if name in self.content.stored_values:
705                         #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
706                         value.saved_value = self.content.stored_values[name]
707                         value.load()
708
709         def __getattr__(self, name):
710                 return self.content.items[name]
711
712         def getSavedValue(self):
713                 res = self.content.stored_values
714                 for (key, val) in self.content.items.items():
715                         if val.saved_value is not None:
716                                 res[key] = val.saved_value
717                         elif key in res:
718                                 del res[key]
719                                 
720                 return res
721
722         def setSavedValue(self, values):
723                 values = dict(values)
724                 
725                 self.content.stored_values = values
726                 
727                 for (key, val) in self.content.items.items():
728                         if key in values:
729                                 val.setSavedValue(values[key])
730
731         saved_value = property(getSavedValue, setSavedValue)
732
733         def save(self):
734                 for x in self.content.items.values():
735                         x.save()
736
737         def load(self):
738                 for x in self.content.items.values():
739                         x.load()
740
741 # the root config object, which also can "pickle" (=serialize)
742 # down the whole config tree.
743 #
744 # we try to keep non-existing config entries, to apply them whenever
745 # a new config entry is added to a subsection
746 # also, non-existing config entries will be saved, so they won't be
747 # lost when a config entry disappears.
748 class Config(ConfigSubsection):
749         def __init__(self):
750                 ConfigSubsection.__init__(self)
751
752         def pickle_this(self, prefix, topickle, result):
753                 for (key, val) in topickle.items():
754                         name = prefix + "." + key
755                         
756                         if isinstance(val, dict):
757                                 self.pickle_this(name, val, result)
758                         elif isinstance(val, tuple):
759                                 result.append(name + "=" + val[0]) # + " ; " + val[1])
760                         else:
761                                 result.append(name + "=" + val)
762
763         def pickle(self):
764                 result = [ ]
765                 self.pickle_this("config", self.saved_value, result)
766                 return '\n'.join(result) + "\n"
767
768         def unpickle(self, lines):
769                 tree = { }
770                 for l in lines:
771                         if not len(l) or l[0] == '#':
772                                 continue
773                         
774                         n = l.find('=')
775                         val = l[n+1:].strip()
776
777                         names = l[:n].split('.')
778 #                       if val.find(' ') != -1:
779 #                               val = val[:val.find(' ')]
780
781                         base = tree
782                         
783                         for n in names[:-1]:
784                                 base = base.setdefault(n, {})
785                         
786                         base[names[-1]] = val
787
788                 # we inherit from ConfigSubsection, so ...
789                 #object.__setattr__(self, "saved_value", tree["config"])
790                 self.setSavedValue(tree["config"])
791
792         def saveToFile(self, filename):
793                 f = open(filename, "w")
794                 f.write(self.pickle())
795                 f.close()
796
797         def loadFromFile(self, filename):
798                 f = open(filename, "r")
799                 self.unpickle(f.readlines())
800                 f.close()
801
802 config = Config()
803 config.misc = ConfigSubsection()
804
805 class ConfigFile:
806         CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "config2")
807
808         def load(self):
809                 try:
810                         config.loadFromFile(self.CONFIG_FILE)
811                 except IOError, e:
812                         print "unable to load config (%s), assuming defaults..." % str(e)
813         
814         def save(self):
815                 config.save()
816                 config.saveToFile(self.CONFIG_FILE)
817         
818         def getResolvedKey(self, key):
819                 return None # FIXME
820
821 def NoSave(element):
822         element.disableSave()
823         return element
824
825 configfile = ConfigFile()
826
827 configfile.load()
828
829 def getConfigListEntry(desc, config):
830         return (desc, config)
831
832 #def _(x):
833 #       return x
834 #
835 #config.bla = ConfigSubsection()
836 #config.bla.test = ConfigYesNo()
837 #config.nim = ConfigSubList()
838 #config.nim.append(ConfigSubsection())
839 #config.nim[0].bla = ConfigYesNo()
840 #config.nim.append(ConfigSubsection())
841 #config.nim[1].bla = ConfigYesNo()
842 #config.nim[1].blub = ConfigYesNo()
843 #config.arg = ConfigSubDict()
844 #config.arg["Hello"] = ConfigYesNo()
845 #
846 #config.arg["Hello"].handleKey(KEY_RIGHT)
847 #config.arg["Hello"].handleKey(KEY_RIGHT)
848 #
849 ##config.saved_value
850 #
851 ##configfile.save()
852 #config.save()
853 #print config.pickle()