diff options
| author | Felix Domke <tmbinc@elitedvb.net> | 2006-10-02 23:55:37 +0000 |
|---|---|---|
| committer | Felix Domke <tmbinc@elitedvb.net> | 2006-10-02 23:55:37 +0000 |
| commit | 6eeefece35e4269e02fdb7abab4f79d8e7b8f98b (patch) | |
| tree | 70f4afcee82f3097e9e52a987ede8914a542b098 /lib/python/Components | |
| parent | cedcadfd77539c39e928a6d5cc4fcd8d1cf48ac8 (diff) | |
| download | enigma2-6eeefece35e4269e02fdb7abab4f79d8e7b8f98b.tar.gz enigma2-6eeefece35e4269e02fdb7abab4f79d8e7b8f98b.zip | |
config rewrite. some extensions still need to be updated.
Diffstat (limited to 'lib/python/Components')
| -rw-r--r-- | lib/python/Components/AVSwitch.py | 50 | ||||
| -rw-r--r-- | lib/python/Components/Clock.py | 6 | ||||
| -rw-r--r-- | lib/python/Components/ConfigList.py | 85 | ||||
| -rw-r--r-- | lib/python/Components/InputDevice.py | 11 | ||||
| -rw-r--r-- | lib/python/Components/Lcd.py | 19 | ||||
| -rw-r--r-- | lib/python/Components/Network.py | 23 | ||||
| -rw-r--r-- | lib/python/Components/NimManager.py | 432 | ||||
| -rw-r--r-- | lib/python/Components/RFmod.py | 16 | ||||
| -rw-r--r-- | lib/python/Components/RecordingConfig.py | 9 | ||||
| -rw-r--r-- | lib/python/Components/Renderer/PositionGauge.py | 22 | ||||
| -rw-r--r-- | lib/python/Components/ServicePosition.py | 29 | ||||
| -rw-r--r-- | lib/python/Components/SetupDevices.py | 38 | ||||
| -rw-r--r-- | lib/python/Components/Sources/Makefile.am | 2 | ||||
| -rw-r--r-- | lib/python/Components/TimerSanityCheck.py | 1 | ||||
| -rw-r--r-- | lib/python/Components/Timezones.py | 2 | ||||
| -rw-r--r-- | lib/python/Components/UsageConfig.py | 12 | ||||
| -rw-r--r-- | lib/python/Components/config.py | 1258 |
17 files changed, 1162 insertions, 853 deletions
diff --git a/lib/python/Components/AVSwitch.py b/lib/python/Components/AVSwitch.py index 19fccf54..33045d40 100644 --- a/lib/python/Components/AVSwitch.py +++ b/lib/python/Components/AVSwitch.py @@ -1,4 +1,4 @@ -from config import * +from config import config, ConfigSelection, ConfigYesNo, ConfigEnableDisable, ConfigSubsection, ConfigBoolean import os from enigma import * @@ -14,7 +14,8 @@ class AVSwitch: else: eAVSwitch.getInstance().setSlowblank(self.INPUT[input][1]) # FIXME why do we have to reset the colorformat? bug in avs-driver? - eAVSwitch.getInstance().setColorFormat(config.av.colorformat.value) + map = {"cvbs": 0, "rgb": 1, "svideo": 2, "yuv": 3} + eAVSwitch.getInstance().setColorFormat(map[config.av.colorformat.value]) def setColorFormat(self, value): eAVSwitch.getInstance().setColorFormat(value) @@ -28,7 +29,7 @@ class AVSwitch: eAVSwitch.getInstance().setVideomode(value) def getAspectRatioSetting(self): - valstr = currentConfigSelectionElement(config.av.aspectratio) + valstr = config.av.aspectratio.value if valstr == "4_3_letterbox": val = 0 elif valstr == "4_3_panscan": @@ -49,7 +50,7 @@ class AVSwitch: if aspect == 0 or aspect == 1: # letterbox or panscan value = 3 # 4:3_full_format elif aspect == 2: # 16:9 - if currentConfigSelectionElement(config.av.wss) == "off": + if not config.av.wss.value: value = 2 # auto(4:3_off) else: value = 1 # auto @@ -71,32 +72,41 @@ class AVSwitch: eAVSwitch.getInstance().setSlowblank(value) def InitAVSwitch(): - config.av = ConfigSubsection(); - config.av.yuvenabled = configElementBoolean("config.av.yuvenabled", 0) - colorformat_choices = ( ("cvbs", _("CVBS")), ("rgb", _("RGB")), ("svideo", _("S-Video")), ("yuv", _("YPbPr")) ) + config.av = ConfigSubsection() + config.av.yuvenabled = ConfigBoolean(default=False) + colorformat_choices = {"cvbs": _("CVBS"), "rgb": _("RGB"), "svideo": _("S-Video")} # when YUV is not enabled, don't let the user select it - if not config.av.yuvenabled.value: - colorformat_choices = colorformat_choices[:3] - - config.av.colorformat = configElement("config.av.colorformat", configSelection, 1, colorformat_choices) - config.av.aspectratio = configElement("config.av.aspectratio", configSelection, 0, (("4_3_letterbox", _("4:3 Letterbox")), ("4_3_panscan", _("4:3 PanScan")), ("16_9", _("16:9")), ("16_9_always", _("16:9 always")), ("16_10_letterbox", _("16:10 Letterbox")), ("16_10_panscan", _("16:10 PanScan"))) ) - #config.av.tvsystem = configElement("config.av.tvsystem", configSelection, 0, ("PAL", "PAL + PAL60", "Multi", "NTSC") ) - config.av.tvsystem = configElement("config.av.tvsystem", configSelection, 0, (("pal", _("PAL")), ("ntsc", _("NTSC"))) ) - config.av.wss = configElement("config.av.wss", configSelection, 0, (("off", _("Off")), ("on", _("On"))) ) - config.av.defaultac3 = configElement("config.av.defaultac3", configSelection, 1, (("enable", _("Enable")), ("disable", _("Disable")))) - config.av.vcrswitch = configElement("config.av.vcrswitch", configSelection, 1, (("enable", _("Enable")), ("disable", _("Disable")))) + if config.av.yuvenabled.value: + colorformat_choices["yuv"] = _("YPbPr") + + config.av.colorformat = ConfigSelection(choices=colorformat_choices, default="rgb") + config.av.aspectratio = ConfigSelection(choices={ + "4_3_letterbox": _("4:3 Letterbox"), + "4_3_panscan": _("4:3 PanScan"), + "16_9": _("16:9"), + "16_9_always": _("16:9 always"), + "16_10_letterbox": _("16:10 Letterbox"), + "16_10_panscan": _("16:10 PanScan")}, + default = "4_3_letterbox") + config.av.tvsystem = ConfigSelection(choices = {"pal": _("PAL"), "ntsc": _("NTSC")}, default="pal") + config.av.wss = ConfigEnableDisable(default = True) + config.av.defaultac3 = ConfigYesNo(default = False) + config.av.vcrswitch = ConfigEnableDisable(default = False) iAVSwitch = AVSwitch() def setColorFormat(configElement): - iAVSwitch.setColorFormat(configElement.value) + map = {"cvbs": 0, "rgb": 1, "svideo": 2, "yuv": 3} + iAVSwitch.setColorFormat(map[configElement.value]) def setAspectRatio(configElement): - iAVSwitch.setAspectRatio(configElement.value) + map = {"4_3_letterbox": 0, "4_3_panscan": 1, "16_9": 2, "16_9_always": 3, "16_10_letterbox": 4, "16_10_panscan": 5} + iAVSwitch.setAspectRatio(map[configElement.value]) def setSystem(configElement): - iAVSwitch.setSystem(configElement.value) + map = {"pal": 0, "ntsc": 1} + iAVSwitch.setSystem(map[configElement.value]) def setWSS(configElement): iAVSwitch.setAspectWSS() diff --git a/lib/python/Components/Clock.py b/lib/python/Components/Clock.py index ae828c4f..95f29b16 100644 --- a/lib/python/Components/Clock.py +++ b/lib/python/Components/Clock.py @@ -7,8 +7,6 @@ from VariableText import * from enigma import * -from config import config - import time # now some "real" components: @@ -28,20 +26,16 @@ class Clock(VariableText, HTMLComponent, GUIComponent): def onHide(self): self.clockTimer.stop() -# "funktionalitaet" def doClock(self): t = time.localtime() timestr = "%2d:%02d:%02d" % (t.tm_hour, t.tm_min, t.tm_sec) self.setText(timestr) -# realisierung als GUI def createWidget(self, parent): return eLabel(parent) def removeWidget(self, w): del self.clockTimer -# ...und als HTML: def produceHTML(self): - # return T.b[self.getText()] return self.getText() diff --git a/lib/python/Components/ConfigList.py b/lib/python/Components/ConfigList.py index 1341ac50..e586f39d 100644 --- a/lib/python/Components/ConfigList.py +++ b/lib/python/Components/ConfigList.py @@ -1,17 +1,27 @@ from HTMLComponent import * from GUIComponent import * -from config import * - -from enigma import eListbox, eListboxPythonConfigContent +from config import KEY_LEFT, KEY_RIGHT, KEY_0, KEY_DELETE, KEY_OK, KEY_TIMEOUT +from Components.ActionMap import NumberActionMap +from enigma import eListbox, eListboxPythonConfigContent, eTimer class ConfigList(HTMLComponent, GUIComponent, object): - def __init__(self, list): + def __init__(self, list, session = None): GUIComponent.__init__(self) self.l = eListboxPythonConfigContent() self.l.setSeperation(100) self.list = list self.onSelectionChanged = [ ] + self.current = None + self.help_window = None + self.setHelpWindowSession(session) + + self.timer = eTimer() + self.timer.timeout.get().append(self.timeout) + def setHelpWindowSession(self, session): + assert self.help_window is None, "you can't move a help window to another session" + self.session = session + def toggle(self): selection = self.getCurrent() selection[1].toggle() @@ -19,9 +29,13 @@ class ConfigList(HTMLComponent, GUIComponent, object): def handleKey(self, key): selection = self.getCurrent() - if selection[1].parent.enabled: + if selection[1].enabled: selection[1].handleKey(key) self.invalidateCurrent() + if self.help_window: + self.help_window.update(selection[1]) + if key not in [KEY_TIMEOUT, KEY_LEFT, KEY_RIGHT, KEY_DELETE, KEY_OK]: + self.timer.start(1000, 1) def getCurrent(self): return self.l.getCurrentSelection() @@ -30,15 +44,26 @@ class ConfigList(HTMLComponent, GUIComponent, object): self.l.invalidateEntry(self.l.getCurrentSelectionIndex()) def invalidate(self, entry): - i = 0 - for x in self.__list: - if (entry.getConfigPath() == x[1].parent.getConfigPath()): - self.l.invalidateEntry(i) - i += 1 + self.l.invalidateEntry(self.__list.index(entry)) GUI_WIDGET = eListbox def selectionChanged(self): + n = self.getCurrent() + + if self.help_window: + print "close old help window!" + self.session.deleteDialog(self.help_window) + + nh = n and n[1].helpWindow() + print "n, nh:", n, nh + if nh is not None and self.session is not None: + print "show new help window" + self.help_window = self.session.instantiateDialog(*nh) + self.help_window.show() + + print "config selection changed, from ", self.current, " to ", n + self.current = n for x in self.onSelectionChanged: x() @@ -57,3 +82,43 @@ class ConfigList(HTMLComponent, GUIComponent, object): return self.__list list = property(getList, setList) + + def timeout(self): + self.handleKey(KEY_TIMEOUT) + +class ConfigListScreen: + def __init__(self, list, session = None): + self["config_actions"] = NumberActionMap(["SetupActions", "TextInputActions"], + { + "ok": self.keyOK, + "left": self.keyLeft, + "right": self.keyRight, + "delete": self.keyDelete, + "1": self.keyNumberGlobal, + "2": self.keyNumberGlobal, + "3": self.keyNumberGlobal, + "4": self.keyNumberGlobal, + "5": self.keyNumberGlobal, + "6": self.keyNumberGlobal, + "7": self.keyNumberGlobal, + "8": self.keyNumberGlobal, + "9": self.keyNumberGlobal, + "0": self.keyNumberGlobal + }, -1) + + self["config"] = ConfigList(list, session = session) + + def keyOK(self): + self["config"].handleKey(KEY_OK) + + def keyLeft(self): + self["config"].handleKey(KEY_LEFT) + + def keyRight(self): + self["config"].handleKey(KEY_RIGHT) + + def keyDelete(self): + self["config"].handleKey(KEY_DELETE) + + def keyNumberGlobal(self, number): + self["config"].handleKey(KEY_0 + number) diff --git a/lib/python/Components/InputDevice.py b/lib/python/Components/InputDevice.py index bfb5435b..3c3bd7a1 100644 --- a/lib/python/Components/InputDevice.py +++ b/lib/python/Components/InputDevice.py @@ -1,9 +1,4 @@ -from config import config #global config instance - -from config import configElement -from config import ConfigSubsection -from config import configSlider -from config import configSelection +from config import config, ConfigSlider, ConfigSubsection class inputDevices: def __init__(self): @@ -17,8 +12,8 @@ class inputDevices: def InitInputDevices(): config.inputDevices = ConfigSubsection(); - config.inputDevices.repeat = configElement("config.inputDevices.repeat", configSlider, 5, (1, 10)) - config.inputDevices.delay = configElement("config.inputDevices.delay", configSlider, 4, (1, 10)) + config.inputDevices.repeat = ConfigSlider(default=5, limits=(1, 10)) + config.inputDevices.delay = ConfigSlider(default=4, limits=(1, 10)) #this instance anywhere else needed? iDevices = inputDevices(); diff --git a/lib/python/Components/Lcd.py b/lib/python/Components/Lcd.py index ea0c37a1..d547a58c 100644 --- a/lib/python/Components/Lcd.py +++ b/lib/python/Components/Lcd.py @@ -1,10 +1,6 @@ -from config import config #global config instance -from config import configSlider -from config import configSelection -from config import ConfigSubsection -from config import configElement +from config import config, ConfigSubsection, ConfigSlider, ConfigYesNo -from enigma import * +from enigma import eDBoxLCD class LCD: def __init__(self): @@ -25,10 +21,10 @@ class LCD: def InitLcd(): config.lcd = ConfigSubsection(); - config.lcd.bright = configElement("config.lcd.bright", configSlider, 10, (1, 10)) - config.lcd.contrast = configElement("config.lcd.contrast", configSlider, 10, (1, 10)) - config.lcd.standby = configElement("config.lcd.standby", configSlider, 0, (1,10)) - config.lcd.invert = configElement("config.lcd.invert", configSelection, 0, (("disable", _("Disable")), ("enable", _("Enable")))) + config.lcd.bright = ConfigSlider(default=10, limits=(1, 10)) + config.lcd.contrast = ConfigSlider(default=10, limits=(1, 10)) + config.lcd.standby = ConfigSlider(default=0, limits=(1,10)) + config.lcd.invert = ConfigYesNo(default=False) ilcd = LCD() @@ -44,6 +40,3 @@ def InitLcd(): config.lcd.bright.addNotifier(setLCDbright); config.lcd.contrast.addNotifier(setLCDcontrast); config.lcd.invert.addNotifier(setLCDinverted); - - - diff --git a/lib/python/Components/Network.py b/lib/python/Components/Network.py index 7d6c5e17..7513901f 100644 --- a/lib/python/Components/Network.py +++ b/lib/python/Components/Network.py @@ -1,4 +1,4 @@ -from config import * +from config import config, ConfigYesNo, ConfigIP, NoSave, ConfigSubsection, ConfigMAC import os from socket import * @@ -14,7 +14,7 @@ class Network: fp.write("auto lo\n") fp.write("iface lo inet loopback\n\n") fp.write("auto eth0\n") - if (currentConfigSelectionElement(config.network.dhcp) == "yes"): + if config.network.dhcp.value: fp.write("iface eth0 inet dhcp\n") else: fp.write("iface eth0 inet static\n") @@ -84,6 +84,7 @@ class Network: import os os.system("/etc/init.d/networking restart") config.network.ip.value = self.getCurrentIP() + config.network.ip.save() def setDHCP(self, useDHCP): if (useDHCP): @@ -140,22 +141,16 @@ iNetwork = Network() def InitNetwork(): ip = iNetwork.getCurrentIP() - config.network = ConfigSubsection() - config.network.dhcp = configElement_nonSave("config.network.dhcp", configSelection, 1, (("no", _("no")), ("yes", _("yes")))) - config.network.ip = configElement_nonSave("config.network.ip", configSequence, ip, configsequencearg.get("IP")) - config.network.netmask = configElement_nonSave("config.network.netmask", configSequence, [255,255,255,0], configsequencearg.get("IP")) - config.network.gateway = configElement_nonSave("config.network.gateway", configSequence, [192,168,1,3], configsequencearg.get("IP")) - config.network.dns = configElement_nonSave("config.network.dns", configSequence, [192,168,1,3], configsequencearg.get("IP")) - config.network.mac = configElement_nonSave("config.network.mac", configSequence, [00,11,22,33,44,55], configsequencearg.get("MAC")) + config.network.dhcp = NoSave(ConfigYesNo(default=True)) + config.network.ip = NoSave(ConfigIP(default=[0,0,0,0])) + config.network.netmask = NoSave(ConfigIP(default=[255,255,255,0])) + config.network.gateway = NoSave(ConfigIP(default=[192,168,1,3])) + config.network.dns = NoSave(ConfigIP(default=[192,168,1,3])) + config.network.mac = NoSave(ConfigMAC(default=[00,11,22,33,44,55])) iNetwork.loadNetworkConfig() - #FIXME using this till other concept for this is implemented - #config.network.activate = configElement("config.network.activate", configSelection, 0, ("yes, sir", "you are my hero")) - #config.network.activate = configElement("config.network.activate", configSelection, 0, ("yes", "you are my hero")) - - def writeNetworkConfig(configElement): iNetwork.writeNetworkConfig() diff --git a/lib/python/Components/NimManager.py b/lib/python/Components/NimManager.py index c24d8d35..783288ec 100644 --- a/lib/python/Components/NimManager.py +++ b/lib/python/Components/NimManager.py @@ -1,13 +1,4 @@ -from config import config #global config instance - -from config import configElement -from config import ConfigSubsection -from config import configSelection -from config import currentConfigSelectionElement -from config import getConfigSelectionElement -from config import configSequence -from config import configsequencearg -from config import configSatlist +from config import config, ConfigSubsection, ConfigSelection, ConfigFloat, ConfigSatlist, ConfigYesNo, ConfigInteger, ConfigSubList, ConfigDummy, ConfigSubDict from enigma import eDVBSatelliteEquipmentControl, \ eDVBSatelliteLNBParameters as lnbParam, \ @@ -74,12 +65,12 @@ class SecConfigure: sec.setInputpowerDelta(50) for x in self.NimManager.satList: - print "Add sat " + str(x[1]) - sec.addSatellite(int(x[1])) + print "Add sat " + str(x[0]) + sec.addSatellite(int(x[0])) sec.setVoltageMode(0) sec.setToneMode(0) sec.setRotorPosNum(0) # USALS - self.satList.append(int(x[1])) + self.satList.append(int(x[0])) def setSatposDepends(self, sec, nim1, nim2): print "tuner", nim1, "depends on satpos of", nim2 @@ -105,13 +96,13 @@ class SecConfigure: x = slot.slotid nim = config.Nims[x] if slot.nimType == self.NimManager.nimType["DVB-S"]: - if currentConfigSelectionElement(nim.configMode) == "equal": + if nim.configMode.value == "equal": self.equal[nim.equalTo.value]=x - if currentConfigSelectionElement(nim.configMode) == "loopthrough": + if nim.configMode.value == "loopthrough": self.linkNIMs(sec, x, nim.linkedTo.value) self.linked[nim.linkedTo.value]=x - elif currentConfigSelectionElement(nim.configMode) == "satposdepends": - self.setSatposDepends(sec, x, nim.satposDependsTo.value) + elif nim.configMode.value == "satposdepends": + self.setSatposDepends(sec, x, nim.satposDependsTo.index) self.satposdepends[nim.satposDependsTo.value]=x for slot in self.NimManager.nimslots: @@ -119,37 +110,38 @@ class SecConfigure: nim = config.Nims[x] if slot.nimType == self.NimManager.nimType["DVB-S"]: print "slot: " + str(x) + " configmode: " + str(nim.configMode.value) - if currentConfigSelectionElement(nim.configMode) in [ "loopthrough", "satposdepends", "equal", "nothing" ]: + print "diseqcmode: ", nim.configMode.value + if nim.configMode.value in [ "loopthrough", "satposdepends", "equal", "nothing" ]: pass - elif currentConfigSelectionElement(nim.configMode) == "simple": #simple config - if currentConfigSelectionElement(nim.diseqcMode) == "single": #single - self.addLNBSimple(sec, slotid = x, orbpos = int(nim.diseqcA.vals[nim.diseqcA.value][1]), toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.NONE, diseqcpos = diseqcParam.SENDNO) - elif currentConfigSelectionElement(nim.diseqcMode) == "toneburst_a_b": #Toneburst A/B - self.addLNBSimple(sec, slotid = x, orbpos = int(nim.diseqcA.vals[nim.diseqcA.value][1]), toneburstmode = diseqcParam.A, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO) - self.addLNBSimple(sec, slotid = x, orbpos = int(nim.diseqcB.vals[nim.diseqcB.value][1]), toneburstmode = diseqcParam.B, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO) - elif currentConfigSelectionElement(nim.diseqcMode) == "diseqc_a_b": #DiSEqC A/B - self.addLNBSimple(sec, slotid = x, orbpos = int(nim.diseqcA.vals[nim.diseqcA.value][1]), toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA) - self.addLNBSimple(sec, slotid = x, orbpos = int(nim.diseqcB.vals[nim.diseqcB.value][1]), toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB) - elif currentConfigSelectionElement(nim.diseqcMode) == "diseqc_a_b_c_d": #DiSEqC A/B/C/D - self.addLNBSimple(sec, slotid = x, orbpos = int(nim.diseqcA.vals[nim.diseqcA.value][1]), toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA) - self.addLNBSimple(sec, slotid = x, orbpos = int(nim.diseqcB.vals[nim.diseqcB.value][1]), toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB) - self.addLNBSimple(sec, slotid = x, orbpos = int(nim.diseqcC.vals[nim.diseqcC.value][1]), toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BA) - self.addLNBSimple(sec, slotid = x, orbpos = int(nim.diseqcD.vals[nim.diseqcD.value][1]), toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BB) - elif currentConfigSelectionElement(nim.diseqcMode) == "positioner": #Positioner - if currentConfigSelectionElement(nim.latitudeOrientation) == "north": + elif nim.configMode.value == "simple": #simple config + if nim.diseqcMode.value == "single": #single + self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.NONE, diseqcpos = diseqcParam.SENDNO) + elif nim.diseqcMode.value == "toneburst_a_b": #Toneburst A/B + self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.A, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO) + self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.B, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.SENDNO) + elif nim.diseqcMode.value == "diseqc_a_b": #DiSEqC A/B + self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA) + self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB) + elif nim.diseqcMode.value == "diseqc_a_b_c_d": #DiSEqC A/B/C/D + self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcA.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AA) + self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcB.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.AB) + self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcC.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BA) + self.addLNBSimple(sec, slotid = x, orbpos = nim.diseqcD.orbital_position, toneburstmode = diseqcParam.NO, diseqcmode = diseqcParam.V1_0, diseqcpos = diseqcParam.BB) + elif nim.diseqcMode.value == "positioner": #Positioner + if nim.latitudeOrientation.value == "north": laValue = rotorParam.NORTH else: laValue = rotorParam.SOUTH - if currentConfigSelectionElement(nim.longitudeOrientation) == "east": + if nim.longitudeOrientation.value == "east": loValue = rotorParam.EAST else: loValue = rotorParam.WEST self.addLNBSimple(sec, slotid = x, diseqcmode = 3, - longitude = configsequencearg.getFloat(nim.longitude), + longitude = nim.longitude.float, loDirection = loValue, - latitude = configsequencearg.getFloat(nim.latitude), + latitude = nim.latitude.float, laDirection = laValue) - elif currentConfigSelectionElement(nim.configMode) == "advanced": #advanced config + elif nim.configMode.value == "advanced": #advanced config self.updateAdvanced(sec, x) print "sec config completed" @@ -158,10 +150,10 @@ class SecConfigure: for x in range(1,33): lnbSat[x] = [] for x in self.NimManager.satList: - lnb = config.Nims[slotid].advanced.sat[x[1]].lnb.value + lnb = int(config.Nims[slotid].advanced.sat[x[0]].lnb.value) if lnb != 0: - print "add", x[1], "to", lnb - lnbSat[lnb].append(x[1]) + print "add", x[0], "to", lnb + lnbSat[lnb].append(x[0]) for x in range(1,33): if len(lnbSat[x]) > 0: currLnb = config.Nims[slotid].advanced.lnb[x] @@ -173,124 +165,110 @@ class SecConfigure: elif self.linked.has_key(slotid): tunermask |= (1 << self.linked[slotid]) - if currentConfigSelectionElement(currLnb.lof) == "universal_lnb": + if currLnb.lof.value == "universal_lnb": sec.setLNBLOFL(9750000) sec.setLNBLOFH(10600000) sec.setLNBThreshold(11700000) - elif currentConfigSelectionElement(currLnb.lof) == "c_band": + elif currLnb.lof.value == "c_band": sec.setLNBLOFL(5150000) sec.setLNBLOFH(5150000) sec.setLNBThreshold(5150000) - elif currentConfigSelectionElement(currLnb.lof) == "user_defined": - sec.setLNBLOFL(currLnb.lofl.value[0] * 1000) - sec.setLNBLOFH(currLnb.lofh.value[0] * 1000) - sec.setLNBThreshold(currLnb.threshold.value[0] * 1000) + elif currLnb.lof.value == "user_defined": + sec.setLNBLOFL(currLnb.lofl.value * 1000) + sec.setLNBLOFH(currLnb.lofh.value * 1000) + sec.setLNBThreshold(currLnb.threshold.value * 1000) - if currentConfigSelectionElement(currLnb.output_12v) == "0V": + if currLnb.output_12v.value == "0V": pass # nyi in drivers - elif currentConfigSelectionElement(currLnb.output_12v) == "12V": + elif currLnb.output_12v.value == "12V": pass # nyi in drivers - if currentConfigSelectionElement(currLnb.increased_voltage) == "yes": + if currLnb.increased_voltage.value: sec.setLNBIncreasedVoltage(lnbParam.ON) else: sec.setLNBIncreasedVoltage(lnbParam.OFF) - - if currentConfigSelectionElement(currLnb.diseqcMode) == "none": + + dm = currLnb.diseqcMode.value + if dm == "none": sec.setDiSEqCMode(diseqcParam.NONE) - elif currentConfigSelectionElement(currLnb.diseqcMode) == "1_0": + elif dm == "1_0": sec.setDiSEqCMode(diseqcParam.V1_0) - elif currentConfigSelectionElement(currLnb.diseqcMode) == "1_1": + elif dm == "1_1": sec.setDiSEqCMode(diseqcParam.V1_1) - elif currentConfigSelectionElement(currLnb.diseqcMode) == "1_2": + elif dm == "1_2": sec.setDiSEqCMode(diseqcParam.V1_2) if self.satposdepends.has_key(slotid): # only useable with rotors tunermask |= (1 << self.satposdepends[slotid]) - if currentConfigSelectionElement(currLnb.diseqcMode) != "none": - if currentConfigSelectionElement(currLnb.toneburst) == "none": + if dm != "none": + if currLnb.toneburst.value == "none": sec.setToneburst(diseqcParam.NO) - elif currentConfigSelectionElement(currLnb.toneburst) == "A": + elif currLnb.toneburst.value == "A": sec.setToneburst(diseqcParam.A) - elif currentConfigSelectionElement(currLnb.toneburst) == "B": + elif currLnb.toneburst.value == "B": sec.setToneburst(diseqcParam.B) + + # Committed Diseqc Command + cdc = currLnb.commitedDiseqcCommand.value + + c = [ + ("none", diseqcParam.SENDNO), + ("AA", diseqcParam.AA), + ("AB", diseqcParam.AB), + ("BA", diseqcParam.BA), + ("BB", diseqcParam.BB)] - if currentConfigSelectionElement(currLnb.commitedDiseqcCommand) == "none": - sec.setCommittedCommand(diseqcParam.SENDNO) - elif currentConfigSelectionElement(currLnb.commitedDiseqcCommand) == "AA": - sec.setCommittedCommand(diseqcParam.AA) - elif currentConfigSelectionElement(currLnb.commitedDiseqcCommand) == "AB": - sec.setCommittedCommand(diseqcParam.AB) - elif currentConfigSelectionElement(currLnb.commitedDiseqcCommand) == "BA": - sec.setCommittedCommand(diseqcParam.BA) - elif currentConfigSelectionElement(currLnb.commitedDiseqcCommand) == "BB": - sec.setCommittedCommand(diseqcParam.BB) + if cdc in c: + sec.setCommittedCommand(c[cdc]) else: - sec.setCommittedCommand(long(currentConfigSelectionElement(currLnb.commitedDiseqcCommand))) + sec.setCommittedCommand(long(cdc)) - if currentConfigSelectionElement(currLnb.fastDiseqc) == "yes": - sec.setFastDiSEqC(True) - else: - sec.setFastDiSEqC(False) + sec.setFastDiSEqC(currLnb.fastDiseqc.value) - if currentConfigSelectionElement(currLnb.sequenceRepeat) == "yes": - sec.setSeqRepeat(True) - else: - sec.setSeqRepeat(False) + sec.setSeqRepeat(currLnb.sequenceRepeat.value) - if currentConfigSelectionElement(currLnb.diseqcMode) == "1_0": + if currLnb.diseqcMode.value == "1_0": currCO = currLnb.commandOrder1_0.value else: currCO = currLnb.commandOrder.value - - if currLnb.uncommittedDiseqcCommand.value > 0: - sec.setUncommittedCommand(0xF0|(currLnb.uncommittedDiseqcCommand.value-1)) + + udc = int(currLnb.uncommittedDiseqcCommand.value) + if udc > 0: + sec.setUncommittedCommand(0xF0|(udc-1)) else: sec.setUncommittedCommand(0) # SENDNO - - if currentConfigSelectionElement(currLnb.diseqcRepeats) == "none": - sec.setRepeats(0) - elif currentConfigSelectionElement(currLnb.diseqcRepeats) == "one": - sec.setRepeats(1) - elif currentConfigSelectionElement(currLnb.diseqcRepeats) == "two": - sec.setRepeats(2) - elif currentConfigSelectionElement(currLnb.diseqcRepeats) == "three": - sec.setRepeats(3) - - setCommandOrder=False - if currCO == 0: # committed, toneburst - setCommandOrder=True - elif currCO == 1: # toneburst, committed - setCommandOrder=True - elif currCO == 2: # committed, uncommitted, toneburst - setCommandOrder=True - elif currCO == 3: # toneburst, committed, uncommitted - setCommandOrder=True - elif currCO == 4: # uncommitted, committed, toneburst - setCommandOrder=True - elif currCO == 5: # toneburst, uncommitted, commmitted - setCommandOrder=True - if setCommandOrder: - sec.setCommandOrder(currCO) - - if currentConfigSelectionElement(currLnb.diseqcMode) == "1_2": - latitude = configsequencearg.getFloat(currLnb.latitude) + + sec.setRepeats({"none": 0, "one": 1, "two": 2, "three": 3}[currLnb.diseqcRepeats.value]) + + setCommandOrder = False + + # 0 "committed, toneburst", + # 1 "toneburst, committed", + # 2 "committed, uncommitted, toneburst", + # 3 "toneburst, committed, uncommitted", + # 4 "uncommitted, committed, toneburst" + # 5 "toneburst, uncommitted, commmitted" + order_map = {"ct": 0, "tc": 1, "cut": 2, "tcu": 3, "uct": 4, "tuc": 5} + sec.setCommandOrder(order_map[currCO]) + + if dm == "1_2": + latitude = currLnb.latitude.float sec.setLatitude(latitude) - longitude = configsequencearg.getFloat(currLnb.longitude) + longitude = currLnb.longitude.float sec.setLongitude(longitude) - if currentConfigSelectionElement(currLnb.latitudeOrientation) == "north": + if currLnb.latitudeOrientation.value == "north": sec.setLaDirection(rotorParam.NORTH) else: sec.setLaDirection(rotorParam.SOUTH) - if currentConfigSelectionElement(currLnb.longitudeOrientation) == "east": + if currLnb.longitudeOrientation.value == "east": sec.setLoDirection(rotorParam.EAST) else: sec.setLoDirection(rotorParam.WEST) - if currentConfigSelectionElement(currLnb.powerMeasurement) == "yes": + if currLnb.powerMeasurement.value: sec.setUseInputpower(True) - sec.setInputpowerDelta(currLnb.powerThreshold.value[0]) + sec.setInputpowerDelta(currLnb.powerThreshold.value) else: sec.setUseInputpower(False) @@ -300,22 +278,23 @@ class SecConfigure: for y in lnbSat[x]: sec.addSatellite(y) currSat = config.Nims[slotid].advanced.sat[y] - if currentConfigSelectionElement(currSat.voltage) == "polarization": + + if currSat.voltage.value == "polarization": sec.setVoltageMode(switchParam.HV) - elif currentConfigSelectionElement(currSat.voltage) == "13V": + elif currSat.voltage.value == "13V": sec.setVoltageMode(switchParam._14V) - elif currentConfigSelectionElement(currSat.voltage) == "18V": + elif currSat.voltage.value == "18V": sec.setVoltageMode(switchParam._18V) - if currentConfigSelectionElement(currSat.tonemode) == "band": + if currSat.tonemode == "band": sec.setToneMode(switchParam.HILO) - elif currentConfigSelectionElement(currSat.tonemode) == "on": + elif currSat.tonemode == "on": sec.setToneMode(switchParam.ON) - elif currentConfigSelectionElement(currSat.tonemode) == "off": + elif currSat.tonemode == "off": sec.setToneMode(switchParam.OFF) - if currentConfigSelectionElement(currSat.usals) == "no": - sec.setRotorPosNum(currSat.rotorposition.value[0]) + if not currSat.usals.value: + sec.setRotorPosNum(currSat.rotorposition.value) else: sec.setRotorPosNum(0) #USALS @@ -345,7 +324,7 @@ class NimManager: tpos = 3600 + tpos tname = attrs.get('name',"").encode("UTF-8") self.satellites[tpos] = tname - self.satList.append( (tname, tpos) ) + self.satList.append( (tpos, tname) ) self.parsedSat = int(tpos) elif (name == "transponder"): modulation = int(attrs.get('modulation',"1")) # QPSK default @@ -575,7 +554,7 @@ class NimManager: return list def getNimConfigMode(self, slotid): - return currentConfigSelectionElement(config.Nims[slotid].configMode) + return config.Nims[slotid].configMode.value def getSatList(self): return self.satList @@ -587,26 +566,27 @@ class NimManager: #print "self.satellites:", self.satList[config.Nims[slotid].diseqcA.value] #print "diseqcA:", config.Nims[slotid].diseqcA.value - configMode = currentConfigSelectionElement(config.Nims[slotid].configMode) + configMode = config.Nims[slotid].configMode.value if configMode == "equal": slotid=0 #FIXME add handling for more than two tuners !!! - configMode = currentConfigSelectionElement(config.Nims[slotid].configMode) + configMode = config.Nims[slotid].configMode.value if configMode == "simple": - if (config.Nims[slotid].diseqcMode.value <= 3): - list.append(self.satList[config.Nims[slotid].diseqcA.value]) - if (0 < config.Nims[slotid].diseqcMode.value <= 3): - list.append(self.satList[config.Nims[slotid].diseqcB.value]) - if (config.Nims[slotid].diseqcMode.value == 3): - list.append(self.satList[config.Nims[slotid].diseqcC.value]) - list.append(self.satList[config.Nims[slotid].diseqcD.value]) - if (config.Nims[slotid].diseqcMode.value == 4): + dm = config.Nims[slotid].diseqcMode.value + if dm in ["single", "toneburst", "diseqc_a_b", "diseqc_a_b_c_d"]: + list.append(self.satList[config.Nims[slotid].diseqcA.index]) + if dm in ["toneburst", "diseqc_a_b", "diseqc_a_b_c_d"]: + list.append(self.satList[config.Nims[slotid].diseqcB.index]) + if dm == "diseqc_a_b_c_d": + list.append(self.satList[config.Nims[slotid].diseqcC.index]) + list.append(self.satList[config.Nims[slotid].diseqcD.index]) + if dm == "positioner": for x in self.satList: list.append(x) elif configMode == "advanced": for x in self.satList: - if config.Nims[slotid].advanced.sat[x[1]].lnb.value != 0: + if int(config.Nims[slotid].advanced.sat[x[0]].lnb.value) != 0: list.append(x) return list @@ -618,18 +598,18 @@ class NimManager: #print "self.satellites:", self.satList[config.Nims[slotid].diseqcA.value] #print "diseqcA:", config.Nims[slotid].diseqcA.value - configMode = currentConfigSelectionElement(config.Nims[slotid].configMode) + configMode = config.Nims[slotid].configMode.value if configMode == "simple": - if (config.Nims[slotid].diseqcMode.value == 4): + if config.Nims[slotid].diseqcMode.value == "positioner": for x in self.satList: list.append(x) elif configMode == "advanced": for x in self.satList: nim = config.Nims[slotid] - lnbnum = nim.advanced.sat[x[1]].lnb.value + lnbnum = int(nim.advanced.sat[x[0]].lnb.value) if lnbnum != 0: lnb = nim.advanced.lnb[lnbnum] - if lnb.diseqcMode.value == 3: # diseqc 1.2 + if lnb.diseqcMode.value == "diseqc_a_b_c_d": list.append(x) return list @@ -651,7 +631,7 @@ class NimManager: pass def InitNimManager(nimmgr): - config.Nims = [] + config.Nims = ConfigSubList() for x in range(nimmgr.nimCount): config.Nims.append(ConfigSubsection()) @@ -661,13 +641,13 @@ def InitNimManager(nimmgr): nimmgr.nimDiseqcModeChanged(slotid, configElement.value) def nimPortAChanged(slotid, configElement): - nimmgr.nimPortAChanged(slotid, configElement.vals[configElement.value][1]) + nimmgr.nimPortAChanged(slotid, configElement.value) def nimPortBChanged(slotid, configElement): - nimmgr.nimPortBChanged(slotid, configElement.vals[configElement.value][1]) + nimmgr.nimPortBChanged(slotid, configElement.value) def nimPortCChanged(slotid, configElement): - nimmgr.nimPortCChanged(slotid, configElement.vals[configElement.value][1]) + nimmgr.nimPortCChanged(slotid, configElement.value) def nimPortDChanged(slotid, configElement): - nimmgr.nimPortDChanged(slotid, configElement.vals[configElement.value][1]) + nimmgr.nimPortDChanged(slotid, configElement.value) for slot in nimmgr.nimslots: x = slot.slotid @@ -676,46 +656,67 @@ def InitNimManager(nimmgr): if slot.nimType == nimmgr.nimType["DVB-S"]: if slot.slotid == 0: - nim.configMode = configElement(cname + "configMode", configSelection, 0, ( - ("simple", _("Simple")), ("advanced", _("Advanced"))), False) + nim.configMode = ConfigSelection( + choices = { + "simple": _("simple"), + "advanced": _("advanced")}, + default = "simple") else: - nim.configMode = configElement(cname + "configMode", configSelection, 0, ( - ("equal", _("Equal to Socket A")), - ("loopthrough", _("Loopthrough to Socket A")), - ("nothing", _("Nothing connected")), - ("satposdepends", _("Secondary cable from motorized LNB")), - ("simple", _("Simple")), - ("advanced", _("Advanced"))), False) + + nim.configMode = ConfigSelection( + choices = { + "equal": _("equal to Socket A"), + "looptrough": _("loopthrough to socket A"), + "nothing": _("nothing connected"), + "satposdepends": _("second cable of motorized LNB"), + "simple": _("simple"), + "advanced": _("advanced")}, + default = "looptrough") + #important - check if just the 2nd one is LT only and the first one is DVB-S - if currentConfigSelectionElement(nim.configMode) in ["loopthrough", "satposdepends", "equal"]: - if x == 0: #first one can never be linked to anything - nim.configMode.value = getConfigSelectionElement(nim.configMode, "simple") #reset to simple + if nim.configMode.value in ["loopthrough", "satposdepends", "equal"]: + if x == 0: # first one can never be linked to anything + # reset to simple + nim.configMode.value = "simple" nim.configMode.save() else: #FIXME: make it better for y in nimmgr.nimslots: if y.slotid == 0: if y.nimType != nimmgr.nimType["DVB-S"]: - nim.configMode.value = getConfigSelectionElement(nim.configMode, "simple") #reset to simple + # reset to simple + nim.configMode.value = "simple" nim.configMode.save() - nim.diseqcMode = configElement(cname + "diseqcMode", configSelection, 2, (("single", _("Single")), ("toneburst_a_b", _("Toneburst A/B")), ("diseqc_a_b", _("DiSEqC A/B")), ("diseqc_a_b_c_d", _("DiSEqC A/B/C/D")), ("positioner", _("Positioner"))), False); - nim.diseqcA = configElement(cname + "diseqcA", configSatlist, 192, nimmgr.satList, False); - nim.diseqcB = configElement(cname + "diseqcB", configSatlist, 130, nimmgr.satList, False); - nim.diseqcC = configElement(cname + "diseqcC", configSatlist, 0, nimmgr.satList, False); - nim.diseqcD = configElement(cname + "diseqcD", configSatlist, 0, nimmgr.satList, False); - nim.positionerMode = configElement(cname + "positionerMode", configSelection, 0, (("usals", _("USALS")), ("manual", _("manual"))), False); - nim.longitude = configElement(cname + "longitude", configSequence, [5,100], configsequencearg.get("FLOAT", [(0,359),(0,999)]), False); - nim.longitudeOrientation = configElement(cname + "longitudeOrientation", configSelection, 0, (("east", _("East")), ("west", _("West"))), False) - nim.latitude = configElement(cname + "latitude", configSequence, [50,767], configsequencearg.get("FLOAT", [(0,359),(0,999)]), False); - nim.latitudeOrientation = configElement(cname + "latitudeOrientation", configSelection, 0, (("north", _("North")), ("south", _("South"))), False) + nim.diseqcMode = ConfigSelection( + choices = [ + ("single", _("Single")), + ("toneburst_a_b", _("Toneburst A/B")), + ("diseqc_a_b", _("DiSEqC A/B")), + ("diseqc_a_b_c_d", _("DiSEqC A/B/C/D")), + ("positioner", _("Positioner"))], + default = "diseqc_a_b") + nim.diseqcA = ConfigSatlist(default = 192, list = nimmgr.satList) + nim.diseqcB = ConfigSatlist(default = 130, list = nimmgr.satList) + nim.diseqcC = ConfigSatlist(list = nimmgr.satList) + nim.diseqcD = ConfigSatlist(list = nimmgr.satList) + nim.positionerMode = ConfigSelection( + choices = [ + ("usals", _("USALS")), + ("manual", _("manual"))], + default = "usals") + nim.longitude = ConfigFloat(default=[5,100], limits=[(0,359),(0,999)]) + nim.longitudeOrientation = ConfigSelection(choices={"east": _("East"), "west": _("West")}, default = "east") + nim.latitude = ConfigFloat(default=[50,767], limits=[(0,359),(0,999)]) + nim.latitudeOrientation = ConfigSelection(choices={"north": _("North"), "south": _("South")}, default="north") satNimList = nimmgr.getNimListOfType(nimmgr.nimType["DVB-S"], slot.slotid) - satNimListNames = [] + satNimListNames = {} for x in satNimList: - satNimListNames.append((("Slot_" + ("A", "B", "C", "D")[x] + "_" + nimmgr.getNimName(x)), _("Slot ") + ("A", "B", "C", "D")[x] + ": " + nimmgr.getNimName(x))) - nim.equalTo = configElement(cname + "equalTo", configSelection, 0, satNimListNames, False); - nim.linkedTo = configElement(cname + "linkedTo", configSelection, 0, satNimListNames, False); - nim.satposDependsTo = configElement(cname + "satposDependsTo", configSelection, 0, satNimListNames, False); + satNimListNames["Slot_" + ("A", "B", "C", "D")[x] + "_" + nimmgr.getNimName(x)] = _("Slot ") + ("A", "B", "C", "D")[x] + ": " + nimmgr.getNimName(x) + if len(satNimListNames): + nim.equalTo = ConfigSelection(choices = satNimListNames) + nim.linkedTo = ConfigSelection(choices = satNimListNames) + nim.satposDependsTo = ConfigSelection(choices = satNimListNames) #perhaps the instance of the slot is more useful? # nim.configMode.addNotifier(boundFunction(nimConfigModeChanged,x)) @@ -727,61 +728,72 @@ def InitNimManager(nimmgr): # advanced config: nim.advanced = ConfigSubsection() - nim.advanced.sats = configElement(cname + "advanced.sats", configSatlist, 192, nimmgr.satList, False); - nim.advanced.sat = {} - lnbs = ["not available"] + nim.advanced.sats = ConfigSatlist(default = 192, list = nimmgr.satList) + nim.advanced.sat = ConfigSubDict() + lnbs = [("0", "not available")] for y in range(1, 33): - lnbs.append("LNB " + str(y)) + lnbs.append((str(y), "LNB " + str(y))) + for x in nimmgr.satList: - nim.advanced.sat[x[1]] = ConfigSubsection() - nim.advanced.sat[x[1]].voltage = configElement(cname + "advanced.sat" + str(x[1]) + ".voltage", configSelection, 0, (("polarization", _("Polarization")), ("13V", _("13 V")), ("18V", _("18 V"))), False) - nim.advanced.sat[x[1]].tonemode = configElement(cname + "advanced.sat" + str(x[1]) + ".tonemode", configSelection, 0, (("band", _("Band")), ("on", _("On")), ("off", _("Off"))), False) - nim.advanced.sat[x[1]].usals = configElement(cname + "advanced.sat" + str(x[1]) + ".usals", configSelection, 0, (("yes", _("Yes")), ("no", _("No"))), False) - nim.advanced.sat[x[1]].rotorposition = configElement(cname + "advanced.sat" + str(x[1]) + ".rotorposition", configSequence, [1], configsequencearg.get("INTEGER", (1, 255)), False) - nim.advanced.sat[x[1]].lnb = configElement(cname + "advanced.sat" + str(x[1]) + ".lnb", configSelection, 0, lnbs, False) + nim.advanced.sat[x[0]] = ConfigSubsection() + nim.advanced.sat[x[0]].voltage = ConfigSelection(choices={"polarization": _("Polarization"), "13V": _("13 V"), "18V": _("18 V")}, default = "polarization") + nim.advanced.sat[x[0]].tonemode = ConfigSelection(choices={"band": _("Band"), "on": _("On"), "off": _("Off")}, default = "band") + nim.advanced.sat[x[0]].usals = ConfigYesNo(default=True) + nim.advanced.sat[x[0]].rotorposition = ConfigInteger(default=1, limits=(1, 255)) + nim.advanced.sat[x[0]].lnb = ConfigSelection(choices = lnbs) csw = [("none", _("None")), ("AA", _("AA")), ("AB", _("AB")), ("BA", _("BA")), ("BB", _("BB"))] for y in range(0, 16): csw.append((str(0xF0|y), "Input " + str(y+1))) - ucsw = [("none", _("None"))] + ucsw = [("0", _("None"))] for y in range(1, 17): - ucsw.append("Input " + str(y)) + ucsw.append((str(y), "Input " + str(y))) - nim.advanced.lnb = [0] + nim.advanced.lnb = ConfigSubList() + nim.advanced.lnb.append(ConfigDummy()) for x in range(1, 33): nim.advanced.lnb.append(ConfigSubsection()) - nim.advanced.lnb[x].lof = configElement(cname + "advanced.lnb" + str(x) + ".lof", configSelection, 0, (("universal_lnb", _("Universal LNB")), ("c_band", _("C-Band")), ("user_defined", _("User defined"))), False) - nim.advanced.lnb[x].lofl = configElement(cname + "advanced.lnb" + str(x) + ".lofl", configSequence, [9750], configsequencearg.get("INTEGER", (0, 99999)), False) - nim.advanced.lnb[x].lofh = configElement(cname + "advanced.lnb" + str(x) + ".lofh", configSequence, [10600], configsequencearg.get("INTEGER", (0, 99999)), False) - nim.advanced.lnb[x].threshold = configElement(cname + "advanced.lnb" + str(x) + ".threshold", configSequence, [11700], configsequencearg.get("INTEGER", (0, 99999)), False) - nim.advanced.lnb[x].output_12v = configElement(cname + "advanced.lnb" + str(x) + ".output_12v", configSelection, 0, (("0V", _("0 V")), ("12V", _("12 V"))), False) - nim.advanced.lnb[x].increased_voltage = configElement(cname + "advanced.lnb" + str(x) + ".increased_voltage", configSelection, 0, (("no", _("No")), ("yes", _("Yes"))), False) - nim.advanced.lnb[x].toneburst = configElement(cname + "advanced.lnb" + str(x) + ".toneburst", configSelection, 0, (("none", _("None")), ("A", _("A")), ("B", _("B"))), False) - nim.advanced.lnb[x].diseqcMode = configElement(cname + "advanced.lnb" + str(x) + ".diseqcMode", configSelection, 0, (("none", _("None")), ("1_0", _("1.0")), ("1_1", _("1.1")), ("1_2", _("1.2"))), False) - nim.advanced.lnb[x].commitedDiseqcCommand = configElement(cname + "advanced.lnb" + str(x) + ".commitedDiseqcCommand", configSelection, 0, csw, False) - nim.advanced.lnb[x].fastDiseqc = configElement(cname + "advanced.lnb" + str(x) + ".fastDiseqc", configSelection, 0, (("no", _("No")), ("yes", _("Yes"))), False) - nim.advanced.lnb[x].sequenceRepeat = configElement(cname + "advanced.lnb" + str(x) + ".sequenceRepeat", configSelection, 0, (("no", _("No")), ("yes", _("Yes"))), False) - nim.advanced.lnb[x].commandOrder1_0 = configElement(cname + "advanced.lnb" + str(x) + ".commandOrder1_0", configSelection, 0, ("committed, toneburst", "toneburst, committed"), False) - nim.advanced.lnb[x].commandOrder = configElement(cname + "advanced.lnb" + str(x) + ".commandOrder", configSelection, 0, ("committed, toneburst", "toneburst, committed", "committed, uncommitted, toneburst", "toneburst, committed, uncommitted", "uncommitted, committed, toneburst", "toneburst, uncommitted, commmitted"), False) - nim.advanced.lnb[x].uncommittedDiseqcCommand = configElement(cname + "advanced.lnb" + str(x) + ".uncommittedDiseqcCommand", configSelection, 0, ucsw, False) - nim.advanced.lnb[x].diseqcRepeats = configElement(cname + "advanced.lnb" + str(x) + ".diseqcRepeats", configSelection, 0, (("none", _("None")), ("one", _("One")), ("two", _("Two")), ("three", _("Three"))), False) - nim.advanced.lnb[x].longitude = configElement(cname + "advanced.lnb" + str(x) + ".longitude", configSequence, [5,100], configsequencearg.get("FLOAT", [(0,359),(0,999)]), False) - nim.advanced.lnb[x].longitudeOrientation = configElement(cname + "advanced.lnb" + str(x) + ".longitudeOrientation", configSelection, 0, (("east", _("East")), ("west", _("West"))), False) - nim.advanced.lnb[x].latitude = configElement(cname + "advanced.lnb" + str(x) + ".latitude", configSequence, [50,767], configsequencearg.get("FLOAT", [(0,359),(0,999)]), False) - nim.advanced.lnb[x].latitudeOrientation = configElement(cname + "advanced.lnb" + str(x) + ".latitudeOrientation", configSelection, 0, (("north", _("North")), ("south", _("South"))), False) - nim.advanced.lnb[x].powerMeasurement = configElement(cname + "advanced.lnb" + str(x) + ".powerMeasurement", configSelection, 0, (("yes", _("Yes")), ("no", _("No"))), False) - nim.advanced.lnb[x].powerThreshold = configElement(cname + "advanced.lnb" + str(x) + ".powerThreshold", configSequence, [50], configsequencearg.get("INTEGER", (0, 100)), False) + nim.advanced.lnb[x].lof = ConfigSelection(choices={"universal_lnb": _("Universal LNB"), "c_band": _("C-Band"), "user_defined": _("User defined")}, default="universal_lnb") + nim.advanced.lnb[x].lofl = ConfigInteger(default=9750, limits = (0, 99999)) + nim.advanced.lnb[x].lofh = ConfigInteger(default=10600, limits = (0, 99999)) + nim.advanced.lnb[x].threshold = ConfigInteger(default=11700, limits = (0, 99999)) + nim.advanced.lnb[x].output_12v = ConfigSelection(choices = [("0V", _("0 V")), ("12V", _("12 V"))], default="0V") + nim.advanced.lnb[x].increased_voltage = ConfigYesNo(default=False) + nim.advanced.lnb[x].toneburst = ConfigSelection(choices = [("none", _("None")), ("A", _("A")), ("B", _("B"))], default = "none") + nim.advanced.lnb[x].diseqcMode = ConfigSelection(choices = [("none", _("None")), ("1_0", _("1.0")), ("1_1", _("1.1")), ("1_2", _("1.2"))], default = "none") + nim.advanced.lnb[x].commitedDiseqcCommand = ConfigSelection(choices = csw) + nim.advanced.lnb[x].fastDiseqc = ConfigYesNo(default=False) + nim.advanced.lnb[x].sequenceRepeat = ConfigYesNo(default=False) + nim.advanced.lnb[x].commandOrder1_0 = ConfigSelection(choices = [("ct", "committed, toneburst"), ("tc", "toneburst, committed")], default = "ct") + nim.advanced.lnb[x].commandOrder = ConfigSelection(choices = [ + ("ct", "committed, toneburst"), + ("tc", "toneburst, committed"), + ("cut", "committed, uncommitted, toneburst"), + ("tcu", "toneburst, committed, uncommitted"), + ("uct", "uncommitted, committed, toneburst"), + ("tuc", "toneburst, uncommitted, commmitted")], + default="ct") + nim.advanced.lnb[x].uncommittedDiseqcCommand = ConfigSelection(choices = ucsw) + nim.advanced.lnb[x].diseqcRepeats = ConfigSelection(choices = [("none", _("None")), ("one", _("One")), ("two", _("Two")), ("three", _("Three"))], default = "none") + nim.advanced.lnb[x].longitude = ConfigFloat(default = [5,100], limits = [(0,359),(0,999)]) + nim.advanced.lnb[x].longitudeOrientation = ConfigSelection(choices = [("east", _("East")), ("west", _("West"))], default = "east") + nim.advanced.lnb[x].latitude = ConfigFloat(default = [50,767], limits = [(0,359),(0,999)]) + nim.advanced.lnb[x].latitudeOrientation = ConfigSelection(choices = [("north", _("North")), ("south", _("South"))], default = "north") + nim.advanced.lnb[x].powerMeasurement = ConfigYesNo(default=True) + nim.advanced.lnb[x].powerThreshold = ConfigInteger(default=50, limits=(0, 100)) + elif slot.nimType == nimmgr.nimType["DVB-C"]: - nim.cable = configElement(cname + "cable", configSelection, 0, nimmgr.cablesList, False); + nim.cable = ConfigSelection(choices = nimmgr.cablesList) elif slot.nimType == nimmgr.nimType["DVB-T"]: list = [] for x in nimmgr.terrestrialsList: list.append(x[0]) - nim.terrestrial = configElement(cname + "terrestrial", configSelection, 0, list, False); - nim.terrestrial_5V = configElement(cname + "terrestrial_5V", configSelection, 1, (("on", _("On")), ("off", _("Off"))), True); + nim.terrestrial = ConfigSelection(choices = list) + nim.terrestrial_5V = ConfigOnOff() else: print "pls add support for this frontend type!" +# assert False nimmgr.sec = SecConfigure(nimmgr) diff --git a/lib/python/Components/RFmod.py b/lib/python/Components/RFmod.py index 881ac28d..ff87a729 100644 --- a/lib/python/Components/RFmod.py +++ b/lib/python/Components/RFmod.py @@ -25,12 +25,12 @@ class RFmod: def InitRFmod(): config.rfmod = ConfigSubsection(); - config.rfmod.enable = configElement("config.rfmod.enable", configSelection, 1, (("enable", _("Enable")), ("disable", _("Disable"))) ); - config.rfmod.test = configElement("config.rfmod.test", configSelection, 0, (("disable", _("Disable")), ("enable", _("Enable"))) ); - config.rfmod.sound = configElement("config.rfmod.sound", configSelection, 0, (("enable", _("Enable")), ("disable", _("Disable"))) ); - config.rfmod.soundcarrier = configElement("config.rfmod.soundcarrier", configSelection, 1, ("4.5 MHz", "5.5 MHz", "6.0 MHz", "6.5 MHz") ); - config.rfmod.channel = configElement("config.rfmod.channel", configSelection, 36 - RFMOD_CHANNEL_MIN, tuple(["%d" % x for x in range(RFMOD_CHANNEL_MIN, RFMOD_CHANNEL_MAX)])) - config.rfmod.finetune = configElement("config.rfmod.finetune", configSlider, 5, (1, 10)); + config.rfmod.enable = ConfigOnOff(default=False) + config.rfmod.test = ConfigOnOff(default=False) + config.rfmod.sound = ConfigOnOff(default=True) + config.rfmod.soundcarrier = ConfigSelection(choices=[("4500","4.5 MHz"), ("5500", "5.5 MHz"), ("6000", "6.0 MHz"), ("6500", "6.5 MHz")], default="5500") + config.rfmod.channel = ConfigSelection(default = "36", choices = ["%d" % x for x in range(RFMOD_CHANNEL_MIN, RFMOD_CHANNEL_MAX)]) + config.rfmod.finetune = ConfigSlider(default=5, limits=(1, 10)) iRFmod = RFmod() @@ -41,9 +41,9 @@ def InitRFmod(): def setSoundFunction(configElement): iRFmod.setSoundFunction(configElement.value); def setSoundCarrier(configElement): - iRFmod.setSoundCarrier(configElement.value); + iRFmod.setSoundCarrier(int(configElement.value)); def setChannel(configElement): - iRFmod.setChannel(configElement.value + RFMOD_CHANNEL_MIN); + iRFmod.setChannel(int(configElement.value)); def setFinetune(configElement): iRFmod.setFinetune(configElement.value - 5); diff --git a/lib/python/Components/RecordingConfig.py b/lib/python/Components/RecordingConfig.py index ea037a61..03719860 100644 --- a/lib/python/Components/RecordingConfig.py +++ b/lib/python/Components/RecordingConfig.py @@ -1,10 +1,9 @@ -from config import * +from config import ConfigInteger, ConfigYesNo, ConfigSubsection, config import os -from enigma import * def InitRecordingConfig(): config.recording = ConfigSubsection(); # actually this is "recordings always have priority". "Yes" does mean: don't ask. The RecordTimer will ask when value is 0. - config.recording.asktozap = configElement("config.recording.asktozap", configSelection, 1, (("no", _("no")), ("yes", _("yes"))) ) - config.recording.margin_before = configElement("config.recording.margin_before", configSequence, [0], configsequencearg.get("INTEGER", (0, 30))) - config.recording.margin_after = configElement("config.recording.margin_after", configSequence, [0], configsequencearg.get("INTEGER", (0, 30))) + config.recording.asktozap = ConfigYesNo(default=True) + config.recording.margin_before = ConfigInteger(default=0, limits=(0,30)) + config.recording.margin_after = ConfigInteger(default=0, limits=(0,30)) diff --git a/lib/python/Components/Renderer/PositionGauge.py b/lib/python/Components/Renderer/PositionGauge.py index 4b49501f..5fa8c356 100644 --- a/lib/python/Components/Renderer/PositionGauge.py +++ b/lib/python/Components/Renderer/PositionGauge.py @@ -5,7 +5,9 @@ class PositionGauge(Renderer): def __init__(self): Renderer.__init__(self) self.__position = 0 + self.__seek_position = 0 self.__length = 0 + self.__seek_enable = 0 self.__cutlist = [ ] GUI_WIDGET = ePositionGauge @@ -53,3 +55,23 @@ class PositionGauge(Renderer): self.instance.setInOutList(cutlist) cutlist = property(getCutlist, setCutlist) + + def getSeekEnable(self): + return self.__seek_enable + + def setSeekEnable(self, val): + self.__seek_enable = val + if self.instance is not None: + self.instance.enableSeekPointer(val) + + seek_pointer_enabled = property(getSeekEnable, setSeekEnable) + + def getSeekPosition(self): + return self.__seek_position + + def setSeekPosition(self, pos): + self.__seek_position = pos + if self.instance is not None: + self.instance.setSeekPosition(pos) + + seek_pointer_position = property(getSeekPosition, setSeekPosition) diff --git a/lib/python/Components/ServicePosition.py b/lib/python/Components/ServicePosition.py index f5771e3a..d34d81fb 100644 --- a/lib/python/Components/ServicePosition.py +++ b/lib/python/Components/ServicePosition.py @@ -3,13 +3,14 @@ from Components.GUIComponent import GUIComponent from enigma import eTimer, iPlayableService, iSeekableServicePtr, ePositionGauge import time -class ServicePosition(PerServiceDisplay): +class ServicePosition(PerServiceDisplay, object): TYPE_LENGTH = 0, TYPE_POSITION = 1, TYPE_REMAINING = 2, TYPE_RELATIVE = 3 def __init__(self, navcore, type): + object.__init__(self) self.updateTimer = eTimer() self.updateTimer.timeout.get().append(self.update) PerServiceDisplay.__init__(self, navcore, @@ -95,6 +96,7 @@ class ServicePositionGauge(PerServiceBase, GUIComponent): iPlayableService.evCuesheetChanged: self.newCuesheet }) self.instance = None + self.__seek_position = 0 def newService(self): if self.get() is None: @@ -107,7 +109,7 @@ class ServicePositionGauge(PerServiceBase, GUIComponent): service = self.navcore.getCurrentService() seek = service and service.seek() if seek is None: - return None + return (0, 0) len = seek.getLength() pos = seek.getPlayPosition() @@ -132,6 +134,7 @@ class ServicePositionGauge(PerServiceBase, GUIComponent): def postWidgetCreate(self, instance): self.newService() + self.setSeekPosition(self.__seek_position) def newCuesheet(self): service = self.navcore.getCurrentService() @@ -139,3 +142,25 @@ class ServicePositionGauge(PerServiceBase, GUIComponent): cutlist = (cue and cue.getCutList()) or [ ] if self.instance is not None: self.instance.setInOutList(cutlist) + + def getSeekEnable(self): + return self.__seek_enable + + def setSeekEnable(self, val): + self.__seek_enable = val + if self.instance is not None: + self.instance.enableSeekPointer(val) + + seek_pointer_enabled = property(getSeekEnable, setSeekEnable) + + def getSeekPosition(self): + return self.__seek_position + + def setSeekPosition(self, pos): + print "set seek position:", pos + self.__seek_position = pos + if self.instance is not None: + print "set instance." + self.instance.setSeekPosition(pos) + + seek_pointer_position = property(getSeekPosition, setSeekPosition) diff --git a/lib/python/Components/SetupDevices.py b/lib/python/Components/SetupDevices.py index 9036fa63..bdbdcf03 100644 --- a/lib/python/Components/SetupDevices.py +++ b/lib/python/Components/SetupDevices.py @@ -1,10 +1,4 @@ -#import os -from config import config #global config instance -from config import configElement -from config import ConfigSubsection -from config import configSlider -from config import configSelection -from config import configText +from config import config, ConfigSlider, ConfigSelection, ConfigSubsection, ConfigOnOff, ConfigText from Components.Timezones import timezones from Components.Language import language @@ -14,34 +8,26 @@ def InitSetupDevices(): timezones.activateTimezone(configElement.value) config.timezone = ConfigSubsection(); - config.timezone.val = configElement("config.timezone.val", configSelection, timezones.getDefaultTimezone(), timezones.getTimezoneList()); + config.timezone.val = ConfigSelection(default = timezones.getDefaultTimezone(), choices = timezones.getTimezoneList()) config.timezone.val.addNotifier(timezoneNotifier) - config.rc = ConfigSubsection(); - config.rc.map = configElement("config.rc.map", configSelection, 0, (_("Default"), _("Classic")) ); - config.keyboard = ConfigSubsection(); - config.keyboard.keymap = configElement("config.keyboard.keymap", configSelection, 1, (_("English"), _("German")) ); + config.keyboard.keymap = ConfigSelection(choices = [("en", _("English")), ("de",_("German"))]) - config.osd = ConfigSubsection(); - config.osd.alpha = configElement("config.osd.alpha", configSlider, 0, (1, 10)); - config.osd.bright = configElement("config.osd.bright", configSlider, 5, (1, 10)); - config.osd.contrast = configElement("config.osd.contrast", configSlider, 5, (1, 10)); - def languageNotifier(configElement): language.activateLanguage(configElement.value) - config.osd.language = configElement("config.osd.language", configText, "en_EN", 0); + config.osd = ConfigSubsection() + config.osd.language = ConfigText(default = "en_EN"); config.osd.language.addNotifier(languageNotifier) config.parental = ConfigSubsection(); - config.parental.lock = configElement("config.parental.lock", configSelection, 1, (_("Enable"), _("Disable")) ); - config.parental.setuplock = configElement("config.parental.setuplock", configSelection, 1, (_("Enable"), _("Disable")) ); + config.parental.lock = ConfigOnOff(default = False) + config.parental.setuplock = ConfigOnOff(default = False) config.expert = ConfigSubsection(); - config.expert.splitsize = configElement("config.expert.splitsize", configSelection, 1, ("0.5Gbyte", "1.0 GByte", "1.5 GByte", "2.0 GByte") ); - config.expert.satpos = configElement("config.expert.satpos", configSelection, 1, (_("Enable"), _("Disable")) ); - config.expert.fastzap = configElement("config.expert.fastzap", configSelection, 0, (_("Enable"), _("Disable")) ); - config.expert.skipconfirm = configElement("config.expert.skipconfirm", configSelection, 1, (_("Enable"), _("Disable")) ); - config.expert.hideerrors = configElement("config.expert.hideerrors", configSelection, 1, (_("Enable"), _("Disable")) ); - config.expert.autoinfo = configElement("config.expert.autoinfo", configSelection, 1, (_("Enable"), _("Disable")) ); + config.expert.satpos = ConfigOnOff(default = True) + config.expert.fastzap = ConfigOnOff(default = True) + config.expert.skipconfirm = ConfigOnOff(default = False) + config.expert.hideerrors = ConfigOnOff(default = False) + config.expert.autoinfo = ConfigOnOff(default = True) diff --git a/lib/python/Components/Sources/Makefile.am b/lib/python/Components/Sources/Makefile.am index 923c6512..a1609840 100644 --- a/lib/python/Components/Sources/Makefile.am +++ b/lib/python/Components/Sources/Makefile.am @@ -2,4 +2,4 @@ installdir = $(LIBDIR)/enigma2/python/Components/Sources install_PYTHON = \ __init__.py Clock.py EventInfo.py Source.py MenuList.py CurrentService.py \ - FrontendStatus.py Boolean.py + FrontendStatus.py Boolean.py Config.py ServiceList.py diff --git a/lib/python/Components/TimerSanityCheck.py b/lib/python/Components/TimerSanityCheck.py index a6af1412..35e78de0 100644 --- a/lib/python/Components/TimerSanityCheck.py +++ b/lib/python/Components/TimerSanityCheck.py @@ -1,4 +1,3 @@ -from Components.config import config from Components.NimManager import nimmanager from time import localtime diff --git a/lib/python/Components/Timezones.py b/lib/python/Components/Timezones.py index 15837450..704b765e 100644 --- a/lib/python/Components/Timezones.py +++ b/lib/python/Components/Timezones.py @@ -52,6 +52,6 @@ class Timezones: def getDefaultTimezone(self): # TODO return something more useful - depending on country-settings? - return 27 + return "(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Vienna" timezones = Timezones() diff --git a/lib/python/Components/UsageConfig.py b/lib/python/Components/UsageConfig.py index e10a7491..36fc4178 100644 --- a/lib/python/Components/UsageConfig.py +++ b/lib/python/Components/UsageConfig.py @@ -1,10 +1,8 @@ -from config import * -import os -from enigma import * +from config import ConfigSubsection, ConfigYesNo, config def InitUsageConfig(): config.usage = ConfigSubsection(); - config.usage.showdish = configElement("config.usage.showdish", configSelection, 1, (("yes", _("yes")), ("no", _("no"))) ) - config.usage.multibouquet = configElement("config.usage.multibouquet", configSelection, 1, (("yes", _("yes")), ("no", _("no"))) ) - config.usage.quickzap_bouquet_change = configElement("config.usage.quickzap_bouquet_change", configSelection, 1, (("yes", _("yes")), ("no", _("no"))) ) - config.usage.e1like_radio_mode = configElement("config.usage.e1like_radio_mode", configSelection, 1, (("yes", _("yes")), ("no", _("no"))) ) + config.usage.showdish = ConfigYesNo(default = False) + config.usage.multibouquet = ConfigYesNo(default = False) + config.usage.quickzap_bouquet_change = ConfigYesNo(default = False) + config.usage.e1like_radio_mode = ConfigYesNo(default = False) diff --git a/lib/python/Components/config.py b/lib/python/Components/config.py index e140295d..b5a0bbbd 100644 --- a/lib/python/Components/config.py +++ b/lib/python/Components/config.py @@ -1,624 +1,840 @@ -from time import * +import time from Tools.NumericalTextInput import NumericalTextInput -from Tools.Directories import * - -class configFile: +from Tools.Directories import resolveFilename, SCOPE_CONFIG + + +# ConfigElement, the base class of all ConfigElements. + +# it stores: +# value the current value, usefully encoded. +# usually a property which retrieves _value, +# and maybe does some reformatting +# _value the value as it's going to be saved in the configfile, +# though still in non-string form. +# this is the object which is actually worked on. +# default the initial value. If _value is equal to default, +# it will not be stored in the config file +# saved_value is a text representation of _value, stored in the config file +# +# and has (at least) the following methods: +# save() stores _value into saved_value, +# (or stores 'None' if it should not be stored) +# load() loads _value from saved_value, or loads +# the default if saved_value is 'None' (default) +# or invalid. +# +class ConfigElement(object): def __init__(self): - self.changed = 0 - self.configElements = { } - try: - self.file = open(resolveFilename(SCOPE_CONFIG, "config")) - except IOError: - print "cannot open config file" - return - - while 1: - line = self.file.readline() - if line == "": - break - - if line.startswith("#"): #skip comments - continue - - self.addElement(line) - self.file.close() - - def addElement(self, line): - x = line.find("=") - if x > -1: - self.configElements[line[:x]] = line[x + 1:-1] - - def getKey(self, key): - return self.configElements[key] - - def setKey(self, key, value, isDefaultKey=False): - self.changed = 1 - if isDefaultKey and self.configElements.has_key(key): - del self.configElements[key] - else: - self.configElements[key] = value + object.__init__(self) + self.saved_value = None + self.save_disabled = False + self.notifiers = [] + self.enabled = True - def getResolvedKey(self, key): - str = self.configElements[key] - if len(str): - pos = str.find('*') - if pos != -1: - str = str[pos+1:] - pos = str.find('*') - if pos != -1: - return str[:pos] - return str - return None + # you need to override this to do input validation + def setValue(self, value): + self._value = value + self.changed() - def save(self): - if self.changed == 0: #no changes, so no write to disk needed - return - - fileHandle = open(resolveFilename(SCOPE_CONFIG, "config"), "w") - - keys = self.configElements.keys() - keys.sort() - for x in keys: - wstr = x + "=" + self.configElements[x] + "\n" + def getValue(self): + return self._value + + value = property(getValue, setValue) - fileHandle.write(wstr) + # you need to override this if self.value is not a string + def fromstring(self, value): + return value - fileHandle.close() - -def currentConfigSelectionElement(element): - return element.vals[element.value][0] - -def getConfigSelectionElement(element, value): - count = 0 - for x in element.vals: - if x[0] == value: - return count - count += 1 - return -1 - -class configSelection: - def __init__(self, parent): - self.parent = parent - - def checkValues(self): - if self.parent.value < 0: - self.parent.value = len(self.parent.vals) - 1 - elif(self.parent.value > (len(self.parent.vals) - 1)): - self.parent.value = 0 + # you can overide this for fancy default handling + def load(self): + if self.saved_value is None: + self.value = self.default + else: + self.value = self.fromstring(self.saved_value) - def cancel(self): - self.parent.reload() + def tostring(self, value): + return str(value) + # you need to override this if str(self.value) doesn't work def save(self): - self.parent.save() + if self.save_disabled or self.value == self.default: + self.saved_value = None + else: + self.saved_value = self.tostring(self.value) - def handleKey(self, key): - if key == config.key["prevElement"]: - self.parent.value = self.parent.value - 1 - if key == config.key["nextElement"]: - self.parent.value = self.parent.value + 1 - - self.checkValues() + def cancel(self): + self.load() - self.parent.change() + def changed(self): + for x in self.notifiers: + x(self) + + def addNotifier(self, notifier): + assert callable(notifier), "notifiers must be callable" + self.notifiers.append(notifier) - def __call__(self, selected): #needed by configlist - self.checkValues() + def disableSave(self): + self.save_disabled = True - returnValue = _(self.parent.vals[self.parent.value]) - if not isinstance(returnValue, str): - returnValue = returnValue[1] + def __call__(self, selected): + return self.getMulti(selected) - # FIXME: it's not really nice to translate this here. - # however, configSelections are persistent. + def helpWindow(self): + return None + +KEY_LEFT = 0 +KEY_RIGHT = 1 +KEY_OK = 2 +KEY_DELETE = 3 +KEY_TIMEOUT = 4 +KEY_NUMBERS = range(12, 12+10) +KEY_0 = 12 +KEY_9 = 12+9 + +def getKeyNumber(key): + assert key in KEY_NUMBERS + return key - KEY_0 + +# +# ConfigSelection is a "one of.."-type. +# it has the "choices", usually a list, which contains +# (id, desc)-tuples (or just only the ids, in case the id +# will be used as description) +# +# all ids MUST be plain strings. +# +class ConfigSelection(ConfigElement): + def __init__(self, choices, default = None): + ConfigElement.__init__(self) + self.choices = [] + self.description = {} - # WORKAROUND: don't translate "" - if returnValue: - returnValue = _(returnValue) + if isinstance(choices, list): + for x in choices: + if isinstance(x, tuple): + self.choices.append(x[0]) + self.description[x[0]] = x[1] + else: + self.choices.append(x) + self.description[x] = x + elif isinstance(choices, dict): + for (key, val) in choices.items(): + self.choices.append(key) + self.description[key] = val + else: + assert False, "ConfigSelection choices must be dict or list!" - return ("text", returnValue) + assert len(self.choices), "you can't have an empty configselection" + + if default is None: + default = self.choices[0] + + assert default in self.choices, "default must be in choice list, but " + repr(default) + " is not!" + for x in self.choices: + assert isinstance(x, str), "ConfigSelection choices must be strings" -class configDateTime: - def __init__(self, parent): - self.parent = parent + self.value = self.default = default + + def setValue(self, value): + if value in self.choices: + self._value = value + else: + self._value = self.default - def checkValues(self): - pass -# if self.parent.value < 0: - #self.parent.value = 0 + self.changed() - #if(self.parent.value >= (len(self.parent.vals) - 1)): - #self.parent.value = len(self.parent.vals) - 1 + def tostring(self, val): + return (val, ','.join(self.choices)) - def cancel(self): - self.parent.reload() + def getValue(self): + return self._value - def save(self): - self.parent.save() + value = property(getValue, setValue) + + def getIndex(self): + return self.choices.index(self.value) + + index = property(getIndex) + # GUI def handleKey(self, key): - if key == config.key["prevElement"]: - self.parent.value = self.parent.value - self.parent.vals[1] - if key == config.key["nextElement"]: - self.parent.value = self.parent.value + self.parent.vals[1] - - self.checkValues() + nchoices = len(self.choices) + i = self.choices.index(self.value) + if key == KEY_LEFT: + self.value = self.choices[(i + nchoices - 1) % nchoices] + elif key == KEY_RIGHT: + self.value = self.choices[(i + 1) % nchoices] + elif key == KEY_TIMEOUT: + self.timeout() + return - self.parent.change() + def getMulti(self, selected): + return ("text", self.description[self.value]) - def __call__(self, selected): #needed by configlist - self.checkValues() - return ("text", strftime(self.parent.vals[0], localtime(self.parent.value))) - -class configSatlist: - def __init__(self, parent): - self.parent = parent + # HTML + def getHTML(self, id): + res = "" + for v in self.choices: + if self.value == v: + checked = 'checked="checked" ' + else: + checked = '' + res += '<input type="radio" name="' + id + '" ' + checked + 'value="' + v + '">' + self.description[v] + "</input></br>\n" + return res; + + def unsafeAssign(self, value): + # setValue does check if value is in choices. This is safe enough. + self.value = value + +# a binary decision. +# +# several customized versions exist for different +# descriptions. +# +class ConfigBoolean(ConfigElement): + def __init__(self, default = False, descriptions = {False: "false", True: "true"}): + ConfigElement.__init__(self) + self.descriptions = descriptions + self.value = self.default = default + def handleKey(self, key): + if key in [KEY_LEFT, KEY_RIGHT]: + self.value = not self.value - def checkValues(self): - if self.parent.value < 0: - self.parent.value = 0 + def getMulti(self, selected): + return ("text", _(self.descriptions[self.value])) - if(self.parent.value >= (len(self.parent.vals) - 1)): - self.parent.value = len(self.parent.vals) - 1 - - def cancel(self): - self.parent.reload() + def tostring(self, value): + if not value: + return "false" + else: + return "true" - def save(self): - self.parent.save() + def fromstring(self, val): + if val == "true": + return True + else: + return False - def handleKey(self, key): - if key == config.key["prevElement"]: - self.parent.value = self.parent.value - 1 - if key == config.key["nextElement"]: - self.parent.value = self.parent.value + 1 - - self.checkValues() + def getHTML(self, id): + if self.value: + checked = ' checked="checked"' + else: + checked = '' + return '<input type="checkbox" name="' + id + '" value="1" ' + checked + " />" + + # this is FLAWED. and must be fixed. + def unsafeAssign(self, value): + if value == "1": + self.value = True + else: + self.value = False - self.parent.change() +class ConfigYesNo(ConfigBoolean): + def __init__(self, default = False): + ConfigBoolean.__init__(self, default = default, descriptions = {False: _("no"), True: _("yes")}) - def __call__(self, selected): #needed by configlist - self.checkValues() - #fixme - return ("text", str(self.parent.vals[self.parent.value][0])) - -class configSequenceArg: - def get(self, type, args = ()): - # configsequencearg.get ("IP") - if (type == "IP"): - return (("."), [(0,255),(0,255),(0,255),(0,255)], "") - # configsequencearg.get ("MAC") - if (type == "POSITION"): - return ((","), [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], "") - if (type == "MAC"): - return ((":"), [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], "") - # configsequencearg.get ("CLOCK") - if (type == "CLOCK"): - return ((":"), [(0,23),(0,59)], "") - # configsequencearg.get("INTEGER", (min, max)) => x with min <= x <= max - if (type == "INTEGER"): - return ((":"), [args], "") - # configsequencearg.get("PINCODE", (number, "*")) => pin with number = length of pincode and "*" as numbers shown as stars - # configsequencearg.get("PINCODE", (number, "")) => pin with number = length of pincode and numbers shown - if (type == "PINCODE"): - return ((":"), [(0, (10**args[0])-1)], args[1]) - # configsequencearg.get("FLOAT", [(min,max),(min1,max1)]) => x.y with min <= x <= max and min1 <= y <= max1 - if (type == "FLOAT"): - return (("."), args, "") - - def getFloat(self, element): - return float(("%d.%0" + str(len(str(element.vals[1][1][1]))) + "d") % (element.value[0], element.value[1])) +class ConfigOnOff(ConfigBoolean): + def __init__(self, default = False): + ConfigBoolean.__init__(self, default = default, descriptions = {False: _("off"), True: _("on")}) + +class ConfigEnableDisable(ConfigBoolean): + def __init__(self, default = False): + ConfigBoolean.__init__(self, default = default, descriptions = {False: _("disable"), True: _("enable")}) + +class ConfigDateTime(ConfigElement): + def __init__(self, default, formatstring, increment = 86400): + ConfigElement.__init__(self) + self.increment = increment + self.formatstring = formatstring + self.value = self.default = int(default) -configsequencearg = configSequenceArg() + def handleKey(self, key): + if key == KEY_LEFT: + self.value = self.value - self.increment + if key == KEY_RIGHT: + self.value = self.value + self.increment + + def getMulti(self, selected): + return ("text", time.strftime(self.formatstring, time.localtime(self.value))) + + def fromstring(self, val): + return int(val) + +# *THE* mighty config element class +# +# allows you to store/edit a sequence of values. +# can be used for IP-addresses, dates, plain integers, ... +# several helper exist to ease this up a bit. +# +class ConfigSequence(ConfigElement): + def __init__(self, seperator, limits, censor_char = "", default = None): + ConfigElement.__init__(self) + assert isinstance(limits, list) and len(limits[0]) == 2, "limits must be [(min, max),...]-tuple-list" + assert censor_char == "" or len(censor_char) == 1, "censor char must be a single char (or \"\")" + #assert isinstance(default, list), "default must be a list" + #assert isinstance(default[0], int), "list must contain numbers" + #assert len(default) == len(limits), "length must match" + + self.marked_pos = 0 + self.seperator = seperator + self.limits = limits + self.censor_char = censor_char -class configSequence: - def __init__(self, parent): - self.parent = parent - self.markedPos = 0 - self.seperator = self.parent.vals[0] - self.valueBounds = self.parent.vals[1] - self.censorChar = self.parent.vals[2] + self.value = self.default = default - def checkValues(self): - maxPos = 0 + def validate(self): + max_pos = 0 num = 0 - for i in self.parent.value: - maxPos += len(str(self.valueBounds[num][1])) - while (self.valueBounds[num][0] > self.parent.value[num]): - self.parent.value[num] += 1 - - while (self.valueBounds[num][1] < self.parent.value[num]): - self.parent.value[num] -= 1 - -# if (self.valueBounds[num][0] <= i <= self.valueBounds[num][1]): - #pass - #else: - #self.parent.value[num] = self.valueBounds[num][0] + for i in self._value: + max_pos += len(str(self.limits[num][1])) + + while self._value[num] < self.limits[num][0]: + self.value[num] += 1 + + while self._value[num] > self.limits[num][1]: + self._value[num] -= 1 + num += 1 - - if self.markedPos >= maxPos: - self.markedPos = maxPos - 1 - if self.markedPos < 0: - self.markedPos = 0 + + if self.marked_pos >= max_pos: + self.marked_pos = max_pos - 1 + + if self.marked_pos < 0: + self.marked_pos = 0 + + def validatePos(self): + if self.marked_pos < 0: + self.marked_pos = 0 - def cancel(self): - self.parent.reload() + total_len = sum([len(str(x[1])) for x in self.limits]) - def save(self): - self.parent.save() + if self.marked_pos >= total_len: + self.marked_pos = total_len - 1 def handleKey(self, key): - #this will no change anything on the value itself - #so we can handle it here in gui element - if key == config.key["prevElement"]: - self.markedPos -= 1 - if key == config.key["nextElement"]: - self.markedPos += 1 + if key == KEY_LEFT: + self.marked_pos -= 1 + self.validatePos() + + if key == KEY_RIGHT: + self.marked_pos += 1 + self.validatePos() - if key >= config.key["0"] and key <= config.key["9"]: - self.blockLen = [] - for x in self.valueBounds: - self.blockLen.append(len(str(x[1]))) - + if key in KEY_NUMBERS: + print "is number" + block_len = [] + for x in self.limits: + block_len.append(len(str(x[1]))) + + total_len = sum(block_len) + pos = 0 blocknumber = 0 - self.blockLenTotal = [0,] - for x in self.blockLen: - pos += self.blockLen[blocknumber] - self.blockLenTotal.append(pos) - if (pos - 1 >= self.markedPos): + block_len_total = [0, ] + for x in block_len: + pos += block_len[blocknumber] + block_len_total.append(pos) + if pos - 1 >= self.marked_pos: pass else: blocknumber += 1 - - number = 9 - config.key["9"] + key + + number = getKeyNumber(key) + # length of numberblock - numberLen = len(str(self.valueBounds[blocknumber][1])) + number_len = len(str(self.limits[blocknumber][1])) + # position in the block - posinblock = self.markedPos - self.blockLenTotal[blocknumber] + posinblock = self.marked_pos - block_len_total[blocknumber] - oldvalue = self.parent.value[blocknumber] - olddec = oldvalue % 10 ** (numberLen - posinblock) - (oldvalue % 10 ** (numberLen - posinblock - 1)) - newvalue = oldvalue - olddec + (10 ** (numberLen - posinblock - 1) * number) + oldvalue = self._value[blocknumber] + olddec = oldvalue % 10 ** (number_len - posinblock) - (oldvalue % 10 ** (number_len - posinblock - 1)) + newvalue = oldvalue - olddec + (10 ** (number_len - posinblock - 1) * number) - self.parent.value[blocknumber] = newvalue - self.markedPos += 1 + self._value[blocknumber] = newvalue + self.marked_pos += 1 - self.checkValues() - - #FIXME: dont call when press left/right - self.parent.change() + self.validate() + self.changed() + + print "res:", self._value - def __call__(self, selected): #needed by configlist + def getMulti(self, selected): value = "" - mPos = self.markedPos + mPos = self.marked_pos num = 0; - for i in self.parent.value: + for i in self._value: if len(value): #fixme no heading separator possible value += self.seperator if mPos >= len(value) - 1: mPos += 1 - - #diff = self.valueBounds - len(str(i)) - #if diff > 0: - ## if this helps?! - #value += " " * diff - if (self.censorChar == ""): - value += ("%0" + str(len(str(self.valueBounds[num][1]))) + "d") % i + + if self.censor_char == "": + value += ("%0" + str(len(str(self.limits[num][1]))) + "d") % i else: - value += (self.censorChar * len(str(self.valueBounds[num][1]))) + value += (self.censorChar * len(str(self.limits[num][1]))) num += 1 + # only mark cursor when we are selected # (this code is heavily ink optimized!) - if (self.parent.enabled == True): + if self.enabled: return ("mtext"[1-selected:], value, [mPos]) else: return ("text", value) -class configNothing: - def __init__(self, parent): - self.parent = parent - self.markedPos = 0 + def tostring(self, val): + return self.seperator.join([self.saveSingle(x) for x in val]) + + def saveSingle(self, v): + return str(v) - def cancel(self): - self.parent.reload() + def fromstring(self, value): + return [int(x) for x in self.saved_value.split(self.seperator)] - def save(self): - self.parent.save() - - def nextEntry(self): - self.parent.vals[1](self.parent.getConfigPath()) +class ConfigIP(ConfigSequence): + def __init__(self, default): + ConfigSequence.__init__(self, seperator = ".", limits = [(0,255),(0,255),(0,255),(0,255)], default = default) - def handleKey(self, key): - pass - - def __call__(self, selected): #needed by configlist - return ("text", "") - -class configText(NumericalTextInput): - # used as first parameter - # is the text of a fixed size or is the user able to extend the length of the text - extendableSize = 1 - fixedSize = 2 - - def __init__(self, parent): - NumericalTextInput.__init__(self, self.nextEntry) - self.parent = parent - self.markedPos = 0 - self.mode = self.parent.vals[0] - try: - self.Text = self.parent.value.decode("utf-8") - except UnicodeDecodeError: - self.Text = self.parent.value - print "utf8 kaputt!" +class ConfigMAC(ConfigSequence): + def __init__(self, default): + ConfigSequence.__init__(self, seperator = ":", limits = [(1,255),(1,255),(1,255),(1,255),(1,255),(1,255)], default = default) - def checkValues(self): - if (self.markedPos < 0): - self.markedPos = 0 - if (self.markedPos >= len(self.Text)): - self.markedPos = len(self.Text) - 1 +class ConfigPosition(ConfigSequence): + def __init__(self, default, args): + ConfigSequence.__init__(self, seperator = ",", limits = [(0,args[0]),(0,args[1]),(0,args[2]),(0,args[3])], default = default) - def cancel(self): - self.parent.reload() +class ConfigClock(ConfigSequence): + def __init__(self, default): + ConfigSequence.__init__(self, seperator = ":", limits = [(0,23),(0,59)], default = default) - def save(self): - self.parent.save() +class ConfigInteger(ConfigSequence): + def __init__(self, default, limits): + ConfigSequence.__init__(self, seperator = ":", limits = [limits], default = default) + + # you need to override this to do input validation + def setValue(self, value): + self._value = [value] + self.changed() + + def getValue(self): + return self._value[0] + + value = property(getValue, setValue) - def nextEntry(self): - self.parent.vals[1](self.parent.getConfigPath()) + def fromstring(self, value): + return int(value) - def handleKey(self, key): - #this will no change anything on the value itself - #so we can handle it here in gui element - if key == config.key["delete"]: - self.Text = self.Text[0:self.markedPos] + self.Text[self.markedPos + 1:] - self.parent.value = self.Text.encode("utf-8") - elif key == config.key["prevElement"]: - self.nextKey() - self.markedPos -= 1 - elif key == config.key["nextElement"]: - self.nextKey() - self.markedPos += 1 - if (self.mode == self.extendableSize): - if (self.markedPos >= len(self.Text)): - self.Text = self.Text.ljust(len(self.Text) + 1) - self.parent.value = self.Text.encode("utf-8") - elif key >= config.key["0"] and key <= config.key["9"]: - number = 9 - config.key["9"] + key - self.Text = self.Text[0:self.markedPos] + self.getKey(number) + self.Text[self.markedPos + 1:] - self.parent.value = self.Text.encode("utf-8") - self.checkValues() - self.parent.change() + def tostring(self, value): + return str(value) + +class ConfigPIN(ConfigSequence): + def __init__(self, default, len = 4, censor = ""): + ConfigSequence.__init__(self, seperator = ":", limits = [(0, (10**len)-1)], censor_char = censor, default = [default]) + +class ConfigFloat(ConfigSequence): + def __init__(self, default, limits): + ConfigSequence.__init__(self, seperator = ".", limits = limits, default = default) - def __call__(self, selected): #needed by configlist - return ("mtext"[1-selected:], self.parent.value, [self.markedPos]) + def getFloat(self): + return float(self.value[1] / float(self.limits[1][1] + 1) + self.value[0]) -class configValue: - def __init__(self, obj): - self.obj = obj + float = property(getFloat) + +# an editable text... +class ConfigText(ConfigElement, NumericalTextInput): + def __init__(self, default = "", fixed_size = True): + ConfigElement.__init__(self) + NumericalTextInput.__init__(self, nextFunc = self.nextFunc, handleTimeout = False) - def __str__(self): - return self.obj + self.marked_pos = 0 + self.fixed_size = fixed_size -class Config: - def __init__(self): - self.key = { "choseElement": 0, - "prevElement": 1, - "nextElement": 2, - "delete": 3, - "0": 10, - "1": 11, - "2": 12, - "3": 13, - "4": 14, - "5": 15, - "6": 16, - "7": 17, - "8": 18, - "9": 19 } + self.value = self.default = default + + def validateMarker(self): + if self.marked_pos < 0: + self.marked_pos = 0 + if self.marked_pos >= len(self.text): + self.marked_pos = len(self.text) - 1 + + #def nextEntry(self): + # self.vals[1](self.getConfigPath()) + + def handleKey(self, key): + # this will no change anything on the value itself + # so we can handle it here in gui element + if key == KEY_DELETE: + self.text = self.text[0:self.marked_pos] + self.text[self.marked_pos + 1:] + elif key == KEY_LEFT: + self.marked_pos -= 1 + elif key == KEY_RIGHT: + self.marked_pos += 1 + if not self.fixed_size: + if self.marked_pos >= len(self.text): + self.text = self.text.ljust(len(self.text) + 1) + elif key in KEY_NUMBERS: + number = self.getKey(getKeyNumber(key)) + self.text = self.text[0:self.marked_pos] + str(number) + self.text[self.marked_pos + 1:] + elif key == KEY_TIMEOUT: + self.timeout() + return + + self.validateMarker() + self.changed() + + def nextFunc(self): + self.marked_pos += 1 + self.validateMarker() + self.changed() + + def getValue(self): + return self.text.encode("utf-8") -config = Config(); + def setValue(self, val): + try: + self.text = val.decode("utf-8") + except UnicodeDecodeError: + self.text = val + print "Broken UTF8!" -configfile = configFile() + value = property(getValue, setValue) + _value = property(getValue, setValue) -class configSlider: - def __init__(self, parent): - self.parent = parent + def getMulti(self, selected): + return ("mtext"[1-selected:], self.value, [self.marked_pos]) - def cancel(self): - self.parent.reload() + def helpWindow(self): + print "helpWindow for text!" - def save(self): - self.parent.save() + from Screens.NumericalTextInputHelpDialog import NumericalTextInputHelpDialog + return (NumericalTextInputHelpDialog,self) + + def getHTML(self, id): + return '<input type="text" name="' + id + '" value="' + self.value + '" /><br>\n' + + def unsafeAssign(self, value): + self.value = str(value) + +# a slider. +class ConfigSlider(ConfigElement): + def __init__(self, default = 0, increment = 1, limits = (0, 100)): + ConfigElement.__init__(self) + self.value = self.default = default + self.min = limits[0] + self.max = limits[1] + self.increment = increment def checkValues(self): - if self.parent.value < 0: - self.parent.value = 0 + if self.value < self.min: + self.value = self.min - if self.parent.value > self.parent.vals[1]: - self.parent.value = self.parent.vals[1] + if self.value > self.max: + self.value = self.max def handleKey(self, key): - if key == config.key["prevElement"]: - self.parent.value = self.parent.value - self.parent.vals[0] - if key == config.key["nextElement"]: - self.parent.value = self.parent.value + self.parent.vals[0] - - self.checkValues() - self.parent.change() - - def __call__(self, selected): #needed by configlist + if key == KEY_LEFT: + self.value -= self.increment + elif key == KEY_RIGHT: + self.value += self.increment + else: + return + self.checkValues() - return ("slider", self.parent.value, self.parent.vals[1]) + self.changed() -class ConfigSubsection: + def getMulti(self, selected): + self.checkValues() + return ("slider", self.value, self.max) + + def fromstring(self, value): + return int(value) + +# a satlist. in fact, it's a ConfigSelection. +class ConfigSatlist(ConfigSelection): + def __init__(self, list, default = None): + if default is not None: + default = str(default) + if list == [ ]: + list = [0, "N/A"] + ConfigSelection.__init__(self, choices = [(str(orbpos), desc) for (orbpos, desc) in list], default = default) + + def getOrbitalPosition(self): + return int(self.value) + + orbital_position = property(getOrbitalPosition) + +# nothing. +class ConfigDummy(ConfigSelection): def __init__(self): - pass - -class configElement: - - def getIndexbyEntry(self, data): - cnt = 0; - tcnt = -1; #for defaultval - for x in self.vals: - if int(x[1]) == int(data): - return cnt - if int(x[1]) == int(self.defaultValue): - tcnt = cnt - cnt += 1 - if tcnt != -1: - return tcnt - return 0 #prevent bigger then array - - def datafromFile(self, control, data): - if control == configSlider: - return int(data) - elif control == configSelection: - try: - return int(data) - except: - for x in data.split(":"): - if x[0] == "*": - count = 0 - for y in self.vals: - if y[0] == x[1:-1]: - return count - count += 1 - return self.defaultValue - elif control == configDateTime: - return int(data) - elif control == configText: - return str(data) - elif control == configSequence: - list = [ ] - part = data.split(self.vals[0]) - for x in part: - list.append(int(x)) - return list - elif control == configSatlist: - return self.getIndexbyEntry(data) - else: - return "" - - def datatoFile(self, control, data): - if control == configSlider: - return str(data) - elif control == configSelection: - if len(self.vals) < data + 1: - return "0" - if isinstance(self.vals[data], str): - return str(data) - else: - confList = [] - count = 0 - for x in self.vals: - if count == data: - confList.append("*" + str(x[0] + "*")) - else: - confList.append(x[0]) - count += 1 - return ":".join(confList) - return str(data) - elif control == configDateTime: - return str(data) - elif control == configText: - return str(data.strip()) - elif control == configSequence: -# print self.vals -# print self.value - try: - value = "" - count = 0 - for i in data: - if value !="": - value += self.vals[0] - value += (("%0" + str(len(str(self.vals[1][count][1]))) + "d") % i) - count += 1 - #value = ((len(data) * ("%d" + self.vals[0]))[0:-1]) % tuple(data) - except: - value = str(data) - return value - elif control == configSatlist: - return str(self.vals[self.value][1]); - else: - return "" - - def loadData(self): - #print "load:" + self.configPath - try: - value = self.datafromFile(self.controlType, configfile.getKey(self.configPath)) - except: - value = "" - - if value == "": - #print "value not found - using default" - if self.controlType == configSatlist: - self.value = self.getIndexbyEntry(self.defaultValue) - elif self.controlType == configSequence: - self.value = self.defaultValue[:] - else: - self.value = self.defaultValue + ConfigSelection.__init__(self, choices = [""]) + +# until here, 'saved_value' always had to be a *string*. +# now, in ConfigSubsection, and only there, saved_value +# is a dict, essentially forming a tree. +# +# config.foo.bar=True +# config.foobar=False +# +# turns into: +# config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"} +# + + +class ConfigSubsectionContent(object): + pass + +# we store a backup of the loaded configuration +# data in self.stored_values, to be able to deploy +# them when a new config element will be added, +# so non-default values are instantly available + +# A list, for example: +# config.dipswitches = ConfigSubList() +# config.dipswitches.append(ConfigYesNo()) +# config.dipswitches.append(ConfigYesNo()) +# config.dipswitches.append(ConfigYesNo()) +class ConfigSubList(list, object): + def __init__(self): + object.__init__(self) + list.__init__(self) + self.stored_values = {} - self.save() #add missing value to dict - else: - #print "set val:" + str(value) - self.value = value - - #is this right? activate settings after load/cancel and use default - self.change() - - def __init__(self, configPath, control, defaultValue, vals, saveDefaults = True): - self.configPath = configPath - self.defaultValue = defaultValue - self.controlType = control - self.vals = vals - self.notifierList = [ ] - self.enabled = True - self.saveDefaults = saveDefaults - self.loadData() - - def getConfigPath(self): - return self.configPath + def save(self): + for x in self: + x.save() - def addNotifier(self, notifier): - self.notifierList.append(notifier); - notifier(self); + def load(self): + for x in self: + x.load() + + def getSavedValue(self): + res = {} + for i in range(len(self)): + sv = self[i].saved_value + if sv is not None: + res[str(i)] = sv + return res + + def setSavedValue(self, values): + self.stored_values = dict(values) + for (key, val) in self.stored_values.items(): + if int(key) < len(self): + self[int(key)].saved_value = val + + saved_value = property(getSavedValue, setSavedValue) + + def append(self, item): + list.append(self, item) + i = str(len(self)) + if i in self.stored_values: + item.saved_value = self.stored_values[i] + item.load() + +# same as ConfigSubList, just as a dictionary. +# care must be taken that the 'key' has a proper +# str() method, because it will be used in the config +# file. +class ConfigSubDict(dict, object): + def __init__(self): + object.__init__(self) + dict.__init__(self) + self.stored_values = {} - def change(self): - for notifier in self.notifierList: - notifier(self) + def save(self): + for x in self.values(): + x.save() + + def load(self): + for x in self.values(): + x.load() + + def getSavedValue(self): + res = {} + for (key, val) in self.items(): + if val.saved_value is not None: + res[str(key)] = val.saved_value + return res + + def setSavedValue(self, values): + self.stored_values = dict(values) + for (key, val) in self.items(): + if str(key) in self.stored_values: + val = self.stored_values[str(key)] + + saved_value = property(getSavedValue, setSavedValue) + + def __setitem__(self, key, item): + dict.__setitem__(self, key, item) + if str(key) in self.stored_values: + item.saved_value = self.stored_values[str(key)] + item.load() + +# Like the classes above, just with a more "native" +# syntax. +# +# some evil stuff must be done to allow instant +# loading of added elements. this is why this class +# is so complex. +# +# we need the 'content' because we overwrite +# __setattr__. +# If you don't understand this, try adding +# __setattr__ to a usual exisiting class and you will. +class ConfigSubsection(object): + def __init__(self): + object.__init__(self) + self.__dict__["content"] = ConfigSubsectionContent() + self.content.items = { } + self.content.stored_values = { } + + def __setattr__(self, name, value): + if name == "saved_value": + return self.setSavedValue(value) + self.content.items[name] = value + if name in self.content.stored_values: + #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name] + value.saved_value = self.content.stored_values[name] + value.load() + + def __getattr__(self, name): + return self.content.items[name] + + def getSavedValue(self): + res = self.content.stored_values + for (key, val) in self.content.items.items(): + if val.saved_value is not None: + res[key] = val.saved_value + return res + + def setSavedValue(self, values): + values = dict(values) + + self.content.stored_values = values + + for (key, val) in self.content.items.items(): + if key in values: + val.setSavedValue(values[key]) - def reload(self): - self.loadData() + saved_value = property(getSavedValue, setSavedValue) def save(self): - if self.controlType == configSatlist: - defaultValue = self.getIndexbyEntry(self.defaultValue) - else: - defaultValue = self.defaultValue - if self.value != defaultValue or self.saveDefaults: - configfile.setKey(self.configPath, self.datatoFile(self.controlType, self.value)) - else: - try: - oldValue = configfile.getKey(self.configPath) - except: - oldValue = None - if oldValue is not None and oldValue != defaultValue: - configfile.setKey(self.configPath, self.datatoFile(self.controlType, self.value), True) + for x in self.content.items.values(): + x.save() + + def load(self): + for x in self.content.items.values(): + x.load() + +# the root config object, which also can "pickle" (=serialize) +# down the whole config tree. +# +# we try to keep non-existing config entries, to apply them whenever +# a new config entry is added to a subsection +# also, non-existing config entries will be saved, so they won't be +# lost when a config entry disappears. +class Config(ConfigSubsection): + def __init__(self): + ConfigSubsection.__init__(self) -class configElement_nonSave(configElement): - def __init__(self, configPath, control, defaultValue, vals): - configElement.__init__(self, configPath, control, defaultValue, vals) + def pickle_this(self, prefix, topickle, result): + for (key, val) in topickle.items(): + name = prefix + "." + key + + if isinstance(val, dict): + self.pickle_this(name, val, result) + elif isinstance(val, tuple): + result.append(name + "=" + val[0]) # + " ; " + val[1]) + else: + result.append(name + "=" + val) + + def pickle(self): + result = [ ] + self.pickle_this("config", self.saved_value, result) + return '\n'.join(result) + "\n" + + def unpickle(self, lines): + tree = { } + for l in lines: + if not len(l) or l[0] == '#': + continue + + n = l.find('=') + val = l[n+1:].strip() - def save(self): - pass + names = l[:n].split('.') +# if val.find(' ') != -1: +# val = val[:val.find(' ')] -def getConfigListEntry(description, element): - b = element - item = b.controlType(b) - return ((description, item)) + base = tree + + for n in names[:-1]: + base = base.setdefault(n, {}) + + base[names[-1]] = val -def configElementBoolean(name, default, texts=(_("Disable"), _("Enable"))): - return configElement(name, configSelection, default, texts) + # we inherit from ConfigSubsection, so ... + #object.__setattr__(self, "saved_value", tree["config"]) + self.setSavedValue(tree["config"]) + def saveToFile(self, filename): + f = open(filename, "w") + f.write(self.pickle()) + f.close() + + def loadFromFile(self, filename): + f = open(filename, "r") + self.unpickle(f.readlines()) + f.close() + +config = Config() config.misc = ConfigSubsection() + +class ConfigFile: + CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "config2") + + def load(self): + try: + config.loadFromFile(self.CONFIG_FILE) + except IOError, e: + print "unable to load config (%s), assuming defaults..." % str(e) + + def save(self): + config.save() + config.saveToFile(self.CONFIG_FILE) + + def getResolvedKey(self, key): + return None # FIXME + +def NoSave(element): + element.disableSave() + return element + +configfile = ConfigFile() + +configfile.load() + +def getConfigListEntry(desc, config): + return (desc, config) + +#def _(x): +# return x +# +#config.bla = ConfigSubsection() +#config.bla.test = ConfigYesNo() +#config.nim = ConfigSubList() +#config.nim.append(ConfigSubsection()) +#config.nim[0].bla = ConfigYesNo() +#config.nim.append(ConfigSubsection()) +#config.nim[1].bla = ConfigYesNo() +#config.nim[1].blub = ConfigYesNo() +#config.arg = ConfigSubDict() +#config.arg["Hello"] = ConfigYesNo() +# +#config.arg["Hello"].handleKey(KEY_RIGHT) +#config.arg["Hello"].handleKey(KEY_RIGHT) +# +##config.saved_value +# +##configfile.save() +#config.save() +#print config.pickle() |
