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