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