Skip to content
Merged
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
14 changes: 13 additions & 1 deletion src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7345,6 +7345,18 @@ fn controllers() -> Vec<pads::Pad> {
pads::connected()
}

/// The window must leave controllers to the launcher (see pads::window_stays_off).
#[tauri::command(async)]
fn pads_window_off() -> bool {
pads::window_stays_off()
}

/// The right stick, for Big Picture's box tilt.
#[tauri::command(async)]
fn pad_right_stick() -> [f32; 2] {
pads::right_stick()
}

/// Keep these pictures on disk, so pages show at once and work offline.
#[tauri::command(async)]
fn prefetch_images(st: State<'_, App>, urls: Vec<String>) {
Expand Down Expand Up @@ -10628,7 +10640,7 @@ pub fn run() {
get_state, get_catalog, get_releases, net_state, check_updates, launcher_update, install, cancel, uninstall, play, stop, set_exe, forget_program, set_setup_mode, open_folder, open_setup_log,
save_settings, set_start_at_login, list_monitors, prepare_tv_mode, leave_tv_mode, open_url, libraries, move_game, game_sizes, game_size, backups, backup_now, restore_backup, pc_check, set_ui_scale, update_retry, ge_proton_install, proton_now, repo_readme, install_vcredist, scan_roms, rom_matches, copy_files, support_local,
desktop_shortcut, refresh_shortcut_art, open_app_control, fs_paste, portable_info, make_portable, add_to_steam, launcher_to_steam, steam_sync::steam_sync_now, steam_sync::steam_sync_state, steam_sync::steam_remove_all, recent_log, screenshots, open_shots, overlay_action, overlay_state, is_handheld, skip_backup, set_cover, art::art_source, art::art_open, art::art_save, art::art_search, art::art_for, launchbox::launchbox_find, launchbox::launchbox_search, launchbox::launchbox_pictures, all_screenshots, delete_screenshot,
copy_screenshot, show_screenshot, controllers, prefetch_images, versions, build_check, news, game_info, mods_state, mods_online,
copy_screenshot, show_screenshot, controllers, pads_window_off, pad_right_stick, prefetch_images, versions, build_check, news, game_info, mods_state, mods_online,
mod_install, mod_remove, open_mods, send_report, beta_feedback, logs_zip::export_logs, game_programs, start_with_programs, run_program, game_root, boot::boot_builtin, update_launcher, resume_game, game_setup, set_game_copy, free_up_space, set_update_copy, set_game_setting, set_game_slider, set_game_binding, reset_game_bindings, usage::report_preview, usage::profile_report, usage::my_reports, usage::report_reply, usage::review_delete,
recomp_games, adopt::move_listing, update_info, set_proxy, umu_repair, dlss_fetch, dlss_set, dlss_state, dlss_remove, cloud::library_pull, cloud::library_push, cloud::playtime_push, cloud::playtime_pull, cloud::playtime_reset, cloud::spons_mine, cloud::spons_seen, cloud::home_layout, cloud::saves_open_backups, game_action, setup_copy, setup_cancel, setup_status, setup_begin, setup_end, setup_input_set, setup_key_remove, setup_inputs_run, easy_setup, set_game_options,
set_prepare_opts,
Expand Down
59 changes: 58 additions & 1 deletion src-tauri/src/pads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use sdl3_sys::everything as sdl;
use std::collections::{HashMap, HashSet};
use std::ffi::{c_char, CStr, CString};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicI16, Ordering};
use std::sync::mpsc::{channel, Sender};
use std::sync::Mutex;
use tauri::{AppHandle, Emitter, Manager};
Expand Down Expand Up @@ -296,6 +296,8 @@ impl Reader {
if let Some(o) = open.remove(&unsafe { ev.gdevice.which }) {
// SAFETY: opened above, closed once.
unsafe { sdl::SDL_CloseGamepad(o.pad) };
// A controller that's gone isn't tilting anything.
RIGHT_STICK.iter().for_each(|v| v.store(0, Ordering::Relaxed));
list(open);
}
}
Expand All @@ -312,6 +314,7 @@ impl Reader {
sdl::SDL_EVENT_GAMEPAD_AXIS_MOTION => {
let a = unsafe { ev.gaxis };
let Some(o) = open.get_mut(&a.which) else { continue };
keep_right_stick(sdl::SDL_GamepadAxis(a.axis as i32), a.value);
for (down, n) in o.axes.moved(sdl::SDL_GamepadAxis(a.axis as i32), a.value) {
let _ = tx.send(if down { Ev::Down(n, o.kind) } else { Ev::Up(n) });
}
Expand All @@ -329,6 +332,7 @@ fn read_sdl(tx: Sender<Ev>, mappings: PathBuf) {
RUNNING.store(false, Ordering::Relaxed);
return;
}
READY.store(true, Ordering::Relaxed);
let mut reader = Reader::default();
while !STOP.load(Ordering::Relaxed) {
reader.poll(&tx);
Expand All @@ -339,6 +343,7 @@ fn read_sdl(tx: Sender<Ev>, mappings: PathBuf) {
let playing = PLAYING.load(Ordering::Relaxed);
std::thread::sleep(std::time::Duration::from_millis(if idle() { 60 } else if playing && !FOCUSED.load(Ordering::Relaxed) { 25 } else { 10 }));
}
READY.store(false, Ordering::Relaxed);
reader.close();
// SAFETY: the last SDL call, on SDL's thread.
unsafe { sdl::SDL_Quit() };
Expand All @@ -352,6 +357,44 @@ fn read_sdl(tx: Sender<Ev>, mappings: PathBuf) {

/// SDL's thread is running (or starting).
static RUNNING: AtomicBool = AtomicBool::new(false);
/// SDL started and is reading controllers.
static READY: AtomicBool = AtomicBool::new(false);
/// The right stick's last position (SDL's -32768..32767, Y positive downwards), for Big Picture's
/// box tilt: on Windows the window can't ask for its own controllers without upsetting them
/// (see `window_stays_off`).
static RIGHT_STICK: [AtomicI16; 2] = [AtomicI16::new(0), AtomicI16::new(0)];

fn keep_right_stick(axis: sdl::SDL_GamepadAxis, value: i16) {
use sdl::SDL_GamepadAxis as A;
let i = match axis {
A::RIGHTX => 0,
A::RIGHTY => 1,
_ => return,
};
RIGHT_STICK[i].store(value, Ordering::Relaxed);
}

/// The right stick, -1..1 each way, Y positive downwards (as the browser's gamepads have it).
pub fn right_stick() -> [f32; 2] {
RIGHT_STICK.each_ref().map(|v| (v.load(Ordering::Relaxed) as f32 / 32767.0).clamp(-1.0, 1.0))
}

/// Whether the window must leave controllers to the launcher, waiting a moment if SDL is still
/// starting. On Windows, while SDL reads them, the window must not ask for gamepads
/// (navigator.getGamepads): that starts WebView2's own controller reading, raw input beside
/// SDL's XInput, and that pair switches off a controller reconnecting through the Xbox Wireless
/// Adapter (issue #496). Elsewhere the window's reading does no harm and stays as the fallback
/// for a controller SDL doesn't open.
pub fn window_stays_off() -> bool {
if !cfg!(windows) {
return false;
}
let t = std::time::Instant::now();
while RUNNING.load(Ordering::Relaxed) && !READY.load(Ordering::Relaxed) && t.elapsed() < std::time::Duration::from_secs(3) {
std::thread::sleep(std::time::Duration::from_millis(10));
}
READY.load(Ordering::Relaxed)
}
/// The launcher is closing: SDL's thread closes the controllers and stops.
static STOP: AtomicBool = AtomicBool::new(false);

Expand Down Expand Up @@ -650,6 +693,11 @@ mod tests {
r.poll(&tx);
let got: Vec<Ev> = rx.try_iter().collect();
assert_eq!(got, vec![Ev::Down("a", "xbox"), Ev::Down("view", "xbox"), Ev::Up("a"), Ev::Down("right", "xbox")]);
// The right stick is kept for Big Picture's tilt, not sent as presses.
axis(x, A::RIGHTY, -32768);
r.poll(&tx);
assert_eq!(right_stick(), [0.0, -1.0]);
assert!(rx.try_iter().next().is_none());

// A Switch Pro Controller: its A is on the right.
let (nid, n) = attach(0x057E, 0x2009);
Expand All @@ -669,6 +717,7 @@ mod tests {
}
r.poll(&tx);
assert_eq!(connected().iter().map(|p| p.kind).collect::<Vec<_>>(), vec!["nintendo"]);
assert_eq!(right_stick(), [0.0, 0.0]);
// Closing the launcher closes the rest.
r.close();
assert!(connected().is_empty(), "{:?}", connected());
Expand All @@ -679,6 +728,14 @@ mod tests {
}
}

/// Only Windows has the Xbox Wireless Adapter trouble (#496): elsewhere the window keeps
/// its own controller reading as the fallback.
#[test]
#[cfg(not(windows))]
fn the_window_reads_controllers_outside_windows() {
assert!(!window_stays_off());
}

#[test]
fn a_held_across_focus_waits_for_its_release() {
let mut h = HeldOver::default();
Expand Down
34 changes: 22 additions & 12 deletions tests/gamepad-stick.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,46 +9,50 @@ const start = tv.indexOf(' const STD = ');
const end = tv.indexOf(' // F11 switches', start);
assert.ok(start >= 0 && end > start, 'the controller fallback is present');

function controller(settings = {}) {
// The fallback starts once the core has said whether the window must leave controllers to it (`windowOff`).
async function controller(settings = {}, windowOff = false) {
let time = 0;
const timers = [], presses = [];
const asked = { gamepads: 0 };
const gp = { index: 0, id: 'standard controller', axes: [0, 0], buttons: Array.from({ length: 17 }, () => ({ pressed: false })) };
const getGamepads = () => { asked.gamepads++; return [gp]; };
const context = vm.createContext({
S: { settings }, TV: { on: true }, nativeSeen: false,
navigator: { getGamepads: () => [gp] }, document: { hasFocus: () => true },
S: { settings }, TV: { on: true }, nativeSeen: false, padsAnswer: Promise.resolve(windowOff),
navigator: { getGamepads }, document: { hasFocus: () => true },
performance: { now: () => time }, setTimeout: fn => timers.push(fn),
pad: button => presses.push(button),
});
vm.runInContext(tv.slice(start, end), context);
await new Promise(setImmediate);
return {
gp, settings, presses,
gp, settings, presses, asked, timers,
tick(ms = 33) { time += ms; assert.ok(timers.length); timers.shift()(); },
};
}

test('disabled stick navigation ignores the fallback controller axes', () => {
const c = controller({ pad_stick: false });
test('disabled stick navigation ignores the fallback controller axes', async () => {
const c = await controller({ pad_stick: false });
c.gp.axes = [0.9, -0.9];
c.tick();
assert.deepEqual(c.presses, []);
});

test('the fallback D-pad still works with stick navigation disabled', () => {
const c = controller({ pad_stick: false });
test('the fallback D-pad still works with stick navigation disabled', async () => {
const c = await controller({ pad_stick: false });
c.gp.buttons[13].pressed = true;
c.tick();
assert.deepEqual(c.presses, ['down']);
});

test('fallback stick navigation remains enabled by default', () => {
const c = controller();
test('fallback stick navigation remains enabled by default', async () => {
const c = await controller();
c.gp.axes[0] = -0.9;
c.tick();
assert.deepEqual(c.presses, ['left']);
});

test('turning stick navigation off stops a held fallback direction from repeating', () => {
const c = controller({ pad_stick: true });
test('turning stick navigation off stops a held fallback direction from repeating', async () => {
const c = await controller({ pad_stick: true });
c.gp.axes[0] = 0.9;
c.tick();
assert.deepEqual(c.presses, ['right']);
Expand All @@ -57,3 +61,9 @@ test('turning stick navigation off stops a held fallback direction from repeatin
c.tick(600);
assert.deepEqual(c.presses, ['right']);
});

test('on Windows the window never asks for gamepads while SDL reads controllers', async () => {
const c = await controller({}, true);
assert.equal(c.timers.length, 0);
assert.equal(c.asked.gamepads, 0);
});
25 changes: 21 additions & 4 deletions ui/tv.js
Original file line number Diff line number Diff line change
Expand Up @@ -875,8 +875,21 @@
PRE.set(src, im);
if (PRE.size > 60) PRE.delete(PRE.keys().next().value);
}
// Whether this window must leave controllers to the core; null until it answers. On Windows,
// while SDL reads them, asking for gamepads starts WebView2's own controller reading, and the two
// together switch off a controller reconnecting through the Xbox Wireless Adapter (#496).
let padsWindowOff = null;
// Outside the launcher (a page opened on its own) there's no core to ask: the window reads them.
const padsAnswer = Promise.resolve().then(() => invoke('pads_window_off')).catch(() => false).then((off) => { padsWindowOff = off; return off; });
// The box you're on tilts with the right stick (or the mouse over it), like turning it in your hands.
const TILT = { raf: 0, x: 0, y: 0, mx: 0, my: 0, mouseAt: 0, el: null };
const TILT = { raf: 0, x: 0, y: 0, mx: 0, my: 0, mouseAt: 0, el: null, stick: [0, 0], asking: false, askedAt: 0 };
// The core's right stick, asked for every 50 ms at most; the tilt eases towards the last answer.
function askRightStick() {
if (TILT.asking || performance.now() - TILT.askedAt < 50) return;
TILT.asking = true;
TILT.askedAt = performance.now();
invoke('pad_right_stick').then((s) => { TILT.stick = s; }).catch(() => {}).finally(() => { TILT.asking = false; });
}
function tiltStart() {
if (TILT.raf || lighter()) return;
TILT.raf = requestAnimationFrame(tiltTick);
Expand All @@ -891,7 +904,11 @@
if (!f || !TV.on) { TILT.x = TILT.y = 0; return; }
let sx = 0, sy = 0;
if (performance.now() - TILT.mouseAt < 1500) { sx = TILT.mx; sy = TILT.my; }
else if (navigator.getGamepads) {
else if (padsWindowOff) {
askRightStick();
[sx, sy] = TILT.stick;
if (Math.hypot(sx, sy) < 0.15) sx = sy = 0;
} else if (padsWindowOff === false && navigator.getGamepads) {
for (const gp of navigator.getGamepads()) {
if (!gp || gp.axes.length < 4) continue;
const x = gp.axes[2] || 0, y = gp.axes[3] || 0;
Expand Down Expand Up @@ -3392,7 +3409,7 @@
}

// Controllers: from the core (Xbox through XInput, PlayStation read directly), with the
// window's own gamepad support as a fallback if the core never reports anything.
// window's own gamepad support as a fallback, except where it must leave them to the core (padsWindowOff).
let nativeSeen = false;
let lastPad = { b: '', t: 0 };
const BORN = performance.now();
Expand Down Expand Up @@ -3477,7 +3494,7 @@
held[k] = now;
}
}
pollPads();
padsAnswer.then((off) => { if (!off) pollPads(); });

// F11 switches between the desktop view and Big Picture mode.
document.addEventListener('keydown', (e) => {
Expand Down
Loading