feat(kwin): focus follows mouse through KWin's focus policy

KWin has a focus policy that gives the focus to the window under the pointer, so
komorebi asks for it and follows where the focus goes, as it does for any change
of focus. Both implementations komorebi for Windows names are the same thing
here. The KWin backend sets the focus policy and no delay in the user's kwinrc
and has KWin read it, and puts the two keys back as the user had them when it is
turned off and, with every other setting, when komorebi exits. The state of the
daemon says whether it is on.

komorebic gets focus-follows-mouse and toggle-focus-follows-mouse. The session
node gets a pointer that a test drives from inside the guest: the program
komorebi-pointer makes an absolute device with uinput, and komorebi_vm.Pointer
sends it commands. vm-focus-follows-mouse moves it over each of two windows and
checks the focus, then the policy that is put back.

komorebi.json takes focus_follows_mouse, which is on with Windows or Komorebi,
and a file that leaves it out turns it off and gives the user's focus policy
back.

Loading a configuration asks the backend for the focus policy now, so the tests
that load one do it with a backend installed.
This commit is contained in:
LGUG2Z committed 2026-10-28 07:20:49 -07:00
1 parent fa1e822e44
commit 9a0693f5d1
37 files changed
+1140 -25

No files matched your search

+2 -1
View File
@@ -262,7 +262,8 @@ window, the others, a locked container, a floating window. `border`, `border-col
animated by another effect, Geometry Change, which `animation`,
`animation-duration` and `animation-style` turn on and set. `transparency` makes
the windows that do not have the focus see-through, by the opacity KWin gives a
window.
window, and `focus-follows-mouse` has KWin give the focus to the window under the
pointer, by its own focus policy.
## Documentation
+26 -2
View File
@@ -843,6 +843,20 @@ stops, [`transparency_manager::restore`] makes every window it changed opaque ag
effect draws a window from a texture that has its opacity in it, and the build komorebi installs
draws it again when the opacity changes ([PLATFORM.md](PLATFORM.md#the-patches)).
## Focus follows mouse
The window under the pointer has the focus when the compositor's focus policy says so, and the
compositor does it. `FocusFollowsMouse` and `ToggleFocusFollowsMouse` set
[`WindowManager::focus_follows_mouse`] (the implementation that was asked for, or none) and ask the
backend ([`Backend::set_focus_follows_mouse`]); whichever of the two implementations is named, on
KDE it is the compositor's own policy. The KWin backend writes `FocusPolicy=1` and
`DelayFocusInterval=0` into the `[Windows]` group of the user's `kwinrc` through [`Kwinrc`], which
records the first value of each key, and asks KWin to reload; turning it off puts those two keys
back ([`Kwinrc::restore_keys`]) and leaves `PerOutputVirtualDesktops`, which is in the same group,
as it is. `shutdown` puts back everything. The focus the compositor gives is an event like the
others: the window manager follows it, and [`State`] says whether focus follows mouse is on.
[DESIGN.md](DESIGN.md#why-is-focus-follows-mouse-kwins-own-focus-policy) has the reasons.
## The NixOS module
The flake exports one module under two names, `nixosModules.default` and
@@ -1094,6 +1108,10 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
| The `transparency` keys of the file are the settings, and a key the file leaves out has the default | framework path: `StaticConfig::apply_globals` stores `transparency` and `transparency_alpha` whether the file has them or not, and adds the ignore rules to `TRANSPARENCY_BLACKLIST` | `the_transparency_keys_of_the_file_are_the_transparency_settings` | none |
| A window komorebi made see-through is opaque again when komorebi exits | framework path: [`WindowManager::stop`] and `main.rs` call [`transparency_manager::restore`] | `what_komorebi_made_see_through_is_opaque_again_when_it_exits` | `SIGKILL`: the windows stay as they were drawn |
| What the backend sends for an opacity is what the bridge sets | tests: the `opacity` command of [`fixtures`] is what the backend's test sends and what the bridge's test answers with, checking the window's `opacity` | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a window is given the opacity it is asked for, and one KWin has not got is given back` | none |
| The user's focus policy is put back when focus follows mouse is turned off and when komorebi exits | framework path: [`Kwinrc`] records the first value of each key it sets, `set_focus_follows_mouse(false)` puts the two keys back with [`Kwinrc::restore_keys`] and `shutdown` puts back all | `one_key_can_be_put_back_while_the_others_in_its_group_stay_changed`, `what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed`, `vm-focus-follows-mouse` | `SIGKILL`: the next run puts it back when it stops |
| Focus follows mouse is the compositor's, whichever implementation is named | framework path: the `FocusFollowsMouse` and `ToggleFocusFollowsMouse` arms ask the backend the same thing for both | `focus_follows_mouse_is_asked_of_the_compositor_and_toggles` | none |
| The `focus_follows_mouse` key of the file turns it on, and a file that leaves it out turns it off | framework path: `StaticConfig::postload` and `StaticConfig::reload` set the window manager's field from the file and ask the backend for it | `the_file_turns_focus_follows_mouse_on_and_a_file_that_leaves_it_out_turns_it_off` | none |
| The window under the pointer has the focus, and komorebi follows | the compositor's focus policy; the window manager follows the focus event as any other | `vm-focus-follows-mouse` (a real pointer over each window) | none |
| The effect komorebi loaded is unloaded, and the user's settings of it are put back, when komorebi stops using it or exits | framework path: the effect's state unloads what komorebi loaded, and [`Kwinrc`] puts the group back | `one_group_can_be_put_back_while_the_others_stay_changed`, `vm-look` | `SIGKILL`: the next run puts the settings back when it stops |
| Queries never block on the compositor | convention only | none | the KWin backend's `cursor_pos` waits up to 250 ms |
| Only the backend module reaches the compositor | convention only | none | none |
@@ -1229,7 +1247,8 @@ A window is shown, and ends up on a tile:
[`komorebi/tests/animation.rs`](../../komorebi/tests/animation.rs), the messages that set the
animation, [`komorebi/tests/animation_config.rs`](../../komorebi/tests/animation_config.rs), its
key of the file, and [`komorebi/tests/animation_stack.rs`](../../komorebi/tests/animation_stack.rs),
the stack commands that turn it off; [`komorebi/tests/transparency.rs`](../../komorebi/tests/transparency.rs)
the stack commands that turn it off; [`komorebi/tests/focus_follows_mouse.rs`](../../komorebi/tests/focus_follows_mouse.rs),
focus follows mouse; [`komorebi/tests/transparency.rs`](../../komorebi/tests/transparency.rs)
and [`komorebi/tests/transparency_config.rs`](../../komorebi/tests/transparency_config.rs),
transparency and its keys of the file; [`komorebi/tests/border_colours.rs`](../../komorebi/tests/border_colours.rs) and
[`komorebi/tests/borders_off.rs`](../../komorebi/tests/borders_off.rs), the color of each
@@ -1237,7 +1256,9 @@ A window is shown, and ends up on a tile:
[`nix/tests/vm/suites/look`](../../nix/tests/vm/suites/look/test.py), the border in a real
Plasma session, read from the pixels of a screenshot, and
[`nix/tests/vm/suites/features`](../../nix/tests/vm/suites/features/test.py), the colors of the
kinds of window.
kinds of window; [`nix/tests/vm/suites/focus-follows-mouse`](../../nix/tests/vm/suites/focus-follows-mouse/test.py),
focus follows mouse with a real pointer, which [`Pointer`](../../nix/tests/vm/lib/komorebi_vm/pointer.py)
moves from inside the guest.
- [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager
driven end to end against the fake.
- [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket,
@@ -1322,6 +1343,9 @@ A window is shown, and ends up on a tile:
[`border_manager::send_notification`]: ../../komorebi/src/border_manager/mod.rs
[`BORDER_DRAWN`]: ../../komorebi/src/border_manager/mod.rs
[`animation`]: ../../komorebi/src/animation/mod.rs
[`WindowManager::focus_follows_mouse`]: ../../komorebi/src/window_manager.rs
[`Backend::set_focus_follows_mouse`]: ../../komorebi/src/backend/mod.rs
[`Kwinrc::restore_keys`]: ../../komorebi/src/kwin/kwinrc.rs
[`transparency_manager`]: ../../komorebi/src/transparency_manager.rs
[`transparency_manager::apply`]: ../../komorebi/src/transparency_manager.rs
[`transparency_manager::transparent_windows`]: ../../komorebi/src/transparency_manager.rs
+12
View File
@@ -469,6 +469,18 @@ the opacity it gave each window that is not opaque (`WindowManager::opacity_appl
difference, makes a window opaque again when it should no longer be see-through (and only if it is
still there), and makes every one opaque when it stops.
## Why is focus follows mouse KWin's own focus policy?
Because KWin has one, and gives the focus to the window under the pointer by itself. komorebi
asks for it by changing the user's `FocusPolicy` and follows the focus, as it follows any change
of focus, and puts the policy back when focus follows mouse is turned off and when it exits
([PLATFORM.md](PLATFORM.md#files-and-directories)). Both implementations komorebi for Windows
names, `Windows` and `Komorebi`, ask KWin for the same thing. Upstream marks the Windows key
end-of-life in favor of masir, a separate program. The code also sets `DelayFocusInterval` to 0,
which is KWin's setting for no delay between the pointer entering a window and the window being
given the focus; why 0 and not the delay KWin has by default is not written down, and needs a
reason.
## Why are the effects patched?
Because the stock effects lack what komorebi needs of them. Each patch leaves the effect
+10 -7
View File
@@ -142,7 +142,9 @@ sends another window there.
When borders are on, it also asks KWin to load KDE Rounded Corners, the effect that draws them,
after writing the effect's settings into `kwinrc`, and asks it to read them again
([KWin effects](#kwin-effects)). It does the same with Geometry Change, the effect that animates
windows, when animation is on. An effect KWin did not find is reported once in the log.
windows, when animation is on. An effect KWin did not find is reported once in the log. When focus
follows mouse is turned on, it sets KWin's focus policy in `kwinrc` (`[Windows] FocusPolicy=1`,
`DelayFocusInterval=0`) and asks KWin to reload its configuration.
Every command of the window manager (move and resize, focus, raise, hide or restore, minimize,
bring back, maximize, unmaximize or close a window, show a workspace on an output, put a window
@@ -171,12 +173,12 @@ an owner again; the VM test `vm-kwin-restart` restarts KWin twice under a runnin
When it is stopped with `SIGINT`, `SIGTERM` or a `Stop` message on its socket, it brings back
the windows it hid, waits until the commands that do so have reached the bridge, removes the
parking desktop, unloads the effects it loaded, puts back the values the keys it set in `kwinrc`
had (`PerOutputVirtualDesktops`, and the keys of the effects), or removes a key the user had not
set, and asks KWin to reload its configuration, asks KWin to unload the script, closes an empty
connection to each subscriber, and removes the socket. The desktops it created for workspaces
stay: they are the user's desktops from then on. A `StopIgnoreRestore` message stops it the same
way, except that it does not bring the windows back: the parking desktop is removed all the same.
The file `bridge.js` stays in the runtime
had (`PerOutputVirtualDesktops`, the focus policy, and the keys of the effects), or removes a key
the user had not set, and asks KWin to reload its configuration, asks KWin to unload the script,
closes an empty connection to each subscriber, and removes the socket. The desktops it created for
workspaces stay: they are the user's desktops from then on. A `StopIgnoreRestore` message stops it
the same way, except that it does not bring the windows back: the parking desktop is removed all
the same. The file `bridge.js` stays in the runtime
directory, which is removed at logout. A daemon that is killed leaves the script running in
KWin, reporting to nobody, the socket file in the runtime directory, per-output desktops
on, and the parking desktop with the hidden windows on it, until the next start replaces the
@@ -243,6 +245,7 @@ since a read right after `createDesktop` has to see the new desktop.
| `$KOMOREBI_CONFIG_HOME/komorebi.json` (`~/.config/komorebi/komorebi.json`) | komorebi's configuration, which komorebi never writes: read when the daemon starts, and again when it changes. `--config` names another file | the user's |
| `$XDG_CONFIG_HOME/autostart/komorebi.desktop` (`~/.config/autostart/komorebi.desktop`) | the XDG autostart entry `komorebic enable-autostart` writes: `Exec=komorebi`, or `komorebi --config "FILE"`, and `X-KDE-autostart-after=plasma-workspace`, which a Plasma session starts komorebi from at login | the user's; `komorebic disable-autostart` removes it |
| `$XDG_CONFIG_HOME/kwinrc` (`~/.config/kwinrc`) | KWin's configuration: komorebi sets `PerOutputVirtualDesktops=true` in `[Windows]`, changing that line or adding it and nothing else, and writes the file beside it first and renames it over it | put back as it was when the daemon stops |
| `$XDG_CONFIG_HOME/kwinrc`, group `[Windows]`, keys `FocusPolicy` and `DelayFocusInterval` | `1` and `0` while focus follows mouse is on: KWin's "focus follows mouse" policy, which KWin takes when it is asked to reconfigure | put back, without the other keys of the group, when focus follows mouse is turned off, and with everything else when the daemon stops |
| `$XDG_CONFIG_HOME/kwinrc`, group `[Round-Corners]` | the settings of the border effect, written when borders are on ([KWin effects](#kwin-effects)) | put back, with the rest of `kwinrc`, when borders are turned off and when the daemon stops |
| `$XDG_CONFIG_HOME/kwinrc`, group `[Effect-kwin4_effect_geometry_change]` | the settings of the animation effect, written when animation is on | put back as above, when animation is turned off and when the daemon stops |
| `$XDG_RUNTIME_DIR/komorebi/kwinrc-backup.json` | the value each key of `kwinrc` had before komorebi first changed it | removed when the values are put back; one a crash left behind is used by the next run |
+12
View File
@@ -88,6 +88,9 @@ display device: the `virtio-gpu-pci` that the test driver adds to every aarch64
guest, and the default VGA of an x86_64 one. The node sets
`komorebi.vm.renderNode` to false, so that an x86_64 guest does not get a second
device: KWin would draw on it, and the screenshot would show the other one.
The node also has uinput, with the test user in the group `uinput`, and the
program `komorebi-pointer`, which makes a pointer device with it: a test drives
the pointer from inside the guest, and KWin takes it as a tablet.
On aarch64 under HVF, at time of writing (2026-10-27), the session has the
Wayland socket after 11 to 19 seconds and a painted desktop after 35 seconds.
@@ -166,6 +169,15 @@ the run.
- `monitor_bridge(path)` records the bridge's traffic on the session bus with
`dbus-monitor`, and `latency.rounds` times each batch of commands in it, from
the daemon's answer to the last frame KWin reports for the windows it moved.
- `Pointer.start(machine, (width, height), scale=)` starts `komorebi-pointer` on
a session node, for a screen of that size, and `move(x, y)`, `down()`, `up()`,
`glide(x, y, steps, ms)` and `drag(start, end)` move and click it. Each
returns once the program has done it, and a glide's moves are made in the
guest, milliseconds apart: moves that each wait for the test are seconds
apart, and KWin was seen to lose the horizontal part of such a drag. The
pointer lands within a pixel of where it is asked. The program itself is
[`komorebi_vm/uinput.py`](../../nix/tests/vm/lib/komorebi_vm/uinput.py),
whose arithmetic the `vm-lib` check tests.
Poll for what the test needs with `wait_for`. A fixed sleep is too long on
KVM and too short on TCG.
+2 -1
View File
@@ -62,7 +62,8 @@ configuration of a running daemon.
[Borders](usage/borders.md) explains how komorebi has KWin draw a border around each window,
[Animation](usage/animation.md) how it has KWin animate the windows going to their places, and
[Transparency](usage/transparency.md) how it makes the windows that do not have the focus
see-through.
see-through, and [Focus follows mouse](usage/focus-follows-mouse.md) how it has KWin give the focus
to the window under the pointer.
[Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program
such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page
for every `komorebic` command, generated from its help.
+1
View File
@@ -66,6 +66,7 @@ how another platform draws or hides windows, are accepted: `titleless_applicatio
| Key | Default | What it does |
|---|---|---|
| `resize_delta` | `50` | How many pixels `resize-edge` and `resize-axis` resize by |
| `focus_follows_mouse` | none | `Windows` or `Komorebi` to have KWin give the focus to the window under the pointer ([Focus follows mouse](focus-follows-mouse.md)); the two are the same on KDE. Left out, KWin's focus policy is the user's own |
| `mouse_follows_focus` | `true` | Whether the pointer goes to the window that is given the focus |
| `cross_monitor_move_behaviour` | `Swap` | What `move` does at the edge of a monitor: `Swap`, `Insert` or `NoOp` |
| `cross_boundary_behaviour` | `Monitor` | Where `focus` and `move` go at the edge of a monitor: to the next `Monitor` or the next `Workspace` |
+51
View File
@@ -0,0 +1,51 @@
# Focus follows mouse
With focus follows mouse, the window under the pointer is the window that has the focus: moving the
pointer into another window gives that window the focus, with no click. komorebi does not do this
itself. It asks KWin to, by changing KWin's own focus policy, and follows where the focus goes like
it follows any other change of focus.
## Turning it on and off
`komorebic focus-follows-mouse` turns it on or off, and `komorebic toggle-focus-follows-mouse`
switches it. It is off by default: KWin's focus policy is the user's own until komorebi changes
it.
```sh
komorebic focus-follows-mouse enable
komorebic focus-follows-mouse disable
komorebic toggle-focus-follows-mouse
```
Both take `--implementation`, `windows` (the default) or `komorebi`, the two that komorebi for
Windows has. On KDE they are the same: both ask KWin for its own focus policy, and which one was
asked for is only remembered, in the `focus_follows_mouse` of the daemon's state.
## In komorebi.json
The `focus_follows_mouse` key of [`komorebi.json`](configuration.md#settings-of-the-daemon) is
`"Windows"` or `"Komorebi"` to turn it on, which is what `--implementation` names, and has no value
or is left out to leave it off:
```json
{
"focus_follows_mouse": "Windows"
}
```
The file sets it when the daemon starts and when the file changes, and a file that leaves it out
turns it off and gives the user's focus policy back, also when it was turned on with a command.
## What it does to KWin
Turning it on sets two keys in the group `[Windows]` of the user's `kwinrc`, `FocusPolicy=1`
("focus follows mouse") and `DelayFocusInterval=0`, and asks KWin to read its configuration
again. Turning it off, and exiting komorebi, put back what the user had: the value each key
had before komorebi changed it, or no value if the key was not there. A daemon that was killed
leaves the keys changed until the next run, whose exit puts them back.
## The pointer follows the focus too
[`komorebic mouse-follows-focus`](../cli/mouse-follows-focus.md) is the other direction: the pointer
goes to the middle of the window that is given the focus. With both on, the pointer and the focus
stay in the same window.
+10
View File
@@ -72,6 +72,8 @@ pub enum Command {
BorderColours(Vec<(u32, u32)>),
/// [`Backend::set_opacity`]: the window, and how opaque it was asked to be.
SetOpacity(u32, u8),
/// [`Backend::set_focus_follows_mouse`]: whether it was turned on or off.
FocusFollowsMouse(bool),
}
#[derive(Default)]
@@ -614,6 +616,14 @@ impl Backend for FakeBackend {
Ok(state.borders_drawn && look.border.is_some())
}
fn set_focus_follows_mouse(&self, enable: bool) -> eyre::Result<()> {
self.state
.lock()
.commands
.push(Command::FocusFollowsMouse(enable));
Ok(())
}
fn set_opacity(&self, id: u32, alpha: u8) -> eyre::Result<()> {
self.record(id, Command::SetOpacity(id, alpha), |state| {
state.opacity.insert(id, alpha);
+24
View File
@@ -467,6 +467,30 @@ pub trait Backend: Send + Sync + 'static {
Ok(())
}
/// Asks the compositor to give the focus to the window under the pointer, as the pointer moves
/// (`true`), or to stop doing that and go back to the focus policy the user had (`false`). The
/// default does nothing.
///
/// # Errors
///
/// When the compositor's configuration cannot be changed.
///
/// # Example
///
/// ```rust
/// use komorebi::backend::Backend;
/// use komorebi::backend::fake::Command;
/// use komorebi::backend::fake::FakeBackend;
///
/// let fake = FakeBackend::with_one_monitor();
/// fake.set_focus_follows_mouse(true)?;
/// assert_eq!(fake.commands(), [Command::FocusFollowsMouse(true)]);
/// # Ok::<(), color_eyre::eyre::Report>(())
/// ```
fn set_focus_follows_mouse(&self, _enable: bool) -> eyre::Result<()> {
Ok(())
}
// ---- provided ------------------------------------------------------------------------------
/// Called once as komorebi exits, after the window manager has put back what it moved, so that
+4
View File
@@ -518,6 +518,10 @@ pub enum SocketMessage {
VisibleWindows,
MonitorInformation,
Query(StateQuery),
FocusFollowsMouse(FocusFollowsMouseImplementation, bool),
ToggleFocusFollowsMouse(FocusFollowsMouseImplementation),
// FocusFollowsMouse(FocusFollowsMouseImplementation, bool),
// ToggleFocusFollowsMouse(FocusFollowsMouseImplementation),
MouseFollowsFocus(bool),
ToggleMouseFollowsFocus,
// RemoveTitleBar(ApplicationIdentifier, String),
+78 -1
View File
@@ -1,5 +1,5 @@
//! KWin's configuration file, `kwinrc`, for the few settings komorebi changes: per-output virtual
//! desktops and the settings of the border and animation effects.
//! desktops, the focus policy, and the settings of the border and animation effects.
//!
//! These are the user's settings, changed on their behalf, so [`Kwinrc::set`] records the value of
//! every key the first time komorebi changes it, in a backup file, and [`Kwinrc::restore`] puts the
@@ -23,6 +23,7 @@
//! | A crash loses none of the recorded values | the backup file, read by the next run | `kwin::kwinrc::tests::a_backup_left_by_a_crash_keeps_the_values_from_before_the_first_run` |
//! | Only the line of the key changes; the rest of the file is left as it was | [`ini_set`], [`ini_unset`] | `kwin::kwinrc::tests::a_key_is_set_in_place_added_to_its_group_or_given_a_group`, `kwin::kwinrc::tests::a_key_is_removed_from_its_own_group_only` |
//! | One group can be put back while the others stay changed | [`Kwinrc::restore_group`] | `kwin::kwinrc::tests::one_group_can_be_put_back_while_the_others_stay_changed` |
//! | Some keys of a group can be put back while the others stay changed | [`Kwinrc::restore_keys`] | `kwin::kwinrc::tests::one_key_can_be_put_back_while_the_others_in_its_group_stay_changed` |
//! | KWin never reads a half-written file | [`Kwinrc`] writes a file beside `kwinrc` and renames it over it | no test |
#![deny(missing_docs)]
@@ -187,6 +188,52 @@ impl Kwinrc {
Ok(true)
}
/// Puts back these keys of one group, leaving the rest of what [`Kwinrc::set`] changed as it
/// is, and returns true if and only if [`Kwinrc::set`] changed any of them.
///
/// `[Windows]` has both the focus policy and per-output desktops, which are turned off at
/// different times.
///
/// # Errors
///
/// Returns an error if `kwinrc` or the backup cannot be written.
pub fn restore_keys(&self, group: &str, wanted: &[&str]) -> io::Result<bool> {
let mut backup = self.read_backup();
let Some(keys) = backup.originals.get_mut(group) else {
return Ok(false);
};
let taken: Vec<(String, Option<String>)> = wanted
.iter()
.filter_map(|key| {
keys.remove(*key)
.map(|original| ((*key).to_string(), original))
})
.collect();
if taken.is_empty() {
return Ok(false);
}
if keys.is_empty() {
backup.originals.remove(group);
}
let mut text = std::fs::read_to_string(&self.path).unwrap_or_default();
for (key, original) in &taken {
text = match original {
Some(value) => ini_set(&text, group, key, value),
None => ini_unset(&text, group, key),
};
}
self.write_file(&text)?;
if backup.originals.is_empty() {
let _ = std::fs::remove_file(&self.backup);
} else {
self.write_backup(&backup)?;
}
Ok(true)
}
/// Returns the backup, or an empty one when there is no backup file or it cannot be read.
fn read_backup(&self) -> Backup {
std::fs::read_to_string(&self.backup)
@@ -480,4 +527,34 @@ mod tests {
assert!(!d.join("backup.json").exists());
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn one_key_can_be_put_back_while_the_others_in_its_group_stay_changed() {
let d = dir("keys");
let rc = Kwinrc::new(d.join("kwinrc"), d.join("backup.json"));
std::fs::write(d.join("kwinrc"), "[Windows]\nFocusPolicy=0\n").unwrap();
rc.set("Windows", &[("FocusPolicy", "1".into())]).unwrap();
rc.set("Windows", &[("PerOutputVirtualDesktops", "true".into())])
.unwrap();
assert!(rc.restore_keys("Windows", &["FocusPolicy"]).unwrap());
let text = std::fs::read_to_string(d.join("kwinrc")).unwrap();
assert_eq!(
ini_value(&text, "Windows", "FocusPolicy").as_deref(),
Some("0")
);
assert!(rc.is_on("Windows", "PerOutputVirtualDesktops"));
// nothing of it left to put back, and the other key still can be
assert!(!rc.restore_keys("Windows", &["FocusPolicy"]).unwrap());
assert!(rc.restore().unwrap());
let text = std::fs::read_to_string(d.join("kwinrc")).unwrap();
assert_eq!(
ini_value(&text, "Windows", "PerOutputVirtualDesktops"),
None
);
assert!(!d.join("backup.json").exists());
let _ = std::fs::remove_dir_all(&d);
}
}
+26
View File
@@ -909,6 +909,32 @@ impl Backend for KWinBackend {
)
}
fn set_focus_follows_mouse(&self, enable: bool) -> eyre::Result<()> {
let shared = self.shared.clone();
self.shared.block_on(async move {
let Some(kwinrc) = &shared.kwinrc else {
eyre::bail!("there is no configuration directory to find kwinrc in");
};
if enable {
kwinrc.set(
"Windows",
&[
("FocusPolicy", "1".to_string()),
("DelayFocusInterval", "0".to_string()),
],
)?;
} else {
kwinrc.restore_keys("Windows", &["FocusPolicy", "DelayFocusInterval"])?;
}
let connection = shared.connection().await?;
kwin_reconfigure(&connection).await;
Ok(())
})?
}
fn set_border_colours(&self, colours: &[(u32, u32)]) -> eyre::Result<bool> {
let shared = self.shared.clone();
+14
View File
@@ -176,6 +176,10 @@
//! **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.
//! - **FocusFollowsMouse** and **ToggleFocusFollowsMouse** set whether the compositor gives the
//! focus to the window under the pointer, as the pointer moves: KWin's own focus policy, whichever
//! of the two implementations is named, put back when it is turned off and when komorebi exits
//! ([`Backend::set_focus_follows_mouse`](crate::backend::Backend::set_focus_follows_mouse)).
//! - **Border** sets whether the compositor draws a border around each window, and **BorderWidth**
//! and **BorderOffset** the room the layout leaves for it: each asks the backend for the look
//! again ([`border_manager::send_notification`]), as does every message once it has been
@@ -1063,6 +1067,16 @@ impl WindowManager {
SocketMessage::EnsureNamedWorkspaces(monitor_idx, ref names) => {
self.ensure_named_workspaces_for_monitor(monitor_idx, names)?;
}
SocketMessage::FocusFollowsMouse(implementation, enable) => {
// KWin does this, whichever of the two was asked for
self.focus_follows_mouse = enable.then_some(implementation);
backend().set_focus_follows_mouse(enable)?;
}
SocketMessage::ToggleFocusFollowsMouse(implementation) => {
let enable = self.focus_follows_mouse.is_none();
self.focus_follows_mouse = enable.then_some(implementation);
backend().set_focus_follows_mouse(enable)?;
}
SocketMessage::ToggleMonocle => self.toggle_monocle()?,
SocketMessage::ToggleMaximize => self.toggle_maximize()?,
SocketMessage::ToggleFloat => self.toggle_float(false)?,
+9 -2
View File
@@ -18,6 +18,7 @@ use crate::IGNORE_IDENTIFIERS;
use crate::MANAGE_IDENTIFIERS;
use crate::TRANSPARENCY_BLACKLIST;
use crate::WORKSPACE_MATCHING_RULES;
use crate::core::FocusFollowsMouseImplementation;
use crate::core::MonocleFocusBehaviour;
use crate::core::MoveBehaviour;
use crate::core::OperationBehaviour;
@@ -161,6 +162,7 @@ pub struct State {
pub monocle_focus_behaviour: MonocleFocusBehaviour,
pub unmanaged_window_operation_behaviour: OperationBehaviour,
pub work_area_offset: Option<Rect>,
pub focus_follows_mouse: Option<FocusFollowsMouseImplementation>,
pub mouse_follows_focus: bool,
}
@@ -244,6 +246,7 @@ impl From<&WindowManager> for State {
float_override: wm.window_management_behaviour.float_override,
cross_monitor_move_behaviour: wm.cross_monitor_move_behaviour,
monocle_focus_behaviour: wm.monocle_focus_behaviour,
focus_follows_mouse: wm.focus_follows_mouse,
mouse_follows_focus: wm.mouse_follows_focus,
unmanaged_window_operation_behaviour: wm.unmanaged_window_operation_behaviour,
}
@@ -253,8 +256,8 @@ impl From<&WindowManager> for State {
impl State {
/// Returns true if and only if the window manager's monitors (with their workspaces,
/// containers and windows), whether it is paused, its new window behavior, its float override,
/// its monocle focus behavior, its unmanaged window operation behavior, its work area offset
/// or its mouse follows focus setting differ from this state's
/// its monocle focus behavior, its unmanaged window operation behavior, its work area offset,
/// or its focus follows mouse or mouse follows focus setting differ from this state's
///
/// A window is compared by its id only, so a window that moved or was renamed is not a
/// change.
@@ -293,6 +296,10 @@ impl State {
return true;
}
if self.focus_follows_mouse != new.focus_follows_mouse {
return true;
}
if self.mouse_follows_focus != new.mouse_follows_focus {
return true;
}
+18
View File
@@ -47,11 +47,13 @@ use crate::animation::ANIMATION_STYLE_GLOBAL;
use crate::animation::ANIMATION_STYLE_PER_ANIMATION;
use crate::animation::DEFAULT_ANIMATION_FPS;
use crate::animation::PerAnimationPrefixConfig;
use crate::backend::backend;
use crate::border_manager;
use crate::core::Axis;
use crate::core::CrossBoundaryBehaviour;
use crate::core::DefaultLayout;
use crate::core::FloatingLayerBehaviour;
use crate::core::FocusFollowsMouseImplementation;
use crate::core::Layout;
use crate::core::LayoutDefaultEntry;
use crate::core::LayoutOptions;
@@ -412,6 +414,10 @@ pub struct StaticConfig {
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(extend("default" = OperationBehaviour::Op)))]
pub unmanaged_window_operation_behaviour: Option<OperationBehaviour>,
/// Focus the window under the pointer. On KDE this is KWin's own focus policy, whichever
/// implementation is named
#[serde(skip_serializing_if = "Option::is_none")]
pub focus_follows_mouse: Option<FocusFollowsMouseImplementation>,
/// Enable or disable mouse follows focus
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_MOUSE_FOLLOWS_FOCUS)))]
@@ -629,6 +635,7 @@ impl From<&WindowManager> for StaticConfig {
),
// minimum_window_height: Some(window::MINIMUM_HEIGHT.load(Ordering::SeqCst)),
// minimum_window_width: Some(window::MINIMUM_WIDTH.load(Ordering::SeqCst)),
focus_follows_mouse: value.focus_follows_mouse,
mouse_follows_focus: Option::from(value.mouse_follows_focus),
app_specific_configuration_path: None,
border_width: Option::from(border_manager::BORDER_WIDTH.load(Ordering::SeqCst)),
@@ -1083,6 +1090,7 @@ impl StaticConfig {
.unmanaged_window_operation_behaviour
.unwrap_or(OperationBehaviour::Op),
resize_delta: value.resize_delta.unwrap_or(DEFAULT_RESIZE_DELTA),
focus_follows_mouse: value.focus_follows_mouse,
opacity_applied: HashMap::new(),
mouse_follows_focus: value
.mouse_follows_focus
@@ -1223,6 +1231,12 @@ impl StaticConfig {
border_manager::BORDER_ENABLED.store(true, Ordering::SeqCst);
}
// the window manager was made from the configuration, before KWin could be asked anything
wm.focus_follows_mouse = value.focus_follows_mouse;
if let Err(error) = backend().set_focus_follows_mouse(wm.focus_follows_mouse.is_some()) {
tracing::warn!("could not set focus follows mouse: {error}");
}
Ok(())
}
@@ -1366,6 +1380,10 @@ impl StaticConfig {
.mouse_follows_focus
.unwrap_or(DEFAULT_MOUSE_FOLLOWS_FOCUS);
wm.work_area_offset = value.global_work_area_offset;
wm.focus_follows_mouse = value.focus_follows_mouse;
if let Err(error) = backend().set_focus_follows_mouse(wm.focus_follows_mouse.is_some()) {
tracing::warn!("could not set focus follows mouse: {error}");
}
let monitor_count = wm.monitors().len();
+5
View File
@@ -63,6 +63,7 @@ use crate::core::Axis;
use crate::core::CrossBoundaryBehaviour;
use crate::core::CycleDirection;
use crate::core::DefaultLayout;
use crate::core::FocusFollowsMouseImplementation;
use crate::core::Layout;
use crate::core::MonocleFocusBehaviour;
use crate::core::MoveBehaviour;
@@ -138,6 +139,9 @@ pub struct WindowManager {
pub monocle_focus_behaviour: MonocleFocusBehaviour,
/// Whether the pointer is moved to the window that is given the focus, which is the default
pub mouse_follows_focus: bool,
/// Whether the compositor gives the focus to the window under the pointer, and the
/// implementation that was asked for: on KDE both are the compositor's own focus policy
pub focus_follows_mouse: Option<FocusFollowsMouseImplementation>,
/// The opacity each window was last given by [`crate::transparency_manager`], for the ones that
/// are not opaque
pub opacity_applied: HashMap<u32, u8>,
@@ -230,6 +234,7 @@ impl WindowManager {
cross_monitor_move_behaviour: Default::default(),
cross_boundary_behaviour: Default::default(),
monocle_focus_behaviour: MonocleFocusBehaviour::default(),
focus_follows_mouse: None,
opacity_applied: HashMap::new(),
mouse_follows_focus: true,
work_area_offset: None,
+1 -1
View File
@@ -45,7 +45,7 @@ fn the_animation_key_of_the_file_is_the_animation_settings() {
})
.unwrap();
let wm = Arc::new(Mutex::new(wm));
StaticConfig::postload(&path, &wm).unwrap();
with_backend(fake.clone(), || StaticConfig::postload(&path, &wm)).unwrap();
let _ = std::fs::remove_file(&socket);
// one value for every kind of animation
+1 -1
View File
@@ -43,7 +43,7 @@ fn the_border_keys_of_the_file_are_the_border_settings() {
})
.unwrap();
let wm = Arc::new(Mutex::new(wm));
StaticConfig::postload(&path, &wm).unwrap();
with_backend(fake.clone(), || StaticConfig::postload(&path, &wm)).unwrap();
let _ = std::fs::remove_file(&socket);
// the file made the settings, and the settings make the look
+1 -1
View File
@@ -96,7 +96,7 @@ fn load(json: &str) -> Loaded {
})
.unwrap();
let wm = Arc::new(Mutex::new(wm));
StaticConfig::postload(&path, &wm).unwrap();
with_backend(fake.clone(), || StaticConfig::postload(&path, &wm)).unwrap();
with_backend(fake.clone(), || wm.lock().retile_all(false)).unwrap();
let _ = std::fs::remove_file(&socket);
+1 -1
View File
@@ -62,7 +62,7 @@ fn a_monitor_takes_the_configuration_its_display_index_preference_gives_it() {
wm
});
let wm = Arc::new(Mutex::new(wm));
StaticConfig::postload(&path, &wm).unwrap();
with_backend(fake.clone(), || StaticConfig::postload(&path, &wm)).unwrap();
let _ = std::fs::remove_file(&socket);
let _ = std::fs::remove_file(&path);
-2
View File
@@ -45,8 +45,6 @@ const WINDOWS_ONLY: &[&str] = &[
const NOT_YET: &[&str] = &[
// a color for each kind of window's border, whose type is komorebi-themes' (49)
"border_colours",
// focus follows mouse (48)
"focus_follows_mouse",
// themes (49)
"theme",
];
+145
View File
@@ -0,0 +1,145 @@
//! Focus follows mouse, against an in-memory desktop.
//!
//! KWin has its own focus follows mouse, and komorebi asks for it: both implementations the
//! configuration can name are the compositor's.
//!
//! The `focus_follows_mouse` key of `komorebi.json` is a setting of the window manager, not a
//! process-wide one, so its test is here.
use komorebi::backend::fake::Command;
use komorebi::backend::fake::FakeBackend;
use komorebi::backend::with_backend;
use komorebi::core::FocusFollowsMouseImplementation;
use komorebi::core::SocketMessage;
use komorebi::state::State;
use komorebi::static_config::StaticConfig;
use komorebi::window_manager::WindowManager;
use parking_lot::Mutex;
use std::os::unix::net::UnixListener;
use std::path::PathBuf;
use std::sync::Arc;
fn desktop() -> (Arc<FakeBackend>, WindowManager) {
let fake = Arc::new(FakeBackend::with_one_monitor());
let (_sender, receiver) = crossbeam_channel::bounded(1);
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let socket = std::path::PathBuf::from(format!(
"/tmp/kmf-{}-{}.sock",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
));
let wm = with_backend(fake.clone(), || {
let mut wm = WindowManager::new(receiver, Some(socket)).unwrap();
wm.init().unwrap();
wm
});
(fake, wm)
}
fn command(fake: &Arc<FakeBackend>, wm: &mut WindowManager, message: SocketMessage) {
with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap();
}
#[test]
fn focus_follows_mouse_is_asked_of_the_compositor_and_toggles() {
let (fake, mut wm) = desktop();
fake.clear_commands();
command(
&fake,
&mut wm,
SocketMessage::FocusFollowsMouse(FocusFollowsMouseImplementation::Windows, true),
);
assert_eq!(
wm.focus_follows_mouse,
Some(FocusFollowsMouseImplementation::Windows)
);
assert!(fake.commands().contains(&Command::FocusFollowsMouse(true)));
command(
&fake,
&mut wm,
SocketMessage::ToggleFocusFollowsMouse(FocusFollowsMouseImplementation::Windows),
);
assert_eq!(wm.focus_follows_mouse, None);
assert!(fake.commands().contains(&Command::FocusFollowsMouse(false)));
command(
&fake,
&mut wm,
SocketMessage::ToggleFocusFollowsMouse(FocusFollowsMouseImplementation::Komorebi),
);
assert_eq!(
wm.focus_follows_mouse,
Some(FocusFollowsMouseImplementation::Komorebi),
"the other implementation is KWin's too, and is remembered as asked for"
);
}
#[test]
fn the_state_says_whether_focus_follows_mouse_is_on_and_a_change_is_a_modification() {
let (fake, mut wm) = desktop();
let before = State::from(&wm);
assert_eq!(before.focus_follows_mouse, None);
command(
&fake,
&mut wm,
SocketMessage::FocusFollowsMouse(FocusFollowsMouseImplementation::Komorebi, true),
);
assert_eq!(
State::from(&wm).focus_follows_mouse,
Some(FocusFollowsMouseImplementation::Komorebi)
);
assert!(before.has_been_modified(&wm));
}
#[test]
fn the_file_turns_focus_follows_mouse_on_and_a_file_that_leaves_it_out_turns_it_off() {
let fake = Arc::new(FakeBackend::with_one_monitor());
let write = |name: &str, json: &str| {
let path = PathBuf::from(format!("/tmp/kmf-ffm-{name}-{}.json", std::process::id()));
std::fs::write(&path, json).unwrap();
path
};
let path = write("on", r#"{ "focus_follows_mouse": "Komorebi" }"#);
let (_sender, receiver) = crossbeam_channel::bounded(1);
let socket = PathBuf::from(format!("/tmp/kmf-ffm-{}.sock", std::process::id()));
let listener = UnixListener::bind(&socket).unwrap();
let wm = with_backend(fake.clone(), || {
let mut wm = StaticConfig::preload(&path, receiver, Some(listener)).unwrap();
wm.init().unwrap();
wm
});
let wm = Arc::new(Mutex::new(wm));
// the window manager has it from the file, and KWin is asked once the monitors are loaded
assert_eq!(
wm.lock().focus_follows_mouse,
Some(FocusFollowsMouseImplementation::Komorebi)
);
with_backend(fake.clone(), || StaticConfig::postload(&path, &wm).unwrap());
let _ = std::fs::remove_file(&socket);
assert!(fake.commands().contains(&Command::FocusFollowsMouse(true)));
assert_eq!(
StaticConfig::from(&*wm.lock()).focus_follows_mouse,
Some(FocusFollowsMouseImplementation::Komorebi),
"and it comes out again in the generated configuration"
);
// a file that is read again and leaves the key out gives the user's focus policy back
let empty = write("empty", "{}");
fake.clear_commands();
with_backend(fake.clone(), || {
StaticConfig::reload(&empty, &mut wm.lock()).unwrap();
});
assert_eq!(wm.lock().focus_follows_mouse, None);
assert!(fake.commands().contains(&Command::FocusFollowsMouse(false)));
for file in [path, empty] {
let _ = std::fs::remove_file(file);
}
}
+1 -1
View File
@@ -57,7 +57,7 @@ fn the_transparency_keys_of_the_file_are_the_transparency_settings() {
})
.unwrap();
let wm = Arc::new(Mutex::new(wm));
StaticConfig::postload(&path, &wm).unwrap();
with_backend(fake.clone(), || StaticConfig::postload(&path, &wm)).unwrap();
let _ = std::fs::remove_file(&socket);
assert!(transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst));
+33
View File
@@ -69,6 +69,8 @@
//! - `border` sets whether the compositor draws a border around each window, `border-colour` the
//! color of the border of a kind of window, and `border-width` and `border-offset` the room the
//! layout leaves for it.
//! - `focus-follows-mouse` and `toggle-focus-follows-mouse` set whether KWin gives the focus to the
//! window under the pointer, as the pointer moves.
//! - `transparency` and `toggle-transparency` set whether the windows that do not have the focus
//! are see-through, and `transparency-alpha` how opaque they are.
//! - `animation`, `animation-duration` and `animation-style` set whether windows are animated going
@@ -118,6 +120,7 @@ use komorebi_client::ApplicationIdentifier;
use komorebi_client::Axis;
use komorebi_client::CycleDirection;
use komorebi_client::DefaultLayout;
use komorebi_client::FocusFollowsMouseImplementation;
use komorebi_client::MoveBehaviour;
use komorebi_client::OperationBehaviour;
use komorebi_client::OperationDirection;
@@ -767,6 +770,22 @@ struct TransparencyAlpha {
alpha: u8,
}
#[derive(Parser)]
struct FocusFollowsMouse {
/// On KDE both are KWin's own focus policy
#[clap(value_enum, short, long, default_value = "windows")]
implementation: FocusFollowsMouseImplementation,
#[clap(value_enum)]
boolean_state: BooleanState,
}
#[derive(Parser)]
struct ToggleFocusFollowsMouse {
/// On KDE both are KWin's own focus policy
#[clap(value_enum, short, long, default_value = "windows")]
implementation: FocusFollowsMouseImplementation,
}
#[derive(Parser)]
struct Animation {
#[clap(value_enum)]
@@ -1258,6 +1277,11 @@ enum SubCommand {
/// Set the ease function for movement animations
#[clap(arg_required_else_help = true)]
AnimationStyle(AnimationStyle),
/// Enable or disable focus follows mouse (KWin's own focus policy)
#[clap(arg_required_else_help = true)]
FocusFollowsMouse(FocusFollowsMouse),
/// Toggle focus follows mouse (KWin's own focus policy)
ToggleFocusFollowsMouse(ToggleFocusFollowsMouse),
/// Enable or disable mouse follows focus on all workspaces
#[clap(arg_required_else_help = true)]
MouseFollowsFocus(MouseFollowsFocus),
@@ -2091,6 +2115,15 @@ fn main() -> eyre::Result<()> {
SubCommand::ToggleTransparency => {
send_message(&SocketMessage::ToggleTransparency)?;
}
SubCommand::FocusFollowsMouse(args) => {
send_message(&SocketMessage::FocusFollowsMouse(
args.implementation,
args.boolean_state.into(),
))?;
}
SubCommand::ToggleFocusFollowsMouse(args) => {
send_message(&SocketMessage::ToggleFocusFollowsMouse(args.implementation))?;
}
SubCommand::Animation(args) => {
send_message(&SocketMessage::Animation(
args.boolean_state.into(),
+21
View File
@@ -512,6 +512,27 @@ fn the_border_subcommands_send_what_they_are_given() {
);
}
#[test]
fn the_focus_follows_mouse_subcommands_send_what_they_are_given() {
sends(
&["focus-follows-mouse", "enable"],
r#"{"type":"FocusFollowsMouse","content":["Windows",true]}"#,
);
sends(
&[
"focus-follows-mouse",
"--implementation",
"komorebi",
"disable",
],
r#"{"type":"FocusFollowsMouse","content":["Komorebi",false]}"#,
);
sends(
&["toggle-focus-follows-mouse"],
r#"{"type":"ToggleFocusFollowsMouse","content":"Windows"}"#,
);
}
#[test]
fn the_transparency_subcommands_send_what_they_are_given() {
sends(
+13 -1
View File
@@ -1,4 +1,4 @@
# schema-sha256: f46c8e0d1557a1e36d2bd123a2d02a4238b28f07146beafb9b5c5fb5825b09df
# schema-sha256: c001e5dc47908d250a272d3be32faaccd8e0b57629a62a0537d7880a53183ae5
{ lib, ... }:
let
animationStyle = (
@@ -393,6 +393,18 @@ in
default = null;
description = "Aspect ratio to resize with when toggling floating mode for a window";
};
focus_follows_mouse = lib.mkOption {
type = (
lib.types.nullOr (
lib.types.enum [
"Komorebi"
"Windows"
]
)
);
default = null;
description = "Focus the window under the pointer. On KDE this is KWin's own focus policy, whichever\nimplementation is named";
};
global_work_area_offset = lib.mkOption {
type = (lib.types.nullOr rect);
default = null;
+5 -2
View File
@@ -12,15 +12,18 @@ A suite imports what it needs from here:
the ring around a window.
* [`latency`](komorebi_vm.latency) times the daemon's commands from a recording
of the session bus.
* [`Pointer`](komorebi_vm.pointer.Pointer) moves and clicks the pointer of a
session node, through [`uinput`](komorebi_vm.uinput), a program the node runs.
The library depends on the small [`Machine`](komorebi_vm.machine.Machine)
protocol, not on the test driver, so `nix/tests/vm/lib/tests` can run it
against a fake machine (the `vm-lib` check does).
"""
from komorebi_vm import daemon, latency, pixels
from komorebi_vm import daemon, latency, pixels, uinput
from komorebi_vm.checks import Checks
from komorebi_vm.kde import Kde, Rect
from komorebi_vm.machine import Machine
from komorebi_vm.pointer import Pointer
__all__ = ["Checks", "Kde", "Machine", "Rect", "daemon", "latency", "pixels"]
__all__ = ["Checks", "Kde", "Machine", "Pointer", "Rect", "daemon", "latency", "pixels", "uinput"]
+115
View File
@@ -0,0 +1,115 @@
"""The pointer of a session node, moved and clicked from inside the guest."""
import shlex
import time
from collections.abc import Callable
from komorebi_vm.machine import Machine
class Pointer:
"""A pointer device in the guest, which [`komorebi_vm.uinput`][] makes with uinput.
[`Pointer.start`][] runs `komorebi-pointer` as the test user, reading its commands from a
FIFO, and every method writes one command to it and waits for the program to say it is done.
A drag is one press, one glide and one release: the glide's moves are made in the guest, a few
milliseconds apart, because moves that each wait for a round trip to the test are seconds
apart, and KWin was seen to drop the horizontal part of such a drag.
Coordinates are pixels of the screen whose size the pointer was started with. KWin puts the
pointer within a pixel of where it is asked.
"""
def __init__(self, machine: Machine, *, uid: int = 1000, scale: float = 1.0) -> None:
self.machine = machine
# In the user's runtime directory, which is the user's: a FIFO of the user's in `/tmp`,
# which everybody may write to, is one root may not open for writing (`protected_fifos`).
self.fifo = f"/run/user/{uid}/komorebi-pointer"
self.log = f"/run/user/{uid}/komorebi-pointer.log"
self.scale = scale
self.done = 0
@classmethod
def start(
cls,
machine: Machine,
size: tuple[int, int],
*,
user: str = "komorebi",
uid: int = 1000,
scale: float = 1.0,
) -> "Pointer":
"""Starts the device for a screen of `size` and waits until KWin can have it.
The device starts with a move to the middle of the screen, since the first move after a
device is created was seen to be lost.
"""
pointer = cls(machine, uid=uid, scale=scale)
width, height = size
f, lg = shlex.quote(pointer.fifo), shlex.quote(pointer.log)
# The FIFO is kept open for writing by a `tail` that never writes, so that the program
# does not see the end of its input between two commands.
script = (
f"rm -f {f} {lg} && mkfifo {f} && "
f"(setsid nohup tail -f /dev/null > {f} 2>/dev/null < /dev/null &) && "
f"(setsid nohup komorebi-pointer {width} {height} < {f} > {lg} 2>&1 &)"
)
machine.succeed(f"runuser -u {user} -- sh -c {shlex.quote(script)}")
if not pointer._wait(lambda: pointer._lines().count("ready") == 1, timeout=30):
raise AssertionError(f"komorebi-pointer did not start: {pointer._lines()}")
pointer.move(width // 2, height // 2)
return pointer
def move(self, x: int, y: int) -> None:
"""Puts the pointer on the pixel (x, y)."""
self._send(f"move {x} {y}")
def down(self) -> None:
"""Presses the left button."""
self._send("down")
def up(self) -> None:
"""Lets go of the left button."""
self._send("up")
def glide(self, x: int, y: int, steps: int = 25, ms: int = 30) -> None:
"""Takes the pointer from where it is to (x, y) in `steps` moves, `ms` milliseconds apart.
It returns once the pointer is there.
"""
self._send(f"glide {x} {y} {steps} {ms}")
def drag(
self,
start: tuple[int, int],
end: tuple[int, int],
steps: int = 25,
ms: int = 30,
) -> None:
"""Presses the left button at `start`, glides to `end` with it held, and lets go there."""
self.move(*start)
self.down()
self.glide(*end, steps=steps, ms=ms)
self.up()
def _send(self, command: str) -> None:
self.machine.succeed(f"echo {shlex.quote(command)} > {shlex.quote(self.fifo)}")
self.done += 1
def answered() -> bool:
lines = self._lines()
return lines.count("ok") >= self.done or any(line.startswith("bad ") for line in lines)
if not self._wait(answered, timeout=30) or self._lines().count("ok") < self.done:
raise AssertionError(f"komorebi-pointer did not do {command!r}: {self._lines()}")
def _lines(self) -> list[str]:
return self.machine.execute(f"cat {shlex.quote(self.log)}")[1].splitlines()
def _wait(self, predicate: Callable[[], bool], timeout: float) -> bool:
deadline = time.monotonic() + timeout * self.scale
while not predicate():
if time.monotonic() >= deadline:
return False
time.sleep(0.05)
return True
+162
View File
@@ -0,0 +1,162 @@
"""komorebi-pointer: an absolute pointer device made with uinput, for the session node.
The session node installs this file as the program `komorebi-pointer`, and
[`Pointer`](komorebi_vm.pointer.Pointer) runs it there as the test user (who is in the group
`uinput`). `komorebi-pointer WIDTH HEIGHT` creates a device whose two axes span a screen of that
size, prints `ready`, and reads one command per line on its standard input:
* `move X Y` puts the pointer on the pixel (X, Y);
* `down` and `up` press and release the left button;
* `glide X Y STEPS MS` takes the pointer from where it is to (X, Y) in STEPS moves, MS
milliseconds apart, without a round trip to the test between two of them.
It prints `ok` once it has written a command's events, and `bad COMMAND` for a line it does not
understand. KWin takes the device as a tablet: a position is absolute, so it does not depend on
pointer acceleration.
The test driver's machine imports this module too, for the parts that do not touch a device, which
the unit tests in `nix/tests/vm/lib/tests` check.
"""
import fcntl
import os
import struct
import sys
import time
from collections.abc import Callable
UI_SET_EVBIT = 0x40045564
UI_SET_KEYBIT = 0x40045565
UI_SET_ABSBIT = 0x40045567
UI_DEV_SETUP = 0x405C5503
UI_ABS_SETUP = 0x401C5504
UI_DEV_CREATE = 0x5501
UI_DEV_DESTROY = 0x5502
EV_SYN = 0
EV_KEY = 1
EV_ABS = 3
ABS_X = 0
ABS_Y = 1
BTN_LEFT = 0x110
# the largest value of an axis; 0 is the first pixel and MAX the end of the last one
MAX = 65535
Event = tuple[int, int, int]
def axis(pixel: int, pixels: int) -> int:
"""The value of an axis that is `pixels` long for the middle of the pixel `pixel`.
The middle, and not the edge, so that KWin's rounding of the position back to a pixel lands on
that pixel: a value at the edge of two pixels comes back as either.
"""
return ((2 * pixel + 1) * (MAX + 1)) // (2 * pixels)
def path(start: tuple[int, int], end: tuple[int, int], steps: int) -> list[tuple[int, int]]:
"""The points a glide from `start` to `end` in `steps` moves goes through, `end` the last."""
(x1, y1), (x2, y2) = start, end
return [
(x1 + round((x2 - x1) * i / steps), y1 + round((y2 - y1) * i / steps))
for i in range(1, steps + 1)
]
class Device:
"""What a command turns into: input events, written by `write` and followed by a sync."""
def __init__(
self,
width: int,
height: int,
write: Callable[[list[Event]], None],
sleep: Callable[[float], None] = time.sleep,
) -> None:
self.width = width
self.height = height
self.write = write
self.sleep = sleep
self.at = (width // 2, height // 2)
def move(self, x: int, y: int) -> None:
"""Puts the pointer on the pixel (x, y)."""
self.write(
[
(EV_ABS, ABS_X, axis(x, self.width)),
(EV_ABS, ABS_Y, axis(y, self.height)),
(EV_SYN, 0, 0),
]
)
self.at = (x, y)
def button(self, down: bool) -> None:
"""Presses the left button, or lets go of it."""
self.write([(EV_KEY, BTN_LEFT, 1 if down else 0), (EV_SYN, 0, 0)])
def glide(self, x: int, y: int, steps: int, ms: int) -> None:
"""Takes the pointer from where it is to (x, y) in `steps` moves, `ms` apart."""
for point in path(self.at, (x, y), max(steps, 1)):
self.sleep(ms / 1000)
self.move(*point)
def command(self, line: str) -> bool:
"""Carries out one line of input; returns false if it is not a command."""
words = line.split()
try:
match words:
case ["move", x, y]:
self.move(int(x), int(y))
case ["down"]:
self.button(True)
case ["up"]:
self.button(False)
case ["glide", x, y, steps, ms]:
self.glide(int(x), int(y), int(steps), int(ms))
case _:
return False
except ValueError:
return False
return True
def pack(events: list[Event]) -> bytes:
"""The events as the kernel reads them: a `struct input_event` each, with no time."""
return b"".join(struct.pack("llHHi", 0, 0, kind, code, value) for kind, code, value in events)
def create(fd: int) -> None:
"""Makes `fd`, an open `/dev/uinput`, an absolute pointer with a left button."""
fcntl.ioctl(fd, UI_SET_EVBIT, EV_KEY)
fcntl.ioctl(fd, UI_SET_KEYBIT, BTN_LEFT)
fcntl.ioctl(fd, UI_SET_EVBIT, EV_ABS)
for code in (ABS_X, ABS_Y):
fcntl.ioctl(fd, UI_SET_ABSBIT, code)
fcntl.ioctl(fd, UI_ABS_SETUP, struct.pack("H2xiiiiii", code, 0, 0, MAX, 0, 0, 0))
setup = struct.pack("HHHH80sI", 0x03, 0x1209, 0x4B4D, 1, b"komorebi-pointer", 0)
fcntl.ioctl(fd, UI_DEV_SETUP, setup)
fcntl.ioctl(fd, UI_DEV_CREATE)
def main() -> None:
width, height = int(sys.argv[1]), int(sys.argv[2])
fd = os.open("/dev/uinput", os.O_WRONLY | os.O_NONBLOCK)
create(fd)
# the compositor needs a moment to open a new device; events before that are lost
time.sleep(1.5)
def write(events: list[Event]) -> None:
os.write(fd, pack(events))
device = Device(width, height, write)
print("ready", flush=True)
for line in sys.stdin:
if not line.strip():
continue
print("ok" if device.command(line) else f"bad {line.strip()}", flush=True)
fcntl.ioctl(fd, UI_DEV_DESTROY)
if __name__ == "__main__":
main()
+67
View File
@@ -0,0 +1,67 @@
import shlex
from pathlib import Path
import pytest
from komorebi_vm import Pointer
from .conftest import FakeMachine
class GuestMachine(FakeMachine):
"""A machine whose `komorebi-pointer` says it is ready, and answers each command it is sent."""
def __init__(self, out_dir: Path, answer: str = "ok") -> None:
super().__init__(out_dir)
self.answer = answer
self.log: list[str] = []
self.sent: list[str] = []
def execute(self, command: str, /) -> tuple[int, str]:
self.commands.append(command)
if command.startswith("runuser"):
self.log.append("ready")
elif command.startswith("echo "):
words = shlex.split(command)
self.sent.append(words[1])
self.log.append(self.answer if self.answer == "ok" else f"bad {words[1]}")
elif command.startswith("cat "):
return 0, "\n".join(self.log) + "\n"
return 0, ""
def test_start_runs_the_program_as_the_user_on_a_fifo_and_moves_to_the_middle(
tmp_path: Path,
) -> None:
machine = GuestMachine(tmp_path)
Pointer.start(machine, (1280, 800))
script = shlex.split(machine.commands[0])
assert script[:4] == ["runuser", "-u", "komorebi", "--"]
assert "mkfifo /run/user/1000/komorebi-pointer" in script[-1]
assert "komorebi-pointer 1280 800 < /run/user/1000/komorebi-pointer" in script[-1]
assert machine.sent == ["move 640 400"]
def test_a_drag_is_a_press_a_glide_and_a_release(tmp_path: Path) -> None:
machine = GuestMachine(tmp_path)
pointer = Pointer.start(machine, (1280, 800))
pointer.drag((100, 200), (172, 200), steps=10, ms=20)
assert machine.sent[1:] == ["move 100 200", "down", "glide 172 200 10 20", "up"]
def test_a_command_the_program_refuses_fails_the_test(tmp_path: Path) -> None:
machine = GuestMachine(tmp_path)
pointer = Pointer.start(machine, (1280, 800))
machine.answer = "bad"
with pytest.raises(AssertionError, match="did not do 'down'"):
pointer.down()
def test_a_program_that_does_not_start_fails_the_test(machine: FakeMachine) -> None:
with pytest.raises(AssertionError, match="did not start"):
Pointer.start(machine, (1280, 800), scale=0.001)
+84
View File
@@ -0,0 +1,84 @@
import struct
from komorebi_vm import uinput
from komorebi_vm.uinput import ABS_X, ABS_Y, BTN_LEFT, EV_ABS, EV_KEY, EV_SYN, MAX, Device
def test_every_pixel_is_sent_as_a_value_that_comes_back_as_that_pixel() -> None:
for pixels in (800, 1080, 1280, 1920):
for pixel in range(pixels):
value = uinput.axis(pixel, pixels)
assert 0 <= value <= MAX
assert value * pixels // (MAX + 1) == pixel, (pixel, pixels, value)
def test_a_glide_goes_in_even_steps_and_ends_where_it_was_asked() -> None:
assert uinput.path((0, 0), (100, 50), 4) == [(25, 12), (50, 25), (75, 38), (100, 50)]
assert uinput.path((10, 10), (10, 10), 3) == [(10, 10), (10, 10), (10, 10)]
assert uinput.path((5, 5), (-5, 9), 1) == [(-5, 9)]
def recorder() -> tuple[Device, list[list[tuple[int, int, int]]], list[float]]:
writes: list[list[tuple[int, int, int]]] = []
sleeps: list[float] = []
device = Device(1280, 800, writes.append, sleeps.append)
return device, writes, sleeps
def test_a_move_is_both_axes_and_a_sync() -> None:
device, writes, _ = recorder()
assert device.command("move 0 799")
assert writes == [
[
(EV_ABS, ABS_X, uinput.axis(0, 1280)),
(EV_ABS, ABS_Y, uinput.axis(799, 800)),
(EV_SYN, 0, 0),
]
]
assert device.at == (0, 799)
def test_down_and_up_press_and_release_the_left_button() -> None:
device, writes, _ = recorder()
assert device.command("down")
assert device.command("up")
assert writes == [
[(EV_KEY, BTN_LEFT, 1), (EV_SYN, 0, 0)],
[(EV_KEY, BTN_LEFT, 0), (EV_SYN, 0, 0)],
]
def test_a_glide_starts_where_the_pointer_is_and_waits_between_its_moves() -> None:
device, writes, sleeps = recorder()
device.command("move 100 100")
writes.clear()
assert device.command("glide 200 140 4 30")
assert [(w[0][2], w[1][2]) for w in writes] == [
(uinput.axis(x, 1280), uinput.axis(y, 800))
for x, y in [(125, 110), (150, 120), (175, 130), (200, 140)]
]
assert sleeps == [0.03] * 4
assert device.at == (200, 140)
def test_a_line_that_is_not_a_command_does_nothing() -> None:
device, writes, _ = recorder()
for line in ("teleport 1 2", "move 1", "move one two", "glide 1 2 3", ""):
assert not device.command(line), line
assert writes == []
def test_an_event_is_packed_as_the_kernel_reads_it() -> None:
packed = uinput.pack([(EV_KEY, BTN_LEFT, 1), (EV_SYN, 0, 0)])
size = struct.calcsize("llHHi")
assert len(packed) == 2 * size
assert struct.unpack("llHHi", packed[:size]) == (0, 0, EV_KEY, BTN_LEFT, 1)
+12 -1
View File
@@ -46,7 +46,18 @@
AutoSuspendAction=0
'';
environment.systemPackages = [ pkgs.kdePackages.konsole ];
# A pointer device the test drives from inside the guest (`komorebi_vm.Pointer`): the program
# makes it with uinput, which the test user may open.
hardware.uinput.enable = true;
users.users.komorebi.extraGroups = [ "uinput" ];
environment.systemPackages = [
pkgs.kdePackages.konsole
(pkgs.writeScriptBin "komorebi-pointer" ''
#!${pkgs.python3.interpreter}
${builtins.readFile ../lib/komorebi_vm/uinput.py}
'')
];
# KWin loads no effect that animates under software rendering, which is all a guest has, unless
# it is told to: with this it loads Geometry Change, which komorebi asks it to load
+4
View File
@@ -325,6 +325,10 @@ mouse-follows-focus enable
mouse-follows-focus disable
toggle-mouse-follows-focus
toggle-mouse-follows-focus
focus-follows-mouse enable
focus-follows-mouse disable
toggle-focus-follows-mouse
toggle-focus-follows-mouse
transparency enable
transparency-alpha 150
toggle-transparency
@@ -0,0 +1,8 @@
{
tier = "slow";
kind = "session";
timeoutMinutes = 15;
# The module's unit starts komorebi when the session does; the test stops that daemon and runs
# the unit itself, so that it sees what komorebi does to KWin's configuration from the first
# moment. The pointer is a uinput device the session node has (komorebi_vm.Pointer).
}
@@ -0,0 +1,136 @@
# Focus follows mouse against a real KWin session, with a real pointer.
#
# komorebi's focus follows mouse is KWin's own focus policy: the window under the pointer is the one
# that has the focus, and komorebi follows. Checked by moving the pointer over each window in turn,
# then turning it off (the focus stays where it was), and on exit (the user's policy is back in
# `kwinrc`). The pointer is a device made inside the guest (`Pointer`, the program
# `komorebi-pointer`), moved to the middle of a window by pixel.
import time
from komorebi_vm import Checks, Kde, Pointer
UNIT = "komorebi.service"
# the session node's display, which the pointer's two axes span
SCREEN = (1280, 800)
start_all()
machine.wait_for_unit("multi-user.target")
checks = Checks()
kde = Kde.session(machine, scale=SCALE)
def answering() -> bool:
return kde.run("komorebic monitor-information")[0] == 0
def running() -> bool:
return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0
def active_title() -> str:
wid = kde.active()
return kde.title(wid) if wid else ""
def focus_policy() -> str | None:
return kde.kwinrc("Windows", "FocusPolicy")
def kwin_has_read_it() -> None:
"""Waits for KWin to have read the focus policy komorebi wrote.
The key is in the file at once, and KWin reads it about 200 ms after it is asked to (it waits
for more changes): a pointer moved before that is moved under the old policy, and a pointer that
then rests over a window moves nothing.
"""
time.sleep(1)
def middle(title: str) -> tuple[int, int]:
frame = kde.rect(kde.wid(title))
return frame.x + frame.w // 2, frame.y + frame.h // 2
# the session started the module's unit when it logged in: this test starts its own run
kde.systemctl("stop", UNIT)
kde.close_colored_windows()
before = focus_policy()
before_delay = kde.kwinrc("Windows", "DelayFocusInterval")
print(f" the user's focus policy before: {before or '(not set: click to focus)'}")
print("== focus follows mouse, turned on by command")
kde.systemctl("start", UNIT)
kde.wait_for(answering, timeout=60)
time.sleep(2)
kde.colored_window("win1", "222233")
time.sleep(1)
kde.colored_window("win2", "223322")
kde.wait_for(lambda: kde.managed() == 2, timeout=30)
time.sleep(2)
pointer = Pointer.start(machine, SCREEN, scale=SCALE)
kde.komorebic("focus-follows-mouse", "enable")
checks.check(
"KWin's focus policy is focus follows mouse, with no delay",
kde.wait_for(
lambda: focus_policy() == "1" and kde.kwinrc("Windows", "DelayFocusInterval") == "0",
timeout=10,
),
)
kwin_has_read_it()
first, second = middle("win1"), middle("win2")
print(f" win1's middle is at {first}, win2's at {second}")
pointer.move(*first)
checks.check(
"the pointer over win1 gives it the focus",
kde.wait_for(lambda: active_title() == "win1", timeout=10),
)
pointer.move(*second)
checks.check("over win2, win2", kde.wait_for(lambda: active_title() == "win2", timeout=10))
pointer.move(*first)
checks.check("and back", kde.wait_for(lambda: active_title() == "win1", timeout=10))
checks.check(
"komorebi followed the compositor",
kde.wait_for(lambda: kde.focused_title() == "win1", timeout=10),
)
print("== turned off")
kde.komorebic("toggle-focus-follows-mouse")
checks.check(
"the policy is back to what it was",
kde.wait_for(lambda: focus_policy() == before, timeout=10),
)
kwin_has_read_it()
pointer.move(*second)
time.sleep(2)
checks.check("the pointer over win2 no longer moves the focus", active_title() == "win1")
print("== turned on again, and put back when komorebi exits")
kde.komorebic("focus-follows-mouse", "enable")
checks.check(
"the policy is focus follows mouse again",
kde.wait_for(lambda: focus_policy() == "1", timeout=10),
)
kwin_has_read_it()
# the pointer is resting over win2: it has to go into a window to be followed
pointer.move(*first)
kde.wait_for(lambda: active_title() == "win1", timeout=10)
pointer.move(*second)
checks.check(
"on again: the pointer over win2 gives it the focus",
kde.wait_for(lambda: active_title() == "win2", timeout=10),
)
kde.komorebic("stop")
kde.wait_for(lambda: not running(), timeout=30)
kde.close_colored_windows()
checks.check(
"when komorebi exits the user's focus policy is back",
kde.wait_for(lambda: focus_policy() == before, timeout=10),
)
checks.check(
"and so is the delay it had",
kde.kwinrc("Windows", "DelayFocusInterval") == before_delay,
)
checks.finish()
+26
View File
@@ -191,6 +191,17 @@
}
]
},
"focus_follows_mouse": {
"description": "Focus the window under the pointer. On KDE this is KWin's own focus policy, whichever\nimplementation is named",
"anyOf": [
{
"$ref": "#/$defs/FocusFollowsMouseImplementation"
},
{
"type": "null"
}
]
},
"global_work_area_offset": {
"description": "Global work area (space used for tiling) offset",
"anyOf": [
@@ -766,6 +777,21 @@
}
]
},
"FocusFollowsMouseImplementation": {
"description": "Focus follows mouse implementation\n\nThe two exist on Windows. On KDE the compositor does it, so both ask KWin for its\n\"focus follows mouse\" focus policy.",
"oneOf": [
{
"description": "Custom FFM implementation (slightly more CPU-intensive)",
"type": "string",
"const": "Komorebi"
},
{
"description": "Native (legacy) Windows FFM implementation",
"type": "string",
"const": "Windows"
}
]
},
"GridLayoutOptions": {
"description": "Options for the Grid layout",
"type": "object",