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