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