forked from tamland/xbmc-keymap-editor
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
79 lines (72 loc) · 2.69 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Thomas Amland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import xml.etree.ElementTree as ET
import json
import xbmc
import xbmcaddon
tr = xbmcaddon.Addon().getLocalizedString
def rpc(method, **params):
params = json.dumps(params)
query = '{"jsonrpc": "2.0", "method": "%s", "params": %s, "id": 1}' % (method, params)
return json.loads(xbmc.executeJSONRPC(query))
def read_keymap(filename):
ret = []
with open(filename, 'r') as xml:
tree = ET.iterparse(xml)
for _, keymap in tree:
for context in keymap:
for device in context:
for mapping in device:
key1 = mapping.get('id') or mapping.tag
key2 = mapping.get('mod')
key = str(key1) + ' + ' + str(key2) if key2 != None else key1
action = mapping.text
if action:
ret.append((context.tag.lower(), action.lower(), key.lower()))
return ret
def write_keymap(keymap, filename):
contexts = list(set([c for c, a, k in keymap]))
builder = ET.TreeBuilder()
builder.start("keymap", {})
for context in contexts:
builder.start(context, {})
builder.start("keyboard", {})
for c, a, k in keymap:
if c == context:
builder.start("key", {"id":k})
builder.data(a)
builder.end("key")
builder.end("keyboard")
builder.end(context)
builder.end("keymap")
element = builder.close()
indent(element)
ET.ElementTree(element).write(filename, 'utf-8', True)
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i