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