Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
feat(controllers): universal pad layer for native games and full mapping DB for Wine
raymondchinsb4ecfc5dd6dd
diff --git a/Makefile b/Makefileindex 58c5823..1a3610c 100644--- a/Makefile+++ b/Makefile@@ -65,7 +65,7 @@ DEPS := $(OBJS:.o=.d)overlay-shim-bench iconmaker icon \appinfo helpers-install ntdll-resolve bridge runcheck compatcheck \compatsvc-check scriptcheck envcheck buildcheck settingscheck routecheck bridgecheck gamedrivecheck \- gamefixescheck launchercheck launch-shell FORCE+ gamefixescheck launchercheck padcheck launch-shell FORCEAPP_PAYLOAD := app/Sources/NotProtonApp/Resources/payload@@ -125,6 +125,10 @@ gamefixescheck:@if [ ! -f dylib/tests/gamefixescheck.sh ]; then $(call SKIP,gamefixescheck,dylib/tests/gamefixescheck.sh); exit 0; fi; \sh dylib/tests/gamefixescheck.sh dylib/feats/compat_run.sh+padcheck:+ @if [ ! -f dylib/tests/padcheck.sh ]; then $(call SKIP,padcheck,dylib/tests/padcheck.sh); exit 0; fi; \+ sh dylib/tests/padcheck.sh dylib/feats/compat_run.sh+launchercheck:@if [ ! -f dylib/tests/launchercheck.sh ]; then $(call SKIP,launchercheck,dylib/tests/launchercheck.sh); exit 0; fi; \sh dylib/tests/launchercheck.sh dylib/feats/compat_run.shdiff --git a/dylib/feats/compat_run.sh b/dylib/feats/compat_run.shindex bbadafd..0555e67 100755--- a/dylib/feats/compat_run.sh+++ b/dylib/feats/compat_run.sh@@ -164,20 +164,58 @@ fiSDL_JOYSTICK_MFI=0export SDL_JOYSTICK_MFI-pad_db="$HOME/Library/Application Support/notproton/gamecontrollerdb.txt"-if [ -f "$pad_db" ]; then- pad_maps=$(sed -e '/^[[:space:]]*#/d' -e '/^[[:space:]]*$/d' "$pad_db")- if [ -n "$pad_maps" ]; then- if [ -n "$SDL_GAMECONTROLLERCONFIG" ]; then- SDL_GAMECONTROLLERCONFIG="$SDL_GAMECONTROLLERCONFIG-$pad_maps"+# The full database, gamecontrollerdb.merged.txt from scripts/update-gamecontrollerdb.sh+# (~90 KB), reaches SDL as a file: SDL_Init reads SDL_GAMECONTROLLERCONFIG_FILE (SDL 2.0.22+),+# then the variable's lines, which outrank the file's. Only the hand-written lines ride in+# the variable, which every Wine process inherits. A runner SDL without the hint gets the+# database in the variable instead. The variable keeps the last line per GUID, newest+# first, up to pad_cap bytes.+np_pad_mappings() {+ pad_db="$np_support/gamecontrollerdb.txt"+ pad_full="$np_support/gamecontrollerdb.merged.txt"+ pad_sdl="$CX_ROOT/lib/libSDL2-2.0.0.dylib"+ pad_cap=32768+ pad_env_src=""+ if [ -f "$pad_full" ] && [ -z "$SDL_GAMECONTROLLERCONFIG_FILE" ]; then+ if [ -f "$pad_sdl" ] && LC_ALL=C grep -q -a SDL_GAMECONTROLLERCONFIG_FILE "$pad_sdl" 2>/dev/null; then+ SDL_GAMECONTROLLERCONFIG_FILE="$pad_full"+ export SDL_GAMECONTROLLERCONFIG_FILE+ echo "controllers: mapping file $pad_full" >> "$log" 2>&1 || trueelse- SDL_GAMECONTROLLERCONFIG="$pad_maps"+ pad_env_src="$pad_full"+ echo "controllers: $pad_sdl lacks SDL_GAMECONTROLLERCONFIG_FILE, $pad_full goes in the environment (capped)" >> "$log" 2>&1 || truefi- export SDL_GAMECONTROLLERCONFIG- echo "controllers: $(printf '%s\n' "$pad_maps" | wc -l | tr -d ' ') mapping(s) from $pad_db" >> "$log" 2>&1 || truefi-fi+ [ -f "$pad_db" ] || pad_db=""+ [ -n "$pad_env_src$pad_db" ] || return 0+ # Last line per GUID, newest first until pad_cap bytes, printed in file order+ pad_maps=$(cat ${pad_env_src:+"$pad_env_src"} ${pad_db:+"$pad_db"} | tr -d '\r' \+ | sed -e '/^[[:space:]]*#/d' -e '/^[[:space:]]*$/d' \+ | awk -v cap="$pad_cap" '+ { line[NR] = $0 }+ END {+ for (i = NR; i >= 1; i--) {+ g = tolower(substr(line[i], 1, 32))+ if (g in seen) continue+ seen[g] = 1+ if (size + length(line[i]) + 1 > cap) { dropped++; continue }+ size += length(line[i]) + 1+ keep[i] = 1+ }+ for (i = 1; i <= NR; i++) if (i in keep) print line[i]+ if (dropped) printf "controllers: %d mapping(s) over the %d-byte cap dropped\n", dropped, cap > "/dev/stderr"+ }' 2>> "$log")+ [ -n "$pad_maps" ] || return 0+ if [ -n "$SDL_GAMECONTROLLERCONFIG" ]; then+ SDL_GAMECONTROLLERCONFIG="$SDL_GAMECONTROLLERCONFIG+$pad_maps"+ else+ SDL_GAMECONTROLLERCONFIG="$pad_maps"+ fi+ export SDL_GAMECONTROLLERCONFIG+ echo "controllers: $(printf '%s\n' "$pad_maps" | wc -l | tr -d ' ') mapping(s) in SDL_GAMECONTROLLERCONFIG from ${pad_env_src:+$pad_env_src }${pad_db}" >> "$log" 2>&1 || true+}+np_pad_mappings# Per-game fixes: the shipped gamefixes-default/<appid>.conf, then the user's# gamefixes/<appid>.conf, the later file winning per key. KEY=VALUE lines are checked@@ -2071,7 +2109,7 @@ elseecho "=== client staged no overlay renderer, overlay disabled ===" >> "$log" 2>&1 || truefiset -- --args "$shim_exe" "$@"-for name in $(env | sed -nE 's/^(CX_APPLEGPTK_LIBD3DSHARED_PATH|SDL_GAMECONTROLLERCONFIG|SDL_JOYSTICK_MFI|WINE_LARGE_ADDRESS_AWARE|WINE_CPU_TOPOLOGY|Steam[A-Za-z0-9]*|(CX_GRAPHICS|D3DM_|DXMT_|DXVK_|MVK_|VKD3D_|STAGING_|MTL_|ROSETTA_)[A-Z0-9_]*)=.*/\1/p'); do+for name in $(env | sed -nE 's/^(CX_APPLEGPTK_LIBD3DSHARED_PATH|SDL_GAMECONTROLLERCONFIG(_FILE)?|SDL_JOYSTICK_MFI|WINE_LARGE_ADDRESS_AWARE|WINE_CPU_TOPOLOGY|Steam[A-Za-z0-9]*|(CX_GRAPHICS|D3DM_|DXMT_|DXVK_|MVK_|VKD3D_|STAGING_|MTL_|ROSETTA_)[A-Z0-9_]*)=.*/\1/p'); doeval "value=\$$name"# shellcheck disable=SC2154 # eval assigns value on the line aboveset -- --env "$name=$value" "$@"diff --git a/dylib/tests/padcheck.sh b/dylib/tests/padcheck.shnew file mode 100644index 0000000..1f87831--- /dev/null+++ b/dylib/tests/padcheck.sh@@ -0,0 +1,177 @@+#!/bin/sh+# Controller mappings: the run script's np_pad_mappings block and+# scripts/update-gamecontrollerdb.sh.+# shellcheck disable=SC2016,SC2034 # sed patterns match literal shell text; the eval'd block reads the case variables+set -e+SRC="${1:-$(dirname "$0")/../feats/compat_run.sh}"+UPDATE="${2:-$(dirname "$0")/../../scripts/update-gamecontrollerdb.sh}"+[ -f "$SRC" ] || { echo "padcheck: $SRC not present, skipped"; exit 0; }++block=$(sed -n '/^np_pad_mappings() {$/,/^}$/p' "$SRC")+forward=$(sed -n '/^for name in $(env /,/^done$/p' "$SRC")+[ -n "$block" ] || { echo "FAIL: np_pad_mappings not found in $SRC"; exit 1; }+[ -n "$forward" ] || { echo "FAIL: the launcher environment loop not found in $SRC"; exit 1; }++fails=0+ok() { printf ' ok %s\n' "$1"; }+bad() { printf ' FAIL %s\n want [%s]\n got [%s]\n' "$1" "$2" "$3"; fails=$((fails + 1)); }+is() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1" "$2" "$3"; fi; }++work=$(mktemp -d)+trap 'rm -rf "$work"' EXIT++g1=03000000373500002210000000010000+g2=0300000037350000221000001b010000+g3=030000005e0400008e02000000000000+own1="$g1,Own Dongle,a:b0,b:b1,platform:Mac OS X,"+own2="$g2,Own Bluetooth,a:b0,b:b1,platform:Mac OS X,"+full_g1="$g1,Community Dongle,a:b1,b:b0,platform:Mac OS X,"+full_g3="$g3,Community Pad,a:b0,b:b1,platform:Mac OS X,"++# case NAME: runs the block in a subshell against $work/NAME (support dir and runner);+# leaves FILE, ENV and the log in $work/NAME.+case_dir=""+new_case() {+ case_dir="$work/$1"+ mkdir -p "$case_dir/support" "$case_dir/runner/lib"+ : > "$case_dir/log"+}+sdl_with_hint() { printf 'xx\0SDL_GAMECONTROLLERCONFIG_FILE\0yy' > "$case_dir/runner/lib/libSDL2-2.0.0.dylib"; }+sdl_without_hint() { printf 'xx\0SDL_GAMECONTROLLERCONFIG\0yy' > "$case_dir/runner/lib/libSDL2-2.0.0.dylib"; }+run_block() {+ (+ np_support="$case_dir/support"+ CX_ROOT="$case_dir/runner"+ log="$case_dir/log"+ eval "$block"+ np_pad_mappings+ printf '%s' "${SDL_GAMECONTROLLERCONFIG_FILE-<unset>}" > "$case_dir/FILE"+ printf '%s' "${SDL_GAMECONTROLLERCONFIG-<unset>}" > "$case_dir/ENV"+ )+}+got_file() { cat "$case_dir/FILE"; }+got_env() { cat "$case_dir/ENV"; }++unset SDL_GAMECONTROLLERCONFIG SDL_GAMECONTROLLERCONFIG_FILE++echo "== run script: no mapping files =="+new_case none+sdl_with_hint+run_block+is "file hint unset" "<unset>" "$(got_file)"+is "variable unset" "<unset>" "$(got_env)"++echo "== run script: own lines only =="+new_case own+sdl_with_hint+printf '# comment\n\n%s\r\n%s\n' "$own1" "$own2" > "$case_dir/support/gamecontrollerdb.txt"+run_block+is "file hint unset without the merged file" "<unset>" "$(got_file)"+is "own lines in the variable, comments and CR gone" "$own1+$own2" "$(got_env)"++echo "== run script: merged file and an SDL with the hint =="+new_case hint+sdl_with_hint+printf '%s\n' "$own1" > "$case_dir/support/gamecontrollerdb.txt"+printf '# header\n%s\n%s\n%s\n' "$full_g1" "$full_g3" "$own1" > "$case_dir/support/gamecontrollerdb.merged.txt"+run_block+is "file hint names the merged file" "$case_dir/support/gamecontrollerdb.merged.txt" "$(got_file)"+is "only own lines in the variable" "$own1" "$(got_env)"++echo "== run script: merged file and an SDL without the hint =="+new_case nohint+sdl_without_hint+printf '%s\n' "$own1" > "$case_dir/support/gamecontrollerdb.txt"+printf '# header\n%s\n%s\n' "$full_g1" "$full_g3" > "$case_dir/support/gamecontrollerdb.merged.txt"+run_block+is "file hint unset" "<unset>" "$(got_file)"+is "database in the variable, own line replaces the community one" "$full_g3+$own1" "$(got_env)"++echo "== run script: no runner SDL counts as no hint =="+new_case nosdl+printf '%s\n' "$full_g3" > "$case_dir/support/gamecontrollerdb.merged.txt"+run_block+is "file hint unset" "<unset>" "$(got_file)"+is "database in the variable" "$full_g3" "$(got_env)"++echo "== run script: the variable is capped, the last lines kept =="+new_case cap+sdl_without_hint+i=0+while [ $i -lt 600 ]; do+ printf '03000000%08x0000000000000000,Pad %d,a:b0,b:b1,x:b2,y:b3,platform:Mac OS X,\n' "$i" "$i"+ i=$((i + 1))+done > "$case_dir/support/gamecontrollerdb.merged.txt"+printf '%s\n' "$own2" > "$case_dir/support/gamecontrollerdb.txt"+run_block+size=$(got_env | wc -c | tr -d ' ')+if [ "$size" -le 32768 ] && [ "$size" -gt 30000 ]; then ok "variable holds $size bytes, at most 32768"; else bad "variable size" "30000..32768" "$size"; fi+is "own line kept last" "$own2" "$(got_env | tail -n 1)"+is "oldest community line dropped" "" "$(got_env | grep ',Pad 0,' || true)"+if grep -q 'over the 32768-byte cap dropped' "$case_dir/log"; then ok "drop logged"; else bad "drop logged" "a cap line" "$(cat "$case_dir/log")"; fi++echo "== run script: values from the launch options are kept =="+new_case user+sdl_with_hint+printf '%s\n' "$own1" > "$case_dir/support/gamecontrollerdb.txt"+printf '%s\n' "$full_g3" > "$case_dir/support/gamecontrollerdb.merged.txt"+SDL_GAMECONTROLLERCONFIG_FILE=/user/db.txt SDL_GAMECONTROLLERCONFIG="$own2" run_block+unset SDL_GAMECONTROLLERCONFIG SDL_GAMECONTROLLERCONFIG_FILE+is "user file hint kept" "/user/db.txt" "$(got_file)"+is "user variable first, own lines after" "$own2+$own1" "$(got_env)"++echo "== run script: the launcher forwards the file hint =="+(+ SDL_GAMECONTROLLERCONFIG_FILE="/a b/gamecontrollerdb.merged.txt"+ export SDL_GAMECONTROLLERCONFIG_FILE+ set --+ eval "$forward"+ for arg in "$@"; do+ case "$arg" in SDL_GAMECONTROLLERCONFIG_FILE=*) printf '%s' "${arg#*=}" ;; esac+ done+) > "$work/forwarded"+is "SDL_GAMECONTROLLERCONFIG_FILE passed as one argument" "/a b/gamecontrollerdb.merged.txt" "$(cat "$work/forwarded")"++if [ -f "$UPDATE" ]; then+ echo "== update-gamecontrollerdb.sh =="+ db="$work/community.txt"+ {+ echo "# Mac OS X"+ echo "$full_g1"+ printf '%s\r\n' "$full_g3"+ echo "$g3,Windows Pad,a:b0,platform:Windows,"+ echo "$g2,Linux Pad,a:b0,platform:Linux,"+ echo "not a mapping,platform:Mac OS X,"+ } > "$db"+ own="$work/own.txt"+ {+ echo "# mine"+ echo "$own1"+ echo "$g2,Own Bluetooth,a:b0,b:b1"+ echo "$g3,Own Linux,a:b0,platform:Linux,"+ } > "$own"++ if sh "$UPDATE" > "$work/usage.out" 2>&1; then status=0; else status=$?; fi+ is "no OUTPUT prints usage and fails" "2" "$status"++ out="$work/out/merged.txt"+ sh "$UPDATE" "$out" --db "$db" --own "$own" > "$work/update.out" 2> "$work/update.err"+ is "three header comments" "3" "$(grep -c '^#' "$out")"+ is "Mac lines, own lines last, last per GUID" "$full_g3+$own1+$g2,Own Bluetooth,a:b0,b:b1,platform:Mac OS X," "$(grep -v '^#' "$out")"+ if grep -q 'skipped non-Mac line' "$work/update.err"; then ok "own non-Mac line reported"; else bad "own non-Mac line reported" "a skip line" "$(cat "$work/update.err")"; fi+ is "no CR left" "" "$(tr -d -c '\r' < "$out")"+ is "file readable by others" "-rw-r--r--" "$(stat -f %Sp "$out")"+ is "nothing else left in the output directory" "merged.txt" "$(ls -A "$work/out")"+fi++if [ "$fails" -eq 0 ]; then+ echo "==> padcheck: all assertions hold"+else+ echo "==> padcheck: $fails failed"+ exit 1+fidiff --git a/native-shim/.gitignore b/native-shim/.gitignoreindex e5d0467..8a38e2e 100644--- a/native-shim/.gitignore+++ b/native-shim/.gitignore@@ -1 +1,2 @@*.dylib+out/diff --git a/native-shim/build.sh b/native-shim/build.shnew file mode 100755index 0000000..c69efe5--- /dev/null+++ b/native-shim/build.sh@@ -0,0 +1,51 @@+#!/bin/bash+# Builds libnp_gamepad.dylib (universal arm64 + x86_64: most native games run under+# Rosetta) into native-shim/out/ and ad-hoc signs it.+# Env: NP_MIN_MACOS sets -mmacosx-version-min (default: the compiler's default).+set -euo pipefail++here="$(cd "$(dirname "$0")" && pwd)"+out="$here/out"+obj="$out/obj"+lib="$out/libnp_gamepad.dylib"+arches=(-arch arm64 -arch x86_64)+cflags=(-O2 -Wall -Werror -I"$here" "${arches[@]}")+[ -n "${NP_MIN_MACOS:-}" ] && cflags+=(-mmacosx-version-min="$NP_MIN_MACOS")++mkdir -p "$obj"+rm -f "$obj"/*.o++objects=()+compile() { # source, extra flags...+ local src="$1"; shift+ local o="$obj/$(basename "${src%.*}").o"+ if ! clang "${cflags[@]}" "$@" -c "$here/$src" -o "$o"; then+ echo "build.sh: FAILED compiling $src" >&2+ exit 1+ fi+ objects+=("$o")+}++for src in gamepad_shim.c hid_profile.c; do+ if [ ! -f "$here/$src" ]; then+ echo "build.sh: FAILED: $src is missing" >&2+ exit 1+ fi+done++compile gamepad_shim.c+compile hid_profile.c+if [ -f "$here/gc_virtual.m" ]; then+ compile gc_virtual.m -fobjc-arc+else+ echo "build.sh: warning: gc_virtual.m not found, building without the GameController path" >&2+fi++if ! clang -dynamiclib "${cflags[@]}" -o "$lib" "${objects[@]}" \+ -framework IOKit -framework CoreFoundation -framework Foundation \+ -framework GameController; then+ echo "build.sh: FAILED linking $lib (undefined np_* symbols mean hid_profile.c or gc_virtual.m is incomplete)" >&2+ exit 1+fi+codesign -s - -f "$lib"+echo "build.sh: built $lib ($(lipo -archs "$lib"))"diff --git a/native-shim/gamepad_shim.c b/native-shim/gamepad_shim.cindex 793f183..6164f53 100644--- a/native-shim/gamepad_shim.c+++ b/native-shim/gamepad_shim.c@@ -1,142 +1,635 @@-// Makes a Bluetooth GameSir G7 Pro usable in native macOS games that read pads through-// raw HID (Unity's Input System among them). Over Bluetooth the pad's primary usage is-// Consumer and its name is unknown to those games, so they skip it. Loaded with-// DYLD_INSERT_LIBRARIES, this presents the pad as an Xbox Wireless Controller and-// rewrites its gamepad report (ID 7) into the Xbox Bluetooth report layout. The button-// bits already match Xbox's; sticks, triggers and the hat differ.+// Makes game controllers that native macOS games do not recognise usable in games that+// read pads through raw HID (Unity's Input System, Rewired, SDL among them). Loaded with+// DYLD_INSERT_LIBRARIES (as part of libnp_gamepad.dylib), this presents every pad that+// np_profile_create() accepts as an Xbox Wireless Controller (Bluetooth, 045E:0B13) and+// rewrites its input reports into the 18-byte Xbox Bluetooth report layout.//-// Build: clang -arch arm64 -arch x86_64 -dynamiclib -O2 -framework IOKit-// -framework CoreFoundation -o libnp_gamepad.dylib gamepad_shim.c+// Origin: the first version handled one Bluetooth GameSir G7 Pro (3537:1022). Over+// Bluetooth that pad's primary usage is Consumer and its name is unknown to those games,+// so they skipped it. The lessons from it apply to every pad and are kept below:+// - Unity identifies the pad only through IOHIDDeviceGetProperty, so spoofing the+// product, manufacturer, vendor/product IDs and primary usage there is enough.+// - Unity sizes its report buffer from MaxInputReportSize; the pad's own (11 for the+// GameSir) would cut the translated report off before the hat and the buttons, so it+// is spoofed to NP_XBOX_REPORT_LEN.+// - Games that match on primary usage are never handed a pad whose primary usage is not+// Gamepad, so device matching is extended (here: by DeviceUsagePairs).+// - Interposed calls made from inside this dylib (hid_profile.c, gc_virtual.m and the+// replacements below) reach the real IOKit functions: dyld does not redirect the+// interposing image's own calls. That is what lets the replacements call the original.+//+// Game code only: dyld interposing also redirects calls made by Apple's frameworks.+// SDL 2.32+/SDL3 ask [GCController supportsHIDDevice:] about every HID device; if+// GameController.framework saw a spoofed 045E:0B13 it could claim the pad and SDL would+// drop it. So every replacement checks its caller (return address + dladdr, cached per+// call site) and passes calls from /System/ and /usr/lib/ images through untouched. A+// caller dladdr cannot place (JIT code: Mono/IL2CPP P/Invoke) counts as game code.+// Limit: a game function that tail-calls an IOHID function from a callback the system+// invoked would look like a system caller; no known game does that.+//+// dlsym: Rewired (Superliminal, Broforce) reaches IOKit through P/Invoke, which resolves+// functions with dlsym, so __interpose never sees those calls. dlsym is interposed too and+// hands game callers our replacements for the hooked names. Because the real dlsym+// resolves RTLD_NEXT/RTLD_SELF relative to its caller (which would now be this dylib),+// those two handles are resolved here relative to the real caller's image.+//+// Lifetime: every device this file has looked at is cached with a CFRetain, so its+// address cannot be reused by a new device while the entry exists (no ABA when a pad+// disconnects and another connects). Entries go away when a manager reports the device+// removed (IOHIDManagerRegisterDeviceRemovalCallback is wrapped), or are pruned when their+// service has left the IORegistry. Pads and their relays live in a static table that is+// never freed; a relay checks that the report's sender is still the pad in its slot, so a+// late report after removal is dropped, never sent through freed memory.+//+// Known limitation: games that read element values instead of input reports+// (IOHIDDeviceCopyMatchingElements, IOHIDDeviceRegisterInputValueCallback,+// IOHIDDeviceGetValue, IOHIDQueue) see the pad's real elements under the spoofed Xbox+// identity. Unity reads reports, so this is not handled yet. Polled reports+// (IOHIDDeviceGetReport) are not translated either.#include <CoreFoundation/CoreFoundation.h>+#include <IOKit/IOKitLib.h>#include <IOKit/hid/IOHIDLib.h>+#include <dlfcn.h>+#include <mach-o/dyld.h>+#include <pthread.h>+#include <stdint.h>+#include <stdio.h>#include <stdlib.h>#include <string.h>-#define GS_VENDOR 0x3537-#define GS_PRODUCT 0x1022+#include "np_pad.h"+#define XB_VENDOR 0x045E#define XB_PRODUCT 0x0B13-#define GS_PAD_REPORT 7-#define XB_REPORT_LEN 18+#define XB_REPORT_ID 1++#define MAX_DEVICES 256 // every HID device a game asked about, profiled or not+#define MAX_PADS 16 // profiled devices+#define MAX_MANAGERS 32 // managers with a wrapped removal callback+#define MAX_CALLERS 512 // call-site cache (power of two)+// Our own buffer for the pad's raw reports; the game's is sized for the Xbox report.+#define RAW_MAX 1024#define INTERPOSE(replacement, original) \__attribute__((used)) static struct { const void *r; const void *o; } \interpose_##original __attribute__((section("__DATA,__interpose"))) = \{ (const void *)(unsigned long)&replacement, (const void *)(unsigned long)&original };-static int number_property(IOHIDDeviceRef device, CFStringRef key) {- CFTypeRef value = IOHIDDeviceGetProperty(device, key);- int out = -1;- if (value && CFGetTypeID(value) == CFNumberGetTypeID())- CFNumberGetValue((CFNumberRef)value, kCFNumberIntType, &out);- return out;-}+#define CALLER __builtin_extract_return_addr(__builtin_return_address(0))-static int is_bluetooth_gamesir(IOHIDDeviceRef device) {- if (!device || number_property(device, CFSTR(kIOHIDVendorIDKey)) != GS_VENDOR ||- number_property(device, CFSTR(kIOHIDProductIDKey)) != GS_PRODUCT)- return 0;- CFTypeRef transport = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDTransportKey));- return transport && CFGetTypeID(transport) == CFStringGetTypeID() &&- CFStringCompare((CFStringRef)transport, CFSTR("Bluetooth"), 0) == kCFCompareEqualTo;-}+struct pad {+ IOHIDDeviceRef device; // NULL = free slot; not retained (struct dev holds it)+ np_profile *profile;+ np_pad_state state;+ IOHIDReportCallback cb;+ void *ctx;+ IOHIDReportWithTimeStampCallback cb_ts;+ void *ctx_ts;+ uint8_t out[NP_XBOX_REPORT_LEN];+ uint8_t out_ts[NP_XBOX_REPORT_LEN];+ uint8_t raw[RAW_MAX];+ uint8_t raw_ts[RAW_MAX];+};++struct dev {+ IOHIDDeviceRef device; // retained; NULL = free slot+ struct pad *pad; // NULL = not a pad we translate+};++struct manager_slot {+ IOHIDManagerRef manager; // not retained; only compared+ IOHIDDeviceCallback cb;+ void *ctx;+};++struct caller {+ const void *address; // call site; NULL = empty+ int system;+};++static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;+static pthread_mutex_t callers_lock = PTHREAD_MUTEX_INITIALIZER;+static struct dev devs[MAX_DEVICES];+static struct pad pads[MAX_PADS];+static struct manager_slot managers[MAX_MANAGERS];+static struct caller callers[MAX_CALLERS];++static pthread_once_t init_once = PTHREAD_ONCE_INIT;+static int hid_on;+static int log_on;+static const char *mode_name = "off";+static CFNumberRef spoof_vendor, spoof_product, spoof_page, spoof_usage, spoof_size;static CFNumberRef make_number(int value) {return CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &value);}-static CFTypeRef np_IOHIDDeviceGetProperty(IOHIDDeviceRef device, CFStringRef key) {- if (!is_bluetooth_gamesir(device))+static void init(void) {+ int mode = np_pad_mode();+ hid_on = (mode & NP_MODE_HID) != 0;+ mode_name = (mode & NP_MODE_HID) ? ((mode & NP_MODE_GC) ? "both" : "hid")+ : ((mode & NP_MODE_GC) ? "gc" : "off");+ const char *log = getenv("NP_PAD_LOG");+ log_on = log && strcmp(log, "1") == 0;+ if (!hid_on) return;+ // Get rule: callers of IOHIDDeviceGetProperty do not release, so these live forever.+ spoof_vendor = make_number(XB_VENDOR);+ spoof_product = make_number(XB_PRODUCT);+ spoof_page = make_number(kHIDPage_GenericDesktop);+ spoof_usage = make_number(kHIDUsage_GD_GamePad);+ spoof_size = make_number(NP_XBOX_REPORT_LEN);+ if (!spoof_vendor || !spoof_product || !spoof_page || !spoof_usage || !spoof_size) {+ hid_on = 0; // cannot spoof safely; stay out of the way+ return;+ }+ np_db_load();+}++static int hid_mode(void) {+ pthread_once(&init_once, init);+ return hid_on;+}++// ---- Caller filter -----------------------------------------------------------------++static int system_path(const char *path) {+ return path && (strncmp(path, "/System/", 8) == 0 || strncmp(path, "/usr/lib/", 9) == 0);+}++// 1 when the call site belongs to an Apple framework or system library.+static int from_system(const void *address) {+ if (!address) return 0;+ unsigned slot = (unsigned)(((uintptr_t)address >> 2) * 2654435761u) & (MAX_CALLERS - 1);+ pthread_mutex_lock(&callers_lock);+ for (unsigned i = 0; i < 8; i++) {+ struct caller *c = &callers[(slot + i) & (MAX_CALLERS - 1)];+ if (c->address == address) {+ int system = c->system;+ pthread_mutex_unlock(&callers_lock);+ return system;+ }+ }+ pthread_mutex_unlock(&callers_lock);+ Dl_info info;+ int system = dladdr(address, &info) && system_path(info.dli_fname);+ pthread_mutex_lock(&callers_lock);+ for (unsigned i = 0; i < 8; i++) {+ struct caller *c = &callers[(slot + i) & (MAX_CALLERS - 1)];+ if (!c->address) {+ c->address = address;+ c->system = system;+ break;+ }+ }+ pthread_mutex_unlock(&callers_lock); // a full bucket just means no caching+ return system;+}++// HID mode is on and the call comes from game code.+static int serve(const void *caller) {+ return hid_mode() && !from_system(caller);+}++// ---- Device cache ------------------------------------------------------------------++// A cached device whose service has left the registry was unplugged without a removal+// callback reaching us.+static int device_gone(IOHIDDeviceRef device) {+ io_service_t service = IOHIDDeviceGetService(device);+ return service == MACH_PORT_NULL || !IORegistryEntryInPlane(service, kIOServicePlane);+}++// Unlinks a cache entry. Called with the lock held; the caller frees the profile and+// releases the device after unlocking, since neither may run under our lock.+static void unlink_dev(struct dev *d, np_profile **profile, IOHIDDeviceRef *device) {+ *profile = NULL;+ *device = d->device;+ if (d->pad) {+ *profile = d->pad->profile;+ // Neutralise the relay; the slot memory stays valid for late callbacks.+ d->pad->device = NULL;+ d->pad->profile = NULL;+ d->pad->cb = NULL;+ d->pad->ctx = NULL;+ d->pad->cb_ts = NULL;+ d->pad->ctx_ts = NULL;+ }+ d->device = NULL;+ d->pad = NULL;+}++static struct dev *find_dev(IOHIDDeviceRef device) {+ for (int i = 0; i < MAX_DEVICES; i++)+ if (devs[i].device == device) return &devs[i];+ return NULL;+}++static void forget_device(IOHIDDeviceRef device) {+ np_profile *profile = NULL;+ IOHIDDeviceRef release = NULL;+ if (!device) return;+ pthread_mutex_lock(&lock);+ struct dev *d = find_dev(device);+ if (d) unlink_dev(d, &profile, &release);+ pthread_mutex_unlock(&lock);+ if (profile) np_profile_free(profile);+ if (release) CFRelease(release);+}++// Drops every entry whose device has gone. Called without the lock.+static void prune(void) {+ np_profile *profiles[MAX_DEVICES];+ IOHIDDeviceRef released[MAX_DEVICES];+ int n = 0;+ pthread_mutex_lock(&lock);+ for (int i = 0; i < MAX_DEVICES; i++)+ if (devs[i].device && device_gone(devs[i].device)) {+ unlink_dev(&devs[i], &profiles[n], &released[n]);+ n++;+ }+ pthread_mutex_unlock(&lock);+ for (int i = 0; i < n; i++) {+ if (profiles[i]) np_profile_free(profiles[i]);+ if (released[i]) CFRelease(released[i]);+ }+}++// The pad slot for a device we translate, creating the profile on first sight; NULL for+// every device we leave alone.+static struct pad *pad_for(IOHIDDeviceRef device) {+ if (!device || CFGetTypeID(device) != IOHIDDeviceGetTypeID()) return NULL;+ pthread_mutex_lock(&lock);+ struct dev *d = find_dev(device);+ struct pad *p = d ? d->pad : NULL;+ pthread_mutex_unlock(&lock);+ if (d) return p;++ // First sight: profile outside the lock (it reads the descriptor through IOKit).+ prune();+ np_profile *profile = np_profile_create(device);+ np_profile *discard = NULL;+ int logged = 0;+ pthread_mutex_lock(&lock);+ d = find_dev(device);+ p = NULL;+ if (d) { // another thread got there first+ p = d->pad;+ discard = profile;+ } else {+ for (int i = 0; i < MAX_DEVICES && !d; i++)+ if (!devs[i].device) d = &devs[i];+ if (!d) {+ discard = profile; // table full: leave the device alone+ } else {+ if (profile)+ for (int i = 0; i < MAX_PADS && !p; i++)+ if (!pads[i].device) p = &pads[i];+ if (profile && !p) discard = profile; // too many pads: leave it alone+ if (p) {+ memset(&p->state, 0, sizeof p->state);+ p->profile = profile;+ p->cb = NULL;+ p->ctx = NULL;+ p->cb_ts = NULL;+ p->ctx_ts = NULL;+ p->device = device;+ logged = log_on;+ }+ d->device = (IOHIDDeviceRef)CFRetain(device);+ d->pad = p;+ }+ }+ pthread_mutex_unlock(&lock);+ if (discard) np_profile_free(discard);+ if (logged) {+ // profile stays valid here: only removal frees it, after this device is gone.+ const char *guid = np_profile_guid(profile), *name = np_profile_name(profile);+ fprintf(stderr, "np_gamepad: %s \"%s\" -> Xbox Wireless Controller, mode=%s\n",+ guid ? guid : "?", name ? name : "?", mode_name);+ }+ return p;+}++// ---- Identity ----------------------------------------------------------------------++static CFTypeRef get_property(const void *caller, IOHIDDeviceRef device, CFStringRef key) {+ if (!key || !serve(caller) || !pad_for(device))return IOHIDDeviceGetProperty(device, key);- // Get rule: the caller does not release, so the spoofed values are made once.- static CFNumberRef vendor, product, page, usage, size;- if (!vendor) {- size = make_number(XB_REPORT_LEN);- vendor = make_number(XB_VENDOR);- product = make_number(XB_PRODUCT);- page = make_number(kHIDPage_GenericDesktop);- usage = make_number(kHIDUsage_GD_GamePad);- }- if (CFEqual(key, CFSTR(kIOHIDProductKey))) return CFSTR("Xbox Wireless Controller");- if (CFEqual(key, CFSTR(kIOHIDManufacturerKey))) return CFSTR("Microsoft");- if (CFEqual(key, CFSTR(kIOHIDVendorIDKey))) return vendor;- if (CFEqual(key, CFSTR(kIOHIDProductIDKey))) return product;- if (CFEqual(key, CFSTR(kIOHIDPrimaryUsagePageKey))) return page;- if (CFEqual(key, CFSTR(kIOHIDPrimaryUsageKey))) return usage;- // Callers size their report buffer from this; the pad's own 11 would cut the+ CFTypeRef spoof = NULL;+ if (CFEqual(key, CFSTR(kIOHIDProductKey))) spoof = CFSTR("Xbox Wireless Controller");+ else if (CFEqual(key, CFSTR(kIOHIDManufacturerKey))) spoof = CFSTR("Microsoft");+ else if (CFEqual(key, CFSTR(kIOHIDVendorIDKey))) spoof = spoof_vendor;+ else if (CFEqual(key, CFSTR(kIOHIDProductIDKey))) spoof = spoof_product;+ else if (CFEqual(key, CFSTR(kIOHIDPrimaryUsagePageKey))) spoof = spoof_page;+ else if (CFEqual(key, CFSTR(kIOHIDPrimaryUsageKey))) spoof = spoof_usage;+ // Callers size their report buffer from this; the pad's own value could cut the// translated report off before the hat and the buttons.- if (CFEqual(key, CFSTR(kIOHIDMaxInputReportSizeKey))) return size;- return IOHIDDeviceGetProperty(device, key);+ else if (CFEqual(key, CFSTR(kIOHIDMaxInputReportSizeKey))) spoof = spoof_size;+ return spoof ? spoof : IOHIDDeviceGetProperty(device, key);+}++static CFTypeRef np_IOHIDDeviceGetProperty(IOHIDDeviceRef device, CFStringRef key) {+ return get_property(CALLER, device, key);}INTERPOSE(np_IOHIDDeviceGetProperty, IOHIDDeviceGetProperty)-struct relay {- IOHIDReportCallback callback;- void *context;- uint8_t out[XB_REPORT_LEN];-};+// ---- Reports ------------------------------------------------------------------------static void put16(uint8_t *at, unsigned value) {- at[0] = value & 0xff;- at[1] = (value >> 8) & 0xff;+// Decodes one raw report into the slot's Xbox buffer. Returns the Xbox report, or NULL+// when the report is dropped. Fills the game's callback and context.+static uint8_t *translate(struct pad *p, void *sender, uint32_t reportID, const uint8_t *report,+ CFIndex length, int timestamped, void **callback, void **context) {+ uint8_t *out = NULL;+ pthread_mutex_lock(&lock);+ if (p->device && p->device == sender && p->profile && report && length > 0) {+ void *cb = timestamped ? (void *)p->cb_ts : (void *)p->cb;+ if (cb && np_profile_decode(p->profile, reportID, report, length, &p->state) == 1) {+ out = timestamped ? p->out_ts : p->out;+ np_xbox_encode(&p->state, out);+ *callback = cb;+ *context = timestamped ? p->ctx_ts : p->ctx;+ }+ }+ pthread_mutex_unlock(&lock);+ return out; // the game's callback runs without our lock held}-// GameSir report 7: [7, X, Y, Z, Rz, hat(low nibble, 0=up clockwise, >7 none),-// buttons lo, buttons hi, accel (right trigger), brake (left trigger), pad].-// Xbox: [1, LX16, LY16, RX16, RY16, LT10, RT10, hat(1=up clockwise, 0 none), buttons32].static void relay_report(void *context, IOReturn result, void *sender, IOHIDReportType type,uint32_t reportID, uint8_t *report, CFIndex length) {- struct relay *r = context;- if (reportID != GS_PAD_REPORT || length < 10) return;- uint8_t *x = r->out;- memset(x, 0, sizeof r->out);- x[0] = 1;- put16(x + 1, report[1] * 257u);- put16(x + 3, report[2] * 257u);- put16(x + 5, report[3] * 257u);- put16(x + 7, report[4] * 257u);- put16(x + 9, report[9] * 1023u / 255u);- put16(x + 11, report[8] * 1023u / 255u);- unsigned hat = report[5] & 0x0f;- x[13] = hat < 8 ? hat + 1 : 0;- x[14] = report[6];- x[15] = report[7];- r->callback(r->context, result, sender, type, 1, x, XB_REPORT_LEN);+ void *cb = NULL, *ctx = NULL;+ uint8_t *out = translate(context, sender, reportID, report, length, 0, &cb, &ctx);+ if (out)+ ((IOHIDReportCallback)cb)(ctx, result, sender, type, XB_REPORT_ID, out,+ NP_XBOX_REPORT_LEN);+}++static void relay_report_ts(void *context, IOReturn result, void *sender, IOHIDReportType type,+ uint32_t reportID, uint8_t *report, CFIndex length,+ uint64_t timeStamp) {+ void *cb = NULL, *ctx = NULL;+ uint8_t *out = translate(context, sender, reportID, report, length, 1, &cb, &ctx);+ if (out)+ ((IOHIDReportWithTimeStampCallback)cb)(ctx, result, sender, type, XB_REPORT_ID, out,+ NP_XBOX_REPORT_LEN, timeStamp);+}++static void register_report(const void *caller, IOHIDDeviceRef device, uint8_t *report,+ CFIndex length, IOHIDReportCallback callback, void *context) {+ struct pad *p = serve(caller) ? pad_for(device) : NULL;+ if (!p) {+ IOHIDDeviceRegisterInputReportCallback(device, report, length, callback, context);+ return;+ }+ pthread_mutex_lock(&lock);+ int live = p->device == device;+ if (live) {+ p->cb = callback;+ p->ctx = context;+ }+ pthread_mutex_unlock(&lock);+ if (!live || !callback) {+ // Unregister (or a device removed meanwhile): the game's own arguments.+ IOHIDDeviceRegisterInputReportCallback(device, report, length, callback, context);+ return;+ }+ // The pad's raw reports go to our buffer: the game's is sized for the Xbox report.+ IOHIDDeviceRegisterInputReportCallback(device, p->raw, RAW_MAX, relay_report, p);}static void np_IOHIDDeviceRegisterInputReportCallback(IOHIDDeviceRef device, uint8_t *report,CFIndex length, IOHIDReportCallback callback,void *context) {- if (!callback || !is_bluetooth_gamesir(device)) {- IOHIDDeviceRegisterInputReportCallback(device, report, length, callback, context);+ register_report(CALLER, device, report, length, callback, context);+}+INTERPOSE(np_IOHIDDeviceRegisterInputReportCallback, IOHIDDeviceRegisterInputReportCallback)++static void register_report_ts(const void *caller, IOHIDDeviceRef device, uint8_t *report,+ CFIndex length, IOHIDReportWithTimeStampCallback callback,+ void *context) {+ struct pad *p = serve(caller) ? pad_for(device) : NULL;+ if (!p) {+ IOHIDDeviceRegisterInputReportWithTimeStampCallback(device, report, length, callback,+ context);return;}- // One registration per open device for the life of the game; the relay is kept.- struct relay *r = calloc(1, sizeof *r);- r->callback = callback;- r->context = context;- IOHIDDeviceRegisterInputReportCallback(device, report, length, relay_report, r);+ pthread_mutex_lock(&lock);+ int live = p->device == device;+ if (live) {+ p->cb_ts = callback;+ p->ctx_ts = context;+ }+ pthread_mutex_unlock(&lock);+ if (!live || !callback) {+ IOHIDDeviceRegisterInputReportWithTimeStampCallback(device, report, length, callback,+ context);+ return;+ }+ IOHIDDeviceRegisterInputReportWithTimeStampCallback(device, p->raw_ts, RAW_MAX,+ relay_report_ts, p);}-INTERPOSE(np_IOHIDDeviceRegisterInputReportCallback, IOHIDDeviceRegisterInputReportCallback)-// Games that match on primary usage would never be handed the pad; ask for it by id too.-static void np_IOHIDManagerSetDeviceMatchingMultiple(IOHIDManagerRef manager, CFArrayRef multiple) {- if (!multiple) {- IOHIDManagerSetDeviceMatchingMultiple(manager, multiple);+static void np_IOHIDDeviceRegisterInputReportWithTimeStampCallback(+ IOHIDDeviceRef device, uint8_t *report, CFIndex length,+ IOHIDReportWithTimeStampCallback callback, void *context) {+ register_report_ts(CALLER, device, report, length, callback, context);+}+INTERPOSE(np_IOHIDDeviceRegisterInputReportWithTimeStampCallback,+ IOHIDDeviceRegisterInputReportWithTimeStampCallback)++// ---- Removal -----------------------------------------------------------------------++static void relay_removal(void *context, IOReturn result, void *sender, IOHIDDeviceRef device) {+ struct manager_slot *m = context;+ pthread_mutex_lock(&lock);+ IOHIDDeviceCallback cb = m->manager == sender ? m->cb : NULL;+ void *ctx = m->ctx;+ pthread_mutex_unlock(&lock);+ // The game's callback first: it may still read the (spoofed) identity of the pad.+ if (cb) cb(ctx, result, sender, device);+ forget_device(device);+}++// Wrapped for every caller: it only adds cache cleanup, the game's callback is unchanged.+static void np_IOHIDManagerRegisterDeviceRemovalCallback(IOHIDManagerRef manager,+ IOHIDDeviceCallback callback,+ void *context) {+ if (!manager || !hid_mode()) {+ IOHIDManagerRegisterDeviceRemovalCallback(manager, callback, context);return;}+ struct manager_slot *m = NULL, *free_slot = NULL;+ pthread_mutex_lock(&lock);+ for (int i = 0; i < MAX_MANAGERS && !m; i++) {+ if (managers[i].manager == manager) m = &managers[i];+ else if (!managers[i].manager && !free_slot) free_slot = &managers[i];+ }+ if (!m) m = free_slot;+ if (m) {+ // A manager freed and a new one at the same address simply takes over the slot.+ m->manager = manager;+ m->cb = callback;+ m->ctx = context;+ }+ pthread_mutex_unlock(&lock);+ if (m) // still registered when the game passes NULL, so the cache is cleaned up+ IOHIDManagerRegisterDeviceRemovalCallback(manager, relay_removal, m);+ else // out of slots: pruning by registry presence still frees stale entries+ IOHIDManagerRegisterDeviceRemovalCallback(manager, callback, context);+}+INTERPOSE(np_IOHIDManagerRegisterDeviceRemovalCallback, IOHIDManagerRegisterDeviceRemovalCallback)++// ---- Matching ----------------------------------------------------------------------++static int dict_int(CFDictionaryRef dict, CFStringRef key, int *out) {+ CFTypeRef value = CFDictionaryGetValue(dict, key);+ return value && CFGetTypeID(value) == CFNumberGetTypeID() &&+ CFNumberGetValue((CFNumberRef)value, kCFNumberIntType, out);+}++// A matching dict that asks for game controllers: GenericDesktop with Joystick, Gamepad,+// MultiAxis or no usage, by primary or device usage, not narrowed to one vendor.+static int wants_pads(CFTypeRef value) {+ if (!value || CFGetTypeID(value) != CFDictionaryGetTypeID()) return 0;+ CFDictionaryRef dict = value;+ int page, usage;+ if (CFDictionaryContainsKey(dict, CFSTR(kIOHIDVendorIDKey))) return 0;+ if (!dict_int(dict, CFSTR(kIOHIDDeviceUsagePageKey), &page) &&+ !dict_int(dict, CFSTR(kIOHIDPrimaryUsagePageKey), &page))+ return 0;+ if (page != kHIDPage_GenericDesktop) return 0;+ if (!dict_int(dict, CFSTR(kIOHIDDeviceUsageKey), &usage) &&+ !dict_int(dict, CFSTR(kIOHIDPrimaryUsageKey), &usage))+ return 1;+ return usage == kHIDUsage_GD_Joystick || usage == kHIDUsage_GD_GamePad ||+ usage == kHIDUsage_GD_MultiAxisController;+}++// The game's dicts plus DeviceUsagePairs dicts for Joystick, Gamepad and MultiAxis, so a+// pad whose primary usage is something else (the GameSir over Bluetooth: Consumer) is+// enumerated too. NULL when nothing needs adding.+static CFArrayRef extend_matching(CFArrayRef multiple) {+ CFIndex count = CFArrayGetCount(multiple);+ int wanted = 0;+ for (CFIndex i = 0; i < count && !wanted; i++)+ wanted = wants_pads(CFArrayGetValueAtIndex(multiple, i));+ if (!wanted) return NULL;CFMutableArrayRef all = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, multiple);- CFMutableDictionaryRef pad = CFDictionaryCreateMutable(kCFAllocatorDefault, 2,- &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);- CFNumberRef vendor = make_number(GS_VENDOR), product = make_number(GS_PRODUCT);- CFDictionarySetValue(pad, CFSTR(kIOHIDVendorIDKey), vendor);- CFDictionarySetValue(pad, CFSTR(kIOHIDProductIDKey), product);- CFArrayAppendValue(all, pad);- IOHIDManagerSetDeviceMatchingMultiple(manager, all);- CFRelease(vendor);- CFRelease(product);- CFRelease(pad);- CFRelease(all);+ if (!all) return NULL;+ static const int usages[] = { kHIDUsage_GD_Joystick, kHIDUsage_GD_GamePad,+ kHIDUsage_GD_MultiAxisController };+ CFNumberRef page = make_number(kHIDPage_GenericDesktop);+ for (unsigned i = 0; page && i < sizeof usages / sizeof *usages; i++) {+ CFNumberRef usage = make_number(usages[i]);+ CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 2,+ &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);+ if (usage && dict) {+ CFDictionarySetValue(dict, CFSTR(kIOHIDDeviceUsagePageKey), page);+ CFDictionarySetValue(dict, CFSTR(kIOHIDDeviceUsageKey), usage);+ CFArrayAppendValue(all, dict);+ }+ if (usage) CFRelease(usage);+ if (dict) CFRelease(dict);+ }+ if (page) CFRelease(page);+ return all;+}++static void set_matching_multiple(const void *caller, IOHIDManagerRef manager,+ CFArrayRef multiple) {+ CFArrayRef all = NULL;+ if (multiple && CFGetTypeID(multiple) == CFArrayGetTypeID() && serve(caller))+ all = extend_matching(multiple);+ IOHIDManagerSetDeviceMatchingMultiple(manager, all ? all : multiple);+ if (all) CFRelease(all);+}++static void np_IOHIDManagerSetDeviceMatchingMultiple(IOHIDManagerRef manager, CFArrayRef multiple) {+ set_matching_multiple(CALLER, manager, multiple);}INTERPOSE(np_IOHIDManagerSetDeviceMatchingMultiple, IOHIDManagerSetDeviceMatchingMultiple)++static void set_matching(const void *caller, IOHIDManagerRef manager, CFDictionaryRef matching) {+ CFArrayRef all = NULL;+ if (matching && serve(caller) && wants_pads(matching)) {+ CFArrayRef one = CFArrayCreate(kCFAllocatorDefault, (const void **)&matching, 1,+ &kCFTypeArrayCallBacks);+ if (one) {+ all = extend_matching(one);+ CFRelease(one);+ }+ }+ if (all) {+ IOHIDManagerSetDeviceMatchingMultiple(manager, all);+ CFRelease(all);+ } else {+ IOHIDManagerSetDeviceMatching(manager, matching);+ }+}++static void np_IOHIDManagerSetDeviceMatching(IOHIDManagerRef manager, CFDictionaryRef matching) {+ set_matching(CALLER, manager, matching);+}+INTERPOSE(np_IOHIDManagerSetDeviceMatching, IOHIDManagerSetDeviceMatching)++// ---- dlsym (P/Invoke) --------------------------------------------------------------++static const struct { const char *name; const void *original; void *replacement; } hooked[] = {+#define HOOK(f) { #f, (const void *)&f, (void *)np_##f }+ HOOK(IOHIDDeviceGetProperty),+ HOOK(IOHIDDeviceRegisterInputReportCallback),+ HOOK(IOHIDDeviceRegisterInputReportWithTimeStampCallback),+ HOOK(IOHIDManagerSetDeviceMatching),+ HOOK(IOHIDManagerSetDeviceMatchingMultiple),+ HOOK(IOHIDManagerRegisterDeviceRemovalCallback),+#undef HOOK+};++// Our replacement when symbol is one of the real IOKit functions we hook (inside this+// image those names still mean the originals), else symbol itself.+static void *hook_symbol(const char *name, void *symbol) {+ if (!symbol || !hid_mode()) return symbol;+ for (unsigned i = 0; i < sizeof hooked / sizeof *hooked; i++)+ if (symbol == hooked[i].original && strcmp(name, hooked[i].name) == 0)+ return hooked[i].replacement;+ return symbol;+}++// RTLD_NEXT / RTLD_SELF on behalf of the image at caller: the first image at or after+// it (after it for RTLD_NEXT) in load order that defines name.+static void *relative_dlsym(const void *caller, const char *name, int include_self) {+ Dl_info info;+ if (!dladdr(caller, &info) || !info.dli_fbase) return NULL;+ uint32_t count = _dyld_image_count();+ uint32_t start = UINT32_MAX;+ for (uint32_t i = 0; i < count; i++)+ if ((const void *)_dyld_get_image_header(i) == info.dli_fbase) {+ start = include_self ? i : i + 1;+ break;+ }+ if (start == UINT32_MAX) return NULL;+ for (uint32_t i = start; i < count; i++) {+ const void *header = _dyld_get_image_header(i);+ const char *path = _dyld_get_image_name(i);+ if (!header || !path) continue;+ void *handle = dlopen(path, RTLD_LAZY | RTLD_NOLOAD);+ if (!handle) continue;+ void *symbol = dlsym(handle, name);+ dlclose(handle);+ Dl_info found;+ // dlsym on a handle also searches its dependencies; keep only this image's own.+ if (symbol && dladdr(symbol, &found) && found.dli_fbase == header) return symbol;+ }+ return NULL;+}++static void *np_dlsym(void *handle, const char *name) {+ const void *caller = CALLER;+ if (!name || from_system(caller)) return dlsym(handle, name);+ Dl_info info;+ // A caller we cannot place (JIT) has no image to be relative to: real dlsym.+ if ((handle == RTLD_NEXT || handle == RTLD_SELF) && dladdr(caller, &info) && info.dli_fbase)+ return hook_symbol(name, relative_dlsym(caller, name, handle == RTLD_SELF));+ return hook_symbol(name, dlsym(handle, name));+}+INTERPOSE(np_dlsym, dlsym)diff --git a/native-shim/gc_virtual.m b/native-shim/gc_virtual.mnew file mode 100644index 0000000..9e21309--- /dev/null+++ b/native-shim/gc_virtual.m@@ -0,0 +1,528 @@+// gc_virtual.m: virtual GCControllers for pads the GameController framework does not expose.+//+// Native macOS games that read controllers only through GameController.framework never see+// generic HID / DirectInput pads (Flydigi, Nacon, BETOP, GameSir Bluetooth, ...). For every+// such pad (np_profile_create() != NULL) this file creates a snapshot controller with+// +[GCController controllerWithExtendedGamepad], feeds it decoded HID reports, and makes the+// game find it: +controllers / +current are swizzled and the connect / disconnect+// notifications are posted with the virtual controller as object.+//+// Built with -fobjc-arc into the same image as gamepad_shim.c, so the IOHID calls made here+// are not caught by that file's interposers. Only Foundation + IOKit are linked: the shim+// must not load GameController.framework into games that do not use it, so every GC class+// is reached through NSClassFromString and the work starts once the framework is loaded.+//+// Facts checked against the macOS 27 SDK / runtime (2026-10):+// - setValue: / setValueForXAxis:yAxis: write snapshot controllers and fire the element-level+// handlers (valueChangedHandler, pressedChangedHandler) of the element written.+// - The profile-level GCExtendedGamepad.valueChangedHandler and (macOS 13+)+// GCPhysicalInputProfile.valueDidChangeHandler do NOT fire for snapshot writes, so they+// are invoked here per changed element (after a startup self-test confirms they don't).+// - vendorName is read-only API but KVC-writable (ivar _vendorName).+// - GCController.input (GCControllerLiveInput, macOS 14+) stays empty on snapshot+// controllers; games that only use that API do not see input from virtual controllers.+// - +supportsHIDDevice: answers YES for pads the framework then never publishes (GameSir+// G7 Pro over Bluetooth), so it is not used to decide duplicates; a real controller with+// the same name is.++#if !__has_feature(objc_arc)+#error gc_virtual.m must be compiled with -fobjc-arc+#endif++#import <Foundation/Foundation.h>+#import <GameController/GameController.h>+#import <IOKit/hid/IOHIDLib.h>+#import <mach-o/dyld.h>+#import <objc/runtime.h>+#import <os/lock.h>+#import <dlfcn.h>+#import <math.h>+#import <stdarg.h>+#import <stdio.h>+#import <stdlib.h>+#import <string.h>++#include "np_pad.h"++// String values of the GameController notification constants; the shim does not link the+// framework, so the extern NSString symbols are not available.+static NSString *const kConnect = @"GCControllerDidConnectNotification";+static NSString *const kDisconnect = @"GCControllerDidDisconnectNotification";+static NSString *const kBecameCurrent = @"GCControllerDidBecomeCurrentNotification";++// A real GCController with the pad's name connecting within this window of the HID device+// appearing means the system serves the pad itself.+static const double kGraceSeconds = 1.0;++static int log_on = -1;++static void gc_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));+static void gc_log(const char *fmt, ...) {+ if (log_on < 0) {+ const char *v = getenv("NP_PAD_LOG");+ log_on = v && *v && strcmp(v, "0") != 0;+ }+ if (!log_on) return;+ va_list ap;+ va_start(ap, fmt);+ fputs("[np_pad gc] ", stderr);+ vfprintf(stderr, fmt, ap);+ fputc('\n', stderr);+ va_end(ap);+}++// ---------------------------------------------------------------------------------------+// Per-pad state. Everything below runs on the main thread except the swizzled class+// methods, which read `published` under `published_lock`.++@interface NPGCPad : NSObject {+@public+ IOHIDDeviceRef device;+ np_profile *profile;+ uint8_t *buffer;+ CFIndex buffer_len;+ np_pad_state last;+ BOOL have_last;+ BOOL removed;+ BOOL shadowed; // a real GCController serves this pad+ __weak id shadow; // that real controller+}+@property (nonatomic, copy) NSString *name; // HID product string+@property (nonatomic, copy) NSString *label; // np_profile_name(), given to the game+@property (nonatomic, strong) GCController *controller; // non-nil while published+@end++@implementation NPGCPad+@end++static Class gc_class;+static NSMutableArray<NPGCPad *> *pads;+static NSArray<GCController *> *published; // immutable, swapped under the lock+static os_unfair_lock published_lock = OS_UNFAIR_LOCK_INIT;+static __weak GCController *last_active;+static IOHIDManagerRef manager;+static BOOL manual_profile_handlers = YES;++static NSArray *(*orig_controllers)(id, SEL);+static GCController *(*orig_current)(id, SEL);++static NSArray<GCController *> *published_snapshot(void) {+ os_unfair_lock_lock(&published_lock);+ NSArray *list = published;+ os_unfair_lock_unlock(&published_lock);+ return list ?: @[];+}++static void republish_list(void) {+ NSMutableArray *list = [NSMutableArray array];+ for (NPGCPad *pad in pads)+ if (pad.controller) [list addObject:pad.controller];+ os_unfair_lock_lock(&published_lock);+ published = [list copy];+ os_unfair_lock_unlock(&published_lock);+}++static BOOL is_virtual(id controller) {+ for (GCController *c in published_snapshot())+ if (c == controller) return YES;+ return NO;+}++// ---------------------------------------------------------------------------------------+// Swizzles++static NSArray *np_controllers(id self, SEL _cmd) {+ NSArray *real = orig_controllers ? orig_controllers(self, _cmd) : @[];+ NSArray *virt = published_snapshot();+ if (virt.count == 0) return real;+ return [(real ?: @[]) arrayByAddingObjectsFromArray:virt];+}++static GCController *np_current(id self, SEL _cmd) {+ GCController *real = orig_current ? orig_current(self, _cmd) : nil;+ if (real) return real;+ GCController *active = last_active;+ if (active && is_virtual(active)) return active;+ return published_snapshot().firstObject;+}++static void swizzle_class_method(SEL sel, IMP replacement, IMP *original) {+ Method m = class_getClassMethod(gc_class, sel);+ if (!m) {+ gc_log("+[GCController %s] missing, not swizzled", sel_getName(sel));+ return;+ }+ *original = method_setImplementation(m, replacement);+}++// ---------------------------------------------------------------------------------------+// Real controllers (system-served) vs our pads++static NSArray<GCController *> *real_controllers(void) {+ NSArray *all = orig_controllers ? orig_controllers(gc_class, @selector(controllers)) : @[];+ NSMutableArray *real = [NSMutableArray array];+ for (GCController *c in all)+ if (!c.isSnapshot && !is_virtual(c)) [real addObject:c];+ return real;+}++static BOOL names_match(NSString *a, NSString *b) {+ if (a.length == 0 || b.length == 0) return NO;+ if ([a caseInsensitiveCompare:b] == NSOrderedSame) return YES;+ NSStringCompareOptions o = NSCaseInsensitiveSearch;+ return [a rangeOfString:b options:o].location != NSNotFound ||+ [b rangeOfString:a options:o].location != NSNotFound;+}++static BOOL claimed(GCController *real) {+ for (NPGCPad *pad in pads)+ if (pad->shadowed && pad->shadow == real) return YES;+ return NO;+}++// A real controller for this pad, not already claimed by another pad of the same name.+static GCController *real_match(NPGCPad *pad) {+ for (GCController *c in real_controllers())+ if (names_match(c.vendorName, pad.name) && !claimed(c)) return c;+ return nil;+}++// ---------------------------------------------------------------------------------------+// Publishing++static void post(NSString *name, GCController *c) {+ [NSNotificationCenter.defaultCenter postNotificationName:name object:c];+}++static void publish(NPGCPad *pad) {+ if (pad.controller || pad->removed || pad->shadowed) return;+ GCController *c = [(id)gc_class controllerWithExtendedGamepad];+ if (!c) {+ gc_log("controllerWithExtendedGamepad returned nil");+ return;+ }+ @try {+ [c setValue:pad.label forKey:@"vendorName"];+ } @catch (NSException *e) {+ gc_log("cannot set vendorName: %s", e.reason.UTF8String);+ }+ // Snapshots start at player index 0; a freshly connected real controller is unset.+ c.playerIndex = GCControllerPlayerIndexUnset;+ // Neutral state: the snapshot starts at zero, which already is neutral for every element.+ pad.controller = c;+ pad->have_last = NO;+ republish_list();+ gc_log("connect virtual \"%s\" (HID \"%s\")", pad.label.UTF8String, pad.name.UTF8String);+ post(kConnect, c);+}++static void unpublish(NPGCPad *pad, const char *why) {+ GCController *c = pad.controller;+ if (!c) return;+ pad.controller = nil;+ republish_list();+ if (last_active == c) last_active = nil;+ gc_log("disconnect virtual \"%s\" (%s)", pad.label.UTF8String, why);+ post(kDisconnect, c);+}++static void shadow_pad(NPGCPad *pad, GCController *real) {+ pad->shadowed = YES;+ pad->shadow = real;+ gc_log("\"%s\" is served by real GCController \"%s\": no virtual controller",+ pad.name.UTF8String, real.vendorName.UTF8String);+ unpublish(pad, "real controller present");+}++// After the grace period: skip the pad when the system serves it, else publish.+static void settle(NPGCPad *pad) {+ if (pad->removed || pad->shadowed || pad.controller) return;+ GCController *real = real_match(pad);+ if (real) shadow_pad(pad, real);+ else publish(pad);+}++static void real_connected(NSNotification *note) {+ GCController *c = note.object;+ if (!c || is_virtual(c) || c.isSnapshot || claimed(c)) return;+ for (NPGCPad *pad in pads) {+ if (pad->removed || pad->shadowed || !names_match(c.vendorName, pad.name)) continue;+ shadow_pad(pad, c);+ return;+ }+}++static void real_disconnected(NSNotification *note) {+ GCController *c = note.object;+ if (!c || is_virtual(c)) return;+ for (NPGCPad *pad in pads) {+ if (!pad->shadowed || pad->shadow != c) continue;+ // The system dropped its controller; if the HID device stays, take over.+ pad->shadowed = NO;+ pad->shadow = nil;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kGraceSeconds * NSEC_PER_SEC)),+ dispatch_get_main_queue(), ^{ settle(pad); });+ }+}++// ---------------------------------------------------------------------------------------+// Input++typedef void (^ProfileHandler)(GCExtendedGamepad *, GCControllerElement *);++static void changed(GCExtendedGamepad *gp, GCControllerElement *el) {+ if (!manual_profile_handlers || !el) return;+ ProfileHandler h = gp.valueChangedHandler;+ if (h) h(gp, el);+ if (@available(macOS 13.0, *)) {+ void (^h2)(GCPhysicalInputProfile *, GCControllerElement *) = gp.valueDidChangeHandler;+ if (h2) h2(gp, el);+ }+}++static void set_button(GCExtendedGamepad *gp, GCControllerButtonInput *b, float v, float old, BOOL force) {+ if (!b || (!force && v == old)) return;+ [b setValue:v];+ changed(gp, b);+}++static void set_pad(GCExtendedGamepad *gp, GCControllerDirectionPad *d, float x, float y, float ox,+ float oy, BOOL force) {+ if (!d || (!force && x == ox && y == oy)) return;+ [d setValueForXAxis:x yAxis:y];+ changed(gp, d);+}++static float clamp1(float v) { return v < -1 ? -1 : v > 1 ? 1 : v; }+static float clamp01(float v) { return v < 0 ? 0 : v > 1 ? 1 : v; }+static float bit(uint32_t buttons, int b) { return (buttons >> b) & 1 ? 1.0f : 0.0f; }++static void apply(NPGCPad *pad, const np_pad_state *s) {+ GCController *c = pad.controller;+ GCExtendedGamepad *gp = c.extendedGamepad;+ if (!gp) return;+ BOOL force = !pad->have_last;+ const np_pad_state *o = &pad->last;+ uint32_t nb = s->buttons, ob = o->buttons;++ // np_pad_state: +y down (SDL). GameController: +y up.+ set_pad(gp, gp.leftThumbstick, clamp1(s->lx), clamp1(-s->ly), clamp1(o->lx), clamp1(-o->ly), force);+ set_pad(gp, gp.rightThumbstick, clamp1(s->rx), clamp1(-s->ry), clamp1(o->rx), clamp1(-o->ry), force);+ set_button(gp, gp.leftTrigger, clamp01(s->lt), clamp01(o->lt), force);+ set_button(gp, gp.rightTrigger, clamp01(s->rt), clamp01(o->rt), force);++ float dx = bit(nb, NP_BTN_DPAD_RIGHT) - bit(nb, NP_BTN_DPAD_LEFT);+ float dy = bit(nb, NP_BTN_DPAD_UP) - bit(nb, NP_BTN_DPAD_DOWN);+ float odx = bit(ob, NP_BTN_DPAD_RIGHT) - bit(ob, NP_BTN_DPAD_LEFT);+ float ody = bit(ob, NP_BTN_DPAD_UP) - bit(ob, NP_BTN_DPAD_DOWN);+ set_pad(gp, gp.dpad, dx, dy, odx, ody, force);++ struct { int bit; GCControllerButtonInput *input; } map[] = {+ {NP_BTN_A, gp.buttonA},+ {NP_BTN_B, gp.buttonB},+ {NP_BTN_X, gp.buttonX},+ {NP_BTN_Y, gp.buttonY},+ {NP_BTN_LEFTSHOULDER, gp.leftShoulder},+ {NP_BTN_RIGHTSHOULDER, gp.rightShoulder},+ {NP_BTN_LEFTSTICK, gp.leftThumbstickButton},+ {NP_BTN_RIGHTSTICK, gp.rightThumbstickButton},+ {NP_BTN_START, gp.buttonMenu},+ {NP_BTN_BACK, gp.buttonOptions},+ {NP_BTN_GUIDE, nil},+ };+ if (@available(macOS 11.0, *)) map[10].input = gp.buttonHome;+ for (size_t i = 0; i < sizeof map / sizeof map[0]; i++)+ set_button(gp, map[i].input, bit(nb, map[i].bit), bit(ob, map[i].bit), force);++ pad->last = *s;+ pad->have_last = YES;++ if (last_active != c && (nb || fabsf(s->lx) > 0.5f || fabsf(s->ly) > 0.5f)) {+ last_active = c;+ BOOL real_current = NO;+ if (@available(macOS 11.0, *)) real_current = orig_current && orig_current(gc_class, @selector(current)) != nil;+ if (!real_current) post(kBecameCurrent, c);+ }+}++static void input_report(void *context, IOReturn result, void *sender, IOHIDReportType type,+ uint32_t reportID, uint8_t *report, CFIndex length) {+ (void)sender;+ (void)type;+ NPGCPad *pad = (__bridge NPGCPad *)context;+ if (result != kIOReturnSuccess || pad->removed || !pad.controller) return;+ np_pad_state s;+ memset(&s, 0, sizeof s);+ if (!np_profile_decode(pad->profile, reportID, report, length, &s)) return;+ @autoreleasepool {+ apply(pad, &s);+ }+}++// ---------------------------------------------------------------------------------------+// HID devices++static NSString *string_property(IOHIDDeviceRef device, CFStringRef key) {+ CFTypeRef v = IOHIDDeviceGetProperty(device, key);+ return v && CFGetTypeID(v) == CFStringGetTypeID() ? (__bridge NSString *)v : nil;+}++static long number_property(IOHIDDeviceRef device, CFStringRef key) {+ CFTypeRef v = IOHIDDeviceGetProperty(device, key);+ long n = 0;+ if (v && CFGetTypeID(v) == CFNumberGetTypeID()) CFNumberGetValue((CFNumberRef)v, kCFNumberLongType, &n);+ return n;+}++static NPGCPad *pad_for(IOHIDDeviceRef device) {+ for (NPGCPad *pad in pads)+ if (pad->device == device) return pad;+ return nil;+}++static void device_added(void *context, IOReturn result, void *sender, IOHIDDeviceRef device) {+ (void)context;+ (void)result;+ (void)sender;+ if (pad_for(device)) return;+ // Synthetic HID devices the GameController framework itself creates.+ CFTypeRef synthetic = IOHIDDeviceGetProperty(device, CFSTR("GCSyntheticDevice"));+ if (synthetic && CFGetTypeID(synthetic) == CFBooleanGetTypeID() && CFBooleanGetValue(synthetic)) return;++ NSString *name = string_property(device, CFSTR(kIOHIDProductKey)) ?: @"";+ long vid = number_property(device, CFSTR(kIOHIDVendorIDKey));+ long pid = number_property(device, CFSTR(kIOHIDProductIDKey));+ np_profile *profile = np_profile_create(device);+ if (!profile) {+ gc_log("skip \"%s\" %04lx:%04lx: no profile (not a pad, or natively supported)", name.UTF8String,+ vid, pid);+ return;+ }++ NPGCPad *pad = [NPGCPad new];+ pad->device = (IOHIDDeviceRef)CFRetain(device);+ pad->profile = profile;+ pad.name = name;+ const char *label = np_profile_name(profile);+ pad.label = label && *label ? @(label) : (name.length ? name : @"Gamepad");+ long len = number_property(device, CFSTR(kIOHIDMaxInputReportSizeKey));+ pad->buffer_len = len > 0 ? len : 64;+ pad->buffer = calloc(1, (size_t)pad->buffer_len);+ [pads addObject:pad];++ IOHIDDeviceRegisterInputReportCallback(device, pad->buffer, pad->buffer_len, input_report,+ (__bridge void *)pad);+ gc_log("pad \"%s\" %04lx:%04lx profile \"%s\" guid %s", name.UTF8String, vid, pid,+ pad.label.UTF8String, np_profile_guid(profile) ?: "?");++ GCController *real = real_match(pad);+ if (real) {+ shadow_pad(pad, real);+ return;+ }+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kGraceSeconds * NSEC_PER_SEC)),+ dispatch_get_main_queue(), ^{ settle(pad); });+}++static void device_removed(void *context, IOReturn result, void *sender, IOHIDDeviceRef device) {+ (void)context;+ (void)result;+ (void)sender;+ NPGCPad *pad = pad_for(device);+ if (!pad) return;+ pad->removed = YES;+ unpublish(pad, "device removed");+ IOHIDDeviceRegisterInputReportCallback(device, pad->buffer, pad->buffer_len, NULL, NULL);+ [pads removeObject:pad];+ np_profile_free(pad->profile);+ pad->profile = NULL;+ // The buffer may still be referenced by a report already queued on this run loop pass;+ // free it on the next turn.+ uint8_t *buffer = pad->buffer;+ IOHIDDeviceRef dev = pad->device;+ pad->buffer = NULL;+ pad->device = NULL;+ dispatch_async(dispatch_get_main_queue(), ^{+ free(buffer);+ CFRelease(dev);+ });+ gc_log("pad \"%s\" removed", pad.name.UTF8String);+}++// ---------------------------------------------------------------------------------------+// Startup++// Startup self-test: does a snapshot write fire the profile-level handler by itself?+static void probe_handler_behaviour(void) {+ GCController *c = [(id)gc_class controllerWithExtendedGamepad];+ GCExtendedGamepad *gp = c.extendedGamepad;+ if (!gp) return;+ __block int fired = 0;+ gp.valueChangedHandler = ^(GCExtendedGamepad *g, GCControllerElement *e) {+ (void)g;+ (void)e;+ fired++;+ };+ [gp.buttonA setValue:1];+ gp.valueChangedHandler = nil;+ manual_profile_handlers = fired == 0;+ gc_log("profile handlers on snapshot write: %s", fired ? "fired by framework" : "invoked by shim");+}++static void start(void) {+ gc_class = NSClassFromString(@"GCController");+ if (!gc_class || ![gc_class respondsToSelector:@selector(controllerWithExtendedGamepad)]) {+ gc_log("GCController.controllerWithExtendedGamepad unavailable, virtual controllers off");+ return;+ }+ pads = [NSMutableArray array];+ np_db_load();+ probe_handler_behaviour();++ swizzle_class_method(@selector(controllers), (IMP)np_controllers, (IMP *)&orig_controllers);+ if (@available(macOS 11.0, *)) swizzle_class_method(@selector(current), (IMP)np_current, (IMP *)&orig_current);++ NSNotificationCenter *nc = NSNotificationCenter.defaultCenter;+ [nc addObserverForName:kConnect object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *n) {+ real_connected(n);+ }];+ [nc addObserverForName:kDisconnect object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *n) {+ real_disconnected(n);+ }];++ manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);+ NSArray *matching = @[+ @{@kIOHIDDeviceUsagePageKey: @(kHIDPage_GenericDesktop), @kIOHIDDeviceUsageKey: @(kHIDUsage_GD_Joystick)},+ @{@kIOHIDDeviceUsagePageKey: @(kHIDPage_GenericDesktop), @kIOHIDDeviceUsageKey: @(kHIDUsage_GD_GamePad)},+ @{@kIOHIDDeviceUsagePageKey: @(kHIDPage_GenericDesktop),+ @kIOHIDDeviceUsageKey: @(kHIDUsage_GD_MultiAxisController)},+ ];+ IOHIDManagerSetDeviceMatchingMultiple(manager, (__bridge CFArrayRef)matching);+ IOHIDManagerRegisterDeviceMatchingCallback(manager, device_added, NULL);+ IOHIDManagerRegisterDeviceRemovalCallback(manager, device_removed, NULL);+ IOHIDManagerScheduleWithRunLoop(manager, CFRunLoopGetMain(), kCFRunLoopCommonModes);+ IOReturn r = IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone);+ gc_log("started (IOHIDManagerOpen 0x%x)", r);+}++static void image_added(const struct mach_header *mh, intptr_t slide) {+ (void)slide;+ static int scheduled;+ if (__atomic_load_n(&scheduled, __ATOMIC_ACQUIRE)) return;+ Dl_info info;+ if (!dladdr(mh, &info) || !info.dli_fname || !strstr(info.dli_fname, "/GameController.framework/")) return;+ if (__atomic_exchange_n(&scheduled, 1, __ATOMIC_ACQ_REL)) return;+ // dyld holds its lock here: do the Objective-C work later on the main queue.+ dispatch_async(dispatch_get_main_queue(), ^{+ @autoreleasepool {+ start();+ }+ });+}++__attribute__((constructor)) static void gc_virtual_init(void) {+ if (!(np_pad_mode() & NP_MODE_GC)) return;+ // Called at once for every loaded image, later for each dlopen: starts only when the+ // game itself brings in GameController.framework.+ _dyld_register_func_for_add_image(image_added);+}diff --git a/native-shim/hid_profile.c b/native-shim/hid_profile.cnew file mode 100644index 0000000..75a5d75--- /dev/null+++ b/native-shim/hid_profile.c@@ -0,0 +1,877 @@+// HID game controller profiles: report descriptor parser, SDL GUID, gamecontrollerdb+// lookup, input report decoder and Xbox report encoder. See np_pad.h for the contract.+//+// Numbering follows SDL2's IOKit joystick backend (src/joystick/darwin/SDL_iokitjoystick.c),+// because gamecontrollerdb "Mac OS X" lines refer to its indices:+// - axes: GenericDesktop X..Wheel (0x30-0x38) and Simulation Rudder, Throttle,+// Accelerator, Brake (0xBA, 0xBB, 0xC4, 0xC5);+// - hats: GenericDesktop Hat switch (0x39);+// - buttons: Button page, Consumer page, and GenericDesktop D-pad Up/Down/Right/Left,+// Start, Select, System Main Menu;+// each list is ordered by usage number alone (page ignored), ties kept in descriptor+// order (SDL's insertion sort with "usage >= current"). SDL drops an element only when+// it has seen the same IOHIDElement (cookie) before; every element this parser creates+// is distinct, so nothing is dropped by usage.+// One deliberate difference: SDL counts the elements of every top-level collection of a+// device whose primary usage is a gamepad, and skips devices whose primary usage is not.+// This parser takes only the GenericDesktop Joystick/GamePad/Multi-axis collection(s),+// whatever the primary usage, so a pad that also exposes Consumer, Keyboard, Mouse or+// vendor collections (GameSir over Bluetooth, Flydigi) is numbered as its gamepad part+// alone, and only the report IDs of that part are decoded.++#include "hid_profile_internal.h"++#include <CoreFoundation/CoreFoundation.h>+#include <mach-o/dyld.h>+#include <math.h>+#include <pthread.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <strings.h>++#define PAGE_GD 0x01+#define PAGE_SIM 0x02+#define PAGE_BUTTON 0x09+#define PAGE_CONSUMER 0x0C++#define MAX_ELEMENTS 4096+#define MAX_LOCAL_USAGES 256+#define MAX_DEPTH 32+#define MAX_PUSH 16+#define MAX_BINDINGS 64++// ---------------------------------------------------------------------------------------+// Devices left alone: the system's GameController framework and games already handle them.+// product 0 = every product of the vendor. Apple's VID (0x05AC) is deliberately absent:+// older third-party pads (GameSir T3, 05ac:061a) report it and are plain HID pads. Nacon's+// PS4-licensed pads (146b, 3285) are absent too: Sony's driver does not take them.+static const struct { uint16_t vendor, product; } native_pads[] = {+ {0x045E, 0}, // Microsoft: every Xbox controller+ {0x054C, 0}, // Sony: DualShock 3/4, DualSense, DualSense Edge+ {0x057E, 0x2006}, // Nintendo Joy-Con (L)+ {0x057E, 0x2007}, // Nintendo Joy-Con (R)+ {0x057E, 0x2009}, // Nintendo Switch Pro Controller+ {0x057E, 0x200E}, // Nintendo Joy-Con charging grip (L+R)+};++static int is_native_pad(uint16_t vendor, uint16_t product, const char *name) {+ for (size_t i = 0; i < sizeof native_pads / sizeof native_pads[0]; i++)+ if (native_pads[i].vendor == vendor &&+ (native_pads[i].product == 0 || native_pads[i].product == product))+ return 1;+ return name && strcasestr(name, "Xbox") != NULL;+}++// ---------------------------------------------------------------------------------------+// Parsed elements.++enum { EL_VAR, EL_ARRAY };++typedef struct {+ uint16_t page, usage;+ uint8_t report_id, size, kind, in_pad;+ uint32_t bit; // offset of the (first) field, counted after the report ID byte+ uint32_t count; // EL_ARRAY: number of fields+ int32_t lmin, lmax;+ int32_t match; // EL_ARRAY: field value that selects this element's usage+} hid_element;++enum { IN_BUTTON, IN_AXIS, IN_HAT };+enum { OUT_BUTTON, OUT_AXIS };+enum { AX_LX, AX_LY, AX_RX, AX_RY, AX_LT, AX_RT, AX_COUNT };++typedef struct {+ uint8_t in_type, out_type, out_index, hat_mask;+ uint16_t in_index; // SDL index of the input axis, button or hat+ float imin, imax, omin, omax;+} binding;++struct np_profile {+ char guid[33];+ char name[128];+ int uses_ids;+ hid_element *el;+ int nel;+ int *axes, *buttons, *hats; // SDL index -> element index+ int naxes, nbuttons, nhats;+ int32_t *raw; // last value per element (EL_ARRAY: 1 = selected)+ binding bind[MAX_BINDINGS];+ int nbind;+ uint8_t mapped[256]; // report IDs that carry a mapped control+};++// ---------------------------------------------------------------------------------------+// Report descriptor parser.++typedef struct {+ uint32_t page, size, count, id;+ int32_t lmin, lmax;+ uint32_t lmax_raw;+ unsigned lmax_bytes;+} hid_globals;++typedef struct {+ uint32_t min, max; // usage, with the page in the high 16 bits when ext+ uint8_t ext;+} usage_range;++typedef struct {+ usage_range r[MAX_LOCAL_USAGES];+ int n;+ uint32_t pending_min;+ uint8_t pending_ext, has_min;+} hid_locals;++typedef struct {+ hid_element *el;+ int nel, cap;+ int uses_ids, has_pad;+} parse_result;++static void add_range(hid_locals *l, uint32_t min, uint32_t max, uint8_t ext) {+ if (l->n >= MAX_LOCAL_USAGES) return;+ if (max < min) max = min;+ l->r[l->n].min = min;+ l->r[l->n].max = max;+ l->r[l->n].ext = ext;+ l->n++;+}++static uint32_t usage_total(const hid_locals *l) {+ uint64_t total = 0;+ for (int i = 0; i < l->n; i++) total += (uint64_t)(l->r[i].max - l->r[i].min) + 1;+ return total > MAX_ELEMENTS ? MAX_ELEMENTS : (uint32_t)total;+}++// i-th usage of the local list as page << 16 | usage; page is the one in effect now+// (at the main item) unless the usage carried its own (4-byte usage).+static uint32_t usage_at(const hid_locals *l, uint32_t page, uint32_t i) {+ for (int k = 0; k < l->n; k++) {+ uint32_t span = l->r[k].max - l->r[k].min;+ if (i <= span) {+ uint32_t u = l->r[k].min + i;+ return l->r[k].ext ? u : (page << 16) | (u & 0xffff);+ }+ i -= span + 1;+ }+ return 0;+}++static int add_element(parse_result *o, const hid_element *e) {+ if (o->nel >= MAX_ELEMENTS) return 0;+ if (o->nel == o->cap) {+ int cap = o->cap ? o->cap * 2 : 64;+ hid_element *grown = realloc(o->el, (size_t)cap * sizeof *grown);+ if (!grown) return 0;+ o->el = grown;+ o->cap = cap;+ }+ o->el[o->nel++] = *e;+ return 1;+}++static void parse_input(parse_result *o, const hid_globals *g, const hid_locals *l,+ uint32_t flags, uint8_t in_pad, uint32_t bit) {+ if (flags & 1) return; // Constant: padding+ uint32_t total = usage_total(l);+ if (!total || g->size == 0 || g->size > 32 || g->count == 0) return;+ int32_t lmax = g->lmax;+ // Logical Maximum is signed per spec, but devices write e.g. 25 FF meaning 255.+ if (g->lmin >= 0 && lmax < g->lmin && g->lmax_bytes < 4)+ lmax = (int32_t)g->lmax_raw;+ hid_element e = {0};+ e.report_id = (uint8_t)g->id;+ e.size = (uint8_t)g->size;+ e.in_pad = in_pad;+ e.lmin = g->lmin;+ e.lmax = lmax;+ if (flags & 2) { // Variable: one field per usage, the last usage repeats+ e.kind = EL_VAR;+ uint32_t count = g->count > MAX_ELEMENTS ? MAX_ELEMENTS : g->count;+ for (uint32_t f = 0; f < count; f++) {+ uint32_t u = usage_at(l, g->page, f < total ? f : total - 1);+ e.page = (uint16_t)(u >> 16);+ e.usage = (uint16_t)u;+ e.bit = bit + f * g->size;+ if (!add_element(o, &e)) return;+ }+ } else { // Array: IOKit exposes one button element per usage of the list+ e.kind = EL_ARRAY;+ e.bit = bit;+ e.count = g->count;+ for (uint32_t k = 0; k < total; k++) {+ uint32_t u = usage_at(l, g->page, k);+ e.page = (uint16_t)(u >> 16);+ e.usage = (uint16_t)u;+ e.match = (int32_t)((int64_t)g->lmin + k);+ if (!add_element(o, &e)) return;+ }+ }+}++static void parse_descriptor(const uint8_t *d, size_t len, parse_result *o) {+ hid_globals g = {0}, stack[MAX_PUSH];+ int sp = 0;+ hid_locals l;+ memset(&l, 0, sizeof l);+ uint64_t bits[256] = {0};+ uint8_t pad[MAX_DEPTH];+ int depth = 0;+ size_t i = 0;+ while (i < len) {+ uint8_t prefix = d[i++];+ if (prefix == 0xFE) { // long item: size, tag, data+ if (i + 2 > len) break;+ i += 2 + (size_t)d[i];+ continue;+ }+ unsigned size = prefix & 3;+ if (size == 3) size = 4;+ unsigned type = (prefix >> 2) & 3, tag = prefix >> 4;+ if (i + size > len) break;+ uint32_t u = 0;+ for (unsigned k = 0; k < size; k++) u |= (uint32_t)d[i + k] << (8 * k);+ int32_t s = size == 1 ? (int8_t)u : size == 2 ? (int16_t)u : (int32_t)u;+ i += size;++ if (type == 1) { // Global+ switch (tag) {+ case 0: g.page = u & 0xffff; break;+ case 1: g.lmin = s; break;+ case 2: g.lmax = s; g.lmax_raw = u; g.lmax_bytes = size; break;+ case 7: g.size = u; break;+ case 8: g.id = u & 0xff; o->uses_ids = 1; break;+ case 9: g.count = u; break;+ case 10: if (sp < MAX_PUSH) stack[sp++] = g; break;+ case 11: if (sp > 0) g = stack[--sp]; break;+ }+ } else if (type == 2) { // Local+ uint8_t ext = size == 4;+ switch (tag) {+ case 0: add_range(&l, u, u, ext); break;+ case 1: l.pending_min = u; l.pending_ext = ext; l.has_min = 1; break;+ case 2:+ if (l.has_min) {+ uint32_t max = l.pending_ext && !ext ? (l.pending_min & 0xffff0000u) | (u & 0xffff) : u;+ add_range(&l, l.pending_min, max, l.pending_ext);+ l.has_min = 0;+ }+ break;+ }+ } else if (type == 0) { // Main+ uint8_t in_pad = depth > 0 && pad[depth - 1];+ switch (tag) {+ case 8: // Input+ parse_input(o, &g, &l, u, in_pad, (uint32_t)bits[g.id & 0xff]);+ bits[g.id & 0xff] += (uint64_t)g.size * g.count;+ break;+ case 10: { // Collection+ uint32_t usage = l.n ? usage_at(&l, g.page, 0) : 0;+ uint8_t is_pad = in_pad;+ if ((usage >> 16) == PAGE_GD) {+ uint16_t gd = usage & 0xffff;+ if (gd == 0x04 || gd == 0x05 || gd == 0x08) is_pad = 1;+ }+ if (is_pad) o->has_pad = 1;+ if (depth < MAX_DEPTH) pad[depth] = is_pad;+ depth++;+ break;+ }+ case 12: if (depth > 0) depth--; break;+ }+ memset(&l, 0, sizeof l);+ }+ }+}++// ---------------------------------------------------------------------------------------+// SDL classification and decoding helpers.++enum { CLS_NONE, CLS_AXIS, CLS_BUTTON, CLS_HAT };++static int classify(const hid_element *e) {+ switch (e->page) {+ case PAGE_GD:+ if (e->usage >= 0x30 && e->usage <= 0x38) return CLS_AXIS;+ if (e->usage == 0x39) return CLS_HAT;+ if ((e->usage >= 0x90 && e->usage <= 0x93) || e->usage == 0x3D || e->usage == 0x3E ||+ e->usage == 0x85)+ return CLS_BUTTON;+ return CLS_NONE;+ case PAGE_SIM:+ return e->usage == 0xBA || e->usage == 0xBB || e->usage == 0xC4 || e->usage == 0xC5+ ? CLS_AXIS : CLS_NONE;+ case PAGE_BUTTON:+ case PAGE_CONSUMER:+ return CLS_BUTTON;+ }+ return CLS_NONE;+}++// SDL's insertion: after every element whose usage is <= this one.+static void insert_sorted(int *list, int *n, const hid_element *el, int index) {+ int at = *n;+ while (at > 0 && el[list[at - 1]].usage > el[index].usage) {+ list[at] = list[at - 1];+ at--;+ }+ list[at] = index;+ (*n)++;+}++static int read_field(const uint8_t *data, long len, uint32_t bit, unsigned size, int sign,+ int32_t *out) {+ if (size == 0 || size > 32 || (uint64_t)bit + size > (uint64_t)len * 8) return 0;+ uint64_t v = 0;+ unsigned got = 0;+ while (got < size) {+ uint32_t b = bit + got;+ unsigned shift = b & 7, take = 8 - shift;+ if (take > size - got) take = size - got;+ v |= (uint64_t)((data[b >> 3] >> shift) & ((1u << take) - 1)) << got;+ got += take;+ }+ if (sign && size < 64 && (v >> (size - 1)) & 1) *out = (int32_t)((int64_t)v - ((int64_t)1 << size));+ else *out = (int32_t)(uint32_t)v;+ return 1;+}++static void update_element(np_profile *p, int index, unsigned id, const uint8_t *data, long len) {+ const hid_element *e = &p->el[index];+ if (e->report_id != id) return;+ int sign = e->lmin < 0;+ int32_t v;+ if (e->kind == EL_VAR) {+ if (read_field(data, len, e->bit, e->size, sign, &v)) p->raw[index] = v;+ return;+ }+ int32_t hit = 0;+ for (uint32_t f = 0; f < e->count; f++) {+ if (!read_field(data, len, e->bit + f * e->size, e->size, sign, &v)) break;+ if (v == e->match) { hit = 1; break; }+ }+ p->raw[index] = hit;+}++static float axis_value(const np_profile *p, int sdl_axis) {+ const hid_element *e = &p->el[p->axes[sdl_axis]];+ if (e->lmax == e->lmin) return 0.0f;+ double n = ((double)p->raw[p->axes[sdl_axis]] - e->lmin) / ((double)e->lmax - e->lmin) * 2.0 - 1.0;+ return (float)(n < -1.0 ? -1.0 : n > 1.0 ? 1.0 : n);+}++// SDL_HAT_* bits: up 1, right 2, down 4, left 8.+static int hat_bits(const np_profile *p, int sdl_hat) {+ static const uint8_t pos[8] = {1, 3, 2, 6, 4, 12, 8, 9};+ const hid_element *e = &p->el[p->hats[sdl_hat]];+ int64_t range = (int64_t)e->lmax - e->lmin + 1;+ int64_t v = (int64_t)p->raw[p->hats[sdl_hat]] - e->lmin;+ if (range == 4) v *= 2;+ else if (range != 8) v = -1;+ return v >= 0 && v < 8 ? pos[v] : 0;+}++// ---------------------------------------------------------------------------------------+// gamecontrollerdb.++typedef struct {+ uint8_t guid[16];+ char *name, *mapping;+} db_entry;++static db_entry *db;+static int db_count, db_cap;+static pthread_once_t db_once = PTHREAD_ONCE_INIT;++static int hexval(char c) {+ if (c >= '0' && c <= '9') return c - '0';+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;+ return -1;+}++static void db_add_line(const char *line, int need_platform) {+ while (*line == ' ' || *line == '\t') line++;+ if (!*line || *line == '#') return;+ const char *c1 = strchr(line, ',');+ if (!c1 || c1 - line != 32) return;+ const char *c2 = strchr(c1 + 1, ',');+ if (!c2) return;+ uint8_t guid[16];+ for (int i = 0; i < 16; i++) {+ int hi = hexval(line[2 * i]), lo = hexval(line[2 * i + 1]);+ if (hi < 0 || lo < 0) return;+ guid[i] = (uint8_t)(hi << 4 | lo);+ }+ // Lines for another platform number their elements differently: never use them.+ const char *plat = strstr(c2, "platform:");+ if (plat) {+ plat += 9;+ size_t n = strcspn(plat, ",\r\n");+ if (n != 8 || strncasecmp(plat, "Mac OS X", 8) != 0) return;+ } else if (need_platform) {+ return;+ }+ size_t end = strcspn(c2 + 1, "\r\n");+ char *name = strndup(c1 + 1, (size_t)(c2 - c1 - 1));+ char *mapping = strndup(c2 + 1, end);+ if (!name || !mapping) { free(name); free(mapping); return; }+ if (db_count == db_cap) {+ int cap = db_cap ? db_cap * 2 : 64;+ db_entry *grown = realloc(db, (size_t)cap * sizeof *grown);+ if (!grown) { free(name); free(mapping); return; }+ db = grown;+ db_cap = cap;+ }+ memcpy(db[db_count].guid, guid, 16);+ db[db_count].name = name;+ db[db_count].mapping = mapping;+ db_count++;+}++static void db_load_file(const char *path) {+ FILE *f = fopen(path, "r");+ if (!f) return;+ char *line = NULL;+ size_t cap = 0;+ while (getline(&line, &cap, f) > 0) db_add_line(line, 1);+ free(line);+ fclose(f);+}++static void db_load_once(void) {+ const char *path = getenv("NP_GAMECONTROLLERDB");+ if (path && *path) {+ db_load_file(path);+ } else {+ const char *home = getenv("HOME");+ if (home) {+ char buf[1024];+ snprintf(buf, sizeof buf, "%s/Library/Application Support/notproton/gamecontrollerdb.txt", home);+ db_load_file(buf);+ }+ }+ const char *env = getenv("SDL_GAMECONTROLLERCONFIG");+ if (env && *env) {+ char *copy = strdup(env), *save = NULL;+ if (copy) {+ for (char *l = strtok_r(copy, "\n", &save); l; l = strtok_r(NULL, "\n", &save))+ db_add_line(l, 0);+ free(copy);+ }+ }+}++void np_db_load(void) {+ pthread_once(&db_once, db_load_once);+}++// ---------------------------------------------------------------------------------------+// Mapping strings -> bindings.++static const char *const button_keys[NP_BTN_COUNT] = {+ "a", "b", "x", "y", "back", "guide", "start", "leftstick", "rightstick",+ "leftshoulder", "rightshoulder", "dpup", "dpdown", "dpleft", "dpright", "misc1",+};+static const char *const axis_keys[AX_COUNT] = {+ "leftx", "lefty", "rightx", "righty", "lefttrigger", "righttrigger",+};++static long parse_uint(const char **s) {+ if (**s < '0' || **s > '9') return -1;+ long v = 0;+ while (**s >= '0' && **s <= '9') {+ v = v * 10 + (**s - '0');+ if (v > 100000) return -1;+ (*s)++;+ }+ return v;+}++// Returns 0 when the pair names an input the device does not have (the line is wrong for+// this device), 1 otherwise (bound, or a key that is not a control and was skipped).+static int parse_pair(np_profile *p, const char *key, size_t klen, const char *val, size_t vlen) {+ char out_half = 0;+ if (klen && (*key == '+' || *key == '-')) { out_half = *key; key++; klen--; }+ binding b = {0};+ int found = 0;+ for (int i = 0; i < NP_BTN_COUNT && !found; i++)+ if (strlen(button_keys[i]) == klen && !strncmp(key, button_keys[i], klen)) {+ b.out_type = OUT_BUTTON; b.out_index = (uint8_t)i; found = 1;+ }+ for (int i = 0; i < AX_COUNT && !found; i++)+ if (strlen(axis_keys[i]) == klen && !strncmp(key, axis_keys[i], klen)) {+ b.out_type = OUT_AXIS; b.out_index = (uint8_t)i; found = 1;+ if (i >= AX_LT) { b.omin = 0; b.omax = 1; }+ else if (out_half == '+') { b.omin = 0; b.omax = 1; }+ else if (out_half == '-') { b.omin = 0; b.omax = -1; }+ else { b.omin = -1; b.omax = 1; }+ }+ if (!found || !vlen) return 1;++ char tmp[32];+ if (vlen >= sizeof tmp) return 1;+ memcpy(tmp, val, vlen);+ tmp[vlen] = 0;+ const char *s = tmp;+ char in_half = 0;+ if (*s == '+' || *s == '-') in_half = *s++;+ char kind = *s++;+ long index = parse_uint(&s);+ if (index < 0) return 1;+ if (kind == 'a') {+ if (index >= p->naxes) return 0;+ b.in_type = IN_AXIS;+ if (in_half == '+') { b.imin = 0; b.imax = 1; }+ else if (in_half == '-') { b.imin = 0; b.imax = -1; }+ else { b.imin = -1; b.imax = 1; }+ if (*s == '~') { float t = b.imin; b.imin = b.imax; b.imax = t; }+ } else if (kind == 'b') {+ if (index >= p->nbuttons) return 0;+ b.in_type = IN_BUTTON;+ } else if (kind == 'h') {+ if (index >= p->nhats || *s++ != '.') return index >= p->nhats ? 0 : 1;+ long mask = parse_uint(&s);+ if (mask <= 0 || mask > 15) return 1;+ b.in_type = IN_HAT;+ b.hat_mask = (uint8_t)mask;+ } else {+ return 1;+ }+ b.in_index = (uint16_t)index;+ if (p->nbind < MAX_BINDINGS) p->bind[p->nbind++] = b;+ return 1;+}++// Replaces the profile's bindings with mapping's. Returns 0 (and leaves no bindings) when+// the mapping references an axis, button or hat the descriptor does not have.+static int apply_mapping(np_profile *p, const char *mapping) {+ p->nbind = 0;+ const char *s = mapping;+ while (*s) {+ size_t n = strcspn(s, ",");+ const char *colon = memchr(s, ':', n);+ if (colon && !parse_pair(p, s, (size_t)(colon - s), colon + 1, n - (size_t)(colon - s) - 1)) {+ p->nbind = 0;+ return 0;+ }+ s += n;+ if (*s == ',') s++;+ }+ return 1;+}++static int find_axis(const np_profile *p, uint16_t page, uint16_t usage) {+ for (int i = 0; i < p->naxes; i++) {+ const hid_element *e = &p->el[p->axes[i]];+ if (e->page == page && e->usage == usage) return i;+ }+ return -1;+}++// SDL "generic" style layout from the descriptor alone.+static void apply_generic(np_profile *p) {+ char m[512];+ size_t n = 0;+#define ADD(...) n += (size_t)snprintf(m + n, n < sizeof m ? sizeof m - n : 0, __VA_ARGS__)+ int x = find_axis(p, PAGE_GD, 0x30), y = find_axis(p, PAGE_GD, 0x31);+ int z = find_axis(p, PAGE_GD, 0x32), rx = find_axis(p, PAGE_GD, 0x33);+ int ry = find_axis(p, PAGE_GD, 0x34), rz = find_axis(p, PAGE_GD, 0x35);+ int accel = find_axis(p, PAGE_SIM, 0xC4), brake = find_axis(p, PAGE_SIM, 0xC5);+ int lt = -1, rt = -1;+ if (x >= 0) ADD("leftx:a%d,", x);+ if (y >= 0) ADD("lefty:a%d,", y);+ if (z >= 0 && rz >= 0) {+ ADD("rightx:a%d,righty:a%d,", z, rz);+ if (rx >= 0 && ry >= 0) { lt = rx; rt = ry; }+ } else if (rx >= 0 && ry >= 0) {+ ADD("rightx:a%d,righty:a%d,", rx, ry);+ if (z >= 0 && rz >= 0) { lt = z; rt = rz; }+ }+ if (accel >= 0 && brake >= 0) { lt = brake; rt = accel; }+ if (lt >= 0) ADD("lefttrigger:a%d,righttrigger:a%d,", lt, rt);+ static const char *const order[] = {+ "a", "b", "x", "y", "leftshoulder", "rightshoulder", "lefttrigger", "righttrigger",+ "back", "start", "leftstick", "rightstick", "guide",+ };+ for (int i = 0; i < (int)(sizeof order / sizeof order[0]) && i < p->nbuttons; i++) {+ if ((i == 6 || i == 7) && lt >= 0) continue; // analog triggers already bound+ ADD("%s:b%d,", order[i], i);+ }+ if (p->nhats > 0) ADD("dpup:h0.1,dpright:h0.2,dpdown:h0.4,dpleft:h0.8,");+#undef ADD+ apply_mapping(p, m);+ snprintf(p->name, sizeof p->name, "Generic HID gamepad");+}++// DB match ignoring the CRC field (bytes 2-3), optionally the version too (bytes 12-13).+// Later lines win. A line that does not fit the descriptor is skipped.+static int apply_db(np_profile *p, const uint8_t guid[16], int ignore_version) {+ for (int i = db_count - 1; i >= 0; i--) {+ const uint8_t *g = db[i].guid;+ if (memcmp(g, guid, 2) || memcmp(g + 4, guid + 4, 8) || memcmp(g + 14, guid + 14, 2))+ continue;+ if (!ignore_version && memcmp(g + 12, guid + 12, 2)) continue;+ if (!apply_mapping(p, db[i].mapping)) continue;+ snprintf(p->name, sizeof p->name, "%s", db[i].name);+ return 1;+ }+ return 0;+}++static void make_guid(uint8_t g[16], uint16_t vendor, uint16_t product, uint16_t version,+ const char *name) {+ memset(g, 0, 16);+ g[0] = 0x03; // SDL_HARDWARE_BUS_USB: SDL's IOKit backend uses it for every device+ // g[2..3] = CRC16 of the name in SDL; gamecontrollerdb lines carry 0 and SDL ignores it.+ if (vendor) {+ g[4] = vendor & 0xff; g[5] = vendor >> 8;+ g[8] = product & 0xff; g[9] = product >> 8;+ g[12] = version & 0xff; g[13] = version >> 8;+ } else if (name) {+ strlcpy((char *)g + 4, name, 12);+ }+}++// ---------------------------------------------------------------------------------------+// Public API.++np_profile *np_profile_create_from_descriptor(const uint8_t *descriptor, size_t length,+ uint16_t vendor, uint16_t product,+ uint16_t version, const char *name) {+ if (!descriptor || !length || is_native_pad(vendor, product, name)) return NULL;+ parse_result o = {0};+ parse_descriptor(descriptor, length, &o);+ np_profile *p = NULL;+ if (!o.has_pad || !o.nel || !(p = calloc(1, sizeof *p))) goto fail;+ p->el = o.el;+ p->nel = o.nel;+ p->uses_ids = o.uses_ids;+ p->axes = calloc((size_t)o.nel, sizeof(int));+ p->buttons = calloc((size_t)o.nel, sizeof(int));+ p->hats = calloc((size_t)o.nel, sizeof(int));+ p->raw = calloc((size_t)o.nel, sizeof(int32_t));+ if (!p->axes || !p->buttons || !p->hats || !p->raw) goto fail_profile;+ for (int i = 0; i < o.nel; i++) {+ if (!o.el[i].in_pad) continue;+ switch (classify(&o.el[i])) {+ case CLS_AXIS: insert_sorted(p->axes, &p->naxes, o.el, i); break;+ case CLS_BUTTON: insert_sorted(p->buttons, &p->nbuttons, o.el, i); break;+ case CLS_HAT: insert_sorted(p->hats, &p->nhats, o.el, i); break;+ }+ }+ if (!p->naxes && !p->nbuttons && !p->nhats) goto fail_profile;+ // Axes rest at their centre and hats at "none" until the first report says otherwise.+ for (int i = 0; i < p->naxes; i++) {+ const hid_element *e = &p->el[p->axes[i]];+ p->raw[p->axes[i]] = (int32_t)(((int64_t)e->lmin + e->lmax + 1) / 2);+ }+ for (int i = 0; i < p->nhats; i++) p->raw[p->hats[i]] = p->el[p->hats[i]].lmax + 1;++ uint8_t guid[16];+ make_guid(guid, vendor, product, version, name);+ for (int i = 0; i < 16; i++) snprintf(p->guid + 2 * i, 3, "%02x", guid[i]);+ np_db_load();+ if (!apply_db(p, guid, 0) && !apply_db(p, guid, 1)) apply_generic(p);++ for (int i = 0; i < p->nbind; i++) {+ const binding *b = &p->bind[i];+ const int *list = b->in_type == IN_AXIS ? p->axes : b->in_type == IN_HAT ? p->hats : p->buttons;+ p->mapped[p->el[list[b->in_index]].report_id] = 1;+ }+ return p;++fail_profile:+ np_profile_free(p);+ return NULL;+fail:+ free(o.el);+ return NULL;+}++static int number_property(IOHIDDeviceRef device, CFStringRef key) {+ CFTypeRef value = IOHIDDeviceGetProperty(device, key);+ int out = 0;+ if (value && CFGetTypeID(value) == CFNumberGetTypeID())+ CFNumberGetValue((CFNumberRef)value, kCFNumberIntType, &out);+ return out;+}++np_profile *np_profile_create(IOHIDDeviceRef device) {+ if (!device) return NULL;+ CFTypeRef desc = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDReportDescriptorKey));+ if (!desc || CFGetTypeID(desc) != CFDataGetTypeID()) return NULL;+ char name[256] = "";+ CFTypeRef product = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDProductKey));+ if (product && CFGetTypeID(product) == CFStringGetTypeID() &&+ !CFStringGetCString((CFStringRef)product, name, sizeof name, kCFStringEncodingUTF8))+ name[0] = 0;+ return np_profile_create_from_descriptor(+ CFDataGetBytePtr((CFDataRef)desc), (size_t)CFDataGetLength((CFDataRef)desc),+ (uint16_t)number_property(device, CFSTR(kIOHIDVendorIDKey)),+ (uint16_t)number_property(device, CFSTR(kIOHIDProductIDKey)),+ (uint16_t)number_property(device, CFSTR(kIOHIDVersionNumberKey)), name);+}++void np_profile_free(np_profile *p) {+ if (!p) return;+ free(p->el);+ free(p->axes);+ free(p->buttons);+ free(p->hats);+ free(p->raw);+ free(p);+}++void np_profile_counts(const np_profile *p, int *axes, int *buttons, int *hats) {+ if (axes) *axes = p ? p->naxes : 0;+ if (buttons) *buttons = p ? p->nbuttons : 0;+ if (hats) *hats = p ? p->nhats : 0;+}++const char *np_profile_guid(const np_profile *p) { return p ? p->guid : ""; }+const char *np_profile_name(const np_profile *p) { return p ? p->name : ""; }++// Allocation-free. Keeps the last value of every element in the profile, so controls spread+// over several reports combine; one profile must not be decoded from two threads at once.+int np_profile_decode(np_profile *p, uint32_t reportID, const uint8_t *report, long length,+ np_pad_state *state) {+ if (!p || !report || !state || length <= 0) return 0;+ unsigned id = 0;+ const uint8_t *data = report;+ long len = length;+ if (p->uses_ids) {+ id = report[0];+ if (reportID && reportID != id) return 0;+ data++;+ len--;+ }+ if (!p->mapped[id]) return 0;+ for (int i = 0; i < p->naxes; i++) update_element(p, p->axes[i], id, data, len);+ for (int i = 0; i < p->nbuttons; i++) update_element(p, p->buttons[i], id, data, len);+ for (int i = 0; i < p->nhats; i++) update_element(p, p->hats[i], id, data, len);++ float axes[AX_COUNT] = {0};+ uint32_t buttons = 0;+ for (int i = 0; i < p->nbind; i++) {+ const binding *b = &p->bind[i];+ int pressed = 0, have_value = 0;+ float value = 0;+ if (b->in_type == IN_AXIS) {+ float v = axis_value(p, b->in_index);+ float lo = fminf(b->imin, b->imax), hi = fmaxf(b->imin, b->imax);+ if (v < lo || v > hi) continue;+ float t = (v - b->imin) / (b->imax - b->imin);+ if (b->out_type == OUT_AXIS) { value = b->omin + t * (b->omax - b->omin); have_value = 1; }+ else pressed = t >= 0.5f;+ } else {+ pressed = b->in_type == IN_BUTTON ? p->raw[p->buttons[b->in_index]] != 0+ : (hat_bits(p, b->in_index) & b->hat_mask) != 0;+ if (b->out_type == OUT_AXIS && pressed) { value = b->omax; have_value = 1; }+ }+ if (b->out_type == OUT_BUTTON) {+ if (pressed) buttons |= 1u << b->out_index;+ } else if (have_value && fabsf(value) > fabsf(axes[b->out_index])) {+ axes[b->out_index] = value;+ }+ }+ for (int i = 0; i < AX_COUNT; i++) {+ float lo = i >= AX_LT ? 0.0f : -1.0f;+ axes[i] = axes[i] < lo ? lo : axes[i] > 1.0f ? 1.0f : axes[i];+ }+ state->lx = axes[AX_LX];+ state->ly = axes[AX_LY];+ state->rx = axes[AX_RX];+ state->ry = axes[AX_RY];+ state->lt = axes[AX_LT];+ state->rt = axes[AX_RT];+ state->buttons = buttons;+ return 1;+}++static void put16(uint8_t *at, unsigned v) {+ at[0] = v & 0xff;+ at[1] = (v >> 8) & 0xff;+}++static unsigned stick16(float v) {+ if (!(v >= -1.0f)) v = -1.0f;+ if (v > 1.0f) v = 1.0f;+ // Round half down so rest (0) gives 32767; 8-bit inputs land exactly on x * 257.+ return (unsigned)floor(((double)v + 1.0) * 0.5 * 65535.0 + 0.499);+}++static unsigned trigger10(float v) {+ if (!(v >= 0.0f)) v = 0.0f;+ if (v > 1.0f) v = 1.0f;+ unsigned t = (unsigned)floor((double)v * 1023.0 + 1e-3);+ return t > 1023 ? 1023 : t;+}++void np_xbox_encode(const np_pad_state *s, uint8_t out[NP_XBOX_REPORT_LEN]) {+ static const int8_t xbox_bit[NP_BTN_COUNT] = {+ [NP_BTN_A] = 0, [NP_BTN_B] = 1, [NP_BTN_X] = 3, [NP_BTN_Y] = 4,+ [NP_BTN_BACK] = 10, [NP_BTN_GUIDE] = 12, [NP_BTN_START] = 11,+ [NP_BTN_LEFTSTICK] = 13, [NP_BTN_RIGHTSTICK] = 14,+ [NP_BTN_LEFTSHOULDER] = 6, [NP_BTN_RIGHTSHOULDER] = 7,+ [NP_BTN_DPAD_UP] = -1, [NP_BTN_DPAD_DOWN] = -1, [NP_BTN_DPAD_LEFT] = -1,+ [NP_BTN_DPAD_RIGHT] = -1, [NP_BTN_MISC1] = -1,+ };+ memset(out, 0, NP_XBOX_REPORT_LEN);+ out[0] = 0x01;+ put16(out + 1, stick16(s->lx));+ put16(out + 3, stick16(s->ly));+ put16(out + 5, stick16(s->rx));+ put16(out + 7, stick16(s->ry));+ put16(out + 9, trigger10(s->lt));+ put16(out + 11, trigger10(s->rt));+ uint32_t b = s->buttons;+ int up = (b >> NP_BTN_DPAD_UP) & 1, down = (b >> NP_BTN_DPAD_DOWN) & 1;+ int left = (b >> NP_BTN_DPAD_LEFT) & 1, right = (b >> NP_BTN_DPAD_RIGHT) & 1;+ if (up && down) up = down = 0;+ if (left && right) left = right = 0;+ uint8_t hat = 0;+ if (up) hat = right ? 2 : left ? 8 : 1;+ else if (down) hat = right ? 4 : left ? 6 : 5;+ else if (right) hat = 3;+ else if (left) hat = 7;+ out[13] = hat;+ uint32_t xb = 0;+ for (int i = 0; i < NP_BTN_COUNT; i++)+ if ((b >> i) & 1 && xbox_bit[i] >= 0) xb |= 1u << xbox_bit[i];+ out[14] = xb & 0xff;+ out[15] = (xb >> 8) & 0xff;+ out[16] = (xb >> 16) & 0xff;+ out[17] = (xb >> 24) & 0xff;+}++int np_pad_mode_from(const char *env, int has_unity) {+ if (env && *env) {+ if (!strcasecmp(env, "hid")) return NP_MODE_HID;+ if (!strcasecmp(env, "gc")) return NP_MODE_GC;+ if (!strcasecmp(env, "both")) return NP_MODE_HID | NP_MODE_GC;+ if (!strcasecmp(env, "off")) return NP_MODE_OFF;+ }+ return has_unity ? NP_MODE_HID : NP_MODE_HID | NP_MODE_GC;+}++static int pad_mode;+static pthread_once_t mode_once = PTHREAD_ONCE_INIT;++// Images are all mapped before any initializer runs, so a constructor already sees+// UnityPlayer when the game links it. A later dlopen of UnityPlayer is not noticed.+static void pad_mode_once(void) {+ int unity = 0;+ uint32_t n = _dyld_image_count();+ for (uint32_t i = 0; i < n && !unity; i++) {+ const char *image = _dyld_get_image_name(i);+ unity = image && strstr(image, "UnityPlayer") != NULL;+ }+ pad_mode = np_pad_mode_from(getenv("NP_PAD_MODE"), unity);+}++int np_pad_mode(void) {+ pthread_once(&mode_once, pad_mode_once);+ return pad_mode;+}diff --git a/native-shim/hid_profile_internal.h b/native-shim/hid_profile_internal.hnew file mode 100644index 0000000..8cacb23--- /dev/null+++ b/native-shim/hid_profile_internal.h@@ -0,0 +1,23 @@+// Private entry points of hid_profile.c, for the unit tests in tests/. The shim itself+// only uses np_pad.h.++#ifndef NP_HID_PROFILE_INTERNAL_H+#define NP_HID_PROFILE_INTERNAL_H++#include "np_pad.h"+#include <stddef.h>++// The device-independent core of np_profile_create: descriptor = the HID report+// descriptor bytes (kIOHIDReportDescriptorKey), name = kIOHIDProductKey (may be NULL).+np_profile *np_profile_create_from_descriptor(const uint8_t *descriptor, size_t length,+ uint16_t vendor, uint16_t product,+ uint16_t version, const char *name);++// Number of SDL axes, buttons and hats the profile sees (SDL IOKit numbering).+void np_profile_counts(const np_profile *profile, int *axes, int *buttons, int *hats);++// np_pad_mode's decision without the process lookups and caching: env = $NP_PAD_MODE+// (NULL when unset), has_unity = a loaded image path contains "UnityPlayer".+int np_pad_mode_from(const char *env, int has_unity);++#endifdiff --git a/native-shim/np_pad.h b/native-shim/np_pad.hnew file mode 100644index 0000000..1a91414--- /dev/null+++ b/native-shim/np_pad.h@@ -0,0 +1,71 @@+// Shared contract of the native controller shim (libnp_gamepad.dylib).+//+// hid_profile.c turns any HID game controller into np_pad_state: it parses the HID+// report descriptor, looks the pad up in gamecontrollerdb (SDL format) by+// its SDL GUID, and decodes input reports with that mapping.+// gamepad_shim.c interposes IOHIDManager/IOHIDDevice so raw-HID games (Unity) see every+// unsupported pad as an Xbox Wireless Controller and get Xbox reports.+// gc_virtual.m gives GameController-framework games a virtual GCController per pad+// the system does not already expose as a GCController.++#ifndef NP_PAD_H+#define NP_PAD_H++#include <IOKit/hid/IOHIDLib.h>+#include <stdint.h>++// Xbox (SDL) button order; also the bit order of np_pad_state.buttons.+enum {+ NP_BTN_A, NP_BTN_B, NP_BTN_X, NP_BTN_Y,+ NP_BTN_BACK, NP_BTN_GUIDE, NP_BTN_START,+ NP_BTN_LEFTSTICK, NP_BTN_RIGHTSTICK,+ NP_BTN_LEFTSHOULDER, NP_BTN_RIGHTSHOULDER,+ NP_BTN_DPAD_UP, NP_BTN_DPAD_DOWN, NP_BTN_DPAD_LEFT, NP_BTN_DPAD_RIGHT,+ NP_BTN_MISC1,+ NP_BTN_COUNT+};++typedef struct {+ float lx, ly, rx, ry; // -1..1, +y is down (SDL convention)+ float lt, rt; // 0..1+ uint32_t buttons; // bit NP_BTN_*; d-pad is reported here, not as a hat+} np_pad_state;++typedef struct np_profile np_profile;++// NULL when the device is not a game controller, or is one the system and games already+// handle natively (Xbox, DualShock 4, DualSense, Switch Pro, MFi-only): those are left alone.+np_profile *np_profile_create(IOHIDDeviceRef device);+void np_profile_free(np_profile *profile);++// Returns 1 and fills state when the report carries controller input, else 0.+// report includes the report ID byte when the device uses report IDs.+int np_profile_decode(np_profile *profile, uint32_t reportID, const uint8_t *report,+ long length, np_pad_state *state);++// SDL GUID string (32 hex chars) and name the profile matched, for logs.+const char *np_profile_guid(const np_profile *profile);+const char *np_profile_name(const np_profile *profile);++// 18-byte Xbox Wireless Controller (Bluetooth) report in the layout Unity's+// XboxGamepadMacOSWireless (XInputControllerWirelessOSXStateV2) reads.+#define NP_XBOX_REPORT_LEN 18+void np_xbox_encode(const np_pad_state *state, uint8_t out[NP_XBOX_REPORT_LEN]);++// Mapping database: $NP_GAMECONTROLLERDB, else+// ~/Library/Application Support/notproton/gamecontrollerdb.txt, plus SDL_GAMECONTROLLERCONFIG.+// Later lines win over earlier ones for the same GUID.+void np_db_load(void);++// Which game-facing path the shim serves, from $NP_PAD_MODE: "hid" (raw-HID games such as+// Unity: Xbox spoof only), "gc" (GameController games: virtual GCControllers only), "both",+// or "off". Unset = "hid" when the process loaded UnityPlayer, else "both". Serving both to+// a game that reads both would show every pad twice, hence the switch.+enum { NP_MODE_OFF = 0, NP_MODE_HID = 1, NP_MODE_GC = 2 };+int np_pad_mode(void); // bitmask of NP_MODE_HID / NP_MODE_GC++// gc_virtual.m reads pads through its own IOHIDManager (GameController games never open+// HID themselves) and decodes them with np_profile_*; it starts itself from a constructor+// when np_pad_mode() has NP_MODE_GC.++#endifdiff --git a/native-shim/tests/fixtures/gamesir_g7pro_bt.hex b/native-shim/tests/fixtures/gamesir_g7pro_bt.hexnew file mode 100644index 0000000..8cfc709--- /dev/null+++ b/native-shim/tests/fixtures/gamesir_g7pro_bt.hex@@ -0,0 +1 @@+050c0901a1018502150025017501950c09ea09cd09b609b509e909b809950a23020a2402094009b709e28102950175048103c005010905a10185070901a1000930093109320935150026ff00750895048102c00939150025073500463b016514750495018142750495018101050919012910150025017501951081020502150026ff0009c409c5950275088102750895018101c005010906a101850175019508050719e029e7150025018102950175088103950575010508190129059102950175039103950a7508150026ff000507190029ff8100c005010902a10185060901a1000509190129051500250195057501810295017503810105010930093116018026ff7f75109502810609381581257f75089501810695018103c0c0diff --git a/native-shim/tests/fixtures/gamesir_g7pro_bt_reports.txt b/native-shim/tests/fixtures/gamesir_g7pro_bt_reports.txtnew file mode 100644index 0000000..564353e--- /dev/null+++ b/native-shim/tests/fixtures/gamesir_g7pro_bt_reports.txt@@ -0,0 +1,120 @@+opened+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 01 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 02 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 08 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 08 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 08 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 10 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 40 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 80 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 01 00 ff 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 02 ff 00 00+id=7 len=11: 07 80 82 81 83 0f 00 02 ff 00 00+id=7 len=11: 07 80 82 81 82 0f 00 02 ff 00 00+id=7 len=11: 07 80 82 81 83 0f 00 02 ff 00 00+id=7 len=11: 07 80 82 81 82 0f 00 02 ff 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 06 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 06 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 06 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 04 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 81 82 02 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 02 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 02 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 00 00 00 00 00 00+id=7 len=11: 07 80 82 81 82 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 83 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 84 0f 00 00 00 00 00+id=7 len=11: 07 80 82 81 85 0f 00 00 00 00 00+id=7 len=11: 07 80 82 82 85 0f 00 00 00 00 00+id=7 len=11: 07 80 82 83 86 0f 00 00 00 00 00+id=7 len=11: 07 80 82 80 86 0f 00 00 00 00 00+id=7 len=11: 07 7f 82 7e 86 0f 00 00 00 00 00diff --git a/native-shim/tests/fixtures/test_gamecontrollerdb.txt b/native-shim/tests/fixtures/test_gamecontrollerdb.txtnew file mode 100644index 0000000..302d9d0--- /dev/null+++ b/native-shim/tests/fixtures/test_gamecontrollerdb.txt@@ -0,0 +1,10 @@+0300000037350000221000001b010000,GameSir G7 Pro (Bluetooth),a:b0,b:b1,x:b3,y:b4,leftshoulder:b6,rightshoulder:b7,lefttrigger:a5,righttrigger:a4,back:b10,start:b11,leftstick:b13,rightstick:b14,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,platform:Mac OS X,+# Test database for tests/test_hid_profile.c.+# Generic pad 1234:5678: only a Windows line exists, which must be ignored.+03000000341200007856000000010000,Windows Only Pad,a:b2,b:b3,leftx:a3,platform:Windows,+# 1234:5679: a Mac line whose indices do not exist on the device (shared VID:PID); ignored.+03000000341200007956000000010000,Wrong Pad,a:b0,b:b1,leftx:a7,lefty:a1,platform:Mac OS X,+# 1234:567a version 0x0105: only a version-less line exists.+03000000341200007a56000000000000,Versionless Pad,a:b1,b:b0,leftx:a0,lefty:a1,dpup:h0.1,platform:Mac OS X,+# 2222:3333: overridden by SDL_GAMECONTROLLERCONFIG in the test.+03000000222200003333000001000000,File Line,a:b0,b:b1,platform:Mac OS X,diff --git a/native-shim/tests/gc_probe.m b/native-shim/tests/gc_probe.mnew file mode 100644index 0000000..7068955--- /dev/null+++ b/native-shim/tests/gc_probe.m@@ -0,0 +1,82 @@+// gc_probe: what a GameController-framework game sees.+//+// Prints every GCController (already present or connecting later), then for N seconds+// (default 5, argv[1]) prints extendedGamepad leftThumbstick / buttonA whenever they change,+// both from the game-style valueChangedHandler and from polling (so a missing handler shows).+//+// clang -fobjc-arc -framework Foundation -framework GameController tests/gc_probe.m -o gc_probe+// ./gc_probe 5+// NP_PAD_MODE=gc DYLD_INSERT_LIBRARIES=libnp_gamepad.dylib ./gc_probe 5++#import <Foundation/Foundation.h>+#import <GameController/GameController.h>++static NSMutableSet *watched;++static void describe(const char *tag, GCController *c) {+ printf("%s vendorName=\"%s\" category=\"%s\" snapshot=%d extended=%d players=%ld\n", tag,+ c.vendorName.UTF8String ?: "(null)", c.productCategory.UTF8String ?: "(null)",+ (int)c.isSnapshot, c.extendedGamepad != nil, (long)c.playerIndex);+ fflush(stdout);+}++static void watch(GCController *c) {+ if (!c.extendedGamepad || [watched containsObject:c]) return;+ [watched addObject:c];+ NSString *name = c.vendorName ?: @"?";+ c.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad *pad, GCControllerElement *el) {+ if (el == pad.leftThumbstick || el == pad.leftThumbstick.xAxis || el == pad.leftThumbstick.yAxis)+ printf(" [handler %s] leftThumbstick x=%+.3f y=%+.3f\n", name.UTF8String,+ pad.leftThumbstick.xAxis.value, pad.leftThumbstick.yAxis.value);+ else if (el == pad.buttonA)+ printf(" [handler %s] buttonA value=%.2f pressed=%d\n", name.UTF8String,+ pad.buttonA.value, pad.buttonA.pressed);+ fflush(stdout);+ };+}++int main(int argc, char **argv) {+ @autoreleasepool {+ double seconds = argc > 1 ? atof(argv[1]) : 5;+ watched = [NSMutableSet set];+ if (@available(macOS 11.3, *)) GCController.shouldMonitorBackgroundEvents = YES;++ NSNotificationCenter *nc = NSNotificationCenter.defaultCenter;+ [nc addObserverForName:GCControllerDidConnectNotification object:nil queue:NSOperationQueue.mainQueue+ usingBlock:^(NSNotification *n) { describe("connect:", n.object); watch(n.object); }];+ [nc addObserverForName:GCControllerDidDisconnectNotification object:nil queue:NSOperationQueue.mainQueue+ usingBlock:^(NSNotification *n) { describe("disconnect:", n.object); [watched removeObject:n.object]; }];++ NSArray *initial = GCController.controllers;+ printf("initial controllers: %lu\n", (unsigned long)initial.count);+ for (GCController *c in initial) { describe("initial:", c); watch(c); }++ __block NSMutableDictionary *last = [NSMutableDictionary dictionary];+ NSTimer *poll = [NSTimer scheduledTimerWithTimeInterval:0.05 repeats:YES block:^(NSTimer *t) {+ for (GCController *c in GCController.controllers) {+ GCExtendedGamepad *p = c.extendedGamepad;+ if (!p) continue;+ NSString *s = [NSString stringWithFormat:@"x=%+.3f y=%+.3f A=%.2f",+ p.leftThumbstick.xAxis.value, p.leftThumbstick.yAxis.value, p.buttonA.value];+ NSValue *key = [NSValue valueWithNonretainedObject:c];+ if (![last[key] isEqualToString:s]) {+ last[key] = s;+ printf(" [poll %s] %s\n", c.vendorName.UTF8String ?: "?", s.UTF8String);+ fflush(stdout);+ }+ }+ }];+ (void)poll;++ [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:seconds]];++ NSArray *final = GCController.controllers;+ printf("final controllers: %lu\n", (unsigned long)final.count);+ for (GCController *c in final) describe("final:", c);+ if (@available(macOS 11.0, *)) {+ GCController *cur = GCController.current;+ printf("current: %s\n", cur ? (cur.vendorName.UTF8String ?: "(null)") : "(none)");+ }+ }+ return 0;+}diff --git a/native-shim/tests/run.sh b/native-shim/tests/run.shnew file mode 100755index 0000000..79ab143--- /dev/null+++ b/native-shim/tests/run.sh@@ -0,0 +1,20 @@+#!/bin/sh+# Builds and runs the hid_profile unit tests with ASan and UBSan. Exits non-zero on failure.+set -eu+here=$(cd "$(dirname "$0")" && pwd)+out=${TMPDIR:-/tmp}/np_hid_profile_tests+clang -arch arm64 -std=c11 -D_DARWIN_C_SOURCE -g -O1 -Wall -Wextra -Werror \+ -fsanitize=address,undefined -fno-sanitize-recover=all \+ -framework IOKit -framework CoreFoundation \+ -o "$out" "$here/../hid_profile.c" "$here/test_hid_profile.c"+"$out" "$here/fixtures"++# LeakSanitizer is not available on macOS; check leaks with the system tool instead.+if command -v leaks >/dev/null 2>&1; then+ clang -arch arm64 -std=c11 -D_DARWIN_C_SOURCE -g -O1 -Wall -Wextra -Werror \+ -framework IOKit -framework CoreFoundation \+ -o "$out.leaks" "$here/../hid_profile.c" "$here/test_hid_profile.c"+ MallocStackLogging=1 leaks --atExit -quiet -- "$out.leaks" "$here/fixtures" >"$out.leaks.log" 2>&1 \+ || { cat "$out.leaks.log"; echo "leaks found"; exit 1; }+ grep -E "leaks for|Process [0-9]+:" "$out.leaks.log" | tail -1+fidiff --git a/native-shim/tests/test_hid_profile.c b/native-shim/tests/test_hid_profile.cnew file mode 100644index 0000000..204f950--- /dev/null+++ b/native-shim/tests/test_hid_profile.c@@ -0,0 +1,369 @@+// Unit tests for hid_profile.c, without IOKit devices. Run through tests/run.sh.++#include "../hid_profile_internal.h"++#include <assert.h>+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#define CHECK(cond) do { if (!(cond)) { fprintf(stderr, "%s:%d: CHECK failed: %s\n", \+ __FILE__, __LINE__, #cond); exit(1); } } while (0)+#define NEAR(a, b) CHECK(fabsf((float)(a) - (float)(b)) < 1e-3f)+#define BTN(n) (1u << (n))++static const char *fixtures;++static size_t read_hex(const char *path, uint8_t *out, size_t cap) {+ FILE *f = fopen(path, "r");+ CHECK(f);+ size_t n = 0;+ int hi = -1, c;+ while ((c = fgetc(f)) != EOF) {+ int v = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10+ : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1;+ if (v < 0) continue;+ if (hi < 0) hi = v;+ else { CHECK(n < cap); out[n++] = (uint8_t)(hi << 4 | v); hi = -1; }+ }+ fclose(f);+ return n;+}++// Copy of the arithmetic of relay_report() in gamepad_shim.c (the hand-written+// GameSir G7 Pro translator this module replaces).+static int reference_relay(const uint8_t *report, long length, uint8_t x[18]) {+ if (report[0] != 7 || length < 10) return 0;+ memset(x, 0, 18);+ x[0] = 1;+ unsigned v[6] = {report[1] * 257u, report[2] * 257u, report[3] * 257u, report[4] * 257u,+ report[9] * 1023u / 255u, report[8] * 1023u / 255u};+ for (int i = 0; i < 6; i++) { x[1 + 2 * i] = v[i] & 0xff; x[2 + 2 * i] = v[i] >> 8; }+ unsigned hat = report[5] & 0x0f;+ x[13] = hat < 8 ? hat + 1 : 0;+ x[14] = report[6];+ x[15] = report[7];+ return 1;+}++static np_profile *decode_hex(np_profile *p, const char *hex, np_pad_state *s) {+ uint8_t r[64];+ size_t n = 0;+ for (const char *c = hex; c[0] && c[1]; ) {+ if (c[0] == ' ') { c++; continue; }+ unsigned v;+ CHECK(sscanf(c, "%2x", &v) == 1);+ r[n++] = (uint8_t)v;+ c += 2;+ }+ CHECK(np_profile_decode(p, r[0], r, (long)n, s));+ return p;+}++static void test_gamesir(void) {+ char path[1024];+ uint8_t desc[1024];+ snprintf(path, sizeof path, "%s/gamesir_g7pro_bt.hex", fixtures);+ size_t len = read_hex(path, desc, sizeof desc);+ CHECK(len == 284);++ np_profile *p = np_profile_create_from_descriptor(desc, len, 0x3537, 0x1022, 0x011b,+ "GameSir-G7 Pro");+ CHECK(p);+ CHECK(!strcmp(np_profile_guid(p), "0300000037350000221000001b010000"));+ CHECK(!strcmp(np_profile_name(p), "GameSir G7 Pro (Bluetooth)"));+ int axes, buttons, hats;+ np_profile_counts(p, &axes, &buttons, &hats);+ // Gamepad collection only: X Y Z Rz Accel Brake, buttons 1-16, one hat. The Consumer,+ // Keyboard and Mouse collections of the same device are not counted.+ CHECK(axes == 6 && buttons == 16 && hats == 1);++ // Reports of the other collections are not decoded.+ np_pad_state s;+ uint8_t consumer[] = {2, 0x01, 0x00, 0x00};+ uint8_t mouse[] = {6, 0x01, 0x10, 0x00, 0x10, 0x00, 0x00, 0x00};+ CHECK(!np_profile_decode(p, 2, consumer, sizeof consumer, &s));+ CHECK(!np_profile_decode(p, 6, mouse, sizeof mouse, &s));++ // Every recorded report: decode + encode == the hand-written translator, except for+ // the button bits the DB line leaves unmapped (b2 b5 b8 b9 b12 b15), which the old+ // translator copied through blindly and which are no Xbox control.+ const uint16_t mapped_bits = 0x6CDB;+ snprintf(path, sizeof path, "%s/gamesir_g7pro_bt_reports.txt", fixtures);+ FILE *f = fopen(path, "r");+ CHECK(f);+ char line[256];+ int compared = 0;+ while (fgets(line, sizeof line, f)) {+ unsigned id, n;+ int off;+ if (sscanf(line, "id=%u len=%u:%n", &id, &n, &off) != 2) continue;+ uint8_t r[64];+ const char *c = line + off;+ for (unsigned i = 0; i < n; i++) {+ unsigned v;+ int used;+ CHECK(sscanf(c, " %2x%n", &v, &used) == 1);+ r[i] = (uint8_t)v;+ c += used;+ }+ uint8_t want[18], got[18];+ CHECK(reference_relay(r, n, want));+ CHECK(np_profile_decode(p, id, r, n, &s));+ np_xbox_encode(&s, got);+ uint16_t want_b = (uint16_t)(want[14] | want[15] << 8) & mapped_bits;+ uint16_t got_b = (uint16_t)(got[14] | got[15] << 8);+ if (memcmp(want, got, 14) || want_b != got_b || got[16] || got[17]) {+ fprintf(stderr, "mismatch for %s", line);+ for (int i = 0; i < 18; i++) fprintf(stderr, " %02x/%02x", want[i], got[i]);+ fprintf(stderr, "\n");+ exit(1);+ }+ compared++;+ }+ fclose(f);+ CHECK(compared == 119);++ // Spot checks.+ uint8_t x[18];+ decode_hex(p, "07 80 82 81 82 0f 01 00 00 00 00", &s); // A+ CHECK(s.buttons == BTN(NP_BTN_A));+ np_xbox_encode(&s, x);+ CHECK(x[0] == 1 && x[14] == 0x01 && x[15] == 0 && x[13] == 0);+ decode_hex(p, "07 80 82 81 82 00 00 00 00 00 00", &s); // hat up+ CHECK(s.buttons == BTN(NP_BTN_DPAD_UP));+ np_xbox_encode(&s, x);+ CHECK(x[13] == 1);+ decode_hex(p, "07 80 82 81 82 03 00 00 00 00 00", &s); // hat down-right+ CHECK(s.buttons == (BTN(NP_BTN_DPAD_DOWN) | BTN(NP_BTN_DPAD_RIGHT)));+ np_xbox_encode(&s, x);+ CHECK(x[13] == 4);+ decode_hex(p, "07 80 82 81 82 0f 00 00 00 ff 00", &s); // brake = LT+ NEAR(s.lt, 1.0f);+ NEAR(s.rt, 0.0f);+ np_xbox_encode(&s, x);+ CHECK((x[9] | x[10] << 8) == 1023 && (x[11] | x[12] << 8) == 0);+ decode_hex(p, "07 00 ff 80 80 0f c0 0c 00 00 00", &s); // LB RB back start, stick corner+ NEAR(s.lx, -1.0f);+ NEAR(s.ly, 1.0f);+ CHECK(s.buttons == (BTN(NP_BTN_LEFTSHOULDER) | BTN(NP_BTN_RIGHTSHOULDER) |+ BTN(NP_BTN_BACK) | BTN(NP_BTN_START)));+ np_xbox_encode(&s, x);+ CHECK((x[1] | x[2] << 8) == 0 && (x[3] | x[4] << 8) == 65535);+ CHECK((x[14] | x[15] << 8) == (0x40 | 0x80 | 0x400 | 0x800));+ decode_hex(p, "07 80 82 81 82 0f 00 60 00 00 00", &s); // L3 R3+ CHECK(s.buttons == (BTN(NP_BTN_LEFTSTICK) | BTN(NP_BTN_RIGHTSTICK)));+ np_profile_free(p);+ printf("ok GameSir G7 Pro BT: %d recorded reports match relay_report\n", compared);+}++// Report ID-less DInput pad: X Y Z Rz (8 bit), hat, 12 buttons.+static const uint8_t generic_desc[] = {+ 0x05, 0x01, 0x09, 0x04, 0xa1, 0x01,+ 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x04,+ 0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x81, 0x02,+ 0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3b, 0x01, 0x65, 0x14,+ 0x75, 0x04, 0x95, 0x01, 0x81, 0x42,+ 0x65, 0x00, 0x75, 0x04, 0x95, 0x01, 0x81, 0x03,+ 0x05, 0x09, 0x19, 0x01, 0x29, 0x0c, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0c, 0x81, 0x02,+ 0x75, 0x04, 0x95, 0x01, 0x81, 0x03,+ 0xc0,+};++static void test_generic(void) {+ np_profile *p = np_profile_create_from_descriptor(generic_desc, sizeof generic_desc,+ 0x1234, 0x5678, 0x0100, "USB Gamepad");+ CHECK(p);+ CHECK(!strcmp(np_profile_guid(p), "03000000341200007856000000010000"));+ // The Windows line for this GUID is ignored.+ CHECK(!strcmp(np_profile_name(p), "Generic HID gamepad"));+ int axes, buttons, hats;+ np_profile_counts(p, &axes, &buttons, &hats);+ CHECK(axes == 4 && buttons == 12 && hats == 1);++ np_pad_state s;+ uint8_t r[7] = {0x80, 0x80, 0x80, 0x80, 0x0f, 0x00, 0x00};+ CHECK(np_profile_decode(p, 0, r, sizeof r, &s));+ CHECK(s.buttons == 0);+ NEAR(s.lx, 0.0039f);+ NEAR(s.lt, 0.0f);+ r[0] = 0x00; r[1] = 0xff; r[2] = 0xff; r[3] = 0x00;+ r[4] = 0x02; // hat right+ r[5] = 0x01 | 0x10 | 0x40; // b0 (A), b4 (LB), b6 (LT digital)+ r[6] = 0x02 | 0x08; // b9 (start), b11 (RS)+ CHECK(np_profile_decode(p, 0, r, sizeof r, &s));+ NEAR(s.lx, -1.0f);+ NEAR(s.ly, 1.0f);+ NEAR(s.rx, 1.0f); // Z+ NEAR(s.ry, -1.0f); // Rz+ NEAR(s.lt, 1.0f);+ NEAR(s.rt, 0.0f);+ CHECK(s.buttons == (BTN(NP_BTN_A) | BTN(NP_BTN_LEFTSHOULDER) | BTN(NP_BTN_DPAD_RIGHT) |+ BTN(NP_BTN_START) | BTN(NP_BTN_RIGHTSTICK)));+ uint8_t x[18];+ np_xbox_encode(&s, x);+ CHECK(x[13] == 3 && (x[9] | x[10] << 8) == 1023);+ CHECK((x[14] | x[15] << 8) == (0x01 | 0x40 | 0x800 | 0x4000));+ // Short report: fields past the end keep their last value.+ CHECK(np_profile_decode(p, 0, r, 2, &s));+ np_profile_free(p);++ // A Mac line whose indices the device does not have is ignored.+ p = np_profile_create_from_descriptor(generic_desc, sizeof generic_desc, 0x1234, 0x5679,+ 0x0100, "USB Gamepad");+ CHECK(p && !strcmp(np_profile_name(p), "Generic HID gamepad"));+ np_profile_free(p);++ // No exact GUID: the line without a version matches.+ p = np_profile_create_from_descriptor(generic_desc, sizeof generic_desc, 0x1234, 0x567a,+ 0x0105, "USB Gamepad");+ CHECK(p && !strcmp(np_profile_name(p), "Versionless Pad"));+ uint8_t up[7] = {0x80, 0x80, 0x80, 0x80, 0x00, 0x01, 0x00};+ CHECK(np_profile_decode(p, 0, up, sizeof up, &s));+ CHECK(s.buttons == (BTN(NP_BTN_B) | BTN(NP_BTN_DPAD_UP))); // a:b1,b:b0+ np_profile_free(p);+ printf("ok generic DInput pad: default mapping, DB fallbacks\n");+}++// Report ID 3: X Y Rx Ry signed 16 bit, 4 buttons; plus a Consumer collection (ID 4).+static const uint8_t signed_desc[] = {+ 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x03,+ 0x16, 0x00, 0x80, 0x26, 0xff, 0x7f, 0x75, 0x10, 0x95, 0x04,+ 0x09, 0x30, 0x09, 0x31, 0x09, 0x33, 0x09, 0x34, 0x81, 0x02,+ 0x05, 0x09, 0x19, 0x01, 0x29, 0x04, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x04, 0x81, 0x02,+ 0x75, 0x04, 0x95, 0x01, 0x81, 0x03,+ 0xc0,+ 0x05, 0x0c, 0x09, 0x01, 0xa1, 0x01, 0x85, 0x04,+ 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x08, 0x19, 0x01, 0x29, 0x08, 0x81, 0x02,+ 0xc0,+};++static void put16s(uint8_t *at, int v) {+ at[0] = (uint8_t)(v & 0xff);+ at[1] = (uint8_t)((v >> 8) & 0xff);+}++static void test_signed16(void) {+ np_profile *p = np_profile_create_from_descriptor(signed_desc, sizeof signed_desc,+ 0x2222, 0x3333, 0x0001, "Pad16");+ CHECK(p);+ CHECK(!strcmp(np_profile_name(p), "Env Line")); // SDL_GAMECONTROLLERCONFIG wins+ int axes, buttons, hats;+ np_profile_counts(p, &axes, &buttons, &hats);+ CHECK(axes == 4 && buttons == 4 && hats == 0);++ np_pad_state s;+ uint8_t r[10] = {3};+ put16s(r + 1, -32768); put16s(r + 3, -32768); put16s(r + 5, 32767); put16s(r + 7, -32768);+ r[9] = 0x02;+ CHECK(np_profile_decode(p, 3, r, sizeof r, &s));+ NEAR(s.lx, -1.0f);+ NEAR(s.ly, 1.0f); // lefty:a1~+ NEAR(s.lt, 1.0f); // lefttrigger:+a2+ NEAR(s.rt, 0.0f); // righttrigger:-a2+ CHECK(s.buttons == (BTN(NP_BTN_A) | BTN(NP_BTN_DPAD_UP))); // a:b1, dpup:-a3+ uint8_t x[18];+ np_xbox_encode(&s, x);+ CHECK((x[1] | x[2] << 8) == 0 && (x[3] | x[4] << 8) == 65535);++ put16s(r + 1, 32767); put16s(r + 3, 0); put16s(r + 5, -32768); put16s(r + 7, 0);+ r[9] = 0x01;+ CHECK(np_profile_decode(p, 3, r, sizeof r, &s));+ NEAR(s.lx, 1.0f);+ NEAR(s.ly, 0.0f);+ NEAR(s.lt, 0.0f);+ NEAR(s.rt, 1.0f);+ CHECK(s.buttons == BTN(NP_BTN_B));+ put16s(r + 1, -16384);+ CHECK(np_profile_decode(p, 3, r, sizeof r, &s));+ NEAR(s.lx, -0.5f);++ uint8_t consumer[2] = {4, 0xff};+ CHECK(!np_profile_decode(p, 4, consumer, sizeof consumer, &s));+ np_profile_free(p);+ printf("ok signed 16-bit axes: normalisation, +/-/~ modifiers, report IDs\n");+}++static void test_left_alone(void) {+ const uint8_t *d = generic_desc;+ size_t n = sizeof generic_desc;+ CHECK(!np_profile_create_from_descriptor(d, n, 0x054C, 0x09CC, 0x0100, "Wireless Controller"));+ CHECK(!np_profile_create_from_descriptor(d, n, 0x045E, 0x0B13, 0x0100, "Controller"));+ CHECK(!np_profile_create_from_descriptor(d, n, 0x057E, 0x2009, 0x0100, "Pro Controller"));+ CHECK(!np_profile_create_from_descriptor(d, n, 0x057E, 0x2006, 0x0100, "Joy-Con (L)"));+ CHECK(!np_profile_create_from_descriptor(d, n, 0x0E6F, 0x02A4, 0x0100, "PDP Xbox Controller"));+ // Apple's VID is not "native": old GameSir pads (T3, 05ac:061a) use it.+ np_profile *p = np_profile_create_from_descriptor(d, n, 0x05AC, 0x061A, 0x0100, "GameSir-T3");+ CHECK(p);+ np_profile_free(p);+ // Nacon PS4-licensed pads are not Sony's.+ p = np_profile_create_from_descriptor(d, n, 0x146B, 0x0D01, 0x0100, "Nacon Revolution");+ CHECK(p);+ np_profile_free(p);++ // No gamepad collection: a mouse, and a vendor-page interface (Flydigi style).+ static const uint8_t mouse[] = {+ 0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00,+ 0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x03, 0x81, 0x02,+ 0x75, 0x05, 0x95, 0x01, 0x81, 0x03,+ 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x15, 0x81, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x02, 0x81, 0x06,+ 0xc0, 0xc0,+ };+ static const uint8_t vendor[] = {+ 0x06, 0xa0, 0xff, 0x09, 0x01, 0xa1, 0x01,+ 0x09, 0x02, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x20, 0x81, 0x02, 0xc0,+ };+ CHECK(!np_profile_create_from_descriptor(mouse, sizeof mouse, 0x1111, 0x2222, 1, "Mouse"));+ CHECK(!np_profile_create_from_descriptor(vendor, sizeof vendor, 0x04B4, 0x2412, 1, "Flydigi"));+ CHECK(!np_profile_create_from_descriptor(NULL, 0, 0x1111, 0x2222, 1, "x"));+ // Garbage must not crash.+ uint8_t junk[300];+ for (size_t i = 0; i < sizeof junk; i++) junk[i] = (uint8_t)(i * 73 + 11);+ np_profile_free(np_profile_create_from_descriptor(junk, sizeof junk, 0x1111, 0x2222, 1, "x"));+ printf("ok left alone: Sony, Microsoft, Nintendo, \"Xbox\", non-gamepads\n");+}++static void test_encode_and_mode(void) {+ np_pad_state s = {0};+ uint8_t x[18];+ np_xbox_encode(&s, x);+ CHECK(x[0] == 1 && (x[1] | x[2] << 8) == 32767 && x[13] == 0);+ s.buttons = BTN(NP_BTN_GUIDE) | BTN(NP_BTN_Y) | BTN(NP_BTN_X) | BTN(NP_BTN_DPAD_LEFT) |+ BTN(NP_BTN_DPAD_UP);+ s.rt = 0.5f;+ np_xbox_encode(&s, x);+ CHECK((x[14] | x[15] << 8) == (0x1000 | 0x10 | 0x08) && x[13] == 8);+ CHECK((x[11] | x[12] << 8) == 511);+ s.buttons = BTN(NP_BTN_DPAD_UP) | BTN(NP_BTN_DPAD_DOWN) | BTN(NP_BTN_DPAD_LEFT);+ np_xbox_encode(&s, x);+ CHECK(x[13] == 7);++ CHECK(np_pad_mode_from(NULL, 1) == NP_MODE_HID);+ CHECK(np_pad_mode_from(NULL, 0) == (NP_MODE_HID | NP_MODE_GC));+ CHECK(np_pad_mode_from("gc", 1) == NP_MODE_GC);+ CHECK(np_pad_mode_from("both", 1) == (NP_MODE_HID | NP_MODE_GC));+ CHECK(np_pad_mode_from("off", 0) == NP_MODE_OFF);+ CHECK(np_pad_mode_from("hid", 0) == NP_MODE_HID);+ CHECK(np_pad_mode() == (NP_MODE_HID | NP_MODE_GC)); // no UnityPlayer, env unset+ printf("ok xbox encode, pad mode\n");+}++int main(int argc, char **argv) {+ fixtures = argc > 1 ? argv[1] : "tests/fixtures";+ char db[1024];+ snprintf(db, sizeof db, "%s/test_gamecontrollerdb.txt", fixtures);+ setenv("NP_GAMECONTROLLERDB", db, 1);+ setenv("SDL_GAMECONTROLLERCONFIG",+ "03000000222200003333000001000000,Env Line,leftx:a0,lefty:a1~,lefttrigger:+a2,"+ "righttrigger:-a2,a:b1,b:b0,dpup:-a3,dpdown:+a3,platform:Mac OS X,\n"+ "03000000222200003333000001000000,Linux Line,a:b3,platform:Linux,\n", 1);+ unsetenv("NP_PAD_MODE");+ test_gamesir();+ test_generic();+ test_signed16();+ test_left_alone();+ test_encode_and_mode();+ printf("all tests passed\n");+ return 0;+}diff --git a/scripts/build-local.sh b/scripts/build-local.shindex 7a20a78..91d0ccd 100755--- a/scripts/build-local.sh+++ b/scripts/build-local.sh@@ -228,7 +228,7 @@ if [ "$run_checks" -eq 1 ]; thenstart=$(date +%s)for target in sigcheck callscheck webpatch-fixtures peicon-fixtures panel-behavior \spawn-env compatcheck compatsvc-check launch-shell envcheck buildcheck \- settingscheck routecheck bridgecheck gamedrivecheck seedcheck app-tests; do+ settingscheck routecheck bridgecheck gamedrivecheck seedcheck padcheck app-tests; doecho "==> [check] make -s $target" | tee -a "$check_log"[ "$target" != app-tests ] || link_test_sparkle >>"$check_log" 2>&1 || trueif make -s "$target" >>"$check_log" 2>&1; thendiff --git a/scripts/update-gamecontrollerdb.sh b/scripts/update-gamecontrollerdb.shnew file mode 100755index 0000000..ebb4a97--- /dev/null+++ b/scripts/update-gamecontrollerdb.sh@@ -0,0 +1,97 @@+#!/bin/sh+# Build the SDL controller mapping file the run script hands winebus.+#+# scripts/update-gamecontrollerdb.sh OUTPUT [--own FILE] [--db FILE|URL]+#+# Takes the community SDL_GameControllerDB, keeps its "platform:Mac OS X" lines, appends+# the hand-written lines from FILE (default: the user's gamecontrollerdb.txt) last, keeps+# only the last line for each GUID and writes the result to OUTPUT. SDL lets a later line+# for a GUID replace an earlier one, so the own lines win. The run script points+# SDL_GAMECONTROLLERCONFIG_FILE at gamecontrollerdb.merged.txt next to gamecontrollerdb.txt.+#+# Windows and Linux lines are not converted: their button and axis indices come from+# DirectInput and evdev, which number a pad's controls differently from SDL's IOKit+# driver, so a converted GUID would carry a wrong layout.++set -eu++db_url=https://raw.githubusercontent.com/mdqinc/SDL_GameControllerDB/master/gamecontrollerdb.txt+own="$HOME/Library/Application Support/notproton/gamecontrollerdb.txt"+db="$db_url"+out=""++usage() {+ sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//' >&2+ exit 2+}++while [ $# -gt 0 ]; do+ case "$1" in+ --own) [ $# -ge 2 ] || usage; own="$2"; shift 2 ;;+ --db) [ $# -ge 2 ] || usage; db="$2"; shift 2 ;;+ -h|--help) usage ;;+ -*) echo "update-gamecontrollerdb: unknown option $1" >&2; usage ;;+ *) [ -z "$out" ] || usage; out="$1"; shift ;;+ esac+done+[ -n "$out" ] || usage++if [ -f "$out" ] && [ -f "$own" ] && [ "$out" -ef "$own" ]; then+ echo "update-gamecontrollerdb: OUTPUT is the own-lines file $own; the next run would treat the whole database as own lines" >&2+fi++work=$(mktemp -d "${TMPDIR:-/tmp}/gamecontrollerdb.XXXXXX")+trap 'rm -rf "$work"' EXIT INT TERM++case "$db" in+ http://*|https://*)+ curl -fsSL --retry 2 --max-time 60 -o "$work/community.txt" "$db" ;;+ *)+ cp "$db" "$work/community.txt" ;;+esac+[ -s "$work/community.txt" ] || { echo "update-gamecontrollerdb: $db is empty" >&2; exit 1; }++tr -d '\r' < "$work/community.txt" \+ | grep -E '^[0-9a-fA-F]{32},' \+ | grep -E '(^|,)platform:Mac OS X(,|$)' > "$work/mac.txt" || true+[ -s "$work/mac.txt" ] || { echo "update-gamecontrollerdb: no Mac OS X lines in $db" >&2; exit 1; }++# Own lines: SDL's file loader skips a line without a platform field, so a Mac one is added;+# a line for another platform would never load here and is dropped.+: > "$work/own.txt"+if [ -f "$own" ]; then+ tr -d '\r' < "$own" | sed -e '/^[[:space:]]*#/d' -e '/^[[:space:]]*$/d' | awk -v src="$own" '+ !/^[0-9a-fA-F]{32},/ { printf "update-gamecontrollerdb: %s: skipped line without a GUID: %s\n", src, $0 > "/dev/stderr"; next }+ /(^|,)platform:/ {+ if ($0 ~ /(^|,)platform:Mac OS X(,|$)/) print+ else printf "update-gamecontrollerdb: %s: skipped non-Mac line: %s\n", src, $0 > "/dev/stderr"+ next+ }+ { line = $0; sub(/,*$/, "", line); print line ",platform:Mac OS X," }+ ' > "$work/own.txt"+fi++community=$(wc -l < "$work/mac.txt" | tr -d ' ')+owned=$(wc -l < "$work/own.txt" | tr -d ' ')++# GUIDs compare case-insensitively in SDL; the last line for a GUID stays, in its place.+cat "$work/mac.txt" "$work/own.txt" | awk '+ { line[NR] = $0; g = tolower(substr($0, 1, 32)); last[g] = NR }+ END { for (i = 1; i <= NR; i++) if (last[tolower(substr(line[i], 1, 32))] == i) print line[i] }+' > "$work/merged.txt"+kept=$(wc -l < "$work/merged.txt" | tr -d ' ')++{+ echo "# SDL controller mappings for NotProton, built by scripts/update-gamecontrollerdb.sh"+ echo "# on $(date -u +%Y-%m-%dT%H:%M:%SZ): $community Mac lines from $db, then $owned from $own;"+ echo "# $kept after keeping the last line per GUID. Regenerate it rather than editing it."+ cat "$work/merged.txt"+} > "$work/out.txt"++out_dir=$(dirname "$out")+mkdir -p "$out_dir"+tmp_out=$(mktemp "$out_dir/.gamecontrollerdb.XXXXXX")+cat "$work/out.txt" > "$tmp_out"+chmod 644 "$tmp_out"+mv -f "$tmp_out" "$out"+echo "update-gamecontrollerdb: wrote $out: $kept mappings ($community community Mac, $owned own, $((community + owned - kept)) replaced), $(wc -c < "$out" | tr -d ' ') bytes"