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