-
Notifications
You must be signed in to change notification settings - Fork 4
/
hid_utils.py.j2
executable file
·283 lines (232 loc) · 8.93 KB
/
hid_utils.py.j2
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
# TODO: display grabbing abstract class
# TODO: for relative control apis, use them as fallback for absolute apis (somehow calibrated, with feedback) when possible
# TODO: check out ROS package index: https://index.ros.org/packages/
from enum import Enum, auto, Flag
from beartype.vale import Is
from typing_extensions import Annotated, TypeAlias
from conscious_struct import HIDActionTypes, HIDActionBase
from log_utils import logger_print
from typing import Dict, Tuple, Union
from abc import ABC, abstractmethod
{% set abstractParamsLUT = dict()%}
{% macro paramDefToClassMethodParams(funcName, paramDef) %}{{funcName}}(self, {{paramDef}}):{% endmacro %}
{% macro impl_abstract(funcName) %}_{{paramDefToClassMethodParams(funcName, abstractParamsLUT[funcName])}}{% endmacro %}
{% macro def_abstract_impl(funcName, paramDef, level=0) %}
{% do abstractParamsLUT.update({funcName: paramDef}) %}
{% set content %}
def {{paramDefToClassMethodParams(funcName, paramDef)}}
"""
{{lstrip(caller()) | indent(4,True)}}
"""
return self._{{funcName}}({{remove_typehint(paramDef)}})
@abstractmethod
def _{{paramDefToClassMethodParams(funcName, paramDef)}}
...
{% endset %}
{{content | indent(4*level, True)}}
{% endmacro %}
# TODO: use abstract implementation pattern (template)
class HIDInterface(ABC):
{% set key_literal = "key_literal: HIDActionTypes.keys" %}
{% set coordinate = "x: Union[int, float], y: Union[int, float]" %}
{% call def_abstract_impl("key_press", key_literal) %}
Press one of key literals.
{% endcall %}
{% call def_abstract_impl("key_release", key_literal) %}
Release one of key literals.
{% endcall %}
{% call def_abstract_impl("mouse_move", coordinate) %}
Move mouse to absolute position (x, y).
{% endcall %}
{% call def_abstract_impl("mouse_click", ",".join([coordinate,"button_literal: HIDActionTypes.mouse_buttons, pressed: bool"])) %}
Press or release one of mouse button literals at absolute position (x, y).
{% endcall %}
{% call def_abstract_impl("mouse_scroll", ",".join([coordinate, "dx: Union[int, float], dy: Union[int, float]"])) %}
Scroll mouse (dx, dy) at absolute position (x, y).
{% endcall %}
def length_limit(l):
return Is[lambda b: len(b) == l]
# import Xlib
# python-xlib
import os
sourcefile_dirname = os.path.dirname(os.path.abspath(__file__))
key_literal_to_xk_keysym_translation_table_path = os.path.join(
sourcefile_dirname, "KL2XKS.json"
)
from functools import lru_cache
import json
@lru_cache
def getKL2XKS() -> Dict[str, str]:
with open(key_literal_to_xk_keysym_translation_table_path, "r") as f:
KL2XKS = json.loads(f.read())
return KL2XKS
from beartype import beartype
@beartype
def strip_key_literal(key_literal: HIDActionTypes.keys) -> Tuple[bool, bool, str]:
# defer strip/lstrip.
# it is not a bug. do not report.
is_special, is_media = False, False
keychar = ...
if key_literal.startswith(prefix := "Key."):
is_special = True
keychar = key_literal.replace(prefix, "")
if keychar.startswith(prefix := "media_"):
is_media = True
keychar = keychar.replace(prefix, "")
if len(key_literal) == 3:
if not (key_literal[0] == key_literal[2] != (keychar := key_literal[1])):
raise Exception(f"Abnormal enclosed keychar: {repr(key_literal)}")
if keychar == Ellipsis:
raise Exception(f"Unable to strip key literal: {repr(key_literal)}")
else:
return is_special, is_media, keychar
@beartype
def key_literal_to_xk_keysym(key_literal: HIDActionTypes.keys) -> Union[None, str]:
# is_special, is_media, stripped_key_literal = strip_key_literal(key_literal)
KL2XKS = getKL2XKS()
xk_keysym = KL2XKS.get(key_literal, None)
if xk_keysym is None:
print(f"skipping translating key literal {repr(key_literal)} to xk_keysym.")
return xk_keysym
# Xlib.XK.string_to_keysym(stripped_key_literal)
# generate this translation table statically, then we will review.
def byte_with_length_limit(l):
return Annotated[bytes, length_limit(l)]
one_byte: TypeAlias = byte_with_length_limit(1)
two_bytes: TypeAlias = byte_with_length_limit(2)
four_bytes: TypeAlias = byte_with_length_limit(4)
six_bytes: TypeAlias = byte_with_length_limit(6)
eight_bytes: TypeAlias = byte_with_length_limit(8)
non_neg_int: TypeAlias = Annotated[int, Is[lambda i: i >= 0]]
pos_int: TypeAlias = Annotated[int, Is[lambda i: i > 0]]
movement: TypeAlias = Annotated[
int, Is[lambda i: i >= -126 and i <= 126]
] # this is hardware limit. software might not be limited. (shall we adapt to software limit instead of hardware)
class ControlCode(Flag):
# @staticmethod
# def _generate_next_value_(name, start, count, last_values):
# return 2 ** (count)
NULL = 0
LEFT_CONTROL = auto()
LEFT_SHIFT = auto()
LEFT_ALT = auto()
LEFT_GUI = auto()
RIGHT_CONTROL = auto()
RIGHT_SHIFT = auto()
RIGHT_ALT = auto()
RIGHT_GUI = auto()
class MouseButton(Flag):
# class MouseButton(Enum):
# @staticmethod
# def _generate_next_value_(name, start, count, last_values):
# return 2 ** (count)
NULL = 0
LEFT = auto()
RIGHT = auto()
MIDDLE = auto()
class MultimediaKey(Flag):
# class MultimediaKey(Enum):
# @staticmethod
# def _generate_next_value_(name, start, count, last_values):
# return 2 ** (count)
Null = 0
# row 1
VolumeUp = auto()
VolumeDown = auto()
Mute = auto()
PlayPause = auto()
NextTrack = auto()
PreviousTrack = auto()
CDStop = auto()
Eject = auto()
# row 2
EMail = auto()
WWWSearch = auto()
WWWFavourites = auto()
WWWHome = auto()
WWWBack = auto()
WWWForward = auto()
WWWStop = auto()
Refresh = auto()
# row 3
Media = auto()
Explorer = auto()
Calculator = auto()
ScreenSave = auto()
MyComputer = auto()
Minimize = auto()
Record = auto()
Rewind = auto()
assert len(MultimediaKey.__members__) == 3 * 8 + 1 # include "Null"
class ACPIKey(Flag):
Null = 0 # for clearing all "ACPI" keys.
Power = auto()
Sleep = auto()
Wakeup = auto()
if __name__ == "__main__":
# generate that table.
import Levenshtein as L
import keysymdef
unicode_str_to_xk_keysym = {}
xk_keysyms = []
xk_keysyms_lut = {}
for xk_keysym, _, unicode_int in keysymdef.keysymdef:
unicode_str = None
as_unicode_char = False
if unicode_int:
try:
unicode_str = chr(unicode_int)
unicode_str_to_xk_keysym[unicode_str] = xk_keysym
as_unicode_char = True
except:
pass
xk_keysym_lower = xk_keysym.lower()
xk_keysyms_lut[xk_keysym_lower] = xk_keysym
# if not as_unicode_char:
xk_keysyms.append(xk_keysym_lower) # for space.
KL2XKS = {}
# import rich
# rich.print(xk_keysyms_lut)
# breakpoint()
keywords_translation_table = dict(
cmd="super",
ctrl="control",
_left="_l",
_right="_r",
esc="escape",
enter="return",
# we do not use xf86 (multimedia) keys. or shall we? how to handle the play/pause button then?
)
def translate(string: str, translation_table: Dict[str, str]):
for k, v in translation_table.items():
string = string.replace(k, v)
return string
import re
for key_literal in HIDActionBase.keys: # nearly instant. no need for progressbar.
is_special, is_media, stripped_key_literal = strip_key_literal(key_literal)
if is_media:
continue
# media prefix is removed.
# if "eth" in stripped_key_literal.lower():
# breakpoint()
if stripped_key_literal in unicode_str_to_xk_keysym.keys():
keysym = unicode_str_to_xk_keysym[stripped_key_literal]
else:
# import humps
stripped_key_literal = translate(
re.sub(
r"^(alt|control|cmd|shift)$", r"\1_l", stripped_key_literal.lower()
),
keywords_translation_table,
)
# if "return" in stripped_key_literal:
# breakpoint()
xk_keysyms.sort(
key=lambda keysym: L.distance(keysym.lower(), stripped_key_literal)
)
keysym = xk_keysyms.pop(0)
KL2XKS.update(val := {key_literal: xk_keysyms_lut[keysym]})
print(val, key_literal, stripped_key_literal)
with open(key_literal_to_xk_keysym_translation_table_path, "w+") as f:
f.write(json.dumps(KL2XKS, ensure_ascii=False, indent=4))
logger_print("write to:", key_literal_to_xk_keysym_translation_table_path)