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