enigma2: 4.3.1r16
[enigma2.git] / usr / lib / enigma2 / python / Components / config.py
1 from enigma import eRCInput, getPrevAsciiCode
2 from Tools.NumericalTextInput import NumericalTextInput, NumericalHexInput
3 from Tools.Directories import resolveFilename, SCOPE_CONFIG, fileExists
4 from Tools.IO import saveFile
5 from copy import copy as copy_copy
6 from os import path as os_path
7 from time import localtime, strftime
8 from netaddr import IPAddress
9 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
1044         def onDeselect(self, session):
1045                 self.selected = False
1046                 eRCInput.getInstance().setKeyboardMode(self._keyboardMode)
1047                 self.marked_pos = 0
1048                 self.offset = 0
1049                 if self.help_window:
1050                         session.deleteDialog(self.help_window)
1051                         self.help_window = None
1052                 ConfigElement.onDeselect(self, session)
1053
1054         def getHTML(self, id):
1055                 return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n'
1056
1057         def unsafeAssign(self, value):
1058                 self.value = str(value)
1059
1060 class ConfigText(ConfigTextBase, NumericalTextInput):
1061         def __init__(self, default = "", fixed_size = True, visible_width = False, censor_char = ''):
1062                 ConfigTextBase.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width, censor_char = censor_char)
1063                 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
1064
1065 #IPv6 Address with validation and autoformatting
1066 class ConfigIP6(ConfigTextBase, NumericalHexInput):
1067         def __init__(self, default = "::", fixed_size=False, visible_width=False):
1068                 ConfigTextBase.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1069                 NumericalHexInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False)
1070
1071         def isValid(self):
1072                 try:
1073                         ip = IPAddress(self.text)
1074                         return ip.version == 6
1075                 except ValueError:
1076                         Log.w("%s is no valid v6 IP" %self.text)
1077                         return False
1078
1079         def getValue(self):
1080                 if not self.isValid():
1081                         self._setDefault(force=True)
1082                 return self.getText()
1083
1084         def setValue(self, val):
1085                 try:
1086                         val = val.decode("utf-8")
1087                         self.text = IPAddress(val).format()
1088                 except:
1089                         Log.w("No valid IPv6 Address")
1090                         self._setDefault(force=True)
1091                 self.changed()
1092
1093         def _setDefault(self, force=False):
1094                 if not self.text or force:
1095                         self.text = self.default
1096
1097         def getText(self):
1098                 return self.text
1099
1100         def onDeselect(self, session):
1101                 self.setValue(self.text)
1102                 ConfigTextBase.onDeselect(self, session)
1103
1104 class ConfigPassword(ConfigText):
1105         def __init__(self, default = "", fixed_size = False, visible_width = False, censor = "*"):
1106                 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width, censor_char = censor)
1107
1108 # lets the user select between [min, min+stepwidth, min+(stepwidth*2)..., maxval] with maxval <= max depending
1109 # on the stepwidth
1110 # min, max, stepwidth, default are int values
1111 # wraparound: pressing RIGHT key at max value brings you to min value and vice versa if set to True
1112 class ConfigSelectionNumber(ConfigSelection):
1113         def __init__(self, min, max, stepwidth, default = None, wraparound = False):
1114                 self.wraparound = wraparound
1115                 if default is None:
1116                         default = min
1117                 default = str(default)
1118                 choices = []
1119                 step = min
1120                 while step <= max:
1121                         choices.append(str(step))
1122                         step += stepwidth
1123                 
1124                 ConfigSelection.__init__(self, choices, default)
1125
1126         def getValue(self):
1127                 return int(ConfigSelection.getValue(self))
1128
1129         def setValue(self, val):
1130                 ConfigSelection.setValue(self, str(val))
1131
1132         def handleKey(self, key):
1133                 if not self.wraparound:
1134                         if key == KEY_RIGHT:
1135                                 if len(self.choices) == (self.choices.index(self.value) + 1):
1136                                         return
1137                         if key == KEY_LEFT:
1138                                 if self.choices.index(self.value) == 0:
1139                                         return
1140                 ConfigSelection.handleKey(self, key)
1141
1142 class ConfigNumber(ConfigText):
1143         def __init__(self, default = 0):
1144                 ConfigText.__init__(self, str(default), fixed_size = False)
1145
1146         def getValue(self):
1147                 return int(self.text)
1148
1149         def setValue(self, val):
1150                 self.text = str(val)
1151                 self.changed()
1152
1153         value = property(getValue, setValue)
1154         _value = property(getValue, setValue)
1155
1156         def isChanged(self):
1157                 sv = self.saved_value
1158                 strv = self.tostring(self.value)
1159                 if sv is None and strv == self.default:
1160                         return False
1161                 return strv != sv
1162
1163         def conform(self):
1164                 pos = len(self.text) - self.marked_pos
1165                 self.text = self.text.lstrip("0")
1166                 if self.text == "":
1167                         self.text = "0"
1168                 if pos > len(self.text):
1169                         self.marked_pos = 0
1170                 else:
1171                         self.marked_pos = len(self.text) - pos
1172
1173         def handleKey(self, key):
1174                 if key in KEY_NUMBERS or key == KEY_ASCII:
1175                         if key == KEY_ASCII:
1176                                 ascii = getPrevAsciiCode()
1177                                 if not (48 <= ascii <= 57):
1178                                         return
1179                         else:
1180                                 ascii = getKeyNumber(key) + 48
1181                         newChar = unichr(ascii)
1182                         if self.allmarked:
1183                                 self.deleteAllChars()
1184                                 self.allmarked = False
1185                         self.insertChar(newChar, self.marked_pos, False)
1186                         self.marked_pos += 1
1187                 else:
1188                         ConfigText.handleKey(self, key)
1189                 self.conform()
1190
1191         def onSelect(self, session):
1192                 self.allmarked = (self.value != "")
1193                 self._keyboardMode = eRCInput.getInstance().getKeyboardMode()
1194
1195 class ConfigSearchText(ConfigText):
1196         def __init__(self, default = "", fixed_size = False, visible_width = False, special_chars = ""):
1197                 ConfigText.__init__(self, default = default, fixed_size = fixed_size, visible_width = visible_width)
1198                 NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False, search = special_chars)
1199
1200 class ConfigDirectory(ConfigText):
1201         def __init__(self, default="", visible_width=60):
1202                 ConfigText.__init__(self, default, fixed_size = True, visible_width = visible_width)
1203
1204         def handleKey(self, key):
1205                 pass
1206
1207         def getValue(self):
1208                 if self.text == "":
1209                         return None
1210                 else:
1211                         return ConfigText.getValue(self)
1212
1213         def setValue(self, val):
1214                 if val == None:
1215                         val = ""
1216                 ConfigText.setValue(self, val)
1217
1218         def getMulti(self, selected):
1219                 if self.text == "":
1220                         return ("mtext"[1-selected:], _("List of Storage Devices"), range(0))
1221                 else:
1222                         return ConfigText.getMulti(self, selected)
1223
1224         def onSelect(self, session):
1225                 self.allmarked = (self.value != "")
1226                 self._keyboardMode = eRCInput.getInstance().getKeyboardMode()
1227
1228 # a slider.
1229 class ConfigSlider(ConfigElement):
1230         def __init__(self, default = 0, increment = 1, limits = (0, 100)):
1231                 ConfigElement.__init__(self)
1232                 self.value = self.default = default
1233                 self.min = limits[0]
1234                 self.max = limits[1]
1235                 self.increment = increment
1236
1237         def checkValues(self):
1238                 if self.value < self.min:
1239                         self.value = self.min
1240
1241                 if self.value > self.max:
1242                         self.value = self.max
1243
1244         def handleKey(self, key):
1245                 if key == KEY_LEFT:
1246                         self.value -= self.increment
1247                 elif key == KEY_RIGHT:
1248                         self.value += self.increment
1249                 elif key == KEY_HOME:
1250                         self.value = self.min
1251                 elif key == KEY_END:
1252                         self.value = self.max
1253                 else:
1254                         return
1255                 self.checkValues()
1256
1257         def getText(self):
1258                 return "%d / %d" % (self.value, self.max)
1259
1260         def getMulti(self, selected):
1261                 self.checkValues()
1262                 return ("slider", self.value, self.max)
1263
1264         def fromstring(self, value):
1265                 return int(value)
1266
1267 # a satlist. in fact, it's a ConfigSelection.
1268 class ConfigSatlist(ConfigSelection):
1269         def __init__(self, list, default = None):
1270                 if default is not None:
1271                         default = str(default)
1272                 ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc, flags) in list], default = default)
1273
1274         def getOrbitalPosition(self):
1275                 if self.value == "":
1276                         return None
1277                 return int(self.value)
1278
1279         orbital_position = property(getOrbitalPosition)
1280
1281 class ConfigSet(ConfigElement):
1282         def __init__(self, choices, default = [], resort=True):
1283                 ConfigElement.__init__(self)
1284                 self.resort = resort
1285                 if isinstance(choices, list):
1286                         if resort:
1287                                 choices.sort()
1288                         self.choices = choicesList(choices, choicesList.LIST_TYPE_LIST)
1289                 else:
1290                         assert False, "ConfigSet choices must be a list!"
1291                 if default is None:
1292                         default = []
1293                 self.pos = -1
1294                 if resort:
1295                         default.sort()
1296                 self.default = default
1297                 self.help_window = None
1298                 self.value = default[:]
1299
1300         def toggleChoice(self, choice):
1301                 value = self.value
1302                 if choice in value:
1303                         value.remove(choice)
1304                 else:
1305                         value.append(choice)
1306                         if self.resort:
1307                                 value.sort()
1308                 self.changed()
1309
1310         def handleKey(self, key):
1311                 if key in KEY_NUMBERS + [KEY_DELETE, KEY_BACKSPACE]:
1312                         if self.pos != -1:
1313                                 self.toggleChoice(self.choices[self.pos])
1314                 elif key == KEY_LEFT:
1315                         if self.pos < 0:
1316                                 self.pos = len(self.choices)-1
1317                         else:
1318                                 self.pos -= 1
1319                 elif key == KEY_RIGHT:
1320                         if self.pos >= len(self.choices)-1:
1321                                 self.pos = -1
1322                         else:
1323                                 self.pos += 1
1324                 elif key in (KEY_HOME, KEY_END):
1325                         self.pos = -1
1326
1327         def genString(self, lst):
1328                 res = ""
1329                 for x in lst:
1330                         res += self.description[x]+" "
1331                 return res
1332
1333         def getText(self):
1334                 return self.genString(self.value)
1335
1336         def getMulti(self, selected):
1337                 if not selected or self.pos == -1:
1338                         return ("text", self.genString(self.value))
1339                 else:
1340                         tmp = self.value[:]
1341                         ch = self.choices[self.pos]
1342                         mem = ch in self.value
1343                         if not mem:
1344                                 tmp.append(ch)
1345                                 if self.resort:
1346                                         tmp.sort()
1347                         ind = tmp.index(ch)
1348                         val1 = self.genString(tmp[:ind])
1349                         val2 = " "+self.genString(tmp[ind+1:])
1350                         if mem:
1351                                 chstr = " "+self.description[ch]+" "
1352                         else:
1353                                 chstr = "("+self.description[ch]+")"
1354                         len_val1 = len(val1)
1355                         return ("mtext", val1+chstr+val2, range(len_val1, len_val1 + len(chstr)))
1356
1357
1358         def onSelect(self, session):
1359                 if session is not None:
1360                         from Screens.ConfigSetHelpDialog import ConfigSetHelpDialog
1361                         self.help_window = session.instantiateDialog(ConfigSetHelpDialog, self, zPosition=5000)
1362                         self.help_window.neverAnimate()
1363                         self.help_window.show()
1364
1365         def onDeselect(self, session):
1366                 self.pos = -1
1367                 if self.help_window:
1368                         session.deleteDialog(self.help_window)
1369                         self.help_window = None
1370                 ConfigElement.onDeselect(self, session)
1371
1372         def tostring(self, value):
1373                 return str(value)
1374
1375         def fromstring(self, val):
1376                 try:
1377                         return literal_eval(val)
1378                 except:
1379                         return self.default
1380
1381         description = property(lambda self: descriptionList(self.choices.choices, choicesList.LIST_TYPE_LIST))
1382
1383 class ConfigLocations(ConfigElement):
1384         def __init__(self, default = [], visible_width = False):
1385                 ConfigElement.__init__(self)
1386                 self.visible_width = visible_width
1387                 self.pos = -1
1388                 self.default = default
1389                 self.locations = []
1390                 self.mountpoints = []
1391                 self.value = default[:]
1392
1393         def setValue(self, value):
1394                 locations = self.locations
1395                 loc = [x[0] for x in locations if x[3]]
1396                 add = [x for x in value if not x in loc]
1397                 diff = add + [x for x in loc if not x in value]
1398                 locations = [x for x in locations if not x[0] in diff] + [[x, self.getMountpoint(x), True, True] for x in add]
1399                 locations.sort(key = lambda x: x[0])
1400                 self.locations = locations
1401                 self.changed()
1402
1403         def getValue(self):
1404                 self.checkChangedMountpoints()
1405                 locations = self.locations
1406                 for x in locations:
1407                         x[3] = x[2]
1408                 return [x[0] for x in locations if x[3]]
1409
1410         value = property(getValue, setValue)
1411
1412         def tostring(self, value):
1413                 return str(value)
1414
1415         def fromstring(self, val):
1416                 return literal_eval(val)
1417
1418         def load(self):
1419                 sv = self.saved_value
1420                 if sv is None:
1421                         tmp = self.default
1422                 else:
1423                         tmp = self.fromstring(sv)
1424                 locations = [[x, None, False, False] for x in tmp]
1425                 self.refreshMountpoints()
1426                 for x in locations:
1427                         if fileExists(x[0]):
1428                                 x[1] = self.getMountpoint(x[0])
1429                                 x[2] = True
1430                 self.locations = locations
1431
1432         def save(self):
1433                 locations = self.locations
1434                 if self.save_disabled or not locations:
1435                         self.saved_value = None
1436                 else:
1437                         self.saved_value = self.tostring([x[0] for x in locations])
1438
1439         def isChanged(self):
1440                 sv = self.saved_value
1441                 locations = self.locations
1442                 if sv is None and not locations:
1443                         return False
1444                 return self.tostring([x[0] for x in locations]) != sv
1445
1446         def addedMount(self, mp):
1447                 for x in self.locations:
1448                         if x[1] == mp:
1449                                 x[2] = True
1450                         elif x[1] == None and fileExists(x[0]):
1451                                 x[1] = self.getMountpoint(x[0])
1452                                 x[2] = True
1453
1454         def removedMount(self, mp):
1455                 for x in self.locations:
1456                         if x[1] == mp:
1457                                 x[2] = False
1458
1459         def refreshMountpoints(self):
1460                 from Components.Harddisk import harddiskmanager
1461                 self.mountpoints = [p.mountpoint for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
1462                 self.mountpoints.sort(key = lambda x: -len(x))
1463
1464         def checkChangedMountpoints(self):
1465                 oldmounts = self.mountpoints
1466                 self.refreshMountpoints()
1467                 newmounts = self.mountpoints
1468                 if oldmounts == newmounts:
1469                         return
1470                 for x in oldmounts:
1471                         if not x in newmounts:
1472                                 self.removedMount(x)
1473                 for x in newmounts:
1474                         if not x in oldmounts:
1475                                 self.addedMount(x)
1476
1477         def getMountpoint(self, file):
1478                 file = os_path.realpath(file)+"/"
1479                 for m in self.mountpoints:
1480                         if file.startswith(m):
1481                                 return m
1482                 return None
1483
1484         def handleKey(self, key):
1485                 if key == KEY_LEFT:
1486                         self.pos -= 1
1487                         if self.pos < -1:
1488                                 self.pos = len(self.value)-1
1489                 elif key == KEY_RIGHT:
1490                         self.pos += 1
1491                         if self.pos >= len(self.value):
1492                                 self.pos = -1
1493                 elif key in (KEY_HOME, KEY_END):
1494                         self.pos = -1
1495
1496         def getText(self):
1497                 return " ".join(self.value)
1498
1499         def getMulti(self, selected):
1500                 if not selected:
1501                         valstr = " ".join(self.value)
1502                         if self.visible_width and len(valstr) > self.visible_width:
1503                                 return ("text", valstr[0:self.visible_width])
1504                         else:
1505                                 return ("text", valstr)
1506                 else:
1507                         i = 0
1508                         valstr = ""
1509                         ind1 = 0
1510                         ind2 = 0
1511                         for val in self.value:
1512                                 if i == self.pos:
1513                                         ind1 = len(valstr)
1514                                 valstr += str(val)+" "
1515                                 if i == self.pos:
1516                                         ind2 = len(valstr)
1517                                 i += 1
1518                         if self.visible_width and len(valstr) > self.visible_width:
1519                                 if ind1+1 < self.visible_width/2:
1520                                         off = 0
1521                                 else:
1522                                         off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
1523                                 return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
1524                         else:
1525                                 return ("mtext", valstr, range(ind1,ind2))
1526
1527         def onDeselect(self, session):
1528                 self.pos = -1
1529                 ConfigElement.onDeselect(self, session)
1530
1531 # nothing.
1532 class ConfigNothing(ConfigSelection):
1533         def __init__(self):
1534                 ConfigSelection.__init__(self, choices = [("","")])
1535
1536 # until here, 'saved_value' always had to be a *string*.
1537 # now, in ConfigSubsection, and only there, saved_value
1538 # is a dict, essentially forming a tree.
1539 #
1540 # config.foo.bar=True
1541 # config.foobar=False
1542 #
1543 # turns into:
1544 # config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
1545 #
1546
1547 class ConfigSubsectionContent(object):
1548         pass
1549
1550 # we store a backup of the loaded configuration
1551 # data in self.stored_values, to be able to deploy
1552 # them when a new config element will be added,
1553 # so non-default values are instantly available
1554
1555 # A list, for example:
1556 # config.dipswitches = ConfigSubList()
1557 # config.dipswitches.append(ConfigYesNo())
1558 # config.dipswitches.append(ConfigYesNo())
1559 # config.dipswitches.append(ConfigYesNo())
1560 class ConfigSubList(list, object):
1561         def __init__(self):
1562                 list.__init__(self)
1563                 self.stored_values = {}
1564
1565         def save(self):
1566                 for x in self:
1567                         x.save()
1568
1569         def load(self):
1570                 for x in self:
1571                         x.load()
1572
1573         def getSavedValue(self):
1574                 res = { }
1575                 for i, val in enumerate(self):
1576                         sv = val.saved_value
1577                         if sv is not None:
1578                                 res[str(i)] = sv
1579                 return res
1580
1581         def setSavedValue(self, values):
1582                 self.stored_values = dict(values)
1583                 for (key, val) in self.stored_values.items():
1584                         if int(key) < len(self):
1585                                 self[int(key)].saved_value = val
1586
1587         saved_value = property(getSavedValue, setSavedValue)
1588
1589         def append(self, item):
1590                 i = str(len(self))
1591                 list.append(self, item)
1592                 if i in self.stored_values:
1593                         item.saved_value = self.stored_values[i]
1594                         item.load()
1595
1596         def dict(self):
1597                 return dict([(str(index), value) for index, value in enumerate(self)])
1598
1599 # same as ConfigSubList, just as a dictionary.
1600 # care must be taken that the 'key' has a proper
1601 # str() method, because it will be used in the config
1602 # file.
1603 class ConfigSubDict(dict, object):
1604         def __init__(self):
1605                 dict.__init__(self)
1606                 self.stored_values = {}
1607
1608         def save(self):
1609                 for x in self.values():
1610                         x.save()
1611
1612         def load(self):
1613                 for x in self.values():
1614                         x.load()
1615
1616         def getSavedValue(self):
1617                 res = {}
1618                 for (key, val) in self.items():
1619                         sv = val.saved_value
1620                         if sv is not None:
1621                                 res[str(key)] = sv
1622                 return res
1623
1624         def setSavedValue(self, values):
1625                 self.stored_values = dict(values)
1626                 for (key, val) in self.items():
1627                         if str(key) in self.stored_values:
1628                                 val.saved_value = self.stored_values[str(key)]
1629
1630         saved_value = property(getSavedValue, setSavedValue)
1631
1632         def __setitem__(self, key, item):
1633                 dict.__setitem__(self, key, item)
1634                 if str(key) in self.stored_values:
1635                         item.saved_value = self.stored_values[str(key)]
1636                         item.load()
1637
1638         def dict(self):
1639                 return self
1640
1641 # Like the classes above, just with a more "native"
1642 # syntax.
1643 #
1644 # some evil stuff must be done to allow instant
1645 # loading of added elements. this is why this class
1646 # is so complex.
1647 #
1648 # we need the 'content' because we overwrite
1649 # __setattr__.
1650 # If you don't understand this, try adding
1651 # __setattr__ to a usual exisiting class and you will.
1652 class ConfigSubsection(object):
1653         def __init__(self):
1654                 self.__dict__["content"] = ConfigSubsectionContent()
1655                 self.content.items = { }
1656                 self.content.stored_values = { }
1657
1658         def __setattr__(self, name, value):
1659                 if name == "saved_value":
1660                         return self.setSavedValue(value)
1661                 assert isinstance(value, (ConfigSubsection, ConfigElement, ConfigSubList, ConfigSubDict)), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
1662                 content = self.content
1663                 content.items[name] = value
1664                 x = content.stored_values.get(name, None)
1665                 if x is not None:
1666                         #print "ok, now we have a new item,", name, "and have the following value for it:", x
1667                         value.saved_value = x
1668                         value.load()
1669
1670         def __getattr__(self, name):
1671                 return self.content.items[name]
1672
1673         def getSavedValue(self):
1674                 res = self.content.stored_values
1675                 for (key, val) in self.content.items.items():
1676                         sv = val.saved_value
1677                         if sv is not None:
1678                                 res[key] = sv
1679                         elif key in res:
1680                                 del res[key]
1681                 return res
1682
1683         def setSavedValue(self, values, append = False):
1684                 values = dict(values)
1685                 if append:
1686                         try:
1687                                 self.content.stored_values.update(values)
1688                         except:
1689                                 self.content.stored_values = values
1690                 else:
1691                         self.content.stored_values = values
1692                 for (key, val) in self.content.items.items():
1693                         value = values.get(key, None)
1694                         if value is not None:
1695                                 if append and isinstance(val, ConfigSubsection):
1696                                         val.setSavedValue(value, append)
1697                                 else:
1698                                         val.saved_value = value
1699
1700         saved_value = property(getSavedValue, setSavedValue)
1701
1702         def save(self):
1703                 for x in self.content.items.values():
1704                         x.save()
1705
1706         def load(self):
1707                 for x in self.content.items.values():
1708                         x.load()
1709
1710         def dict(self):
1711                 return self.content.items
1712
1713 # the root config object, which also can "pickle" (=serialize)
1714 # down the whole config tree.
1715 #
1716 # we try to keep non-existing config entries, to apply them whenever
1717 # a new config entry is added to a subsection
1718 # also, non-existing config entries will be saved, so they won't be
1719 # lost when a config entry disappears.
1720 class Config(ConfigSubsection):
1721         def __init__(self):
1722                 ConfigSubsection.__init__(self)
1723
1724         def pickle_this(self, prefix, topickle, result):
1725                 for (key, val) in topickle.items():
1726                         name = '.'.join((prefix, key))
1727                         if isinstance(val, dict):
1728                                 self.pickle_this(name, val, result)
1729                         elif isinstance(val, tuple):
1730                                 result += [name, '=', val[0], '\n']
1731                         else:
1732                                 result += [name, '=', val, '\n']
1733
1734         def pickle(self):
1735                 result = []
1736                 self.pickle_this("config", self.saved_value, result)
1737                 return ''.join(result)
1738
1739         def unpickle(self, lines, base_file=True, append = False):
1740                 tree = { }
1741                 for l in lines:
1742                         if not l or l[0] == '#':
1743                                 continue
1744
1745                         n = l.find('=')
1746                         name = l[:n]
1747                         val = l[n+1:].strip()
1748
1749                         names = name.split('.')
1750 #                       if val.find(' ') != -1:
1751 #                               val = val[:val.find(' ')]
1752
1753                         base = tree
1754
1755                         for n in names[:-1]:
1756                                 base = base.setdefault(n, {})
1757
1758                         base[names[-1]] = val
1759
1760                         if not base_file: # not the initial config file..
1761                                 #update config.x.y.value when exist
1762                                 try:
1763                                         configEntry = eval(name)
1764                                         if configEntry is not None:
1765                                                 configEntry.value = val
1766                                 except (SyntaxError, KeyError):
1767                                         pass
1768
1769                 # we inherit from ConfigSubsection, so ...
1770                 #object.__setattr__(self, "saved_value", tree["config"])
1771                 if "config" in tree:
1772                         self.setSavedValue(tree["config"], append)
1773
1774         def saveToFile(self, filename):
1775                 saveFile(filename, self.pickle())
1776
1777         def loadFromFile(self, filename, base_file=False, append = False):
1778                 f = open(filename, "r")
1779                 lines_read = f.readlines()
1780                 lines = []
1781
1782                 # HACK to migrate changed unicable configuration
1783                 for l in lines_read:
1784                         changed = False
1785                         tmp = l.split('=')
1786                         x = tmp[0].split('.')
1787                         ent = len(x)
1788                         if ent > 6:
1789                                 if x[1] == 'Nims' and x[3] == 'advanced' and x[6].startswith('unicable'):
1790                                         if ent > 8 and x[8] in ('vco', 'scr', 'product'):
1791                                                 if x[8] != 'product':
1792                                                         del x[9]
1793                                                 del x[7]
1794                                                 changed = True
1795                                         elif x[6] == 'unicableLnbManufacturer':
1796                                                 x[6] = 'unicableLnb.manufacturer'
1797                                                 changed = True
1798                                         elif x[6] == 'unicableMatrixManufacturer':
1799                                                 x[6] = 'unicableMatrix.manufacturer'
1800                                                 changed = True
1801                                         if changed:
1802                                                 tmp[0] = '.'.join(x) 
1803                                                 l = '='.join(tmp)
1804                                                 print "UNICABLE MIGRATION", l,
1805                         lines.append(l)
1806
1807                 self.unpickle(lines, base_file, append)
1808                 f.close()
1809
1810 config = Config()
1811 config.misc = ConfigSubsection()
1812
1813 class ConfigFile:
1814         CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
1815
1816         def load(self):
1817                 try:
1818                         config.loadFromFile(self.CONFIG_FILE, True)
1819                 except IOError, e:
1820                         print "unable to load config (%s), assuming defaults..." % str(e)
1821
1822         def save(self):
1823                 config.saveToFile(self.CONFIG_FILE)
1824
1825         def __resolveValue(self, pickles, cmap):
1826                 key = pickles[0]
1827                 if cmap.has_key(key):
1828                         if len(pickles) > 1:
1829                                 return self.__resolveValue(pickles[1:], cmap[key].dict())
1830                         else:
1831                                 return str(cmap[key].value)
1832                 return None
1833
1834         def getResolvedKey(self, key):
1835                 names = key.split('.')
1836                 if len(names) > 1:
1837                         if names[0] == "config":
1838                                 ret=self.__resolveValue(names[1:], config.content.items)
1839                                 if ret and len(ret):
1840                                         return ret
1841                 return None
1842
1843 def NoSave(element):
1844         element.disableSave()
1845         return element
1846
1847 configfile = ConfigFile()
1848 configfile.load()
1849
1850 def getConfigListEntry(*args):
1851         assert len(args) > 0, "getConfigListEntry needs a minimum of one argument (descr)"
1852         return args
1853
1854 def updateConfigElement(element, newelement):
1855         newelement.value = element.value
1856         return newelement
1857
1858 #def _(x):
1859 #       return x
1860 #
1861 #config.bla = ConfigSubsection()
1862 #config.bla.test = ConfigYesNo()
1863 #config.nim = ConfigSubList()
1864 #config.nim.append(ConfigSubsection())
1865 #config.nim[0].bla = ConfigYesNo()
1866 #config.nim.append(ConfigSubsection())
1867 #config.nim[1].bla = ConfigYesNo()
1868 #config.nim[1].blub = ConfigYesNo()
1869 #config.arg = ConfigSubDict()
1870 #config.arg["Hello"] = ConfigYesNo()
1871 #
1872 #config.arg["Hello"].handleKey(KEY_RIGHT)
1873 #config.arg["Hello"].handleKey(KEY_RIGHT)
1874 #
1875 ##config.saved_value
1876 #
1877 ##configfile.save()
1878 #config.save()
1879 #print config.pickle()