-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreflight.py
More file actions
executable file
Β·1561 lines (1315 loc) Β· 59.3 KB
/
Copy pathpreflight.py
File metadata and controls
executable file
Β·1561 lines (1315 loc) Β· 59.3 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
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
"""
preflight β controller gate for Ryubing (Ryujinx) on SteamOS.
Confirms which physical controller is which player, verifies the face-button
labelling, writes Ryujinx's Config.json, then launches the game.
preflight.py "/path/to/Game.nsp" # check, then launch that ROM
preflight.py # check, then open the Ryujinx list
preflight.py --dry-run "<rom>" # everything except writing/launching
Zero dependencies: ctypes against the system libSDL2 and libSDL2_ttf.
Two behaviours here are empirical, established by phase0 against real
hardware, not guesses:
* Ryujinx builds its config id as "<sdl_index>-<guid>" where the guid is
SDL's, converted through .NET's Guid(byte[]) byte order, with the 16-bit
name-CRC field ZEROED. Reproducing that zeroing is essential; without it
nothing we write will ever match.
* Because Ryujinx discards that CRC, Steam's virtual pads all collapse to
one identical id. We keep the CRC ourselves so we can still tell them
apart even when Ryujinx cannot.
"""
import copy
import ctypes
import select
import struct
import json
import os
import shutil
import subprocess
import sys
import time
import sdlui
from sdlui import (UI, BTN_A, BTN_B, BTN_X, BTN_Y, BTN_START, BTN_BACK,
BTN_LSHOULDER, BTN_RSHOULDER, BTN_LSTICK, BTN_RSTICK,
BTN_DPAD_UP, BTN_DPAD_DOWN, BTN_DPAD_LEFT, BTN_DPAD_RIGHT,
BUTTON_NAMES, SWITCH_EQUIVALENT, SDLK_ESCAPE)
HERE = os.path.dirname(os.path.abspath(__file__))
STATE_DIR = os.path.join(HERE, "state")
KNOWN_PADS = os.path.join(STATE_DIR, "known_pads.json")
GAMES_FILE = os.path.join(HERE, "games.json")
BACKUP_DIR = os.path.join(STATE_DIR, "backups")
DEFAULT_APP_ID = "io.github.ryubing.Ryujinx"
MAX_PLAYERS = 4
BG = (18, 19, 24)
CARD = (32, 34, 42)
FG = (232, 233, 238)
DIM = (140, 143, 155)
ACCENT = (120, 200, 140)
WARN = (232, 180, 90)
BAD = (226, 106, 106)
# One colour per player slot. Chosen to stay distinguishable on a dark
# background and to differ in brightness as well as hue, so they still read
# apart for red/green colour blindness.
PLAYER_COLORS = [
(232, 93, 93), # P1 red
(86, 156, 232), # P2 blue
(232, 186, 82), # P3 amber
(108, 199, 130), # P4 green
]
THEME_FILE = os.path.join(HERE, "theme.json")
def blend(base, tint, amount):
return tuple(int(base[i] + (tint[i] - base[i]) * amount) for i in range(3))
def _hex_to_rgb(value):
s = str(value).lstrip("#")
if len(s) != 6:
raise ValueError(value)
return tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
def apply_theme():
"""Overlay theme.json onto the defaults. Bad entries are skipped, not fatal
β a typo in a colour should never stop you launching a game."""
theme = load_json(THEME_FILE, {})
if not theme:
return
global BG, CARD, FG, DIM, ACCENT, WARN, BAD, PLAYER_COLORS
simple = {"background": "BG", "card": "CARD", "text": "FG", "dim": "DIM",
"accent": "ACCENT", "warning": "WARN", "error": "BAD"}
for key, name in simple.items():
if key in theme:
try:
globals()[name] = _hex_to_rgb(theme[key])
except (ValueError, TypeError):
print(f"theme.json: ignoring bad colour for {key!r}",
file=sys.stderr)
rumble = theme.get("rumble")
if isinstance(rumble, dict):
global RUMBLE_ON_MS, RUMBLE_GAP_MS, RUMBLE_STRENGTH
for key, name, lo, hi in (("on_ms", "RUMBLE_ON_MS", 50, 3000),
("gap_ms", "RUMBLE_GAP_MS", 0, 10000),
("strength", "RUMBLE_STRENGTH", 0, 0xFFFF)):
if key in rumble:
try:
globals()[name] = max(lo, min(hi, int(rumble[key])))
except (ValueError, TypeError):
print(f"theme.json: ignoring bad rumble.{key}",
file=sys.stderr)
if isinstance(theme.get("players"), list):
colors = []
for entry in theme["players"]:
try:
colors.append(_hex_to_rgb(entry))
except (ValueError, TypeError):
print(f"theme.json: ignoring bad player colour {entry!r}",
file=sys.stderr)
if colors:
PLAYER_COLORS = colors
def player_color(slot):
return PLAYER_COLORS[(slot - 1) % len(PLAYER_COLORS)]
POWER = {-1: "?", 0: "empty", 1: "low", 2: "med", 3: "full", 4: "wired"}
# ---------------------------------------------------------------- identity
def ryujinx_guid(sdl_guid_hex):
"""SDL GUID hex -> the dashed guid Ryujinx writes, with name-CRC zeroed."""
b = bytearray(bytes.fromhex(sdl_guid_hex))
b[2:4] = b"\x00\x00" # Ryujinx drops the name CRC
d1 = int.from_bytes(b[0:4], "little")
d2 = int.from_bytes(b[4:6], "little")
d3 = int.from_bytes(b[6:8], "little")
return f"{d1:08x}-{d2:04x}-{d3:04x}-{b[8]:02x}{b[9]:02x}-{bytes(b[10:16]).hex()}"
def guid_name_crc(sdl_guid_hex):
return int.from_bytes(bytes.fromhex(sdl_guid_hex)[2:4], "little")
def guid_vendor_product(sdl_guid_hex):
b = bytes.fromhex(sdl_guid_hex)
return (int.from_bytes(b[4:6], "little"), int.from_bytes(b[8:10], "little"))
# SDL reports whatever layout a pad advertises, which is often a lie: Steam
# publishes its controllers as fake Xbox 360 pads, and 8BitDo spoofs Microsoft
# or Nintendo depending on its mode. These tables turn the advertised identity
# back into something a human recognises.
DEVICE_NAMES = {
(0x28DE, 0x11FF): "Steam Controller",
(0x045E, 0x0B13): "Xbox Series X|S Controller",
(0x045E, 0x02E0): "Xbox One S Controller",
(0x045E, 0x028E): "Xbox 360 Controller",
(0x18D1, 0x9400): "Stadia Controller",
(0x057E, 0x2009): "Switch Pro Controller",
(0x054C, 0x0CE6): "DualSense",
(0x054C, 0x09CC): "DualShock 4",
}
# Names here must match MAC_OUI spelling β the mismatch check below compares
# the two, so calling 0x045e "Xbox" would make genuine Microsoft pads look
# like they were spoofing.
VENDOR_NAMES = {0x2DC8: "8BitDo", 0x045E: "Microsoft", 0x18D1: "Google",
0x057E: "Nintendo", 0x28DE: "Valve", 0x054C: "Sony"}
# First three bytes of a MAC identify the actual manufacturer, regardless of
# what USB identity the pad is currently pretending to have.
MAC_OUI = {"e4:17:d8": "8BitDo", "98:7a:14": "Microsoft", "9c:aa:1b": "Microsoft",
"00:1b:dc": "Nintendo", "98:b6:e9": "Nintendo", "cc:9e:00": "Sony"}
# What a spoofed vendor tells us about the mode the pad is running in.
SPOOF_MODE = {0x045E: "X-input", 0x057E: "Switch mode", 0x054C: "PS mode"}
STEAM_VIRTUAL = (0x28DE, 0x11FF)
# Names Steam gives a virtual pad when it isn't telling us what's behind it.
GENERIC_VIRTUAL = ("x-box 360 pad", "steam virtual gamepad", "xbox 360 controller")
def label_pads(pads):
"""Resolve display names with the whole set in view.
Under Steam Input every pad is a Steam virtual pad sharing one
vendor/product, so the vendor tables cannot name them. Steam often does
put the real device's name on the virtual pad β "Steam Controller",
"Xbox One controller" β so that is used when it is informative, and a
short slot tag when it is not.
The CRC is NOT a durable identity for a physical controller: it tracks the
virtual pad slot, and Steam moves devices between slots. It is reliable
within one session, which is all the config write needs.
"""
for p in pads:
if p.nickname:
p.display = p.nickname
continue
if p.real:
# Identified through its physical twin β name it properly.
p.display = friendly_name(_Shim(name=p.real["name"],
mac=p.real["mac"],
vendor=p.real["vendor"],
product=p.real["product"]))
elif (p.vendor, p.product) == STEAM_VIRTUAL:
name = (p.name or "").strip()
generic = not name or any(g in name.lower() for g in GENERIC_VIRTUAL)
p.display = f"Steam pad {p.name_crc:04x}" if generic else name
else:
p.display = friendly_name(p)
def friendly_name(pad):
"""A label that says what the pad actually is.
Priority: a hand-set nickname in known_pads.json, then real-manufacturer
detection via MAC, then the vendor/product table, then whatever SDL said.
"""
if pad.nickname:
return pad.nickname
advertised = DEVICE_NAMES.get((pad.vendor, pad.product))
oui = (pad.mac or "").lower().replace("-", ":")[:8]
maker = MAC_OUI.get(oui)
claimed = VENDOR_NAMES.get(pad.vendor)
# Hardware maker disagrees with the advertised vendor: the pad is spoofing
# a standard layout. Name the real maker and say which mode it's in.
if maker and claimed and maker.split()[0].lower() != claimed.lower():
return f"{maker} β {SPOOF_MODE.get(pad.vendor, 'compat mode')}"
if advertised:
return advertised
if claimed:
return f"{claimed} Gamepad"
return pad.name
def sysfs_read(path):
try:
with open(path) as fh:
return fh.read().strip()
except OSError:
return ""
def sysfs_battery(mac):
"""Some drivers publish a controller battery under its MAC. Most don't β
plain xpad and the Microsoft HID driver report nothing at all β so this is
a bonus when available rather than something to rely on."""
if not mac:
return None
key = mac.lower().replace("-", ":")
try:
entries = os.listdir("/sys/class/power_supply")
except OSError:
return None
for entry in entries:
if key in entry.lower().replace("-", ":"):
try:
with open(f"/sys/class/power_supply/{entry}/capacity") as fh:
return f"{fh.read().strip()}%"
except OSError:
pass
return None
def sysfs_uniq(devpath):
if not devpath or not devpath.startswith("/dev/input/event"):
return None
node = os.path.basename(devpath)
try:
with open(f"/sys/class/input/{node}/device/uniq") as fh:
return fh.read().strip() or None
except OSError:
return None
class Pad:
"""One controller as SDL currently sees it."""
def __init__(self, sdl, index):
self.sdl = sdl
self.index = index
name = sdl.SDL_JoystickNameForIndex(index)
self.name = name.decode(errors="replace") if name else f"Pad {index}"
buf = ctypes.create_string_buffer(33)
sdl.SDL_JoystickGetGUIDString(sdl.SDL_JoystickGetDeviceGUID(index),
buf, 33)
self.sdl_guid = buf.value.decode()
self.guid = ryujinx_guid(self.sdl_guid)
self.name_crc = guid_name_crc(self.sdl_guid)
self.vendor, self.product = guid_vendor_product(self.sdl_guid)
self.handle = sdl.SDL_GameControllerOpen(index)
self.instance_id = -1
self.battery = "?"
self.serial = None
if self.handle:
js = sdl.SDL_GameControllerGetJoystick(self.handle)
self.instance_id = sdl.SDL_JoystickInstanceID(js)
self.battery = POWER.get(sdl.SDL_JoystickCurrentPowerLevel(js), "?")
if hasattr(sdl, "SDL_GameControllerGetSerial"):
s = sdl.SDL_GameControllerGetSerial(self.handle)
self.serial = s.decode(errors="replace") if s else None
devpath = None
if hasattr(sdl, "SDL_JoystickPathForIndex"):
p = sdl.SDL_JoystickPathForIndex(index)
devpath = p.decode(errors="replace") if p else None
self.mac = self.serial or sysfs_uniq(devpath)
if self.battery == "?":
self.battery = sysfs_battery(self.mac) # None when truly unknown
self.slot = None # 1..4 once assigned
self.nickname = None
self.can_rumble = None # None until we've actually tried
self.held = set() # SDL button ids currently down
self.axes = {} # axis id -> raw -32768..32767
self.display = None # filled in by label_pads()
self.real = None # the physical device behind a virtual pad
# A/B and X/Y always move together β no real controller mirrors one
# pair without the other β so this is a single setting.
self.swap_faces = False
@property
def store_key(self):
"""Where this pad's settings are remembered.
Prefer the physical device's MAC once we have identified it: Steam's
virtual pads are reassigned between sessions, so a CRC-keyed record
can end up attached to the wrong controller.
"""
if self.real and self.real.get("mac"):
return self.real["mac"]
return self.key
@property
def key(self):
"""Stable identity across sessions.
A MAC when the pad exposes one. Steam's virtual pads don't, but they
do carry a distinct name-CRC that phase0 confirmed is stable across
reboots and launch contexts, so that is the fallback.
"""
if self.mac:
return self.mac.lower().replace("-", ":")
return f"crc:{self.name_crc:04x}"
@property
def label(self):
return self.display or friendly_name(self)
def attached(self):
"""False once the pad is really gone β a slept Bluetooth pad can sit in
SDL's list looking alive, and rumble keeps returning success on it."""
if not self.handle:
return False
return bool(self.sdl.SDL_GameControllerGetAttached(self.handle))
@property
def ryujinx_id(self):
return f"{self.index}-{self.guid}"
def rumble(self, strength, duration_ms):
"""Buzz the pad. Returns False if this controller can't rumble."""
if not self.handle or not hasattr(self.sdl, "SDL_GameControllerRumble"):
return False
ok = self.sdl.SDL_GameControllerRumble(
self.handle, strength, strength, duration_ms) == 0
if duration_ms:
self.can_rumble = ok
return ok
def close(self):
if self.handle:
self.rumble(0, 0) # never leave a pad buzzing behind us
self.sdl.SDL_GameControllerClose(self.handle)
self.handle = None
class _Shim:
"""Just enough of a Pad for friendly_name() to work on a raw device."""
def __init__(self, **kw):
self.__dict__.update(kw)
self.nickname = None
def scan_real_gamepads():
"""The physical controllers, including ones Steam Input hides from SDL.
Steam does not remove a controller it takes over β it only sets
SDL_GAMECONTROLLER_IGNORE_DEVICES so the *game's* SDL skips it. The kernel
device is still there with its real name and MAC, which is the only
durable identity available once Steam is in the way.
"""
import glob
out = []
for base in sorted(glob.glob("/sys/class/input/event*"),
key=lambda q: int(os.path.basename(q)[5:])):
node = os.path.basename(base)
dev = f"{base}/device"
caps = sysfs_read(f"{dev}/capabilities/key")
if not caps:
continue
words = caps.split()[::-1] # sysfs prints MSB group first
idx, off = 0x130 // 64, 0x130 % 64 # BTN_SOUTH marks a gamepad
try:
if idx >= len(words) or not (int(words[idx], 16) >> off & 1):
continue
except ValueError:
continue
if os.path.realpath(base).startswith("/sys/devices/virtual/input"):
continue # a uinput pad, not hardware
try:
ven = int(sysfs_read(f"{dev}/id/vendor") or "0", 16)
prod = int(sysfs_read(f"{dev}/id/product") or "0", 16)
except ValueError:
ven = prod = 0
if (ven, prod) == STEAM_VIRTUAL:
continue
out.append({"path": f"/dev/input/{node}",
"name": sysfs_read(f"{dev}/name") or node,
"mac": (sysfs_read(f"{dev}/uniq") or "").lower() or None,
"vendor": ven, "product": prod})
return out
class RealWatcher:
"""Correlates presses on the hidden physical pads with the virtual ones.
Steam's virtual pad carries nothing that points back at the hardware
driving it. But a button press fires on both within milliseconds, so
watching the real evdev nodes alongside SDL tells us which is which β and
hands back the real MAC, which is what makes settings stick across
sessions.
"""
WINDOW_MS = 250
def __init__(self):
self.fds = {}
self.recent = []
self.available = False
def open(self):
for info in scan_real_gamepads():
try:
self.fds[os.open(info["path"], os.O_RDONLY | os.O_NONBLOCK)] = info
except OSError:
pass
self.available = bool(self.fds)
return self.available
def poll(self, now):
if not self.fds:
return
try:
ready, _, _ = select.select(list(self.fds), [], [], 0)
except (OSError, ValueError):
return
for fd in ready:
try:
data = os.read(fd, 24 * 64)
except OSError:
continue
for off in range(0, len(data) - 23, 24):
_, _, etype, _, value = struct.unpack_from("qqHHi", data, off)
if etype == 1 and value == 1: # EV_KEY press
self.recent.append((now, self.fds[fd]))
self.recent = [(t, i) for t, i in self.recent
if now - t <= self.WINDOW_MS]
def claim(self, now, taken):
"""The single unclaimed real device that just fired, if unambiguous.
Two people pressing at the same instant would make the pairing a
guess, so that case is skipped rather than risking a wrong label.
"""
hits = [i for t, i in self.recent
if now - t <= self.WINDOW_MS and i["path"] not in taken]
if not hits:
return None
paths = {i["path"] for i in hits}
return hits[-1] if len(paths) == 1 else None
def close(self):
for fd in self.fds:
try:
os.close(fd)
except OSError:
pass
self.fds.clear()
def scan_pads(sdl):
"""Returns (pads, unmapped).
SDL only reports a device as a game controller when it has a button
mapping for it. Anything else is a bare joystick we cannot interpret β
reported separately so an unsupported pad shows up as an explanation
rather than as nothing at all.
"""
pads, unmapped = [], []
for i in range(sdl.SDL_NumJoysticks()):
if sdl.SDL_IsGameController(i):
pads.append(Pad(sdl, i))
else:
name = sdl.SDL_JoystickNameForIndex(i)
unmapped.append(name.decode(errors="replace") if name
else f"device {i}")
return pads, unmapped
# ------------------------------------------------------------------- state
def load_json(path, default):
try:
with open(path) as fh:
return json.load(fh)
except (OSError, json.JSONDecodeError):
return default
def save_known(known):
os.makedirs(STATE_DIR, exist_ok=True)
tmp = KNOWN_PADS + ".tmp"
with open(tmp, "w") as fh:
json.dump(known, fh, indent=2, sort_keys=True)
os.replace(tmp, KNOWN_PADS)
def is_hardware_key(key):
"""True when a key identifies a physical controller.
A MAC belongs to one piece of hardware forever. A `crc:` key only names a
Steam virtual pad slot, and Steam moves controllers between slots between
sessions β so a preference stored against one can resurface on somebody
else's pad.
"""
return bool(key) and not key.startswith("crc:")
def apply_known(pads, known):
for p in pads:
rec = known.get(p.store_key)
if rec:
# Records without a schema marker predate friendly labels, and
# their `nickname` was auto-filled with whatever SDL happened to
# report that run β which would override the real label forever.
# Only honour a nickname from a record that knows what one means.
p.nickname = rec.get("nickname") if rec.get("schema", 0) >= 2 else None
# swap_faces used to mean "flip whatever the template held"; it now
# means "write the mirrored mapping". Old values invert in effect,
# so anything below schema 3 starts from the default. And it is
# only trusted from a hardware-keyed record β see is_hardware_key.
p.swap_faces = (bool(rec.get("swap_faces"))
if rec.get("schema", 0) >= 3
and is_hardware_key(p.store_key) else False)
def remember(pads, known):
for p in pads:
if p.slot:
known[p.store_key] = {
"schema": 3,
# Left null so the label stays automatic; set it by hand in
# this file to override.
"nickname": p.nickname,
"guid": p.guid,
"name": p.name,
# The physical device, so a mis-pairing is visible in the file
# rather than hidden behind a virtual pad's name.
"hardware": p.real["name"] if p.real else None,
"detected_as": p.label,
# Only recorded against real hardware. Saving it under a
# virtual-pad slot would hand the setting to whichever
# controller Steam parks there next time.
"swap_faces": p.swap_faces if is_hardware_key(p.store_key) else False,
"last_seen": time.strftime("%Y-%m-%dT%H:%M:%S"),
}
save_known(known)
RUMBLE_ON_MS = 320 # long enough to feel, short enough to stay crisp
RUMBLE_GAP_MS = 900 # silence between pads so the cycle reads as steps
RUMBLE_STRENGTH = 0xA000 # ~63%; a full-power buzz is startling in the hand
class RumbleCycle:
"""Buzz each assigned pad in turn, forever, so everyone can feel which
player they are without pressing anything.
This is the answer to "whose controller is Player 2?" β the card lights up
at the same moment the pad in someone's hands vibrates.
"""
def __init__(self, sdl):
self.sdl = sdl
self.enabled = True
self.pos = 0
self.active = None # instance_id currently buzzing
self.next_at = 0
self.stop_at = 0
def update(self, pads):
now = self.sdl.SDL_GetTicks()
# Only pads that are genuinely still attached β buzzing a sleeping pad
# silently "succeeds" and lights its bay for a controller nobody holds.
targets = [p for p in sorted(pads, key=lambda q: q.slot)
if p.slot and p.attached()]
if not self.enabled or not targets:
self.active = None
return
if self.active is not None and now >= self.stop_at:
self.active = None
if now >= self.next_at:
pad = targets[self.pos % len(targets)]
pad.rumble(RUMBLE_STRENGTH, RUMBLE_ON_MS)
self.active = pad.instance_id
self.stop_at = now + RUMBLE_ON_MS
self.next_at = now + RUMBLE_ON_MS + RUMBLE_GAP_MS
self.pos = (self.pos + 1) % len(targets)
def new_slot_state():
return {"order": {}, "seq": 0, "present": set()}
def bind_real(pad, info, known, pads):
"""Attach a physical device to a virtual pad and re-read its settings.
The settings were loaded under the CRC key; now that the real MAC is
known, anything saved against it wins.
"""
pad.real = info
rec = known.get(pad.store_key)
if rec:
pad.nickname = rec.get("nickname") if rec.get("schema", 0) >= 2 else None
pad.swap_faces = (bool(rec.get("swap_faces"))
if rec.get("schema", 0) >= 3
and is_hardware_key(pad.store_key) else False)
label_pads(pads)
def resolve_slots(pads, st, claimed_p1=None):
"""Pack players into slots by wake order, contiguously.
A pad that goes away and comes back is treated as newly arrived and joins
at the end β it does not reclaim the slot it used to hold. Someone who
took over while it was asleep keeps their place, which is what everyone
in the room expects after a controller nods off mid-session.
A pad that has claimed P1 keeps it regardless of arrival order.
"""
for p in sorted(pads, key=lambda q: q.index):
if p.key not in st["present"]:
st["seq"] += 1
st["order"][p.key] = st["seq"]
st["present"] = {p.key for p in pads}
order = sorted(pads, key=lambda q: (0 if q.key == claimed_p1 else 1,
st["order"][q.key]))
for i, p in enumerate(order):
p.slot = i + 1 if i < MAX_PLAYERS else None
return order
# ------------------------------------------------------------ ryujinx config
EMU_ENUM = r"""
import ctypes, sys
sdl = ctypes.CDLL(sys.argv[1])
class G(ctypes.Structure):
_fields_ = [("d", ctypes.c_uint8 * 16)]
for h in (b"SDL_JOYSTICK_HIDAPI_STEAM", b"SDL_JOYSTICK_HIDAPI_STEAMDECK"):
sdl.SDL_SetHint(h, b"0")
sdl.SDL_Init(0x00000200 | 0x00002000)
sdl.SDL_JoystickGetDeviceGUID.restype = G
sdl.SDL_JoystickGetDeviceGUID.argtypes = [ctypes.c_int]
sdl.SDL_JoystickGetGUIDString.argtypes = [G, ctypes.c_char_p, ctypes.c_int]
sdl.SDL_JoystickNameForIndex.restype = ctypes.c_char_p
for i in range(sdl.SDL_NumJoysticks()):
b = ctypes.create_string_buffer(33)
sdl.SDL_JoystickGetGUIDString(sdl.SDL_JoystickGetDeviceGUID(i), b, 33)
n = sdl.SDL_JoystickNameForIndex(i)
print(i, b.value.decode(), (n or b"?").decode(errors="replace"), sep="\t")
sdl.SDL_Quit()
"""
def find_emulator_sdl():
"""Path to the libSDL2 Ryujinx actually links against.
This matters more than it looks. SDL changed the bus type it reports for
Bluetooth pads between 2.30 and 2.32, which lands in the GUID β the same
Stadia pad is ...-0000-0005-... under the system SDL and ...-0000-0003-...
under Ryujinx's bundled 2.30. Ids computed with the wrong SDL never match
and Ryujinx logs "No matching controllers found" while every pad works
perfectly in this tool.
"""
import glob
for root in ("/var/lib/flatpak/app", os.path.expanduser("~/.local/share/flatpak/app")):
for path in glob.glob(f"{root}/*yu*/*/*/*/files/bin/libSDL2*.so*"):
return path
return None
def emulator_gamepads():
"""(index, guid_hex, name) as Ryujinx's own SDL will see them.
Run in a throwaway subprocess: two libSDL2 builds share a SONAME, so
loading both in one process gets us whichever landed first β the UI keeps
the system SDL, this borrows the emulator's.
"""
lib = find_emulator_sdl()
if not lib:
return None
try:
out = subprocess.run([sys.executable, "-c", EMU_ENUM, lib],
capture_output=True, text=True, timeout=20)
except (subprocess.SubprocessError, OSError):
return None
if out.returncode != 0:
return None
rows = []
for line in out.stdout.splitlines():
bits = line.split("\t")
if len(bits) == 3 and bits[0].isdigit():
rows.append((int(bits[0]), bits[1], bits[2]))
return rows or None
def find_app_id():
if not shutil.which("flatpak"):
return DEFAULT_APP_ID
try:
out = subprocess.run(["flatpak", "list", "--app", "--columns=application"],
capture_output=True, text=True, timeout=15).stdout
for line in out.splitlines():
if "ryu" in line.lower():
return line.strip()
except (subprocess.SubprocessError, OSError):
pass
return DEFAULT_APP_ID
def find_config(app_id):
for path in (os.path.expanduser(f"~/.var/app/{app_id}/config/Ryujinx/Config.json"),
os.path.expanduser(
f"~/.var/app/{DEFAULT_APP_ID}/config/Ryujinx/Config.json"),
os.path.expanduser("~/.config/Ryujinx/Config.json")):
if os.path.isfile(path):
return path
return None
# A complete, standard SDL gamepad binding β used when the user's config has
# no gamepad entry to clone from, i.e. a fresh Ryujinx install. Field names and
# value spellings are taken verbatim from a real Ryujinx-written entry rather
# than guessed; the schema is undocumented.
DEFAULT_ENTRY = {
"left_joycon_stick": {"joystick": "Left", "invert_stick_x": False,
"invert_stick_y": False, "rotate90_cw": False,
"stick_button": "LeftStick"},
"right_joycon_stick": {"joystick": "Right", "invert_stick_x": False,
"invert_stick_y": False, "rotate90_cw": False,
"stick_button": "RightStick"},
"deadzone_left": 0.1,
"deadzone_right": 0.1,
"range_left": 1,
"range_right": 1,
"trigger_threshold": 0.5,
"motion": {"slot": 0, "alt_slot": 0, "mirror_input": False,
"dsu_server_host": None, "dsu_server_port": 0,
"motion_backend": "CemuHook", "sensitivity": 100,
"gyro_deadzone": 1, "enable_motion": True},
"rumble": {"strong_rumble": 1, "weak_rumble": 1, "enable_rumble": True},
"led": {"enable_led": False, "turn_off_led": False, "use_rainbow": False,
"led_color": 0},
"left_joycon": {"button_minus": "Back", "button_l": "LeftShoulder",
"button_zl": "LeftTrigger",
"button_sl": "SingleLeftTrigger0",
"button_sr": "SingleRightTrigger0",
"dpad_up": "DpadUp", "dpad_down": "DpadDown",
"dpad_left": "DpadLeft", "dpad_right": "DpadRight"},
"right_joycon": {"button_plus": "Start", "button_r": "RightShoulder",
"button_zr": "RightTrigger",
"button_sl": "SingleLeftTrigger1",
"button_sr": "SingleRightTrigger1",
"button_x": "X", "button_b": "B",
"button_y": "Y", "button_a": "A"},
"version": 1,
"backend": "GamepadSDL2",
"id": "",
"name": "",
"controller_type": "ProController",
"player_index": "Player1",
}
def pick_template(entries, pad):
"""Reuse the user's own button maps rather than inventing any.
Prefer an entry already written for this exact controller; otherwise any
SDL gamepad entry. Ryujinx stores SDL's normalised button names, so a map
from one gamepad transfers cleanly to another.
"""
for e in entries:
eid = e.get("id", "")
if "-" in eid and eid.split("-", 1)[1] == pad.guid:
return copy.deepcopy(e)
for e in entries:
if e.get("backend") == "GamepadSDL2":
return copy.deepcopy(e)
# Nothing to clone β a fresh Ryujinx install. Everything except the face
# buttons comes from the template, so without this the tool could not
# write a usable entry at all.
return copy.deepcopy(DEFAULT_ENTRY)
# Confirmed against a real GamepadSDL2 entry: Ryujinx names face buttons with
# SDL's own letters, so the identity mapping is literally what-you-see-is-what
# -you-get β press the button marked A, the game receives A.
FACE_IDENTITY = {"button_a": "A", "button_b": "B",
"button_x": "X", "button_y": "Y"}
FACE_MIRRORED = {"button_a": "B", "button_b": "A",
"button_x": "Y", "button_y": "X"}
# Every binding a gamepad entry must actually have. SL/SR are left out: they
# are Joy-Con rail buttons and are legitimately unbound on anything else.
REQUIRED_BINDINGS = {
"left_joycon_stick": ("joystick", "stick_button"),
"right_joycon_stick": ("joystick", "stick_button"),
"left_joycon": ("button_minus", "button_l", "button_zl",
"dpad_up", "dpad_down", "dpad_left", "dpad_right"),
"right_joycon": ("button_plus", "button_r", "button_zr",
"button_a", "button_b", "button_x", "button_y"),
}
def missing_bindings(entry):
"""Bindings that are absent, blank or explicitly Unbound.
The tool reads sticks and buttons through SDL, so they look fine on screen
whatever the config says β but only the face mapping is written from
scratch. Everything else is copied from the existing entry, so a gap there
is invisible until the game starts and half a controller does nothing.
"""
gaps = []
for section, keys in REQUIRED_BINDINGS.items():
block = entry.get(section)
if not isinstance(block, dict):
gaps.extend(f"{section}.{k}" for k in keys)
continue
for key in keys:
value = block.get(key)
if value in (None, "", "Unbound"):
gaps.append(f"{section}.{key}")
return gaps
def repair_entry(entry):
"""Fill any gap from the known-good defaults. Returns what was repaired."""
repaired = []
for name in missing_bindings(entry):
section, key = name.split(".", 1)
entry.setdefault(section, {})[key] = DEFAULT_ENTRY[section][key]
repaired.append(name)
return repaired
def config_binding_gaps(cfg_path):
"""Gaps in the config we would be cloning from, for warning up front."""
data = load_json(cfg_path, None) if cfg_path else None
if not data:
return []
for entry in data.get("input_config") or []:
if entry.get("backend") == "GamepadSDL2":
return missing_bindings(entry)
return []
def apply_face_mapping(entry, pad):
"""Write the face mapping outright rather than swapping what was there.
Swapping depends on the template being in a known state; setting it
guarantees the result whatever we cloned from.
"""
rj = entry.get("right_joycon")
if not isinstance(rj, dict):
return
for key, value in (FACE_MIRRORED if pad.swap_faces else FACE_IDENTITY).items():
if key in rj:
rj[key] = value
def emulator_id_for(pad, rows, used):
"""Match one of our pads to the emulator's enumeration.
Vendor and product survive the SDL version difference even though the bus
byte does not, so they are what we match on; identical models are matched
in order.
"""
if rows is None:
return None
# Prefer an exact name-CRC hit. Steam's virtual pads all share one
# vendor/product, so vendor alone cannot separate them β but the CRC is
# per-device and, unlike the bus byte, agrees across SDL versions.
for want_crc in (True, False):
for idx, guid_hex, _ in rows:
if (idx, guid_hex) in used:
continue
if guid_vendor_product(guid_hex) != (pad.vendor, pad.product):
continue
if want_crc and guid_name_crc(guid_hex) != pad.name_crc:
continue
used.add((idx, guid_hex))
return f"{idx}-{ryujinx_guid(guid_hex)}"
return None
def build_entries(existing, pads, rows=None):
out, problems = [], []
used = set()
for p in sorted((q for q in pads if q.slot), key=lambda q: q.slot):
tpl = pick_template(existing, p)
tpl["id"] = emulator_id_for(p, rows, used) or p.ryujinx_id
tpl["player_index"] = f"Player{p.slot}"
tpl["backend"] = "GamepadSDL2"
if "name" in tpl:
tpl["name"] = p.label # what Ryujinx's own input UI shows
apply_face_mapping(tpl, p)
# The face mapping is authored; the rest is inherited. Patch any hole
# in what was inherited rather than shipping a half-dead controller.
repaired = repair_entry(tpl)
if repaired:
print(f"repaired for {p.label}: {', '.join(repaired)}", flush=True)
out.append(tpl)
ids = [e["id"] for e in out]
for i in set(ids):
if ids.count(i) > 1:
problems.append(f"duplicate id would be written: {i}")
if out and not any(e["player_index"] == "Player1" for e in out):
problems.append("nothing assigned to Player 1 β no controller would work")
return out, problems
def write_config(cfg_path, pads):
data = load_json(cfg_path, None)
if data is None:
return ["cannot read Config.json"]
rows = emulator_gamepads()
if rows is None:
problems_pre = ["Could not read the emulator's own SDL β ids may not "
"match. Is Ryujinx installed as a flatpak?"]
else:
problems_pre = []
entries, problems = build_entries(data.get("input_config") or [], pads, rows)
problems = problems_pre + problems
if problems:
return problems
if not entries:
return ["no controllers assigned"]
os.makedirs(BACKUP_DIR, exist_ok=True)
shutil.copy2(cfg_path, os.path.join(
BACKUP_DIR, f"Config.{time.strftime('%Y%m%d-%H%M%S')}.json"))
data["input_config"] = entries
tmp = cfg_path + ".preflight.tmp"
with open(tmp, "w") as fh:
json.dump(data, fh, indent=2)
os.replace(tmp, cfg_path)
return []
# ----------------------------------------------------------------- screens
def swap_icon(ui, cx, cy, size, color):
"""Two arrows trading places β shown on a pad whose A/B and X/Y are
mirrored, so a non-default mapping is never invisible."""
span, th, head = size * 0.62, size * 0.17, size * 0.20
for sign in (-1, 1): # -1 top row, +1 bottom row
y = cy + sign * size * 0.26
if sign < 0: # top arrow points right
ui.rect(cx - span / 2, y - th / 2, span * 0.72, th, color)
tip = cx + span / 2
ui.fill_triangle((tip - head, y - head * 0.8),