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