Merge branch 'bug_474_fix_multicontent_clear'
[enigma2.git] / lib / python / Components / config.py
1 from enigma import getPrevAsciiCode
2 from Tools.NumericalTextInput import NumericalTextInput
3 from Tools.Directories import resolveFilename, SCOPE_CONFIG, fileExists
4 from Components.Harddisk import harddiskmanager
5 from copy import copy as copy_copy
6 from os import path as os_path
7 from time import localtime, strftime
8
9 # ConfigElement, the base class of all ConfigElements.
10
11 # it stores:
12 #   value    the current value, usefully encoded.
13 #            usually a property which retrieves _value,
14 #            and maybe does some reformatting
15 #   _value   the value as it's going to be saved in the configfile,
16 #            though still in non-string form.
17 #            this is the object which is actually worked on.
18 #   default  the initial value. If _value is equal to default,
19 #            it will not be stored in the config file
20 #   saved_value is a text representation of _value, stored in the config file
21 #
22 # and has (at least) the following methods:
23 #   save()   stores _value into saved_value,
24 #            (or stores 'None' if it should not be stored)
25 #   load()   loads _value from saved_value, or loads
26 #            the default if saved_value is 'None' (default)
27 #            or invalid.
28 #
29 class ConfigElement(object):
30         def __init__(self):
31                 self.saved_value = None
32                 self.last_value = None
33                 self.save_disabled = False
34                 self.__notifiers = None
35                 self.__notifiers_final = None
36                 self.enabled = True
37                 self.callNotifiersOnSaveAndCancel = False
38
39         def getNotifiers(self):
40                 if self.__notifiers is None:
41                         self.__notifiers = [ ]
42                 return self.__notifiers
43
44         def setNotifiers(self, val):
45                 self.__notifiers = val
46
47         notifiers = property(getNotifiers, setNotifiers)
48
49         def getNotifiersFinal(self):
50                 if self.__notifiers_final is None:
51                         self.__notifiers_final = [ ]
52                 return self.__notifiers_final
53
54         def setNotifiersFinal(self, val):
55                 self.__notifiers_final = val
56
57         notifiers_final = property(getNotifiersFinal, setNotifiersFinal)
58
59         # you need to override this to do input validation
60         def setValue(self, value):
61                 self._value = value
62                 self.changed()
63
64         def getValue(self):
65                 return self._value
66
67         value = property(getValue, setValue)
68
69         # you need to override this if self.value is not a string
70         def fromstring(self, value):
71                 return value
72
73         # you can overide this for fancy default handling
74         def load(self):
75                 sv = self.saved_value
76                 if sv is None:
77                         self.value = self.default
78                 else:
79                         self.value = self.fromstring(sv)
80
81         def tostring(self, value):
82                 return str(value)
83
84         # you need to override this if str(self.value) doesn't work
85         def save(self):
86                 if self.save_disabled or self.value == self.default:
87                         self.saved_value = None
88                 else:
89                         self.saved_value = self.tostring(self.value)
90                 if self.callNotifiersOnSaveAndCancel:
91                         self.changed()
92
93         def cancel(self):
94                 self.load()
95                 if self.callNotifiersOnSaveAndCancel:
96                         self.changed()
97
98         def isChanged(self):
99                 sv = self.saved_value
100                 if sv is None and self.value == self.default:
101                         return False
102                 return self.tostring(self.value) != sv
103
104         def changed(self):
105                 if self.__notifiers:
106                         for x in self.notifiers:
107                                 x(self)
108
109         def changedFinal(self):
110                 if self.__notifiers_final:
111                         for x in self.notifiers_final:
112                                 x(self)
113
114         def addNotifier(self, notifier, initial_call = True, immediate_feedback = True):
115                 assert callable(notifier), "notifiers must be callable"
116                 if immediate_feedback:
117                         self.notifiers.append(notifier)
118                 else:
119                         self.notifiers_final.append(notifier)
120                 # CHECKME:
121                 # do we want to call the notifier
122                 #  - at all when adding it? (yes, though optional)
123                 #  - when the default is active? (yes)
124                 #  - when no value *yet* has been set,
125                 #    because no config has ever been read (currently yes)
126                 #    (though that's not so easy to detect.
127                 #     the entry could just be new.)
128                 if initial_call:
129                         notifier(self)
130
131         def disableSave(self):
132                 self.save_disabled = True
133
134         def __call__(self, selected):
135                 return self.getMulti(selected)
136
137         def onSelect(self, session):
138                 pass
139
140         def onDeselect(self, session):
141                 if not self.last_value == self.value:
142                         self.changedFinal()
143                         self.last_value = self.value
144
145 KEY_LEFT = 0
146 KEY_RIGHT = 1
147 KEY_OK = 2
148 KEY_DELETE = 3
149 KEY_BACKSPACE = 4
150 KEY_HOME = 5
151 KEY_END = 6
152 KEY_TOGGLEOW = 7
153 KEY_ASCII = 8
154 KEY_TIMEOUT = 9
155 KEY_NUMBERS = range(12, 12+10)
156 KEY_0 = 12
157 KEY_9 = 12+9
158
159 def getKeyNumber(key):
160         assert key in KEY_NUMBERS
161         return key - KEY_0
162
163 class choicesList(object): # XXX: we might want a better name for this
164         LIST_TYPE_LIST = 1
165         LIST_TYPE_DICT = 2
166
167         def __init__(self, choices, type = None):
168                 self.choices = choices
169                 if type is None:
170                         if isinstance(choices, list):
171                                 self.type = choicesList.LIST_TYPE_LIST
172                         elif isinstance(choices, dict):
173                                 self.type = choicesList.LIST_TYPE_DICT
174                         else:
175                                 assert False, "choices must be dict or list!"
176                 else:
177                         self.type = type
178
179         def __list__(self):
180                 if self.type == choicesList.LIST_TYPE_LIST:
181                         ret = [not isinstance(x, tuple) and x or len(x) > 0 and x[0] or len(x) == 0 and x for x in self.choices]
182                 else:
183                         ret = self.choices.keys()
184                 return ret or [""]
185
186         def __iter__(self):
187                 if self.type == choicesList.LIST_TYPE_LIST:
188                         ret = [not isinstance(x, tuple) and x or x[0] for x in self.choices]
189                 else:
190                         ret = self.choices
191                 return iter(ret or [""])
192
193         def __len__(self):
194                 return len(self.choices) or 1
195
196         def __getitem__(self, index):
197                 if self.type == choicesList.LIST_TYPE_LIST:
198                         ret = self.choices[index]
199                         if isinstance(ret, tuple):
200                                 ret = ret[0]
201                         return ret
202                 return self.choices.keys()[index]
203
204         def index(self, value):
205                 return self.__list__().index(value)
206
207         def __setitem__(self, index, value):
208                 if self.type == choicesList.LIST_TYPE_LIST:
209                         orig = self.choices[index]
210                         if isinstance(orig, tuple):
211                                 self.choices[index] = (value, orig[1])
212                         else:
213                                 self.choices[index] = value
214                 else:
215                         key = self.choices.keys()[index]
216                         orig = self.choices[key]
217                         del self.choices[key]
218                         self.choices[value] = orig
219
220         def default(self):
221                 choices = self.choices
222                 if not choices:
223                         return ""
224                 if self.type is choicesList.LIST_TYPE_LIST:
225                         default = choices[0]
226                         if isinstance(default, tuple):
227                                 default = default[0]
228                 else:
229                         default = choices.keys()[0]
230                 return default
231
232 class descriptionList(choicesList): # XXX: we might want a better name for this
233         def __list__(self):
234                 if self.type == choicesList.LIST_TYPE_LIST:
235                         ret = [not isinstance(x, tuple) and x or x[1] for x in self.choices]
236                 else:
237                         ret = self.choices.values()
238                 return ret or [""]
239
240         def __iter__(self):
241                 return iter(self.__list__())
242
243         def __getitem__(self, index):
244                 if self.type == choicesList.LIST_TYPE_LIST:
245                         for x in self.choices:
246                                 if isinstance(x, tuple):
247                                         if x[0] == index:
248                                                 return str(x[1])
249                                 elif x == index:
250                                         return str(x)
251                         return str(index) # Fallback!
252                 else:
253                         return str(self.choices.get(index, ""))
254
255         def __setitem__(self, index, value):
256                 if self.type == choicesList.LIST_TYPE_LIST:
257                         i = self.index(index)
258                         orig = self.choices[i]
259                         if isinstance(orig, tuple):
260                                 self.choices[i] = (orig[0], value)
261                         else:
262                                 self.choices[i] = value
263                 else:
264                         self.choices[index] = value
265
266 #
267 # ConfigSelection is a "one of.."-type.
268 # it has the "choices", usually a list, which contains
269 # (id, desc)-tuples (or just only the ids, in case the id
270 # will be used as description)
271 #
272 # all ids MUST be plain strings.
273 #
274 class ConfigSelection(ConfigElement):
275         def __init__(self, choices, default = None):
276                 ConfigElement.__init__(self)
277                 self.choices = choicesList(choices)
278
279                 if default is None:
280                         default = self.choices.default()
281
282                 self._descr = None
283                 self.default = self._value = self.last_value = default
284
285         def setChoices(self, choices, default = None):
286                 self.choices = choicesList(choices)
287
288                 if default is None:
289                         default = self.choices.default()
290                 self.default = default
291
292                 if self.value not in self.choices:
293                         self.value = default
294
295         def setValue(self, value):
296                 if value in self.choices:
297                         self._value = value
298                 else:
299                         self._value = self.default
300                 self._descr = None
301                 self.changed()
302
303         def tostring(self, val):
304                 return val
305
306         def getValue(self):
307                 return self._value
308
309         def setCurrentText(self, text):
310                 i = self.choices.index(self.value)
311                 self.choices[i] = text
312                 self._descr = self.description[text] = text
313                 self._value = text
314
315         value = property(getValue, setValue)
316
317         def getIndex(self):
318                 return self.choices.index(self.value)
319
320         index = property(getIndex)
321
322         # GUI
323         def handleKey(self, key):
324                 nchoices = len(self.choices)
325                 i = self.choices.index(self.value)
326                 if key == KEY_LEFT:
327                         self.value = self.choices[(i + nchoices - 1) % nchoices]
328                 elif key == KEY_RIGHT:
329                         self.value = self.choices[(i + 1) % nchoices]
330                 elif key == KEY_HOME:
331                         self.value = self.choices[0]
332                 elif key == KEY_END:
333                         self.value = self.choices[nchoices - 1]
334
335         def selectNext(self):
336                 nchoices = len(self.choices)
337                 i = self.choices.index(self.value)
338                 self.value = self.choices[(i + 1) % nchoices]
339
340         def getText(self):
341                 if self._descr is not None:
342                         return self._descr
343                 descr = self._descr = self.description[self.value]
344                 if descr:
345                         return _(descr)
346                 return descr
347
348         def getMulti(self, selected):
349                 if self._descr is not None:
350                         descr = self._descr
351                 else:
352                         descr = self._descr = self.description[self.value]
353                 if descr:
354                         return ("text", _(descr))
355                 return ("text", descr)
356
357         # HTML
358         def getHTML(self, id):
359                 res = ""
360                 for v in self.choices:
361                         descr = self.description[v]
362                         if self.value == v:
363                                 checked = 'checked="checked" '
364                         else:
365                                 checked = ''
366                         res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + descr + "</input></br>\n"
367                 return res;
368
369         def unsafeAssign(self, value):
370                 # setValue does check if value is in choices. This is safe enough.
371                 self.value = value
372
373         description = property(lambda self: descriptionList(self.choices.choices, self.choices.type))
374
375 # a binary decision.
376 #
377 # several customized versions exist for different
378 # descriptions.
379 #
380 boolean_descriptions = {False: "false", True: "true"}
381 class ConfigBoolean(ConfigElement):
382         def __init__(self, default = False, descriptions = boolean_descriptions):
383                 ConfigElement.__init__(self)
384                 self.descriptions = descriptions
385                 self.value = self.last_value = self.default = default
386
387         def handleKey(self, key):
388                 if key in (KEY_LEFT, KEY_RIGHT):
389                         self.value = not self.value
390                 elif key == KEY_HOME:
391                         self.value = False
392                 elif key == KEY_END:
393                         self.value = True
394
395         def getText(self):
396                 descr = self.descriptions[self.value]
397                 if descr:
398                         return _(descr)
399                 return descr
400
401         def getMulti(self, selected):
402                 descr = self.descriptions[self.value]
403                 if descr:
404                         return ("text", _(descr))
405                 return ("text", descr)
406
407         def tostring(self, value):
408                 if not value:
409                         return "false"
410                 else:
411                         return "true"
412
413         def fromstring(self, val):
414                 if val == "true":
415                         return True
416                 else:
417                         return False
418
419         def getHTML(self, id):
420                 if self.value:
421                         checked = ' checked="checked"'
422                 else:
423                         checked = ''
424                 return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />"
425
426         # this is FLAWED. and must be fixed.
427         def unsafeAssign(self, value):
428                 if value == "1":
429                         self.value = True
430                 else:
431                         self.value = False
432
433         def onDeselect(self, session):
434                 if not self.last_value == self.value:
435                         self.changedFinal()
436                         self.last_value = self.value
437
438 yes_no_descriptions = {False: _("no"), True: _("yes")}
439 class ConfigYesNo(ConfigBoolean):
440         def __init__(self, default = False):
441                 ConfigBoolean.__init__(self, default = default, descriptions = yes_no_descriptions)
442
443 on_off_descriptions = {False: _("off"), True: _("on")}
444 class ConfigOnOff(ConfigBoolean):
445         def __init__(self, default = False):
446                 ConfigBoolean.__init__(self, default = default, descriptions = on_off_descriptions)
447
448 enable_disable_descriptions = {False: _("disable"), True: _("enable")}
449 class ConfigEnableDisable(ConfigBoolean):
450         def __init__(self, default = False):
451                 ConfigBoolean.__init__(self, default = default, descriptions = enable_disable_descriptions)
452
453 class ConfigDateTime(ConfigElement):
454         def __init__(self, default, formatstring, increment = 86400):
455                 ConfigElement.__init__(self)
456                 self.increment = increment
457                 self.formatstring = formatstring
458                 self.value = self.last_value = self.default = int(default)
459
460         def handleKey(self, key):
461                 if key == KEY_LEFT:
462                         self.value = self.value - self.increment
463                 elif key == KEY_RIGHT:
464                         self.value = self.value + self.increment
465                 elif key == KEY_HOME or key == KEY_END:
466                         self.value = self.default
467
468         def getText(self):
469                 return strftime(self.formatstring, localtime(self.value))
470
471         def getMulti(self, selected):
472                 return ("text", strftime(self.formatstring, localtime(self.value)))
473
474         def fromstring(self, val):
475                 return int(val)
476
477 # *THE* mighty config element class
478 #
479 # allows you to store/edit a sequence of values.
480 # can be used for IP-addresses, dates, plain integers, ...
481 # several helper exist to ease this up a bit.
482 #
483 class ConfigSequence(ConfigElement):
484         def __init__(self, seperator, limits, default, censor_char = ""):
485                 ConfigElement.__init__(self)
486                 assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list"
487                 assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")"
488                 #assert isinstance(default, list), "default must be a list"
489                 #assert isinstance(default[0], int), "list must contain numbers"
490                 #assert len(default) == len(limits), "length must match"
491
492                 self.marked_pos = 0
493                 self.seperator = seperator
494                 self.limits = limits
495                 self.censor_char = censor_char
496
497                 self.last_value = self.default = default
498                 self.value = copy_copy(default)
499                 self.endNotifier = None
500
501         def validate(self):
502                 max_pos = 0
503                 num = 0
504                 for i in self._value:
505                         max_pos += len(str(self.limits[num][1]))
506
507                         if self._value[num] < self.limits[num][0]:
508                                 self._value[num] = self.limits[num][0]
509
510                         if self._value[num] > self.limits[num][1]:
511                                 self._value[num] = self.limits[num][1]
512
513                         num += 1
514
515                 if self.marked_pos >= max_pos:
516                         if self.endNotifier:
517                                 for x in self.endNotifier:
518                                         x(self)
519                         self.marked_pos = max_pos - 1
520
521                 if self.marked_pos < 0:
522                         self.marked_pos = 0
523
524         def validatePos(self):
525                 if self.marked_pos < 0:
526                         self.marked_pos = 0
527
528                 total_len = sum([len(str(x[1])) for x in self.limits])
529
530                 if self.marked_pos >= total_len:
531                         self.marked_pos = total_len - 1
532
533         def addEndNotifier(self, notifier):
534                 if self.endNotifier is None:
535                         self.endNotifier = []
536                 self.endNotifier.append(notifier)
537
538         def handleKey(self, key):
539                 if key == KEY_LEFT:
540                         self.marked_pos -= 1
541                         self.validatePos()
542
543                 elif key == KEY_RIGHT:
544                         self.marked_pos += 1
545                         self.validatePos()
546
547                 elif key == KEY_HOME:
548                         self.marked_pos = 0
549                         self.validatePos()
550
551                 elif key == KEY_END:
552                         max_pos = 0
553                         num = 0
554                         for i in self._value:
555                                 max_pos += len(str(self.limits[num][1]))
556                                 num += 1
557                         self.marked_pos = max_pos - 1
558                         self.validatePos()
559
560                 elif key in KEY_NUMBERS or key == KEY_ASCII:
561                         if key == KEY_ASCII:
562                                 code = getPrevAsciiCode()
563                                 if code < 48 or code > 57:
564                                         return
565                                 number = code - 48
566                         else:
567                                 number = getKeyNumber(key)
568
569                         block_len = [len(str(x[1])) for x in self.limits]
570                         total_len = sum(block_len)
571
572                         pos = 0
573                         blocknumber = 0
574                         block_len_total = [0, ]
575                         for x in block_len:
576                                 pos += block_len[blocknumber]
577                                 block_len_total.append(pos)
578                                 if pos - 1 >= self.marked_pos:
579                                         pass
580                                 else:
581                                         blocknumber += 1
582
583                         # length of numberblock
584                         number_len = len(str(self.limits[blocknumber][1]))
585
586                         # position in the block
587                         posinblock = self.marked_pos - block_len_total[blocknumber]
588
589                         oldvalue = self._value[blocknumber]
590                         olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1))
591                         newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number)
592
593                         self._value[blocknumber] = newvalue
594                         self.marked_pos += 1
595
596                         self.validate()
597                         self.changed()
598
599         def genText(self):
600                 value = ""
601                 mPos = self.marked_pos
602                 num = 0;
603                 for i in self._value:
604                         if value:       #fixme no heading separator possible
605                                 value += self.seperator
606                                 if mPos >= len(value) - 1:
607                                         mPos += 1
608                         if self.censor_char == "":
609                                 value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i
610                         else:
611                                 value += (self.censor_char * len(str(self.limits[num][1])))
612                         num += 1
613                 return (value, mPos)
614
615         def getText(self):
616                 (value, mPos) = self.genText()
617                 return value
618
619         def getMulti(self, selected):
620                 (value, mPos) = self.genText()
621                         # only mark cursor when we are selected
622                         # (this code is heavily ink optimized!)
623                 if self.enabled:
624                         return ("mtext"[1-selected:], value, [mPos])
625                 else:
626                         return ("text", value)
627
628         def tostring(self, val):
629                 return self.seperator.join([self.saveSingle(x) for x in val])
630
631         def saveSingle(self, v):
632                 return str(v)
633
634         def fromstring(self, value):
635                 return [int(x) for x in value.split(self.seperator)]
636
637         def onDeselect(self, session):
638                 if self.last_value != self._value:
639                         self.changedFinal()
640                         self.last_value = copy_copy(self._value)
641
642 ip_limits = [(0,255),(0,255),(0,255),(0,255)]
643 class ConfigIP(ConfigSequence):
644         def __init__(self, default, auto_jump = False):
645                 ConfigSequence.__init__(self, seperator = ".", limits = ip_limits, default = default)
646                 self.block_len = [len(str(x[1])) for x in self.limits]
647                 self.marked_block = 0
648                 self.overwrite = True
649                 self.auto_jump = auto_jump
650
651         def handleKey(self, key):
652                 if key == KEY_LEFT:
653                         if self.marked_block > 0:
654                                 self.marked_block -= 1
655                         self.overwrite = True
656
657                 elif key == KEY_RIGHT:
658                         if self.marked_block < len(self.limits)-1:
659                                 self.marked_block += 1
660                         self.overwrite = True
661
662                 elif key == KEY_HOME:
663                         self.marked_block = 0
664                         self.overwrite = True
665
666                 elif key == KEY_END:
667                         self.marked_block = len(self.limits)-1
668                         self.overwrite = True
669
670                 elif key in KEY_NUMBERS or key == KEY_ASCII:
671                         if key == KEY_ASCII:
672                                 code = getPrevAsciiCode()
673                                 if code < 48 or code > 57:
674                                         return
675                                 number = code - 48
676                         else:
677                                 number = getKeyNumber(key)
678                         oldvalue = self._value[self.marked_block]
679
680                         if self.overwrite:
681                                 self._value[self.marked_block] = number
682                                 self.overwrite = False
683                         else:
684                                 oldvalue *= 10
685                                 newvalue = oldvalue + number
686                                 if self.auto_jump and newvalue > self.limits[self.marked_block][1] and self.marked_block < len(self.limits)-1:
687                                         self.handleKey(KEY_RIGHT)
688                                         self.handleKey(key)
689                                         return
690                                 else:
691                                         self._value[self.marked_block] = newvalue
692
693                         if len(str(self._value[self.marked_block])) >= self.block_len[self.marked_block]:
694                                 self.handleKey(KEY_RIGHT)
695
696                         self.validate()
697                         self.changed()
698
699         def genText(self):
700                 value = ""
701                 block_strlen = []
702                 for i in self._value:
703                         block_strlen.append(len(str(i)))
704                         if value:
705                                 value += self.seperator
706                         value += str(i)
707                 leftPos = sum(block_strlen[:(self.marked_block)])+self.marked_block
708                 rightPos = sum(block_strlen[:(self.marked_block+1)])+self.marked_block
709                 mBlock = range(leftPos, rightPos)
710                 return (value, mBlock)
711
712         def getMulti(self, selected):
713                 (value, mBlock) = self.genText()
714                 if self.enabled:
715                         return ("mtext"[1-selected:], value, mBlock)
716                 else:
717                         return ("text", value)
718
719         def getHTML(self, id):
720                 # we definitely don't want leading zeros
721                 return '.'.join(["%d" % d for d in self.value])
722
723 mac_limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)]
724 class ConfigMAC(ConfigSequence):
725         def __init__(self, default):
726                 ConfigSequence.__init__(self, seperator = ":", limits = mac_limits, default = default)
727
728 class ConfigPosition(ConfigSequence):
729         def __init__(self, default, args):
730                 ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default)
731
732 clock_limits = [(0,23),(0,59)]
733 class ConfigClock(ConfigSequence):
734         def __init__(self, default):
735                 t = localtime(default)
736                 ConfigSequence.__init__(self, seperator = ":", limits = clock_limits, default = [t.tm_hour, t.tm_min])
737
738         def increment(self):
739                 # Check if Minutes maxed out
740                 if self._value[1] == 59:
741                         # Increment Hour, reset Minutes
742                         if self._value[0] < 23:
743                                 self._value[0] += 1
744                         else:
745                                 self._value[0] = 0
746                         self._value[1] = 0
747                 else:
748                         # Increment Minutes
749                         self._value[1] += 1
750                 # Trigger change
751                 self.changed()
752
753         def decrement(self):
754                 # Check if Minutes is minimum
755                 if self._value[1] == 0:
756                         # Decrement Hour, set Minutes to 59
757                         if self._value[0] > 0:
758                                 self._value[0] -= 1
759                         else:
760                                 self._value[0] = 23
761                         self._value[1] = 59
762                 else:
763                         # Decrement Minutes
764                         self._value[1] -= 1
765                 # Trigger change
766                 self.changed()
767
768 integer_limits = (0, 9999999999)
769 class ConfigInteger(ConfigSequence):
770         def __init__(self, default, limits = integer_limits):
771                 ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default)
772
773         # you need to override this to do input validation
774         def setValue(self, value):
775                 self._value = [value]
776                 self.changed()
777
778         def getValue(self):
779                 return self._value[0]
780
781         value = property(getValue, setValue)
782
783         def fromstring(self, value):
784                 return int(value)
785
786         def tostring(self, value):
787                 return str(value)
788
789 class ConfigPIN(ConfigInteger):
790         def __init__(self, default, len = 4, censor = ""):
791                 assert isinstance(default, int), "ConfigPIN default must be an integer"
792                 if default == -1:
793                         default = "aaaa"
794                 ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = default)
795                 self.len = len
796
797         def getLength(self):
798                 return self.len
799
800 class ConfigFloat(ConfigSequence):
801         def __init__(self, default, limits):
802                 ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default)
803
804         def getFloat(self):
805                 return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0])
806
807         float = property(getFloat)
808
809 # an editable text...
810 class ConfigText(ConfigElement, NumericalTextInput):
811         def __init__(self, default = "", fixed_size = True, visible_width = False):
812                 ConfigElement.__init__(self)
813                 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
814
815                 self.marked_pos = 0
816                 self.allmarked = (default != "")
817                 self.fixed_size = fixed_size
818                 self.visible_width = visible_width
819                 self.offset = 0
820                 self.overwrite = fixed_size
821                 self.help_window = None
822                 self.value = self.last_value = self.default = default
823
824         def validateMarker(self):
825                 textlen = len(self.text)
826                 if self.fixed_size:
827                         if self.marked_pos > textlen-1:
828                                 self.marked_pos = textlen-1
829                 else:
830                         if self.marked_pos > textlen:
831                                 self.marked_pos = textlen
832                 if self.marked_pos < 0:
833                         self.marked_pos = 0
834                 if self.visible_width:
835                         if self.marked_pos < self.offset:
836                                 self.offset = self.marked_pos
837                         if self.marked_pos >= self.offset + self.visible_width:
838                                 if self.marked_pos == textlen:
839                                         self.offset = self.marked_pos - self.visible_width
840                                 else:
841                                         self.offset = self.marked_pos - self.visible_width + 1
842                         if self.offset > 0 and self.offset + self.visible_width > textlen:
843                                 self.offset = max(0, len - self.visible_width)
844
845         def insertChar(self, ch, pos, owr):
846                 if owr or self.overwrite:
847                         self.text = self.text[0:pos] + ch + self.text[pos + 1:]
848                 elif self.fixed_size:
849                         self.text = self.text[0:pos] + ch + self.text[pos:-1]
850                 else:
851                         self.text = self.text[0:pos] + ch + self.text[pos:]
852
853         def deleteChar(self, pos):
854                 if not self.fixed_size:
855                         self.text = self.text[0:pos] + self.text[pos + 1:]
856                 elif self.overwrite:
857                         self.text = self.text[0:pos] + " " + self.text[pos + 1:]
858                 else:
859                         self.text = self.text[0:pos] + self.text[pos + 1:] + " "
860
861         def deleteAllChars(self):
862                 if self.fixed_size:
863                         self.text = " " * len(self.text)
864                 else:
865                         self.text = ""
866                 self.marked_pos = 0
867
868         def handleKey(self, key):
869                 # this will no change anything on the value itself
870                 # so we can handle it here in gui element
871                 if key == KEY_DELETE:
872                         self.timeout()
873                         if self.allmarked:
874                                 self.deleteAllChars()
875                                 self.allmarked = False
876                         else:
877                                 self.deleteChar(self.marked_pos)
878                                 if self.fixed_size and self.overwrite:
879                                         self.marked_pos += 1
880                 elif key == KEY_BACKSPACE:
881                         self.timeout()
882                         if self.allmarked:
883                                 self.deleteAllChars()
884                                 self.allmarked = False
885                         elif self.marked_pos > 0:
886                                 self.deleteChar(self.marked_pos-1)
887                                 if not self.fixed_size and self.offset > 0:
888                                         self.offset -= 1
889                                 self.marked_pos -= 1
890                 elif key == KEY_LEFT:
891                         self.timeout()
892                         if self.allmarked:
893                                 self.marked_pos = len(self.text)
894                                 self.allmarked = False
895                         else:
896                                 self.marked_pos -= 1
897                 elif key == KEY_RIGHT:
898                         self.timeout()
899                         if self.allmarked:
900                                 self.marked_pos = 0
901                                 self.allmarked = False
902                         else:
903                                 self.marked_pos += 1
904                 elif key == KEY_HOME:
905                         self.timeout()
906                         self.allmarked = False
907                         self.marked_pos = 0
908                 elif key == KEY_END:
909                         self.timeout()
910                         self.allmarked = False
911                         self.marked_pos = len(self.text)
912                 elif key == KEY_TOGGLEOW:
913                         self.timeout()
914                         self.overwrite = not self.overwrite
915                 elif key == KEY_ASCII:
916                         self.timeout()
917                         newChar = unichr(getPrevAsciiCode())
918                         if not self.useableChars or newChar in self.useableChars:
919                                 if self.allmarked:
920                                         self.deleteAllChars()
921                                         self.allmarked = False
922                                 self.insertChar(newChar, self.marked_pos, False)
923                                 self.marked_pos += 1
924                 elif key in KEY_NUMBERS:
925                         owr = self.lastKey == getKeyNumber(key)
926                         newChar = self.getKey(getKeyNumber(key))
927                         if self.allmarked:
928                                 self.deleteAllChars()
929                                 self.allmarked = False
930                         self.insertChar(newChar, self.marked_pos, owr)
931                 elif key == KEY_TIMEOUT:
932                         self.timeout()
933                         if self.help_window:
934                                 self.help_window.update(self)
935                         return
936
937                 if self.help_window:
938                         self.help_window.update(self)
939                 self.validateMarker()
940                 self.changed()
941
942         def nextFunc(self):
943                 self.marked_pos += 1
944                 self.validateMarker()
945                 self.changed()
946
947         def getValue(self):
948                 return self.text.encode("utf-8")
949
950         def setValue(self, val):
951                 try:
952                         self.text = val.decode("utf-8")
953                 except UnicodeDecodeError:
954                         self.text = val.decode("utf-8", "ignore")
955                         print "Broken UTF8!"
956
957         value = property(getValue, setValue)
958         _value = property(getValue, setValue)
959
960         def getText(self):
961                 return self.text.encode("utf-8")
962
963         def getMulti(self, selected):
964                 if self.visible_width:
965                         if self.allmarked:
966                                 mark = range(0, min(self.visible_width, len(self.text)))
967                         else:
968                                 mark = [self.marked_pos-self.offset]
969                         return ("mtext"[1-selected:], self.text[self.offset:self.offset+self.visible_width].encode("utf-8")+" ", mark)
970                 else:
971                         if self.allmarked:
972                                 mark = range(0, len(self.text))
973                         else:
974                                 mark = [self.marked_pos]
975                         return ("mtext"[1-selected:], self.text.encode("utf-8")+" ", mark)
976
977         def onSelect(self, session):
978                 self.allmarked = (self.value != "")
979                 if session is not None:
980                         from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog
981                         self.help_window = session.instantiateDialog(NumericalTextInputHelpDialog, self)
982                         self.help_window.show()
983
984         def onDeselect(self, session):
985                 self.marked_pos = 0
986                 self.offset = 0
987                 if self.help_window:
988                         session.deleteDialog(self.help_window)
989                         self.help_window = None
990                 if not self.last_value == self.value:
991                         self.changedFinal()
992                         self.last_value = self.value
993
994         def getHTML(self, id):
995                 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
996
997         def unsafeAssign(self, value):
998                 self.value = str(value)
999
1000 class ConfigPassword(ConfigText):
1001         def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
1002                 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1003                 self.censor_char = censor
1004                 self.hidden = True
1005
1006         def getMulti(self, selected):
1007                 mtext, text, mark = ConfigText.getMulti(self, selected)
1008                 if self.hidden:
1009                         text = len(text) * self.censor_char
1010                 return (mtext, text, mark)
1011
1012         def onSelect(self, session):
1013                 ConfigText.onSelect(self, session)
1014                 self.hidden = False
1015
1016         def onDeselect(self, session):
1017                 ConfigText.onDeselect(self, session)
1018                 self.hidden = True
1019
1020 # lets the user select between [min, min+stepwidth, min+(stepwidth*2)..., maxval] with maxval <= max depending
1021 # on the stepwidth
1022 # min, max, stepwidth, default are int values
1023 # wraparound: pressing RIGHT key at max value brings you to min value and vice versa if set to True
1024 class ConfigSelectionNumber(ConfigSelection):
1025         def __init__(self, min, max, stepwidth, default = None, wraparound = False):
1026                 self.wraparound = wraparound
1027                 if default is None:
1028                         default = min
1029                 default = str(default)
1030                 choices = []
1031                 step = min
1032                 while step <= max:
1033                         choices.append(str(step))
1034                         step += stepwidth
1035                 
1036                 ConfigSelection.__init__(self, choices, default)
1037
1038         def getValue(self):
1039                 return int(ConfigSelection.getValue(self))
1040
1041         def setValue(self, val):
1042                 ConfigSelection.setValue(self, str(val))
1043
1044         def handleKey(self, key):
1045                 if not self.wraparound:
1046                         if key == KEY_RIGHT:
1047                                 if len(self.choices) == (self.choices.index(self.value) + 1):
1048                                         return
1049                         if key == KEY_LEFT:
1050                                 if self.choices.index(self.value) == 0:
1051                                         return
1052                 ConfigSelection.handleKey(self, key)
1053
1054 class ConfigNumber(ConfigText):
1055         def __init__(self, default = 0):
1056                 ConfigText.__init__(self, str(default), fixed_size = False)
1057
1058         def getValue(self):
1059                 return int(self.text)
1060
1061         def setValue(self, val):
1062                 self.text = str(val)
1063
1064         value = property(getValue, setValue)
1065         _value = property(getValue, setValue)
1066
1067         def isChanged(self):
1068                 sv = self.saved_value
1069                 strv = self.tostring(self.value)
1070                 if sv is None and strv == self.default:
1071                         return False
1072                 return strv != sv
1073
1074         def conform(self):
1075                 pos = len(self.text) - self.marked_pos
1076                 self.text = self.text.lstrip("0")
1077                 if self.text == "":
1078                         self.text = "0"
1079                 if pos > len(self.text):
1080                         self.marked_pos = 0
1081                 else:
1082                         self.marked_pos = len(self.text) - pos
1083
1084         def handleKey(self, key):
1085                 if key in KEY_NUMBERS or key == KEY_ASCII:
1086                         if key == KEY_ASCII:
1087                                 ascii = getPrevAsciiCode()
1088                                 if not (48 <= ascii <= 57):
1089                                         return
1090                         else:
1091                                 ascii = getKeyNumber(key) + 48
1092                         newChar = unichr(ascii)
1093                         if self.allmarked:
1094                                 self.deleteAllChars()
1095                                 self.allmarked = False
1096                         self.insertChar(newChar, self.marked_pos, False)
1097                         self.marked_pos += 1
1098                 else:
1099                         ConfigText.handleKey(self, key)
1100                 self.conform()
1101
1102         def onSelect(self, session):
1103                 self.allmarked = (self.value != "")
1104
1105         def onDeselect(self, session):
1106                 self.marked_pos = 0
1107                 self.offset = 0
1108                 if not self.last_value == self.value:
1109                         self.changedFinal()
1110                         self.last_value = self.value
1111
1112 class ConfigSearchText(ConfigText):
1113         def __init__(self, default = "", fixed_size = False, visible_width = False):
1114                 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1115                 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = True)
1116
1117 class ConfigDirectory(ConfigText):
1118         def __init__(self, default="", visible_width=60):
1119                 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
1120
1121         def handleKey(self, key):
1122                 pass
1123
1124         def getValue(self):
1125                 if self.text == "":
1126                         return None
1127                 else:
1128                         return ConfigText.getValue(self)
1129
1130         def setValue(self, val):
1131                 if val == None:
1132                         val = ""
1133                 ConfigText.setValue(self, val)
1134
1135         def getMulti(self, selected):
1136                 if self.text == "":
1137                         return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
1138                 else:
1139                         return ConfigText.getMulti(self, selected)
1140
1141         def onSelect(self, session):
1142                 self.allmarked = (self.value != "")
1143
1144 # a slider.
1145 class ConfigSlider(ConfigElement):
1146         def __init__(self, default = 0, increment = 1, limits = (0, 100)):
1147                 ConfigElement.__init__(self)
1148                 self.value = self.last_value = self.default = default
1149                 self.min = limits[0]
1150                 self.max = limits[1]
1151                 self.increment = increment
1152
1153         def checkValues(self):
1154                 if self.value < self.min:
1155                         self.value = self.min
1156
1157                 if self.value > self.max:
1158                         self.value = self.max
1159
1160         def handleKey(self, key):
1161                 if key == KEY_LEFT:
1162                         self.value -= self.increment
1163                 elif key == KEY_RIGHT:
1164                         self.value += self.increment
1165                 elif key == KEY_HOME:
1166                         self.value = self.min
1167                 elif key == KEY_END:
1168                         self.value = self.max
1169                 else:
1170                         return
1171                 self.checkValues()
1172
1173         def getText(self):
1174                 return "%d / %d" % (self.value, self.max)
1175
1176         def getMulti(self, selected):
1177                 self.checkValues()
1178                 return ("slider", self.value, self.max)
1179
1180         def fromstring(self, value):
1181                 return int(value)
1182
1183 # a satlist. in fact, it's a ConfigSelection.
1184 class ConfigSatlist(ConfigSelection):
1185         def __init__(self, list, default = None):
1186                 if default is not None:
1187                         default = str(default)
1188                 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1189
1190         def getOrbitalPosition(self):
1191                 if self.value == "":
1192                         return None
1193                 return int(self.value)
1194
1195         orbital_position = property(getOrbitalPosition)
1196
1197 class ConfigSet(ConfigElement):
1198         def __init__(self, choices, default = []):
1199                 ConfigElement.__init__(self)
1200                 if isinstance(choices, list):
1201                         choices.sort()
1202                         self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
1203                 else:
1204                         assert False, "ConfigSet choices must be a list!"
1205                 if default is None:
1206                         default = []
1207                 self.pos = -1
1208                 default.sort()
1209                 self.last_value = self.default = default
1210                 self.value = default[:]
1211
1212         def toggleChoice(self, choice):
1213                 value = self.value
1214                 if choice in value:
1215                         value.remove(choice)
1216                 else:
1217                         value.append(choice)
1218                         value.sort()
1219                 self.changed()
1220
1221         def handleKey(self, key):
1222                 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1223                         if self.pos != -1:
1224                                 self.toggleChoice(self.choices[self.pos])
1225                 elif key == KEY_LEFT:
1226                         if self.pos < 0:
1227                                 self.pos = len(self.choices)-1
1228                         else:
1229                                 self.pos -= 1
1230                 elif key == KEY_RIGHT:
1231                         if self.pos >= len(self.choices)-1:
1232                                 self.pos = -1
1233                         else:
1234                                 self.pos += 1
1235                 elif key in (KEY_HOME, KEY_END):
1236                         self.pos = -1
1237
1238         def genString(self, lst):
1239                 res = ""
1240                 for x in lst:
1241                         res += self.description[x]+" "
1242                 return res
1243
1244         def getText(self):
1245                 return self.genString(self.value)
1246
1247         def getMulti(self, selected):
1248                 if not selected or self.pos == -1:
1249                         return ("text", self.genString(self.value))
1250                 else:
1251                         tmp = self.value[:]
1252                         ch = self.choices[self.pos]
1253                         mem = ch in self.value
1254                         if not mem:
1255                                 tmp.append(ch)
1256                                 tmp.sort()
1257                         ind = tmp.index(ch)
1258                         val1 = self.genString(tmp[:ind])
1259                         val2 = " "+self.genString(tmp[ind+1:])
1260                         if mem:
1261                                 chstr = " "+self.description[ch]+" "
1262                         else:
1263                                 chstr = "("+self.description[ch]+")"
1264                         len_val1 = len(val1)
1265                         return ("mtext", val1+chstr+val2, range(len_val1, len_val1 + len(chstr)))
1266
1267         def onDeselect(self, session):
1268                 self.pos = -1
1269                 if not self.last_value == self.value:
1270                         self.changedFinal()
1271                         self.last_value = self.value[:]
1272
1273         def tostring(self, value):
1274                 return str(value)
1275
1276         def fromstring(self, val):
1277                 return eval(val)
1278
1279         description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
1280
1281 class ConfigLocations(ConfigElement):
1282         def __init__(self, default = [], visible_width = False):
1283                 ConfigElement.__init__(self)
1284                 self.visible_width = visible_width
1285                 self.pos = -1
1286                 self.default = default
1287                 self.locations = []
1288                 self.mountpoints = []
1289                 self.value = default[:]
1290
1291         def setValue(self, value):
1292                 locations = self.locations
1293                 loc = [x[0] for x in locations if x[3]]
1294                 add = [x for x in value if not x in loc]
1295                 diff = add + [x for x in loc if not x in value]
1296                 locations = [x for x in locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1297                 locations.sort(key = lambda x: x[0])
1298                 self.locations = locations
1299                 self.changed()
1300
1301         def getValue(self):
1302                 self.checkChangedMountpoints()
1303                 locations = self.locations
1304                 for x in locations:
1305                         x[3] = x[2]
1306                 return [x[0] for x in locations if x[3]]
1307
1308         value = property(getValue, setValue)
1309
1310         def tostring(self, value):
1311                 return str(value)
1312
1313         def fromstring(self, val):
1314                 return eval(val)
1315
1316         def load(self):
1317                 sv = self.saved_value
1318                 if sv is None:
1319                         tmp = self.default
1320                 else:
1321                         tmp = self.fromstring(sv)
1322                 locations = [[x, None, False, False] for x in tmp]
1323                 self.refreshMountpoints()
1324                 for x in locations:
1325                         if fileExists(x[0]):
1326                                 x[1] = self.getMountpoint(x[0])
1327                                 x[2] = True
1328                 self.locations = locations
1329
1330         def save(self):
1331                 locations = self.locations
1332                 if self.save_disabled or not locations:
1333                         self.saved_value = None
1334                 else:
1335                         self.saved_value = self.tostring([x[0] for x in locations])
1336
1337         def isChanged(self):
1338                 sv = self.saved_value
1339                 locations = self.locations
1340                 if val is None and not locations:
1341                         return False
1342                 return self.tostring([x[0] for x in locations]) != sv
1343
1344         def addedMount(self, mp):
1345                 for x in self.locations:
1346                         if x[1] == mp:
1347                                 x[2] = True
1348                         elif x[1] == None and fileExists(x[0]):
1349                                 x[1] = self.getMountpoint(x[0])
1350                                 x[2] = True
1351
1352         def removedMount(self, mp):
1353                 for x in self.locations:
1354                         if x[1] == mp:
1355                                 x[2] = False
1356
1357         def refreshMountpoints(self):
1358                 self.mountpoints = [p.mountpoint for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1359                 self.mountpoints.sort(key = lambda x: -len(x))
1360
1361         def checkChangedMountpoints(self):
1362                 oldmounts = self.mountpoints
1363                 self.refreshMountpoints()
1364                 newmounts = self.mountpoints
1365                 if oldmounts == newmounts:
1366                         return
1367                 for x in oldmounts:
1368                         if not x in newmounts:
1369                                 self.removedMount(x)
1370                 for x in newmounts:
1371                         if not x in oldmounts:
1372                                 self.addedMount(x)
1373
1374         def getMountpoint(self, file):
1375                 file = os_path.realpath(file)+"/"
1376                 for m in self.mountpoints:
1377                         if file.startswith(m):
1378                                 return m
1379                 return None
1380
1381         def handleKey(self, key):
1382                 if key == KEY_LEFT:
1383                         self.pos -= 1
1384                         if self.pos < -1:
1385                                 self.pos = len(self.value)-1
1386                 elif key == KEY_RIGHT:
1387                         self.pos += 1
1388                         if self.pos >= len(self.value):
1389                                 self.pos = -1
1390                 elif key in (KEY_HOME, KEY_END):
1391                         self.pos = -1
1392
1393         def getText(self):
1394                 return " ".join(self.value)
1395
1396         def getMulti(self, selected):
1397                 if not selected:
1398                         valstr = " ".join(self.value)
1399                         if self.visible_width and len(valstr) > self.visible_width:
1400                                 return ("text", valstr[0:self.visible_width])
1401                         else:
1402                                 return ("text", valstr)
1403                 else:
1404                         i = 0
1405                         valstr = ""
1406                         ind1 = 0
1407                         ind2 = 0
1408                         for val in self.value:
1409                                 if i == self.pos:
1410                                         ind1 = len(valstr)
1411                                 valstr += str(val)+" "
1412                                 if i == self.pos:
1413                                         ind2 = len(valstr)
1414                                 i += 1
1415                         if self.visible_width and len(valstr) > self.visible_width:
1416                                 if ind1+1 < self.visible_width/2:
1417                                         off = 0
1418                                 else:
1419                                         off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1420                                 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1421                         else:
1422                                 return ("mtext", valstr, range(ind1,ind2))
1423
1424         def onDeselect(self, session):
1425                 self.pos = -1
1426
1427 # nothing.
1428 class ConfigNothing(ConfigSelection):
1429         def __init__(self):
1430                 ConfigSelection.__init__(self, choices = [("","")])
1431
1432 # until here, 'saved_value' always had to be a *string*.
1433 # now, in ConfigSubsection, and only there, saved_value
1434 # is a dict, essentially forming a tree.
1435 #
1436 # config.foo.bar=True
1437 # config.foobar=False
1438 #
1439 # turns into:
1440 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1441 #
1442
1443 class ConfigSubsectionContent(object):
1444         pass
1445
1446 # we store a backup of the loaded configuration
1447 # data in self.stored_values, to be able to deploy
1448 # them when a new config element will be added,
1449 # so non-default values are instantly available
1450
1451 # A list, for example:
1452 # config.dipswitches = ConfigSubList()
1453 # config.dipswitches.append(ConfigYesNo())
1454 # config.dipswitches.append(ConfigYesNo())
1455 # config.dipswitches.append(ConfigYesNo())
1456 class ConfigSubList(list, object):
1457         def __init__(self):
1458                 list.__init__(self)
1459                 self.stored_values = {}
1460
1461         def save(self):
1462                 for x in self:
1463                         x.save()
1464
1465         def load(self):
1466                 for x in self:
1467                         x.load()
1468
1469         def getSavedValue(self):
1470                 res = { }
1471                 for i, val in enumerate(self):
1472                         sv = val.saved_value
1473                         if sv is not None:
1474                                 res[str(i)] = sv
1475                 return res
1476
1477         def setSavedValue(self, values):
1478                 self.stored_values = dict(values)
1479                 for (key, val) in self.stored_values.items():
1480                         if int(key) < len(self):
1481                                 self[int(key)].saved_value = val
1482
1483         saved_value = property(getSavedValue, setSavedValue)
1484
1485         def append(self, item):
1486                 i = str(len(self))
1487                 list.append(self, item)
1488                 if i in self.stored_values:
1489                         item.saved_value = self.stored_values[i]
1490                         item.load()
1491
1492         def dict(self):
1493                 return dict([(str(index), value) for index, value in enumerate(self)])
1494
1495 # same as ConfigSubList, just as a dictionary.
1496 # care must be taken that the 'key' has a proper
1497 # str() method, because it will be used in the config
1498 # file.
1499 class ConfigSubDict(dict, object):
1500         def __init__(self):
1501                 dict.__init__(self)
1502                 self.stored_values = {}
1503
1504         def save(self):
1505                 for x in self.values():
1506                         x.save()
1507
1508         def load(self):
1509                 for x in self.values():
1510                         x.load()
1511
1512         def getSavedValue(self):
1513                 res = {}
1514                 for (key, val) in self.items():
1515                         sv = val.saved_value
1516                         if sv is not None:
1517                                 res[str(key)] = sv
1518                 return res
1519
1520         def setSavedValue(self, values):
1521                 self.stored_values = dict(values)
1522                 for (key, val) in self.items():
1523                         if str(key) in self.stored_values:
1524                                 val.saved_value = self.stored_values[str(key)]
1525
1526         saved_value = property(getSavedValue, setSavedValue)
1527
1528         def __setitem__(self, key, item):
1529                 dict.__setitem__(self, key, item)
1530                 if str(key) in self.stored_values:
1531                         item.saved_value = self.stored_values[str(key)]
1532                         item.load()
1533
1534         def dict(self):
1535                 return self
1536
1537 # Like the classes above, just with a more "native"
1538 # syntax.
1539 #
1540 # some evil stuff must be done to allow instant
1541 # loading of added elements. this is why this class
1542 # is so complex.
1543 #
1544 # we need the 'content' because we overwrite
1545 # __setattr__.
1546 # If you don't understand this, try adding
1547 # __setattr__ to a usual exisiting class and you will.
1548 class ConfigSubsection(object):
1549         def __init__(self):
1550                 self.__dict__["content"] = ConfigSubsectionContent()
1551                 self.content.items = { }
1552                 self.content.stored_values = { }
1553
1554         def __setattr__(self, name, value):
1555                 if name == "saved_value":
1556                         return self.setSavedValue(value)
1557                 assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1558                 content = self.content
1559                 content.items[name] = value
1560                 x = content.stored_values.get(name, None)
1561                 if x is not None:
1562                         #print "ok, now we have a new item,", name, "and have the following value for it:", x
1563                         value.saved_value = x
1564                         value.load()
1565
1566         def __getattr__(self, name):
1567                 return self.content.items[name]
1568
1569         def getSavedValue(self):
1570                 res = self.content.stored_values
1571                 for (key, val) in self.content.items.items():
1572                         sv = val.saved_value
1573                         if sv is not None:
1574                                 res[key] = sv
1575                         elif key in res:
1576                                 del res[key]
1577                 return res
1578
1579         def setSavedValue(self, values):
1580                 values = dict(values)
1581                 self.content.stored_values = values
1582                 for (key, val) in self.content.items.items():
1583                         value = values.get(key, None)
1584                         if value is not None:
1585                                 val.saved_value = value
1586
1587         saved_value = property(getSavedValue, setSavedValue)
1588
1589         def save(self):
1590                 for x in self.content.items.values():
1591                         x.save()
1592
1593         def load(self):
1594                 for x in self.content.items.values():
1595                         x.load()
1596
1597         def dict(self):
1598                 return self.content.items
1599
1600 # the root config object, which also can "pickle" (=serialize)
1601 # down the whole config tree.
1602 #
1603 # we try to keep non-existing config entries, to apply them whenever
1604 # a new config entry is added to a subsection
1605 # also, non-existing config entries will be saved, so they won't be
1606 # lost when a config entry disappears.
1607 class Config(ConfigSubsection):
1608         def __init__(self):
1609                 ConfigSubsection.__init__(self)
1610
1611         def pickle_this(self, prefix, topickle, result):
1612                 for (key, val) in topickle.items():
1613                         name = '.'.join((prefix, key))
1614                         if isinstance(val, dict):
1615                                 self.pickle_this(name, val, result)
1616                         elif isinstance(val, tuple):
1617                                 result += [name, '=', val[0], '\n']
1618                         else:
1619                                 result += [name, '=', val, '\n']
1620
1621         def pickle(self):
1622                 result = []
1623                 self.pickle_this("config", self.saved_value, result)
1624                 return ''.join(result)
1625
1626         def unpickle(self, lines):
1627                 tree = { }
1628                 for l in lines:
1629                         if not l or l[0] == '#':
1630                                 continue
1631
1632                         n = l.find('=')
1633                         val = l[n+1:].strip()
1634
1635                         names = l[:n].split('.')
1636 #                       if val.find(' ') != -1:
1637 #                               val = val[:val.find(' ')]
1638
1639                         base = tree
1640
1641                         for n in names[:-1]:
1642                                 base = base.setdefault(n, {})
1643
1644                         base[names[-1]] = val
1645
1646                 # we inherit from ConfigSubsection, so ...
1647                 #object.__setattr__(self, "saved_value", tree["config"])
1648                 if "config" in tree:
1649                         self.setSavedValue(tree["config"])
1650
1651         def saveToFile(self, filename):
1652                 text = self.pickle()
1653                 f = open(filename, "w")
1654                 f.write(text)
1655                 f.close()
1656
1657         def loadFromFile(self, filename):
1658                 f = open(filename, "r")
1659                 self.unpickle(f.readlines())
1660                 f.close()
1661
1662 config = Config()
1663 config.misc = ConfigSubsection()
1664
1665 class ConfigFile:
1666         CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1667
1668         def load(self):
1669                 try:
1670                         config.loadFromFile(self.CONFIG_FILE)
1671                 except IOError, e:
1672                         print "unable to load config (%s), assuming defaults..." % str(e)
1673
1674         def save(self):
1675 #               config.save()
1676                 config.saveToFile(self.CONFIG_FILE)
1677
1678         def __resolveValue(self, pickles, cmap):
1679                 key = pickles[0]
1680                 if cmap.has_key(key):
1681                         if len(pickles) > 1:
1682                                 return self.__resolveValue(pickles[1:], cmap[key].dict())
1683                         else:
1684                                 return str(cmap[key].value)
1685                 return None
1686
1687         def getResolvedKey(self, key):
1688                 names = key.split('.')
1689                 if len(names) > 1:
1690                         if names[0] == "config":
1691                                 ret=self.__resolveValue(names[1:], config.content.items)
1692                                 if ret and len(ret):
1693                                         return ret
1694                 print "getResolvedKey", key, "failed !! (Typo??)"
1695                 return ""
1696
1697 def NoSave(element):
1698         element.disableSave()
1699         return element
1700
1701 configfile = ConfigFile()
1702
1703 configfile.load()
1704
1705 def getConfigListEntry(*args):
1706         assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
1707         return args
1708
1709 def updateConfigElement(element, newelement):
1710         newelement.value = element.value
1711         return newelement
1712
1713 #def _(x):
1714 #       return x
1715 #
1716 #config.bla = ConfigSubsection()
1717 #config.bla.test = ConfigYesNo()
1718 #config.nim = ConfigSubList()
1719 #config.nim.append(ConfigSubsection())
1720 #config.nim[0].bla = ConfigYesNo()
1721 #config.nim.append(ConfigSubsection())
1722 #config.nim[1].bla = ConfigYesNo()
1723 #config.nim[1].blub = ConfigYesNo()
1724 #config.arg = ConfigSubDict()
1725 #config.arg["Hello"] = ConfigYesNo()
1726 #
1727 #config.arg["Hello"].handleKey(KEY_RIGHT)
1728 #config.arg["Hello"].handleKey(KEY_RIGHT)
1729 #
1730 ##config.saved_value
1731 #
1732 ##configfile.save()
1733 #config.save()
1734 #print config.pickle()