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