added an example for weekday selection
[enigma2.git] / 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("INTEGER", (min, max)) => x with min <= x <= max
158                 if (type == "INTEGER"):
159                         return ((":"), [args], "")
160                 # configsequencearg.get("PINCODE", (number, "*")) => pin with number = length of pincode and "*" as numbers shown as stars
161                 # configsequencearg.get("PINCODE", (number, "")) => pin with number = length of pincode and numbers shown
162                 if (type == "PINCODE"):
163                         return ((":"), [(0, (10**args[0])-1)], args[1])
164                 # configsequencearg.get("FLOAT", [(min,max),(min1,max1)]) => x.y with min <= x <= max and min1 <= y <= max1
165                 if (type == "FLOAT"):
166                         return (("."), args, "")
167
168 configsequencearg = configSequenceArg()
169                 
170 class configSequence:
171         def __init__(self, parent):
172                 self.parent = parent
173                 self.markedPos = 0
174                 self.seperator = self.parent.vals[0]
175                 self.valueBounds = self.parent.vals[1]
176                 self.censorChar = self.parent.vals[2]
177
178         def checkValues(self):
179                 maxPos = 0
180                 num = 0
181                 for i in self.parent.value:
182                         maxPos += len(str(self.valueBounds[num][1]))
183                         while (self.valueBounds[num][0] > self.parent.value[num]):
184                                 self.parent.value[num] += 1
185
186                         while (self.valueBounds[num][1] < self.parent.value[num]):
187                                 self.parent.value[num] -= 1
188                                 
189 #                       if (self.valueBounds[num][0] <= i <= self.valueBounds[num][1]):
190                                 #pass
191                         #else:
192                                 #self.parent.value[num] = self.valueBounds[num][0]
193                         num += 1
194                 
195                 if self.markedPos >= maxPos:
196                         self.markedPos = maxPos - 1
197                 if self.markedPos < 0:
198                         self.markedPos = 0
199                         
200         def cancel(self):
201                 self.parent.reload()
202
203         def save(self):
204                 self.parent.save()
205
206         def handleKey(self, key):
207                 #this will no change anything on the value itself
208                 #so we can handle it here in gui element
209                 if key == config.key["prevElement"]:
210                         self.markedPos -= 1
211                 if key == config.key["nextElement"]:
212                         self.markedPos += 1
213                 
214                 if key >= config.key["0"] and key <= config.key["9"]:
215                         number = 9 - config.key["9"] + key
216                         # length of numberblock
217                         numberLen = len(str(self.valueBounds[0][1]))
218                         # position in the block
219                         posinblock = self.markedPos % numberLen
220                         # blocknumber
221                         blocknumber = self.markedPos / numberLen
222                         
223                         oldvalue = self.parent.value[blocknumber]
224                         olddec = oldvalue % 10 ** (numberLen - posinblock) - (oldvalue % 10 ** (numberLen - posinblock - 1))
225                         newvalue = oldvalue - olddec + (10 ** (numberLen - posinblock - 1) * number)
226                         
227                         print "You actually pressed a number (" + str(number) + ") which will be added at block number " + str(blocknumber) + " on position " + str(posinblock)
228                         print "Old value: " + str(oldvalue) + " olddec: " + str(olddec) + " newvalue: " + str(newvalue)
229                         self.parent.value[blocknumber] = newvalue
230                         self.markedPos += 1
231                 
232                 self.checkValues()                      
233                 
234                 print "markPos:",
235                 print self.markedPos
236
237                 #FIXME: dont call when press left/right
238                 self.parent.change()    
239
240         def __call__(self, selected):                   #needed by configlist
241                 value = ""
242                 mPos = self.markedPos
243                 print "Positon: " + str(mPos)
244                 num = 0;
245                 for i in self.parent.value:
246                         if len(value):  #fixme no heading separator possible
247                                 value += self.seperator
248                                 if mPos >= len(value) - 1:
249                                         mPos += 1
250                                 
251                         #diff =         self.valueBounds - len(str(i))
252                         #if diff > 0:
253                                 ## if this helps?!
254                                 #value += " " * diff
255                         print (("%0" + str(len(str(self.valueBounds[num][1]))) + "d") % i)
256                         if (self.censorChar == ""):
257                                 value += ("%0" + str(len(str(self.valueBounds[num][1]))) + "d") % i
258                         else:
259                                 value += (self.censorChar * len(str(self.valueBounds[num][1])))
260                         num += 1
261                         # only mark cursor when we are selected
262                         # (this code is heavily ink optimized!)
263                 return ("mtext"[1-selected:], value, [mPos])
264
265 class configValue:
266         def __init__(self, obj):
267                 self.obj = obj
268                 
269         def __str__(self):
270                 return self.obj
271
272 class Config:
273         def __init__(self):
274                 self.key = { "choseElement": 0,
275                                          "prevElement": 1,
276                                          "nextElement": 2,
277                                          "0": 10,
278                                          "1": 11,
279                                          "2": 12,
280                                          "3": 13,
281                                          "4": 14,
282                                          "5": 15,
283                                          "6": 16,
284                                          "7": 17,
285                                          "8": 18,
286                                          "9": 19 }
287                 
288 config = Config();
289 configfile = configFile()
290
291 class ConfigSlider:
292         def __init__(self, parent):
293                 self.parent = parent
294
295         def cancel(self):
296                 self.parent.reload()
297
298         def save(self):
299                 self.parent.save()
300
301         def checkValues(self):
302                 if self.parent.value < 0:
303                         self.parent.value = 0   
304
305                 if self.parent.value > 10:
306                         self.parent.value = 10  
307
308         def handleKey(self, key):
309                 if key == config.key["prevElement"]:
310                         self.parent.value = self.parent.value - 1
311                 if key == config.key["nextElement"]:
312                         self.parent.value = self.parent.value + 1
313                                         
314                 self.checkValues()      
315                 self.parent.change()    
316
317         def __call__(self, selected):                   #needed by configlist
318                 self.checkValues()
319                 return ("slider", self.parent.value * 10)
320
321 class ConfigSubsection:
322         def __init__(self):
323                 pass
324
325 class configElement:
326
327         def getIndexbyEntry(self, data):
328                 cnt = 0;
329                 tcnt = -1; #for defaultval
330                 for x in self.vals:
331                         if int(x[1]) == int(data):
332                                         return cnt
333                         if int(x[1]) == int(self.defaultValue):
334                                         tcnt = cnt
335                         cnt += 1
336                 if tcnt != -1:
337                         return tcnt                     
338                 return 0        #prevent bigger then array
339
340         def datafromFile(self, control, data):
341                 if control == ConfigSlider:
342                         return int(data);
343                 elif control == configSelection:
344                         return int(data);
345                 elif control == configDateTime:
346                         return int(data);
347                 elif control == configSequence:
348                         list = [ ]
349                         part = data.split(self.vals[0])
350                         for x in part:
351                                 list.append(int(x))
352                         return list
353                 elif control == configSatlist:
354                         return self.getIndexbyEntry(data)
355                 else: 
356                         return ""       
357
358         def datatoFile(self, control, data):
359                 if control == ConfigSlider:
360                         return str(data);
361                 elif control == configSelection:
362                         return str(data);
363                 elif control == configDateTime:
364                         return str(data);
365                 elif control == configSequence:
366                         value = ((len(data) * ("%d" + self.vals[0]))[0:-1]) % tuple(data)
367 #                       just in case you don't understand the above, here an equivalent:
368 #                       value = ""
369 #                       for i in data:
370 #                               if value !="":
371 #                                       value += self.vals[0]
372 #                               value += str(i)
373                         return value
374                 elif control == configSatlist:
375                         return str(self.vals[self.value][1]);
376                 else: 
377                         return ""       
378
379         def loadData(self):
380                 try:
381                         value = self.datafromFile(self.controlType, configfile.getKey(self.configPath))
382                 except:         
383                         value = ""
384
385                 if value == "":
386                         #print "value not found - using default"
387
388                         if self.controlType == configSatlist:
389                                 self.value = self.getIndexbyEntry(self.defaultValue)
390                         else:   
391                                 self.value = self.defaultValue
392
393                         self.save()             #add missing value to dict
394                 else:
395                         self.value = value
396                         
397                 #is this right? activate settings after load/cancel and use default     
398                 self.change()
399
400         def __init__(self, configPath, control, defaultValue, vals):
401                 self.configPath = configPath
402                 self.defaultValue = defaultValue
403                 self.controlType = control
404                 self.vals = vals
405                 self.notifierList = [ ]
406                 self.enabled = True
407                 self.loadData()         
408         def addNotifier(self, notifier):
409                 self.notifierList.append(notifier);
410                 notifier(self);
411         def change(self):
412                 for notifier in self.notifierList:
413                         notifier(self)
414         def reload(self):
415                 self.loadData()
416         def save(self):
417                 configfile.setKey(self.configPath, self.datatoFile(self.controlType,self.value))
418
419 class configElement_nonSave(configElement):
420         def __init__(self, configPath, control, defaultValue, vals):
421                 configElement.__init__(self, configPath, control, defaultValue, vals)
422
423         def save(self):
424                 pass
425                 
426 def getConfigListEntry(description, element):
427         b = element
428         item = b.controlType(b)
429         return ((description, item))
430
431