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