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