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