diff --git a/README.md b/README.md index 0ceb1a95..decc406d 100644 --- a/README.md +++ b/README.md @@ -36,8 +36,8 @@ with one monitor and no windows instead. While it runs, the daemon takes messages on a Unix socket, `komorebi.sock` in `$XDG_RUNTIME_DIR/komorebi` (the local data directory when there is no runtime directory): a message can ask for the state of the window manager, ask which -monitor, workspace or container has the focus, retile every monitor, or stop -the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, +monitor, workspace or container has the focus, give the focus to another +window, retile every monitor, or stop the daemon. [`komorebi-client`](komorebi-client) writes them, and `komorebic`, the command line, is how a person sends them. `komorebic start` runs the `komorebi` on the `PATH`, and passes it what follows a `--`. In a Plasma session: @@ -129,7 +129,10 @@ tiles the workspace in front again. Everything else reaches the daemon as a message on its socket: one JSON `SocketMessage` per line, handled one at a time with the window manager -locked. A message that asks a question is answered on the same connection. +locked. A message that asks a question is answered on the same connection. A +message that gives an order changes the model the way an event does: `focus` +and `cycle-focus` give the focus to the container on one side of the focused +one in the layout, or to the next one in the workspace's order. A program such as a status bar can subscribe to the daemon's notifications: it listens on a socket of its own, and after each event and each message, the diff --git a/docs/cli/cycle-focus.md b/docs/cli/cycle-focus.md new file mode 100644 index 00000000..6cb38ec3 --- /dev/null +++ b/docs/cli/cycle-focus.md @@ -0,0 +1,14 @@ +```text +Change focus to the window in the specified cycle direction + +Usage: cycle-focus + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus.md b/docs/cli/focus.md new file mode 100644 index 00000000..f3883b76 --- /dev/null +++ b/docs/cli/focus.md @@ -0,0 +1,14 @@ +```text +Change focus to the window in the specified direction + +Usage: focus + +Arguments: + + [possible values: left, right, up, down] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/mouse-follows-focus.md b/docs/cli/mouse-follows-focus.md new file mode 100644 index 00000000..bfb906a3 --- /dev/null +++ b/docs/cli/mouse-follows-focus.md @@ -0,0 +1,14 @@ +```text +Enable or disable mouse follows focus on all workspaces + +Usage: mouse-follows-focus + +Arguments: + + [possible values: enable, disable] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-mouse-follows-focus.md b/docs/cli/toggle-mouse-follows-focus.md new file mode 100644 index 00000000..94b51a28 --- /dev/null +++ b/docs/cli/toggle-mouse-follows-focus.md @@ -0,0 +1,10 @@ +```text +Toggle mouse follows focus on all workspaces + +Usage: toggle-mouse-follows-focus + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 23c072a0..706dc404 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -8,8 +8,9 @@ tested, without one. This page describes that trait, who implements and calls it, where each of its rules is enforced, the model of the desktop the window manager tiles, the backend that reaches KWin, how an event about a window becomes a tile, how a message on the daemon's socket is -answered, how subscribers are notified of both, and how the NixOS module runs the daemon. It -grows with the code: each part of the daemon that is added has its place here. +answered, how subscribers are notified of both, what the orders a message gives do, and how the +NixOS module runs the daemon. It grows with the code: each part of the daemon that is added has +its place here. ## Vocabulary @@ -26,7 +27,10 @@ grows with the code: each part of the daemon that is added has its place here. - **Event**: what the compositor reports about a window: it was shown, destroyed, given the focus, minimized or restored ([`WindowManagerEvent`]). - **Message**: what a client sends the daemon on its socket, a [`SocketMessage`]: an order - (retile, stop) or a question (the state, the monitors, one [`StateQuery`]). + (focus a window, retile, stop) or a question (the state, the monitors, one [`StateQuery`]). +- **Direction**: where an order goes from the focused container: a side of its tile + ([`OperationDirection`]), or the next or the previous container of the workspace + ([`CycleDirection`]). - **State**: the window manager's monitors, workspaces, containers and windows, and its settings, as the daemon answers a `State` message with them ([`State`]). - **Subscriber**: a program that listens on a socket of its own in [`DATA_DIR`] and has @@ -230,6 +234,26 @@ channel of [`window_manager_event_listener`], and past 20 the backend drops them When the daemon stops ([`WindowManager::stop`], or `SIGINT` and `SIGTERM` in `main.rs`), it connects to each subscriber and shuts the connection down without writing anything. +## Commands + +A message that gives an order is a call to a method of the [`WindowManager`] from +[`WindowManager::process_command`]. An order that goes somewhere takes one of two kinds of +direction, both from `komorebi-layouts`: + +- An [`OperationDirection`] (left, right, up, down) is a side of the focused container's tile. + The workspace asks its layout which container is on that side + ([`Workspace::new_idx_for_direction`]). A layout answers from the index of the focused + container and the number of containers, not from where the windows are. +- A [`CycleDirection`] (next, previous) follows the order of the workspace's containers, and + wraps around at both ends ([`Workspace::new_idx_for_cycle_direction`]). + +`FocusWindow` and `CycleFocusWindow` focus another container of the focused workspace and give +its window the focus with the backend's `focus` ([`WindowManager::focus_container_in_direction`], +[`WindowManager::focus_container_in_cycle_direction`]). They retile nothing. When there is no +container in that direction, the message fails and changes nothing. Whether the pointer follows +the focus is [`WindowManager::mouse_follows_focus`], which `MouseFollowsFocus` and +`ToggleMouseFollowsFocus` set. + ## The NixOS module The flake exports one module under two names, `nixosModules.default` and @@ -280,7 +304,7 @@ module's unit. changes its containers. - [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the operations on it (tile the workspace in front, tile every monitor, take a minimized - window out). + window out, move the focus). - [`desktop`](../../komorebi/src/desktop.rs): loads the monitors and the open windows from the backend. - [`window_manager_event`](../../komorebi/src/window_manager_event.rs) and @@ -362,6 +386,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | Messages are handled one at a time, and in order on one connection | framework path: [`read_commands_uds`] reads a connection line by line and handles each message with the window manager locked | `the_messages_on_one_connection_are_handled_in_order` | none | | A socket left behind by a daemon that did not stop cleanly does not keep the next one from starting | framework path: [`WindowManager::new`] removes the file before it binds | `a_socket_file_left_behind_is_replaced` | none | | A daemon that is told to stop leaves no socket behind | framework path: [`WindowManager::stop`] removes it before it exits | `the_daemon_answers_on_its_socket_and_stops_when_it_is_told_to` | `SIGKILL` | +| Moving the focus moves no window | test | `focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing`, `vm-core-e2e` ("moving the focus moved no window") | none | | A subscriber that is gone is dropped, not retried | test | `a_subscriber_that_is_gone_is_dropped_and_not_tried_again` | none | | The bridge holds no window manager logic | convention, with every decision about an event in the table, which the `kwin::state` unit tests pin | the unit tests in `komorebi/src/kwin/state.rs` | none | | What the bridge sends is what the table reads | type checker: the JSDoc types of the messages in [`bridge.js`]; tests: the events of [`fixtures`] are what the bridge's tests check it sends and what the table's tests feed it | `what the bridge sends for a session is what the daemon's tests read`, `the_bridges_events_for_a_session_are_the_window_events_komorebi_expects` | none | @@ -469,6 +494,8 @@ A window is shown, and ends up on a tile: driven end to end against the fake. - [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket, from its start to a `Stop`. +- [`komorebi/tests/focus.rs`](../../komorebi/tests/focus.rs): the focus commands against the + fake. - [`nix/nixos-module.nix`](../../nix/nixos-module.nix): the NixOS module; [`nix/tests/nixos-module.nix`](../../nix/tests/nixos-module.nix), its scenarios, evaluated in real NixOS systems; and [`nix/tests/vm/suites/module`](../../nix/tests/vm/suites/module/test.py), @@ -494,6 +521,13 @@ A window is shown, and ends up on a tile: [`WindowManager`]: ../../komorebi/src/window_manager.rs [`WindowManager::process_event`]: ../../komorebi/src/process_event.rs [`WindowManager::update_focused_workspace`]: ../../komorebi/src/window_manager.rs +[`WindowManager::focus_container_in_direction`]: ../../komorebi/src/window_manager.rs +[`WindowManager::focus_container_in_cycle_direction`]: ../../komorebi/src/window_manager.rs +[`WindowManager::mouse_follows_focus`]: ../../komorebi/src/window_manager.rs +[`Workspace::new_idx_for_direction`]: ../../komorebi/src/workspace.rs +[`Workspace::new_idx_for_cycle_direction`]: ../../komorebi/src/workspace.rs +[`OperationDirection`]: ../../komorebi/src/core/mod.rs +[`CycleDirection`]: ../../komorebi/src/core/mod.rs [`WindowManagerEvent`]: ../../komorebi/src/window_manager_event.rs [`window_manager_event_listener`]: ../../komorebi/src/window_manager_event_listener.rs [`listen_for_events`]: ../../komorebi/src/process_event.rs diff --git a/docs/index.md b/docs/index.md index 09f529d9..64b3fdfb 100644 --- a/docs/index.md +++ b/docs/index.md @@ -32,6 +32,7 @@ key bindings --------> komorebic <------> komorebi the flake's module, which also starts komorebi with every Plasma session, and from source anywhere else. [Running komorebi](usage/running-komorebi.md) explains how to start and stop the daemon, ask it what it is doing and read its log. +[Focusing windows](usage/focusing-windows.md) explains how to give the focus to another window. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/focusing-windows.md b/docs/usage/focusing-windows.md new file mode 100644 index 00000000..599d306f --- /dev/null +++ b/docs/usage/focusing-windows.md @@ -0,0 +1,57 @@ +# Focusing windows + +komorebi gives the focus to another window of the focused workspace when it is told to. It +moves no window to do it: the windows stay on their tiles, and KWin makes the chosen one the +active window. + +## In a direction + +[`komorebic focus`](../cli/focus.md) focuses the window whose tile is on one side of the +focused one: `left`, `right`, `up` or `down`. Which tile is on which side is the layout's +business. In the BSP layout with three windows, for example, the first window has the left +half, and `focus right` from it goes to the window at the top right. + +```sh +komorebic focus left +komorebic focus down +komorebic focus up +komorebic focus right +``` + +When there is no tile on that side, nothing happens, and the daemon logs "there is no container +in this direction". + +## In order + +[`komorebic cycle-focus`](../cli/cycle-focus.md) focuses the next or the previous window in the +order of the workspace, which is the order in which the windows were opened, each new one +after the window that had the focus. It wraps around: `next` from the last window is the +first. + +```sh +komorebic cycle-focus next +komorebic cycle-focus previous +``` + +## The pointer + +By default the pointer moves to the middle of the window that is given the focus. komorebi asks +KWin to do it with its "Move Mouse to Focus" shortcut, so the pointer follows only in a session +that has KWin's global shortcuts (a headless KWin has none). +[`komorebic mouse-follows-focus`](../cli/mouse-follows-focus.md) turns this on or off, and +[`komorebic toggle-mouse-follows-focus`](../cli/toggle-mouse-follows-focus.md) switches between +the two: + +```sh +komorebic mouse-follows-focus disable +komorebic toggle-mouse-follows-focus +``` + +The setting is in the daemon's state as `mouse_follows_focus`, and it lasts until the daemon +stops. + +## Binding them to keys + +komorebi reads no keys. Bind the commands to keys in Plasma's System Settings, under Keyboard, +Shortcuts, as custom shortcuts that run a command: for example `Meta+H` for +`komorebic focus left` and `Meta+L` for `komorebic focus right`. diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index f5c474ae..155ea46d 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -8,7 +8,9 @@ //! //! [`SocketMessage`] is every message the daemon takes on its socket, [`StateQuery`] every //! question [`SocketMessage::Query`] can ask, and [`SubscribeOptions`] what a subscriber can ask -//! of its notifications. +//! of its notifications. A message that goes somewhere takes the directions of the layouts: an +//! [`OperationDirection`] is a side of the focused tile, and a [`CycleDirection`] the next or the +//! previous container in the order of the workspace. use clap::ValueEnum; use color_eyre::eyre; @@ -334,11 +336,18 @@ pub struct SubscribeOptions { #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(tag = "type", content = "content")] pub enum SocketMessage { + // Window / Container Commands + FocusWindow(OperationDirection), + CycleFocusWindow(CycleDirection), Stop, Retile, State, MonitorInformation, Query(StateQuery), + MouseFollowsFocus(bool), + ToggleMouseFollowsFocus, + // RemoveTitleBar(ApplicationIdentifier, String), + // ToggleTitleBars, AddSubscriberSocket(String), AddSubscriberSocketWithOptions(String, SubscribeOptions), RemoveSubscriberSocket(String), diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index 6bfa64a6..e6208fab 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -58,6 +58,31 @@ pub struct Monitor { pub workspace_padding: Option, } +/// Returns a monitor with one empty workspace, the way [`Monitor::new`] makes one, from owned +/// names +pub fn new( + id: u32, + size: Rect, + work_area_size: Rect, + device: String, + serial_number_id: String, +) -> Monitor { + let mut workspaces = Ring::default(); + workspaces.elements_mut().push_back(Workspace::default()); + + Monitor { + id, + device, + serial_number_id, + size, + work_area_size, + work_area_offset: None, + workspaces, + container_padding: None, + workspace_padding: None, + } +} + impl Monitor { #[allow(clippy::field_reassign_with_default)] pub fn new( diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index ecd3721c..c1f4c923 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -10,10 +10,18 @@ //! - **MonitorInformation**: the id, the name and the bounds of each monitor, as JSON. //! - **Query**: one value as text, the answer to a [`StateQuery`]. //! -//! The others answer nothing: **Retile** tiles the focused workspace of every monitor again, -//! **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name of -//! its socket in the data directory, **RemoveSubscriberSocket** removes one, and **Stop** stops the -//! daemon ([`WindowManager::stop`]). +//! The others answer nothing: +//! +//! - **FocusWindow** and **CycleFocusWindow** give the focus to the container on one side of the +//! focused one, or to the next or the previous one in the workspace +//! ([`WindowManager::focus_container_in_direction`], +//! [`WindowManager::focus_container_in_cycle_direction`]). +//! - **MouseFollowsFocus** and **ToggleMouseFollowsFocus** set whether the pointer is moved to +//! the window that is given the focus. +//! - **Retile** tiles the focused workspace of every monitor again. +//! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name +//! of its socket in the data directory, and **RemoveSubscriberSocket** removes one. +//! - **Stop** stops the daemon ([`WindowManager::stop`]). //! //! Once a message has been handled, every subscriber is sent a notification of it //! ([`notify_subscribers`]). @@ -96,6 +104,9 @@ impl WindowManager { /// # Errors /// /// - A query about the focused monitor, workspace or container when there is none. + /// - The focus cannot be moved, for one of the reasons + /// [`WindowManager::focus_container_in_direction`] and + /// [`WindowManager::focus_container_in_cycle_direction`] give. /// - The window manager fails to retile, for one of the reasons /// [`WindowManager::retile_all`] gives. /// - The answer cannot be written to `reply`. @@ -114,6 +125,12 @@ impl WindowManager { let initial_state = State::from(self.as_ref()); match message { + SocketMessage::FocusWindow(direction) => { + self.focus_container_in_direction(direction)?; + } + SocketMessage::CycleFocusWindow(direction) => { + self.focus_container_in_cycle_direction(direction)?; + } SocketMessage::Retile => self.retile_all()?, SocketMessage::State => { let state = match serde_json::to_string_pretty(&State::from(&*self)) { @@ -181,6 +198,12 @@ impl WindowManager { reply.write_all(response.as_bytes())?; } + SocketMessage::MouseFollowsFocus(enable) => { + self.mouse_follows_focus = enable; + } + SocketMessage::ToggleMouseFollowsFocus => { + self.mouse_follows_focus = !self.mouse_follows_focus; + } SocketMessage::AddSubscriberSocket(ref socket) => { let mut sockets = SUBSCRIPTION_SOCKETS.lock(); let socket_path = DATA_DIR.join(socket); diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 4e99ad3d..6a36c32a 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -7,8 +7,10 @@ //! again ([`WindowManager::update_focused_workspace`]). //! //! It also owns the daemon's command socket, which [`listen_for_commands`] reads -//! ([`WindowManager::process_command`]), and stops the daemon when it is asked to -//! ([`WindowManager::stop`]). +//! ([`WindowManager::process_command`]), carries out the orders that come in on it, such as +//! moving the focus ([`WindowManager::focus_container_in_direction`], +//! [`WindowManager::focus_container_in_cycle_direction`]), and stops the daemon when it is asked +//! to ([`WindowManager::stop`]). //! //! [`listen_for_commands`]: crate::process_command::listen_for_commands @@ -17,6 +19,8 @@ use crate::LibraryError; use crate::SUBSCRIPTION_SOCKETS; use crate::backend::backend; use crate::container::Container; +use crate::core::CycleDirection; +use crate::core::OperationDirection; use crate::core::Rect; use crate::desktop; use crate::monitor::Monitor; @@ -26,6 +30,7 @@ use crate::window_manager_event::WindowManagerEvent; use crate::workspace::Workspace; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use color_eyre::eyre::bail; use crossbeam_channel::Receiver; use std::collections::HashMap; use std::io::ErrorKind; @@ -40,6 +45,7 @@ pub struct WindowManager { /// The socket the daemon takes messages on, `komorebi.sock` in [`struct@DATA_DIR`] unless /// [`WindowManager::new`] was given another path pub command_listener: UnixListener, + /// Whether the pointer is moved to the window that is given the focus, which is the default pub mouse_follows_focus: bool, pub work_area_offset: Option, /// The events the backend has reported and the window manager has yet to handle, from @@ -112,6 +118,48 @@ impl WindowManager { Ok(()) } + /// Gives the focus to the window of the container whose tile is on the `direction` side of + /// the focused one, and the pointer follows it if [`WindowManager::mouse_follows_focus`] is + /// set + /// + /// Nothing is retiled: the focus moves, the windows stay where they are. + /// + /// # Errors + /// + /// - There is no focused workspace, or no container on that side of the focused one. + /// - The backend refuses to focus the window. + #[tracing::instrument(skip(self))] + pub fn focus_container_in_direction( + &mut self, + direction: OperationDirection, + ) -> eyre::Result<()> { + let mouse_follows_focus = self.mouse_follows_focus; + + let workspace = self.focused_workspace()?; + + tracing::info!("focusing container"); + + let new_idx = workspace.new_idx_for_direction(direction); + + // if there is no container in that direction for this workspace + match new_idx { + None => bail!("there is no container in this direction"), + Some(idx) => { + let workspace = self.focused_workspace_mut()?; + workspace.focus_container(idx); + } + } + + let ws = self.focused_workspace_mut()?; + if !ws.is_empty() + && let Ok(focused_window) = self.focused_window() + { + focused_window.focus(mouse_follows_focus)?; + } + + Ok(()) + } + #[tracing::instrument(skip(self))] pub fn update_focused_workspace( &mut self, @@ -256,6 +304,36 @@ impl WindowManager { Ok(()) } + /// Gives the focus to the window of the next (or the previous) container of the focused + /// workspace, wrapping around at the ends, and the pointer follows it if + /// [`WindowManager::mouse_follows_focus`] is set + /// + /// # Errors + /// + /// - There is no focused workspace, or it has no containers. + /// - The backend refuses to focus the window. + #[tracing::instrument(skip(self))] + pub fn focus_container_in_cycle_direction( + &mut self, + direction: CycleDirection, + ) -> eyre::Result<()> { + tracing::info!("focusing container"); + + let mouse_follows_focus = self.mouse_follows_focus; + + let workspace = self.focused_workspace_mut()?; + + let new_idx = workspace + .new_idx_for_cycle_direction(direction) + .ok_or_eyre("this is not a valid direction from the current position")?; + + workspace.focus_container(new_idx); + + self.focused_window_mut()?.focus(mouse_follows_focus)?; + + Ok(()) + } + pub fn update_known_window_ids(&mut self) { tracing::trace!("updating list of known window_ids"); let mut known_window_ids = HashMap::new(); @@ -281,6 +359,7 @@ mod tests { use super::*; use crate::backend::fake::FakeBackend; use crate::backend::with_backend; + use crate::monitor; use crossbeam_channel::Sender; use crossbeam_channel::bounded; use std::path::PathBuf; @@ -328,6 +407,54 @@ mod tests { let (_wm, _test_context) = setup_window_manager(); } + #[test] + fn test_focus_container_in_cycle_direction() { + let (mut wm, _test_context) = setup_window_manager(); + + // Create a monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + let workspace = m.focused_workspace_mut().unwrap(); + + for i in 0..4 { + let mut container = Container::default(); + container.windows_mut().push_back(Window::from(i)); + workspace.add_container_to_back(container); + } + assert_eq!(workspace.containers().len(), 4); + + workspace.focus_container(0); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + + // container focus should be on the second container + wm.focus_container_in_cycle_direction(CycleDirection::Next) + .ok(); + assert_eq!(wm.focused_container_idx().unwrap(), 1); + + // container focus should be on the third container + wm.focus_container_in_cycle_direction(CycleDirection::Next) + .ok(); + assert_eq!(wm.focused_container_idx().unwrap(), 2); + + // container focus should be on the second container + wm.focus_container_in_cycle_direction(CycleDirection::Previous) + .ok(); + assert_eq!(wm.focused_container_idx().unwrap(), 1); + + // container focus should be on the first container + wm.focus_container_in_cycle_direction(CycleDirection::Previous) + .ok(); + assert_eq!(wm.focused_container_idx().unwrap(), 0); + } + #[test] fn a_socket_file_left_behind_is_replaced() -> eyre::Result<()> { let socket_path = PathBuf::from(format!("/tmp/komorebi-test-{}.sock", Uuid::new_v4())); diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 6af1e023..f21e0da0 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -6,8 +6,10 @@ //! falls back to come from the monitor it is on ([`WorkspaceGlobals`]). use crate::container::Container; +use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::OperationDirection; use crate::core::Rect; use crate::lockable_sequence::LockableSequence; use crate::ring::Ring; @@ -67,6 +69,29 @@ impl Workspace { self.focus_container(j); } + /// Returns the index of the container whose tile is on the `direction` side of the focused + /// one in the workspace's layout, or `None` when there is none on that side + pub fn new_idx_for_direction(&self, direction: OperationDirection) -> Option { + let len = NonZeroUsize::new(self.containers().len())?; + + direction.destination( + self.layout.as_boxed_direction().as_ref(), + None, + self.focused_container_idx(), + len, + None, + ) + } + + /// Returns the index of the container after (or before) the focused one, wrapping around at + /// the ends, or `None` when the workspace has no containers + pub fn new_idx_for_cycle_direction(&self, direction: CycleDirection) -> Option { + Option::from(direction.next_idx( + self.focused_container_idx(), + NonZeroUsize::new(self.containers().len())?, + )) + } + pub fn container_idx_for_window(&self, window_id: u32) -> Option { let mut idx = None; for (i, x) in self.containers().iter().enumerate() { diff --git a/komorebi/tests/focus.rs b/komorebi/tests/focus.rs new file mode 100644 index 00000000..648616d1 --- /dev/null +++ b/komorebi/tests/focus.rs @@ -0,0 +1,191 @@ +//! Moving the focus with `focus` and `cycle-focus`, against an in-memory desktop: the messages go +//! in through [`WindowManager::process_command`], and what comes out is the window the backend is +//! asked to focus and whether the pointer goes with it. +//! +//! Window ids are in the 19_000s. + +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::CycleDirection; +use komorebi::core::OperationDirection; +use komorebi::core::SocketMessage; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +/// A window manager over a fake desktop with one 1920x1080 monitor, and a window for each of +/// `ids`, opened in that order. The last one has the focus, and the commands it took to get there +/// are cleared. +fn desktop_with(ids: &[u32]) -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + // unix socket paths are limited to ~104 bytes on macOS, which the temp dir alone can exceed + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmf-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + for &id in ids { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + wm + }); + + fake.clear_commands(); + (fake, wm) +} + +fn send(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn focused(wm: &WindowManager) -> u32 { + wm.focused_window().unwrap().id +} + +#[test] +fn focus_gives_the_focus_to_the_window_on_that_side_and_moves_nothing() { + let (fake, mut wm) = desktop_with(&[19_001, 19_002]); + let tiles = (fake.rect_of(19_001), fake.rect_of(19_002)); + assert_eq!(focused(&wm), 19_002); + + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Left), + ); + + assert_eq!(focused(&wm), 19_001); + assert_eq!(fake.commands(), [Command::Focus(19_001, true)]); + + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Right), + ); + + assert_eq!(focused(&wm), 19_002); + assert_eq!( + fake.commands(), + [Command::Focus(19_001, true), Command::Focus(19_002, true)] + ); + assert_eq!((fake.rect_of(19_001), fake.rect_of(19_002)), tiles); +} + +#[test] +fn focus_towards_a_side_with_no_window_is_an_error_and_changes_nothing() { + // the two windows are side by side: there is nothing above them + let (fake, mut wm) = desktop_with(&[19_011, 19_012]); + + let result = with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::FocusWindow(OperationDirection::Up), + Vec::new(), + ) + }); + + assert_eq!( + result.map_err(|error| error.to_string()), + Err(String::from("there is no container in this direction")) + ); + assert_eq!(focused(&wm), 19_012); + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); +} + +#[test] +fn cycle_focus_goes_round_the_containers_in_order() { + let (fake, mut wm) = desktop_with(&[19_021, 19_022, 19_023]); + assert_eq!(focused(&wm), 19_023); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(CycleDirection::Next), + ); + assert_eq!(focused(&wm), 19_021, "next from the last is the first"); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(CycleDirection::Next), + ); + assert_eq!(focused(&wm), 19_022); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(CycleDirection::Previous), + ); + send( + &fake, + &mut wm, + SocketMessage::CycleFocusWindow(CycleDirection::Previous), + ); + assert_eq!(focused(&wm), 19_023, "previous from the first is the last"); + + assert_eq!( + fake.commands(), + [ + Command::Focus(19_021, true), + Command::Focus(19_022, true), + Command::Focus(19_021, true), + Command::Focus(19_023, true), + ] + ); +} + +#[test] +fn cycle_focus_on_an_empty_workspace_is_an_error() { + let (fake, mut wm) = desktop_with(&[]); + + let result = with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::CycleFocusWindow(CycleDirection::Next), + Vec::new(), + ) + }); + + assert!(result.is_err()); + assert!(fake.commands().is_empty(), "{:?}", fake.commands()); +} + +#[test] +fn without_mouse_follows_focus_the_pointer_stays_where_it_is() { + let (fake, mut wm) = desktop_with(&[19_031, 19_032]); + + send(&fake, &mut wm, SocketMessage::MouseFollowsFocus(false)); + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Left), + ); + send(&fake, &mut wm, SocketMessage::ToggleMouseFollowsFocus); + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Right), + ); + + assert_eq!( + fake.commands(), + [Command::Focus(19_031, false), Command::Focus(19_032, true)] + ); + assert!(wm.mouse_follows_focus); +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 2e0c4805..d09856d2 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -5,6 +5,9 @@ //! is written and the answer is printed. The messages are [`komorebi_client::SocketMessage`]s, //! sent with [`komorebi_client::send_message`] and [`komorebi_client::send_query`]. //! +//! `focus` and `cycle-focus` give the focus to another window of the focused workspace, and +//! `mouse-follows-focus` and `toggle-mouse-follows-focus` set whether the pointer goes with it. +//! //! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens //! on a socket in the daemon's data directory, to which the daemon sends a notification after each //! event and each message it handles. @@ -17,8 +20,11 @@ use chrono::Utc; use clap::CommandFactory; use clap::Parser; +use clap::ValueEnum; use color_eyre::eyre; use fs_tail::TailedFile; +use komorebi_client::CycleDirection; +use komorebi_client::OperationDirection; use komorebi_client::SocketMessage; use komorebi_client::StateQuery; use komorebi_client::send_message; @@ -32,6 +38,21 @@ use std::process::Stdio; use std::time::Duration; use sysinfo::ProcessesToUpdate; +#[derive(Copy, Clone, ValueEnum)] +enum BooleanState { + Enable, + Disable, +} + +impl From for bool { + fn from(b: BooleanState) -> Self { + match b { + BooleanState::Enable => true, + BooleanState::Disable => false, + } + } +} + macro_rules! gen_enum_subcommand_args { // SubCommand Pattern: Enum Type ( $( $name:ident: $element:ty ),+ $(,)? ) => { @@ -48,6 +69,9 @@ macro_rules! gen_enum_subcommand_args { } gen_enum_subcommand_args! { + Focus: OperationDirection, + CycleFocus: CycleDirection, + MouseFollowsFocus: BooleanState, Query: StateQuery, } @@ -132,8 +156,19 @@ enum SubCommand { // UnsubscribePipe(UnsubscribePipe), /// Tail komorebi's process logs (cancel with Ctrl-C) Log, + /// Change focus to the window in the specified direction + #[clap(arg_required_else_help = true)] + Focus(Focus), + /// Change focus to the window in the specified cycle direction + #[clap(arg_required_else_help = true)] + CycleFocus(CycleFocus), /// Force the retiling of all managed windows Retile, + /// Enable or disable mouse follows focus on all workspaces + #[clap(arg_required_else_help = true)] + MouseFollowsFocus(MouseFollowsFocus), + /// Toggle mouse follows focus on all workspaces + ToggleMouseFollowsFocus, } fn print_query(message: &SocketMessage) { @@ -251,6 +286,12 @@ fn main() -> eyre::Result<()> { println!("{line}"); } } + SubCommand::Focus(args) => { + send_message(&SocketMessage::FocusWindow(args.operation_direction))?; + } + SubCommand::CycleFocus(args) => { + send_message(&SocketMessage::CycleFocusWindow(args.cycle_direction))?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } @@ -263,6 +304,12 @@ fn main() -> eyre::Result<()> { SubCommand::MonitorInformation => { print_query(&SocketMessage::MonitorInformation); } + SubCommand::ToggleMouseFollowsFocus => { + send_message(&SocketMessage::ToggleMouseFollowsFocus)?; + } + SubCommand::MouseFollowsFocus(args) => { + send_message(&SocketMessage::MouseFollowsFocus(args.boolean_state.into()))?; + } SubCommand::SubscribeSocket(args) => { send_message(&SocketMessage::AddSubscriberSocket(args.socket))?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index c50a99a5..1e25859e 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -144,6 +144,55 @@ fn subscribe_socket_and_unsubscribe_socket_send_the_name_they_are_given() { } } +/// Runs `komorebic` with `args` against a daemon that answers nothing, and checks that it wrote +/// `message` on the socket, printed nothing and exited with status 0 +fn sends(args: &[&str], message: &str) { + let runtime = Runtime::new(); + let daemon = runtime.serve(""); + + let output = runtime.komorebic(args); + + assert!(output.status.success(), "{args:?}: {output:?}"); + assert_eq!(daemon.join().unwrap(), message, "{args:?}"); + assert_eq!(stdout(&output), "", "{args:?}"); +} + +#[test] +fn focus_and_cycle_focus_send_the_direction_they_are_given() { + sends( + &["focus", "left"], + r#"{"type":"FocusWindow","content":"Left"}"#, + ); + sends( + &["focus", "down"], + r#"{"type":"FocusWindow","content":"Down"}"#, + ); + sends( + &["cycle-focus", "next"], + r#"{"type":"CycleFocusWindow","content":"Next"}"#, + ); + sends( + &["cycle-focus", "previous"], + r#"{"type":"CycleFocusWindow","content":"Previous"}"#, + ); +} + +#[test] +fn mouse_follows_focus_is_set_with_enable_and_disable_or_toggled() { + sends( + &["mouse-follows-focus", "enable"], + r#"{"type":"MouseFollowsFocus","content":true}"#, + ); + sends( + &["mouse-follows-focus", "disable"], + r#"{"type":"MouseFollowsFocus","content":false}"#, + ); + sends( + &["toggle-mouse-follows-focus"], + r#"{"type":"ToggleMouseFollowsFocus"}"#, + ); +} + #[test] fn without_a_daemon_a_question_fails() { let runtime = Runtime::new(); @@ -184,15 +233,19 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { pages, [ "completions.md", + "cycle-focus.md", "data-directory.md", + "focus.md", "log.md", "monitor-information.md", + "mouse-follows-focus.md", "query.md", "retile.md", "start.md", "state.md", "stop.md", "subscribe-socket.md", + "toggle-mouse-follows-focus.md", "unsubscribe-socket.md", ] ); diff --git a/nix/tests/vm/suites/core-e2e/test.py b/nix/tests/vm/suites/core-e2e/test.py index 8fdbb315..269c27a6 100644 --- a/nix/tests/vm/suites/core-e2e/test.py +++ b/nix/tests/vm/suites/core-e2e/test.py @@ -2,8 +2,9 @@ # reach KWin through the held call and that KWin carries them out, so that each window is where # the daemon asked for it (`komorebi/tests/wm_events.rs` checks the window manager's side against # the fake), that the daemon and KWin agree on which window has the focus, that `komorebic` reaches -# the daemon of a session and reads its state, and that `komorebic stop` gives KWin back what the -# daemon set up in it. A window manager that agrees with itself proves nothing, so what the daemon +# the daemon of a session and reads its state, that `komorebic focus` and `cycle-focus` move KWin's +# focus (`komorebi/tests/focus.rs` checks which window they pick), and that `komorebic stop` gives +# KWin back what the daemon set up in it. A window manager that agrees with itself proves nothing, so what the daemon # believes is read from its debug log and from `komorebic state`, and what KWin has through kdotool. import json @@ -108,7 +109,32 @@ checks.check("KWin focused win1", kde.wait_for(lambda: kde.title(kde.active()) = checks.check("... and the daemon followed", kde.wait_for(focus_agrees)) checks.check("... and its state says so", kde.wait_for(state_agrees)) -print("== 4. minimize and restore") +print("== 4. the focus moves on komorebic's commands") +kde.komorebic("focus", "right") +checks.check( + "after 'focus right' KWin has given the focus to another window", + kde.wait_for(lambda: kde.title(kde.active()) not in ("", "win1")), +) +checks.check("... and komorebi's state focuses the same one", kde.wait_for(state_agrees)) +kde.komorebic("focus", "left") +checks.check( + "'focus left' gives it back to win1", kde.wait_for(lambda: kde.title(kde.active()) == "win1") +) +checks.check("... and komorebi's state says so", kde.wait_for(state_agrees)) +kde.komorebic("cycle-focus", "next") +checks.check( + "'cycle-focus next' focuses win2, the next container in komorebi's order", + kde.wait_for(lambda: kde.title(kde.active()) == "win2"), +) +checks.check("... and komorebi's state says so", kde.wait_for(state_agrees)) +kde.komorebic("cycle-focus", "previous") +checks.check( + "'cycle-focus previous' goes back to win1", + kde.wait_for(lambda: kde.title(kde.active()) == "win1"), +) +checks.check("moving the focus moved no window", all(where_asked(t) for t in titles)) + +print("== 5. minimize and restore") kde.minimize(kde.wid("win2")) two = ["win1", "win3"] checks.check( @@ -135,7 +161,7 @@ checks.check( ) report(titles) -print("== 5. close") +print("== 6. close") kde.close(kde.wid("win3")) checks.check("KWin closed win3", kde.wait_for(lambda: kde.wid("win3") == "", timeout=10)) checks.check( @@ -152,7 +178,7 @@ report(["win1", "win2"]) checks.check("komorebi manages the two that are left", kde.wait_for(lambda: kde.managed() == 2)) checks.check("KWin carried out every command", "the bridge could not do" not in daemon_log()) -print("== 6. KWin restarts under the daemon") +print("== 7. KWin restarts under the daemon") kde.restart_kwin() checks.check( "the daemon loaded its script into the new KWin", @@ -173,7 +199,7 @@ checks.check( ) report(["afterwards"]) -print("== 7. komorebic stop") +print("== 8. komorebic stop") kde.komorebic("stop") checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running())) checks.check("its socket is gone", kde.run(f"test -e {kde.runtime}/komorebi/komorebi.sock")[0] != 0)