Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
684 changes: 684 additions & 0 deletions controller_helper.py

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions electron-builder.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@ module.exports = {
"package.json",
"lutris_wrapper.sh",
"lutris_wrapper.py",
"controller_helper.py",
"src_backend/**/*",
"!node_modules/**/{test,tests,example,examples,doc,docs}/**/*",
],
asarUnpack: [
"lutris_wrapper.sh",
"lutris_wrapper.py",
"controller_helper.py",
"electron_preload.cjs",
"src_backend/resources/gamecontrollerdb.txt",
],
Expand Down
6 changes: 6 additions & 0 deletions electron.cjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const { app, Menu } = require("electron");

const { getAppConfig } = require("./src_backend/config_manager.cjs");
const {
initControllerModeManager,
shutdownControllerModeManager,
} = require("./src_backend/controller_mode_manager.cjs");
const {
closeRunningGameProcess,
toggleGamePause,
Expand Down Expand Up @@ -34,6 +38,7 @@ app.on("second-instance", () => {
});

app.on("window-all-closed", () => {
shutdownControllerModeManager();
if (getAppConfig().keepGamesRunningOnQuit) {
toggleGamePause({ forceStatus: "running" });
} else {
Expand Down Expand Up @@ -88,6 +93,7 @@ app

try {
registerIpcHandlers();
initControllerModeManager();
createWindow(() => {
logInfo("Main window closed!");
if (!getAppConfig().keepGamesRunningOnQuit) {
Expand Down
1 change: 1 addition & 0 deletions electron_preload.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,5 @@ contextBridge.exposeInMainWorld("electronAPI", {

// Sdl
pollGamepadsSdl: () => ipcRenderer.invoke("poll-gamepads-sdl"),
listControllers: () => ipcRenderer.invoke("list-controllers"),
});
1 change: 1 addition & 0 deletions src_backend/config_manager.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const defaultConfig = {
showRunnerIcon: true,
keepGamesRunningOnQuit: false,
enableUiActionSoundFeedbacks: true,
controllerInputMode: "native",
};

const SUBSCRIPTIONS = {};
Expand Down
72 changes: 72 additions & 0 deletions src_backend/controller_family_db.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
const { readFileSync } = require("node:fs");

const { localeAppFile, logWarn } = require("./utils.cjs");

let controllerDbCache = null;

const FAMILY_PATTERNS = [
{ family: "playstation", pattern: /dualsense|dualshock|playstation|\bps4\b|\bps5\b|wireless controller|sony/i },
{ family: "xbox", pattern: /xbox|xinput|microsoft/i },
{ family: "nintendo", pattern: /\bswitch\b|joy-?con|pro controller|nintendo/i },
{ family: "steam", pattern: /steam deck|steam controller|valve/i },
{ family: "8bitdo", pattern: /8bitdo/i },
{ family: "generic", pattern: /gamepad|controller|joystick/i },
];

function normalizeHex(value) {
return (value || "0000").toLowerCase().replace(/^0x/, "").padStart(4, "0");
}

function loadControllerDatabase() {
if (controllerDbCache) {
return controllerDbCache;
}

const dbPath = localeAppFile("./src_frontend/resources/gamepad_mapping_db.json");
if (dbPath instanceof Error) {
logWarn("controller_family_db", "controller mapping database not found");
controllerDbCache = {};
return controllerDbCache;
}

try {
const raw = readFileSync(dbPath, "utf8");
const parsed = JSON.parse(raw);
controllerDbCache = parsed && typeof parsed === "object" ? parsed : {};
} catch (error) {
logWarn("controller_family_db", "unable to parse controller mapping database", error);
controllerDbCache = {};
}

return controllerDbCache;
}

function inferFamilyFromName(name = "") {
const text = name;
for (const { family, pattern } of FAMILY_PATTERNS) {
if (pattern.test(text)) {
return family;
}
}
return "unknown";
}

function resolveControllerIdentity(vendorId, productId, fallbackName) {
const db = loadControllerDatabase();
const key = `${normalizeHex(vendorId)}_${normalizeHex(productId)}`;
const entry = db[key];
const isRecognized = Boolean(entry?.n);
const standardizedName = entry?.n || fallbackName;
const family = inferFamilyFromName(standardizedName || "");

return {
databaseKey: key,
isRecognized,
standardizedName,
family,
};
}

module.exports = {
resolveControllerIdentity,
};
141 changes: 141 additions & 0 deletions src_backend/controller_mode_manager.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
const { spawn } = require("node:child_process");

const {
getAppConfig,
subscribeConfigValueChange,
} = require("./config_manager.cjs");
const { localeAppFile, logError, logInfo, logWarn } = require("./utils.cjs");

let helperProcess = null;
let grabbedDevice = null;
let virtualDevice = null;

function getControllerHelperPath() {
return localeAppFile("controller_helper.py");
}

function startXinputHelper() {
if (helperProcess) {
logWarn("controller_mode_manager", "xinput helper already running");
return;
}

let helperPath;
try {
helperPath = getControllerHelperPath();
} catch {
logError(
"controller_mode_manager",
"controller_helper.py not found, cannot start xinput mode",
);
return;
}

logInfo("controller_mode_manager", "starting xinput helper");

const proc = spawn(
"python3",
[helperPath, "serve", "--mode", "xinput", "--exclusive-grab"],
{ stdio: ["ignore", "pipe", "pipe"] },
);

const stdoutDecoder = new TextDecoder();
const stderrDecoder = new TextDecoder();

proc.stdout.on("data", (data) => {
const text = stdoutDecoder.decode(data).trim();
if (text) {
logInfo("controller_mode_manager", text);
try {
const msg = JSON.parse(text);
if (msg.status === "ready" && msg.vendorId && msg.productId) {
grabbedDevice = {
vendorId: msg.vendorId,
productId: msg.productId,
};
}
if (msg.status === "ready" && msg.virtualDevice) {
virtualDevice = msg.virtualDevice;
}
} catch {
// not JSON, ignore
}
}
});

proc.stderr.on("data", (data) => {
const text = stderrDecoder.decode(data).trim();
if (text) {
logError("controller_mode_manager", text);
}
});

proc.on("close", (code) => {
logInfo("controller_mode_manager", `xinput helper exited with code ${code}`);
if (helperProcess === proc) {
helperProcess = null;
grabbedDevice = null;
virtualDevice = null;
}
});

proc.on("error", (error) => {
logError("controller_mode_manager", "failed to start xinput helper", error);
if (helperProcess === proc) {
helperProcess = null;
grabbedDevice = null;
virtualDevice = null;
}
});

helperProcess = proc;
}

function stopXinputHelper() {
if (!helperProcess) {
return;
}

logInfo("controller_mode_manager", "stopping xinput helper");
helperProcess.kill("SIGTERM");
helperProcess = null;
grabbedDevice = null;
virtualDevice = null;
}

function applyInputMode(mode) {
if (mode === "xinput") {
startXinputHelper();
} else {
stopXinputHelper();
}
}

function initControllerModeManager() {
const config = getAppConfig();
applyInputMode(config.controllerInputMode);

subscribeConfigValueChange("controllerInputMode", (newMode) => {
logInfo("controller_mode_manager", `input mode changed to: ${newMode}`);
applyInputMode(newMode);
});
}

function shutdownControllerModeManager() {
stopXinputHelper();
}

function getGrabbedDevice() {
return grabbedDevice;
}

function getVirtualDevice() {
return virtualDevice;
}

module.exports = {
initControllerModeManager,
shutdownControllerModeManager,
getGrabbedDevice,
getVirtualDevice,
};
21 changes: 18 additions & 3 deletions src_backend/game_manager.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const path = require("node:path");
const { globalShortcut } = require("electron");

const { getAppConfig } = require("./config_manager.cjs");
const { getGrabbedDevice } = require("./controller_mode_manager.cjs");
const {
getCoverartPath,
getRuntimeIconPath,
Expand Down Expand Up @@ -280,13 +281,27 @@ function launchGame(gameId) {
}

const gameStartTime = Date.now();
const appConfig = getAppConfig();

const spawnOptions = {
detached: appConfig.keepGamesRunningOnQuit,
};

const grabbed = getGrabbedDevice();
if (appConfig.controllerInputMode === "xinput" && grabbed) {
const vid = `0x${grabbed.vendorId}`;
const pid = `0x${grabbed.productId}`;
spawnOptions.env = {
...process.env,
SDL_GAMECONTROLLER_IGNORE_DEVICES: `${vid}/${pid}`,
SDL_JOYSTICK_IGNORE_DEVICES: `${vid}/${pid}`,
};
}

const newGameProcess = spawn(
"bash",
[getLutrisWrapperPath(), `lutris:rungameid/${gameId}`],
{
detached: getAppConfig().keepGamesRunningOnQuit,
},
spawnOptions,
);

const stdoutTextDecoder = new TextDecoder();
Expand Down
6 changes: 5 additions & 1 deletion src_backend/ipc_handlers.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const {
updateLutrisSetting,
getLutrisRunners,
} = require("./lutris_wrapper.cjs");
const { mapSdlGamepadsToWebApi, pollGamepads } = require("./sdl_manager.cjs");
const { mapSdlGamepadsToWebApi, pollGamepads, listControllers } = require("./sdl_manager.cjs");
const { getMainWindow } = require("./state.cjs");
const { getUserTheme } = require("./theme_manager.cjs");
const {
Expand Down Expand Up @@ -303,6 +303,10 @@ function registerIpcHandlers() {
ipcHandleWithError("poll-gamepads-sdl", async () => {
return mapSdlGamepadsToWebApi(await pollGamepads());
});

ipcHandleWithError("list-controllers", async () => {
return await listControllers();
});
}

module.exports = { registerIpcHandlers };
23 changes: 23 additions & 0 deletions src_backend/sdl_bindings.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ function bindSDL2(lib) {

SDL_Init: lib.func("int SDL_Init(Uint32 flags)"),
SDL_Quit: lib.func("void SDL_Quit(void)"),
SDL_PumpEvents: lib.func("void SDL_PumpEvents(void)"),

SDL_RWFromFile: lib.func(
"void* SDL_RWFromFile(const char* file, const char* mode)",
Expand Down Expand Up @@ -59,8 +60,30 @@ function bindSDL2(lib) {
SDL_GameControllerName: lib.func(
"const char* SDL_GameControllerName(SDL_GameController* gamecontroller)",
),
SDL_GameControllerGetVendor: lib.func(
"Uint16 SDL_GameControllerGetVendor(SDL_GameController* gamecontroller)",
),
SDL_GameControllerGetProduct: lib.func(
"Uint16 SDL_GameControllerGetProduct(SDL_GameController* gamecontroller)",
),
};

try {
sdl.SDL_GameControllerGetProductVersion = lib.func(
"Uint16 SDL_GameControllerGetProductVersion(SDL_GameController* gamecontroller)",
);
} catch {
sdl.SDL_GameControllerGetProductVersion = null;
}

try {
sdl.SDL_GameControllerPath = lib.func(
"const char* SDL_GameControllerPath(SDL_GameController* gamecontroller)",
);
} catch {
sdl.SDL_GameControllerPath = null;
}

sdl.SDL_GameControllerAddMappingsFromFile = function (file) {
const rw = sdl.SDL_RWFromFile(file, "rb");
if (!rw) {
Expand Down
Loading