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