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