コード例 #1
0
 def readTimezones(
     self,
     filename=TIMEZONE_FILE
 ):  # Read the timezones.xml file and load all time zones found.
     fileDom = fileReadXML(filename, source=MODULE_NAME)
     zones = []
     if fileDom:
         for zone in fileDom.findall("zone"):
             name = zone.get("name", "")
             if isinstance(name, six.text_type):
                 name = six.ensure_str(
                     name.encode(encoding="UTF-8", errors="ignore"))
             zonePath = zone.get("zone", "")
             if isinstance(zonePath, six.text_type):
                 zonePath = six.ensure_str(
                     zonePath.encode(encoding="UTF-8", errors="ignore"))
             if exists(pathjoin(TIMEZONE_DATA, zonePath)):
                 zones.append((zonePath, name))
             else:
                 print(
                     "[Timezones] Warning: Classic time zone '%s' (%s) is not available in '%s'!"
                     % (name, zonePath, TIMEZONE_DATA))
         self.timezones["Classic"] = zones
     if len(zones) == 0:
         self.timezones["Classic"] = [("UTC", "UTC")]
コード例 #2
0
ファイル: InputDevice.py プロジェクト: wedebe/enigma2
	def __init__(self):
		self.model = BoxInfo.getItem("model")
		self.rcName = BoxInfo.getItem("rcname")
		self.rcType = self.readRemoteControlType()
		remotes = fileReadXML(resolveFilename(SCOPE_SKINS, "remotes.xml"), source=MODULE_NAME)
		self.remotes = []
		if remotes:
			for remote in sorted(remotes.findall("remote"), key=lambda remote: (remote.tag, remote.get("displayName"))):
				model = remote.attrib.get("model")
				rcType = remote.attrib.get("rcType")
				codeName = remote.attrib.get("codeName")
				displayName = remote.attrib.get("displayName")
				if codeName and displayName:
					if config.crash.debugRemoteControls.value:
						print("[InputDevice] Adding remote control identifier for '%s'." % displayName)
					self.remotes.append((model, rcType, codeName, displayName))
		self.remotes.insert(0, ("", "", "", _("Default")))
		if BoxInfo.getItem("RemoteTypeZeroAllowed", False):
			self.remotes.insert(1, ("", "0", "", _("All supported")))
		rcChoices = []
		default = "0"
		for index, remote in enumerate(self.remotes):
			index = str(index)
			rcChoices.append((index, remote[REMOTE_DISPLAY_NAME]))
			if self.model == remote[REMOTE_MODEL] and self.rcType == remote[REMOTE_RCTYPE] and self.rcName in [x.strip() for x in remote[REMOTE_NAME].split(",")]:
				print("[InputDevice] Default remote control identified as '%s'.  (model='%s', rcName='%s', rcType='%s')" % (remote[REMOTE_DISPLAY_NAME], self.model, self.rcName, self.rcType))
				default = index
		config.inputDevices.remotesIndex = ConfigSelection(choices=rcChoices, default=default)
		self.remote = self.loadRemoteControl(BoxInfo.getItem("RCMapping"))
コード例 #3
0
 def loadXML(self):  # Load the volume configuration data.
     serviceVolumeOffsets = []
     volumeDom = fileReadXML(VOLUME_FILE, source=MODULE_NAME)
     if volumeDom:
         print("[VolumeAdjust] Loading volume offset data from '%s'." %
               VOLUME_FILE)
         for services in volumeDom.findall("services"):
             for service in services.findall("service"):
                 serviceName = service.get("name")
                 serviceReference = service.get("ref")
                 serviceVolumeOffset = int(service.get("volume", "0"))
                 if serviceName and serviceReference:
                     serviceVolumeOffsets.append([
                         serviceName, serviceReference, serviceVolumeOffset
                     ])
         for channels in volumeDom.findall(
                 "channels"
         ):  # This code is for old versions of "volume.xml".  This can be removed after a reasonable period for users to update.
             for service in channels.findall("service"):
                 serviceName = service.get("name")
                 serviceReference = service.get("ref")
                 serviceVolumeOffset = int(service.get("volume", "0"))
                 if serviceName and serviceReference:
                     serviceVolumeOffsets.append([
                         serviceName, serviceReference, serviceVolumeOffset
                     ])
     return serviceVolumeOffsets
コード例 #4
0
ファイル: InputDevice.py プロジェクト: wedebe/enigma2
	def loadRemoteControl(self, filename):
		print("[InputDevice] Loading remote control '%s'." % filename)
		rcs = fileReadXML(filename, source=MODULE_NAME)
		rcButtons = {}
		if rcs:
			rc = rcs.find("rc")
			if rc:
				logRemaps = []
				remapButtons = {}
				placeHolder = 0
				rcButtons["keyIds"] = []
				rcButtons["image"] = rc.attrib.get("image")
				if config.crash.debugRemoteControls.value:
					print("[InputDevice] Remote control image file '%s'." % rcButtons["image"])
				for button in rc.findall("button"):
					id = button.attrib.get("id", "KEY_RESERVED")
					remap = button.attrib.get("remap")
					keyId = KEYIDS.get(id)
					remapId = KEYIDS.get(remap)
					if keyId is not None and remapId is not None:
						logRemaps.append((id, remap))
						remapButtons[keyId] = remapId
						keyId = remapId
					if keyId == 0:
						placeHolder -= 1
						keyId = placeHolder
					rcButtons["keyIds"].append(keyId)
					rcButtons[keyId] = {}
					rcButtons[keyId]["id"] = id
					rcButtons[keyId]["label"] = button.attrib.get("label")
					rcButtons[keyId]["pos"] = [int(x.strip()) for x in button.attrib.get("pos", "0").split(",")]
					rcButtons[keyId]["title"] = button.attrib.get("title")
					rcButtons[keyId]["shape"] = button.attrib.get("shape")
					rcButtons[keyId]["coords"] = [int(x.strip()) for x in button.attrib.get("coords", "0").split(",")]
					if config.crash.debugRemoteControls.value:
						print("[InputDevice] Remote control button id='%s', keyId='%s', label='%s', pos='%s', title='%s', shape='%s', coords='%s'." % (id, keyId, rcButtons[keyId]["label"], rcButtons[keyId]["pos"], rcButtons[keyId]["title"], rcButtons[keyId]["shape"], rcButtons[keyId]["coords"]))
				if logRemaps:
					for remap in logRemaps:
						print("[InputDevice] Remapping '%s' to '%s'." % (remap[0], remap[1]))
					for evdev, evdevinfo in sorted(inputDevices.devices.items()):
						if evdevinfo["type"] == "remote":
							result = eRCInput.getInstance().setKeyMapping(evdevinfo["name"], remapButtons)
							resStr = {
								eRCInput.remapOk: "Remap completed okay.",
								eRCInput.remapUnsupported: "Error: Remapping not supported on device!",
								eRCInput.remapFormatErr: "Error: Remap map in incorrect format!",
								eRCInput.remapNoSuchDevice: "Error: Unknown device!",
							}.get(result, "Error: Unknown error!")
							print("[InputDevice] Remote remap evdev='%s', name='%s': %s" % (evdev, evdevinfo["name"], resStr))
		return rcButtons
コード例 #5
0
def loadKeymap(filename):
    actionMapInstance = eActionMap.getInstance()
    domKeymap = fileReadXML(filename, source=MODULE_NAME)
    if domKeymap:
        for domMap in domKeymap.findall("map"):
            context = domMap.attrib.get("context")
            if context is None:
                print(
                    "ActionMap] Error: All keymap action maps in '%s' must have a context!"
                    % filename)
            else:
                parseKeymap(filename, context, actionMapInstance, "generic",
                            domMap)
                for domDevice in domMap.findall("device"):
                    parseKeymap(filename, context, actionMapInstance,
                                domDevice.attrib.get("name"), domDevice)
コード例 #6
0
	def loadTimers(self):
		timersDom = fileReadXML(self.timersFilename, source=MODULE_NAME)
		if timersDom is None:
			if not exists(self.timersFilename):
				return
			AddPopup(_("The timer file 'pm_timers.xml' is corrupt and could not be loaded."), type=MessageBox.TYPE_ERROR, timeout=0, id="TimerLoadFailed")
			print("[PowerTimer] Error: Loading 'pm_timers.xml' failed!")
			try:
				rename(self.timersFilename, "%s_bad" % self.timersFilename)
			except (IOError, OSError) as err:
				print("[PowerTimer] Error %d: Renaming broken timer file failed!  (%s)" % (err.errno, err.strerror))
			return
		check = True
		overlapText = [_("Timer overlaps detected in pm_timers.xml!"), _("Please check all timers!")]
		for timer in timersDom.findall("timer"):
			newTimer = self.createTimer(timer)
			if (self.record(newTimer, True, dosave=False) is not None) and (check == True):
				AddPopup("\n".join(overlapText), type=MessageBox.TYPE_ERROR, timeout=0, id="TimerLoadFailed")
				check = False  # At moment it is enough when the message is displayed one time.
コード例 #7
0
    def loadXML(self):
        # load the list
        print("[Volume Adjust] load xml...")

        self.read_services = []
        self.read_volume = []

        timersDom = fileReadXML(self.filen, source=MODULE_NAME)
        if timersDom is None:
            return

        for channels in timersDom.findall("channels"):
            for service in channels.findall("service"):
                read_service_name = ensure_str(service.get("name"))
                read_service_ref = ensure_str(service.get("ref"))
                read_service_volume = ensure_str(service.get("volume"))
                self.read_services.append(read_service_ref)
                self.read_volume.append(read_service_volume)

        for i in self.read_services:
            print(i)
コード例 #8
0
    def loadXML(self):
        print("[Volume Adjust] load xml...")

        self.read_services = []
        self.read_volume = []

        timersDom = fileReadXML(self.filename, source=MODULE_NAME)
        if timersDom is None:
            return

        for channels in timersDom.findall("channels"):
            for service in channels.findall("service"):
                read_service_name = ensure_str(service.get("name"))
                read_service_ref = ensure_str(service.get("ref"))
                read_service_volume = ensure_str(service.get("volume"))
                self.read_services.append(read_service_ref)
                self.read_volume.append(read_service_volume)

        for item in self.read_services:
            if len(item):
                self.finishedChannelSelection(item)
        self["ServiceList"].l.setList(self.servicelist)
コード例 #9
0
def setupDom(setup=None, plugin=None):
    # Constants for checkItems()
    ROOT_ALLOWED = ("setup", )  # Tags allowed in top level of setupxml entry.
    ELEMENT_ALLOWED = ("item", "if"
                       )  # Tags allowed in top level of setup entry.
    IF_ALLOWED = ("item", "if", "elif", "else")  # Tags allowed inside <if />.
    AFTER_ELSE_ALLOWED = ("item", "if"
                          )  # Tags allowed after <elif /> or <else />.
    CHILDREN_ALLOWED = (
        "setup",
        "if",
    )  # Tags that may have children.
    TEXT_ALLOWED = ("item",
                    )  # Tags that may have non-whitespace text (or tail).
    KEY_ATTRIBUTES = {  # Tags that have a reference key mandatory attribute.
        "setup": "key",
        "item": "text"
    }
    MANDATORY_ATTRIBUTES = {  # Tags that have a list of mandatory attributes.
        "setup": ("key", "title"),
        "item": ("text", )
    }

    def checkItems(parentNode,
                   key,
                   allowed=ROOT_ALLOWED,
                   mandatory=MANDATORY_ATTRIBUTES,
                   reference=KEY_ATTRIBUTES):
        keyText = " in '%s'" % key if key else ""
        for element in parentNode:
            if element.tag not in allowed:
                print(
                    "[Setup] Error: Tag '%s' not permitted%s!  (Permitted: '%s')"
                    % (element.tag, keyText, ", ".join(allowed)))
                continue
            if mandatory and element.tag in mandatory:
                valid = True
                for attrib in mandatory[element.tag]:
                    if element.get(attrib) is None:
                        print(
                            "[Setup] Error: Tag '%s'%s does not contain the mandatory '%s' attribute!"
                            % (element.tag, keyText, attrib))
                        valid = False
                if not valid:
                    continue
            if element.tag not in TEXT_ALLOWED:
                if element.text and not element.text.isspace():
                    print("[Setup] Tag '%s'%s contains text '%s'." %
                          (element.tag, keyText, element.text.strip()))
                if element.tail and not element.tail.isspace():
                    print("[Setup] Tag '%s'%s has trailing text '%s'." %
                          (element.tag, keyText, element.text.strip()))
            if element.tag not in CHILDREN_ALLOWED and len(element):
                itemKey = ""
                if element.tag in reference:
                    itemKey = " (%s)" % element.get(reference[element.tag])
                print(
                    "[Setup] Tag '%s'%s%s contains children where none expected."
                    % (element.tag, itemKey, keyText))
            if element.tag in CHILDREN_ALLOWED:
                if element.tag in reference:
                    key = element.get(reference[element.tag])
                checkItems(element, key, allowed=IF_ALLOWED)
            elif element.tag == "else":
                allowed = AFTER_ELSE_ALLOWED  # Another else and elif not permitted after else.
            elif element.tag == "elif":
                pass

    setupFileDom = fromstring("<setupxml></setupxml>")
    setupFile = resolveFilename(SCOPE_PLUGINS, pathjoin(
        plugin, "setup.xml")) if plugin else resolveFilename(
            SCOPE_SKINS, "setup.xml")
    global domSetups, setupModTimes
    try:
        modTime = getmtime(setupFile)
    except (IOError, OSError) as err:
        print("[Setup] Error %d: Unable to get '%s' modified time!  (%s)" %
              (err.errno, setupFile, err.strerror))
        if setupFile in domSetups:
            del domSetups[setupFile]
        if setupFile in setupModTimes:
            del setupModTimes[setupFile]
        return setupFileDom
    cached = setupFile in domSetups and setupFile in setupModTimes and setupModTimes[
        setupFile] == modTime
    print("[Setup] XML%s setup file '%s', using element '%s'%s." %
          (" cached" if cached else "", setupFile, setup,
           " from plugin '%s'" % plugin if plugin else ""))
    if cached:
        return domSetups[setupFile]
    if setupFile in domSetups:
        del domSetups[setupFile]
    if setupFile in setupModTimes:
        del setupModTimes[setupFile]
    fileDom = fileReadXML(setupFile, source=MODULE_NAME)
    if fileDom:
        checkItems(fileDom, None)
        setupFileDom = fileDom
        domSetups[setupFile] = setupFileDom
        setupModTimes[setupFile] = modTime
        for setup in setupFileDom.findall("setup"):
            key = setup.get("key")
            if key:  # If there is no key then this element is useless and can be skipped!
                title = setup.get("title", "").encode(
                    "UTF-8", errors="ignore") if PY2 else setup.get(
                        "title", "")
                if title == "":
                    print(
                        "[Setup] Error: Setup key '%s' title is missing or blank!"
                        % key)
                    title = "** Setup error: '%s' title is missing or blank!" % key
                # print("[Setup] DEBUG: XML setup load: key='%s', title='%s'." % (key, setup.get("title", "").encode("UTF-8", errors="ignore")))
    return setupFileDom