diff --git a/README.md b/README.md index 8d1a7d0b..0f402fe3 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,9 @@ without showing it; their `cycle-` and `-last-workspace` forms go to the next, the previous or the last workspace, `workspace-name` names a workspace for `focus-named-workspace` and the other named commands, and `new-workspace` and `close-workspace` add and remove one. +At the edge of a monitor, `focus` and `move` cross to the monitor on that side; +`focus-monitor`, `move-to-monitor`, `send-to-monitor` and their kind work on the +monitors, and `eager-focus` finds the window of an application wherever it is. 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/cross-monitor-move-behaviour.md b/docs/cli/cross-monitor-move-behaviour.md new file mode 100644 index 00000000..aa3dbfb2 --- /dev/null +++ b/docs/cli/cross-monitor-move-behaviour.md @@ -0,0 +1,19 @@ +```text +Set the behaviour when moving windows across monitor boundaries + +Usage: cross-monitor-move-behaviour + +Arguments: + + Possible values: + - swap: Swap the window container with the window container at the edge of the adjacent + monitor + - insert: Insert the window container into the focused workspace on the adjacent monitor + - no-op: Do nothing if trying to move a window container in the direction of an adjacent + monitor + +Options: + -h, --help + Print help (see a summary with '-h') + +``` diff --git a/docs/cli/cycle-monitor.md b/docs/cli/cycle-monitor.md new file mode 100644 index 00000000..5ff4e41b --- /dev/null +++ b/docs/cli/cycle-monitor.md @@ -0,0 +1,14 @@ +```text +Focus the monitor in the given cycle direction + +Usage: cycle-monitor + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-move-to-monitor.md b/docs/cli/cycle-move-to-monitor.md new file mode 100644 index 00000000..66e561a3 --- /dev/null +++ b/docs/cli/cycle-move-to-monitor.md @@ -0,0 +1,14 @@ +```text +Move the focused window to the monitor in the given cycle direction + +Usage: cycle-move-to-monitor + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-move-workspace-to-monitor.md b/docs/cli/cycle-move-workspace-to-monitor.md new file mode 100644 index 00000000..e7b5353b --- /dev/null +++ b/docs/cli/cycle-move-workspace-to-monitor.md @@ -0,0 +1,14 @@ +```text +Move the focused workspace monitor in the given cycle direction + +Usage: cycle-move-workspace-to-monitor + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/cycle-send-to-monitor.md b/docs/cli/cycle-send-to-monitor.md new file mode 100644 index 00000000..e872f961 --- /dev/null +++ b/docs/cli/cycle-send-to-monitor.md @@ -0,0 +1,14 @@ +```text +Send the focused window to the monitor in the given cycle direction + +Usage: cycle-send-to-monitor + +Arguments: + + [possible values: previous, next] + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/display-index-preference.md b/docs/cli/display-index-preference.md new file mode 100644 index 00000000..fa39695b --- /dev/null +++ b/docs/cli/display-index-preference.md @@ -0,0 +1,17 @@ +```text +Set the display index preference for a monitor identified using its display name + +Usage: display-index-preference + +Arguments: + + Preferred monitor index (zero-indexed) + + + Display name as identified in komorebic state + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/eager-focus.md b/docs/cli/eager-focus.md new file mode 100644 index 00000000..826abe1d --- /dev/null +++ b/docs/cli/eager-focus.md @@ -0,0 +1,14 @@ +```text +Focus the first managed window matching the given executable + +Usage: eager-focus + +Arguments: + + Case-sensitive exe identifier + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-monitor-at-cursor.md b/docs/cli/focus-monitor-at-cursor.md new file mode 100644 index 00000000..dba13349 --- /dev/null +++ b/docs/cli/focus-monitor-at-cursor.md @@ -0,0 +1,10 @@ +```text +Focus the monitor at the current cursor location + +Usage: focus-monitor-at-cursor + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-monitor-workspace.md b/docs/cli/focus-monitor-workspace.md new file mode 100644 index 00000000..c20cbb22 --- /dev/null +++ b/docs/cli/focus-monitor-workspace.md @@ -0,0 +1,17 @@ +```text +Focus the specified workspace on the target monitor + +Usage: focus-monitor-workspace + +Arguments: + + Target monitor index (zero-indexed) + + + Workspace index on the target monitor (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/focus-monitor.md b/docs/cli/focus-monitor.md new file mode 100644 index 00000000..28bc26d6 --- /dev/null +++ b/docs/cli/focus-monitor.md @@ -0,0 +1,14 @@ +```text +Focus the specified monitor + +Usage: focus-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-to-monitor-workspace.md b/docs/cli/move-to-monitor-workspace.md new file mode 100644 index 00000000..cab10d66 --- /dev/null +++ b/docs/cli/move-to-monitor-workspace.md @@ -0,0 +1,17 @@ +```text +Move the focused window to the specified monitor workspace + +Usage: move-to-monitor-workspace + +Arguments: + + Target monitor index (zero-indexed) + + + Workspace index on the target monitor (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-to-monitor.md b/docs/cli/move-to-monitor.md new file mode 100644 index 00000000..fe9f95f8 --- /dev/null +++ b/docs/cli/move-to-monitor.md @@ -0,0 +1,14 @@ +```text +Move the focused window to the specified monitor + +Usage: move-to-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-to-named-workspace.md b/docs/cli/move-to-named-workspace.md new file mode 100644 index 00000000..8233cbb7 --- /dev/null +++ b/docs/cli/move-to-named-workspace.md @@ -0,0 +1,14 @@ +```text +Move the focused window to the specified workspace + +Usage: move-to-named-workspace + +Arguments: + + Target workspace name + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/move-workspace-to-monitor.md b/docs/cli/move-workspace-to-monitor.md new file mode 100644 index 00000000..c1f3148d --- /dev/null +++ b/docs/cli/move-workspace-to-monitor.md @@ -0,0 +1,14 @@ +```text +Move the focused workspace to the specified monitor + +Usage: move-workspace-to-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/send-to-monitor-workspace.md b/docs/cli/send-to-monitor-workspace.md new file mode 100644 index 00000000..213303ea --- /dev/null +++ b/docs/cli/send-to-monitor-workspace.md @@ -0,0 +1,17 @@ +```text +Send the focused window to the specified monitor workspace + +Usage: send-to-monitor-workspace + +Arguments: + + Target monitor index (zero-indexed) + + + Workspace index on the target monitor (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/send-to-monitor.md b/docs/cli/send-to-monitor.md new file mode 100644 index 00000000..5ae3ae21 --- /dev/null +++ b/docs/cli/send-to-monitor.md @@ -0,0 +1,14 @@ +```text +Send the focused window to the specified monitor + +Usage: send-to-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/send-to-named-workspace.md b/docs/cli/send-to-named-workspace.md new file mode 100644 index 00000000..75cea540 --- /dev/null +++ b/docs/cli/send-to-named-workspace.md @@ -0,0 +1,14 @@ +```text +Send the focused window to the specified workspace + +Usage: send-to-named-workspace + +Arguments: + + Target workspace name + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/swap-workspaces-with-monitor.md b/docs/cli/swap-workspaces-with-monitor.md new file mode 100644 index 00000000..c4c8bebe --- /dev/null +++ b/docs/cli/swap-workspaces-with-monitor.md @@ -0,0 +1,14 @@ +```text +Swap focused monitor workspaces with specified monitor + +Usage: swap-workspaces-with-monitor + +Arguments: + + Target index (zero-indexed) + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/toggle-cross-monitor-move-behaviour.md b/docs/cli/toggle-cross-monitor-move-behaviour.md new file mode 100644 index 00000000..a5c8900b --- /dev/null +++ b/docs/cli/toggle-cross-monitor-move-behaviour.md @@ -0,0 +1,10 @@ +```text +Toggle the behaviour when moving windows across monitor boundaries + +Usage: toggle-cross-monitor-move-behaviour + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 906490c4..07dc1607 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -304,7 +304,10 @@ direction, both from `komorebi-layouts`: `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 +container in that direction, the focus goes to the monitor in that direction +([`WindowManager::monitor_idx_in_direction`], from the bounds of the monitors), to its container +nearest the monitor the focus came from (the leftmost one going right); with no monitor there +either, the message fails and changes nothing. Whether the pointer follows the focus is [`WindowManager::mouse_follows_focus`], which `MouseFollowsFocus` and `ToggleMouseFollowsFocus` set. @@ -313,8 +316,13 @@ direction ([`WindowManager::move_container_in_direction`], [`WindowManager::move_container_in_cycle_direction`]), and tile the workspace again: the window that moved takes the other's tile, keeps the focus, and the pointer follows it. The swap goes through `LockableSequence`, so a lock stays with its index: the container swapped onto a locked -index is locked in its place. When there is no container in that direction, the message fails -and nothing moves. +index is locked in its place. When there is no container in that direction, the container goes +to the monitor in that direction ([`WindowManager::move_container_to_monitor`]), and +[`WindowManager::cross_monitor_move_behaviour`] says what it does there: by default (`Swap`) the +container at that edge of the other monitor comes back in its place, `Insert` puts it in among +the containers there, and `NoOp` keeps it where it is. With no monitor in that direction, the +message fails and nothing moves. [`WindowManager::cross_boundary_behaviour`] can make both cross +to the next workspace of the same monitor instead. `ChangeLayout` and `CycleLayout` set the focused workspace's [`Layout`], and `FlipLayout` mirrors it along an axis, on top of the flip it has ([`Workspace::layout_flip`]); each tiles @@ -438,6 +446,21 @@ gives a monitor workspaces up to a number, and `CloseWorkspace` removes the work when it has no window and no name and is not the monitor's last. A name is komorebi's: the compositor's desktops keep theirs. +A window the compositor reports shown or focused on a monitor that is not the focused one +focuses that monitor ([`WindowManager::monitor_idx_from_window`]). The monitor commands work on +the ring of monitors: `FocusMonitorNumber`, `CycleFocusMonitor` and `FocusMonitorAtCursor` focus +one ([`WindowManager::focus_monitor`]), and `FocusMonitorWorkspaceNumber` a workspace of it; +`MoveContainerToMonitorNumber`, `SendContainerToMonitorNumber`, their cycle and monitor-workspace +forms, and `MoveContainerToNamedWorkspace` and `SendContainerToNamedWorkspace` take the focused +container to another monitor, put its windows on the desktop of the workspace they go to, and tile +both monitors ([`WindowManager::move_container_to_monitor`]); `MoveWorkspaceToMonitorNumber` and +`CycleMoveWorkspaceToMonitor` take the workspace in front to another monitor, and +`SwapWorkspacesToMonitorNumber` exchanges the workspaces of two monitors. +`DisplayIndexPreference` gives a monitor, by its serial number id, the index the window manager +puts it at when it loads the monitors, with placeholders before it while the monitors in between +are not connected. `EagerFocus` focuses the first window of an executable, searching every +workspace of every monitor, and shows its workspace. + `PreselectDirection` reserves the index on one side of the focused container for the next window ([`WindowManager::preselect_container_in_direction`]). The workspace inserts an empty container there ([`Container::preselect`]), which [`Workspace::update`] keeps and the layout @@ -499,7 +522,8 @@ module's unit. promote the focused container, float a window, lock a container, set the padding of a workspace, manage and unmanage a window, show a workspace, move a container to another workspace, follow a workspace switch made by something else, name a workspace and find - it by its name, set the layout of a workspace that is not in front). + it by its name, set the layout of a workspace that is not in front, focus another monitor, + and move containers and workspaces between monitors). - [`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 @@ -602,6 +626,8 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | komorebi's own switch or move, reported back by KWin, changes nothing | framework path: the table records a switch and a move when it makes their commands | `the_compositor_reporting_komorebis_own_switch_changes_nothing`, `komorebis_own_move_coming_back_as_an_event_moves_nothing`, `komorebi_switching_a_monitor_comes_back_as_a_change_to_what_it_already_knows` | none | | The user's `kwinrc` gets back the value komorebi changed, also after a crash | framework path: [`Kwinrc`] records the first value of a key in a backup file, and the backend's `shutdown` puts it back | `what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed`, `a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run`, `vm-workspace-switch` ("back as they were") | `SIGKILL`: the next run puts it back when it stops | | A workspace is closed only when it has no window and no name and is not the monitor's last | framework path: the `CloseWorkspace` arm of [`WindowManager::process_command`] checks all three | `new_workspace_adds_one_and_close_workspace_removes_it_when_it_is_empty_and_unnamed` | none | +| The focus and a move at the edge of a monitor go to the monitor on that side, and fail only when there is none | framework path: the `None` arms of [`WindowManager::focus_container_in_direction`] and [`WindowManager::move_container_in_direction`] | `the_focus_crosses_to_the_monitor_on_that_side`, `a_move_at_the_edge_of_a_monitor_swaps_with_the_window_on_the_next_one_by_default`, `focus_towards_a_side_with_no_window_is_an_error_and_changes_nothing` | `NoOp` keeps a move on its monitor | +| A window shown or focused on another monitor focuses that monitor, and nothing else does | framework path: `handle_event` focuses the monitor of a `Show` or `FocusChange` before it acts on it | `a_window_that_opens_on_the_monitor_that_is_not_focused_focuses_it`, `a_scrolling_strip_on_the_next_monitor_over_does_not_take_focus_with_it` | none | | 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 | @@ -735,7 +761,9 @@ A window is shown, and ends up on a tile: - [`komorebi/tests/workspaces.rs`](../../komorebi/tests/workspaces.rs): workspaces as the fake's desktops; [`komorebi/tests/workspace_commands.rs`](../../komorebi/tests/workspace_commands.rs), naming, - cycling and the other workspace commands; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the + cycling and the other workspace commands; + [`komorebi/tests/monitors.rs`](../../komorebi/tests/monitors.rs), two monitors: crossing from + one to the other, the monitor commands and `EagerFocus`; [`komorebi/src/kwin/kwinrc.rs`](../../komorebi/src/kwin/kwinrc.rs), the `kwinrc` editor and its tests. - [`nix/tests/vm/suites/workspace-switch`](../../nix/tests/vm/suites/workspace-switch/test.py): workspaces as a real KWin's desktops, switched by `komorebic` and by KWin; @@ -832,6 +860,11 @@ A window is shown, and ends up on a tile: [`WindowManager::move_container_to_workspace`]: ../../komorebi/src/window_manager.rs [`WindowManager::monitor_workspace_index_by_name`]: ../../komorebi/src/window_manager.rs [`WindowManager::focus_monitor`]: ../../komorebi/src/window_manager.rs +[`WindowManager::monitor_idx_in_direction`]: ../../komorebi/src/window_manager.rs +[`WindowManager::monitor_idx_from_window`]: ../../komorebi/src/window_manager.rs +[`WindowManager::move_container_to_monitor`]: ../../komorebi/src/window_manager.rs +[`WindowManager::cross_monitor_move_behaviour`]: ../../komorebi/src/window_manager.rs +[`WindowManager::cross_boundary_behaviour`]: ../../komorebi/src/window_manager.rs [`Monitor::focus_workspace`]: ../../komorebi/src/monitor.rs [`bridge.js`]: ../../komorebi/src/kwin/bridge.js [`kwin-api.d.ts`]: ../../komorebi/src/kwin/kwin-api.d.ts diff --git a/docs/usage/focusing-windows.md b/docs/usage/focusing-windows.md index ee9ed845..c582636f 100644 --- a/docs/usage/focusing-windows.md +++ b/docs/usage/focusing-windows.md @@ -18,8 +18,21 @@ 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". +When there is no tile on that side, the focus goes to the monitor on that side, if there is one, +to the tile nearest the monitor the focus came from: `focus right` lands on the leftmost tile of +the monitor on the right. With no monitor there either, nothing happens, and the daemon logs +"there is no container or monitor in this direction". + +[`komorebic focus-monitor`](../cli/focus-monitor.md) focuses a monitor by its index, +[`komorebic cycle-monitor`](../cli/cycle-monitor.md) the next or the previous one, and +[`komorebic focus-monitor-at-cursor`](../cli/focus-monitor-at-cursor.md) the one the pointer is +on. [`komorebic eager-focus`](../cli/eager-focus.md) focuses the first window komorebi manages of +an executable, whichever workspace of whichever monitor it is on, and shows its workspace. + +```sh +komorebic focus-monitor 1 +komorebic eager-focus firefox +``` ## In order diff --git a/docs/usage/moving-windows.md b/docs/usage/moving-windows.md index 4a8ff2c1..62b4db47 100644 --- a/docs/usage/moving-windows.md +++ b/docs/usage/moving-windows.md @@ -18,8 +18,34 @@ komorebic move up komorebic move right ``` -When there is no tile on that side, nothing moves, and the daemon logs "there is no container -in this direction". +When there is no tile on that side, the window goes to the monitor on that side, if there is one, +and takes the place nearest the monitor it came from. What it does there is +[`komorebic cross-monitor-move-behaviour`](../cli/cross-monitor-move-behaviour.md): `swap`, the +default, sends the window it takes the place of back to where it came from; `insert` puts it in +among the windows there; `no-op` keeps it where it is. +[`komorebic toggle-cross-monitor-move-behaviour`](../cli/toggle-cross-monitor-move-behaviour.md) +switches between `insert` and `swap`. With no monitor on that side, nothing moves, and the daemon +logs "there is no container or monitor in this direction". + +## To another monitor + +[`komorebic move-to-monitor`](../cli/move-to-monitor.md) takes the focused window to a monitor, by +its index, and focuses it there; [`komorebic send-to-monitor`](../cli/send-to-monitor.md) does the +same and leaves the focus on the monitor it came from. Their `cycle-` forms take the next or the +previous monitor. [`komorebic move-to-monitor-workspace`](../cli/move-to-monitor-workspace.md) and +[`komorebic send-to-monitor-workspace`](../cli/send-to-monitor-workspace.md) name a workspace of +that monitor too, and [`komorebic move-to-named-workspace`](../cli/move-to-named-workspace.md) and +[`komorebic send-to-named-workspace`](../cli/send-to-named-workspace.md) find it by its name. + +```sh +komorebic move-to-monitor 1 +komorebic send-to-monitor-workspace 1 2 +``` + +[`komorebic move-workspace-to-monitor`](../cli/move-workspace-to-monitor.md) takes the whole +workspace in front to another monitor, and +[`komorebic swap-workspaces-with-monitor`](../cli/swap-workspaces-with-monitor.md) exchanges the +workspaces of the focused monitor with those of another. ## In order diff --git a/komorebi-client/src/lib.rs b/komorebi-client/src/lib.rs index 699ebbc3..a0c037b7 100644 --- a/komorebi-client/src/lib.rs +++ b/komorebi-client/src/lib.rs @@ -198,7 +198,7 @@ where /// # let daemon = std::thread::spawn(move || -> std::io::Result<()> { /// # let (mut stream, _) = listener.accept()?; /// # BufReader::new(stream.try_clone()?).read_line(&mut String::new())?; -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// # stream.write_all(state.as_bytes()) /// # }); /// use komorebi_client::SocketMessage; @@ -260,7 +260,7 @@ pub fn send_query(message: &SocketMessage) -> std::io::Result { /// # let mut message = String::new(); /// # BufReader::new(stream).read_line(&mut message)?; /// # let subscriber = komorebi_client::DATA_DIR.join("bar.sock"); -/// # let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; +/// # let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// # let notification = format!(r#"{{"event":{message},"state":{state}}}"#); /// # std::os::unix::net::UnixStream::connect(subscriber)?.write_all(notification.as_bytes())?; /// # Ok(message) diff --git a/komorebi/src/container.rs b/komorebi/src/container.rs index b7176388..e35450ee 100644 --- a/komorebi/src/container.rs +++ b/komorebi/src/container.rs @@ -62,6 +62,19 @@ impl Container { self.id == "PRESELECT" } + /// The index of the first window of the executable `exe` in this container + pub fn idx_from_exe(&self, exe: &str) -> Option { + for (idx, window) in self.windows().iter().enumerate() { + if let Some(window_exe) = window.exe() + && exe == window_exe + { + return Option::from(idx); + } + } + + None + } + pub fn contains_window(&self, window_id: u32) -> bool { for window in self.windows() { if window.id == window_id { diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index e8d78060..f33eae60 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -351,10 +351,21 @@ pub enum SocketMessage { ResizeWindowAxis(Axis, Sizing), MoveContainerToLastWorkspace, SendContainerToLastWorkspace, + MoveContainerToMonitorNumber(usize), + CycleMoveContainerToMonitor(CycleDirection), MoveContainerToWorkspaceNumber(usize), + MoveContainerToNamedWorkspace(String), CycleMoveContainerToWorkspace(CycleDirection), + SendContainerToMonitorNumber(usize), + CycleSendContainerToMonitor(CycleDirection), SendContainerToWorkspaceNumber(usize), CycleSendContainerToWorkspace(CycleDirection), + SendContainerToMonitorWorkspaceNumber(usize, usize), + MoveContainerToMonitorWorkspaceNumber(usize, usize), + SendContainerToNamedWorkspace(String), + CycleMoveWorkspaceToMonitor(CycleDirection), + MoveWorkspaceToMonitorNumber(usize), + SwapWorkspacesToMonitorNumber(usize), // ForceFocus, Close, Minimize, @@ -362,10 +373,13 @@ pub enum SocketMessage { PromoteSwap, PromoteFocus, PromoteWindow(OperationDirection), + EagerFocus(String), LockMonitorWorkspaceContainer(usize, usize, usize), UnlockMonitorWorkspaceContainer(usize, usize, usize), ToggleLock, ToggleFloat, + ToggleCrossMonitorMoveBehaviour, + CrossMonitorMoveBehaviour(MoveBehaviour), UnmanagedWindowOperationBehaviour(OperationBehaviour), // Current Workspace Commands ManageFocusedWindow, @@ -380,6 +394,7 @@ pub enum SocketMessage { FlipLayout(Axis), // Monitor and Workspace Commands // MonitorIndexPreference(usize, i32, i32, i32, i32), + DisplayIndexPreference(usize, String), EnsureWorkspaces(usize, usize), EnsureNamedWorkspaces(usize, Vec), NewWorkspace, @@ -392,12 +407,16 @@ pub enum SocketMessage { QuickLoad, Save(#[serde_as(as = "ResolvedPathBuf")] PathBuf), Load(#[serde_as(as = "ResolvedPathBuf")] PathBuf), + CycleFocusMonitor(CycleDirection), CycleFocusWorkspace(CycleDirection), CycleFocusEmptyWorkspace(CycleDirection), + FocusMonitorNumber(usize), + FocusMonitorAtCursor, FocusLastWorkspace, CloseWorkspace, FocusWorkspaceNumber(usize), FocusWorkspaceNumbers(usize), + FocusMonitorWorkspaceNumber(usize, usize), FocusNamedWorkspace(String), ContainerPadding(usize, usize, i32), FocusedWorkspaceContainerPadding(i32), diff --git a/komorebi/src/desktop.rs b/komorebi/src/desktop.rs index cf579a49..45725a4b 100644 --- a/komorebi/src/desktop.rs +++ b/komorebi/src/desktop.rs @@ -36,6 +36,7 @@ #![deny(missing_docs)] +use crate::DISPLAY_INDEX_PREFERENCES; use crate::backend::backend; use crate::container::Container; use crate::core::Rect; @@ -44,6 +45,7 @@ use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; use color_eyre::eyre; +use std::collections::HashMap; fn contains_point(area: &Rect, x: i32, y: i32) -> bool { x >= area.left && x < area.left + area.right && y >= area.top && y < area.top + area.bottom @@ -86,11 +88,14 @@ pub fn latest_monitor_information() -> eyre::Result> { .collect()) } -/// Adds the monitors the window manager does not have yet, after the ones it has, in the -/// backend's order. +/// Adds the monitors the window manager does not have yet, and rebuilds the map from the indices +/// the user gives monitors to the window manager's ([`WindowManager::monitor_usr_idx_map`]). /// -/// A monitor is known when the window manager has one with the same serial number id, so -/// loading twice adds nothing the second time, and a known monitor keeps its workspaces. +/// A monitor the user gave an index to (`DisplayIndexPreference`) is put at that index, with +/// placeholders before it while the monitors in between are not there; any other new monitor goes +/// after the ones the window manager has, in the backend's order. A monitor is known when the +/// window manager has one with the same serial number id, so loading twice adds nothing the +/// second time, and a known monitor keeps its workspaces. /// /// # Errors /// @@ -127,6 +132,7 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { let all_devices = latest_monitor_information()?; let monitors = &mut wm.monitors; + let monitor_usr_idx_map = &mut wm.monitor_usr_idx_map; 'read: for device in all_devices { for monitor in monitors.elements() { @@ -135,7 +141,74 @@ pub fn load_monitor_information(wm: &mut WindowManager) -> eyre::Result<()> { } } - monitors.elements_mut().push_back(device); + let m = device.clone(); + + let mut index_preference = None; + let display_index_preferences = DISPLAY_INDEX_PREFERENCES.read(); + for (index, id) in &*display_index_preferences { + if m.serial_number_id.eq(id) { + index_preference = Option::from(index); + } + } + + if let Some(preference) = index_preference { + while *preference >= monitors.elements().len() { + monitors.elements_mut().push_back(Monitor::placeholder()); + } + + let current_serial_id = monitors + .elements_mut() + .get(*preference) + .map_or("", |m| &m.serial_number_id); + if current_serial_id == "PLACEHOLDER" { + let _ = monitors.elements_mut().remove(*preference); + monitors.elements_mut().insert(*preference, m); + } else { + monitors.elements_mut().insert(*preference, m); + } + } else { + monitors.elements_mut().push_back(m); + } + } + + monitors + .elements_mut() + .retain(|m| m.serial_number_id.ne("PLACEHOLDER")); + + // Rebuild monitor index map + *monitor_usr_idx_map = HashMap::new(); + let mut added_monitor_idxs = Vec::new(); + for (index, id) in &*DISPLAY_INDEX_PREFERENCES.read() { + if let Some(m_idx) = monitors + .elements() + .iter() + .position(|m| m.serial_number_id.eq(id)) + { + monitor_usr_idx_map.insert(*index, m_idx); + added_monitor_idxs.push(m_idx); + } + } + + let max_usr_idx = monitors + .elements() + .len() + .max(monitor_usr_idx_map.keys().max().map_or(0, |v| *v)); + + let mut available_usr_idxs = (0..max_usr_idx) + .filter(|i| !monitor_usr_idx_map.contains_key(i)) + .collect::>(); + + let not_added_monitor_idxs = (0..monitors.elements().len()) + .filter(|i| !added_monitor_idxs.contains(i)) + .collect::>(); + + for i in not_added_monitor_idxs { + if let Some(next_usr_idx) = available_usr_idxs.first() { + monitor_usr_idx_map.insert(*next_usr_idx, i); + available_usr_idxs.remove(0); + } else if let Some(idx) = monitor_usr_idx_map.keys().max() { + monitor_usr_idx_map.insert(*idx, i); + } } Ok(()) diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 3f0e3882..6b55a09b 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -34,6 +34,7 @@ use crate::window_manager_event::WindowManagerEvent; use color_eyre::eyre; use lazy_static::lazy_static; use parking_lot::Mutex; +use parking_lot::RwLock; use regex::Regex; use serde::Deserialize; use serde::Serialize; @@ -100,6 +101,10 @@ lazy_static! { static ref FLOATING_WINDOW_TOGGLE_ASPECT_RATIO: Arc> = Arc::new(Mutex::new( AspectRatio::Predefined(PredefinedAspectRatio::Widescreen) )); + /// The index the user gives each monitor, by its serial number id + /// ([`SocketMessage::DisplayIndexPreference`]): the window manager orders its monitors by it + static ref DISPLAY_INDEX_PREFERENCES: Arc>> = + Arc::new(RwLock::new(HashMap::new())); /// The compiled regular expression of each rule whose matching strategy is `Regex`, by the /// rule's id static ref REGEX_IDENTIFIERS: Arc>> = @@ -165,7 +170,7 @@ pub enum NotificationEvent { /// use komorebi::core::SocketMessage; /// use komorebi::window_manager_event::WindowManagerEvent; /// -/// let state = r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; +/// let state = r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#; /// /// let shown = format!( /// r#"{{"event":{{"type":"Show","content":[{{"type":"KWin","content":"WindowAdded"}},{{"id":7}}]}},"state":{state}}}"# @@ -240,7 +245,7 @@ pub struct Notification { /// ]); /// /// let state: State = serde_json::from_str( -/// r#"{"monitors":{"elements":[],"focused":0},"is_paused":false,"resize_delta":50,"unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#, +/// r#"{"monitors":{"elements":[],"focused":0},"monitor_usr_idx_map":{},"is_paused":false,"resize_delta":50,"cross_monitor_move_behaviour":"Swap","unmanaged_window_operation_behaviour":"Op","work_area_offset":null,"mouse_follows_focus":true}"#, /// )?; /// let event = NotificationEvent::Socket(SocketMessage::Retile); /// notify_subscribers(Notification { event, state }, false)?; diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index ea14c389..5573429e 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -128,6 +128,26 @@ impl Monitor { } } + /// A stand-in for a monitor the user gave an index to (`DisplayIndexPreference`) that is not + /// connected, so that the monitors after it keep their indices while it is not there + pub fn placeholder() -> Self { + Self { + // temp + id: 2051316, + device: "".to_string(), + serial_number_id: "PLACEHOLDER".to_string(), + size: Default::default(), + work_area_size: Default::default(), + work_area_offset: None, + window_based_work_area_offset: None, + window_based_work_area_offset_limit: 0, + workspaces: Default::default(), + last_focused_workspace: None, + container_padding: None, + workspace_padding: None, + } + } + /// Tiles the focused workspace in this monitor's work area, less `offset` if the monitor has /// no offset of its own #[tracing::instrument(skip_all)] @@ -390,6 +410,30 @@ impl Monitor { Ok(()) } + pub fn update_workspaces_globals(&mut self, offset: Option) { + let container_padding = self + .container_padding + .or(Some(DEFAULT_CONTAINER_PADDING.load(Ordering::SeqCst))); + let workspace_padding = self + .workspace_padding + .or(Some(DEFAULT_WORKSPACE_PADDING.load(Ordering::SeqCst))); + let work_area = self.work_area_size; + let work_area_offset = self.work_area_offset.or(offset); + let window_based_work_area_offset = self.window_based_work_area_offset; + let window_based_work_area_offset_limit = self.window_based_work_area_offset_limit; + + for workspace in self.workspaces_mut() { + workspace.globals = WorkspaceGlobals { + container_padding, + workspace_padding, + work_area, + work_area_offset, + window_based_work_area_offset, + window_based_work_area_offset_limit, + } + } + } + pub fn remove_workspace_by_idx(&mut self, idx: usize) -> Option { if idx < self.workspaces().len() { return self.workspaces_mut().remove(idx); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 88a4bb49..08b3624a 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -18,11 +18,14 @@ //! 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 +//! focused one (or of the monitor on that side, at the edge of a monitor), or to the next or the +//! previous one in the workspace //! ([`WindowManager::focus_container_in_direction`], //! [`WindowManager::focus_container_in_cycle_direction`]). //! - **MoveWindow** and **CycleMoveWindow** swap the focused container with the one on one side -//! of it, or with the next or the previous one, and tile the workspace again +//! of it (or take it to the monitor on that side, at the edge of a monitor, as +//! **CrossMonitorMoveBehaviour** and **ToggleCrossMonitorMoveBehaviour** set), or with the next or +//! the previous one, and tile the workspace again //! ([`WindowManager::move_container_in_direction`], //! [`WindowManager::move_container_in_cycle_direction`]). //! - **Promote** moves the focused container to the largest tile, **PromoteSwap** swaps it with @@ -100,6 +103,15 @@ //! **WorkspaceTiling** do by index. **EnsureWorkspaces** gives a monitor workspaces up to a //! number, **NewWorkspace** adds one and shows it, and **CloseWorkspace** removes the workspace //! in front when it has no window and no name and is not the monitor's last. +//! - **FocusMonitorNumber**, **CycleFocusMonitor** and **FocusMonitorAtCursor** focus another +//! monitor ([`WindowManager::focus_monitor`]), and **FocusMonitorWorkspaceNumber** a workspace +//! of it. **MoveContainerToMonitorNumber**, **SendContainerToMonitorNumber**, their cycle and +//! monitor-workspace forms, **MoveContainerToNamedWorkspace** and +//! **SendContainerToNamedWorkspace** take the focused container to another monitor +//! ([`WindowManager::move_container_to_monitor`]); **MoveWorkspaceToMonitorNumber**, +//! **CycleMoveWorkspaceToMonitor** and **SwapWorkspacesToMonitorNumber** move workspaces +//! between monitors. **DisplayIndexPreference** gives a monitor an index, and **EagerFocus** +//! focuses the first window of an executable on any workspace of any monitor. //! - **Retile** tiles the focused workspace of every monitor again, without the resize //! adjustments, and **RetileWithResizeDimensions** with them. //! - **AddSubscriberSocket** and **AddSubscriberSocketWithOptions** add a subscriber by the name @@ -110,6 +122,7 @@ //! ([`notify_subscribers`]). use crate::DATA_DIR; +use crate::DISPLAY_INDEX_PREFERENCES; use crate::FLOATING_APPLICATIONS; use crate::IGNORE_IDENTIFIERS; use crate::MANAGE_IDENTIFIERS; @@ -123,6 +136,7 @@ use crate::core::ApplicationIdentifier; use crate::core::Axis; use crate::core::Layout; use crate::core::LayoutOptions; +use crate::core::MoveBehaviour; use crate::core::OperationDirection; use crate::core::Rect; use crate::core::ScrollingLayoutOptions; @@ -138,6 +152,7 @@ use crate::state::State; use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; +use crate::workspace::WorkspaceWindowLocation; use color_eyre::eyre; use color_eyre::eyre::Context; use color_eyre::eyre::OptionExt; @@ -222,6 +237,8 @@ impl WindowManager { /// `UnlockMonitorWorkspaceContainer` is not there (a container that is not there is ignored). /// - The focused window cannot be floated or put back, for one of the reasons /// [`WindowManager::toggle_float`] gives. + /// - The monitor a monitor command names is not there, or the compositor reports no window + /// with the focus to take to it ([`WindowManager::move_container_to_monitor`]). /// - The monitor or the workspace a message names by its index is not there /// (`WorkspaceName`, `WorkspaceLayout`, `WorkspaceTiling`, `EnsureWorkspaces`, /// `EnsureNamedWorkspaces`). A name no workspace has is ignored. @@ -265,6 +282,71 @@ impl WindowManager { self.focus_container_in_direction(direction)?; self.promote_container_to_front()? } + SocketMessage::EagerFocus(ref exe) => { + let focused_monitor_idx = self.focused_monitor_idx(); + let mouse_follows_focus = self.mouse_follows_focus; + + let mut window_location = None; + let mut monitor_to_focus = None; + let mut needs_workspace_loading = false; + + 'search: for (monitor_idx, monitor) in self.monitors_mut().iter_mut().enumerate() { + for (workspace_idx, workspace) in monitor.workspaces().iter().enumerate() { + if let Some(location) = workspace.location_from_exe(exe) { + window_location = Some(location); + + if monitor_idx != focused_monitor_idx { + monitor_to_focus = Some(monitor_idx); + } + + // Focus workspace if it is not already the focused one, without + // loading it so that we don't give focus to the wrong window, we will + // load it later after focusing the wanted window + let focused_ws_idx = monitor.focused_workspace_idx(); + if focused_ws_idx != workspace_idx { + monitor.last_focused_workspace = Option::from(focused_ws_idx); + monitor.focus_workspace(workspace_idx)?; + needs_workspace_loading = true; + } + + break 'search; + } + } + } + + if let Some(monitor_idx) = monitor_to_focus { + self.focus_monitor(monitor_idx)?; + } + + if let Some(location) = window_location { + match location { + WorkspaceWindowLocation::Container(container_idx, window_idx) => { + let focused_container_idx = self.focused_container_idx()?; + if container_idx != focused_container_idx { + self.focused_workspace_mut()?.focus_container(container_idx); + } + + self.focus_container_window(window_idx)?; + } + WorkspaceWindowLocation::Floating(window_idx) => { + if let Some(window) = self + .focused_workspace_mut()? + .floating_windows_mut() + .get_mut(window_idx) + { + window.focus(mouse_follows_focus)?; + } + } + } + + if needs_workspace_loading { + let mouse_follows_focus = self.mouse_follows_focus; + if let Some(monitor) = self.focused_monitor_mut() { + monitor.load_focused_workspace(mouse_follows_focus)?; + } + } + } + } SocketMessage::FocusWindow(direction) => { self.focus_container_in_direction(direction)?; } @@ -299,7 +381,29 @@ impl WindowManager { SocketMessage::CycleMoveWindow(direction) => { self.move_container_in_cycle_direction(direction)?; } + SocketMessage::CycleFocusMonitor(direction) => { + let monitor_idx = direction.next_idx( + self.focused_monitor_idx(), + NonZeroUsize::new(self.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + self.focus_monitor(monitor_idx)?; + self.update_focused_workspace(self.mouse_follows_focus, true)?; + } SocketMessage::CycleFocusWorkspace(direction) => { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; let focused_workspace_idx = focused_monitor.focused_workspace_idx(); @@ -345,6 +449,15 @@ impl WindowManager { self.focus_workspace(workspace_idx)?; } } + SocketMessage::FocusMonitorNumber(monitor_idx) => { + self.focus_monitor(monitor_idx)?; + self.update_focused_workspace(self.mouse_follows_focus, true)?; + } + SocketMessage::FocusMonitorAtCursor => { + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() { + self.focus_monitor(monitor_idx)?; + } + } SocketMessage::FocusLastWorkspace => { let idx = self .focused_monitor() @@ -378,6 +491,17 @@ impl WindowManager { self.focus_workspace(workspace_idx)?; } + SocketMessage::FocusMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { + let focused_monitor_idx = self.focused_monitor_idx(); + let focused_workspace_idx = self.focused_workspace_idx().unwrap_or_default(); + + let focused_pair = (focused_monitor_idx, focused_workspace_idx); + + if focused_pair != (monitor_idx, workspace_idx) { + self.focus_monitor(monitor_idx)?; + self.focus_workspace(workspace_idx)?; + } + } SocketMessage::FocusNamedWorkspace(ref name) => { if let Some((monitor_idx, workspace_idx)) = self.monitor_workspace_index_by_name(name) @@ -420,6 +544,18 @@ impl WindowManager { self.move_container_to_workspace(workspace_idx, false, None)?; } SocketMessage::MoveContainerToLastWorkspace => { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + let idx = self .focused_monitor() .ok_or_eyre("there is no monitor")? @@ -436,6 +572,18 @@ impl WindowManager { .last_focused_workspace = Option::from(idx); } SocketMessage::SendContainerToLastWorkspace => { + // This is to ensure that even on an empty workspace on a secondary monitor, the + // secondary monitor where the cursor is focused will be used as the target for + // the workspace switch op + if let Some(monitor_idx) = self.monitor_idx_from_current_pos() + && monitor_idx != self.focused_monitor_idx() + && let Some(monitor) = self.monitors().get(monitor_idx) + && let Some(workspace) = monitor.focused_workspace() + && workspace.is_empty() + { + self.focus_monitor(monitor_idx)?; + } + let idx = self .focused_monitor() .ok_or_eyre("there is no monitor")? @@ -464,6 +612,23 @@ impl WindowManager { self.move_container_to_workspace(workspace_idx, true, None)?; } + SocketMessage::MoveContainerToMonitorNumber(monitor_idx) => { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor(monitor_idx, None, true, direction)?; + } + SocketMessage::SwapWorkspacesToMonitorNumber(monitor_idx) => { + self.swap_focused_monitor(monitor_idx)?; + } + SocketMessage::CycleMoveContainerToMonitor(direction) => { + let monitor_idx = direction.next_idx( + self.focused_monitor_idx(), + NonZeroUsize::new(self.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor(monitor_idx, None, true, direction)?; + } SocketMessage::CycleSendContainerToWorkspace(direction) => { let focused_monitor = self.focused_monitor().ok_or_eyre("there is no monitor")?; @@ -478,6 +643,95 @@ impl WindowManager { self.move_container_to_workspace(workspace_idx, false, None)?; } + SocketMessage::SendContainerToMonitorNumber(monitor_idx) => { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor(monitor_idx, None, false, direction)?; + } + SocketMessage::CycleSendContainerToMonitor(direction) => { + let monitor_idx = direction.next_idx( + self.focused_monitor_idx(), + NonZeroUsize::new(self.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor(monitor_idx, None, false, direction)?; + } + SocketMessage::SendContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor( + monitor_idx, + Option::from(workspace_idx), + false, + direction, + )?; + } + SocketMessage::MoveContainerToMonitorWorkspaceNumber(monitor_idx, workspace_idx) => { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor( + monitor_idx, + Option::from(workspace_idx), + true, + direction, + )?; + } + SocketMessage::SendContainerToNamedWorkspace(ref workspace) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor( + monitor_idx, + Option::from(workspace_idx), + false, + direction, + )?; + } + } + SocketMessage::MoveContainerToNamedWorkspace(ref workspace) => { + if let Some((monitor_idx, workspace_idx)) = + self.monitor_workspace_index_by_name(workspace) + { + let direction = self.direction_from_monitor_idx(monitor_idx); + self.move_container_to_monitor( + monitor_idx, + Option::from(workspace_idx), + true, + direction, + )?; + } + } + + SocketMessage::MoveWorkspaceToMonitorNumber(monitor_idx) => { + self.move_workspace_to_monitor(monitor_idx)?; + } + SocketMessage::CycleMoveWorkspaceToMonitor(direction) => { + let monitor_idx = direction.next_idx( + self.focused_monitor_idx(), + NonZeroUsize::new(self.monitors().len()) + .ok_or_eyre("there must be at least one monitor")?, + ); + + self.move_workspace_to_monitor(monitor_idx)?; + } + SocketMessage::ToggleCrossMonitorMoveBehaviour => { + match self.cross_monitor_move_behaviour { + MoveBehaviour::Swap => { + self.cross_monitor_move_behaviour = MoveBehaviour::Insert; + } + MoveBehaviour::Insert => { + self.cross_monitor_move_behaviour = MoveBehaviour::Swap; + } + _ => {} + } + } + SocketMessage::CrossMonitorMoveBehaviour(behaviour) => { + self.cross_monitor_move_behaviour = behaviour; + } + SocketMessage::DisplayIndexPreference(index_preference, ref display) => { + let mut display_index_preferences = DISPLAY_INDEX_PREFERENCES.write(); + display_index_preferences.insert(index_preference, display.clone()); + } SocketMessage::NewWorkspace => { self.new_workspace()?; } diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index ca4e4385..794c6acf 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -159,6 +159,16 @@ impl WindowManager { // We don't have From implemented for &mut WindowManager let initial_state = State::from(self.as_ref()); + // a window can open on a monitor other than the focused one, and focus can follow + if matches!( + event, + WindowManagerEvent::FocusChange(_, _) | WindowManagerEvent::Show(_, _) + ) && let Some(monitor_idx) = self.monitor_idx_from_window(window) + && self.focused_monitor_idx() != monitor_idx + { + self.focus_monitor(monitor_idx)?; + } + match event { WindowManagerEvent::FocusChange(_, _) => { let is_known = self.known_window_ids.get(&window_id).cloned(); diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 8f3ea9ad..8161d000 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -14,6 +14,7 @@ use crate::DATA_DIR; use crate::IGNORE_IDENTIFIERS; use crate::MANAGE_IDENTIFIERS; +use crate::core::MoveBehaviour; use crate::core::OperationBehaviour; use crate::core::Rect; use crate::core::config_generation::MatchingRule; @@ -23,6 +24,7 @@ use crate::window_manager::WindowManager; use crate::workspace::Workspace; use serde::Deserialize; use serde::Serialize; +use std::collections::HashMap; use std::collections::VecDeque; use std::path::PathBuf; @@ -119,8 +121,10 @@ impl Default for GlobalState { #[derive(Clone, Debug, Serialize, Deserialize)] pub struct State { pub monitors: Ring, + pub monitor_usr_idx_map: HashMap, pub is_paused: bool, pub resize_delta: i32, + pub cross_monitor_move_behaviour: MoveBehaviour, pub unmanaged_window_operation_behaviour: OperationBehaviour, pub work_area_offset: Option, pub mouse_follows_focus: bool, @@ -181,9 +185,11 @@ impl From<&WindowManager> for State { Self { monitors: stripped_monitors, + monitor_usr_idx_map: wm.monitor_usr_idx_map.clone(), is_paused: wm.is_paused, work_area_offset: wm.work_area_offset, resize_delta: wm.resize_delta, + cross_monitor_move_behaviour: wm.cross_monitor_move_behaviour, mouse_follows_focus: wm.mouse_follows_focus, unmanaged_window_operation_behaviour: wm.unmanaged_window_operation_behaviour, } @@ -208,6 +214,10 @@ impl State { return true; } + if self.cross_monitor_move_behaviour != new.cross_monitor_move_behaviour { + return true; + } + if self.unmanaged_window_operation_behaviour != new.unmanaged_window_operation_behaviour { return true; } diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 909167f6..c230cb70 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -240,6 +240,34 @@ impl Window { }) } + /// Moves the window from one work area to another, keeping where it is in the area and how + /// much of it it takes, in proportion: a floating window that goes to another monitor + pub fn move_to_area(&self, current_area: &Rect, target_area: &Rect) -> eyre::Result<()> { + let current_rect = self.rect()?; + let x_diff = target_area.left - current_area.left; + let y_diff = target_area.top - current_area.top; + let x_ratio = f32::abs((target_area.right as f32) / (current_area.right as f32)); + let y_ratio = f32::abs((target_area.bottom as f32) / (current_area.bottom as f32)); + let window_relative_x = current_rect.left - current_area.left; + let window_relative_y = current_rect.top - current_area.top; + let corrected_relative_x = (window_relative_x as f32 * x_ratio) as i32; + let corrected_relative_y = (window_relative_y as f32 * y_ratio) as i32; + let window_x = current_area.left + corrected_relative_x; + let window_y = current_area.top + corrected_relative_y; + let left = x_diff + window_x; + let top = y_diff + window_y; + + let corrected_width = (current_rect.right as f32 * x_ratio) as i32; + let corrected_height = (current_rect.bottom as f32 * y_ratio) as i32; + + self.set_position(&Rect { + left, + top, + right: corrected_width, + bottom: corrected_height, + }) + } + /// Whether the window is one komorebi should tile: a window that is still alive, that the /// compositor considers a normal application window, as opposed to a dialog, a splash screen, /// a utility window or a dock ([`WindowInfo::normal`](crate::backend::WindowInfo::normal)), diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index d39b54c8..f91bcb28 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -22,6 +22,11 @@ //! ([`WindowManager::set_workspace_name`]) and found by its name on any monitor //! ([`WindowManager::monitor_workspace_index_by_name`]). //! +//! With more than one monitor, the focus and a move at the edge of a monitor cross to the monitor +//! in that direction ([`WindowManager::monitor_idx_in_direction`]), and a container or a workspace +//! can be taken to another monitor ([`WindowManager::move_container_to_monitor`], +//! [`WindowManager::move_workspace_to_monitor`]). +//! //! [`listen_for_commands`]: crate::process_command::listen_for_commands use crate::DATA_DIR; @@ -32,9 +37,11 @@ use crate::backend::backend; use crate::container::Container; use crate::core::Arrangement; use crate::core::Axis; +use crate::core::CrossBoundaryBehaviour; use crate::core::CycleDirection; use crate::core::DefaultLayout; use crate::core::Layout; +use crate::core::MoveBehaviour; use crate::core::OperationBehaviour; use crate::core::OperationDirection; use crate::core::Rect; @@ -66,6 +73,9 @@ const MINIMUM_TILE_FRACTION: i32 = 10; #[derive(Debug)] pub struct WindowManager { pub monitors: Ring, + /// The monitor index a user's index stands for, when the indices the user gives monitors + /// (`DisplayIndexPreference`) are not the order the compositor reports them in + pub monitor_usr_idx_map: HashMap, /// The socket the daemon takes messages on, `komorebi.sock` in [`struct@DATA_DIR`] unless /// [`WindowManager::new`] was given another path pub command_listener: UnixListener, @@ -79,6 +89,13 @@ pub struct WindowManager { pub unmanaged_window_operation_behaviour: OperationBehaviour, /// How new and floated windows are placed: `ToggleFloat` reads its `toggle_float_placement` pub window_management_behaviour: WindowManagementBehaviour, + /// What a move towards a side with no container does: swap the container with the one at the + /// edge of the monitor on that side (`Swap`, the default), put it in among the containers there + /// (`Insert`), or nothing (`NoOp`) + pub cross_monitor_move_behaviour: MoveBehaviour, + /// Where a focus or a move towards a side with no container goes: the monitor on that side + /// (`Monitor`, the default), or the next workspace of the same monitor (`Workspace`) + pub cross_boundary_behaviour: CrossBoundaryBehaviour, /// 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, @@ -130,11 +147,14 @@ impl WindowManager { Ok(Self { monitors: Ring::default(), + monitor_usr_idx_map: HashMap::new(), command_listener: listener, is_paused: false, resize_delta: 50, unmanaged_window_operation_behaviour: Default::default(), window_management_behaviour: WindowManagementBehaviour::default(), + cross_monitor_move_behaviour: Default::default(), + cross_boundary_behaviour: Default::default(), mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -213,30 +233,114 @@ impl WindowManager { /// 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 + /// set. Where there is no such container, the focus crosses to the monitor on that side. /// /// 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. + /// - There is no focused workspace, or neither a container nor a monitor on that side of the + /// focused one. + /// - [`WindowManager::handle_unmanaged_window_behaviour`] refuses the message. /// - The backend refuses to focus the window. #[tracing::instrument(skip(self))] pub fn focus_container_in_direction( &mut self, direction: OperationDirection, ) -> eyre::Result<()> { + self.handle_unmanaged_window_behaviour()?; let mouse_follows_focus = self.mouse_follows_focus; let workspace = self.focused_workspace()?; + let workspace_idx = self.focused_workspace_idx()?; tracing::info!("focusing container"); let new_idx = workspace.new_idx_for_direction(direction); + // this is for when we are scrolling across workspaces like PaperWM + if new_idx.is_none() + && matches!( + self.cross_boundary_behaviour, + CrossBoundaryBehaviour::Workspace + ) + && matches!( + direction, + OperationDirection::Left | OperationDirection::Right + ) + { + let workspace_count = if let Some(monitor) = self.focused_monitor() { + monitor.workspaces().len() + } else { + 1 + }; + + let next_idx = match direction { + OperationDirection::Left => match workspace_idx { + 0 => workspace_count - 1, + n => n - 1, + }, + OperationDirection::Right => match workspace_idx { + n if n == workspace_count - 1 => 0, + n => n + 1, + }, + _ => workspace_idx, + }; + + self.focus_workspace(next_idx)?; + + if let Ok(focused_workspace) = self.focused_workspace_mut() { + match direction { + OperationDirection::Left => match focused_workspace.layout { + Layout::Default(layout) => { + let target_index = + layout.rightmost_index(focused_workspace.containers().len()); + focused_workspace.focus_container(target_index); + } + }, + OperationDirection::Right => match focused_workspace.layout { + Layout::Default(layout) => { + let target_index = + layout.leftmost_index(focused_workspace.containers().len()); + focused_workspace.focus_container(target_index); + } + }, + _ => {} + }; + } + + return Ok(()); + } + // if there is no container in that direction for this workspace match new_idx { - None => bail!("there is no container in this direction"), + None => { + let monitor_idx = self + .monitor_idx_in_direction(direction) + .ok_or_eyre("there is no container or monitor in this direction")?; + + self.focus_monitor(monitor_idx)?; + + if let Ok(focused_workspace) = self.focused_workspace_mut() { + match direction { + OperationDirection::Left => match focused_workspace.layout { + Layout::Default(layout) => { + let target_index = + layout.rightmost_index(focused_workspace.containers().len()); + focused_workspace.focus_container(target_index); + } + }, + OperationDirection::Right => match focused_workspace.layout { + Layout::Default(layout) => { + let target_index = + layout.leftmost_index(focused_workspace.containers().len()); + focused_workspace.focus_container(target_index); + } + }, + _ => {} + }; + } + } Some(idx) => { let workspace = self.focused_workspace_mut()?; workspace.focus_container(idx); @@ -259,26 +363,149 @@ impl WindowManager { /// The container keeps the focus, and the pointer follows it if /// [`WindowManager::mouse_follows_focus`] is set. A lock stays with its index: a container /// that is swapped onto the index of a locked one is locked in its place - /// ([`Workspace::swap_containers`]). + /// ([`Workspace::swap_containers`]). Where there is no container on that side, the container + /// goes to the monitor there as [`WindowManager::cross_monitor_move_behaviour`] says: swapped + /// with a container of that monitor, put in among them, or left where it is. /// /// # Errors /// - /// - There is no focused workspace, or no container on that side of the focused one. + /// - There is no focused workspace, or neither a container nor a monitor on that side of the + /// focused one. + /// - [`WindowManager::handle_unmanaged_window_behaviour`] refuses the message. /// - The workspace cannot be tiled, or the backend refuses to focus the window. #[tracing::instrument(skip(self))] pub fn move_container_in_direction( &mut self, direction: OperationDirection, ) -> eyre::Result<()> { + self.handle_unmanaged_window_behaviour()?; + let workspace = self.focused_workspace()?; + let workspace_idx = self.focused_workspace_idx()?; tracing::info!("moving container"); let origin_container_idx = workspace.focused_container_idx(); + let origin_monitor_idx = self.focused_monitor_idx(); let target_container_idx = workspace.new_idx_for_direction(direction); + // this is for when we are scrolling across workspaces like PaperWM + if target_container_idx.is_none() + && matches!( + self.cross_boundary_behaviour, + CrossBoundaryBehaviour::Workspace + ) + && matches!( + direction, + OperationDirection::Left | OperationDirection::Right + ) + { + let workspace_count = if let Some(monitor) = self.focused_monitor() { + monitor.workspaces().len() + } else { + 1 + }; + + let next_idx = match direction { + OperationDirection::Left => match workspace_idx { + 0 => workspace_count - 1, + n => n - 1, + }, + OperationDirection::Right => match workspace_idx { + n if n == workspace_count - 1 => 0, + n => n + 1, + }, + _ => workspace_idx, + }; + + // passing the direction here is how we handle whether to insert at the front + // or the back of the container vecdeque in the target workspace + self.move_container_to_workspace(next_idx, true, Some(direction))?; + self.update_focused_workspace(self.mouse_follows_focus, true)?; + + return Ok(()); + } + match target_container_idx { - None => bail!("there is no container in this direction"), + // If there is nowhere to move on the current workspace, try to move it onto the monitor + // in that direction if there is one + None => { + // Don't do anything if the user has set the MoveBehaviour to NoOp + if matches!(self.cross_monitor_move_behaviour, MoveBehaviour::NoOp) { + return Ok(()); + } + + let target_monitor_idx = self + .monitor_idx_in_direction(direction) + .ok_or_eyre("there is no container or monitor in this direction")?; + + { + // actually move the container to target monitor using the direction + self.move_container_to_monitor( + target_monitor_idx, + None, + true, + Some(direction), + )?; + + // focus the target monitor + self.focus_monitor(target_monitor_idx)?; + + // get a mutable ref to the focused workspace on the target monitor + let target_workspace = self.focused_workspace_mut()?; + + // if there is only one container on the target workspace after the insertion + // it means that there won't be one swapped back, so we have to decrement the + // focused position + if target_workspace.containers().len() == 1 { + let origin_workspace = + self.focused_workspace_for_monitor_idx_mut(origin_monitor_idx)?; + + origin_workspace.focus_container( + origin_workspace.focused_container_idx().saturating_sub(1), + ); + } + } + + // if our MoveBehaviour is Swap, let's try to send back the window container + // whose position which just took over + if matches!(self.cross_monitor_move_behaviour, MoveBehaviour::Swap) { + { + let target_workspace = self.focused_workspace_mut()?; + + // if the target workspace doesn't have more than one container, this means it + // was previously empty, by only doing the second part of the swap when there is + // more than one container, we can fall back to a "move" if there is nothing to + // swap with on the target monitor + if target_workspace.containers().len() > 1 { + // remove the container from the target monitor workspace + let target_container = target_workspace + // this is now focused_container_idx + 1 because we have inserted our origin container + .remove_container_by_idx( + target_workspace.focused_container_idx() + 1, + ) + .ok_or_eyre("could not remove container at given target index")?; + + let origin_workspace = + self.focused_workspace_for_monitor_idx_mut(origin_monitor_idx)?; + + // insert the container from the target monitor workspace into the origin monitor workspace + // at the same position from which our origin container was removed + origin_workspace + .insert_container_at_idx(origin_container_idx, target_container); + } + } + } + + // make sure to update the origin monitor workspace layout because it is no + // longer focused so it won't get updated at the end of this fn + let offset = self.work_area_offset; + + self.monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .update_focused_workspace(offset)?; + } Some(new_idx) => { let workspace = self.focused_workspace_mut()?; workspace.swap_containers(origin_container_idx, new_idx); @@ -384,6 +611,25 @@ impl WindowManager { .ok_or_eyre("there is no workspace") } + pub fn focused_workspace_for_monitor_idx(&self, idx: usize) -> eyre::Result<&Workspace> { + self.monitors() + .get(idx) + .ok_or_eyre("there is no monitor at this index")? + .focused_workspace() + .ok_or_eyre("there is no workspace") + } + + pub fn focused_workspace_for_monitor_idx_mut( + &mut self, + idx: usize, + ) -> eyre::Result<&mut Workspace> { + self.monitors_mut() + .get_mut(idx) + .ok_or_eyre("there is no monitor at this index")? + .focused_workspace_mut() + .ok_or_eyre("there is no workspace") + } + #[tracing::instrument(skip(self))] pub fn new_workspace(&mut self) -> eyre::Result<()> { tracing::info!("adding new workspace"); @@ -427,6 +673,13 @@ impl WindowManager { .ok_or_eyre("there is no window") } + pub fn focused_monitor_size(&self) -> eyre::Result { + Ok(self + .focused_monitor() + .ok_or_eyre("there is no monitor")? + .size) + } + pub fn focused_monitor_work_area(&self) -> eyre::Result { Ok(self .focused_monitor() @@ -1022,6 +1275,82 @@ impl WindowManager { Ok(()) } + // TODO: see if this logic is the same in macos when I have more than one monitor + pub fn monitor_idx_in_direction(&self, direction: OperationDirection) -> Option { + let current_monitor_size = self.focused_monitor_size().ok()?; + + for (idx, monitor) in self.monitors.elements().iter().enumerate() { + match direction { + OperationDirection::Left => { + if monitor.size.left + monitor.size.right == current_monitor_size.left { + return Option::from(idx); + } + } + OperationDirection::Right => { + if current_monitor_size.right + current_monitor_size.left == monitor.size.left { + return Option::from(idx); + } + } + OperationDirection::Up => { + if monitor.size.top + monitor.size.bottom == current_monitor_size.top { + return Option::from(idx); + } + } + OperationDirection::Down => { + if current_monitor_size.top + current_monitor_size.bottom == monitor.size.top { + return Option::from(idx); + } + } + } + } + + None + } + + /// The monitor a window is on: the one whose workspace holds it if it is managed, otherwise + /// the one the middle of the window is on. + /// + /// A managed window is not necessarily where its workspace is: the scrolling layout runs a + /// strip of windows past the edge of the monitor, and KWin lets them sit on the next monitor + /// over, where asking the geometry would hand focus to a monitor that does not own them. + pub fn monitor_idx_from_window(&self, window: Window) -> Option { + if let Some((monitor_idx, _)) = self.known_window_ids.get(&window.id) { + return Some(*monitor_idx); + } + + let rect = window.rect().ok()?; + let middle = (rect.left + rect.right / 2, rect.top + rect.bottom / 2); + + self.monitors() + .iter() + .position(|monitor| monitor.size.contains_point(middle)) + } + + pub fn monitor_idx_from_current_pos(&mut self) -> Option { + let (x, y) = backend().cursor_pos()?; + let monitor_id = backend().monitor_from_point(x, y)?; + + for (i, monitor) in self.monitors().iter().enumerate() { + if monitor.id == monitor_id { + return Option::from(i); + } + } + + // TODO: figure out if we need this on macOS + // // our hmonitor might be stale, so if we didn't return above, try querying via the latest + // // info taken from win32_display_data and update our hmonitor while we're at it + // if let Ok(latest) = MacosApi::monitor(monitor_id) { + // for (i, monitor) in self.monitors_mut().iter_mut().enumerate() { + // if monitor.device_id() == latest.device_id() { + // monitor.set_id(latest.id()); + // return Option::from(i); + // } + // } + // } + + None + } + #[tracing::instrument(skip(self))] pub fn monitor_workspace_index_by_name(&mut self, name: &str) -> Option<(usize, usize)> { tracing::info!("looking up workspace by name"); @@ -1039,6 +1368,245 @@ impl WindowManager { None } + /// Calculates the direction of a move across monitors given a specific monitor index + pub fn direction_from_monitor_idx( + &self, + target_monitor_idx: usize, + ) -> Option { + let current_monitor_idx = self.focused_monitor_idx(); + if current_monitor_idx == target_monitor_idx { + return None; + } + + let current_monitor_size = self.focused_monitor_size().ok()?; + let target_monitor_size = self.monitors().get(target_monitor_idx)?.size; + + if target_monitor_size.left + target_monitor_size.right == current_monitor_size.left { + return Some(OperationDirection::Left); + } + if current_monitor_size.right + current_monitor_size.left == target_monitor_size.left { + return Some(OperationDirection::Right); + } + if target_monitor_size.top + target_monitor_size.bottom == current_monitor_size.top { + return Some(OperationDirection::Up); + } + if current_monitor_size.top + current_monitor_size.bottom == target_monitor_size.top { + return Some(OperationDirection::Down); + } + + None + } + + #[tracing::instrument(skip(self))] + pub fn move_container_to_monitor( + &mut self, + monitor_idx: usize, + workspace_idx: Option, + follow: bool, + move_direction: Option, + ) -> eyre::Result<()> { + tracing::info!("moving container"); + + let focused_monitor_idx = self.focused_monitor_idx(); + + if focused_monitor_idx == monitor_idx + && let Some(workspace_idx) = workspace_idx + { + return self.move_container_to_workspace(workspace_idx, follow, None); + } + + let offset = self.work_area_offset; + let mouse_follows_focus = self.mouse_follows_focus; + + let monitor = self + .focused_monitor_mut() + .ok_or_eyre("there is no monitor")?; + + let current_area = monitor.work_area_size; + + let workspace = monitor + .focused_workspace_mut() + .ok_or_eyre("there is no workspace")?; + + let foreground_window_id = backend() + .foreground_window() + .ok_or_eyre("no foreground window")?; + let floating_window_index = workspace + .floating_windows() + .iter() + .position(|w| w.id == foreground_window_id); + + let floating_window = + floating_window_index.and_then(|idx| workspace.floating_windows_mut().remove(idx)); + let container = if floating_window_index.is_none() { + Some( + workspace + .remove_focused_container() + .ok_or_eyre("there is no container")?, + ) + } else { + None + }; + monitor.update_focused_workspace(offset)?; + + let target_monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let target_monitor_work_area_size = target_monitor.work_area_size; + + let mut should_load_workspace = false; + if let Some(workspace_idx) = workspace_idx + && workspace_idx != target_monitor.focused_workspace_idx() + { + target_monitor.focus_workspace(workspace_idx)?; + should_load_workspace = true; + } + let target_workspace = target_monitor + .focused_workspace_mut() + .ok_or_eyre("there is no focused workspace on target monitor")?; + + if let Some(window) = floating_window { + window.move_to_area(¤t_area, &target_monitor_work_area_size)?; + target_workspace.floating_windows_mut().push_back(window); + } else if let Some(container) = container { + let _container_window_ids = + container.windows().iter().map(|w| w.id).collect::>(); + + if let Some(direction) = move_direction { + target_monitor.add_container_with_direction(container, workspace_idx, direction)?; + } else { + target_monitor.add_container(container, workspace_idx)?; + } + + if let Some(workspace) = target_monitor.focused_workspace() + && !workspace.tile + { + // TODO: figure out how to construct a Window from just an id here + // for window_id in container_window_ids { + // Window::from(window_id) + // .move_to_area(¤t_area, &target_monitor.work_area_size)?; + // } + } + } else { + eyre::bail!("failed to find a window to move"); + } + + // the moved window has to be on the target workspace's desktop before it is shown or focused + target_monitor.assign_windows_to_workspaces(); + + if should_load_workspace { + target_monitor.load_focused_workspace(mouse_follows_focus)?; + } + target_monitor.update_focused_workspace(offset)?; + + // this second one is for DPI changes when the target is another monitor + // if we don't do this the layout on the other monitor could look funny + // until it is interacted with again + target_monitor.update_focused_workspace(offset)?; + + if follow { + self.focus_monitor(monitor_idx)?; + } + + self.update_focused_workspace(self.mouse_follows_focus, true)?; + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn swap_focused_monitor(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("swapping focused monitor"); + + let focused_monitor_idx = self.focused_monitor_idx(); + let mouse_follows_focus = self.mouse_follows_focus; + + self.swap_monitor_workspaces(focused_monitor_idx, idx)?; + + self.update_focused_workspace(mouse_follows_focus, true) + } + + #[tracing::instrument(skip(self))] + pub fn swap_monitor_workspaces( + &mut self, + first_idx: usize, + second_idx: usize, + ) -> eyre::Result<()> { + tracing::info!("swaping monitors"); + if first_idx == second_idx { + return Ok(()); + } + let mouse_follows_focus = self.mouse_follows_focus; + let offset = self.work_area_offset; + let first_focused_workspace = { + let first_monitor = self + .monitors() + .get(first_idx) + .ok_or_eyre("There is no monitor")?; + first_monitor.focused_workspace_idx() + }; + + let second_focused_workspace = { + let second_monitor = self + .monitors() + .get(second_idx) + .ok_or_eyre("There is no monitor")?; + second_monitor.focused_workspace_idx() + }; + + // Swap workspaces between the first and second monitors + + let first_workspaces = self + .monitors_mut() + .get_mut(first_idx) + .ok_or_eyre("There is no monitor")? + .remove_workspaces(); + + let second_workspaces = self + .monitors_mut() + .get_mut(second_idx) + .ok_or_eyre("There is no monitor")? + .remove_workspaces(); + + self.monitors_mut() + .get_mut(first_idx) + .ok_or_eyre("There is no monitor")? + .workspaces_mut() + .extend(second_workspaces); + + self.monitors_mut() + .get_mut(second_idx) + .ok_or_eyre("There is no monitor")? + .workspaces_mut() + .extend(first_workspaces); + + // Set the focused workspaces for the first and second monitors + if let Some(first_monitor) = self.monitors_mut().get_mut(first_idx) { + first_monitor.update_workspaces_globals(offset); + first_monitor.focus_workspace(second_focused_workspace)?; + first_monitor.load_focused_workspace(mouse_follows_focus)?; + } + + if let Some(second_monitor) = self.monitors_mut().get_mut(second_idx) { + second_monitor.update_workspaces_globals(offset); + second_monitor.focus_workspace(first_focused_workspace)?; + second_monitor.load_focused_workspace(mouse_follows_focus)?; + } + + self.update_focused_workspace_by_monitor_idx(second_idx)?; + self.update_focused_workspace_by_monitor_idx(first_idx) + } + + pub fn update_focused_workspace_by_monitor_idx(&mut self, idx: usize) -> eyre::Result<()> { + let offset = self.work_area_offset; + + self.monitors_mut() + .get_mut(idx) + .ok_or_eyre("there is no monitor")? + .update_focused_workspace(offset) + } + /// 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 @@ -1098,6 +1666,35 @@ impl WindowManager { self.update_focused_workspace(self.mouse_follows_focus, true) } + /// Gives the focus to the window at `idx` in the focused container + #[tracing::instrument(skip(self))] + pub fn focus_container_window(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("focusing container window at index {idx}"); + + let mouse_follows_focus = self.mouse_follows_focus; + + let container = self.focused_container_mut()?; + + let len = NonZeroUsize::new(container.windows().len()) + .ok_or_eyre("there must be at least one window in a container")?; + + if len.get() == 1 && idx != 0 { + eyre::bail!("there is only one window in this container"); + } + + if container.windows().get(idx).is_none() { + eyre::bail!("there is no window in this container at index {idx}"); + } + + container.focus_window(idx); + + if let Some(window) = container.focused_window() { + window.focus(mouse_follows_focus)?; + } + + self.update_focused_workspace(mouse_follows_focus, true) + } + /// With [`OperationBehaviour::NoOp`], refuses a message while the window that has the focus /// in the compositor is not in a container of the focused workspace: a window komorebi does /// not manage, one the user unmanaged, or a floating window @@ -1405,6 +2002,31 @@ impl WindowManager { Ok(()) } + #[tracing::instrument(skip(self))] + pub fn move_workspace_to_monitor(&mut self, idx: usize) -> eyre::Result<()> { + tracing::info!("moving workspace"); + let mouse_follows_focus = self.mouse_follows_focus; + let offset = self.work_area_offset; + let workspace = self + .remove_focused_workspace() + .ok_or_eyre("there is no workspace")?; + + { + let target_monitor: &mut Monitor = self + .monitors_mut() + .get_mut(idx) + .ok_or_eyre("there is no monitor")?; + + target_monitor.workspaces_mut().push_back(workspace); + target_monitor.update_workspaces_globals(offset); + target_monitor.focus_workspace(target_monitor.workspaces().len().saturating_sub(1))?; + target_monitor.load_focused_workspace(mouse_follows_focus)?; + } + + self.focus_monitor(idx)?; + self.update_focused_workspace(mouse_follows_focus, true) + } + pub fn remove_focused_workspace(&mut self) -> Option { let focused_monitor: &mut Monitor = self.focused_monitor_mut()?; let focused_workspace_idx = focused_monitor.focused_workspace_idx(); @@ -1460,6 +2082,177 @@ impl WindowManager { Ok(()) } + + #[tracing::instrument(skip(self))] + pub fn transfer_window( + &mut self, + origin: (usize, usize, u32), + target: (usize, usize, usize), + ) -> eyre::Result<()> { + let (origin_monitor_idx, origin_workspace_idx, window_id) = origin; + let (target_monitor_idx, target_workspace_idx, target_container_idx) = target; + + let origin_workspace = self + .monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("cannot get monitor idx")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("cannot get workspace idx")?; + + let origin_container_idx = origin_workspace + .container_for_window(window_id) + .and_then(|c| origin_workspace.containers().iter().position(|cc| cc == c)); + + if let Some(origin_container_idx) = origin_container_idx { + // Moving normal container window + self.transfer_container( + ( + origin_monitor_idx, + origin_workspace_idx, + origin_container_idx, + ), + ( + target_monitor_idx, + target_workspace_idx, + target_container_idx, + ), + )?; + } else if let Some(idx) = origin_workspace + .floating_windows() + .iter() + .position(|w| w.id == window_id) + { + // Moving floating window + // There is no need to physically move the floating window between areas with + // `move_to_area` because the user already did that, so we only need to transfer the + // window to the target `floating_windows` + if let Some(floating_window) = origin_workspace.floating_windows_mut().remove(idx) { + let target_workspace = self + .monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this idx")? + .focused_workspace_mut() + .ok_or_eyre("there is no focused workspace for this monitor")?; + + target_workspace + .floating_windows_mut() + .push_back(floating_window); + } + } + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn swap_containers( + &mut self, + origin: (usize, usize, usize), + target: (usize, usize, usize), + ) -> eyre::Result<()> { + let (origin_monitor_idx, origin_workspace_idx, origin_container_idx) = origin; + let (target_monitor_idx, target_workspace_idx, target_container_idx) = target; + + let origin_container_is_valid = self + .monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .containers() + .get(origin_container_idx) + .is_some(); + + let target_container_is_valid = self + .monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(target_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .containers() + .get(origin_container_idx) + .is_some(); + + if origin_container_is_valid && target_container_is_valid { + let origin_container = self + .monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .remove_container(origin_container_idx) + .ok_or_eyre("there is no container at this index")?; + + let target_container = self + .monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(target_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .remove_container(target_container_idx); + + self.monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(target_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .containers_mut() + .insert(target_container_idx, origin_container); + + if let Some(target_container) = target_container { + self.monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .containers_mut() + .insert(origin_container_idx, target_container); + } + } + + Ok(()) + } + + #[tracing::instrument(skip(self))] + pub fn transfer_container( + &mut self, + origin: (usize, usize, usize), + target: (usize, usize, usize), + ) -> eyre::Result<()> { + let (origin_monitor_idx, origin_workspace_idx, origin_container_idx) = origin; + let (target_monitor_idx, target_workspace_idx, target_container_idx) = target; + + let origin_container = self + .monitors_mut() + .get_mut(origin_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(origin_workspace_idx) + .ok_or_eyre("there is no workspace at this index")? + .remove_container(origin_container_idx) + .ok_or_eyre("there is no container at this index")?; + + let target_workspace = self + .monitors_mut() + .get_mut(target_monitor_idx) + .ok_or_eyre("there is no monitor at this index")? + .workspaces_mut() + .get_mut(target_workspace_idx) + .ok_or_eyre("there is no workspace at this index")?; + + target_workspace + .containers_mut() + .insert(target_container_idx, origin_container); + + target_workspace.focus_container(target_container_idx); + + Ok(()) + } } #[cfg(test)] @@ -1649,6 +2442,157 @@ mod tests { assert_eq!(workspace_index.1, 0); } + #[test] + fn test_switch_focus_monitors() { + let (mut wm, _test_context) = setup_window_manager(); + + { + // Create a first monitor + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + assert_eq!(wm.monitors().len(), 1); + + { + // Create a second monitor + let m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + assert_eq!(wm.monitors().len(), 2); + + { + // Create a third monitor + let m = monitor::new( + 2, + Rect::default(), + Rect::default(), + "TestMonitor3".to_string(), + "TestDeviceID3".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + assert_eq!(wm.monitors().len(), 3); + + { + // Set the first monitor as focused and check if it is focused + wm.focus_monitor(0).unwrap(); + let current_monitor_idx = wm.monitors.focused_idx(); + assert_eq!(current_monitor_idx, 0); + } + + { + // Set the second monitor as focused and check if it is focused + wm.focus_monitor(1).unwrap(); + let current_monitor_idx = wm.monitors.focused_idx(); + assert_eq!(current_monitor_idx, 1); + } + + { + // Set the third monitor as focused and check if it is focused + wm.focus_monitor(2).unwrap(); + let current_monitor_idx = wm.monitors.focused_idx(); + assert_eq!(current_monitor_idx, 2); + } + + // Switch back to the first monitor + wm.focus_monitor(0).unwrap(); + let current_monitor_idx = wm.monitors.focused_idx(); + assert_eq!(current_monitor_idx, 0); + } + + #[test] + fn test_switch_focus_to_nonexistent_monitor() { + let (mut wm, _test_context) = setup_window_manager(); + + { + // Create a first monitor + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + + // Should have 1 monitor and the monitor index should be 0 + assert_eq!(wm.monitors().len(), 1); + assert_eq!(wm.focused_monitor_idx(), 0); + + // Should receive an error when trying to focus a non-existent monitor + let result = wm.focus_monitor(1); + assert!( + result.is_err(), + "Expected an error when focusing a non-existent monitor" + ); + + // Should still be focused on the first monitor + assert_eq!(wm.focused_monitor_idx(), 0); + } + + #[test] + fn test_focused_monitor_size() { + let (mut wm, _test_context) = setup_window_manager(); + + { + // Create a first monitor + let m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // monitor should have a single workspace + assert_eq!(m.workspaces().len(), 1); + + // add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + assert_eq!(wm.monitors().len(), 1); + + { + // Set the first monitor as focused and check if it is focused + wm.focus_monitor(0).unwrap(); + let current_monitor_size = wm.focused_monitor_size().unwrap(); + assert_eq!(current_monitor_size, Rect::default()); + } + } + #[test] fn test_focus_container_in_cycle_direction() { let (mut wm, _test_context) = setup_window_manager(); @@ -1697,6 +2641,625 @@ mod tests { assert_eq!(wm.focused_container_idx().unwrap(), 0); } + #[test] + fn test_transfer_window() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(0)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + { + // Create a second monitor + let mut m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + // Should contain 2 monitors + assert_eq!(wm.monitors().len(), 2); + + { + // Monitor 0, Workspace 0, Window 0 + let origin = (0, 0, 0); + + // Monitor 1, Workspace 0, Window 0 + let target = (1, 0, 0); + + // Transfer the window from monitor 0 to monitor 1 + wm.transfer_window(origin, target).unwrap(); + + // Monitor 1 should contain 0 containers + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 0); + + // Monitor 2 should contain 2 containers + wm.focus_monitor(1).unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 2); + } + + { + // Monitor 1, Workspace 0, Window 0 + let origin = (1, 0, 0); + + // Monitor 0, Workspace 0, Window 0 + let target = (0, 0, 0); + + // Transfer the window from monitor 1 back to monitor 0 + wm.transfer_window(origin, target).unwrap(); + + // Monitor 2 should contain 1 containers + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 1); + + // Monitor 1 should contain 1 containers + wm.focus_monitor(0).unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 1); + } + } + + #[test] + fn test_transfer_window_to_nonexistent_monitor() { + // NOTE: transfer_window is primarily used when a window is being dragged by a mouse. The + // transfer_window function does return an error when the target monitor doesn't exist but + // there is a bug where the window isn't in the container after the window fails to + // transfer. The test will test for the result of the transfer_window function but not if + // the window is in the container after the transfer fails. + + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(0)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + { + // Monitor 0, Workspace 0, Window 0 + let origin = (0, 0, 0); + + // Monitor 1, Workspace 0, Window 0 + // + let target = (1, 0, 0); + + // Attempt to transfer the window from monitor 0 to a non-existent monitor + let result = wm.transfer_window(origin, target); + + // Result should be an error since the monitor doesn't exist + assert!( + result.is_err(), + "Expected an error when transferring to a non-existent monitor" + ); + + assert_eq!(wm.focused_container_idx().unwrap(), 0); + assert_eq!(wm.focused_workspace_idx().unwrap(), 0); + } + } + + #[test] + fn test_transfer_container() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(0)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + { + // Create a second monitor + let mut m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + // Should contain 2 monitors + assert_eq!(wm.monitors().len(), 2); + + { + // Monitor 0, Workspace 0, Window 0 + let origin = (0, 0, 0); + + // Monitor 1, Workspace 0, Window 0 + let target = (1, 0, 0); + + // Transfer the window from monitor 0 to monitor 1 + wm.transfer_container(origin, target).unwrap(); + + // Monitor 1 should contain 0 containers + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 0); + + // Monitor 2 should contain 2 containers + wm.focus_monitor(1).unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 2); + } + + { + // Monitor 1, Workspace 0, Window 0 + let origin = (1, 0, 0); + + // Monitor 0, Workspace 0, Window 0 + let target = (0, 0, 0); + + // Transfer the window from monitor 1 back to monitor 0 + wm.transfer_container(origin, target).unwrap(); + + // Monitor 2 should contain 1 containers + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 1); + + // Monitor 1 should contain 1 containers + wm.focus_monitor(0).unwrap(); + let workspace = wm.focused_workspace_mut().unwrap(); + assert_eq!(workspace.containers().len(), 1); + } + } + + #[test] + fn test_swap_containers() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let mut container = Container::default(); + + // Add three windows to the container + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + + // Should have 3 windows in the container + assert_eq!(container.windows().len(), 3); + + // Add the container to the workspace + let workspace = m.focused_workspace_mut().unwrap(); + workspace.add_container_to_back(container); + + // Add monitor to the window manager + wm.monitors_mut().push_back(m); + } + + { + // Create a second monitor + let mut m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + wm.monitors_mut().push_back(m); + } + + // Should contain 2 monitors + assert_eq!(wm.monitors().len(), 2); + + // Monitor 0, Workspace 0, Window 0 + let origin = (0, 0, 0); + + // Monitor 1, Workspace 0, Window 0 + let target = (1, 0, 0); + + wm.swap_containers(origin, target).unwrap(); + + { + // Monitor 0 Workspace 0 container 0 should contain 1 container + let workspace = wm.focused_workspace_mut().unwrap(); + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 1); + } + + wm.focus_monitor(1).unwrap(); + + { + // Monitor 1 Workspace 0 container 0 should contain 3 containers + let workspace = wm.focused_workspace_mut().unwrap(); + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 3); + } + } + + // #[test] + // fn test_swap_container_with_nonexistent_container() { + // let (mut wm, _context) = setup_window_manager(); + // + // { + // // Create a first monitor + // let mut m = monitor::new( + // 0, + // Rect::default(), + // Rect::default(), + // "TestMonitor".to_string(), + // "TestDeviceID".to_string(), + // ); + // + // // Create a container + // let mut container = Container::default(); + // + // // Add three windows to the container + // for i in 0..3 { + // container.windows_mut().push_back(Window::from(i)); + // } + // + // // Should have 3 windows in the container + // assert_eq!(container.windows().len(), 3); + // + // // Add the container to the workspace + // let workspace = m.focused_workspace_mut().unwrap(); + // workspace.add_container_to_back(container); + // + // // Add monitor to the window manager + // wm.monitors_mut().push_back(m); + // } + // + // // Monitor 0, Workspace 0, Window 0 + // let origin = (0, 0, 0); + // + // // Monitor 1, Workspace 0, Window 0 + // let target = (0, 3, 0); + // + // // Should be focused on the first container + // assert_eq!(wm.focused_container_idx().unwrap(), 0); + // + // // Should return an error since there is only one container in the workspace + // let result = wm.swap_containers(origin, target); + // assert!( + // result.is_err(), + // "Expected an error when swapping with a non-existent container" + // ); + // + // // Should still be focused on the first container + // assert_eq!(wm.focused_container_idx().unwrap(), 0); + // + // { + // // Should still have 1 container in the workspace + // let workspace = wm.focused_workspace_mut().unwrap(); + // assert_eq!(workspace.containers().len(), 1); + // + // // Container should still have 3 windows + // let container = workspace.focused_container_mut().unwrap(); + // assert_eq!(container.windows().len(), 3); + // } + // } + + #[test] + fn test_swap_monitor_workspaces() { + let (mut wm, _context) = setup_window_manager(); + + { + // Create a first monitor + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Create a container + let mut container = Container::default(); + + // Add three windows to the container + for i in 0..3 { + container.windows_mut().push_back(Window::from(i)); + } + + // Should have 3 windows in the container + assert_eq!(container.windows().len(), 3); + + // Add the container to the workspace + let workspace = m.focused_workspace_mut().unwrap(); + workspace.add_container_to_back(container); + + // Add monitor to the window manager + wm.monitors_mut().push_back(m); + } + + { + // Create a second monitor + let mut m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Create a container + let workspace = m.focused_workspace_mut().unwrap(); + let mut container = Container::default(); + + // Add a window to the container + container.windows_mut().push_back(Window::from(1)); + workspace.add_container_to_back(container); + + // Should contain 1 container + assert_eq!(workspace.containers().len(), 1); + + // Add the monitor to the window manager + wm.monitors_mut().push_back(m); + } + + // Swap the workspaces between Monitor 0 and Monitor 1 + wm.swap_monitor_workspaces(0, 1).ok(); + + { + // The focused workspace container in Monitor 0 should contain 3 containers + let workspace = wm.focused_workspace_mut().unwrap(); + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 1); + } + + // Switch to Monitor 1 + wm.focus_monitor(1).unwrap(); + assert_eq!(wm.focused_monitor_idx(), 1); + + { + // The focused workspace container in Monitor 1 should contain 3 containers + let workspace = wm.focused_workspace_mut().unwrap(); + let container = workspace.focused_container_mut().unwrap(); + assert_eq!(container.windows().len(), 3); + } + } + + #[test] + fn test_swap_workspace_with_nonexistent_monitor() { + let (mut wm, _context) = setup_window_manager(); + + { + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add another workspace + let new_workspace_index = m.new_workspace_idx(); + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Add monitor to window manager + wm.monitors_mut().push_back(m); + } + + // Should be an error since Monitor 1 does not exist + let result = wm.swap_monitor_workspaces(1, 0); + assert!( + result.is_err(), + "Expected an error when swapping with a non-existent monitor" + ); + + { + // Should still have 2 workspaces in Monitor 0 + let monitor = wm.monitors().front().unwrap(); + let workspaces = monitor.workspaces(); + assert_eq!( + workspaces.len(), + 2, + "Expected 2 workspaces after swap attempt" + ); + assert_eq!(wm.focused_monitor_idx(), 0); + } + } + + #[test] + fn test_move_workspace_to_monitor() { + let (mut wm, _context) = setup_window_manager(); + + { + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add another workspace + let new_workspace_index = m.new_workspace_idx(); + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Add monitor to window manager + wm.monitors_mut().push_back(m); + } + + { + let m = monitor::new( + 1, + Rect::default(), + Rect::default(), + "TestMonitor2".to_string(), + "TestDeviceID2".to_string(), + ); + + // Should contain 1 workspace + assert_eq!(m.workspaces().len(), 1); + + // Add monitor to workspace + wm.monitors_mut().push_back(m); + } + + // Should contain 2 monitors + assert_eq!(wm.monitors().len(), 2); + + // Move a workspace from Monitor 0 to Monitor 1 + wm.move_workspace_to_monitor(1).ok(); + + { + // Should be focused on Monitor 1 + assert_eq!(wm.focused_monitor_idx(), 1); + + // Should contain 2 workspaces + let monitor = wm.focused_monitor_mut().unwrap(); + assert_eq!(monitor.workspaces().len(), 2); + } + + { + // Switch to Monitor 0 + wm.focus_monitor(0).unwrap(); + + // Should contain 1 workspace + let monitor = wm.focused_monitor_mut().unwrap(); + assert_eq!(monitor.workspaces().len(), 1); + } + } + + #[test] + fn test_move_workspace_to_nonexistent_monitor() { + let (mut wm, _context) = setup_window_manager(); + + { + let mut m = monitor::new( + 0, + Rect::default(), + Rect::default(), + "TestMonitor".to_string(), + "TestDeviceID".to_string(), + ); + + // Add another workspace + let new_workspace_index = m.new_workspace_idx(); + m.focus_workspace(new_workspace_index).unwrap(); + + // Should have 2 workspaces + assert_eq!(m.workspaces().len(), 2); + + // Add monitor to window manager + wm.monitors_mut().push_back(m); + } + + // Attempt to move a workspace to a non-existent monitor + let result = wm.move_workspace_to_monitor(1); + + // Should be an error since Monitor 1 does not exist + assert!( + result.is_err(), + "Expected an error when moving to a non-existent monitor" + ); + } + #[test] fn test_toggle_tiling() { let (mut wm, _context) = setup_window_manager(); diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 7ec1771b..a5a8996b 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -76,6 +76,13 @@ impl Default for Workspace { } } +/// Where a workspace has a window of an application ([`Workspace::location_from_exe`]) +#[derive(Debug)] +pub enum WorkspaceWindowLocation { + Container(usize, usize), // container_idx, window_idx + Floating(usize), // idx in floating_windows +} + #[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq)] /// The work area a monitor gives the workspace it shows, the padding and the offset the /// workspace falls back to when it sets none of its own, and the monitor's window-based offset @@ -378,6 +385,29 @@ impl Workspace { false } + /// Where this workspace has a window of the executable `exe`, the first one in a container + /// before a floating one + pub fn location_from_exe(&self, exe: &str) -> Option { + for (container_idx, container) in self.containers().iter().enumerate() { + if let Some(window_idx) = container.idx_from_exe(exe) { + return Some(WorkspaceWindowLocation::Container( + container_idx, + window_idx, + )); + } + } + + for (window_idx, window) in self.floating_windows().iter().enumerate() { + if let Some(window_exe) = window.exe() + && exe == window_exe + { + return Some(WorkspaceWindowLocation::Floating(window_idx)); + } + } + + None + } + /// Returns true if and only if the window is in one of the containers, which leaves out the /// floating windows: the windows komorebi tiles pub fn contains_managed_window(&self, window_id: u32) -> bool { @@ -738,6 +768,12 @@ impl Workspace { Ok(()) } + + /// The container that has the window, if one of this workspace's does + pub fn container_for_window(&self, window_id: u32) -> Option<&Container> { + self.containers() + .get(self.container_idx_for_window(window_id)?) + } } impl Workspace { diff --git a/komorebi/tests/focus.rs b/komorebi/tests/focus.rs index 648616d1..6267e723 100644 --- a/komorebi/tests/focus.rs +++ b/komorebi/tests/focus.rs @@ -103,7 +103,9 @@ fn focus_towards_a_side_with_no_window_is_an_error_and_changes_nothing() { assert_eq!( result.map_err(|error| error.to_string()), - Err(String::from("there is no container in this direction")) + Err(String::from( + "there is no container or monitor in this direction" + )) ); assert_eq!(focused(&wm), 19_012); assert!(fake.commands().is_empty(), "{:?}", fake.commands()); diff --git a/komorebi/tests/monitors.rs b/komorebi/tests/monitors.rs new file mode 100644 index 00000000..1086ba37 --- /dev/null +++ b/komorebi/tests/monitors.rs @@ -0,0 +1,402 @@ +//! More than one monitor, against an in-memory desktop with two 1920x1080 monitors side by side: +//! the focus and a move that cross to the next monitor at the edge of one, the monitor commands, +//! moving workspaces between monitors, a window that opens on the monitor that is not focused, and +//! `eager-focus`. The messages go in through [`WindowManager::process_command`]; what comes out is +//! the monitors of the window manager and where the fake has the windows. +//! +//! Window ids are in the 32_000s. + +use komorebi::backend::Backend; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::CycleDirection; +use komorebi::core::MoveBehaviour; +use komorebi::core::OperationDirection; +use komorebi::core::Rect; +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; + +const LEFT: u32 = 1; +const RIGHT: u32 = 2; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn activated(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +/// The bounds of the monitor on the right, which is also its work area +fn right_half() -> Rect { + Rect { + left: 1920, + top: 0, + right: 1920, + bottom: 1080, + } +} + +/// A window manager over a fake desktop with the monitor of `with_one_monitor` on the left and a +/// second one on the right +fn two_monitors() -> (Arc, WindowManager) { + let fake = FakeBackend::with_one_monitor(); + fake.add_monitor(RIGHT, "Virtual-1", right_half(), right_half()); + let fake = Arc::new(fake); + 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/kmm-{}-{}.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(); + wm + }); + + (fake, wm) +} + +/// Opens a window on the left monitor, or on the right one, and has the window manager show it +fn open(fake: &Arc, wm: &mut WindowManager, id: u32, on_right: bool) { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + if on_right { + fake.move_window_by_user( + id, + Rect { + left: 2020, + top: 100, + right: 800, + bottom: 600, + }, + ); + } + with_backend(fake.clone(), || wm.process_event(added(id))).unwrap(); +} + +fn send( + fake: &Arc, + wm: &mut WindowManager, + message: SocketMessage, +) -> color_eyre::Result<()> { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())) +} + +/// The ids of the windows of the focused workspace of each monitor +fn windows(wm: &WindowManager) -> Vec> { + wm.monitors() + .iter() + .map(|monitor| { + monitor + .focused_workspace() + .unwrap() + .containers() + .iter() + .flat_map(|container| container.windows().iter().map(|window| window.id)) + .collect() + }) + .collect() +} + +fn on_right(fake: &FakeBackend, id: u32) -> bool { + fake.rect_of(id).is_some_and(|rect| rect.left >= 1920) +} + +#[test] +fn a_window_that_opens_on_the_monitor_that_is_not_focused_focuses_it() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_001, false); + assert_eq!(wm.focused_monitor_idx(), 0); + + open(&fake, &mut wm, 32_002, true); + + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(windows(&wm), [vec![32_001], vec![32_002]]); + assert!(on_right(&fake, 32_002)); +} + +#[test] +fn the_focus_crosses_to_the_monitor_on_that_side() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_011, true); + open(&fake, &mut wm, 32_012, false); + assert_eq!(wm.focused_monitor_idx(), 0); + + send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Right), + ) + .unwrap(); + + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(fake.foreground_window(), Some(32_011)); + + // and with no monitor further right, it is an error that changes nothing + let result = send( + &fake, + &mut wm, + SocketMessage::FocusWindow(OperationDirection::Right), + ); + assert_eq!( + result.map_err(|error| error.to_string()), + Err(String::from( + "there is no container or monitor in this direction" + )) + ); + assert_eq!(wm.focused_monitor_idx(), 1); +} + +#[test] +fn a_move_at_the_edge_of_a_monitor_swaps_with_the_window_on_the_next_one_by_default() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_021, true); + open(&fake, &mut wm, 32_022, false); + + send( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Right), + ) + .unwrap(); + + assert_eq!(windows(&wm), [vec![32_021], vec![32_022]]); + assert_eq!(wm.focused_monitor_idx(), 1); + assert!(on_right(&fake, 32_022) && !on_right(&fake, 32_021)); +} + +#[test] +fn with_insert_a_move_at_the_edge_puts_the_window_in_among_those_of_the_next_monitor() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_031, true); + open(&fake, &mut wm, 32_032, false); + send( + &fake, + &mut wm, + SocketMessage::CrossMonitorMoveBehaviour(MoveBehaviour::Insert), + ) + .unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Right), + ) + .unwrap(); + + assert!(windows(&wm)[0].is_empty()); + let mut right = windows(&wm)[1].clone(); + right.sort_unstable(); + assert_eq!(right, [32_031, 32_032]); + assert!(on_right(&fake, 32_031) && on_right(&fake, 32_032)); +} + +#[test] +fn with_no_op_a_move_at_the_edge_moves_nothing() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_041, true); + open(&fake, &mut wm, 32_042, false); + send( + &fake, + &mut wm, + SocketMessage::CrossMonitorMoveBehaviour(MoveBehaviour::NoOp), + ) + .unwrap(); + fake.clear_commands(); + + send( + &fake, + &mut wm, + SocketMessage::MoveWindow(OperationDirection::Right), + ) + .unwrap(); + + assert_eq!(windows(&wm), [vec![32_042], vec![32_041]]); + assert_eq!(wm.focused_monitor_idx(), 0); +} + +#[test] +fn toggle_cross_monitor_move_behaviour_switches_between_swap_and_insert() { + let (fake, mut wm) = two_monitors(); + + send( + &fake, + &mut wm, + SocketMessage::ToggleCrossMonitorMoveBehaviour, + ) + .unwrap(); + assert_eq!(wm.cross_monitor_move_behaviour, MoveBehaviour::Insert); + send( + &fake, + &mut wm, + SocketMessage::ToggleCrossMonitorMoveBehaviour, + ) + .unwrap(); + assert_eq!(wm.cross_monitor_move_behaviour, MoveBehaviour::Swap); +} + +#[test] +fn a_monitor_is_focused_by_its_index_or_in_order() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_051, false); + open(&fake, &mut wm, 32_052, true); + + send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(0)).unwrap(); + assert_eq!(wm.focused_monitor_idx(), 0); + assert_eq!(fake.foreground_window(), Some(32_051)); + + send( + &fake, + &mut wm, + SocketMessage::CycleFocusMonitor(CycleDirection::Next), + ) + .unwrap(); + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(fake.foreground_window(), Some(32_052)); + + assert!(send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(5)).is_err()); + assert_eq!(wm.focused_monitor_idx(), 1); +} + +#[test] +fn move_to_monitor_follows_the_window_and_send_to_monitor_does_not() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_061, false); + open(&fake, &mut wm, 32_062, false); + + send( + &fake, + &mut wm, + SocketMessage::SendContainerToMonitorNumber(1), + ) + .unwrap(); + assert_eq!(wm.focused_monitor_idx(), 0); + assert_eq!(windows(&wm), [vec![32_061], vec![32_062]]); + assert!(on_right(&fake, 32_062)); + + send( + &fake, + &mut wm, + SocketMessage::MoveContainerToMonitorNumber(1), + ) + .unwrap(); + assert_eq!(wm.focused_monitor_idx(), 1); + assert!(windows(&wm)[0].is_empty()); + assert!(on_right(&fake, 32_061) && on_right(&fake, 32_062)); +} + +#[test] +fn a_window_sent_to_a_workspace_of_another_monitor_goes_on_its_desktop() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_071, false); + open(&fake, &mut wm, 32_072, false); + + send( + &fake, + &mut wm, + SocketMessage::SendContainerToMonitorWorkspaceNumber(1, 2), + ) + .unwrap(); + + assert_eq!(wm.focused_monitor_idx(), 0); + let right = &wm.monitors()[1]; + assert_eq!(right.focused_workspace_idx(), 2); + assert!(right.workspaces()[2].contains_window(32_072)); + assert_eq!(fake.workspace_of(32_072), Some(2)); +} + +#[test] +fn a_named_workspace_on_another_monitor_takes_the_window_sent_to_it() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_081, false); + open(&fake, &mut wm, 32_082, false); + send( + &fake, + &mut wm, + SocketMessage::WorkspaceName(1, 0, String::from("side")), + ) + .unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::MoveContainerToNamedWorkspace(String::from("side")), + ) + .unwrap(); + + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(windows(&wm), [vec![32_081], vec![32_082]]); +} + +#[test] +fn a_workspace_moves_to_another_monitor_and_workspaces_are_swapped_between_monitors() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_091, false); + open(&fake, &mut wm, 32_092, true); + + send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(0)).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::SwapWorkspacesToMonitorNumber(1), + ) + .unwrap(); + assert_eq!(windows(&wm), [vec![32_092], vec![32_091]]); + + send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(0)).unwrap(); + send( + &fake, + &mut wm, + SocketMessage::MoveWorkspaceToMonitorNumber(1), + ) + .unwrap(); + assert_eq!(wm.focused_monitor_idx(), 1); + let right = &wm.monitors()[1]; + assert_eq!(right.workspaces().len(), 2); + assert!(right.focused_workspace().unwrap().contains_window(32_092)); +} + +#[test] +fn eager_focus_finds_the_window_of_an_executable_on_any_monitor_and_workspace() { + let (fake, mut wm) = two_monitors(); + open(&fake, &mut wm, 32_101, false); + fake.open_window(32_102, "firefox", "firefox", "a browser"); + with_backend(fake.clone(), || wm.process_event(added(32_102))).unwrap(); + // the browser on workspace 1 of the right monitor, and the focus back on the terminal + send( + &fake, + &mut wm, + SocketMessage::SendContainerToMonitorWorkspaceNumber(1, 1), + ) + .unwrap(); + with_backend(fake.clone(), || wm.process_event(activated(32_101))).unwrap(); + send(&fake, &mut wm, SocketMessage::FocusMonitorNumber(0)).unwrap(); + + send( + &fake, + &mut wm, + SocketMessage::EagerFocus(String::from("firefox")), + ) + .unwrap(); + + assert_eq!(wm.focused_monitor_idx(), 1); + assert_eq!(wm.focused_workspace_idx().unwrap(), 1); + assert_eq!(fake.foreground_window(), Some(32_102)); + assert_eq!(fake.shown_workspace(RIGHT), 1); + assert_eq!(fake.shown_workspace(LEFT), 0); +} diff --git a/komorebi/tests/moving.rs b/komorebi/tests/moving.rs index 9fad1850..41d76346 100644 --- a/komorebi/tests/moving.rs +++ b/komorebi/tests/moving.rs @@ -120,7 +120,9 @@ fn move_towards_a_side_with_no_window_is_an_error_and_moves_nothing() { assert_eq!( result.map_err(|error| error.to_string()), - Err(String::from("there is no container in this direction")) + Err(String::from( + "there is no container or monitor in this direction" + )) ); assert_eq!(order(&wm), [20_011, 20_012]); assert!(fake.commands().is_empty(), "{:?}", fake.commands()); diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 54dac229..08a85caf 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -38,6 +38,15 @@ //! `move-to-last-workspace` and `send-to-last-workspace` to the one that was in front before, //! `focus-workspaces` shows a workspace on every monitor, and `new-workspace` and //! `close-workspace` add a workspace and remove an empty one. +//! - `focus-monitor`, `cycle-monitor` and `focus-monitor-at-cursor` focus another monitor, and +//! `focus-monitor-workspace` a workspace of another monitor; `move-to-monitor`, +//! `send-to-monitor`, their `cycle-` forms, `move-to-monitor-workspace`, +//! `send-to-monitor-workspace`, `move-to-named-workspace` and `send-to-named-workspace` take the +//! focused window to another monitor; `move-workspace-to-monitor`, +//! `cycle-move-workspace-to-monitor` and `swap-workspaces-with-monitor` take workspaces there; +//! `cross-monitor-move-behaviour` and `toggle-cross-monitor-move-behaviour` set what `move` does +//! at the edge of a monitor, and `display-index-preference` gives a monitor an index. +//! `eager-focus` focuses the first window of an executable, on any workspace of any monitor. //! - `workspace-name` names a workspace, which `focus-named-workspace`, `named-workspace-layout` //! and `named-workspace-tiling` find by its name; `workspace-layout` and `workspace-tiling` set //! the layout and the tiling of a workspace by its index, and `ensure-workspaces` and @@ -67,6 +76,7 @@ use komorebi_client::ApplicationIdentifier; use komorebi_client::Axis; use komorebi_client::CycleDirection; use komorebi_client::DefaultLayout; +use komorebi_client::MoveBehaviour; use komorebi_client::OperationBehaviour; use komorebi_client::OperationDirection; use komorebi_client::Rect; @@ -124,14 +134,19 @@ gen_enum_subcommand_args! { CycleMove: CycleDirection, CycleMoveToWorkspace: CycleDirection, CycleSendToWorkspace: CycleDirection, + CycleSendToMonitor: CycleDirection, + CycleMoveToMonitor: CycleDirection, + CycleMonitor: CycleDirection, CycleWorkspace: CycleDirection, CycleEmptyWorkspace: CycleDirection, + CycleMoveWorkspaceToMonitor: CycleDirection, FlipLayout: Axis, ChangeLayout: DefaultLayout, CycleLayout: CycleDirection, // WatchConfiguration: BooleanState, MouseFollowsFocus: BooleanState, Query: StateQuery, + CrossMonitorMoveBehaviour: MoveBehaviour, UnmanagedWindowOperationBehaviour: OperationBehaviour, PromoteWindow: OperationDirection, } @@ -150,10 +165,15 @@ macro_rules! gen_target_subcommand_args { } gen_target_subcommand_args! { + MoveToMonitor, MoveToWorkspace, + SendToMonitor, SendToWorkspace, + FocusMonitor, FocusWorkspace, FocusWorkspaces, + MoveWorkspaceToMonitor, + SwapWorkspacesWithMonitor, } macro_rules! gen_named_target_subcommand_args { @@ -170,6 +190,8 @@ macro_rules! gen_named_target_subcommand_args { } gen_named_target_subcommand_args! { + MoveToNamedWorkspace, + SendToNamedWorkspace, FocusNamedWorkspace, } @@ -396,6 +418,38 @@ struct WorkspaceWorkAreaOffset { bottom: i32, } +#[derive(Parser)] +struct FocusMonitorWorkspace { + /// Target monitor index (zero-indexed) + target_monitor: usize, + /// Workspace index on the target monitor (zero-indexed) + target_workspace: usize, +} + +#[derive(Parser)] +pub struct SendToMonitorWorkspace { + /// Target monitor index (zero-indexed) + target_monitor: usize, + /// Workspace index on the target monitor (zero-indexed) + target_workspace: usize, +} + +#[derive(Parser)] +pub struct MoveToMonitorWorkspace { + /// Target monitor index (zero-indexed) + target_monitor: usize, + /// Workspace index on the target monitor (zero-indexed) + target_workspace: usize, +} + +#[derive(Parser)] +struct DisplayIndexPreference { + /// Preferred monitor index (zero-indexed) + index_preference: usize, + /// Display name as identified in komorebic state + display: String, +} + #[derive(Parser)] struct EnsureWorkspaces { /// Monitor index (zero-indexed) @@ -437,6 +491,12 @@ struct LoadResize { path: PathBuf, } +#[derive(Parser)] +struct EagerFocus { + /// Case-sensitive exe identifier + exe: String, +} + #[derive(Parser)] struct ScrollingLayoutColumns { /// Desired number of visible columns @@ -550,6 +610,9 @@ enum SubCommand { /// Move the focused window in the specified cycle direction #[clap(arg_required_else_help = true)] CycleMove(CycleMove), + /// Focus the first managed window matching the given executable + #[clap(arg_required_else_help = true)] + EagerFocus(EagerFocus), /// Resize the focused window in the specified direction #[clap(arg_required_else_help = true)] #[clap(alias = "resize")] @@ -557,22 +620,51 @@ enum SubCommand { /// Resize the focused window or primary column along the specified axis #[clap(arg_required_else_help = true)] ResizeAxis(ResizeAxis), + /// Move the focused window to the specified monitor + #[clap(arg_required_else_help = true)] + MoveToMonitor(MoveToMonitor), + /// Move the focused window to the monitor in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleMoveToMonitor(CycleMoveToMonitor), /// Move the focused window to the specified workspace #[clap(arg_required_else_help = true)] MoveToWorkspace(MoveToWorkspace), + /// Move the focused window to the specified workspace + #[clap(arg_required_else_help = true)] + MoveToNamedWorkspace(MoveToNamedWorkspace), /// Move the focused window to the workspace in the given cycle direction #[clap(arg_required_else_help = true)] CycleMoveToWorkspace(CycleMoveToWorkspace), + /// Send the focused window to the specified monitor + #[clap(arg_required_else_help = true)] + SendToMonitor(SendToMonitor), + /// Send the focused window to the monitor in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleSendToMonitor(CycleSendToMonitor), /// Send the focused window to the specified workspace #[clap(arg_required_else_help = true)] SendToWorkspace(SendToWorkspace), + /// Send the focused window to the specified workspace + #[clap(arg_required_else_help = true)] + SendToNamedWorkspace(SendToNamedWorkspace), /// Send the focused window to the workspace in the given cycle direction #[clap(arg_required_else_help = true)] CycleSendToWorkspace(CycleSendToWorkspace), + /// Send the focused window to the specified monitor workspace + #[clap(arg_required_else_help = true)] + SendToMonitorWorkspace(SendToMonitorWorkspace), + /// Move the focused window to the specified monitor workspace + #[clap(arg_required_else_help = true)] + MoveToMonitorWorkspace(MoveToMonitorWorkspace), /// Send the focused window to the last focused monitor workspace SendToLastWorkspace, /// Move the focused window to the last focused monitor workspace MoveToLastWorkspace, + /// Focus the specified monitor + #[clap(arg_required_else_help = true)] + FocusMonitor(FocusMonitor), + /// Focus the monitor at the current cursor location + FocusMonitorAtCursor, /// Focus the last focused workspace on the focused monitor FocusLastWorkspace, /// Focus the specified workspace on the focused monitor @@ -581,17 +673,32 @@ enum SubCommand { /// Focus the specified workspace on all monitors #[clap(arg_required_else_help = true)] FocusWorkspaces(FocusWorkspaces), + /// Focus the specified workspace on the target monitor + #[clap(arg_required_else_help = true)] + FocusMonitorWorkspace(FocusMonitorWorkspace), /// Focus the specified workspace #[clap(arg_required_else_help = true)] FocusNamedWorkspace(FocusNamedWorkspace), /// Close the focused workspace (must be empty and unnamed) CloseWorkspace, + /// Focus the monitor in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleMonitor(CycleMonitor), /// Focus the workspace in the given cycle direction #[clap(arg_required_else_help = true)] CycleWorkspace(CycleWorkspace), /// Focus the next empty workspace in the given cycle direction (if one exists) #[clap(arg_required_else_help = true)] CycleEmptyWorkspace(CycleWorkspace), + /// Move the focused workspace to the specified monitor + #[clap(arg_required_else_help = true)] + MoveWorkspaceToMonitor(MoveWorkspaceToMonitor), + /// Move the focused workspace monitor in the given cycle direction + #[clap(arg_required_else_help = true)] + CycleMoveWorkspaceToMonitor(CycleMoveWorkspaceToMonitor), + /// Swap focused monitor workspaces with specified monitor + #[clap(arg_required_else_help = true)] + SwapWorkspacesWithMonitor(SwapWorkspacesWithMonitor), /// Create and append a new workspace on the focused monitor NewWorkspace, /// Set the resize delta (used by resize-edge and resize-axis) @@ -651,6 +758,12 @@ enum SubCommand { PromoteWindow(PromoteWindow), /// Force the retiling of all managed windows Retile, + // /// Set the monitor index preference for a monitor identified using its size + // #[clap(arg_required_else_help = true)] + // MonitorIndexPreference(MonitorIndexPreference), + /// Set the display index preference for a monitor identified using its display name + #[clap(arg_required_else_help = true)] + DisplayIndexPreference(DisplayIndexPreference), /// Create at least this many workspaces for the specified monitor #[clap(arg_required_else_help = true)] EnsureWorkspaces(EnsureWorkspaces), @@ -698,6 +811,11 @@ enum SubCommand { Manage, /// Unmanage a window that was forcibly managed Unmanage, + /// Set the behaviour when moving windows across monitor boundaries + #[clap(arg_required_else_help = true)] + CrossMonitorMoveBehaviour(CrossMonitorMoveBehaviour), + /// Toggle the behaviour when moving windows across monitor boundaries + ToggleCrossMonitorMoveBehaviour, /// Set the operation behavior when the focused window is not managed #[clap(arg_required_else_help = true)] UnmanagedWindowOperationBehaviour(UnmanagedWindowOperationBehaviour), @@ -869,18 +987,36 @@ fn main() -> eyre::Result<()> { SubCommand::FocusWorkspace(args) => { send_message(&SocketMessage::FocusWorkspaceNumber(args.target))?; } + SubCommand::ToggleCrossMonitorMoveBehaviour => { + send_message(&SocketMessage::ToggleCrossMonitorMoveBehaviour)?; + } + SubCommand::FocusMonitor(args) => { + send_message(&SocketMessage::FocusMonitorNumber(args.target))?; + } + SubCommand::FocusMonitorAtCursor => { + send_message(&SocketMessage::FocusMonitorAtCursor)?; + } SubCommand::FocusLastWorkspace => { send_message(&SocketMessage::FocusLastWorkspace)?; } SubCommand::FocusWorkspaces(args) => { send_message(&SocketMessage::FocusWorkspaceNumbers(args.target))?; } + SubCommand::FocusMonitorWorkspace(args) => { + send_message(&SocketMessage::FocusMonitorWorkspaceNumber( + args.target_monitor, + args.target_workspace, + ))?; + } SubCommand::FocusNamedWorkspace(args) => { send_message(&SocketMessage::FocusNamedWorkspace(args.workspace))?; } SubCommand::CloseWorkspace => { send_message(&SocketMessage::CloseWorkspace)?; } + SubCommand::CycleMonitor(args) => { + send_message(&SocketMessage::CycleFocusMonitor(args.cycle_direction))?; + } SubCommand::CycleWorkspace(args) => { send_message(&SocketMessage::CycleFocusWorkspace(args.cycle_direction))?; } @@ -898,28 +1034,77 @@ fn main() -> eyre::Result<()> { SubCommand::ResizeAxis(args) => { send_message(&SocketMessage::ResizeWindowAxis(args.axis, args.sizing))?; } + SubCommand::MoveToMonitor(args) => { + send_message(&SocketMessage::MoveContainerToMonitorNumber(args.target))?; + } + SubCommand::CycleMoveToMonitor(args) => { + send_message(&SocketMessage::CycleMoveContainerToMonitor( + args.cycle_direction, + ))?; + } SubCommand::MoveToWorkspace(args) => { send_message(&SocketMessage::MoveContainerToWorkspaceNumber(args.target))?; } + SubCommand::MoveToNamedWorkspace(args) => { + send_message(&SocketMessage::MoveContainerToNamedWorkspace( + args.workspace, + ))?; + } SubCommand::CycleMoveToWorkspace(args) => { send_message(&SocketMessage::CycleMoveContainerToWorkspace( args.cycle_direction, ))?; } + SubCommand::SendToMonitor(args) => { + send_message(&SocketMessage::SendContainerToMonitorNumber(args.target))?; + } + SubCommand::CycleSendToMonitor(args) => { + send_message(&SocketMessage::CycleSendContainerToMonitor( + args.cycle_direction, + ))?; + } SubCommand::SendToWorkspace(args) => { send_message(&SocketMessage::SendContainerToWorkspaceNumber(args.target))?; } + SubCommand::SendToNamedWorkspace(args) => { + send_message(&SocketMessage::SendContainerToNamedWorkspace( + args.workspace, + ))?; + } SubCommand::CycleSendToWorkspace(args) => { send_message(&SocketMessage::CycleSendContainerToWorkspace( args.cycle_direction, ))?; } + SubCommand::SendToMonitorWorkspace(args) => { + send_message(&SocketMessage::SendContainerToMonitorWorkspaceNumber( + args.target_monitor, + args.target_workspace, + ))?; + } + SubCommand::MoveToMonitorWorkspace(args) => { + send_message(&SocketMessage::MoveContainerToMonitorWorkspaceNumber( + args.target_monitor, + args.target_workspace, + ))?; + } + SubCommand::MoveWorkspaceToMonitor(args) => { + send_message(&SocketMessage::MoveWorkspaceToMonitorNumber(args.target))?; + } + SubCommand::CycleMoveWorkspaceToMonitor(args) => { + send_message(&SocketMessage::CycleMoveWorkspaceToMonitor( + args.cycle_direction, + ))?; + } SubCommand::MoveToLastWorkspace => { send_message(&SocketMessage::MoveContainerToLastWorkspace)?; } SubCommand::SendToLastWorkspace => { send_message(&SocketMessage::SendContainerToLastWorkspace)?; } + SubCommand::SwapWorkspacesWithMonitor(args) => { + send_message(&SocketMessage::SwapWorkspacesToMonitorNumber(args.target))?; + } SubCommand::Retile => { send_message(&SocketMessage::Retile)?; } @@ -983,6 +1168,9 @@ fn main() -> eyre::Result<()> { SubCommand::ManageRule(args) => { send_message(&SocketMessage::ManageRule(args.identifier, args.id))?; } + SubCommand::EagerFocus(args) => { + send_message(&SocketMessage::EagerFocus(args.exe))?; + } SubCommand::NewWorkspace => { send_message(&SocketMessage::NewWorkspace)?; } @@ -1099,6 +1287,17 @@ fn main() -> eyre::Result<()> { send_message(&SocketMessage::LayoutRatios(args.columns, args.rows))?; } } + SubCommand::CrossMonitorMoveBehaviour(args) => { + send_message(&SocketMessage::CrossMonitorMoveBehaviour( + args.move_behaviour, + ))?; + } + SubCommand::DisplayIndexPreference(args) => { + send_message(&SocketMessage::DisplayIndexPreference( + args.index_preference, + args.display, + ))?; + } SubCommand::EnsureWorkspaces(workspaces) => { send_message(&SocketMessage::EnsureWorkspaces( workspaces.monitor, diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 3b98916f..747317dc 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -514,6 +514,86 @@ fn the_named_workspace_subcommands_send_the_names_they_are_given() { ); } +#[test] +fn the_monitor_subcommands_send_what_they_are_given() { + sends( + &["focus-monitor", "1"], + r#"{"type":"FocusMonitorNumber","content":1}"#, + ); + sends( + &["cycle-monitor", "next"], + r#"{"type":"CycleFocusMonitor","content":"Next"}"#, + ); + sends( + &["focus-monitor-at-cursor"], + r#"{"type":"FocusMonitorAtCursor"}"#, + ); + sends( + &["focus-monitor-workspace", "1", "2"], + r#"{"type":"FocusMonitorWorkspaceNumber","content":[1,2]}"#, + ); + sends( + &["move-to-monitor", "1"], + r#"{"type":"MoveContainerToMonitorNumber","content":1}"#, + ); + sends( + &["send-to-monitor", "0"], + r#"{"type":"SendContainerToMonitorNumber","content":0}"#, + ); + sends( + &["cycle-move-to-monitor", "previous"], + r#"{"type":"CycleMoveContainerToMonitor","content":"Previous"}"#, + ); + sends( + &["cycle-send-to-monitor", "next"], + r#"{"type":"CycleSendContainerToMonitor","content":"Next"}"#, + ); + sends( + &["move-to-monitor-workspace", "1", "0"], + r#"{"type":"MoveContainerToMonitorWorkspaceNumber","content":[1,0]}"#, + ); + sends( + &["send-to-monitor-workspace", "0", "1"], + r#"{"type":"SendContainerToMonitorWorkspaceNumber","content":[0,1]}"#, + ); + sends( + &["move-to-named-workspace", "mail"], + r#"{"type":"MoveContainerToNamedWorkspace","content":"mail"}"#, + ); + sends( + &["send-to-named-workspace", "mail"], + r#"{"type":"SendContainerToNamedWorkspace","content":"mail"}"#, + ); + sends( + &["move-workspace-to-monitor", "1"], + r#"{"type":"MoveWorkspaceToMonitorNumber","content":1}"#, + ); + sends( + &["cycle-move-workspace-to-monitor", "next"], + r#"{"type":"CycleMoveWorkspaceToMonitor","content":"Next"}"#, + ); + sends( + &["swap-workspaces-with-monitor", "1"], + r#"{"type":"SwapWorkspacesToMonitorNumber","content":1}"#, + ); + sends( + &["cross-monitor-move-behaviour", "insert"], + r#"{"type":"CrossMonitorMoveBehaviour","content":"Insert"}"#, + ); + sends( + &["toggle-cross-monitor-move-behaviour"], + r#"{"type":"ToggleCrossMonitorMoveBehaviour"}"#, + ); + sends( + &["display-index-preference", "1", "DP-2"], + r#"{"type":"DisplayIndexPreference","content":[1,"DP-2"]}"#, + ); + sends( + &["eager-focus", "firefox"], + r#"{"type":"EagerFocus","content":"firefox"}"#, + ); +} + #[test] fn without_a_daemon_a_question_fails() { let runtime = Runtime::new(); @@ -562,18 +642,28 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "close.md", "completions.md", "container-padding.md", + "cross-monitor-move-behaviour.md", "cycle-empty-workspace.md", "cycle-focus.md", "cycle-layout.md", + "cycle-monitor.md", + "cycle-move-to-monitor.md", "cycle-move-to-workspace.md", + "cycle-move-workspace-to-monitor.md", "cycle-move.md", + "cycle-send-to-monitor.md", "cycle-send-to-workspace.md", "cycle-workspace.md", "data-directory.md", + "display-index-preference.md", + "eager-focus.md", "ensure-named-workspaces.md", "ensure-workspaces.md", "flip-layout.md", "focus-last-workspace.md", + "focus-monitor-at-cursor.md", + "focus-monitor-workspace.md", + "focus-monitor.md", "focus-named-workspace.md", "focus-workspace.md", "focus-workspaces.md", @@ -593,7 +683,11 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "monitor-work-area-offset.md", "mouse-follows-focus.md", "move-to-last-workspace.md", + "move-to-monitor-workspace.md", + "move-to-monitor.md", + "move-to-named-workspace.md", "move-to-workspace.md", + "move-workspace-to-monitor.md", "move.md", "named-workspace-layout.md", "named-workspace-tiling.md", @@ -613,6 +707,9 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "save-resize.md", "scrolling-layout-columns.md", "send-to-last-workspace.md", + "send-to-monitor-workspace.md", + "send-to-monitor.md", + "send-to-named-workspace.md", "send-to-workspace.md", "session-float-rule.md", "session-float-rules.md", @@ -620,6 +717,8 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "state.md", "stop.md", "subscribe-socket.md", + "swap-workspaces-with-monitor.md", + "toggle-cross-monitor-move-behaviour.md", "toggle-float.md", "toggle-lock.md", "toggle-mouse-follows-focus.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index e57dd17a..d2d3a711 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -229,6 +229,35 @@ workspace-layout 0 0 columns workspace-layout 0 0 bsp named-workspace-layout one columns named-workspace-layout one bsp +focus-monitor 1 +focus-monitor 0 +cycle-monitor next +cycle-monitor previous +focus-monitor-workspace 1 1 +focus-monitor-workspace 0 0 +focus-monitor-at-cursor +focus-monitor 0 +send-to-named-workspace two +focus-named-workspace two +move-to-named-workspace one +focus-named-workspace one +send-to-monitor 1 +focus-monitor 1 +move-to-monitor 0 +focus-monitor 0 +cycle-send-to-monitor next +focus-monitor 1 +cycle-move-to-monitor next +focus-monitor 0 +send-to-monitor-workspace 1 1 +focus-monitor-workspace 1 1 +move-to-monitor-workspace 0 0 +focus-monitor 0 +focus-workspace 0 +move-workspace-to-monitor 1 +cycle-move-workspace-to-monitor next +swap-workspaces-with-monitor 1 +swap-workspaces-with-monitor 1 global-work-area-offset 10 10 20 20 global-work-area-offset 0 0 0 0 monitor-work-area-offset 0 10 10 20 20 @@ -249,9 +278,14 @@ container-padding 0 0 12 container-padding 0 0 10 workspace-padding 0 0 12 workspace-padding 0 0 10 +cross-monitor-move-behaviour insert +cross-monitor-move-behaviour swap +toggle-cross-monitor-move-behaviour +toggle-cross-monitor-move-behaviour unmanaged-window-operation-behaviour op unmanaged-window-operation-behaviour no-op unmanaged-window-operation-behaviour op +display-index-preference 0 Virtual-0 mouse-follows-focus enable mouse-follows-focus disable toggle-mouse-follows-focus @@ -265,6 +299,7 @@ manage-rule exe nonexistent manage close retile +eager-focus foot """ for line in SWEEP.strip().splitlines(): status, out = kde.run(shlex.join(["komorebic", *line.split()]))