feat: show keyboard keys or the controller's own buttons in the hint bar
The hint bar always named Xbox buttons, so someone at a keyboard was told to press buttons they did not have, and owners of other pads got the wrong letters. Hints now name an action, and the keys or button icons come from the input used last: keyboard, or an Xbox, PlayStation, Switch or Steam Deck controller. Behind Steam, every pad is Steam's virtual one. remus reads the file Steam names in SteamVirtualGamepadInfo to find the physical controller, matching the slot in the pad's name, as SDL does. Icons are Kenney's Input Prompts (CC0), with the licence beside them.
This commit is contained in:
+84
-28
@@ -2,7 +2,7 @@
|
||||
//! through `slint::invoke_from_event_loop` + `with_app`.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::future::Future;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::PathBuf;
|
||||
@@ -19,6 +19,7 @@ use tokio::sync::Semaphore;
|
||||
use crate::config::{self, Config, Settings};
|
||||
use crate::palette::{Lab, Palette, Role, Tone};
|
||||
use crate::player::{Player, PlayerEvent};
|
||||
use crate::prompts::{self, Control, Family, Prompts};
|
||||
use crate::subsonic::{self, Album, Artist, Client, Playlist, SearchResult, Song};
|
||||
use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme};
|
||||
|
||||
@@ -43,7 +44,7 @@ pub fn install(ui: &AppWindow, rt: Handle) {
|
||||
let app = App::new(ui.clone_strong(), rt);
|
||||
APP.with(|cell| *cell.borrow_mut() = Some(app));
|
||||
|
||||
ui.on_action(|a| with_app(move |app| app.action(a)));
|
||||
ui.on_action(|a| with_app(move |app| app.key_action(a)));
|
||||
ui.on_item_clicked(|i| with_app(move |app| app.item_clicked(i.max(0) as usize)));
|
||||
ui.on_wheel(|d| with_app(move |app| app.wheel(d)));
|
||||
ui.on_sidebar_clicked(|i| with_app(move |app| app.sidebar_clicked(i.max(0) as usize)));
|
||||
@@ -216,6 +217,10 @@ pub struct App {
|
||||
scrobbled: bool,
|
||||
login_focus: i32,
|
||||
toast_timer: Timer,
|
||||
/// Keyboard keys or the buttons of the controller used last.
|
||||
prompts: Prompts,
|
||||
/// Decoded hint icons, so a selection move does not parse SVG again.
|
||||
icons: RefCell<HashMap<(Prompts, Control), Vec<Image>>>,
|
||||
settings: Settings,
|
||||
fade: Fade,
|
||||
}
|
||||
@@ -263,6 +268,8 @@ impl App {
|
||||
scrobbled: false,
|
||||
login_focus: 0,
|
||||
toast_timer: Timer::default(),
|
||||
prompts: Prompts::Keyboard,
|
||||
icons: RefCell::default(),
|
||||
settings: config::load_settings(),
|
||||
fade: Fade {
|
||||
from: Palette::brand(),
|
||||
@@ -405,6 +412,30 @@ impl App {
|
||||
|
||||
// ---------------------------------------------------------------- input
|
||||
|
||||
/// A key pressed in the window.
|
||||
pub fn key_action(&mut self, a: Action) {
|
||||
self.set_prompts(Prompts::Keyboard);
|
||||
self.action(a);
|
||||
}
|
||||
|
||||
/// A button pressed on a controller of this family.
|
||||
pub fn pad_action(&mut self, a: Action, family: Family) {
|
||||
self.set_prompts(Prompts::Pad(family));
|
||||
self.action(a);
|
||||
}
|
||||
|
||||
/// A controller connected (its family) or the last one disconnected.
|
||||
pub fn pad_present(&mut self, family: Option<Family>) {
|
||||
self.set_prompts(family.map_or(Prompts::Keyboard, Prompts::Pad));
|
||||
}
|
||||
|
||||
fn set_prompts(&mut self, prompts: Prompts) {
|
||||
if prompts != self.prompts {
|
||||
self.prompts = prompts;
|
||||
self.render_hints();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn action(&mut self, a: Action) {
|
||||
match a {
|
||||
Action::Quit => {
|
||||
@@ -1225,26 +1256,32 @@ impl App {
|
||||
}
|
||||
|
||||
fn render_hints(&self) {
|
||||
let h = |k: &str, l: &str| Hint {
|
||||
key: k.into(),
|
||||
label: l.into(),
|
||||
};
|
||||
let mut hints = Vec::new();
|
||||
let mut h = |c: Control, l: &str| {
|
||||
let icons = self.hint_icons(c);
|
||||
// Nothing to press for it with this input, such as Steam + X on a keyboard.
|
||||
if !icons.is_empty() {
|
||||
hints.push(Hint {
|
||||
icons: ModelRc::new(VecModel::from(icons)),
|
||||
label: l.into(),
|
||||
});
|
||||
}
|
||||
};
|
||||
match self.screen {
|
||||
Screen::Login => {
|
||||
hints.push(h("A", if self.login_focus < 2 { "Next" } else { "Connect" }));
|
||||
h(Control::Activate, if self.login_focus < 2 { "Next" } else { "Connect" });
|
||||
}
|
||||
Screen::Browse => match self.area {
|
||||
Area::Sidebar => {
|
||||
hints.push(h("A", "Open"));
|
||||
hints.push(h("X", "Play / Pause"));
|
||||
hints.push(h("VIEW", "Search"));
|
||||
hints.push(h("MENU", "Now playing"));
|
||||
h(Control::Activate, "Open");
|
||||
h(Control::PlayPause, "Play / Pause");
|
||||
h(Control::Search, "Search");
|
||||
h(Control::NowPlaying, "Now playing");
|
||||
}
|
||||
Area::Search => {
|
||||
hints.push(h("A", "Search"));
|
||||
hints.push(h("B", "Back"));
|
||||
hints.push(h("STEAM + X", "Keyboard"));
|
||||
h(Control::Activate, "Search");
|
||||
h(Control::Back, "Back");
|
||||
h(Control::OnScreenKeyboard, "Keyboard");
|
||||
}
|
||||
_ => {
|
||||
let target = self
|
||||
@@ -1252,34 +1289,53 @@ impl App {
|
||||
.and_then(|p| p.entries.get(p.sel))
|
||||
.map(|e| &e.target);
|
||||
match target {
|
||||
Some(Target::Song(_)) => hints.push(h("A", "Play")),
|
||||
Some(Target::Setting(_)) => hints.push(h("A", "Change")),
|
||||
Some(_) => hints.push(h("A", "Open")),
|
||||
Some(Target::Song(_)) => h(Control::Activate, "Play"),
|
||||
Some(Target::Setting(_)) => h(Control::Activate, "Change"),
|
||||
Some(_) => h(Control::Activate, "Open"),
|
||||
None if self.current_page().is_some_and(|p| p.error.is_some()) => {
|
||||
hints.push(h("A", "Try again"))
|
||||
h(Control::Activate, "Try again")
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
hints.push(h("B", "Back"));
|
||||
h(Control::Back, "Back");
|
||||
if matches!(target, Some(Target::Song(_) | Target::Album(_) | Target::Playlist(_))) {
|
||||
hints.push(h("Y", "Add to queue"));
|
||||
h(Control::Queue, "Add to queue");
|
||||
}
|
||||
hints.push(h("X", "Play / Pause"));
|
||||
hints.push(h("LT RT", "Sections"));
|
||||
hints.push(h("MENU", "Now playing"));
|
||||
h(Control::PlayPause, "Play / Pause");
|
||||
h(Control::Sections, "Sections");
|
||||
h(Control::NowPlaying, "Now playing");
|
||||
}
|
||||
},
|
||||
Screen::NowPlaying => {
|
||||
hints.push(h("A", "Play selected"));
|
||||
hints.push(h("B", "Back"));
|
||||
hints.push(h("X", "Play / Pause"));
|
||||
hints.push(h("LB RB", "Skip"));
|
||||
hints.push(h("◀ ▶", "Seek"));
|
||||
h(Control::Activate, "Play selected");
|
||||
h(Control::Back, "Back");
|
||||
h(Control::PlayPause, "Play / Pause");
|
||||
h(Control::Skip, "Skip");
|
||||
h(Control::Seek, "Seek");
|
||||
}
|
||||
}
|
||||
self.ui.set_hints(ModelRc::new(VecModel::from(hints)));
|
||||
}
|
||||
|
||||
fn hint_icons(&self, control: Control) -> Vec<Image> {
|
||||
self.icons
|
||||
.borrow_mut()
|
||||
.entry((self.prompts, control))
|
||||
.or_insert_with(|| {
|
||||
prompts::icons(self.prompts, control)
|
||||
.iter()
|
||||
.filter_map(|svg| match Image::load_from_svg_data(svg) {
|
||||
Ok(img) => Some(img),
|
||||
Err(e) => {
|
||||
log::warn!("hint icon for {control:?}: {e:?}");
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn toast(&mut self, text: String) {
|
||||
self.ui.set_toast(text.into());
|
||||
self.toast_timer
|
||||
|
||||
@@ -56,6 +56,17 @@ fn step(ui: slint::Weak<AppWindow>, steps: Vec<String>, i: usize) {
|
||||
Err(e) => log::error!("snapshot failed: {e}"),
|
||||
}
|
||||
}
|
||||
Some(("prompts", kind)) => {
|
||||
use crate::prompts::Family;
|
||||
let family = match kind {
|
||||
"xbox" => Some(Family::Xbox),
|
||||
"playstation" => Some(Family::PlayStation),
|
||||
"switch" => Some(Family::Switch),
|
||||
"steamdeck" => Some(Family::SteamDeck),
|
||||
_ => None,
|
||||
};
|
||||
app::with_app(move |app| app.pad_present(family));
|
||||
}
|
||||
Some(("login", creds)) => {
|
||||
let mut parts = creds.splitn(3, '|').map(str::to_string);
|
||||
let (url, user, pass) = (
|
||||
|
||||
+96
-11
@@ -1,14 +1,27 @@
|
||||
//! Gamepad input. Buttons map to the same `Action`s as the keyboard bindings in app.slint.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gilrs::{Axis, Button, EventType, GamepadId, Gilrs};
|
||||
|
||||
use crate::Action;
|
||||
use crate::prompts::{self, Family, PRODUCT_STEAM_VIRTUAL_GAMEPAD, VENDOR_VALVE};
|
||||
|
||||
/// Steam's virtual controllers. When one is present the physical pad behind it
|
||||
/// also shows up as an evdev device, so only Steam's is listened to.
|
||||
const STEAM_VENDOR: u16 = 0x28de;
|
||||
const STEAM_VENDOR: u16 = VENDOR_VALVE;
|
||||
|
||||
/// How often to look again for the physical controller behind a Steam virtual
|
||||
/// pad that Steam's file did not list yet. SDL checks as often.
|
||||
const RECHECK_VIRTUAL: Duration = Duration::from_secs(3);
|
||||
|
||||
pub enum PadEvent {
|
||||
/// A press, from a controller of this family.
|
||||
Action(Action, Family),
|
||||
/// The family of a connected controller, or None when the last one went.
|
||||
Present(Option<Family>),
|
||||
}
|
||||
|
||||
const REPEAT_DELAY: Duration = Duration::from_millis(380);
|
||||
const REPEAT_SLOW: Duration = Duration::from_millis(110);
|
||||
@@ -27,11 +40,12 @@ enum Source {
|
||||
struct Held {
|
||||
source: Source,
|
||||
action: Action,
|
||||
family: Family,
|
||||
since: Instant,
|
||||
next: Instant,
|
||||
}
|
||||
|
||||
pub fn spawn_gamepad(emit: impl Fn(Action) + Send + 'static) {
|
||||
pub fn spawn_gamepad(emit: impl Fn(PadEvent) + Send + 'static) {
|
||||
let spawned = std::thread::Builder::new().name("gamepad".into()).spawn(move || {
|
||||
let mut gilrs = match Gilrs::new() {
|
||||
Ok(g) => g,
|
||||
@@ -40,22 +54,35 @@ pub fn spawn_gamepad(emit: impl Fn(Action) + Send + 'static) {
|
||||
return;
|
||||
}
|
||||
};
|
||||
for (_, pad) in gilrs.gamepads() {
|
||||
log::info!("gamepad: {} (vendor {:04x?})", pad.name(), pad.vendor_id());
|
||||
let mut families = Families::default();
|
||||
for (id, pad) in gilrs.gamepads() {
|
||||
log::info!(
|
||||
"gamepad: {} (vendor {:04x?}, product {:04x?}), {:?} prompts",
|
||||
pad.name(),
|
||||
pad.vendor_id(),
|
||||
pad.product_id(),
|
||||
families.family(&gilrs, id)
|
||||
);
|
||||
}
|
||||
emit(PadEvent::Present(present(&gilrs, &mut families)));
|
||||
let mut held: Option<Held> = None;
|
||||
loop {
|
||||
while let Some(ev) = gilrs.next_event_blocking(Some(Duration::from_millis(15))) {
|
||||
if matches!(ev.event, EventType::Connected | EventType::Disconnected) {
|
||||
families.forget(ev.id);
|
||||
emit(PadEvent::Present(present(&gilrs, &mut families)));
|
||||
}
|
||||
if !accept_from(&gilrs, ev.id) {
|
||||
continue;
|
||||
}
|
||||
let family = families.family(&gilrs, ev.id);
|
||||
match ev.event {
|
||||
EventType::ButtonPressed(b, _) => {
|
||||
if let Some(a) = dpad_action(b) {
|
||||
held = Some(start_hold(Source::DPad, a));
|
||||
emit(a);
|
||||
held = Some(start_hold(Source::DPad, a, family));
|
||||
emit(PadEvent::Action(a, family));
|
||||
} else if let Some(a) = button_action(b) {
|
||||
emit(a);
|
||||
emit(PadEvent::Action(a, family));
|
||||
}
|
||||
}
|
||||
EventType::ButtonReleased(b, _) => {
|
||||
@@ -74,8 +101,8 @@ pub fn spawn_gamepad(emit: impl Fn(Action) + Send + 'static) {
|
||||
match (dir, held.as_ref()) {
|
||||
(Some(a), Some(h)) if h.source == source && h.action == a => {}
|
||||
(Some(a), _) => {
|
||||
held = Some(start_hold(source, a));
|
||||
emit(a);
|
||||
held = Some(start_hold(source, a, family));
|
||||
emit(PadEvent::Action(a, family));
|
||||
}
|
||||
(None, Some(h)) if h.source == source => held = None,
|
||||
_ => {}
|
||||
@@ -88,7 +115,7 @@ pub fn spawn_gamepad(emit: impl Fn(Action) + Send + 'static) {
|
||||
if let Some(h) = held.as_mut() {
|
||||
let now = Instant::now();
|
||||
if now >= h.next {
|
||||
emit(h.action);
|
||||
emit(PadEvent::Action(h.action, h.family));
|
||||
let step = if now - h.since > FAST_AFTER {
|
||||
REPEAT_FAST
|
||||
} else {
|
||||
@@ -109,16 +136,74 @@ fn accept_from(gilrs: &Gilrs, id: GamepadId) -> bool {
|
||||
!steam_present || gilrs.gamepad(id).vendor_id() == Some(STEAM_VENDOR)
|
||||
}
|
||||
|
||||
fn start_hold(source: Source, action: Action) -> Held {
|
||||
fn start_hold(source: Source, action: Action, family: Family) -> Held {
|
||||
let now = Instant::now();
|
||||
Held {
|
||||
source,
|
||||
action,
|
||||
family,
|
||||
since: now,
|
||||
next: now + REPEAT_DELAY,
|
||||
}
|
||||
}
|
||||
|
||||
/// The family of the first controller listened to, if any.
|
||||
fn present(gilrs: &Gilrs, families: &mut Families) -> Option<Family> {
|
||||
let id = gilrs.gamepads().map(|(id, _)| id).find(|&id| accept_from(gilrs, id))?;
|
||||
Some(families.family(gilrs, id))
|
||||
}
|
||||
|
||||
/// Controller families per pad. A Steam virtual pad whose physical controller
|
||||
/// is not in Steam's file yet is looked up again now and then.
|
||||
#[derive(Default)]
|
||||
struct Families {
|
||||
known: HashMap<GamepadId, (Family, Option<Instant>)>,
|
||||
}
|
||||
|
||||
impl Families {
|
||||
fn family(&mut self, gilrs: &Gilrs, id: GamepadId) -> Family {
|
||||
if let Some(&(family, unresolved)) = self.known.get(&id)
|
||||
&& unresolved.is_none_or(|at| at.elapsed() < RECHECK_VIRTUAL)
|
||||
{
|
||||
return family;
|
||||
}
|
||||
let (family, resolved) = resolve_family(&gilrs.gamepad(id));
|
||||
self.known.insert(id, (family, (!resolved).then(Instant::now)));
|
||||
family
|
||||
}
|
||||
|
||||
fn forget(&mut self, id: GamepadId) {
|
||||
self.known.remove(&id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The family of a pad, and whether it is certain. For Steam's virtual pad the
|
||||
/// physical controller comes from the file Steam names in
|
||||
/// SteamVirtualGamepadInfo, the way SDL finds it.
|
||||
fn resolve_family(pad: &gilrs::Gamepad<'_>) -> (Family, bool) {
|
||||
let (vendor, product) = (pad.vendor_id(), pad.product_id());
|
||||
if (vendor, product) != (Some(VENDOR_VALVE), Some(PRODUCT_STEAM_VIRTUAL_GAMEPAD)) {
|
||||
return (prompts::family_from_ids(vendor, product), true);
|
||||
}
|
||||
let physical = prompts::virtual_slot(pad.os_name()).and_then(|slot| {
|
||||
let path = std::env::var_os("SteamVirtualGamepadInfo")?;
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
prompts::parse_virtual_pads(&text).remove(&slot)
|
||||
});
|
||||
match physical {
|
||||
Some(p) => {
|
||||
log::info!(
|
||||
"Steam virtual pad '{}' is a {:04x?}:{:04x?}",
|
||||
pad.os_name(),
|
||||
p.vendor,
|
||||
p.product
|
||||
);
|
||||
(prompts::family_from_ids(p.vendor, p.product), true)
|
||||
}
|
||||
None => (Family::Xbox, false),
|
||||
}
|
||||
}
|
||||
|
||||
fn dpad_action(b: Button) -> Option<Action> {
|
||||
Some(match b {
|
||||
Button::DPadUp => Action::Up,
|
||||
|
||||
+8
-2
@@ -6,6 +6,7 @@ mod devscript;
|
||||
mod input;
|
||||
mod palette;
|
||||
mod player;
|
||||
mod prompts;
|
||||
mod subsonic;
|
||||
|
||||
use std::time::Duration;
|
||||
@@ -24,8 +25,13 @@ fn main() -> anyhow::Result<()> {
|
||||
let ui = AppWindow::new()?;
|
||||
ui.set_version(env!("CARGO_PKG_VERSION").into());
|
||||
app::install(&ui, rt.handle().clone());
|
||||
input::spawn_gamepad(|action| {
|
||||
let _ = slint::invoke_from_event_loop(move || app::with_app(move |app| app.action(action)));
|
||||
input::spawn_gamepad(|ev| {
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
app::with_app(move |app| match ev {
|
||||
input::PadEvent::Action(action, family) => app.pad_action(action, family),
|
||||
input::PadEvent::Present(family) => app.pad_present(family),
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
// Kept alive until the event loop ends.
|
||||
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
//! Which icons the hint bar shows: keyboard keys, or the buttons of the
|
||||
//! controller in use. Icons are Kenney's Input Prompts (CC0), in ui/prompts.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Controller families with their own button icons.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Family {
|
||||
Xbox,
|
||||
PlayStation,
|
||||
Switch,
|
||||
SteamDeck,
|
||||
}
|
||||
|
||||
/// What the hints are drawn for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Prompts {
|
||||
Keyboard,
|
||||
Pad(Family),
|
||||
}
|
||||
|
||||
/// An action the hint bar can point at. Each maps to one control per input:
|
||||
/// the gamepad side matches `button_action` in src/input.rs, the keyboard
|
||||
/// side the key-pressed handler in ui/app.slint.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Control {
|
||||
Activate,
|
||||
Back,
|
||||
PlayPause,
|
||||
Queue,
|
||||
Skip,
|
||||
Sections,
|
||||
Search,
|
||||
NowPlaying,
|
||||
Seek,
|
||||
/// Steam + X brings up Steam's on-screen keyboard. Nothing to show for a
|
||||
/// real keyboard.
|
||||
OnScreenKeyboard,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl Control {
|
||||
pub const ALL: [Control; 10] = [
|
||||
Control::Activate,
|
||||
Control::Back,
|
||||
Control::PlayPause,
|
||||
Control::Queue,
|
||||
Control::Skip,
|
||||
Control::Sections,
|
||||
Control::Search,
|
||||
Control::NowPlaying,
|
||||
Control::Seek,
|
||||
Control::OnScreenKeyboard,
|
||||
];
|
||||
}
|
||||
|
||||
macro_rules! icon {
|
||||
($dir:literal, $name:literal) => {
|
||||
include_bytes!(concat!("../ui/prompts/", $dir, "/", $name, ".svg")) as &'static [u8]
|
||||
};
|
||||
}
|
||||
|
||||
/// The SVG icons for `control`, left to right. Empty when there is nothing to
|
||||
/// press for it with this input.
|
||||
pub fn icons(prompts: Prompts, control: Control) -> &'static [&'static [u8]] {
|
||||
use Control::*;
|
||||
match prompts {
|
||||
Prompts::Keyboard => match control {
|
||||
Activate => &[icon!("keyboard", "keyboard_enter")],
|
||||
Back => &[icon!("keyboard", "keyboard_escape")],
|
||||
PlayPause => &[icon!("keyboard", "keyboard_space")],
|
||||
Queue => &[icon!("keyboard", "keyboard_q")],
|
||||
Skip => &[icon!("keyboard", "keyboard_p"), icon!("keyboard", "keyboard_n")],
|
||||
Sections => &[icon!("keyboard", "keyboard_tab")],
|
||||
Search => &[icon!("keyboard", "keyboard_slash_forward")],
|
||||
NowPlaying => &[icon!("keyboard", "keyboard_f")],
|
||||
Seek => &[icon!("keyboard", "keyboard_arrows_horizontal")],
|
||||
OnScreenKeyboard => &[],
|
||||
},
|
||||
Prompts::Pad(Family::Xbox) => match control {
|
||||
Activate => &[icon!("xbox", "xbox_button_color_a")],
|
||||
Back => &[icon!("xbox", "xbox_button_color_b")],
|
||||
PlayPause => &[icon!("xbox", "xbox_button_color_x")],
|
||||
Queue => &[icon!("xbox", "xbox_button_color_y")],
|
||||
Skip => &[icon!("xbox", "xbox_lb"), icon!("xbox", "xbox_rb")],
|
||||
Sections => &[icon!("xbox", "xbox_lt"), icon!("xbox", "xbox_rt")],
|
||||
Search => &[icon!("xbox", "xbox_button_view")],
|
||||
NowPlaying => &[icon!("xbox", "xbox_button_menu")],
|
||||
Seek => &[icon!("xbox", "xbox_dpad_horizontal")],
|
||||
OnScreenKeyboard => &[icon!("xbox", "xbox_guide"), icon!("xbox", "xbox_button_color_x")],
|
||||
},
|
||||
Prompts::Pad(Family::PlayStation) => match control {
|
||||
Activate => &[icon!("playstation", "playstation_button_color_cross")],
|
||||
Back => &[icon!("playstation", "playstation_button_color_circle")],
|
||||
PlayPause => &[icon!("playstation", "playstation_button_color_square")],
|
||||
Queue => &[icon!("playstation", "playstation_button_color_triangle")],
|
||||
Skip => &[
|
||||
icon!("playstation", "playstation_trigger_l1"),
|
||||
icon!("playstation", "playstation_trigger_r1"),
|
||||
],
|
||||
Sections => &[
|
||||
icon!("playstation", "playstation_trigger_l2"),
|
||||
icon!("playstation", "playstation_trigger_r2"),
|
||||
],
|
||||
Search => &[icon!("playstation", "playstation5_button_create")],
|
||||
NowPlaying => &[icon!("playstation", "playstation5_button_options")],
|
||||
Seek => &[icon!("playstation", "playstation_dpad_horizontal")],
|
||||
// The pack has no PS button; Steam's own label says the same thing.
|
||||
OnScreenKeyboard => &[
|
||||
icon!("steamdeck", "steamdeck_button_guide"),
|
||||
icon!("playstation", "playstation_button_color_square"),
|
||||
],
|
||||
},
|
||||
// By position, as gilrs reports buttons: the bottom face button is B on a Switch.
|
||||
Prompts::Pad(Family::Switch) => match control {
|
||||
Activate => &[icon!("switch", "switch_button_b")],
|
||||
Back => &[icon!("switch", "switch_button_a")],
|
||||
PlayPause => &[icon!("switch", "switch_button_y")],
|
||||
Queue => &[icon!("switch", "switch_button_x")],
|
||||
Skip => &[icon!("switch", "switch_button_l"), icon!("switch", "switch_button_r")],
|
||||
Sections => &[icon!("switch", "switch_button_zl"), icon!("switch", "switch_button_zr")],
|
||||
Search => &[icon!("switch", "switch_button_minus")],
|
||||
NowPlaying => &[icon!("switch", "switch_button_plus")],
|
||||
Seek => &[icon!("switch", "switch_dpad_horizontal")],
|
||||
OnScreenKeyboard => &[
|
||||
icon!("switch", "switch_button_home"),
|
||||
icon!("switch", "switch_button_y"),
|
||||
],
|
||||
},
|
||||
Prompts::Pad(Family::SteamDeck) => match control {
|
||||
Activate => &[icon!("steamdeck", "steamdeck_button_a")],
|
||||
Back => &[icon!("steamdeck", "steamdeck_button_b")],
|
||||
PlayPause => &[icon!("steamdeck", "steamdeck_button_x")],
|
||||
Queue => &[icon!("steamdeck", "steamdeck_button_y")],
|
||||
Skip => &[
|
||||
icon!("steamdeck", "steamdeck_button_l1"),
|
||||
icon!("steamdeck", "steamdeck_button_r1"),
|
||||
],
|
||||
Sections => &[
|
||||
icon!("steamdeck", "steamdeck_button_l2"),
|
||||
icon!("steamdeck", "steamdeck_button_r2"),
|
||||
],
|
||||
Search => &[icon!("steamdeck", "steamdeck_button_view")],
|
||||
NowPlaying => &[icon!("steamdeck", "steamdeck_button_options")],
|
||||
Seek => &[icon!("steamdeck", "steamdeck_dpad_horizontal")],
|
||||
OnScreenKeyboard => &[
|
||||
icon!("steamdeck", "steamdeck_button_guide"),
|
||||
icon!("steamdeck", "steamdeck_button_x"),
|
||||
],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const VENDOR_MICROSOFT: u16 = 0x045e;
|
||||
const VENDOR_SONY: u16 = 0x054c;
|
||||
const VENDOR_NINTENDO: u16 = 0x057e;
|
||||
pub const VENDOR_VALVE: u16 = 0x28de;
|
||||
/// Steam's virtual gamepad, which stands in for whatever is really connected.
|
||||
pub const PRODUCT_STEAM_VIRTUAL_GAMEPAD: u16 = 0x11ff;
|
||||
const PRODUCT_STEAM_DECK: u16 = 0x1205;
|
||||
|
||||
/// The family of a physical controller, by its USB ids. Unknown controllers,
|
||||
/// and Steam's virtual one, get Xbox icons: most pads follow that layout.
|
||||
pub fn family_from_ids(vendor: Option<u16>, product: Option<u16>) -> Family {
|
||||
match (vendor, product) {
|
||||
(Some(VENDOR_SONY), _) => Family::PlayStation,
|
||||
(Some(VENDOR_NINTENDO), _) => Family::Switch,
|
||||
(Some(VENDOR_VALVE), Some(PRODUCT_STEAM_DECK)) => Family::SteamDeck,
|
||||
(Some(VENDOR_MICROSOFT), _) => Family::Xbox,
|
||||
_ => Family::Xbox,
|
||||
}
|
||||
}
|
||||
|
||||
/// One physical controller listed in Steam's virtual gamepad file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct VirtualPad {
|
||||
pub vendor: Option<u16>,
|
||||
pub product: Option<u16>,
|
||||
}
|
||||
|
||||
/// Parses the file `SteamVirtualGamepadInfo` points at, as SDL does
|
||||
/// (src/joystick/SDL_steam_virtual_gamepad.c): `[slot N]` sections with
|
||||
/// `VID=` and `PID=` lines, numbers in C notation (0x for hex).
|
||||
pub fn parse_virtual_pads(text: &str) -> HashMap<u32, VirtualPad> {
|
||||
let mut pads = HashMap::new();
|
||||
let mut slot: Option<u32> = None;
|
||||
for line in text.lines().map(str::trim) {
|
||||
if let Some(n) = line.strip_prefix("[slot").and_then(|r| r.strip_suffix(']')) {
|
||||
slot = n.trim().parse().ok();
|
||||
if let Some(s) = slot {
|
||||
pads.entry(s).or_insert(VirtualPad {
|
||||
vendor: None,
|
||||
product: None,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (Some(s), Some((key, value))) = (slot, line.split_once('=')) else {
|
||||
continue;
|
||||
};
|
||||
let Some(pad) = pads.get_mut(&s) else { continue };
|
||||
match key {
|
||||
"VID" => pad.vendor = parse_c_number(value),
|
||||
"PID" => pad.product = parse_c_number(value),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
pads
|
||||
}
|
||||
|
||||
fn parse_c_number(s: &str) -> Option<u16> {
|
||||
let s = s.trim();
|
||||
match s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
|
||||
Some(hex) => u16::from_str_radix(hex, 16).ok(),
|
||||
None if s.len() > 1 && s.starts_with('0') => u16::from_str_radix(&s[1..], 8).ok(),
|
||||
None => s.parse().ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The slot of a Steam virtual pad, from its OS name ("... pad 2" is slot 2),
|
||||
/// as SDL reads it.
|
||||
pub fn virtual_slot(os_name: &str) -> Option<u32> {
|
||||
let rest = &os_name[os_name.find("pad ")? + 4..];
|
||||
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
|
||||
digits.parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_control_has_icons_for_every_controller() {
|
||||
for family in [Family::Xbox, Family::PlayStation, Family::Switch, Family::SteamDeck] {
|
||||
for control in Control::ALL {
|
||||
assert!(
|
||||
!icons(Prompts::Pad(family), control).is_empty(),
|
||||
"{family:?} {control:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_has_icons_for_everything_but_steam_keyboard() {
|
||||
for control in Control::ALL {
|
||||
let n = icons(Prompts::Keyboard, control).len();
|
||||
if control == Control::OnScreenKeyboard {
|
||||
assert_eq!(n, 0);
|
||||
} else {
|
||||
assert!(n > 0, "{control:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn icons_are_svg() {
|
||||
for prompts in [
|
||||
Prompts::Keyboard,
|
||||
Prompts::Pad(Family::Xbox),
|
||||
Prompts::Pad(Family::PlayStation),
|
||||
Prompts::Pad(Family::Switch),
|
||||
Prompts::Pad(Family::SteamDeck),
|
||||
] {
|
||||
for control in Control::ALL {
|
||||
for svg in icons(prompts, control) {
|
||||
assert!(svg.starts_with(b"<svg") || svg.starts_with(b"<?xml"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn families_by_usb_ids() {
|
||||
assert_eq!(family_from_ids(Some(0x054c), Some(0x0ce6)), Family::PlayStation);
|
||||
assert_eq!(family_from_ids(Some(0x057e), Some(0x2009)), Family::Switch);
|
||||
assert_eq!(family_from_ids(Some(0x28de), Some(0x1205)), Family::SteamDeck);
|
||||
assert_eq!(family_from_ids(Some(0x045e), Some(0x0b12)), Family::Xbox);
|
||||
assert_eq!(family_from_ids(Some(0x28de), Some(0x11ff)), Family::Xbox);
|
||||
assert_eq!(family_from_ids(None, None), Family::Xbox);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steam_virtual_pad_file() {
|
||||
let text = "[slot 0]\nname=Steam Deck\nVID=0x28de\nPID=0x1205\ntype=steamdeck\nhandle=0x1\n\n\
|
||||
[slot 1]\r\nname=DualSense\r\nVID=0x054c\r\nPID=3302\r\n";
|
||||
let pads = parse_virtual_pads(text);
|
||||
assert_eq!(
|
||||
pads[&0],
|
||||
VirtualPad {
|
||||
vendor: Some(0x28de),
|
||||
product: Some(0x1205)
|
||||
}
|
||||
);
|
||||
assert_eq!(pads[&1].product, Some(3302));
|
||||
assert_eq!(family_from_ids(pads[&1].vendor, pads[&1].product), Family::PlayStation);
|
||||
assert!(parse_virtual_pads("VID=0x054c\ngarbage\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slots_come_from_the_pad_name() {
|
||||
assert_eq!(virtual_slot("Microsoft X-Box 360 pad 0"), Some(0));
|
||||
assert_eq!(virtual_slot("Microsoft X-Box 360 pad 12"), Some(12));
|
||||
assert_eq!(virtual_slot("Steam Virtual Gamepad"), None);
|
||||
assert_eq!(virtual_slot("gamepad x"), None);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user