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