-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathEDKeys.py
More file actions
345 lines (306 loc) · 13.8 KB
/
EDKeys.py
File metadata and controls
345 lines (306 loc) · 13.8 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
from __future__ import annotations
import json
from os import environ, listdir
import os
from os.path import getmtime, isfile, join
from time import sleep
from typing import Any, final
from xml.etree.ElementTree import parse
import win32gui
import xmltodict
from Screen import set_focus_elite_window
from directinput import *
from EDlogger import logger
"""
Description: Pulls the keybindings for specific controls from the ED Key Bindings file, this class also
has method for sending a key to the display that has focus (so must have ED with focus)
Constraints: This file will use the latest modified *.binds file
"""
@final
class EDKeys:
def __init__(self, cb):
self.ap_ckb = cb
self.key_mod_delay = 0.01 # Delay for key modifiers to ensure modifier is detected before/after the key
self.key_def_hold_time = 0.2 # Default hold time for a key press
self.key_repeat_delay = 0.1 # Delay between key press repeats
self.activate_window = False
self.keys_to_obtain = [
'YawLeftButton',
'YawRightButton',
'RollLeftButton',
'RollRightButton',
'PitchUpButton',
'PitchDownButton',
'SetSpeedZero',
'SetSpeed50',
'SetSpeed100',
'HyperSuperCombination',
'SelectTarget',
'DeployHeatSink',
'UIFocus',
'UI_Up',
'UI_Down',
'UI_Left',
'UI_Right',
'UI_Select',
'UI_Back',
'CycleNextPanel',
'HeadLookReset',
'PrimaryFire',
'SecondaryFire',
'ExplorationFSSEnter',
'ExplorationFSSQuit',
'MouseReset',
'DeployHardpointToggle',
'IncreaseEnginesPower',
'IncreaseWeaponsPower',
'IncreaseSystemsPower',
'GalaxyMapOpen',
'CamZoomIn', # Gal map zoom in
'SystemMapOpen',
'UseBoostJuice',
'Supercruise',
'UpThrustButton',
'LandingGearToggle',
'TargetNextRouteSystem', # Target next system in route
'CamTranslateForward',
'CamTranslateRight',
'OrderAggressiveBehaviour',
]
self.keys = self.get_bindings()
self.bindings = self.get_bindings_dict()
self.missing_keys = []
# We want to log the keyboard name instead of just the key number so we build a reverse dictionary
# so we can look up the name also
self.reversed_dict = {value: key for key, value in SCANCODE.items()}
# dump config to log
for key in self.keys_to_obtain:
try:
# lookup the keyname in the SCANCODE reverse dictionary and output that key name
keyname = self.reversed_dict.get(self.keys[key]['key'], "Key not found")
keymod = " "
# if key modifier, then look up that modifier name also
if len(self.keys[key]['mods']) != 0:
keymod = self.reversed_dict.get(self.keys[key]['mods'][0], " ")
logger.info('\tget_bindings_<{}>={} Key: <{}> Mod: <{}>'.format(key, self.keys[key], keyname, keymod))
if key not in self.keys:
self.ap_ckb('log',
f"WARNING: \tget_bindings_<{key}>= does not have a valid keyboard keybind {keyname}.")
logger.warning(
"\tget_bindings_<{}>= does not have a valid keyboard keybind {}".format(key, keyname).upper())
self.missing_keys.append(key)
except Exception as e:
self.ap_ckb('log', f"WARNING: \tget_bindings_<{key}>= does not have a valid keyboard keybind.")
logger.warning("\tget_bindings_<{}>= does not have a valid keyboard keybind.".format(key).upper())
self.missing_keys.append(key)
# Check for key collisions with the keys EDAP uses.
for key in self.keys_to_obtain:
collisions = self.get_collisions(key)
if len(collisions) > 1:
# lookup the keyname in the SCANCODE reverse dictionary and output that key name
keyname = self.reversed_dict.get(self.keys[key]['key'], "Key not found")
warn_text = (f"Key '{keyname}' is used for the following bindings: {collisions}. "
"This MAY causes issues when using EDAP. Monitor and adjust accordingly.")
self.ap_ckb('log', f"WARNING: {warn_text}")
logger.warning(f"{warn_text}")
# Check if the hotkeys are used in ED
binding_name = self.check_hotkey_in_bindings('Key_End')
if binding_name != "":
warn_text = (f"Hotkey 'Key_End' is used in the ED keybindings for '{binding_name}'. Recommend changing in"
f" ED to another key to avoid EDAP accidentally being triggered.")
self.ap_ckb('log', f"WARNING: {warn_text}")
logger.warning(f"{warn_text}")
binding_name = self.check_hotkey_in_bindings('Key_Insert')
if binding_name != "":
warn_text = (f"Hotkey 'Key_Insert' is used in the ED keybindings for '{binding_name}'. Recommend changing in"
f" ED to another key to avoid EDAP accidentally being triggered.")
self.ap_ckb('log', f"WARNING: {warn_text}")
logger.warning(f"{warn_text}")
binding_name = self.check_hotkey_in_bindings('Key_PageUp')
if binding_name != "":
warn_text = (f"Hotkey 'Key_PageUp' is used in the ED keybindings for '{binding_name}'. Recommend changing in"
f" ED to another key to avoid EDAP accidentally being triggered.")
self.ap_ckb('log', f"WARNING: {warn_text}")
logger.warning(f"{warn_text}")
binding_name = self.check_hotkey_in_bindings('Key_Home')
if binding_name != "":
warn_text = (f"Hotkey 'Key_Home' is used in the ED keybindings for '{binding_name}'. Recommend changing in"
f" ED to another key to avoid EDAP accidentally being triggered.")
self.ap_ckb('log', f"WARNING: {warn_text}")
logger.warning(f"{warn_text}")
def get_bindings(self) -> dict[str, Any]:
"""Returns a dict struct with the direct input equivalent of the necessary elite keybindings"""
direct_input_keys = {}
latest_bindings = self.get_latest_keybinds()
if not latest_bindings:
return {}
bindings_tree = parse(latest_bindings)
bindings_root = bindings_tree.getroot()
for item in bindings_root:
if item.tag in self.keys_to_obtain:
key = None
mods = []
hold = None
# Check primary
if item[0].attrib['Device'].strip() == "Keyboard":
key = item[0].attrib['Key']
for modifier in item[0]:
if modifier.tag == "Modifier":
mods.append(modifier.attrib['Key'])
elif modifier.tag == "Hold":
hold = True
# Check secondary (and prefer secondary)
if item[1].attrib['Device'].strip() == "Keyboard":
key = item[1].attrib['Key']
mods = []
hold = None
for modifier in item[1]:
if modifier.tag == "Modifier":
mods.append(modifier.attrib['Key'])
elif modifier.tag == "Hold":
hold = True
# Prepare final binding
binding: None | dict[str, Any] = None
try:
if key is not None:
binding = {}
binding['key'] = SCANCODE[key]
binding['mods'] = []
for mod in mods:
binding['mods'].append(SCANCODE[mod])
if hold is not None:
binding['hold'] = True
except KeyError:
print("Unrecognised key '" + (
json.dumps(binding) if binding else '?') + "' for bind '" + item.tag + "'")
if binding is not None:
direct_input_keys[item.tag] = binding
if len(list(direct_input_keys.keys())) < 1:
return {}
else:
return direct_input_keys
def get_bindings_dict(self) -> dict[str, Any]:
"""Returns a dict of all the elite keybindings.
@return: A dictionary of the keybinds file.
Example:
{
'Root': {
'YawLeftButton': {
'Primary': {
'@Device': 'Keyboard',
'@Key': 'Key_A'
},
'Secondary': {
'@Device': '{NoDevice}',
'@Key': ''
}
}
}
}
"""
latest_bindings = self.get_latest_keybinds()
if not latest_bindings:
return {}
try:
with open(latest_bindings, 'r') as file:
my_xml = file.read()
my_dict = xmltodict.parse(my_xml)
return my_dict
except OSError as e:
logger.error(f"OS Error reading Elite Dangerous bindings file: {latest_bindings}.")
raise Exception(f"OS Error reading Elite Dangerous bindings file: {latest_bindings}.")
def check_hotkey_in_bindings(self, key_name: str) -> str:
""" Check for the action keys. """
ret = []
for key, value in self.bindings['Root'].items():
if type(value) is dict:
primary = value.get('Primary', None)
if primary is not None:
if primary['@Key'] == key_name:
ret.append(f"{key} (Primary)")
secondary = value.get('Secondary', None)
if secondary is not None:
if secondary['@Key'] == key_name:
ret.append(f"{key} (Secondary)")
return " and ".join(ret)
# Note: this routine will grab the *.binds file which is the latest modified
def get_latest_keybinds(self):
path_bindings = environ['LOCALAPPDATA'] + "\Frontier Developments\Elite Dangerous\Options\Bindings"
try:
list_of_bindings = [join(path_bindings, f) for f in listdir(path_bindings) if
isfile(join(path_bindings, f)) and f.endswith('.binds')]
except FileNotFoundError as e:
return None
if not list_of_bindings:
return None
latest_bindings = max(list_of_bindings, key=getmtime)
logger.info(f'Latest keybindings file:{latest_bindings}')
return latest_bindings
def send_key(self, type, key):
# Focus Elite window if configured
if self.activate_window:
set_focus_elite_window()
sleep(0.05)
if type == 'Up':
ReleaseKey(key)
else:
PressKey(key)
def send(self, key_binding, hold=None, repeat=1, repeat_delay=None, state=None):
""" Send a key based on the defined keybind
@param key_binding: The key bind name (i.e. UseBoostJuice).
@param hold: The time to hold the key down in seconds.
@param repeat: Number of times to repeat the key.
@param repeat_delay: Time delay in seconds between repeats. If None, uses the default repeat delay.
@param state: Key state:
None - press and release (default).
1 - press (but don't release).
0 - release (a previous press state).
"""
key = self.keys.get(key_binding)
if key is None:
logger.warning('SEND=NONE !!!!!!!!')
self.ap_ckb('log', f"WARNING: Unable to retrieve keybinding for {key_binding}.")
raise Exception(
f"Unable to retrieve keybinding for {key_binding}. Advise user to check game settings for keyboard bindings.")
key_name = self.reversed_dict.get(key['key'], "Key not found")
logger.debug('\tsend=' + key_binding + ',key:' + str(key) + ',key_name:' + key_name + ',hold:' + str(
hold) + ',repeat:' + str(
repeat) + ',repeat_delay:' + str(repeat_delay) + ',state:' + str(state))
for i in range(repeat):
# Focus Elite window if configured.
if self.activate_window:
set_focus_elite_window()
sleep(0.05)
if state is None or state == 1:
for mod in key['mods']:
PressKey(mod)
sleep(self.key_mod_delay)
PressKey(key['key'])
if state is None:
if hold:
if hold > 0.0:
sleep(hold)
else:
if self.key_def_hold_time > 0.0:
sleep(self.key_def_hold_time)
if 'hold' in key:
sleep(0.1)
if state is None or state == 0:
ReleaseKey(key['key'])
for mod in key['mods']:
sleep(self.key_mod_delay)
ReleaseKey(mod)
if repeat_delay:
sleep(repeat_delay)
else:
sleep(self.key_repeat_delay)
def get_collisions(self, key_name: str) -> list[str]:
""" Get key name collisions (keys used for more than one binding).
@param key_name: The key name (i.e. UI_Up, UI_Down).
"""
key = self.keys.get(key_name)
collisions = []
for k, v in self.keys.items():
if key == v:
collisions.append(k)
return collisions