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