-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
numberpad.py
executable file
·2637 lines (1988 loc) · 93.4 KB
/
numberpad.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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import configparser
import importlib
import logging
from systemd.journal import JournalHandler
import math
import os
import re
import subprocess
import sys
import threading
from time import sleep, time
from typing import Optional
import numpy as np
from libevdev import EV_ABS, EV_KEY, EV_LED, EV_MSC, EV_SYN, Device, InputEvent, const, device
from pyinotify import WatchManager, IN_CLOSE_WRITE, IN_IGNORED, IN_MOVED_TO, AsyncNotifier
import Xlib.display
import Xlib.X
import Xlib.XK
from xkbcommon import xkb
from pywayland.client import Display
from pywayland.protocol.wayland import WlSeat
import mmap
from smbus2 import SMBus, i2c_msg
import ast
import signal
import math
import glob
xdg_session_type = os.environ.get('XDG_SESSION_TYPE')
display_var = os.environ.get('DISPLAY')
display_wayland_var = os.environ.get('WAYLAND_DISPLAY')
display_wayland = None
keyboard_state = None
display = None
keymap_loaded = False
listening_touchpad_events_started = False
logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s',
level=os.environ.get('LOG', 'INFO')
)
log = logging.getLogger('asus-numberpad-driver')
log.addHandler(JournalHandler())
xauth_in_tmp_dir = glob.glob('/tmp/xauth_*')
if len(xauth_in_tmp_dir) > 0:
os.environ['XAUTHORITY'] = xauth_in_tmp_dir[0]
log.info("X11 has xauth file in /tmp folder with filename changed each boot, currently {}".format(os.environ['XAUTHORITY']))
if not xdg_session_type:
log.error("xdg session type can not be empty. Exiting")
sys.exit(1)
if xdg_session_type == "x11":
try:
display = Xlib.display.Display(display_var)
log.info("X11 detected and connected succesfully to the display {}".format(display_var))
except:
log.error("X11 detected but not connected succesfully to the display {}. Exiting".format(display_var))
sys.exit(1)
udev = None
threads = []
stop_threads = False
enabled_evdev_keys = []
# only to avoid first - x11 only
gnome_current_layout = None
# only to avoid first - x11 even wayland (e.g. Ubuntu 22.04)
gnome_current_layout_index = None
watch_manager = None
event_notifier = None
def mod_name_to_specific_keysym_name(mod_name):
global display_wayland
mod_to_specific_keysym_name = {
'Control': 'Control_L',
'Shift': 'Shift_L',
'Lock': 'Caps_Lock',
'Mod1': 'Alt_L',
'Mod2': 'Num_Lock',
'Mod3': 'Caps_Lock',
'Mod4': 'Meta_L',
'Mod5': 'Scroll_Lock',
'NumLock': 'Num_Lock',
'Alt': 'Alt_L',
'LevelThree': 'ISO_Level3_Shift',
'LAlt': 'Alt_L',
'RAlt': 'Alt_R',
'RControl': 'Control_R',
'LControl': 'Control_L',
'ScrollLock': 'Scroll_Lock',
'LevelFive': 'ISO_Level5_Shift',
'AltGr': 'Alt_R',
'Meta': 'Meta_L',
'Super': 'Meta_L',
'Hyper': 'Hyper_L'
}
mods_to_indexes_x11 = {
"Shift": Xlib.X.ShiftMapIndex,
"Lock": Xlib.X.LockMapIndex,
"Control": Xlib.X.ControlMapIndex,
"Mod1": Xlib.X.Mod1MapIndex,
"Mod2": Xlib.X.Mod2MapIndex,
"Mod3": Xlib.X.Mod3MapIndex,
"Mod4": Xlib.X.Mod4MapIndex,
"Mod5": Xlib.X.Mod5MapIndex
}
if display and mod_name in mods_to_indexes_x11:
mods = display.get_modifier_mapping()
first_keycode = mods[mods_to_indexes_x11[mod_name]][0]
if first_keycode:
key = EV_KEY.codes[int(first_keycode) - 8]
keysym = display.keycode_to_keysym(first_keycode, 0)
for key in Xlib.XK.__dict__:
if key.startswith("XK") and Xlib.XK.__dict__[key] == keysym:
return key[3:]
else:
return mod_to_specific_keysym_name[mod_name]
elif display_wayland:
keymap = keyboard_state.get_keymap()
num_mods = keymap.num_mods()
for keycode in keymap:
keyboard_state_clean = keymap.state_new()
key_state = keyboard_state_clean.update_key(keycode, xkb.KeyDirection.XKB_KEY_DOWN)
num_layouts = keymap.num_layouts_for_key(keycode)
for layout in range(0, num_layouts):
if gnome_current_layout_index is not None and gnome_current_layout_index == layout:
layout_is_active = True
else:
layout_is_active = keyboard_state_clean.layout_index_is_active(layout, xkb.StateComponent.XKB_STATE_LAYOUT_EFFECTIVE)
if layout_is_active:
for mod_index in range(0, num_mods):
is_key_mod = key_state & xkb.StateComponent.XKB_STATE_MODS_DEPRESSED
if is_key_mod:
is_mod_active = keyboard_state_clean.mod_index_is_active(mod_index, xkb.StateComponent.XKB_STATE_MODS_DEPRESSED)
if is_mod_active:
if keymap.mod_get_name(mod_index) == mod_name:
keysyms = keymap.key_get_syms_by_level(keycode, layout, 0)
if len(keysyms) != 1:
continue
keysym_name = xkb.keysym_get_name(keysyms[0])
#log.info(mod_name)
#log.info(keycode)
#log.info(keysym_name)
return keysym_name
else:
return mod_to_specific_keysym_name[mod_name]
keysym_name_associated_to_evdev_key_reflecting_current_layout = None
# default are for unicode shortcuts + is loaded layout during start (BackSpace, Return - enter, asterisk, minus etc. can be found using xev)
def set_defaults_keysym_name_associated_to_evdev_key_reflecting_current_layout():
global keysym_name_associated_to_evdev_key_reflecting_current_layout
keysym_name_associated_to_evdev_key_reflecting_current_layout = {
'Num_Lock': '',
# unicode shortcut - for hex value
'0': '',
'1': '',
'2': '',
'3': '',
'4': '',
'5': '',
'6': '',
'7': '',
'8': '',
'9': '',
'a': '',
'b': '',
'c': '',
'd': '',
'e': '',
'f': '',
# unicode shortcut - start sequence
mod_name_to_specific_keysym_name('Shift'): '',
mod_name_to_specific_keysym_name('Control'): '',
'u': '',
# unicode shortcut - end sequence
'space': ''
}
def get_keysym_name_associated_to_evdev_key_reflecting_current_layout():
global keysym_name_associated_to_evdev_key_reflecting_current_layout
# lazy initialization because of loading modifiers inside Shift & Control
if not keysym_name_associated_to_evdev_key_reflecting_current_layout:
set_defaults_keysym_name_associated_to_evdev_key_reflecting_current_layout()
return keysym_name_associated_to_evdev_key_reflecting_current_layout
# necessary when are new keys enabled
def reset_udev_device():
global dev, udev
log.info("Old device at {} ({})".format(udev.devnode, udev.syspath))
udev = dev.create_uinput_device()
log.info("New device at {} ({})".format(udev.devnode, udev.syspath))
# Sleep for a little bit so udev, libinput, Xorg, Wayland, ... all have had
# a chance to see the device and initialize it. Otherwise the event
# will be sent by the kernel but nothing is ready to listen to the
# device yet
sleep(0.5)
def enable_key(key_or_key_combination, reset_udev = False):
global enabled_evdev_keys, dev, udev
enabled_keys_count = len(enabled_evdev_keys)
if isEvent(key_or_key_combination):
if key_or_key_combination not in enabled_evdev_keys:
enabled_evdev_keys.append(key_or_key_combination)
dev.enable(key_or_key_combination)
elif isEventList(key_or_key_combination):
for key in key_or_key_combination:
if key not in enabled_evdev_keys:
enabled_evdev_keys.append(key)
dev.enable(key)
# one or more changed to something not enabled yet to send using udev device? -> udev device has to be re-created
if len(enabled_evdev_keys) > enabled_keys_count and reset_udev:
reset_udev_device()
def load_evdev_key_for_x11(char):
global display, keysym_name_associated_to_evdev_key_reflecting_current_layout
keysym = Xlib.XK.string_to_keysym(char)
if keysym == 0:
return
keycode = display.keysym_to_keycode(keysym)
key = EV_KEY.codes[int(keycode) - 8]
# bare
if display.keycode_to_keysym(keycode, 0) == keysym:
pass
# shift
elif display.keycode_to_keysym(keycode, 1) == keysym:
key = [load_evdev_key_for_x11(mod_name_to_specific_keysym_name('Shift')), key]
# altgr
elif display.keycode_to_keysym(keycode, 2) == keysym:
key = [load_evdev_key_for_x11(mod_name_to_specific_keysym_name('AltGr')), key]
# shift altgr
elif display.keycode_to_keysym(keycode, 3) == keysym:
key = [load_evdev_key_for_x11(mod_name_to_specific_keysym_name('Shift')), load_evdev_key_for_x11(mod_name_to_specific_keysym_name('AltGr')), key]
set_evdev_key_for_char(char, key)
enable_key(key)
return key
def load_evdev_keys_for_x11():
global enabled_evdev_keys, keymap_loaded, udev
log.debug("X11 will try to load keymap")
enabled_keys_count = len(enabled_evdev_keys)
for char in get_keysym_name_associated_to_evdev_key_reflecting_current_layout().copy():
load_evdev_key_for_x11(char)
# one or more changed to something not enabled yet to send using udev device? -> udev device has to be re-created
#
# BUT only reset if event is not first one - driver is starting and keymap is not loaded yet
if len(enabled_evdev_keys) > enabled_keys_count and keymap_loaded and udev:
reset_udev_device()
keymap_loaded = True
log.debug("X11 loaded keymap succesfully")
log.debug(get_keysym_name_associated_to_evdev_key_reflecting_current_layout())
def set_evdev_key_for_char(char, evdev_key):
global keysym_name_associated_to_evdev_key_reflecting_current_layout
# lazy initialization because of loading modifiers inside Shift & Control
if not keysym_name_associated_to_evdev_key_reflecting_current_layout:
set_defaults_keysym_name_associated_to_evdev_key_reflecting_current_layout()
keysym_name_associated_to_evdev_key_reflecting_current_layout[char] = evdev_key
def get_evdev_key_for_char(char):
keysym_name_associated_to_evdev_key_reflecting_current_layout = get_keysym_name_associated_to_evdev_key_reflecting_current_layout()
return keysym_name_associated_to_evdev_key_reflecting_current_layout[char]
def isEvent(event):
if hasattr(event, "name") and hasattr(EV_KEY, event.name):
return True
else:
return False
def isEventList(events):
if type(events) is list:
for event in events:
if not isEvent(event):
return False
return True
else:
return False
def load_evdev_key_for_wayland(char, keyboard_state):
global gnome_current_layout_index
keysym = xkb.keysym_from_name(char)
keymap = keyboard_state.get_keymap()
num_mods = keymap.num_mods()
for keycode in keymap:
num_layouts = keymap.num_layouts_for_key(keycode)
for layout in range(0, num_layouts):
num_levels = keymap.num_levels_for_key(keycode, layout)
for level in range(0, num_levels):
mod_masks_for_level = keymap.key_get_mods_for_level(keycode, layout, level)
if len(mod_masks_for_level) < 1:
continue
keysyms = keymap.key_get_syms_by_level(keycode, layout, level)
if len(keysyms) != 1 or keysyms[0] != keysym:
continue
for mod_mask_index in range(0, len(mod_masks_for_level)):
mod_evdev_keys = []
for mod_index in range(0, num_mods):
if (mod_masks_for_level[mod_mask_index] & (1 << mod_index) == 0):
continue
mod_name = keymap.mod_get_name(mod_index)
mod_as_evdev_key = load_evdev_key_for_wayland(mod_name_to_specific_keysym_name(mod_name), keyboard_state)
mod_evdev_keys.append(mod_as_evdev_key)
if not mod_as_evdev_key:
continue
if len(mod_evdev_keys) > 0:
key = mod_evdev_keys + [EV_KEY.codes[int(keycode - 8)]]
else:
key = EV_KEY.codes[int(keycode - 8)]
if gnome_current_layout_index is not None and gnome_current_layout_index == layout:
layout_is_active = True
else:
layout_is_active = keyboard_state.layout_index_is_active(layout, xkb.StateComponent.XKB_STATE_LAYOUT_EFFECTIVE)
enable_key(key)
if layout_is_active:
set_evdev_key_for_char(char, key)
return key
def wl_load_keymap_state():
global keyboard_state, keymap_loaded, udev
log.debug("Wayland will try to load keymap")
enabled_keys = len(enabled_evdev_keys)
for char in get_keysym_name_associated_to_evdev_key_reflecting_current_layout().copy():
load_evdev_key_for_wayland(char, keyboard_state)
# one or more changed to something not enabled yet to send using udev device? -> udev device has to be re-created
#
# BUT only reset if event is not first one - driver is starting and keymap is not loaded yet
if len(enabled_evdev_keys) > enabled_keys and keymap_loaded and udev:
reset_udev_device()
keymap_loaded = True
log.debug("Wayland loaded keymap succesfully")
log.debug(get_keysym_name_associated_to_evdev_key_reflecting_current_layout())
def wl_keyboard_keymap_handler(keyboard, format_, fd, size):
global keyboard_state
keymap_data = mmap.mmap(
fd, size, prot=mmap.PROT_READ, flags=mmap.MAP_PRIVATE
)
xkb_context = xkb.Context()
keymap = xkb_context.keymap_new_from_buffer(keymap_data, length=size - 1)
keymap_data.close()
keyboard_state = keymap.state_new()
wl_load_keymap_state()
def wl_registry_handler(registry, id_, interface, version):
log.debug(registry)
log.debug(id_)
log.debug(interface)
log.debug(version)
if interface == "wl_seat":
seat = registry.bind(id_, WlSeat, version)
keyboard = seat.get_keyboard()
keyboard.dispatcher["keymap"] = wl_keyboard_keymap_handler
def load_keymap_listener_wayland():
global stop_threads, display_wayland_var, display_wayland
try:
display_wayland = Display(display_wayland_var)
display_wayland.connect()
registry = display_wayland.get_registry()
registry.dispatcher["global"] = wl_registry_handler
display_wayland.dispatch(block=True)
display_wayland.roundtrip()
while not stop_threads and display_wayland.dispatch(block=True) != -1:
pass
except:
log.exception("Wayland load keymap listener error. Exiting")
os.kill(os.getpid(), signal.SIGUSR1)
def load_keymap_listener_x11():
global stop_threads, display, listening_touchpad_events_started
try:
while not stop_threads:
event = display.next_event()
if event.type == Xlib.X.MappingNotify and event.count > 0 and event.request == Xlib.X.MappingKeyboard:
if listening_touchpad_events_started or not keymap_loaded:
display.refresh_keyboard_mapping(event)
load_evdev_keys_for_x11()
#raise Xlib.error.ConnectionClosedError("fd") # testing purpose only
except:
log.exception("X11 load keymap listener error. Exiting")
os.kill(os.getpid(), signal.SIGUSR1)
EV_KEY_TOP_LEFT_ICON = "EV_KEY_TOP_LEFT_ICON"
numlock: bool = False
is_idled: bool = False
# Constants
try_times = 5
try_sleep = 0.1
gsettings_failure_count = 0
gsettings_max_failure_count = 3
qdbus_failure_count = 0
qdbus_max_failure_count = 3
getting_device_via_xinput_status_failure_count = 0
getting_device_via_xinput_status_max_failure_count = 3
getting_device_via_synclient_status_failure_count = 0
getting_device_via_synclient_status_max_failure_count = 3
# Numpad layout model
model = None
if len(sys.argv) > 1:
model = sys.argv[1]
try:
model_layout = importlib.import_module('layouts.' + model)
except:
log.error("Numpad layout *.py from dir layouts is required as first argument. Re-run install script or add missing first argument (valid value is b7402, e210ma, g533, gx551, gx701, up5401ea, ..).")
sys.exit(1)
# Config file dir
config_file_dir = ""
if len(sys.argv) > 2:
config_file_dir = sys.argv[2]
# When is given config dir empty or is used default -> to ./ because inotify needs check folder (nor nothing = "")
if config_file_dir == "":
config_file_dir = "./"
# Layout
left_offset = getattr(model_layout, "left_offset", 0)
right_offset = getattr(model_layout, "right_offset", 0)
top_offset = getattr(model_layout, "top_offset", 0)
bottom_offset = getattr(model_layout, "bottom_offset", 0)
top_left_icon_width = getattr(model_layout, "top_left_icon_width", 0)
top_left_icon_height = getattr(model_layout, "top_left_icon_height", 0)
top_right_icon_width = getattr(model_layout, "top_right_icon_width", 0)
top_right_icon_height = getattr(model_layout, "top_right_icon_height", 0)
top_left_icon_slide_func_keys = getattr(model_layout, "top_left_icon_slide_func_keys", [
EV_KEY.KEY_CALC
])
keys = getattr(model_layout, "keys", [])
if not len(keys) > 0 or not len(keys[0]) > 0:
log.error('keys is required to set, dimension has to be atleast array of len 1 inside array')
sys.exit(1)
for row in keys:
for field in row:
if not isEvent(field) and not isEventList(field):
set_evdev_key_for_char(field, '')
if isEvent(field):
enable_key(field)
keys_ignore_offset = getattr(model_layout, "keys_ignore_offset", [])
# loaded in load_all_config_values
backlight_levels = []
# Config
CONFIG_FILE_NAME = "numberpad_dev"
CONFIG_SECTION = "main"
CONFIG_IDLED = "idled"
CONFIG_IDLED_DEFAULT = False
CONFIG_ENABLED = "enabled"
CONFIG_ENABLED_DEFAULT = False
CONFIG_LAST_BRIGHTNESS = "brightness"
CONFIG_IDLE_BRIGHTNESS = "idle_brightness"
CONFIG_IDLE_BRIGHTNESS_DEFAULT = 30
CONFIG_IDLE_ENABLED = "idle_enabled"
CONFIG_IDLE_ENABLED_DEFAULT = 0
CONFIG_IDLE_TIME = "idle_time"
CONFIG_IDLE_TIME_DEFAULT = 10
CONFIG_DEFAULT_BACKLIGHT_LEVEL = "default_backlight_level"
CONFIG_DEFAULT_BACKLIGHT_LEVEL_DEFAULT = "0x01"
CONFIG_LEFT_ICON_ACTIVATION_TIME = "top_left_icon_activation_time"
CONFIG_LEFT_ICON_ACTIVATION_TIME_DEFAULT = True
CONFIG_TOP_LEFT_ICON_BRIGHTNESS_FUNC_DISABLED = "top_left_icon_brightness_func_disabled"
CONFIG_TOP_LEFT_ICON_BRIGHTNESS_FUNC_DISABLED_DEFAULT = False
CONFIG_TOP_LEFT_ICON_SLIDE_FUNC_ACTIVATES_NUMPAD = "top_left_icon_slide_func_activates_numpad"
CONFIG_TOP_LEFT_ICON_SLIDE_FUNC_ACTIVATES_NUMPAD_DEFAULT = True
CONFIG_TOP_LEFT_ICON_SLIDE_FUNC_ACTIVATION_RADIUS = "top_left_icon_slide_func_activation_radius"
CONFIG_TOP_LEFT_ICON_SLIDE_FUNC_ACTIVATION_RADIUS_DEFAULT = 1200
CONFIG_TOP_LEFT_ICON_BRIGHTNESS_FUNC_MAX_MIN_ONLY = "top_left_icon_brightness_func_max_min_only"
CONFIG_TOP_LEFT_ICON_BRIGHTNESS_FUNC_MAX_MIN_ONLY_DEFAULT = False
CONFIG_TOP_RIGHT_ICON_SLIDE_FUNC_ACTIVATION_RADIUS = "top_right_icon_slide_func_activation_radius"
CONFIG_TOP_RIGHT_ICON_SLIDE_FUNC_ACTIVATION_RADIUS_DEFAULT = 1200
CONFIG_NUMPAD_DISABLES_SYS_NUMLOCK = "numpad_disables_sys_numlock"
CONFIG_NUMPAD_DISABLES_SYS_NUMLOCK_DEFAULT = True
CONFIG_DISABLE_DUE_INACTIVITY_TIME = "disable_due_inactivity_time"
CONFIG_DISABLE_DUE_INACTIVITY_TIME_DEFAULT = 0
CONFIG_TOUCHPAD_DISABLES_NUMPAD = "touchpad_disables_numpad"
CONFIG_TOUCHPAD_DISABLES_NUMPAD_DEFAULT = True
CONFIG_KEY_REPETITIONS = "key_repetitions"
CONFIG_KEY_REPETITIONS_DEFAULT = False
CONFIG_MULTITOUCH = "multitouch"
CONFIG_MULTITOUCH_DEFAULT = False
CONFIG_ONE_TOUCH_KEY_ROTATION = "one_touch_key_rotation"
CONFIG_ONE_TOUCH_KEY_ROTATION_DEFAULT = False
CONFIG_ACTIVATION_TIME = "activation_time"
CONFIG_ACTIVATION_TIME_DEFAULT = True
CONFIG_NUMLOCK_ENABLES_NUMPAD = "sys_numlock_enables_numpad"
CONFIG_NUMLOCK_ENABLES_NUMPAD_DEFAULT = True
CONFIG_ENABLED_TOUCHPAD_POINTER = "enabled_touchpad_pointer"
CONFIG_ENABLED_TOUCHPAD_POINTER_DEFAULT = 3
CONFIG_PRESS_KEY_WHEN_IS_DONE_UNTOUCH = "press_key_when_is_done_untouch"
CONFIG_PRESS_KEY_WHEN_IS_DONE_UNTOUCH_DEFAULT = True
CONFIG_DISTANCE_TO_MOVE_ONLY_POINTER = "distance_to_move_only_pointer"
CONFIG_DISTANCE_TO_MOVE_ONLY_POINTER_DEFAULT = False
config_file_path = config_file_dir + CONFIG_FILE_NAME
config = configparser.ConfigParser()
config_lock = threading.Lock()
# methods for read & write from config file
def config_get(key, key_default):
try:
value = config.get(CONFIG_SECTION, key)
parsed_value = parse_value_from_config(value)
return parsed_value
except:
config.set(CONFIG_SECTION, key, parse_value_to_config(key_default))
return key_default
def send_value_to_touchpad_via_i2c(value):
global device_id, device_addr
try:
with SMBus(int(device_id)) as bus:
data = [0x05, 0x00, 0x3d, 0x03, 0x06, 0x00, 0x07, 0x00, 0x0d, 0x14, 0x03, int(value, 16), 0xad]
msg = i2c_msg.write(device_addr, data)
bus.i2c_rdwr(msg)
except Exception as e:
log.error('Error during sending via i2c: \"%s\"', e)
def parse_value_from_config(value):
if value == '0':
return False
elif value == '1':
return True
else:
return value
def parse_value_to_config(value):
if value == True:
return '1'
elif value == False:
return '0'
else:
return str(value)
def config_save():
global config_file_dir, config_file_path
try:
with open(config_file_path, 'w') as configFile:
config.write(configFile)
log.debug('Writting to config file: \"%s\"', configFile)
except:
log.error('Error during writting to config file: \"%s\"', config_file_path)
pass
def config_set(key, value, no_save=False, already_has_lock=False):
global config, config_file_dir, config_lock
if not already_has_lock:
#log.debug("config_set: config_lock.acquire will be called")
config_lock.acquire()
#log.debug("config_set: config_lock.acquire called succesfully")
config.set(CONFIG_SECTION, key, parse_value_to_config(value))
log.info('Setting up for config file key: \"%s\" with value: \"%s\"', key, value)
if not no_save:
config_save()
if not already_has_lock:
# because inotify (deadlock)
sleep(0.1)
config_lock.release()
return value
def gsettingsSet(path, name, value):
global gsettings_failure_count, gsettings_max_failure_count
if gsettings_failure_count < gsettings_max_failure_count:
try:
sudo_user = os.environ.get('SUDO_USER')
if sudo_user is not None:
cmd = ['runuser', '-u', sudo_user, 'gsettings', 'set', path, name, str(value)]
else:
cmd = ['gsettings', 'set', path, name, str(value)]
log.debug(cmd)
subprocess.call(cmd)
except Exception as e:
log.debug(e, exc_info=True)
gsettings_failure_count+=1
else:
log.debug('Gsettings failed more then: \"%s\" so is not try anymore', gsettings_max_failure_count)
def gsettingsGet(path, name):
global gsettings_failure_count, gsettings_max_failure_count
if gsettings_failure_count < gsettings_max_failure_count:
try:
cmd = ['gsettings', 'get', path, name]
result = subprocess.check_output(cmd).rstrip()
return result
except Exception as e:
log.debug(e, exc_info=True)
gsettings_failure_count+=1
else:
log.debug('Gsettings failed more then: \"%s\" so is not try anymore', gsettings_max_failure_count)
def qdbusSet(value):
global qdbus_failure_count, qdbus_max_failure_count, touchpad
if qdbus_failure_count < qdbus_max_failure_count:
try:
cmd = [
'qdbus',
'org.kde.KWin',
f'/org/kde/KWin/InputDevice/event{touchpad}',
'org.kde.KWin.InputDevice.tapToClick',
str(value)
]
subprocess.call(cmd)
except Exception as e:
log.debug(e, exc_info=True)
qdbus_failure_count+=1
else:
log.debug('Qdbus failed more then: \"%s\" so is not try anymore', qdbus_max_failure_count)
def qdbusGet(service, path, interface, property_name):
global qdbus_failure_count, qdbus_max_failure_count
if qdbus_failure_count < qdbus_max_failure_count:
try:
cmd = [
'qdbus',
service,
path,
'org.freedesktop.DBus.Properties.Get',
interface,
property_name
]
result = subprocess.check_output(cmd).rstrip()
return result
except Exception as e:
log.debug(e, exc_info=True)
qdbus_failure_count+=1
else:
log.debug('Qdbus failed more then: \"%s\" so is not try anymore', qdbus_max_failure_count)
def qdbusSetTouchpadTapToClick(value):
qdbusSet(value)
def qdbusGetTouchpadEnabled():
global touchpad
try:
return qdbusGet(
'org.kde.KWin',
f'/org/kde/KWin/InputDevice/event{touchpad}',
'org.kde.KWin.InputDevice',
'enabled'
).decode().rstrip()
except:
return None
def gsettingsGetTouchpadSendEvents():
try:
return gsettingsGet('org.gnome.desktop.peripherals.touchpad', 'send-events').decode().rstrip()
except:
return None
def gsettingsSetTouchpadTapToClick(value):
gsettingsSet('org.gnome.desktop.peripherals.touchpad', 'tap-to-click', str(bool(value)).lower())
def gsettingsGetUnicodeHotkey():
try:
return gsettingsGet('org.freedesktop.ibus.panel.emoji', 'unicode-hotkey').decode().rstrip()
except:
return None
def get_compose_key_start_events_for_unicode_string(reset_udev = True):
global gsettings_failure_count, gsettings_max_failure_count, mods_to_evdev_keys
string_with_unicode_hotkey = gsettingsGetUnicodeHotkey()
keys = []
if string_with_unicode_hotkey is not None:
string_with_unicode_hotkey = string_with_unicode_hotkey.split("'")[1]
key_modifiers = re.findall("<(.*?)>", string_with_unicode_hotkey)
for key_modifier in key_modifiers:
try:
key_evdev = get_evdev_key_for_char(mod_name_to_specific_keysym_name(key_modifier))
keys.append(key_evdev)
enable_key(key_evdev, reset_udev)
except:
log.error("Error during trying to find key for modifier of found compose shortcut {}".format(key_modifier))
pass
try:
first_number_index = string_with_unicode_hotkey.rfind('>') + 1
key_evdev = get_evdev_key_for_char(string_with_unicode_hotkey[first_number_index])
keys.append(key_evdev)
enable_key(key_evdev)
except:
pass
else:
control_key = get_evdev_key_for_char(mod_name_to_specific_keysym_name('Control'))
keys.append(control_key)
enable_key(control_key, reset_udev)
shift_key = get_evdev_key_for_char(mod_name_to_specific_keysym_name('Shift'))
keys.append(shift_key)
enable_key(shift_key, reset_udev)
u_key = get_evdev_key_for_char("u")
keys.append(u_key)
enable_key(u_key, reset_udev)
events = []
for key in keys:
inputEvent = InputEvent(key, 1)
events.append(InputEvent(EV_MSC.MSC_SCAN, inputEvent.code.value))
events.append(inputEvent)
for key in keys:
inputEvent = InputEvent(key, 0)
events.append(InputEvent(EV_MSC.MSC_SCAN, inputEvent.code.value))
events.append(inputEvent)
return events
# Figure out devices from devices file
touchpad: Optional[str] = None
touchpad_name: Optional[str] = None
keyboard: Optional[str] = None
d_k = None
fd_k = None
numlock_lock = threading.Lock()
idle_lock = threading.Lock()
device_id: Optional[str] = None
device_addr: Optional[int] = None
# Look into the devices file #
while try_times > 0:
touchpad_detected = 0
keyboard_detected = 0
with open('/proc/bus/input/devices', 'r') as f:
lines = f.readlines()
for line in lines:
# Look for the touchpad #
# https://github.com/mohamed-badaoui/asus-touchpad-numpad-driver/issues/87
# https://github.com/asus-linux-drivers/asus-numberpad-driver/issues/95
# https://github.com/asus-linux-drivers/asus-numberpad-driver/issues/110
# https://github.com/asus-linux-drivers/asus-numberpad-driver/issues/161
# https://github.com/asus-linux-drivers/asus-numberpad-driver/issues/198
if (touchpad_detected == 0 and ("Name=\"ASUE" in line or "Name=\"ELAN" in line or "Name=\"ASUP" or "Name=\"ASUF" in line) and "Touchpad" in line and not "9009" in line):
touchpad_detected = 1
log.info('Detecting touchpad from string: \"%s\"', line.strip())
touchpad_name = line.split("\"")[1]
# https://github.com/asus-linux-drivers/asus-numberpad-driver/issues/161
if ("ASUF1416" in line or "ASUF1205" in line or "ASUF1204" in line):
device_addr = 0x38
else:
device_addr = 0x15
if touchpad_detected == 1:
if "S: " in line:
# search device id
device_id = re.sub(r".*i2c-(\d+)/.*$",
r'\1', line).replace("\n", "")
log.info('Set touchpad device id %s from %s',
device_id, line.strip())
if "H: " in line:
touchpad = line.split("event")[1]
touchpad = touchpad.split(" ")[0]
touchpad_detected = 2
log.info('Set touchpad id %s from %s',
touchpad, line.strip())
# Look for the keyboard
if keyboard_detected == 0 and ("Name=\"AT Translated Set 2 keyboard" in line or (("Name=\"ASUE" in line or "Name=\"Asus" in line or "Name=\"ASUP" in line or "Name=\"ASUF" in line) and "Keyboard" in line)):
keyboard_detected = 1
log.info(
'Detecting keyboard from string: \"%s\"', line.strip())
# We look for keyboard with numlock, scrollock, capslock inputs
if keyboard_detected == 1 and "H: " in line:
keyboard = line.split("event")[1]
keyboard = keyboard.split(" ")[0]
with open('/dev/input/event' + str(keyboard), 'rb') as fd_k:
d_k = Device(fd_k)
if d_k.has(EV_LED.LED_NUML):
keyboard_detected = 2
log.info('Set keyboard %s from %s', keyboard, line.strip())
else:
keyboard_detected = 0
keyboard = None
d_k = None
# Do not stop looking if touchpad and keyboard have been found
# because more drivers can be installed
# https://github.com/mohamed-badaoui/asus-touchpad-numpad-driver/issues/87
# https://github.com/asus-linux-drivers/asus-numberpad-driver/issues/95
#if touchpad_detected == 2 and keyboard_detected == 2:
# break
if touchpad_detected != 2 or keyboard_detected != 2:
try_times -= 1
if try_times == 0:
with open('/proc/bus/input/devices', 'r') as f:
lines = f.readlines()
for line in lines:
log.error(line)
if keyboard_detected != 2:
log.error("Can't find keyboard (code: %s)", keyboard_detected)
# keyboard is optional, no sys.exit(1)!
if touchpad_detected != 2:
log.error("Can't find touchpad (code: %s)", touchpad_detected)
sys.exit(1)
if touchpad_detected == 2 and not device_id.isnumeric():
log.error("Can't find device id")
sys.exit(1)
else:
break
sleep(try_sleep)
# Open a handle to "/dev/i2c-x", representing the I2C bus
try:
bus = SMBus()
bus.open(int(device_id))
bus.close()
except:
log.error("Can't open the I2C bus connection (id: %s)", device_id)
sys.exit(1)
# Start monitoring the touchpad
fd_t = open('/dev/input/event' + str(touchpad), 'rb')
d_t = Device(fd_t)
# Retrieve touchpad dimensions
ai = d_t.absinfo[EV_ABS.ABS_X]
minx, maxx = (ai.minimum, ai.maximum)
minx_numpad = minx + left_offset
maxx_numpad = maxx - right_offset
ai = d_t.absinfo[EV_ABS.ABS_Y]
(miny, maxy) = (ai.minimum, ai.maximum)
miny_numpad = miny + top_offset
maxy_numpad = maxy - bottom_offset
log.info('Touchpad min-max: x %d-%d, y %d-%d', minx, maxx, miny, maxy)
log.info('Numpad min-max: x %d-%d, y %d-%d', minx_numpad,
maxx_numpad, miny_numpad, maxy_numpad)
# Detect col, row count from map of keys
col_count = len(max(keys, key=len))
row_count = len(keys)
col_width = (maxx_numpad - minx_numpad) / col_count
row_height = (maxy_numpad - miny_numpad) / row_count
# Create a new keyboard device to send numpad events
dev = Device()
dev.name = touchpad_name.split(" ")[0] + " " + touchpad_name.split(" ")[1] + " NumberPad"
enable_key(EV_MSC.MSC_SCAN)
enable_key(EV_KEY.BTN_LEFT)
enable_key(EV_KEY.BTN_RIGHT)
enable_key(EV_KEY.BTN_MIDDLE)
for key_to_enable in top_left_icon_slide_func_keys:
enable_key(key_to_enable)
def check_gnome_layout():
global stop_threads, gnome_current_layout, gnome_current_layout_index, keyboard_state, display_wayland_var