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