sanity checks for the timer
[enigma2.git] / lib / python / Components / config.py
1 from time import *
2 from Tools.NumericalTextInput import *
3
4 class configFile:
5         def __init__(self):
6                 self.changed = 0
7                 self.configElements = { }
8                 try:
9                         self.file = open("config")
10                 except IOError:
11                         print "cannot open config file"
12                         return 
13                 
14                 while 1:
15                         line = self.file.readline()
16                         if line == "":
17                                 break
18                         
19                         if line.startswith("#"):                #skip comments
20                                 continue        
21                                 
22                         self.addElement(line)
23                 self.file.close()
24
25         def addElement(self, line):
26                 x = line.find("=")
27                 if x > -1:
28                         self.configElements[line[:x]] = line[x + 1:]
29         
30         def getKey(self, key):
31                 return self.configElements[key]
32
33         def setKey(self, key, value):
34                 self.changed = 1
35                 self.configElements[key] = value
36
37         def save(self):
38                 if self.changed == 0:           #no changes, so no write to disk needed
39                         return
40                         
41                 fileHandle = open("config", "w")
42                 
43                 keys = self.configElements.keys()
44                 keys.sort()
45                 for x in keys:
46                         wstr = x + "=" + self.configElements[x]
47                         
48                         if wstr[len(wstr) - 1] != '\n':
49                                 wstr = wstr + "\n"
50
51                         fileHandle.write(wstr)
52
53                 fileHandle.close()              
54
55 class configSelection:
56         def __init__(self, parent):
57                 self.parent = parent
58                 
59         def checkValues(self):
60                 if self.parent.value < 0:
61                         self.parent.value = 0   
62
63                 if(self.parent.value >= (len(self.parent.vals) - 1)):
64                         self.parent.value = len(self.parent.vals) - 1
65
66         def cancel(self):
67                 self.parent.reload()
68
69         def save(self):
70                 self.parent.save()
71
72         def handleKey(self, key):
73                 if key == config.key["prevElement"]:
74                         self.parent.value = self.parent.value - 1
75                 if key == config.key["nextElement"]:
76                         self.parent.value = self.parent.value + 1
77                 
78                 self.checkValues()                      
79
80                 self.parent.change()
81
82         def __call__(self, selected):                   #needed by configlist
83                 self.checkValues()
84                 return ("text", self.parent.vals[self.parent.value])
85
86 class configDateTime:
87         def __init__(self, parent):
88                 self.parent = parent
89                 
90         def checkValues(self):
91                 pass
92 #               if self.parent.value < 0:
93                         #self.parent.value = 0  
94
95                 #if(self.parent.value >= (len(self.parent.vals) - 1)):
96                         #self.parent.value = len(self.parent.vals) - 1
97
98         def cancel(self):
99                 self.parent.reload()
100
101         def save(self):
102                 self.parent.save()
103
104         def handleKey(self, key):
105                 if key == config.key["prevElement"]:
106                         self.parent.value = self.parent.value - self.parent.vals[1]
107                 if key == config.key["nextElement"]:
108                         self.parent.value = self.parent.value + self.parent.vals[1]
109                 
110                 self.checkValues()
111
112                 self.parent.change()    
113
114         def __call__(self, selected):                   #needed by configlist
115                 self.checkValues()
116                 return ("text", strftime(self.parent.vals[0], localtime(self.parent.value)))
117         
118 class configSatlist:
119         def __init__(self, parent):
120                 self.parent = parent
121
122         def checkValues(self):
123                 if self.parent.value < 0:
124                         self.parent.value = 0   
125
126                 if(self.parent.value >= (len(self.parent.vals) - 1)):
127                         self.parent.value = len(self.parent.vals) - 1
128                         
129         def cancel(self):
130                 self.parent.reload()
131
132         def save(self):
133                 self.parent.save()
134
135         def handleKey(self, key):
136                 if key == config.key["prevElement"]:
137                         self.parent.value = self.parent.value - 1
138                 if key == config.key["nextElement"]:
139                         self.parent.value = self.parent.value + 1
140                 
141                 self.checkValues()                      
142
143                 self.parent.change()    
144
145         def __call__(self, selected):                   #needed by configlist
146                 self.checkValues()
147                 #fixme
148                 return ("text", str(self.parent.vals[self.parent.value][0]))
149
150 class configSequenceArg:
151         def get(self, type, args = ()):
152                 # configsequencearg.get ("IP")
153                 if (type == "IP"):
154                         return (("."), [(1,255),(0,255),(0,255),(0,255)], "")
155                 # configsequencearg.get ("MAC")
156                 if (type == "MAC"):
157                         return ((":"), [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], "")
158                 # configsequencearg.get ("CLOCK")
159                 if (type == "CLOCK"):
160                         return ((":"), [(0,23),(0,59)], "")
161                 # configsequencearg.get("INTEGER", (min, max)) => x with min <= x <= max
162                 if (type == "INTEGER"):
163                         return ((":"), [args], "")
164                 # configsequencearg.get("PINCODE", (number, "*")) => pin with number = length of pincode and "*" as numbers shown as stars
165                 # configsequencearg.get("PINCODE", (number, "")) => pin with number = length of pincode and numbers shown
166                 if (type == "PINCODE"):
167                         return ((":"), [(0, (10**args[0])-1)], args[1])
168                 # configsequencearg.get("FLOAT", [(min,max),(min1,max1)]) => x.y with min <= x <= max and min1 <= y <= max1
169                 if (type == "FLOAT"):
170                         return (("."), args, "")
171
172 configsequencearg = configSequenceArg()
173                 
174 class configSequence:
175         def __init__(self, parent):
176                 self.parent = parent
177                 self.markedPos = 0
178                 self.seperator = self.parent.vals[0]
179                 self.valueBounds = self.parent.vals[1]
180                 self.censorChar = self.parent.vals[2]
181
182         def checkValues(self):
183                 maxPos = 0
184                 num = 0
185                 for i in self.parent.value:
186                         maxPos += len(str(self.valueBounds[num][1]))
187                         while (self.valueBounds[num][0] > self.parent.value[num]):
188                                 self.parent.value[num] += 1
189
190                         while (self.valueBounds[num][1] < self.parent.value[num]):
191                                 self.parent.value[num] -= 1
192                                 
193 #                       if (self.valueBounds[num][0] <= i <= self.valueBounds[num][1]):
194                                 #pass
195                         #else:
196                                 #self.parent.value[num] = self.valueBounds[num][0]
197                         num += 1
198                 
199                 if self.markedPos >= maxPos:
200                         self.markedPos = maxPos - 1
201                 if self.markedPos < 0:
202                         self.markedPos = 0
203                         
204         def cancel(self):
205                 self.parent.reload()
206
207         def save(self):
208                 self.parent.save()
209
210         def handleKey(self, key):
211                 #this will no change anything on the value itself
212                 #so we can handle it here in gui element
213                 if key == config.key["prevElement"]:
214                         self.markedPos -= 1
215                 if key == config.key["nextElement"]:
216                         self.markedPos += 1
217                 
218                 if key >= config.key["0"] and key <= config.key["9"]:
219                         number = 9 - config.key["9"] + key
220                         # length of numberblock
221                         numberLen = len(str(self.valueBounds[0][1]))
222                         # position in the block
223                         posinblock = self.markedPos % numberLen
224                         # blocknumber
225                         blocknumber = self.markedPos / numberLen
226                         
227                         oldvalue = self.parent.value[blocknumber]
228                         olddec = oldvalue % 10 ** (numberLen - posinblock) - (oldvalue % 10 ** (numberLen - posinblock - 1))
229                         newvalue = oldvalue - olddec + (10 ** (numberLen - posinblock - 1) * number)
230                         
231                         print "You actually pressed a number (" + str(number) + ") which will be added at block number " + str(blocknumber) + " on position " + str(posinblock)
232                         print "Old value: " + str(oldvalue) + " olddec: " + str(olddec) + " newvalue: " + str(newvalue)
233                         self.parent.value[blocknumber] = newvalue
234                         self.markedPos += 1
235                 
236                 self.checkValues()                      
237                 
238                 print "markPos:",
239                 print self.markedPos
240
241                 #FIXME: dont call when press left/right
242                 self.parent.change()    
243
244         def __call__(self, selected):                   #needed by configlist
245                 value = ""
246                 mPos = self.markedPos
247                 print "Positon: " + str(mPos)
248                 num = 0;
249                 for i in self.parent.value:
250                         if len(value):  #fixme no heading separator possible
251                                 value += self.seperator
252                                 if mPos >= len(value) - 1:
253                                         mPos += 1
254                                 
255                         #diff =         self.valueBounds - len(str(i))
256                         #if diff > 0:
257                                 ## if this helps?!
258                                 #value += " " * diff
259                         print (("%0" + str(len(str(self.valueBounds[num][1]))) + "d") % i)
260                         if (self.censorChar == ""):
261                                 value += ("%0" + str(len(str(self.valueBounds[num][1]))) + "d") % i
262                         else:
263                                 value += (self.censorChar * len(str(self.valueBounds[num][1])))
264                         num += 1
265                         # only mark cursor when we are selected
266                         # (this code is heavily ink optimized!)
267                 return ("mtext"[1-selected:], value, [mPos])
268
269 class configText:
270         # used as first parameter
271         # is the text of a fixed size or is the user able to extend the length of the text
272         extendableSize = 1
273         fixedSize = 2
274
275         def __init__(self, parent):
276                 self.parent = parent
277                 self.markedPos = 0
278                 self.mode = self.parent.vals[0]
279                 self.textInput = NumericalTextInput(self.nextEntry)
280
281         def checkValues(self):
282                 if (self.markedPos < 0):
283                         self.markedPos = 0
284                 if (self.markedPos >= len(self.parent.value)):
285                         self.markedPos = len(self.parent.value) - 1
286                         
287         def cancel(self):
288                 self.parent.reload()
289
290         def save(self):
291                 self.parent.save()
292                 
293         def nextEntry(self):
294                 print "Next entry"
295                 self.handleKey(config.key["nextElement"])
296
297         def handleKey(self, key):
298                 #this will no change anything on the value itself
299                 #so we can handle it here in gui element
300                 if key == config.key["prevElement"]:
301                         self.textInput.nextKey()
302                         self.markedPos -= 1
303
304                 if key == config.key["nextElement"]:
305                         self.textInput.nextKey()
306                         self.markedPos += 1
307                         if (self.mode == self.extendableSize):
308                                 if (self.markedPos >= len(self.parent.value)):
309                                         self.parent.value = self.parent.value.ljust(len(self.parent.value) + 1)
310                         
311                                 
312                 if key >= config.key["0"] and key <= config.key["9"]:
313                         number = 9 - config.key["9"] + key
314
315                         self.parent.value = self.parent.value[0:self.markedPos] + str(self.textInput.getKey(number)) + self.parent.value[self.markedPos + 1:]
316                 
317                 self.checkValues()                      
318                 
319                 self.parent.change()    
320
321         def __call__(self, selected):                   #needed by configlist
322                 return ("mtext"[1-selected:], str(self.parent.value), [self.markedPos])
323                 
324 class configValue:
325         def __init__(self, obj):
326                 self.obj = obj
327                 
328         def __str__(self):
329                 return self.obj
330
331 class Config:
332         def __init__(self):
333                 self.key = { "choseElement": 0,
334                                          "prevElement": 1,
335                                          "nextElement": 2,
336                                          "0": 10,
337                                          "1": 11,
338                                          "2": 12,
339                                          "3": 13,
340                                          "4": 14,
341                                          "5": 15,
342                                          "6": 16,
343                                          "7": 17,
344                                          "8": 18,
345                                          "9": 19 }
346                 
347 config = Config();
348 configfile = configFile()
349
350 class ConfigSlider:
351         def __init__(self, parent):
352                 self.parent = parent
353
354         def cancel(self):
355                 self.parent.reload()
356
357         def save(self):
358                 self.parent.save()
359
360         def checkValues(self):
361                 if self.parent.value < 0:
362                         self.parent.value = 0   
363
364                 if self.parent.value > 10:
365                         self.parent.value = 10  
366
367         def handleKey(self, key):
368                 if key == config.key["prevElement"]:
369                         self.parent.value = self.parent.value - 1
370                 if key == config.key["nextElement"]:
371                         self.parent.value = self.parent.value + 1
372                                         
373                 self.checkValues()      
374                 self.parent.change()    
375
376         def __call__(self, selected):                   #needed by configlist
377                 self.checkValues()
378                 return ("slider", self.parent.value * 10)
379
380 class ConfigSubsection:
381         def __init__(self):
382                 pass
383
384 class configElement:
385
386         def getIndexbyEntry(self, data):
387                 cnt = 0;
388                 tcnt = -1; #for defaultval
389                 for x in self.vals:
390                         if int(x[1]) == int(data):
391                                         return cnt
392                         if int(x[1]) == int(self.defaultValue):
393                                         tcnt = cnt
394                         cnt += 1
395                 if tcnt != -1:
396                         return tcnt
397                 return 0        #prevent bigger then array
398
399         def datafromFile(self, control, data):
400                 if control == ConfigSlider:
401                         return int(data)
402                 elif control == configSelection:
403                         return int(data)
404                 elif control == configDateTime:
405                         return int(data)
406                 elif control == configText:
407                         return str(data)
408                 elif control == configSequence:
409                         list = [ ]
410                         part = data.split(self.vals[0])
411                         for x in part:
412                                 list.append(int(x))
413                         return list
414                 elif control == configSatlist:
415                         return self.getIndexbyEntry(data)
416                 else: 
417                         return ""       
418
419         def datatoFile(self, control, data):
420                 if control == ConfigSlider:
421                         return str(data)
422                 elif control == configSelection:
423                         return str(data)
424                 elif control == configDateTime:
425                         return str(data)
426                 elif control == configText:
427                         return str(data.strip())
428
429                 elif control == configSequence:
430                         value = ((len(data) * ("%d" + self.vals[0]))[0:-1]) % tuple(data)
431 #                       just in case you don't understand the above, here an equivalent:
432 #                       value = ""
433 #                       for i in data:
434 #                               if value !="":
435 #                                       value += self.vals[0]
436 #                               value += str(i)
437                         return value
438                 elif control == configSatlist:
439                         return str(self.vals[self.value][1]);
440                 else: 
441                         return ""       
442
443         def loadData(self):
444                 try:
445                         value = self.datafromFile(self.controlType, configfile.getKey(self.configPath))
446                 except:         
447                         value = ""
448
449                 if value == "":
450                         #print "value not found - using default"
451
452                         if self.controlType == configSatlist:
453                                 self.value = self.getIndexbyEntry(self.defaultValue)
454                         else:   
455                                 self.value = self.defaultValue
456
457                         self.save()             #add missing value to dict
458                 else:
459                         self.value = value
460                         
461                 #is this right? activate settings after load/cancel and use default     
462                 self.change()
463
464         def __init__(self, configPath, control, defaultValue, vals):
465                 self.configPath = configPath
466                 self.defaultValue = defaultValue
467                 self.controlType = control
468                 self.vals = vals
469                 self.notifierList = [ ]
470                 self.enabled = True
471                 self.loadData()         
472                 
473         def getConfigPath(self):
474                 return self.configPath
475         
476         def addNotifier(self, notifier):
477                 self.notifierList.append(notifier);
478                 notifier(self);
479         def change(self):
480                 for notifier in self.notifierList:
481                         notifier(self)
482         def reload(self):
483                 self.loadData()
484         def save(self):
485                 configfile.setKey(self.configPath, self.datatoFile(self.controlType,self.value))
486
487 class configElement_nonSave(configElement):
488         def __init__(self, configPath, control, defaultValue, vals):
489                 configElement.__init__(self, configPath, control, defaultValue, vals)
490
491         def save(self):
492                 pass
493                 
494 def getConfigListEntry(description, element):
495         b = element
496         item = b.controlType(b)
497         return ((description, item))