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