diff --git a/docs/cli.md b/docs/cli.md index e1a1a996..28dfd99b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -51,6 +51,7 @@ driftwm msg --json focus --id 5 | Command | Description | | --- | --- | | [`state`](#driftwm-msg-state) | Dump camera, zoom, and the window inventory | +| [`bindings`](#driftwm-msg-bindings) | List the effective keybindings: built-in defaults merged with the config | | [`subscribe`](#driftwm-msg-subscribe) | Stream state snapshots as they change (one JSON line per event with --json) | | [`focus`](#driftwm-msg-focus) | Print the focused window, or focus one by `app_id` substring or `--id` | | [`move`](#driftwm-msg-move) | Get a window's position, or move it to ` ` (visible-frame center, Y-up) | @@ -85,6 +86,22 @@ Also prints the keyboard layout, the fullscreen and pinned screen-space inventor driftwm msg --json state | jq '.Ok.State.windows' ``` +#### `driftwm msg bindings` + +``` +driftwm msg bindings +``` + +List the effective keybindings: built-in defaults merged with the config. + +Prints keyboard, tap and mouse bindings in config syntax; mouse bindings are tagged with the `[mouse.*]` context they live in. Reflects the config as currently loaded, including hot reloads. Gesture and touch bindings are not listed. + +`--json` reply: `{"Ok":{"Bindings":{"mod_key":"super","keys":[{"trigger":"super+Return","action":"exec-terminal"}],"taps":[..],"mouse":[..]}}}`. + +```bash +driftwm msg --json bindings | jq -r '.Ok.Bindings.keys[] | "\(.trigger)\t\(.action)"' +``` + #### `driftwm msg subscribe` ``` diff --git a/src/config/display.rs b/src/config/display.rs new file mode 100644 index 00000000..f253173a --- /dev/null +++ b/src/config/display.rs @@ -0,0 +1,160 @@ +//! Config-syntax rendering of bindings: the inverse of the `parse_*` functions, +//! so a binding read back out of the compositor reads like the config line that +//! produced it. + +use std::fmt; + +use smithay::input::keyboard::xkb; + +use super::types::*; + +impl fmt::Display for Direction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Direction::Up => "up", + Direction::Down => "down", + Direction::Left => "left", + Direction::Right => "right", + Direction::UpLeft => "up-left", + Direction::UpRight => "up-right", + Direction::DownLeft => "down-left", + Direction::DownRight => "down-right", + }) + } +} + +impl fmt::Display for LayoutSwitch { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LayoutSwitch::Next => f.write_str("next"), + LayoutSwitch::Prev => f.write_str("prev"), + LayoutSwitch::Index(i) => write!(f, "{i}"), + } + } +} + +impl fmt::Display for TrackpadState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + TrackpadState::Toggle => "toggle", + TrackpadState::On => "on", + TrackpadState::Off => "off", + }) + } +} + +impl fmt::Display for Action { + /// Exhaustive on purpose: a new `Action` variant fails to compile here until + /// it is given its config spelling. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Action::Exec(cmd) => write!(f, "exec {cmd}"), + Action::ExecTerminal => f.write_str("exec-terminal"), + Action::ExecLauncher => f.write_str("exec-launcher"), + Action::Spawn(cmd) => write!(f, "spawn {cmd}"), + Action::CloseWindow => f.write_str("close-window"), + Action::SuspendWindow => f.write_str("suspend-window"), + Action::NudgeWindow(d) => write!(f, "nudge-window {d}"), + Action::MoveToSnap(d) => write!(f, "move-to-snap {d}"), + Action::GrowWindow(d) => write!(f, "grow-window {d}"), + Action::ShrinkWindow(d) => write!(f, "shrink-window {d}"), + Action::ResizeToSnap(d) => write!(f, "resize-to-snap {d}"), + Action::PanViewport(d) => write!(f, "pan-viewport {d}"), + Action::CenterWindow => f.write_str("center-window"), + Action::CenterNearest(d) => write!(f, "center-nearest {d}"), + Action::FocusNearest(d) => write!(f, "focus-nearest {d}"), + Action::CycleWindows { backward: false } => f.write_str("cycle-windows forward"), + Action::CycleWindows { backward: true } => f.write_str("cycle-windows backward"), + Action::HomeToggle => f.write_str("home-toggle"), + Action::GoToBookmark(name) => write!(f, "go-to-bookmark {name}"), + Action::SetBookmark(name) => write!(f, "set-bookmark {name}"), + Action::MoveToBookmark(name) => write!(f, "move-to-bookmark {name}"), + Action::ZoomIn => f.write_str("zoom-in"), + Action::ZoomOut => f.write_str("zoom-out"), + Action::ZoomReset => f.write_str("zoom-reset"), + Action::ZoomToFit => f.write_str("zoom-to-fit"), + Action::ZoomToFitSnapped => f.write_str("zoom-to-fit-snapped"), + Action::ToggleFullscreen => f.write_str("toggle-fullscreen"), + Action::FitWindow => f.write_str("fit-window"), + Action::FitWindowSnapped => f.write_str("fit-window-snapped"), + Action::FillWindow => f.write_str("fill-window"), + Action::SendToOutput(d) => write!(f, "send-to-output {d}"), + Action::SendCursorToOutput(d) => write!(f, "send-cursor-to-output {d}"), + Action::FocusCenter => f.write_str("focus-center"), + Action::TogglePinToScreen => f.write_str("toggle-pin-to-screen"), + Action::SwitchLayout(target) => write!(f, "switch-layout {target}"), + Action::ReloadConfig => f.write_str("reload-config"), + Action::ToggleCursorPan => f.write_str("toggle-cursor-pan"), + Action::SetTrackpad(state) => write!(f, "set-trackpad {state}"), + Action::Quit => f.write_str("quit"), + } + } +} + +impl fmt::Display for MouseAction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MouseAction::MoveWindow => f.write_str("move-window"), + MouseAction::MoveSnappedWindows => f.write_str("move-snapped-windows"), + MouseAction::ResizeWindow => f.write_str("resize-window"), + MouseAction::ResizeWindowSnapped => f.write_str("resize-window-snapped"), + MouseAction::PanViewport => f.write_str("pan-viewport"), + MouseAction::Zoom => f.write_str("zoom"), + MouseAction::CenterNearest => f.write_str("center-nearest"), + MouseAction::FocusNearest => f.write_str("focus-nearest"), + MouseAction::Action(action) => action.fmt(f), + } + } +} + +fn modifier_names(m: &Modifiers) -> impl Iterator { + [ + (m.logo, "super"), + (m.ctrl, "ctrl"), + (m.alt, "alt"), + (m.shift, "shift"), + (m.mod3, "mod3"), + ] + .into_iter() + .filter_map(|(on, name)| on.then_some(name)) +} + +fn write_modifier_prefix(f: &mut fmt::Formatter<'_>, m: &Modifiers) -> fmt::Result { + modifier_names(m).try_for_each(|name| write!(f, "{name}+")) +} + +impl fmt::Display for Modifiers { + /// A bare modifier chord, as a tap binding is written (`alt+shift`). + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&modifier_names(self).collect::>().join("+")) + } +} + +impl fmt::Display for KeyCombo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_modifier_prefix(f, &self.modifiers)?; + f.write_str(&xkb::keysym_get_name(self.sym)) + } +} + +impl fmt::Display for MouseTrigger { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MouseTrigger::Button(BTN_LEFT) => f.write_str("left"), + MouseTrigger::Button(BTN_RIGHT) => f.write_str("right"), + MouseTrigger::Button(BTN_MIDDLE) => f.write_str("middle"), + MouseTrigger::Button(code) => write!(f, "button-{code:#x}"), + MouseTrigger::TrackpadScroll => f.write_str("trackpad-scroll"), + MouseTrigger::WheelScroll => f.write_str("wheel-scroll"), + MouseTrigger::WheelUp => f.write_str("wheel-up"), + MouseTrigger::WheelDown => f.write_str("wheel-down"), + } + } +} + +impl fmt::Display for MouseBinding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write_modifier_prefix(f, &self.modifiers)?; + self.trigger.fmt(f) + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs index 16fe02cf..2b34a08b 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -1,4 +1,5 @@ mod defaults; +mod display; mod parse; mod parse_helpers; @@ -321,6 +322,14 @@ impl Config { self.bindings.get(&combo) } + pub fn iter_key_bindings(&self) -> impl Iterator { + self.bindings.iter() + } + + pub fn iter_tap_bindings(&self) -> impl Iterator { + self.tap_bindings.iter() + } + /// Look up a tap-modifier binding by the completed chord's modifier set. pub fn tap_lookup(&self, mods: &Modifiers) -> Option<&Action> { self.tap_bindings.get(mods) diff --git a/src/ipc/client.rs b/src/ipc/client.rs index afc51fdb..09c65c02 100644 --- a/src/ipc/client.rs +++ b/src/ipc/client.rs @@ -8,7 +8,8 @@ use std::os::unix::net::UnixStream; use std::path::{Path, PathBuf}; use super::protocol::{ - Event, Reply, Request, Response, ScreenshotTarget, StateInfo, WindowSelector, socket_path, + BindingInfo, BindingsInfo, Event, Reply, Request, Response, ScreenshotTarget, StateInfo, + WindowSelector, socket_path, }; /// `driftwm msg <...>` subcommands. Variants with optional positionals read when @@ -23,6 +24,15 @@ pub enum Msg { /// /// `--json` reply: `{"Ok":{"State":{"camera":[..],"zoom":1.0,"windows":[..],"outputs":[..]}}}`. State, + /// List the effective keybindings: built-in defaults merged with the config. + /// + /// Prints keyboard, tap and mouse bindings in config syntax; mouse + /// bindings are tagged with the `[mouse.*]` context they live in. Reflects the config as + /// currently loaded, including hot reloads. Gesture and touch bindings are + /// not listed. + /// + /// `--json` reply: `{"Ok":{"Bindings":{"mod_key":"super","keys":[{"trigger":"super+Return","action":"exec-terminal"}],"taps":[..],"mouse":[..]}}}`. + Bindings, /// Stream state snapshots as they change (one JSON line per event with --json). /// /// The server acks, pushes the current state immediately, then pushes a @@ -406,6 +416,7 @@ fn to_request(msg: &Msg) -> Result { Msg::Layout { short } => Request::Layout { short: *short }, Msg::Cursor => Request::Cursor, Msg::State => Request::State, + Msg::Bindings => Request::Bindings, Msg::DebugCounters => Request::DebugCounters, Msg::Subscribe => Request::Subscribe, Msg::Focus { app_id, id } => Request::Focus(window_selector(app_id, *id)), @@ -640,6 +651,7 @@ fn print_response(response: Response) { Response::Screenshot { path, .. } => println!("{path}"), Response::Ok => println!("ok"), Response::State(info) => print_state(&info), + Response::Bindings(info) => print_bindings(&info), Response::DebugCounters(counters) => { for (key, value) in counters { println!("{key}: {value}"); @@ -648,6 +660,29 @@ fn print_response(response: Response) { } } +fn print_bindings(info: &BindingsInfo) { + println!("mod {}", info.mod_key); + let sections = [ + ("keys", &info.keys), + ("taps", &info.taps), + ("mouse", &info.mouse), + ]; + for (name, bindings) in sections { + println!("{name}"); + for BindingInfo { + trigger, + context, + action, + } in bindings + { + match context { + Some(context) => println!(" {trigger} [{context}] = {action}"), + None => println!(" {trigger} = {action}"), + } + } + } +} + fn print_state(info: &StateInfo) { println!("camera {} {}", info.camera.0, info.camera.1); println!("zoom {}", info.zoom); diff --git a/src/ipc/mod.rs b/src/ipc/mod.rs index 36ad97d4..896361b7 100644 --- a/src/ipc/mod.rs +++ b/src/ipc/mod.rs @@ -14,14 +14,15 @@ use smithay::wayland::seat::WaylandFocus; use crate::decorations::DecorationKey; use crate::state::{DriftWm, NavZoom, RevealPan, StageWindow, SuspendedId}; +use driftwm::config::{Config, ModKey}; use driftwm::window_ext::WindowExt; pub mod client; pub mod protocol; use self::protocol::{ - Event, OutputInfo, Reply, Request, Response, ScreenshotTarget, StateInfo, WindowSelector, - socket_path, + BindingInfo, BindingsInfo, Event, OutputInfo, Reply, Request, Response, ScreenshotTarget, + StateInfo, WindowSelector, socket_path, }; /// Reject a command line longer than this (without a newline) — bounds the @@ -269,6 +270,7 @@ pub(crate) fn dispatch(request: Request, state: &mut DriftWm) -> Reply { Request::Layout { short } => cmd_layout(short, state), Request::Cursor => cmd_cursor(state), Request::State => Ok(cmd_state(state)), + Request::Bindings => Ok(Response::Bindings(bindings_info(&state.config))), Request::DebugCounters => Ok(Response::DebugCounters(state.debug_counters())), // Handled in serve_connection, which has the raw stream Subscribe needs. Request::Subscribe => unreachable!("Subscribe is handled before dispatch"), @@ -432,6 +434,50 @@ fn layout_code(layout_list: &str, index: usize) -> Option { .map(str::to_owned) } +fn bindings_info(config: &Config) -> BindingsInfo { + fn sorted(mut list: Vec) -> Vec { + list.sort_by(|a, b| (&a.trigger, &a.context).cmp(&(&b.trigger, &b.context))); + list + } + let binding = |trigger: String, context: Option<&str>, action: String| BindingInfo { + trigger, + context: context.map(str::to_owned), + action, + }; + + let keys = config + .iter_key_bindings() + .map(|(combo, action)| binding(combo.to_string(), None, action.to_string())) + .collect(); + let taps = config + .iter_tap_bindings() + .map(|(mods, action)| binding(mods.to_string(), None, action.to_string())) + .collect(); + let mouse = [ + (&config.mouse.anywhere, None), + (&config.mouse.on_window, Some("on-window")), + (&config.mouse.on_canvas, Some("on-canvas")), + ] + .into_iter() + .flat_map(|(map, context)| { + map.iter() + .map(move |(trigger, action)| binding(trigger.to_string(), context, action.to_string())) + }) + .collect(); + + BindingsInfo { + mod_key: match config.mod_key { + ModKey::Alt => "alt", + ModKey::Super => "super", + ModKey::Mod3 => "mod3", + } + .to_owned(), + keys: sorted(keys), + taps: sorted(taps), + mouse: sorted(mouse), + } +} + fn cmd_state(state: &mut DriftWm) -> Response { Response::State(Box::new(state_info(state))) } diff --git a/src/ipc/protocol.rs b/src/ipc/protocol.rs index 9e402cd8..7eac1537 100644 --- a/src/ipc/protocol.rs +++ b/src/ipc/protocol.rs @@ -36,6 +36,9 @@ pub enum Request { /// the output it is on. Cursor, State, + /// The effective keyboard, tap and mouse bindings: built-in defaults merged + /// with the user's config, as currently loaded. + Bindings, /// Sizes of the compositor's leak-prone internal collections, keyed by /// field name. A debug/introspection endpoint — the keys are unstable /// implementation detail, not a compatibility surface. @@ -162,6 +165,7 @@ pub enum Response { /// reply variant. Serde-transparent, so the wire shape is unchanged. State(Box), DebugCounters(BTreeMap), + Bindings(BindingsInfo), Focused(Option), /// Visible-frame center, Y-up coordinates. Position { @@ -199,6 +203,31 @@ pub enum Response { /// The result of a request: `Ok(Response)` or a human-readable error string. pub type Reply = Result; +/// One binding in a [`Response::Bindings`] reply, in config syntax. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct BindingInfo { + /// The trigger as written in the config, e.g. `super+Return` or `super+left`. + pub trigger: String, + /// `on-window` or `on-canvas` for a mouse binding limited to one; absent for + /// keys, taps and mouse bindings that apply everywhere. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option, + /// The action as written in the config, e.g. `focus-nearest up`. + pub action: String, +} + +/// The payload of a [`Response::Bindings`] reply. Each list is sorted by trigger +/// so the reply is stable across runs. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct BindingsInfo { + /// The key `super`, `alt` or `mod3` that `mod` stands for in the config. + pub mod_key: String, + pub keys: Vec, + /// Bare modifier chords that fire when released with no other key pressed. + pub taps: Vec, + pub mouse: Vec, +} + /// The focused window in a [`Response::Focused`] reply. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FocusedWindow { @@ -397,6 +426,7 @@ mod tests { Request::Layout { short: true }, Request::Cursor, Request::State, + Request::Bindings, Request::DebugCounters, Request::Subscribe, Request::Focus(None), @@ -653,6 +683,20 @@ mod tests { output: "DP-1".into(), }), Ok(Response::State(Box::new(sample_state()))), + Ok(Response::Bindings(BindingsInfo { + mod_key: "super".into(), + keys: vec![BindingInfo { + trigger: "super+Return".into(), + context: None, + action: "exec-terminal".into(), + }], + taps: vec![], + mouse: vec![BindingInfo { + trigger: "super+left".into(), + context: Some("on-window".into()), + action: "move-window".into(), + }], + })), Ok(Response::DebugCounters( [("stage_entries".to_string(), 2usize)] .into_iter() diff --git a/src/tests/cli_docs.rs b/src/tests/cli_docs.rs index b708d43f..4f438529 100644 --- a/src/tests/cli_docs.rs +++ b/src/tests/cli_docs.rs @@ -40,6 +40,12 @@ const EXAMPLES: &[(&str, &[&str])] = &[ "driftwm msg state", &["driftwm msg --json state | jq '.Ok.State.windows'"], ), + ( + "driftwm msg bindings", + &[ + "driftwm msg --json bindings | jq -r '.Ok.Bindings.keys[] | \"\\(.trigger)\\t\\(.action)\"'", + ], + ), ( "driftwm msg subscribe", &["driftwm msg --json subscribe | jq --unbuffered -r '.State.zoom'"], diff --git a/src/tests/ipc_bindings.rs b/src/tests/ipc_bindings.rs new file mode 100644 index 00000000..e87d5219 --- /dev/null +++ b/src/tests/ipc_bindings.rs @@ -0,0 +1,114 @@ +//! The IPC `bindings` verb: the effective key, tap and mouse bindings, in +//! config syntax, after defaults and the user's config are merged. + +use super::{Fixture, config}; +use crate::ipc::dispatch; +use crate::ipc::protocol::{BindingInfo, BindingsInfo, Request, Response}; + +fn bindings(f: &mut Fixture) -> BindingsInfo { + match dispatch(Request::Bindings, f.state()) { + Ok(Response::Bindings(info)) => info, + other => panic!("expected a Bindings reply, got {other:?}"), + } +} + +fn action_of<'a>(list: &'a [BindingInfo], trigger: &str) -> Option<&'a str> { + list.iter() + .find(|b| b.trigger == trigger) + .map(|b| b.action.as_str()) +} + +#[test] +fn lists_the_defaults_in_config_syntax() { + let mut f = Fixture::new(); + let info = bindings(&mut f); + + assert_eq!(info.mod_key, "super"); + assert_eq!(action_of(&info.keys, "super+Return"), Some("exec-terminal")); + assert_eq!(action_of(&info.keys, "super+Up"), Some("focus-nearest up")); + assert_eq!( + action_of(&info.keys, "alt+Tab"), + Some("cycle-windows forward") + ); +} + +#[test] +fn user_bindings_override_defaults_and_none_unbinds() { + let mut f = Fixture::with_config(config( + r#" +[keybindings] +"mod+return" = "exec foot" +"mod+q" = "none" +"mod+w" = "spawn notify-send hi" +"#, + )); + let info = bindings(&mut f); + + assert_eq!(action_of(&info.keys, "super+Return"), Some("exec foot")); + assert_eq!(action_of(&info.keys, "super+q"), None); + assert_eq!( + action_of(&info.keys, "super+w"), + Some("spawn notify-send hi") + ); +} + +#[test] +fn disabled_default_categories_are_absent() { + let mut f = Fixture::with_config(config("[bindings]\ndisable_defaults = [\"keys\"]\n")); + assert!(bindings(&mut f).keys.is_empty()); +} + +#[test] +fn tap_chords_are_listed_apart_from_keys() { + let mut f = Fixture::with_config(config( + "[keybindings]\n\"alt+shift\" = \"switch-layout next\"\n", + )); + let info = bindings(&mut f); + + assert_eq!( + action_of(&info.taps, "alt+shift"), + Some("switch-layout next") + ); + assert!(info.keys.iter().all(|b| b.trigger != "alt+shift")); +} + +#[test] +fn mouse_bindings_carry_their_context() { + let mut f = Fixture::new(); + let info = bindings(&mut f); + + assert!(!info.mouse.is_empty()); + assert!( + info.mouse + .iter() + .any(|b| b.trigger == "alt+left" && b.action == "move-window"), + "no alt+left move-window default in {:?}", + info.mouse + ); +} + +#[test] +fn every_list_is_sorted_by_trigger() { + let mut f = Fixture::new(); + let info = bindings(&mut f); + + for list in [&info.keys, &info.taps, &info.mouse] { + let triggers: Vec<_> = list.iter().map(|b| (&b.trigger, &b.context)).collect(); + assert!(triggers.is_sorted()); + } +} + +#[test] +fn every_listed_binding_parses_back_to_the_same_action() { + use driftwm::config::{ModKey, parse_action, parse_key_combo}; + + let mut f = Fixture::new(); + for b in bindings(&mut f).keys { + let combo = parse_key_combo(&b.trigger, ModKey::Super) + .unwrap_or_else(|e| panic!("trigger {:?} does not parse: {e}", b.trigger)); + assert_eq!(combo.to_string(), b.trigger); + let action = parse_action(&b.action) + .unwrap_or_else(|e| panic!("action {:?} does not parse: {e}", b.action)); + assert_eq!(action.to_string(), b.action); + } +} diff --git a/src/tests/mod.rs b/src/tests/mod.rs index c0673035..802ad52f 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -49,6 +49,7 @@ mod hotplug; mod hover_focus; mod input_dispatch; mod interact_min; +mod ipc_bindings; mod ipc_bounds; mod ipc_cursor; mod ipc_focus;