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