small fix
[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.Text = self.parent.value.decode("utf-8")
351                 except UnicodeDecodeError:
352                         self.Text = self.parent.value
353                         print "utf8 kaputt!"
354
355         def checkValues(self):
356                 if (self.markedPos < 0):
357                         self.markedPos = 0
358                 if (self.markedPos >= len(self.Text)):
359                         self.markedPos = len(self.Text) - 1
360
361         def cancel(self):
362                 self.parent.reload()
363
364         def save(self):
365                 self.parent.save()
366
367         def nextEntry(self):
368                 self.parent.vals[1](self.parent.getConfigPath())
369
370         def handleKey(self, key):
371                 #this will no change anything on the value itself
372                 #so we can handle it here in gui element
373                 if key == config.key["delete"]:
374                         self.Text = self.Text[0:self.markedPos] + self.Text[self.markedPos + 1:]
375                         self.parent.value = self.Text.encode("utf-8")
376                 elif key == config.key["prevElement"]:
377                         self.nextKey()
378                         self.markedPos -= 1
379                 elif key == config.key["nextElement"]:
380                         self.nextKey()
381                         self.markedPos += 1
382                         if (self.mode == self.extendableSize):
383                                 if (self.markedPos >= len(self.Text)):
384                                         self.Text = self.Text.ljust(len(self.Text) + 1)
385                                         self.parent.value = self.Text.encode("utf-8")
386                 elif key >= config.key["0"] and key <= config.key["9"]:
387                         number = 9 - config.key["9"] + key
388                         self.Text = self.Text[0:self.markedPos] + self.getKey(number) + self.Text[self.markedPos + 1:]
389                         self.parent.value = self.Text.encode("utf-8")
390                 self.checkValues()
391                 self.parent.change()
392
393         def __call__(self, selected):                   #needed by configlist
394                 return ("mtext"[1-selected:], self.parent.value, [self.markedPos])
395
396 class configValue:
397         def __init__(self, obj):
398                 self.obj = obj
399                 
400         def __str__(self):
401                 return self.obj
402
403 class Config:
404         def __init__(self):
405                 self.key = { "choseElement": 0,
406                                          "prevElement": 1,
407                                          "nextElement": 2,
408                                          "delete": 3,
409                                          "0": 10,
410                                          "1": 11,
411                                          "2": 12,
412                                          "3": 13,
413                                          "4": 14,
414                                          "5": 15,
415                                          "6": 16,
416                                          "7": 17,
417                                          "8": 18,
418                                          "9": 19 }
419                 
420 config = Config();
421
422 configfile = configFile()
423
424 class configSlider:
425         def __init__(self, parent):
426                 self.parent = parent
427
428         def cancel(self):
429                 self.parent.reload()
430
431         def save(self):
432                 self.parent.save()
433
434         def checkValues(self):
435                 if self.parent.value < 0:
436                         self.parent.value = 0   
437
438                 if self.parent.value > self.parent.vals[1]:
439                         self.parent.value = self.parent.vals[1]
440
441         def handleKey(self, key):
442                 if key == config.key["prevElement"]:
443                         self.parent.value = self.parent.value - self.parent.vals[0]
444                 if key == config.key["nextElement"]:
445                         self.parent.value = self.parent.value + self.parent.vals[0]
446                                         
447                 self.checkValues()      
448                 self.parent.change()    
449
450         def __call__(self, selected):                   #needed by configlist
451                 self.checkValues()
452                 return ("slider", self.parent.value, self.parent.vals[1])
453
454 class ConfigSubsection:
455         def __init__(self):
456                 pass
457
458 class configElement:
459
460         def getIndexbyEntry(self, data):
461                 cnt = 0;
462                 tcnt = -1; #for defaultval
463                 for x in self.vals:
464                         if int(x[1]) == int(data):
465                                         return cnt
466                         if int(x[1]) == int(self.defaultValue):
467                                         tcnt = cnt
468                         cnt += 1
469                 if tcnt != -1:
470                         return tcnt
471                 return 0        #prevent bigger then array
472
473         def datafromFile(self, control, data):
474                 if control == configSlider:
475                         return int(data)
476                 elif control == configSelection:
477                         try:
478                                 return int(data)
479                         except:
480                                 for x in data.split(":"):
481                                         if x[0] == "*":
482                                                 count = 0
483                                                 for y in self.vals:
484                                                         if y[0] == x[1:-1]:
485                                                                 return count
486                                                         count += 1
487                                 return self.defaultValue
488                 elif control == configDateTime:
489                         return int(data)
490                 elif control == configText:
491                         return str(data)
492                 elif control == configSequence:
493                         list = [ ]
494                         part = data.split(self.vals[0])
495                         for x in part:
496                                 list.append(int(x))
497                         return list
498                 elif control == configSatlist:
499                         return self.getIndexbyEntry(data)
500                 else: 
501                         return ""       
502
503         def datatoFile(self, control, data):
504                 if control == configSlider:
505                         return str(data)
506                 elif control == configSelection:
507                         if len(self.vals) < data + 1:
508                                 return "0"
509                         if isinstance(self.vals[data], str):
510                                 return str(data)
511                         else:
512                                 confList = []
513                                 count = 0
514                                 for x in self.vals:
515                                         if count == data:
516                                                 confList.append("*" + str(x[0] + "*"))
517                                         else:
518                                                 confList.append(x[0])
519                                         count += 1
520                                 return ":".join(confList)
521                         return str(data)
522                 elif control == configDateTime:
523                         return str(data)
524                 elif control == configText:
525                         return str(data.strip())
526                 elif control == configSequence:
527 #                       print self.vals
528 #                       print self.value
529                         try:
530                                 value = ""
531                                 count = 0
532                                 for i in data:
533                                         if value !="":
534                                                 value += self.vals[0]
535                                         value += (("%0" + str(len(str(self.vals[1][count][1]))) + "d") % i)
536                                         count += 1
537                                         #value = ((len(data) * ("%d" + self.vals[0]))[0:-1]) % tuple(data)
538                         except: 
539                                 value = str(data)       
540                         return value
541                 elif control == configSatlist:
542                         return str(self.vals[self.value][1]);
543                 else: 
544                         return ""       
545
546         def loadData(self):
547                 #print "load:" + self.configPath
548                 try:
549                         value = self.datafromFile(self.controlType, configfile.getKey(self.configPath))
550                 except:         
551                         value = ""
552
553                 if value == "":
554                         #print "value not found - using default"
555                         if self.controlType == configSatlist:
556                                 self.value = self.getIndexbyEntry(self.defaultValue)
557                         elif self.controlType == configSequence:
558                                 self.value = self.defaultValue[:]
559                         else:
560                                 self.value = self.defaultValue
561
562                         self.save()             #add missing value to dict
563                 else:
564                         #print "set val:" + str(value)
565                         self.value = value
566
567                 #is this right? activate settings after load/cancel and use default     
568                 self.change()
569
570         def __init__(self, configPath, control, defaultValue, vals, saveDefaults = True):
571                 self.configPath = configPath
572                 self.defaultValue = defaultValue
573                 self.controlType = control
574                 self.vals = vals
575                 self.notifierList = [ ]
576                 self.enabled = True
577                 self.saveDefaults = saveDefaults
578                 self.loadData()         
579                 
580         def getConfigPath(self):
581                 return self.configPath
582         
583         def addNotifier(self, notifier):
584                 self.notifierList.append(notifier);
585                 notifier(self);
586
587         def change(self):
588                 for notifier in self.notifierList:
589                         notifier(self)
590
591         def reload(self):
592                 self.loadData()
593
594         def save(self):
595                 if self.controlType == configSatlist:
596                         defaultValue = self.getIndexbyEntry(self.defaultValue)
597                 else:
598                         defaultValue = self.defaultValue
599                 if self.value != defaultValue or self.saveDefaults:
600                         configfile.setKey(self.configPath, self.datatoFile(self.controlType, self.value))
601                 else:
602                         try:
603                                 oldValue = configfile.getKey(self.configPath)
604                         except:
605                                 oldValue = None
606                         if oldValue is not None and oldValue != defaultValue:
607                                 configfile.setKey(self.configPath, self.datatoFile(self.controlType, self.value), True)
608
609 class configElement_nonSave(configElement):
610         def __init__(self, configPath, control, defaultValue, vals):
611                 configElement.__init__(self, configPath, control, defaultValue, vals)
612
613         def save(self):
614                 pass
615
616 def getConfigListEntry(description, element):
617         b = element
618         item = b.controlType(b)
619         return ((description, item))
620
621 def configElementBoolean(name, default, texts=(_("Disable"), _("Enable"))):
622         return configElement(name, configSelection, default, texts)
623
624 config.misc = ConfigSubsection()