mirror of
https://github.com/LGUG2Z/komorebi.git
synced 2026-12-04 14:06:32 +01:00
refactor(repo): move the KDE and macOS nix files under nix/ (pure move)
komorebi-for-kde/nix/ -> nix/linux/ komorebi-for-mac/nix/ -> nix/macos/ The nix expressions of the platforms (modules, option files, VM test suites, kwin effects, the darwin module) sit next to the existing nix/workspace-src.nix. Renames only (252 files); the flakes that import them are replaced by one root flake later in this stack, so nix does not evaluate at this revision.
This commit is contained in:
1 parent
d781028a2a
commit
f01853ceca
252 files changed
No files matched your search
@@ -0,0 +1,137 @@
|
||||
# `nix-options-validation`: the options `just nixgen` makes from `schema.json`, evaluated against
|
||||
# the example configuration, whose JSON is checked against the schema, and against the example
|
||||
# file of the docs, and against the places a workspace can give the windows that open, in every
|
||||
# form komorebi reads. Run with `nix build -f nix/tests/default.nix`, or as a check of the flake.
|
||||
{
|
||||
pkgs ? import <nixpkgs> { },
|
||||
}:
|
||||
let
|
||||
lib = pkgs.lib;
|
||||
|
||||
# the Nix module system uses null for an optional field that is not set, and the schema wants
|
||||
# the field to be absent
|
||||
filterNulls =
|
||||
value:
|
||||
if value == null then
|
||||
null
|
||||
else if builtins.isList value then
|
||||
map filterNulls (builtins.filter (x: x != null) value)
|
||||
else if builtins.isAttrs value then
|
||||
lib.filterAttrs (_n: v: v != null) (builtins.mapAttrs (_n: v: filterNulls v) value)
|
||||
else
|
||||
value;
|
||||
|
||||
evaluated =
|
||||
(lib.evalModules {
|
||||
modules = [
|
||||
(import ../komorebi-options.nix)
|
||||
(import ./komorebi-example.nix)
|
||||
];
|
||||
}).config.komorebi;
|
||||
|
||||
evaluatedJson = pkgs.writeText "komorebi-example-from-nix.json" (
|
||||
builtins.toJSON (filterNulls evaluated)
|
||||
);
|
||||
|
||||
# where a workspace puts the windows that open, in each form komorebi reads: a name, a number,
|
||||
# text that is a number, and a map of places to rules (whose keys are text)
|
||||
placements =
|
||||
(lib.evalModules {
|
||||
modules = [
|
||||
(import ../komorebi-options.nix)
|
||||
{
|
||||
komorebi.monitors = [
|
||||
{
|
||||
workspaces = [
|
||||
{
|
||||
name = "name";
|
||||
initial_window_placement_rules = "Primary";
|
||||
}
|
||||
{
|
||||
name = "number";
|
||||
initial_window_placement_rules = 3;
|
||||
}
|
||||
{
|
||||
name = "text";
|
||||
initial_window_placement_rules = "3";
|
||||
}
|
||||
{
|
||||
name = "map";
|
||||
initial_window_placement_rules = {
|
||||
Primary = {
|
||||
kind = "Exe";
|
||||
id = "firefox";
|
||||
matching_strategy = "Equals";
|
||||
};
|
||||
"2" = [
|
||||
{
|
||||
kind = "Title";
|
||||
id = "notes";
|
||||
matching_strategy = "StartsWith";
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
}).config.komorebi;
|
||||
|
||||
placementsJson = pkgs.writeText "komorebi-placements.json" (
|
||||
builtins.toJSON (filterNulls placements)
|
||||
);
|
||||
|
||||
# a place that is neither a name nor a number
|
||||
nowhereJson = pkgs.writeText "komorebi-nowhere.json" (
|
||||
builtins.toJSON {
|
||||
monitors = [
|
||||
{
|
||||
workspaces = [
|
||||
{
|
||||
name = "x";
|
||||
initial_window_placement_rules = "Nowhere";
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
}
|
||||
);
|
||||
|
||||
# the file has comment lines (komorebi reads them), which the schema checker does not
|
||||
exampleJson = pkgs.runCommand "komorebi.example.json" { } ''
|
||||
grep -v '^\s*//' ${../../docs/komorebi.example.json} > $out
|
||||
'';
|
||||
schema = ../../schema.json;
|
||||
in
|
||||
pkgs.runCommand "nix-options-validation"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.check-jsonschema
|
||||
pkgs.jq
|
||||
];
|
||||
}
|
||||
''
|
||||
echo "Validating the example, written in Nix, against the schema..."
|
||||
check-jsonschema --schemafile ${schema} ${evaluatedJson}
|
||||
|
||||
echo "Validating the example file of the docs against the schema..."
|
||||
check-jsonschema --schemafile ${schema} ${exampleJson}
|
||||
|
||||
echo "Checking that the two examples say the same..."
|
||||
jq -e --slurpfile example ${exampleJson} 'contains($example[0])' ${evaluatedJson} > /dev/null
|
||||
|
||||
echo "Validating the places a workspace can give a new window, in every form, against the schema..."
|
||||
check-jsonschema --schemafile ${schema} ${placementsJson}
|
||||
jq -e '[.monitors[0].workspaces[].initial_window_placement_rules | type] == ["string", "number", "string", "object"]' ${placementsJson} > /dev/null
|
||||
|
||||
echo "Checking that the schema refuses a place that is neither a name nor a number..."
|
||||
if check-jsonschema --schemafile ${schema} ${nowhereJson} > /dev/null 2>&1; then
|
||||
echo "the schema accepts a place that komorebi cannot read" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "All validations passed!"
|
||||
touch $out
|
||||
''
|
||||
@@ -0,0 +1,94 @@
|
||||
# Install checks of the KWin effects komorebi drives: each package is built and its files are
|
||||
# inspected the way KWin finds them, without a session. Whether an effect loads in a real KWin is a
|
||||
# question for the VM tests.
|
||||
{ pkgs, packages }:
|
||||
let
|
||||
inherit (pkgs.kdePackages) kwin qttools;
|
||||
fail = ''
|
||||
fail() {
|
||||
echo "FAIL: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
'';
|
||||
in
|
||||
{
|
||||
kde-rounded-corners-komorebi-install =
|
||||
pkgs.runCommand "kde-rounded-corners-komorebi-install"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
pkgs.jq
|
||||
pkgs.patchelf
|
||||
# qtplugininfo reads a plugin's metadata as Qt and KWin read it
|
||||
qttools
|
||||
];
|
||||
}
|
||||
''
|
||||
${fail}
|
||||
plugin=${packages.kde-rounded-corners-komorebi}/lib/qt-6/plugins/kwin/effects/plugins/kwin4_effect_shapecorners.so
|
||||
|
||||
[ -f "$plugin" ] || fail "no plugin at $plugin"
|
||||
echo "ok: the plugin is where KWin looks for effect plugins"
|
||||
|
||||
# The metadata is compiled into the plugin; KWin does not read metadata.json at run time.
|
||||
qtplugininfo --full-json "$plugin" > metadata.json || fail "qtplugininfo cannot read $plugin"
|
||||
if ! jq -e '.MetaData.KPlugin.EnabledByDefault == false' metadata.json > /dev/null; then
|
||||
cat metadata.json
|
||||
fail "the plugin's metadata does not say EnabledByDefault false"
|
||||
fi
|
||||
echo "ok: the plugin's metadata says EnabledByDefault false"
|
||||
|
||||
# The plugin is loaded into KWin, so it has to link the libkwin of that KWin: the dynamic
|
||||
# loader takes the first directory of the RUNPATH that has the library.
|
||||
needed=$(patchelf --print-needed "$plugin" | grep -m 1 -x 'libkwin\.so\.[0-9]*') ||
|
||||
fail "the plugin does not link libkwin"
|
||||
found=
|
||||
IFS=: read -r -a dirs <<< "$(patchelf --print-rpath "$plugin")"
|
||||
for dir in "''${dirs[@]}"; do
|
||||
if [ -e "$dir/$needed" ]; then
|
||||
found=$dir/$needed
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ "$found" = "${kwin}/lib/$needed" ] ||
|
||||
fail "$needed resolves to '$found', not to the KWin of this nixpkgs (${kwin})"
|
||||
echo "ok: $needed is ${kwin}/lib/$needed"
|
||||
|
||||
# komorebi's patch: the interface that takes a color for each window
|
||||
grep -q -a -F org.komorebi.BorderColours1 "$plugin" ||
|
||||
fail "the plugin has no org.komorebi.BorderColours1: komorebi-border-colours.patch is not in it"
|
||||
echo "ok: the plugin has org.komorebi.BorderColours1"
|
||||
|
||||
touch $out
|
||||
'';
|
||||
|
||||
kwin-effect-geometry-change-komorebi-install =
|
||||
pkgs.runCommand "kwin-effect-geometry-change-komorebi-install" { nativeBuildInputs = [ pkgs.jq ]; }
|
||||
''
|
||||
${fail}
|
||||
# KWin finds scripted effects by their metadata.json, in a directory of share/kwin/effects
|
||||
effect=${packages.kwin-effect-geometry-change-komorebi}/share/kwin/effects/kwin4_effect_geometry_change
|
||||
|
||||
[ -f "$effect/metadata.json" ] || fail "no metadata.json in $effect"
|
||||
jq -e '.KPlugin.Id == "kwin4_effect_geometry_change"' "$effect/metadata.json" > /dev/null ||
|
||||
fail "the metadata does not name the effect kwin4_effect_geometry_change"
|
||||
main=$effect/contents/$(jq -r '."X-Plasma-MainScript"' "$effect/metadata.json")
|
||||
[ -f "$main" ] || fail "no main script at $main"
|
||||
echo "ok: the effect is where KWin looks for scripted effects, with its script"
|
||||
|
||||
# upstream's choice, which komorebi relies on: asserted so that an update cannot change it
|
||||
if ! jq -e '.KPlugin.EnabledByDefault == false' "$effect/metadata.json" > /dev/null; then
|
||||
cat "$effect/metadata.json"
|
||||
fail "the metadata does not say EnabledByDefault false"
|
||||
fi
|
||||
echo "ok: the metadata says EnabledByDefault false"
|
||||
|
||||
# komorebi's patch: the curve is a setting (the stock effect names QEasingCurve.OutExpo too)
|
||||
grep -q -F 'readConfig("Curve"' "$main" ||
|
||||
fail "the script does not read a Curve setting: curve.patch is not in it"
|
||||
grep -q -F '<entry name="Curve"' "$effect/contents/config/main.xml" ||
|
||||
fail "the effect's settings have no Curve: curve.patch is not in it"
|
||||
echo "ok: the effect reads a Curve setting"
|
||||
|
||||
touch $out
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
== blacklist.skhdrc
|
||||
blacklist.skhdrc: line 7: note: every binding goes through the engine: the file has a blacklist
|
||||
0 shortcuts would be written to shortcuts (0 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
== braces.skhdrc
|
||||
Alt+H komorebic focus left
|
||||
Alt+J komorebic focus down
|
||||
Alt+K komorebic focus up
|
||||
Alt+L komorebic focus right
|
||||
Alt+1 komorebic focus-workspace 0
|
||||
Alt+2 komorebic focus-workspace 1
|
||||
Alt+3 komorebic focus-workspace 2
|
||||
Alt+! komorebic move-to-workspace 0
|
||||
Alt+@ komorebic move-to-workspace 1
|
||||
Alt+# komorebic move-to-workspace 2
|
||||
10 shortcuts would be written to shortcuts (10 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== braces.sxhkdrc
|
||||
Alt+H komorebic focus left
|
||||
Alt+J komorebic focus down
|
||||
Alt+K komorebic focus up
|
||||
Alt+L komorebic focus right
|
||||
Alt+1 komorebic focus-workspace 0
|
||||
Alt+2 komorebic focus-workspace 1
|
||||
Alt+3 komorebic focus-workspace 2
|
||||
Alt+! komorebic move-to-workspace 0
|
||||
Alt+@ komorebic move-to-workspace 1
|
||||
Alt+# komorebic move-to-workspace 2
|
||||
10 shortcuts would be written to shortcuts (10 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== braces.whkdrc
|
||||
braces.whkdrc: line 2: note: commands run through `sh -c`, not `pwsh`
|
||||
Alt+H komorebic focus left
|
||||
Alt+J komorebic focus down
|
||||
Alt+K komorebic focus up
|
||||
Alt+L komorebic focus right
|
||||
Alt+1 komorebic focus-workspace 0
|
||||
Alt+2 komorebic focus-workspace 1
|
||||
Alt+3 komorebic focus-workspace 2
|
||||
Alt+! komorebic move-to-workspace 0
|
||||
Alt+@ komorebic move-to-workspace 1
|
||||
Alt+# komorebic move-to-workspace 2
|
||||
10 shortcuts would be written to shortcuts (10 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== chords.sxhkdrc
|
||||
chords.sxhkdrc: line 2: warning: in sxhkd a key that is not in the chain after `Alt+W` ends it; here only Escape and the chord timeout do
|
||||
chords.sxhkdrc: line 2: note: every binding goes through the engine: the file declares modes
|
||||
chords.sxhkdrc: line 6: warning: in sxhkd a key that is not in the chain after `Alt+R` ends it; here only Escape does
|
||||
0 shortcuts would be written to shortcuts (0 new, 0 changed, 0 removed), 6 bindings need the engine
|
||||
|
||||
== comments.skhdrc
|
||||
Alt+H komorebic focus left
|
||||
Alt+X komorebic flip-layout horizontal
|
||||
2 shortcuts would be written to shortcuts (2 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== comments.sxhkdrc
|
||||
Alt+H komorebic focus left
|
||||
Alt+X komorebic flip-layout horizontal
|
||||
2 shortcuts would be written to shortcuts (2 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== comments.whkdrc
|
||||
comments.whkdrc: line 2: note: commands run through `sh -c`, not `pwsh`
|
||||
Alt+H komorebic focus left
|
||||
Alt+X komorebic flip-layout horizontal
|
||||
2 shortcuts would be written to shortcuts (2 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== define.skhdrc
|
||||
define.skhdrc: line 5: note: Alt+B goes through the engine: it does something else in each application
|
||||
Alt+H komorebic focus left
|
||||
Alt+L komorebic focus right
|
||||
2 shortcuts would be written to shortcuts (2 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
== define.whkdrc
|
||||
define.whkdrc: line 2: note: commands run through `sh -c`, not `pwsh`
|
||||
define.whkdrc: line 4: note: Alt+B goes through the engine: it does something else in each application
|
||||
Alt+H komorebic focus left
|
||||
Alt+L komorebic focus right
|
||||
2 shortcuts would be written to shortcuts (2 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
== keycodes.skhdrc
|
||||
Alt+[ komorebic cycle-stack previous
|
||||
Alt+] komorebic cycle-stack next
|
||||
Alt+; komorebic unstack
|
||||
Alt+= komorebic resize-axis horizontal increase
|
||||
Alt+- komorebic resize-axis horizontal decrease
|
||||
Alt+{ komorebic cycle-focus previous
|
||||
6 shortcuts would be written to shortcuts (6 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== keycodes.sxhkdrc
|
||||
Alt+[ komorebic cycle-stack previous
|
||||
Alt+] komorebic cycle-stack next
|
||||
Alt+; komorebic unstack
|
||||
Alt+= komorebic resize-axis horizontal increase
|
||||
Alt+- komorebic resize-axis horizontal decrease
|
||||
Alt+{ komorebic cycle-focus previous
|
||||
6 shortcuts would be written to shortcuts (6 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== keycodes.whkdrc
|
||||
keycodes.whkdrc: line 2: note: commands run through `sh -c`, not `pwsh`
|
||||
Alt+[ komorebic cycle-stack previous
|
||||
Alt+] komorebic cycle-stack next
|
||||
Alt+; komorebic unstack
|
||||
Alt+= komorebic resize-axis horizontal increase
|
||||
Alt+- komorebic resize-axis horizontal decrease
|
||||
Alt+{ komorebic cycle-focus previous
|
||||
6 shortcuts would be written to shortcuts (6 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== modes.skhdrc
|
||||
modes.skhdrc: line 2: warning: `resize` captures every key in skhd; here the keys it has no binding for reach the application
|
||||
modes.skhdrc: line 3: note: every binding goes through the engine: the file declares modes
|
||||
0 shortcuts would be written to shortcuts (0 new, 0 changed, 0 removed), 6 bindings need the engine
|
||||
|
||||
== modifiers.skhdrc
|
||||
Meta+Return konsole
|
||||
Ctrl+Alt+Left komorebic stack left
|
||||
Alt+Shift+H komorebic move left
|
||||
Ctrl+Shift+Right komorebic resize-edge right increase
|
||||
Alt+! komorebic move-to-workspace 0
|
||||
Ctrl+Alt+( komorebic move-to-workspace 8
|
||||
Meta+Ctrl+Alt+Shift+A komorebic retile
|
||||
Ctrl+Alt+Shift+M komorebic toggle-monocle
|
||||
8 shortcuts would be written to shortcuts (8 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== modifiers.sxhkdrc
|
||||
Meta+Return konsole
|
||||
Ctrl+Alt+Left komorebic stack left
|
||||
Alt+Shift+H komorebic move left
|
||||
Ctrl+Shift+Right komorebic resize-edge right increase
|
||||
Alt+! komorebic move-to-workspace 0
|
||||
Ctrl+Alt+( komorebic move-to-workspace 8
|
||||
Meta+Ctrl+Alt+Shift+A komorebic retile
|
||||
Ctrl+Alt+Shift+M komorebic toggle-monocle
|
||||
8 shortcuts would be written to shortcuts (8 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== modifiers.whkdrc
|
||||
modifiers.whkdrc: line 2: note: commands run through `sh -c`, not `pwsh`
|
||||
Meta+Return konsole
|
||||
Ctrl+Alt+Left komorebic stack left
|
||||
Alt+Shift+H komorebic move left
|
||||
Ctrl+Shift+Right komorebic resize-edge right increase
|
||||
Alt+! komorebic move-to-workspace 0
|
||||
Ctrl+Alt+( komorebic move-to-workspace 8
|
||||
Meta+Ctrl+Alt+Shift+A komorebic retile
|
||||
Ctrl+Alt+Shift+M komorebic toggle-monocle
|
||||
8 shortcuts would be written to shortcuts (8 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== pause.whkdrc
|
||||
pause.whkdrc: line 2: note: commands run through `sh -c`, not `pwsh`
|
||||
pause.whkdrc: line 6: note: every binding goes through the engine: the file has a pause binding
|
||||
0 shortcuts would be written to shortcuts (0 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
== plain.skhdrc
|
||||
Alt+H komorebic focus left
|
||||
Alt+J komorebic focus down
|
||||
Alt+K komorebic focus up
|
||||
Alt+L komorebic focus right
|
||||
Alt+Q komorebic close
|
||||
5 shortcuts would be written to shortcuts (5 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== plain.sxhkdrc
|
||||
Alt+H komorebic focus left
|
||||
Alt+J komorebic focus down
|
||||
Alt+K komorebic focus up
|
||||
Alt+L komorebic focus right
|
||||
Alt+Q komorebic close
|
||||
5 shortcuts would be written to shortcuts (5 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== plain.whkdrc
|
||||
plain.whkdrc: line 2: note: commands run through `sh -c`, not `pwsh`
|
||||
Alt+H komorebic focus left
|
||||
Alt+J komorebic focus down
|
||||
Alt+K komorebic focus up
|
||||
Alt+L komorebic focus right
|
||||
Alt+Q komorebic close
|
||||
5 shortcuts would be written to shortcuts (5 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== release.sxhkdrc
|
||||
release.sxhkdrc: line 2: warning: a release binding fires when any key of its combo is released first
|
||||
release.sxhkdrc: line 2: note: Alt+Space goes through the engine: it fires when the key is released
|
||||
0 shortcuts would be written to shortcuts (0 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
== sample.skhdrc
|
||||
Alt+H komorebic focus left
|
||||
Alt+J komorebic focus down
|
||||
Alt+K komorebic focus up
|
||||
Alt+L komorebic focus right
|
||||
Alt+{ komorebic cycle-focus previous
|
||||
Alt+} komorebic cycle-focus next
|
||||
Alt+Shift+H komorebic move left
|
||||
Alt+Shift+J komorebic move down
|
||||
Alt+Shift+K komorebic move up
|
||||
Alt+Shift+L komorebic move right
|
||||
Alt+Shift+Return komorebic promote
|
||||
Ctrl+Alt+Left komorebic stack left
|
||||
Ctrl+Alt+Down komorebic stack down
|
||||
Ctrl+Alt+Up komorebic stack up
|
||||
Ctrl+Alt+Right komorebic stack right
|
||||
Alt+; komorebic unstack
|
||||
Alt+[ komorebic cycle-stack previous
|
||||
Alt+] komorebic cycle-stack next
|
||||
Alt+: komorebic toggle-workspace-layer
|
||||
Alt+= komorebic resize-axis horizontal increase
|
||||
Alt+- komorebic resize-axis horizontal decrease
|
||||
Alt++ komorebic resize-axis vertical increase
|
||||
Alt+_ komorebic resize-axis vertical decrease
|
||||
Alt+T komorebic toggle-float
|
||||
Alt+Shift+T komorebic toggle-workspace-float-override
|
||||
Alt+Shift+F komorebic toggle-monocle
|
||||
Alt+Shift+R komorebic retile
|
||||
Alt+P komorebic toggle-pause
|
||||
Alt+0 komorebic toggle-window-container-behaviour
|
||||
Alt+X komorebic flip-layout horizontal
|
||||
Alt+Y komorebic flip-layout vertical
|
||||
Alt+Shift+X komorebic session-float-rule
|
||||
Alt+1 komorebic focus-workspace 0
|
||||
Alt+2 komorebic focus-workspace 1
|
||||
Alt+3 komorebic focus-workspace 2
|
||||
Alt+4 komorebic focus-workspace 3
|
||||
Alt+5 komorebic focus-workspace 4
|
||||
Alt+6 komorebic focus-workspace 5
|
||||
Alt+7 komorebic focus-workspace 6
|
||||
Alt+8 komorebic focus-workspace 7
|
||||
Alt+9 komorebic focus-workspace 8
|
||||
Alt+! komorebic move-to-workspace 0
|
||||
Alt+@ komorebic move-to-workspace 1
|
||||
Alt+# komorebic move-to-workspace 2
|
||||
Alt+$ komorebic move-to-workspace 3
|
||||
Alt+% komorebic move-to-workspace 4
|
||||
Alt+^ komorebic move-to-workspace 5
|
||||
Alt+& komorebic move-to-workspace 6
|
||||
Alt+* komorebic move-to-workspace 7
|
||||
Alt+( komorebic move-to-workspace 8
|
||||
50 shortcuts would be written to shortcuts (50 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== sample.sxhkdrc
|
||||
Alt+H komorebic focus left
|
||||
Alt+J komorebic focus down
|
||||
Alt+K komorebic focus up
|
||||
Alt+L komorebic focus right
|
||||
Alt+{ komorebic cycle-focus previous
|
||||
Alt+} komorebic cycle-focus next
|
||||
Alt+Shift+H komorebic move left
|
||||
Alt+Shift+J komorebic move down
|
||||
Alt+Shift+K komorebic move up
|
||||
Alt+Shift+L komorebic move right
|
||||
Alt+Shift+Return komorebic promote
|
||||
Ctrl+Alt+Left komorebic stack left
|
||||
Ctrl+Alt+Down komorebic stack down
|
||||
Ctrl+Alt+Up komorebic stack up
|
||||
Ctrl+Alt+Right komorebic stack right
|
||||
Alt+; komorebic unstack
|
||||
Alt+[ komorebic cycle-stack previous
|
||||
Alt+] komorebic cycle-stack next
|
||||
Alt+: komorebic toggle-workspace-layer
|
||||
Alt+= komorebic resize-axis horizontal increase
|
||||
Alt+- komorebic resize-axis horizontal decrease
|
||||
Alt++ komorebic resize-axis vertical increase
|
||||
Alt+_ komorebic resize-axis vertical decrease
|
||||
Alt+T komorebic toggle-float
|
||||
Alt+Shift+T komorebic toggle-workspace-float-override
|
||||
Alt+Shift+F komorebic toggle-monocle
|
||||
Alt+Shift+R komorebic retile
|
||||
Alt+P komorebic toggle-pause
|
||||
Alt+0 komorebic toggle-window-container-behaviour
|
||||
Alt+X komorebic flip-layout horizontal
|
||||
Alt+Y komorebic flip-layout vertical
|
||||
Alt+Shift+X komorebic session-float-rule
|
||||
Alt+1 komorebic focus-workspace 0
|
||||
Alt+2 komorebic focus-workspace 1
|
||||
Alt+3 komorebic focus-workspace 2
|
||||
Alt+4 komorebic focus-workspace 3
|
||||
Alt+5 komorebic focus-workspace 4
|
||||
Alt+6 komorebic focus-workspace 5
|
||||
Alt+7 komorebic focus-workspace 6
|
||||
Alt+8 komorebic focus-workspace 7
|
||||
Alt+9 komorebic focus-workspace 8
|
||||
Alt+! komorebic move-to-workspace 0
|
||||
Alt+@ komorebic move-to-workspace 1
|
||||
Alt+# komorebic move-to-workspace 2
|
||||
Alt+$ komorebic move-to-workspace 3
|
||||
Alt+% komorebic move-to-workspace 4
|
||||
Alt+^ komorebic move-to-workspace 5
|
||||
Alt+& komorebic move-to-workspace 6
|
||||
Alt+* komorebic move-to-workspace 7
|
||||
Alt+( komorebic move-to-workspace 8
|
||||
50 shortcuts would be written to shortcuts (50 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== sample.whkdrc
|
||||
sample.whkdrc: line 2: note: commands run through `sh -c`, not `pwsh`
|
||||
Alt+H komorebic focus left
|
||||
Alt+J komorebic focus down
|
||||
Alt+K komorebic focus up
|
||||
Alt+L komorebic focus right
|
||||
Alt+{ komorebic cycle-focus previous
|
||||
Alt+} komorebic cycle-focus next
|
||||
Alt+Shift+H komorebic move left
|
||||
Alt+Shift+J komorebic move down
|
||||
Alt+Shift+K komorebic move up
|
||||
Alt+Shift+L komorebic move right
|
||||
Alt+Shift+Return komorebic promote
|
||||
Ctrl+Alt+Left komorebic stack left
|
||||
Ctrl+Alt+Down komorebic stack down
|
||||
Ctrl+Alt+Up komorebic stack up
|
||||
Ctrl+Alt+Right komorebic stack right
|
||||
Alt+; komorebic unstack
|
||||
Alt+[ komorebic cycle-stack previous
|
||||
Alt+] komorebic cycle-stack next
|
||||
Alt+: komorebic toggle-workspace-layer
|
||||
Alt+= komorebic resize-axis horizontal increase
|
||||
Alt+- komorebic resize-axis horizontal decrease
|
||||
Alt++ komorebic resize-axis vertical increase
|
||||
Alt+_ komorebic resize-axis vertical decrease
|
||||
Alt+T komorebic toggle-float
|
||||
Alt+Shift+T komorebic toggle-workspace-float-override
|
||||
Alt+Shift+F komorebic toggle-monocle
|
||||
Alt+Shift+R komorebic retile
|
||||
Alt+P komorebic toggle-pause
|
||||
Alt+0 komorebic toggle-window-container-behaviour
|
||||
Alt+X komorebic flip-layout horizontal
|
||||
Alt+Y komorebic flip-layout vertical
|
||||
Alt+Shift+X komorebic session-float-rule
|
||||
Alt+1 komorebic focus-workspace 0
|
||||
Alt+2 komorebic focus-workspace 1
|
||||
Alt+3 komorebic focus-workspace 2
|
||||
Alt+4 komorebic focus-workspace 3
|
||||
Alt+5 komorebic focus-workspace 4
|
||||
Alt+6 komorebic focus-workspace 5
|
||||
Alt+7 komorebic focus-workspace 6
|
||||
Alt+8 komorebic focus-workspace 7
|
||||
Alt+9 komorebic focus-workspace 8
|
||||
Alt+! komorebic move-to-workspace 0
|
||||
Alt+@ komorebic move-to-workspace 1
|
||||
Alt+# komorebic move-to-workspace 2
|
||||
Alt+$ komorebic move-to-workspace 3
|
||||
Alt+% komorebic move-to-workspace 4
|
||||
Alt+^ komorebic move-to-workspace 5
|
||||
Alt+& komorebic move-to-workspace 6
|
||||
Alt+* komorebic move-to-workspace 7
|
||||
Alt+( komorebic move-to-workspace 8
|
||||
50 shortcuts would be written to shortcuts (50 new, 0 changed, 0 removed), 0 bindings need the engine
|
||||
|
||||
== scopes.skhdrc
|
||||
scopes.skhdrc: line 2: note: Alt+N goes through the engine: it does something else in each application
|
||||
Alt+H komorebic focus left
|
||||
1 shortcuts would be written to shortcuts (1 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
== scopes.whkdrc
|
||||
scopes.whkdrc: line 2: note: commands run through `sh -c`, not `pwsh`
|
||||
scopes.whkdrc: line 4: note: Alt+N goes through the engine: it does something else in each application
|
||||
Alt+H komorebic focus left
|
||||
1 shortcuts would be written to shortcuts (1 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
== vm.skhdrc
|
||||
vm.skhdrc: line 4: note: Alt+, goes through the engine: a comma cannot be written in `X-KDE-Shortcuts`
|
||||
Alt+J touch /tmp/keys-corpus-alt-j
|
||||
1 shortcuts would be written to shortcuts (1 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
== vm.sxhkdrc
|
||||
vm.sxhkdrc: line 5: note: Alt+, goes through the engine: a comma cannot be written in `X-KDE-Shortcuts`
|
||||
Alt+J touch /tmp/keys-corpus-alt-j
|
||||
1 shortcuts would be written to shortcuts (1 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
== vm.whkdrc
|
||||
vm.whkdrc: line 3: note: commands run through `sh -c`, not `pwsh`
|
||||
vm.whkdrc: line 6: note: Alt+, goes through the engine: a comma cannot be written in `X-KDE-Shortcuts`
|
||||
Alt+J touch /tmp/keys-corpus-alt-j
|
||||
1 shortcuts would be written to shortcuts (1 new, 0 changed, 0 removed), 1 bindings need the engine
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# `keybindings-fixtures`: every key binding file of the fixture corpus
|
||||
# (komorebi-hotkeys/tests/fixtures) through `komorebic hotkeys compile --mode auto --dry-run`,
|
||||
# the command the NixOS module runs, compared with `keybindings.expected`: the static shortcuts of
|
||||
# each file, the bindings left to the engine, and the diagnostics, as the build log of the module
|
||||
# shows them. After a change that means to change them, write the file again with the loop below,
|
||||
# run in the fixtures directory, and read the difference. The sample files of the user guide,
|
||||
# docs/*.sample, are the corpus's case `sample`, which this checks too.
|
||||
{
|
||||
pkgs,
|
||||
# a package with bin/komorebic
|
||||
komorebic,
|
||||
}:
|
||||
let
|
||||
inherit (pkgs) lib;
|
||||
in
|
||||
pkgs.runCommand "keybindings-fixtures"
|
||||
{
|
||||
fixtures = ../../komorebi-hotkeys/tests/fixtures;
|
||||
expected = ./keybindings.expected;
|
||||
samples = lib.fileset.toSource {
|
||||
root = ../../docs;
|
||||
fileset = lib.fileset.fileFilter (file: file.hasExt "sample") ../../docs;
|
||||
};
|
||||
}
|
||||
''
|
||||
for format in skhdrc whkdrc sxhkdrc; do
|
||||
diff -u $fixtures/sample.$format $samples/$format.sample
|
||||
done
|
||||
cd $fixtures
|
||||
for file in $(ls | sort); do
|
||||
echo "== $file"
|
||||
${komorebic}/bin/komorebic hotkeys compile --mode auto --dry-run "$file" --output shortcuts 2>&1
|
||||
echo
|
||||
done > $TMPDIR/got
|
||||
diff -u $expected $TMPDIR/got
|
||||
echo "$(ls $fixtures | wc -l) files plan as expected"
|
||||
touch $out
|
||||
''
|
||||
@@ -0,0 +1,59 @@
|
||||
# Nix equivalent of docs/komorebi.example.json
|
||||
# This tests that users can write the exact same config in Nix
|
||||
{ ... }:
|
||||
{
|
||||
komorebi = {
|
||||
app_specific_configuration_path = "$HOME/.config/komorebi/applications.json";
|
||||
cross_monitor_move_behaviour = "Insert";
|
||||
default_workspace_padding = 15;
|
||||
default_container_padding = 15;
|
||||
border = true;
|
||||
border_width = 6;
|
||||
border_offset = 5;
|
||||
floating_window_aspect_ratio = "Widescreen";
|
||||
floating_layer_behaviour = "Float";
|
||||
resize_delta = 100;
|
||||
ignore_rules = [ ];
|
||||
floating_applications = [ ];
|
||||
manage_rules = [ ];
|
||||
monitors = [
|
||||
{
|
||||
workspaces = [
|
||||
{
|
||||
name = "I";
|
||||
layout = "BSP";
|
||||
initial_workspace_rules = [ ];
|
||||
}
|
||||
{
|
||||
name = "II";
|
||||
layout = "VerticalStack";
|
||||
}
|
||||
{
|
||||
name = "III";
|
||||
layout = "HorizontalStack";
|
||||
}
|
||||
{
|
||||
name = "IV";
|
||||
layout = "UltrawideVerticalStack";
|
||||
}
|
||||
{
|
||||
name = "V";
|
||||
layout = "Rows";
|
||||
}
|
||||
{
|
||||
name = "VI";
|
||||
layout = "Grid";
|
||||
}
|
||||
{
|
||||
name = "VII";
|
||||
layout = "RightMainVerticalStack";
|
||||
}
|
||||
{
|
||||
name = "VIII";
|
||||
layout = "Scrolling";
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,885 @@
|
||||
# `nixos-module-eval`: `services.komorebi` in real NixOS systems, evaluated and never built. Each
|
||||
# scenario is a `nixosSystem` with the module, and the checks read what it evaluates to: the
|
||||
# assertions and warnings, the unit the module defines, and its read-only `execStart`. A scenario
|
||||
# that must not evaluate is caught with `builtins.tryEval`. Nothing here builds a Linux package
|
||||
# (the derivation below gets only check names and booleans), so a Mac runs it too.
|
||||
{
|
||||
pkgs,
|
||||
# nixpkgs' `lib.nixosSystem`
|
||||
nixosSystem,
|
||||
# the module, as the flake exports it, with its overlay
|
||||
module,
|
||||
# the flake's komorebi-full for a system, which the overlay has to provide
|
||||
komorebiFor,
|
||||
# the flake's KDE Rounded Corners for a system, which the overlay has to provide as well
|
||||
borderEffectFor,
|
||||
# the flake's Geometry Change for a system, likewise
|
||||
animationEffectFor,
|
||||
}:
|
||||
let
|
||||
inherit (pkgs) lib;
|
||||
|
||||
# the systems are of the host's architecture
|
||||
system = "${pkgs.stdenv.hostPlatform.parsed.cpu.name}-linux";
|
||||
|
||||
# enough of a machine for every NixOS assertion to hold, since no scenario is ever built
|
||||
machine = {
|
||||
nixpkgs.hostPlatform = system;
|
||||
boot.loader.grub.enable = false;
|
||||
fileSystems."/" = {
|
||||
device = "/dev/vda";
|
||||
fsType = "ext4";
|
||||
};
|
||||
system.stateVersion = lib.trivial.release;
|
||||
};
|
||||
|
||||
plasma = {
|
||||
services.desktopManager.plasma6.enable = true;
|
||||
};
|
||||
|
||||
eval =
|
||||
scenario:
|
||||
(nixosSystem {
|
||||
modules = [
|
||||
module
|
||||
machine
|
||||
scenario
|
||||
];
|
||||
}).config;
|
||||
|
||||
enabled = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi.enable = true;
|
||||
};
|
||||
|
||||
disabled = eval plasma;
|
||||
|
||||
withoutPlasma = eval { services.komorebi.enable = true; };
|
||||
|
||||
debug = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
logLevel = "debug";
|
||||
};
|
||||
};
|
||||
|
||||
# a package that is not the overlay's: any package will do, since nothing is built
|
||||
otherPackage = eval (
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
package = pkgs.hello;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
withConfigFile = eval (
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
configFile = pkgs.writeText "komorebi.json" "{}";
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
withConfig = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
config = {
|
||||
default_workspace_padding = 20;
|
||||
window_container_behaviour = "Append";
|
||||
float_override_placement = "Center";
|
||||
monocle_focus_behaviour = "Cycle";
|
||||
monitors = [
|
||||
{
|
||||
floating_layer_behaviour = "Tile";
|
||||
workspaces = [
|
||||
{
|
||||
name = "web";
|
||||
layout = "BSP";
|
||||
}
|
||||
{
|
||||
name = "code";
|
||||
layout = "Columns";
|
||||
window_container_behaviour_rules."2" = "Append";
|
||||
float_override = false;
|
||||
floating_layer_behaviour = "Float";
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
# where a workspace puts the windows that open, in each form komorebi reads: a name, a number,
|
||||
# text that is a number, and a map of places to rules
|
||||
withPlacement = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
config.monitors = [
|
||||
{
|
||||
workspaces = [
|
||||
{
|
||||
name = "name";
|
||||
initial_window_placement_rules = "Primary";
|
||||
}
|
||||
{
|
||||
name = "number";
|
||||
initial_window_placement_rules = 3;
|
||||
}
|
||||
{
|
||||
name = "text";
|
||||
initial_window_placement_rules = "3";
|
||||
}
|
||||
{
|
||||
name = "map";
|
||||
initial_window_placement_rules = {
|
||||
Primary = {
|
||||
kind = "Exe";
|
||||
id = "firefox";
|
||||
matching_strategy = "Equals";
|
||||
};
|
||||
};
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
# a layout komorebi does not have
|
||||
badLayout = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
config.monitors = [
|
||||
{
|
||||
workspaces = [
|
||||
{
|
||||
name = "x";
|
||||
layout = "Nope";
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
withSource = eval (
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
config.resize_delta = 70;
|
||||
applicationSpecificConfiguration.sources = [
|
||||
{
|
||||
owner = "someone";
|
||||
repo = "komorebi-rules";
|
||||
rev = "0123456789abcdef0123456789abcdef01234567";
|
||||
hash = pkgs.lib.fakeHash;
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
# the same source and config, with the sources turned off
|
||||
withSourceOff = eval (
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
config.resize_delta = 70;
|
||||
applicationSpecificConfiguration = {
|
||||
enable = false;
|
||||
sources = [
|
||||
{
|
||||
owner = "someone";
|
||||
repo = "komorebi-rules";
|
||||
rev = "0123456789abcdef0123456789abcdef01234567";
|
||||
hash = pkgs.lib.fakeHash;
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
# the sources turned off, and no config: nothing is left to write
|
||||
onlySourceOff = eval (
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
applicationSpecificConfiguration = {
|
||||
enable = false;
|
||||
sources = [
|
||||
{
|
||||
owner = "someone";
|
||||
repo = "komorebi-rules";
|
||||
rev = "0123456789abcdef0123456789abcdef01234567";
|
||||
hash = pkgs.lib.fakeHash;
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
bothConfigs = eval (
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
configFile = pkgs.writeText "komorebi.json" "{}";
|
||||
config.resize_delta = 70;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
noBorderEffect = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
effects.borders.enable = false;
|
||||
};
|
||||
};
|
||||
|
||||
# borders asked for in the configuration, and the effect that draws them left out
|
||||
borderWithoutEffect = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
config.border = true;
|
||||
effects.borders.enable = false;
|
||||
};
|
||||
};
|
||||
|
||||
# the same, with the effect installed, and with borders turned off in the configuration
|
||||
borderWithEffect = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
config.border = true;
|
||||
};
|
||||
};
|
||||
|
||||
noBorderWithoutEffect = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
config.border = false;
|
||||
effects.borders.enable = false;
|
||||
};
|
||||
};
|
||||
|
||||
noAnimationEffect = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
effects.animation.enable = false;
|
||||
};
|
||||
};
|
||||
|
||||
# a package that is not the overlay's: any package will do, since nothing is built
|
||||
otherBorderEffect = eval (
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
effects.borders.package = pkgs.hello;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
unknownLevel = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
logLevel = "verbose";
|
||||
};
|
||||
};
|
||||
|
||||
execStartSet = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
execStart = "/bin/true";
|
||||
};
|
||||
};
|
||||
|
||||
keybindings =
|
||||
settings:
|
||||
eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
keybindings = settings;
|
||||
};
|
||||
};
|
||||
|
||||
withText = keybindings {
|
||||
format = "skhd";
|
||||
text = "alt - h : komorebic focus left\n";
|
||||
mode = "auto";
|
||||
chordTimeout = 1500;
|
||||
appAliases.terminal = [
|
||||
"foot"
|
||||
"konsole"
|
||||
];
|
||||
};
|
||||
|
||||
withFile = keybindings {
|
||||
format = "sxhkd";
|
||||
file = ../../komorebi-hotkeys/tests/fixtures/plain.sxhkdrc;
|
||||
};
|
||||
|
||||
textAndFile = keybindings {
|
||||
format = "skhd";
|
||||
text = "alt - h : komorebic focus left\n";
|
||||
file = ../../komorebi-hotkeys/tests/fixtures/plain.skhdrc;
|
||||
};
|
||||
|
||||
# the typed `config` and the key bindings are two parts of one command line
|
||||
withConfigAndKeybindings = eval {
|
||||
imports = [ plasma ];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
config.default_workspace_padding = 20;
|
||||
keybindings = {
|
||||
format = "skhd";
|
||||
text = "alt - h : komorebic focus left\n";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
withoutFormat = keybindings { text = "alt - h : komorebic focus left\n"; };
|
||||
|
||||
withLoad = keybindings {
|
||||
format = "skhd";
|
||||
text = ".load \"/home/me/.config/skhd/more\"\nalt - h : komorebic focus left\n";
|
||||
};
|
||||
|
||||
# a file with a line komorebic cannot read, which the build only reports unless `strict` is set.
|
||||
# Evaluation does not read the bindings the way komorebic does (it looks for skhd's .load and no
|
||||
# more), so what `strict` changes is the build of the compiled key bindings: its script is what
|
||||
# these checks read, and the build that fails is not run here.
|
||||
unreadableLine = "alt - h : komorebic focus left\nalt - nosuchkey : komorebic focus up\n";
|
||||
|
||||
withStrict = keybindings {
|
||||
format = "skhd";
|
||||
text = unreadableLine;
|
||||
strict = true;
|
||||
};
|
||||
|
||||
withoutStrict = keybindings {
|
||||
format = "skhd";
|
||||
text = unreadableLine;
|
||||
};
|
||||
|
||||
# the package that compiles the key bindings, and the script that builds it
|
||||
compiled =
|
||||
config: lib.findFirst (p: p.name == "komorebi-keybindings") null config.environment.systemPackages;
|
||||
compileScript = config: (compiled config).buildCommand;
|
||||
|
||||
installed = config: map (p: p.name) config.environment.systemPackages;
|
||||
|
||||
supportedKwin = import ../supported-kwin.nix;
|
||||
|
||||
# The scenarios above have the KWin of the flake's nixpkgs, which the weekly canary moves to the
|
||||
# tip of nixpkgs-unstable, so no check depends on its version. These give the system a KWin of
|
||||
# a version of their own: nothing is built, so the package keeps its store path and only the
|
||||
# version the module reads changes.
|
||||
kwinAt = version: {
|
||||
nixpkgs.overlays = [
|
||||
(_: prev: {
|
||||
kdePackages = prev.kdePackages // {
|
||||
kwin = prev.kdePackages.kwin // {
|
||||
inherit version;
|
||||
};
|
||||
};
|
||||
})
|
||||
];
|
||||
};
|
||||
|
||||
withKwin =
|
||||
version: settings:
|
||||
eval {
|
||||
imports = [
|
||||
plasma
|
||||
(kwinAt version)
|
||||
];
|
||||
services.komorebi = {
|
||||
enable = true;
|
||||
}
|
||||
// settings;
|
||||
};
|
||||
|
||||
# a KWin of Plasma 6.7, and one of the next major version after the newest one tested
|
||||
olderKwin = "6.7.5";
|
||||
newerKwin = "${toString (lib.toInt (lib.versions.major supportedKwin.testedMax) + 1)}.0";
|
||||
|
||||
kwinTooOld = withKwin olderKwin { };
|
||||
kwinAtMin = withKwin supportedKwin.min { };
|
||||
kwinTested = withKwin supportedKwin.testedMax { };
|
||||
kwinNewer = withKwin newerKwin { };
|
||||
kwinNewerIsError = withKwin newerKwin { kwin.untestedIsError = true; };
|
||||
kwinTestedIsError = withKwin supportedKwin.testedMax { kwin.untestedIsError = true; };
|
||||
kwinTooOldDisabled = eval {
|
||||
imports = [
|
||||
plasma
|
||||
(kwinAt olderKwin)
|
||||
];
|
||||
};
|
||||
|
||||
failed = config: map (a: a.message) (lib.filter (a: !a.assertion) config.assertions);
|
||||
# the module's warnings, and not those other modules may have
|
||||
kwinWarnings = config: lib.filter (lib.hasInfix "untestedIsError") config.warnings;
|
||||
unit = config: config.systemd.user.services.komorebi;
|
||||
evaluates = value: (builtins.tryEval value).success;
|
||||
|
||||
checks = [
|
||||
{
|
||||
name = "enabled with Plasma 6, every assertion holds";
|
||||
ok = failed enabled == [ ];
|
||||
got = failed enabled;
|
||||
}
|
||||
{
|
||||
name = "the unit is started by plasma-workspace.target";
|
||||
ok = (unit enabled).wantedBy == [ "plasma-workspace.target" ];
|
||||
got = (unit enabled).wantedBy;
|
||||
}
|
||||
{
|
||||
name = "the unit starts after plasma-core.target";
|
||||
ok = lib.elem "plasma-core.target" (unit enabled).after;
|
||||
got = (unit enabled).after;
|
||||
}
|
||||
{
|
||||
name = "the unit is restarted when it fails";
|
||||
ok = (unit enabled).serviceConfig.Restart == "on-failure";
|
||||
}
|
||||
{
|
||||
name = "the unit counts the exit status of a SIGTERM (130) as success";
|
||||
ok = (unit enabled).serviceConfig.SuccessExitStatus == 130;
|
||||
}
|
||||
{
|
||||
name = "the unit releases the keys of the daemon when it stops";
|
||||
ok =
|
||||
(unit enabled).serviceConfig.ExecStopPost
|
||||
== "${enabled.services.komorebi.package}/bin/komorebic hotkeys release";
|
||||
got = (unit enabled).serviceConfig.ExecStopPost;
|
||||
}
|
||||
{
|
||||
name = "the unit runs execStart";
|
||||
ok = (unit enabled).serviceConfig.ExecStart == enabled.services.komorebi.execStart;
|
||||
got = (unit enabled).serviceConfig.ExecStart;
|
||||
}
|
||||
{
|
||||
name = "execStart is bin/komorebi of the package, at the info level";
|
||||
ok =
|
||||
enabled.services.komorebi.execStart
|
||||
== "${enabled.services.komorebi.package}/bin/komorebi --log-level info";
|
||||
got = enabled.services.komorebi.execStart;
|
||||
}
|
||||
{
|
||||
name = "the default package is the flake's komorebi-full, from the overlay";
|
||||
ok = enabled.services.komorebi.package.outPath == (komorebiFor system).outPath;
|
||||
}
|
||||
{
|
||||
name = "the unit has the PATH of the user's session";
|
||||
ok =
|
||||
(unit enabled).environment.PATH
|
||||
== "/run/wrappers/bin:/etc/profiles/per-user/%u/bin:/run/current-system/sw/bin";
|
||||
got = (unit enabled).environment.PATH;
|
||||
}
|
||||
{
|
||||
name = "the package is installed in the system profile";
|
||||
ok = lib.elem enabled.services.komorebi.package enabled.environment.systemPackages;
|
||||
}
|
||||
{
|
||||
name = "the default border effect is the flake's KDE Rounded Corners, from the overlay";
|
||||
ok = enabled.services.komorebi.effects.borders.package.outPath == (borderEffectFor system).outPath;
|
||||
}
|
||||
{
|
||||
name = "the border effect is installed in the system profile";
|
||||
ok = lib.elem enabled.services.komorebi.effects.borders.package enabled.environment.systemPackages;
|
||||
}
|
||||
{
|
||||
name = "with the border effect off, komorebi is installed and the effect is not";
|
||||
ok =
|
||||
lib.elem noBorderEffect.services.komorebi.package noBorderEffect.environment.systemPackages
|
||||
&& !(lib.elem noBorderEffect.services.komorebi.effects.borders.package noBorderEffect.environment.systemPackages);
|
||||
}
|
||||
{
|
||||
name = "another border effect is the one installed";
|
||||
ok =
|
||||
lib.elem otherBorderEffect.services.komorebi.effects.borders.package otherBorderEffect.environment.systemPackages
|
||||
&& !(lib.elem enabled.services.komorebi.effects.borders.package otherBorderEffect.environment.systemPackages);
|
||||
}
|
||||
{
|
||||
name = "the default animation effect is the flake's Geometry Change, from the overlay";
|
||||
ok =
|
||||
enabled.services.komorebi.effects.animation.package.outPath == (animationEffectFor system).outPath;
|
||||
}
|
||||
{
|
||||
name = "the animation effect is installed in the system profile";
|
||||
ok = lib.elem enabled.services.komorebi.effects.animation.package enabled.environment.systemPackages;
|
||||
}
|
||||
{
|
||||
name = "with the animation effect off, the border effect is installed and the animation effect is not";
|
||||
ok =
|
||||
lib.elem noAnimationEffect.services.komorebi.effects.borders.package noAnimationEffect.environment.systemPackages
|
||||
&& !(lib.elem noAnimationEffect.services.komorebi.effects.animation.package noAnimationEffect.environment.systemPackages);
|
||||
}
|
||||
{
|
||||
name = "a configuration that draws borders, without the effect that draws them, is warned about";
|
||||
ok = lib.any (lib.hasInfix "effects.borders.enable is false") borderWithoutEffect.warnings;
|
||||
got = borderWithoutEffect.warnings;
|
||||
}
|
||||
{
|
||||
name = "borders with the effect, and no borders without it, are not warned about";
|
||||
ok =
|
||||
!(lib.any (lib.hasInfix "effects.borders") borderWithEffect.warnings)
|
||||
&& !(lib.any (lib.hasInfix "effects.borders") noBorderWithoutEffect.warnings)
|
||||
&& !(lib.any (lib.hasInfix "effects.borders") noBorderEffect.warnings);
|
||||
got = borderWithEffect.warnings ++ noBorderWithoutEffect.warnings ++ noBorderEffect.warnings;
|
||||
}
|
||||
{
|
||||
name = "disabled, every assertion holds";
|
||||
ok = failed disabled == [ ];
|
||||
got = failed disabled;
|
||||
}
|
||||
{
|
||||
name = "disabled, there is no unit";
|
||||
ok = !(disabled.systemd.user.services ? komorebi);
|
||||
}
|
||||
{
|
||||
name = "disabled, nothing is installed";
|
||||
ok =
|
||||
!(lib.elem disabled.services.komorebi.package disabled.environment.systemPackages)
|
||||
&& !(lib.elem disabled.services.komorebi.effects.borders.package disabled.environment.systemPackages)
|
||||
&& !(lib.elem disabled.services.komorebi.effects.animation.package disabled.environment.systemPackages);
|
||||
}
|
||||
{
|
||||
name = "without Plasma 6, an assertion fails and names the option to set";
|
||||
ok = lib.any (lib.hasInfix "services.desktopManager.plasma6.enable = true") (failed withoutPlasma);
|
||||
got = failed withoutPlasma;
|
||||
}
|
||||
{
|
||||
name = "logLevel reaches execStart and the unit";
|
||||
ok =
|
||||
debug.services.komorebi.execStart
|
||||
== "${debug.services.komorebi.package}/bin/komorebi --log-level debug"
|
||||
&& (unit debug).serviceConfig.ExecStart == debug.services.komorebi.execStart;
|
||||
got = (unit debug).serviceConfig.ExecStart;
|
||||
}
|
||||
{
|
||||
name = "another package is the one the unit runs and the one installed";
|
||||
ok =
|
||||
(unit otherPackage).serviceConfig.ExecStart
|
||||
== "${otherPackage.services.komorebi.package}/bin/komorebi --log-level info"
|
||||
&& lib.elem otherPackage.services.komorebi.package otherPackage.environment.systemPackages;
|
||||
got = (unit otherPackage).serviceConfig.ExecStart;
|
||||
}
|
||||
{
|
||||
name = "without a configFile, the unit passes no --config";
|
||||
ok = !(lib.hasInfix "--config" enabled.services.komorebi.execStart);
|
||||
got = enabled.services.komorebi.execStart;
|
||||
}
|
||||
{
|
||||
name = "configFile reaches execStart and the unit as --config, after the log level";
|
||||
ok =
|
||||
lib.hasPrefix "${withConfigFile.services.komorebi.package}/bin/komorebi --log-level info --config /nix/store/" withConfigFile.services.komorebi.execStart
|
||||
&& (unit withConfigFile).serviceConfig.ExecStart == withConfigFile.services.komorebi.execStart;
|
||||
got = (unit withConfigFile).serviceConfig.ExecStart;
|
||||
}
|
||||
{
|
||||
name = "with neither a configFile nor a config, there is nothing to write";
|
||||
ok = enabled.services.komorebi.internal.configAttrs == null;
|
||||
}
|
||||
{
|
||||
name = "config is the komorebi.json the daemon is given, with no null left in it";
|
||||
ok =
|
||||
withConfig.services.komorebi.internal.configAttrs.default_workspace_padding == 20
|
||||
&&
|
||||
map (w: w.name) (lib.head withConfig.services.komorebi.internal.configAttrs.monitors).workspaces
|
||||
== [
|
||||
"web"
|
||||
"code"
|
||||
]
|
||||
&& !(lib.hasInfix "null" (builtins.toJSON withConfig.services.komorebi.internal.configAttrs));
|
||||
got = withConfig.services.komorebi.internal.configAttrs;
|
||||
}
|
||||
{
|
||||
name = "the keys of the stacks, the float override, monocle and the floating layer are typed options";
|
||||
ok =
|
||||
withConfig.services.komorebi.internal.configAttrs.window_container_behaviour == "Append"
|
||||
&& withConfig.services.komorebi.internal.configAttrs.float_override_placement == "Center"
|
||||
&& withConfig.services.komorebi.internal.configAttrs.monocle_focus_behaviour == "Cycle"
|
||||
&&
|
||||
(lib.head withConfig.services.komorebi.internal.configAttrs.monitors).floating_layer_behaviour
|
||||
== "Tile"
|
||||
&&
|
||||
(lib.elemAt (lib.head withConfig.services.komorebi.internal.configAttrs.monitors).workspaces 1)
|
||||
.window_container_behaviour_rules."2" == "Append";
|
||||
got = withConfig.services.komorebi.internal.configAttrs;
|
||||
}
|
||||
{
|
||||
name = "the place a workspace gives the windows that open is a typed option in each form it is read";
|
||||
ok =
|
||||
let
|
||||
workspaces = (lib.head withPlacement.services.komorebi.internal.configAttrs.monitors).workspaces;
|
||||
place = name: (lib.findFirst (w: w.name == name) null workspaces).initial_window_placement_rules;
|
||||
in
|
||||
place "name" == "Primary"
|
||||
&& place "number" == 3
|
||||
&& place "text" == "3"
|
||||
&& (place "map").Primary.id == "firefox";
|
||||
got = withPlacement.services.komorebi.internal.configAttrs;
|
||||
}
|
||||
{
|
||||
name = "config reaches execStart as a komorebi.json that was checked against the schema";
|
||||
ok =
|
||||
lib.hasInfix " --config " withConfig.services.komorebi.execStart
|
||||
&& lib.hasSuffix "-validated-komorebi.json" withConfig.services.komorebi.execStart
|
||||
&& (unit withConfig).serviceConfig.ExecStart == withConfig.services.komorebi.execStart;
|
||||
got = withConfig.services.komorebi.execStart;
|
||||
}
|
||||
{
|
||||
name = "configFile is checked against the schema too";
|
||||
ok = lib.hasSuffix "-validated-komorebi.json" withConfigFile.services.komorebi.execStart;
|
||||
got = withConfigFile.services.komorebi.execStart;
|
||||
}
|
||||
{
|
||||
name = "a layout komorebi does not have does not evaluate";
|
||||
ok = !(evaluates (builtins.deepSeq badLayout.services.komorebi.internal.configAttrs true));
|
||||
}
|
||||
{
|
||||
name = "a source of application specific configuration is the daemon's app_specific_configuration_path";
|
||||
ok =
|
||||
lib.hasSuffix "-applications.json" withSource.services.komorebi.internal.configAttrs.app_specific_configuration_path
|
||||
&& withSource.services.komorebi.internal.configAttrs.resize_delta == 70;
|
||||
got = withSource.services.komorebi.internal.configAttrs.app_specific_configuration_path;
|
||||
}
|
||||
{
|
||||
name = "with applicationSpecificConfiguration.enable = false, the sources are left out of config";
|
||||
ok =
|
||||
withSource.services.komorebi.internal.configAttrs ? app_specific_configuration_path
|
||||
&& !(withSourceOff.services.komorebi.internal.configAttrs ? app_specific_configuration_path)
|
||||
&& withSourceOff.services.komorebi.internal.configAttrs.resize_delta == 70;
|
||||
got = withSourceOff.services.komorebi.internal.configAttrs;
|
||||
}
|
||||
{
|
||||
name = "with the sources turned off and no config, there is nothing to write and no --config";
|
||||
ok =
|
||||
onlySourceOff.services.komorebi.internal.configAttrs == null
|
||||
&& !(lib.hasInfix "--config" onlySourceOff.services.komorebi.execStart);
|
||||
got = onlySourceOff.services.komorebi.execStart;
|
||||
}
|
||||
{
|
||||
name = "with a configFile, config is ignored, and the module says so";
|
||||
ok =
|
||||
lib.any (lib.hasInfix "services.komorebi.config is ignored") bothConfigs.warnings
|
||||
&& lib.hasSuffix "-validated-komorebi.json" bothConfigs.services.komorebi.execStart;
|
||||
got = bothConfigs.warnings;
|
||||
}
|
||||
{
|
||||
name = "a log level the daemon does not have does not evaluate";
|
||||
ok = !(evaluates unknownLevel.services.komorebi.logLevel);
|
||||
}
|
||||
{
|
||||
name = "execStart cannot be set";
|
||||
ok = !(evaluates execStartSet.services.komorebi.execStart);
|
||||
}
|
||||
{
|
||||
name = "without key bindings, nothing is compiled";
|
||||
ok = !(lib.elem "komorebi-keybindings" (installed enabled));
|
||||
got = installed enabled;
|
||||
}
|
||||
{
|
||||
name = "key bindings as text: every assertion holds";
|
||||
ok = failed withText == [ ];
|
||||
got = failed withText;
|
||||
}
|
||||
{
|
||||
name = "key bindings as text reach execStart, with the mode, the chord timeout and the aliases";
|
||||
# a regular expression cannot refer to a store path, so both lose their context
|
||||
ok =
|
||||
builtins.match (
|
||||
lib.escapeRegex (
|
||||
builtins.unsafeDiscardStringContext "${withText.services.komorebi.package}/bin/komorebi"
|
||||
)
|
||||
+ " --log-level info"
|
||||
+ " --keybindings /nix/store/[a-z0-9]+-komorebi-skhdrc --keybindings-format skhd"
|
||||
+ " --keybindings-mode auto --chord-timeout 1500 --app-alias 'terminal=foot,konsole'"
|
||||
) (builtins.unsafeDiscardStringContext withText.services.komorebi.execStart) != null;
|
||||
got = withText.services.komorebi.execStart;
|
||||
}
|
||||
{
|
||||
name = "the compiled key bindings are installed in the system profile";
|
||||
ok = lib.elem "komorebi-keybindings" (installed withText);
|
||||
got = installed withText;
|
||||
}
|
||||
{
|
||||
name = "key bindings from a file reach execStart, in the default mode, engine";
|
||||
ok = lib.hasInfix "-plain.sxhkdrc --keybindings-format sxhkd --keybindings-mode engine --chord-timeout 3000" withFile.services.komorebi.execStart;
|
||||
got = withFile.services.komorebi.execStart;
|
||||
}
|
||||
{
|
||||
name = "a typed config and key bindings reach execStart together: the checked file, then the keys";
|
||||
ok =
|
||||
failed withConfigAndKeybindings == [ ]
|
||||
&&
|
||||
builtins.match (
|
||||
".* --log-level info --config /nix/store/[a-z0-9]+-validated-komorebi.json"
|
||||
+ " --keybindings /nix/store/[a-z0-9]+-komorebi-skhdrc --keybindings-format skhd"
|
||||
+ " --keybindings-mode engine --chord-timeout 3000"
|
||||
) (builtins.unsafeDiscardStringContext withConfigAndKeybindings.services.komorebi.execStart) != null
|
||||
&& withConfigAndKeybindings.services.komorebi.internal.configAttrs.default_workspace_padding == 20;
|
||||
got = withConfigAndKeybindings.services.komorebi.execStart;
|
||||
}
|
||||
{
|
||||
name = "text and file together: an assertion fails";
|
||||
ok = lib.any (lib.hasInfix "exactly one of text and file") (failed textAndFile);
|
||||
got = failed textAndFile;
|
||||
}
|
||||
{
|
||||
name = "key bindings without a format: an assertion fails";
|
||||
ok = lib.any (lib.hasInfix "needs a format") (failed withoutFormat);
|
||||
got = failed withoutFormat;
|
||||
}
|
||||
{
|
||||
name = "skhd's .load: an assertion fails";
|
||||
ok = lib.any (lib.hasInfix ".load is not supported") (failed withLoad);
|
||||
got = failed withLoad;
|
||||
}
|
||||
{
|
||||
name = "with strict, the build of the key bindings runs komorebic hotkeys compile --strict, and fails when it does";
|
||||
ok =
|
||||
failed withStrict == [ ]
|
||||
&& lib.hasInfix "hotkeys compile" (compileScript withStrict)
|
||||
&& lib.hasInfix "--strict" (compileScript withStrict)
|
||||
&& lib.hasInfix "exit 1" (compileScript withStrict);
|
||||
got = compileScript withStrict;
|
||||
}
|
||||
{
|
||||
name = "without strict, a line komorebic cannot read is a warning in the build log: no --strict";
|
||||
ok =
|
||||
failed withoutStrict == [ ]
|
||||
&& lib.hasInfix "hotkeys compile" (compileScript withoutStrict)
|
||||
&& !(lib.hasInfix "--strict" (compileScript withoutStrict))
|
||||
&& lib.hasInfix "cat $out/diagnostics.txt >&2" (compileScript withoutStrict);
|
||||
got = compileScript withoutStrict;
|
||||
}
|
||||
{
|
||||
name = "strict is for the build: the daemon is started with the same command line either way";
|
||||
ok = withStrict.services.komorebi.execStart == withoutStrict.services.komorebi.execStart;
|
||||
got = withStrict.services.komorebi.execStart;
|
||||
}
|
||||
{
|
||||
name = "a layout other than us does not evaluate";
|
||||
ok =
|
||||
!(evaluates
|
||||
(keybindings {
|
||||
format = "skhd";
|
||||
text = "";
|
||||
layout = "de";
|
||||
}).services.komorebi.keybindings.layout
|
||||
);
|
||||
}
|
||||
{
|
||||
name = "untestedIsError is false by default";
|
||||
ok = enabled.services.komorebi.kwin.untestedIsError == false;
|
||||
}
|
||||
{
|
||||
name = "a KWin older than min fails an assertion that names min and the version";
|
||||
ok = lib.any (
|
||||
message: lib.hasInfix "KWin ${supportedKwin.min} or newer" message && lib.hasInfix olderKwin message
|
||||
) (failed kwinTooOld);
|
||||
got = failed kwinTooOld;
|
||||
}
|
||||
{
|
||||
name = "with a KWin older than min, the system does not evaluate";
|
||||
ok = !(evaluates kwinTooOld.system.build.toplevel.drvPath);
|
||||
}
|
||||
{
|
||||
name = "with the KWin of min, the system evaluates";
|
||||
ok = evaluates kwinAtMin.system.build.toplevel.drvPath;
|
||||
}
|
||||
{
|
||||
name = "the KWin of min is supported, with no warning";
|
||||
ok = failed kwinAtMin == [ ] && kwinWarnings kwinAtMin == [ ];
|
||||
got = failed kwinAtMin ++ kwinWarnings kwinAtMin;
|
||||
}
|
||||
{
|
||||
name = "the KWin of testedMax is supported, with no warning";
|
||||
ok = failed kwinTested == [ ] && kwinWarnings kwinTested == [ ];
|
||||
got = failed kwinTested ++ kwinWarnings kwinTested;
|
||||
}
|
||||
{
|
||||
name = "a KWin newer than testedMax is a warning that names it and testedMax";
|
||||
ok =
|
||||
failed kwinNewer == [ ]
|
||||
&& lib.any (
|
||||
warning: lib.hasInfix newerKwin warning && lib.hasInfix supportedKwin.testedMax warning
|
||||
) (kwinWarnings kwinNewer);
|
||||
got = failed kwinNewer ++ kwinWarnings kwinNewer;
|
||||
}
|
||||
{
|
||||
name = "with untestedIsError, a KWin newer than testedMax fails an assertion, with no warning";
|
||||
ok =
|
||||
lib.any (lib.hasInfix "untestedIsError is true") (failed kwinNewerIsError)
|
||||
&& kwinWarnings kwinNewerIsError == [ ];
|
||||
got = failed kwinNewerIsError ++ kwinWarnings kwinNewerIsError;
|
||||
}
|
||||
{
|
||||
name = "with untestedIsError, the KWin of testedMax is supported";
|
||||
ok = failed kwinTestedIsError == [ ];
|
||||
got = failed kwinTestedIsError;
|
||||
}
|
||||
{
|
||||
name = "disabled, a KWin older than min is not refused";
|
||||
ok = failed kwinTooOldDisabled == [ ] && kwinWarnings kwinTooOldDisabled == [ ];
|
||||
got = failed kwinTooOldDisabled;
|
||||
}
|
||||
];
|
||||
|
||||
failures = lib.filter (check: !check.ok) checks;
|
||||
|
||||
# what a failed check got, without the store paths' context: this derivation must not depend on
|
||||
# a Linux package
|
||||
show =
|
||||
check:
|
||||
check.name
|
||||
+ lib.optionalString (check ? got) (
|
||||
": got " + builtins.unsafeDiscardStringContext (builtins.toJSON check.got)
|
||||
);
|
||||
in
|
||||
pkgs.runCommand "nixos-module-eval" { } (
|
||||
if failures == [ ] then
|
||||
''
|
||||
${lib.concatMapStringsSep "\n" (check: "echo ${lib.escapeShellArg "ok: ${check.name}"}") checks}
|
||||
echo "${toString (lib.length checks)} checks of services.komorebi passed"
|
||||
touch $out
|
||||
''
|
||||
else
|
||||
''
|
||||
${lib.concatMapStringsSep "\n" (
|
||||
check: "echo ${lib.escapeShellArg "FAILED: ${show check}"}"
|
||||
) failures}
|
||||
exit 1
|
||||
''
|
||||
)
|
||||
@@ -0,0 +1,113 @@
|
||||
# What `run-kde` says and starts, for machines that a test makes up from the variables the script
|
||||
# reads (RUN_KDE_*, WAYLAND_DISPLAY, DISPLAY): a WSL 2 with WSLg and a GPU, one with WSLg and a
|
||||
# software OpenGL or none, a Linux machine with no window, and machines that cannot run the guest.
|
||||
# `--dry-run` prints what the script would start, which is the environment and the arguments the
|
||||
# runner is given; `--doctor` prints what the machine lacks and how to fix it, and starts the
|
||||
# virtiofsd of nixpkgs for real, as the sandbox's user, to see that it serves a directory. The
|
||||
# sandbox has no KVM, no GPU and no WSL, which is the point: the script's answer does not depend on
|
||||
# the machine it is run on. The expected texts are in `run-kde/`.
|
||||
{ pkgs, runKde }:
|
||||
let
|
||||
exe = pkgs.lib.getExe runKde;
|
||||
|
||||
# The files that stand for a machine, and a command that runs the script in an environment of its
|
||||
# own, with the variables that follow it. @T@ is where the files are, which the expected texts do
|
||||
# not keep.
|
||||
setup = ''
|
||||
t=$PWD/machine
|
||||
mkdir -p $t/bin $t/repo $t/dri $t/wsl-lib $t/va
|
||||
touch $t/repo/flake.nix $t/kvm $t/kvm-denied $t/fuse $t/dxg $t/va/d3d12_drv_video.so
|
||||
chmod 000 $t/kvm-denied
|
||||
printf '#!/bin/sh\n' > $t/bin/nix
|
||||
printf '#!/bin/sh\necho "[ERROR virtiofsd] Error creating the vhost-user socket: Address in use (os error 98)" >&2\nexit 1\n' > $t/bin/virtiofsd-broken
|
||||
chmod +x $t/bin/nix $t/bin/virtiofsd-broken
|
||||
printf 'MemTotal: 16777216 kB\n' > $t/meminfo
|
||||
printf 'MemTotal: 6291456 kB\n' > $t/meminfo-small
|
||||
printf '5.15.167.4-microsoft-standard-WSL2\n' > $t/osrelease-wsl
|
||||
printf '6.18.0\n' > $t/osrelease-linux
|
||||
printf 'flags : fpu vme svm sse\n' > $t/cpuinfo-svm
|
||||
printf 'flags : fpu vme sse\n' > $t/cpuinfo-none
|
||||
|
||||
machine() {
|
||||
env -i PATH=$t/bin:$PATH HOME=/home/user XDG_STATE_HOME=/state \
|
||||
KOMOREBI_REPO=$t/repo RUN_KDE_GUEST=run-kde-x86_64 \
|
||||
RUN_KDE_RUNNER_BIN=/nix/store/fake-nixos-vm/bin/run-komorebi-demo-vm \
|
||||
RUN_KDE_CPUINFO=$t/cpuinfo-svm RUN_KDE_STORE_DIR=$t RUN_KDE_FREE_GB=100 \
|
||||
RUN_KDE_DRI_DIR=$t/dri RUN_KDE_CPUS=12 RUN_KDE_FUSE_DEVICE=$t/fuse \
|
||||
RUN_KDE_WSL_LIB_DIR=$t/wsl-lib RUN_KDE_VA_DRIVERS_DIR=$t/va \
|
||||
"$@"
|
||||
}
|
||||
plain() { sed "s|$t|@T@|g"; }
|
||||
'';
|
||||
|
||||
# a WSL 2 with WSLg, 16 GB of memory and KVM; and a Linux machine with none of WSL
|
||||
wslg = "WAYLAND_DISPLAY=wayland-0 DISPLAY=:0 RUN_KDE_OSRELEASE=$t/osrelease-wsl RUN_KDE_KVM_DEVICE=$t/kvm RUN_KDE_MEMINFO=$t/meminfo";
|
||||
linux = "RUN_KDE_OSRELEASE=$t/osrelease-linux RUN_KDE_KVM_DEVICE=$t/kvm RUN_KDE_MEMINFO=$t/meminfo RUN_KDE_HOST_RENDERER=";
|
||||
|
||||
# runs `command`, which has to exit with `status` and print what `run-kde/NAME.expected` has
|
||||
scenario = name: status: command: ''
|
||||
echo "== ${name}"
|
||||
set +e
|
||||
${command} > ${name}.raw 2>&1
|
||||
got=$?
|
||||
set -e
|
||||
plain < ${name}.raw > ${name}.out
|
||||
if [ "$got" != ${toString status} ]; then
|
||||
echo "${name}: the exit status is $got, not ${toString status}"
|
||||
cat ${name}.out
|
||||
exit 1
|
||||
fi
|
||||
diff -u ${./run-kde + "/${name}.expected"} ${name}.out
|
||||
'';
|
||||
|
||||
check =
|
||||
name: scenarios:
|
||||
pkgs.runCommand name { nativeBuildInputs = [ pkgs.diffutils ]; } ''
|
||||
${setup}
|
||||
${builtins.concatStringsSep "\n" scenarios}
|
||||
touch $out
|
||||
'';
|
||||
in
|
||||
{
|
||||
run-kde-dry-run = check "run-kde-dry-run" [
|
||||
(scenario "dry-run-wslg-gpu" 0
|
||||
''machine ${wslg} RUN_KDE_DXG_DEVICE=$t/dxg "RUN_KDE_HOST_RENDERER=D3D12 (AMD Radeon RX 7800 XT)" ${exe} --dry-run''
|
||||
)
|
||||
# without the d3d12 video driver the host's GPU still renders, and nothing says libva which driver
|
||||
(scenario "dry-run-wslg-gpu-no-video-driver" 0
|
||||
''machine ${wslg} RUN_KDE_DXG_DEVICE=$t/dxg "RUN_KDE_HOST_RENDERER=D3D12 (AMD Radeon RX 7800 XT)" RUN_KDE_VA_DRIVERS_DIR=$t/absent ${exe} --dry-run''
|
||||
)
|
||||
# what a person has set is kept, and the directory of Windows' libraries comes first
|
||||
(scenario "dry-run-wslg-gpu-own-env" 0
|
||||
''machine ${wslg} RUN_KDE_DXG_DEVICE=$t/dxg "RUN_KDE_HOST_RENDERER=D3D12 (AMD Radeon RX 7800 XT)" GALLIUM_DRIVER=zink LD_LIBRARY_PATH=/opt/lib LIBVA_DRIVER_NAME=radeonsi ${exe} --dry-run''
|
||||
)
|
||||
(scenario "dry-run-wslg-no-gpu" 0
|
||||
"machine ${wslg} RUN_KDE_DXG_DEVICE=$t/absent RUN_KDE_HOST_RENDERER= ${exe} --dry-run"
|
||||
)
|
||||
(scenario "dry-run-wslg-software-gl" 0
|
||||
''machine ${wslg} RUN_KDE_DXG_DEVICE=$t/dxg "RUN_KDE_HOST_RENDERER=llvmpipe (LLVM 21.1.8, 256 bits)" ${exe} --dry-run''
|
||||
)
|
||||
(scenario "dry-run-headless" 0 "machine ${linux} RUN_KDE_MEMINFO=$t/meminfo-small ${exe} --dry-run")
|
||||
(scenario "dry-run-tcg" 0 "machine ${linux} RUN_KDE_KVM_DEVICE=$t/absent ${exe} --dry-run --tcg")
|
||||
];
|
||||
|
||||
run-kde-doctor = check "run-kde-doctor" [
|
||||
(scenario "doctor-wslg-gpu" 0
|
||||
''machine ${wslg} RUN_KDE_DXG_DEVICE=$t/dxg "RUN_KDE_HOST_RENDERER=D3D12 (AMD Radeon RX 7800 XT)" RUN_KDE_WSLCONFIG=$t/none ${exe} --doctor''
|
||||
)
|
||||
(scenario "doctor-wslg-gpu-no-driver" 0
|
||||
''machine ${wslg} RUN_KDE_DXG_DEVICE=$t/dxg "RUN_KDE_HOST_RENDERER=D3D12 (AMD Radeon RX 7800 XT)" RUN_KDE_WSL_LIB_DIR=$t/absent RUN_KDE_VA_DRIVERS_DIR=$t/absent RUN_KDE_WSLCONFIG=$t/none ${exe} --doctor''
|
||||
)
|
||||
(scenario "doctor-wsl-no-kvm" 1
|
||||
"machine WAYLAND_DISPLAY=w RUN_KDE_OSRELEASE=$t/osrelease-wsl RUN_KDE_KVM_DEVICE=$t/absent RUN_KDE_CPUINFO=$t/cpuinfo-none RUN_KDE_MEMINFO=$t/meminfo-small RUN_KDE_DXG_DEVICE=$t/absent RUN_KDE_HOST_RENDERER= RUN_KDE_WSLCONFIG=$t/none ${exe} --doctor"
|
||||
)
|
||||
(scenario "doctor-kvm-denied" 1 "machine ${linux} RUN_KDE_KVM_DEVICE=$t/kvm-denied ${exe} --doctor")
|
||||
(scenario "doctor-fuse-missing" 0 "machine ${linux} RUN_KDE_FUSE_DEVICE=$t/absent ${exe} --doctor")
|
||||
(scenario "doctor-fuse-denied" 0
|
||||
"machine ${linux} RUN_KDE_FUSE_DEVICE=$t/kvm-denied ${exe} --doctor"
|
||||
)
|
||||
(scenario "doctor-virtiofsd-broken" 1
|
||||
"machine ${linux} RUN_KDE_VIRTIOFSD=$t/bin/virtiofsd-broken ${exe} --doctor"
|
||||
)
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
run-kde: what the guest needs, and what this machine has
|
||||
✓ this is Linux, not WSL 2 (6.18.0)
|
||||
✓ nix is installed
|
||||
✓ KVM: @T@/kvm can be used
|
||||
! FUSE: @T@/kvm-denied is there and this user cannot open it; virtiofsd does not use it, so the guest can still start
|
||||
on NixOS, services.udev.extraRules = ''KERNEL=="fuse", MODE="0666"'';
|
||||
for now: sudo chmod 666 @T@/kvm-denied
|
||||
✓ virtiofsd: starts as this user and serves a directory
|
||||
✓ memory: this machine has 16384 MB, and the guest gets 8192 MB
|
||||
✓ cores: this machine has 12, and the guest gets 6
|
||||
✓ disk: 100 GB are free for the Nix store (@T@)
|
||||
! there is no window to show the guest in (neither WAYLAND_DISPLAY nor DISPLAY is set), so the guest is reached over RDP
|
||||
! GPU: there is no render node in @T@/dri, so the guest renders on its CPUs
|
||||
✓ the guest will not use the GPU: there is no window to show it in (the display is rdp)
|
||||
run-kde: 0 error(s), 3 warning(s)
|
||||
@@ -0,0 +1,14 @@
|
||||
run-kde: what the guest needs, and what this machine has
|
||||
✓ this is Linux, not WSL 2 (6.18.0)
|
||||
✓ nix is installed
|
||||
✓ KVM: @T@/kvm can be used
|
||||
! FUSE: @T@/absent does not exist; virtiofsd does not use it, so the guest can still start
|
||||
on NixOS, boot.kernelModules = [ "fuse" ];
|
||||
✓ virtiofsd: starts as this user and serves a directory
|
||||
✓ memory: this machine has 16384 MB, and the guest gets 8192 MB
|
||||
✓ cores: this machine has 12, and the guest gets 6
|
||||
✓ disk: 100 GB are free for the Nix store (@T@)
|
||||
! there is no window to show the guest in (neither WAYLAND_DISPLAY nor DISPLAY is set), so the guest is reached over RDP
|
||||
! GPU: there is no render node in @T@/dri, so the guest renders on its CPUs
|
||||
✓ the guest will not use the GPU: there is no window to show it in (the display is rdp)
|
||||
run-kde: 0 error(s), 3 warning(s)
|
||||
@@ -0,0 +1,15 @@
|
||||
run-kde: what the guest needs, and what this machine has
|
||||
✓ this is Linux, not WSL 2 (6.18.0)
|
||||
✓ nix is installed
|
||||
✗ KVM: @T@/kvm-denied is there and this user cannot open it
|
||||
put this user in the group kvm: on NixOS, users.users.<you>.extraGroups = [ "kvm" ];
|
||||
then open a new login (on WSL: run `wsl --shutdown` in PowerShell and start it again)
|
||||
✓ FUSE: @T@/fuse can be opened
|
||||
✓ virtiofsd: starts as this user and serves a directory
|
||||
✓ memory: this machine has 16384 MB, and the guest gets 8192 MB
|
||||
✓ cores: this machine has 12, and the guest gets 6
|
||||
✓ disk: 100 GB are free for the Nix store (@T@)
|
||||
! there is no window to show the guest in (neither WAYLAND_DISPLAY nor DISPLAY is set), so the guest is reached over RDP
|
||||
! GPU: there is no render node in @T@/dri, so the guest renders on its CPUs
|
||||
✓ the guest will not use the GPU: there is no window to show it in (the display is rdp)
|
||||
run-kde: 1 thing(s) to fix first
|
||||
@@ -0,0 +1,17 @@
|
||||
run-kde: what the guest needs, and what this machine has
|
||||
✓ this is Linux, not WSL 2 (6.18.0)
|
||||
✓ nix is installed
|
||||
✓ KVM: @T@/kvm can be used
|
||||
✓ FUSE: @T@/fuse can be opened
|
||||
✗ virtiofsd: does not start as this user, and the guest mounts its /nix/store through it
|
||||
virtiofsd said: [ERROR virtiofsd] Error creating the vhost-user socket: Address in use (os error 98)
|
||||
virtiofsd ran with the options of the guest's runner and could not serve a directory: the lines above say why.
|
||||
A socket path is 107 bytes at most, so a long $TMPDIR is one cause: TMPDIR=/tmp run-kde
|
||||
Say what virtiofsd printed when you ask for help: the guest cannot start without it
|
||||
✓ memory: this machine has 16384 MB, and the guest gets 8192 MB
|
||||
✓ cores: this machine has 12, and the guest gets 6
|
||||
✓ disk: 100 GB are free for the Nix store (@T@)
|
||||
! there is no window to show the guest in (neither WAYLAND_DISPLAY nor DISPLAY is set), so the guest is reached over RDP
|
||||
! GPU: there is no render node in @T@/dri, so the guest renders on its CPUs
|
||||
✓ the guest will not use the GPU: there is no window to show it in (the display is rdp)
|
||||
run-kde: 1 thing(s) to fix first
|
||||
@@ -0,0 +1,20 @@
|
||||
run-kde: what the guest needs, and what this machine has
|
||||
✓ this is WSL 2 (5.15.167.4-microsoft-standard-WSL2)
|
||||
✓ nix is installed
|
||||
✗ KVM: @T@/absent does not exist, and the guest needs it
|
||||
the CPU's virtualization flags (svm or vmx) are not visible here, so nested virtualization is off
|
||||
in %UserProfile%\.wslconfig, under [wsl2], set: nestedVirtualization=true
|
||||
and turn on SVM (AMD) or VT-x (Intel) in the firmware setup of the machine
|
||||
✓ FUSE: @T@/fuse can be opened
|
||||
✓ virtiofsd: starts as this user and serves a directory
|
||||
! memory: this machine has 6144 MB, so the guest gets 4096 MB (8192 is comfortable)
|
||||
in %UserProfile%\.wslconfig, under [wsl2], set: memory=12GB
|
||||
✓ cores: this machine has 12, and the guest gets 6
|
||||
✓ disk: 100 GB are free for the Nix store (@T@)
|
||||
✓ a window can be shown (WAYLAND_DISPLAY=w)
|
||||
! Windows interop: mstsc.exe or cmdkey.exe cannot be run, which --rdp needs
|
||||
on NixOS-WSL, wsl.interop.includePath = true; (and wsl.interop.register = true;)
|
||||
! GPU: there is no @T@/absent, so the guest renders on its CPUs
|
||||
install the Windows GPU driver with WSL support; on NixOS-WSL, wsl.useWindowsDriver = true;
|
||||
✓ the guest will not use the GPU: there is no @T@/absent, so WSL has no GPU
|
||||
run-kde: 1 thing(s) to fix first
|
||||
@@ -0,0 +1,20 @@
|
||||
run-kde: what the guest needs, and what this machine has
|
||||
✓ this is WSL 2 (5.15.167.4-microsoft-standard-WSL2)
|
||||
✓ nix is installed
|
||||
✓ KVM: @T@/kvm can be used
|
||||
✓ FUSE: @T@/fuse can be opened
|
||||
✓ virtiofsd: starts as this user and serves a directory
|
||||
✓ memory: this machine has 16384 MB, and the guest gets 8192 MB
|
||||
✓ cores: this machine has 12, and the guest gets 6
|
||||
✓ disk: 100 GB are free for the Nix store (@T@)
|
||||
✓ a window can be shown (WAYLAND_DISPLAY=wayland-0 DISPLAY=:0)
|
||||
! Windows interop: mstsc.exe or cmdkey.exe cannot be run, which --rdp needs
|
||||
on NixOS-WSL, wsl.interop.includePath = true; (and wsl.interop.register = true;)
|
||||
✓ GPU: @T@/dxg is there
|
||||
✓ GPU: the host's OpenGL renderer is D3D12 (AMD Radeon RX 7800 XT)
|
||||
! GPU: there is no @T@/absent, so Mesa cannot take the Windows driver (d3d12)
|
||||
run `wsl --update` in PowerShell, and install the Windows GPU driver with WSL support
|
||||
! GPU: there is no d3d12 video driver in @T@/absent, so KRDP encodes H.264 on the guest's CPUs
|
||||
on NixOS-WSL, wsl.useWindowsDriver = true; with a Mesa that is built with video codecs
|
||||
✓ the guest will use the GPU: @T@/dxg is there and the OpenGL of the host is D3D12 (AMD Radeon RX 7800 XT)
|
||||
run-kde: 0 error(s), 3 warning(s)
|
||||
@@ -0,0 +1,18 @@
|
||||
run-kde: what the guest needs, and what this machine has
|
||||
✓ this is WSL 2 (5.15.167.4-microsoft-standard-WSL2)
|
||||
✓ nix is installed
|
||||
✓ KVM: @T@/kvm can be used
|
||||
✓ FUSE: @T@/fuse can be opened
|
||||
✓ virtiofsd: starts as this user and serves a directory
|
||||
✓ memory: this machine has 16384 MB, and the guest gets 8192 MB
|
||||
✓ cores: this machine has 12, and the guest gets 6
|
||||
✓ disk: 100 GB are free for the Nix store (@T@)
|
||||
✓ a window can be shown (WAYLAND_DISPLAY=wayland-0 DISPLAY=:0)
|
||||
! Windows interop: mstsc.exe or cmdkey.exe cannot be run, which --rdp needs
|
||||
on NixOS-WSL, wsl.interop.includePath = true; (and wsl.interop.register = true;)
|
||||
✓ GPU: @T@/dxg is there
|
||||
✓ GPU: the host's OpenGL renderer is D3D12 (AMD Radeon RX 7800 XT)
|
||||
✓ GPU: the Windows driver is in @T@/wsl-lib
|
||||
✓ GPU: the video driver of Mesa for it (d3d12) is in @T@/va
|
||||
✓ the guest will use the GPU: @T@/dxg is there and the OpenGL of the host is D3D12 (AMD Radeon RX 7800 XT)
|
||||
run-kde: 0 error(s), 1 warning(s)
|
||||
@@ -0,0 +1,12 @@
|
||||
run-kde would start run-kde-x86_64:
|
||||
host: Linux, KVM yes
|
||||
display: rdp
|
||||
gpu: off, because there is no window to show it in (the display is rdp)
|
||||
environment:
|
||||
NIX_DISK_IMAGE=/state/komorebi-run-kde/disk.qcow2
|
||||
KOMOREBI_REPO=@T@/repo
|
||||
RUN_KDE_STATE=/state/komorebi-run-kde
|
||||
RUN_KDE_MEMORY=4096
|
||||
QEMU_NET_OPTS=hostfwd=tcp:127.0.0.1:2223-:22,hostfwd=tcp:127.0.0.1:3389-:3389
|
||||
QEMU_OPTS=-cpu host -display none -vga none -device virtio-vga,xres=1280,yres=800
|
||||
command: /nix/store/fake-nixos-vm/bin/run-komorebi-demo-vm -m 4096 -smp 6
|
||||
@@ -0,0 +1,12 @@
|
||||
run-kde would start run-kde-x86_64:
|
||||
host: Linux, KVM no
|
||||
display: rdp
|
||||
gpu: off, because there is no window to show it in (the display is rdp)
|
||||
environment:
|
||||
NIX_DISK_IMAGE=/state/komorebi-run-kde/disk.qcow2
|
||||
KOMOREBI_REPO=@T@/repo
|
||||
RUN_KDE_STATE=/state/komorebi-run-kde
|
||||
RUN_KDE_MEMORY=8192
|
||||
QEMU_NET_OPTS=hostfwd=tcp:127.0.0.1:2223-:22,hostfwd=tcp:127.0.0.1:3389-:3389
|
||||
QEMU_OPTS=-display none -vga none -device virtio-vga,xres=1280,yres=800
|
||||
command: /nix/store/fake-nixos-vm/bin/run-komorebi-demo-vm -m 8192 -smp 6
|
||||
@@ -0,0 +1,14 @@
|
||||
run-kde would start run-kde-x86_64:
|
||||
host: WSL 2, KVM yes
|
||||
display: gtk
|
||||
gpu: on, because @T@/dxg is there and the OpenGL of the host is D3D12 (AMD Radeon RX 7800 XT)
|
||||
environment:
|
||||
NIX_DISK_IMAGE=/state/komorebi-run-kde/disk.qcow2
|
||||
KOMOREBI_REPO=@T@/repo
|
||||
RUN_KDE_STATE=/state/komorebi-run-kde
|
||||
RUN_KDE_MEMORY=8192
|
||||
QEMU_NET_OPTS=hostfwd=tcp:127.0.0.1:2223-:22,hostfwd=tcp:127.0.0.1:3389-:3389
|
||||
QEMU_OPTS=-cpu host -display gtk,gl=on -vga none -device virtio-vga-gl,xres=1280,yres=800
|
||||
GALLIUM_DRIVER=d3d12
|
||||
LD_LIBRARY_PATH=@T@/wsl-lib
|
||||
command: /nix/store/fake-nixos-vm/bin/run-komorebi-demo-vm -m 8192 -smp 6
|
||||
@@ -0,0 +1,16 @@
|
||||
run-kde would start run-kde-x86_64:
|
||||
host: WSL 2, KVM yes
|
||||
display: gtk
|
||||
gpu: on, because @T@/dxg is there and the OpenGL of the host is D3D12 (AMD Radeon RX 7800 XT)
|
||||
environment:
|
||||
NIX_DISK_IMAGE=/state/komorebi-run-kde/disk.qcow2
|
||||
KOMOREBI_REPO=@T@/repo
|
||||
RUN_KDE_STATE=/state/komorebi-run-kde
|
||||
RUN_KDE_MEMORY=8192
|
||||
QEMU_NET_OPTS=hostfwd=tcp:127.0.0.1:2223-:22,hostfwd=tcp:127.0.0.1:3389-:3389
|
||||
QEMU_OPTS=-cpu host -display gtk,gl=on -vga none -device virtio-vga-gl,xres=1280,yres=800
|
||||
GALLIUM_DRIVER=zink
|
||||
LD_LIBRARY_PATH=@T@/wsl-lib:/opt/lib
|
||||
LIBVA_DRIVER_NAME=radeonsi
|
||||
LIBVA_DRIVERS_PATH=@T@/va
|
||||
command: /nix/store/fake-nixos-vm/bin/run-komorebi-demo-vm -m 8192 -smp 6
|
||||
@@ -0,0 +1,16 @@
|
||||
run-kde would start run-kde-x86_64:
|
||||
host: WSL 2, KVM yes
|
||||
display: gtk
|
||||
gpu: on, because @T@/dxg is there and the OpenGL of the host is D3D12 (AMD Radeon RX 7800 XT)
|
||||
environment:
|
||||
NIX_DISK_IMAGE=/state/komorebi-run-kde/disk.qcow2
|
||||
KOMOREBI_REPO=@T@/repo
|
||||
RUN_KDE_STATE=/state/komorebi-run-kde
|
||||
RUN_KDE_MEMORY=8192
|
||||
QEMU_NET_OPTS=hostfwd=tcp:127.0.0.1:2223-:22,hostfwd=tcp:127.0.0.1:3389-:3389
|
||||
QEMU_OPTS=-cpu host -display gtk,gl=on -vga none -device virtio-vga-gl,xres=1280,yres=800
|
||||
GALLIUM_DRIVER=d3d12
|
||||
LD_LIBRARY_PATH=@T@/wsl-lib
|
||||
LIBVA_DRIVER_NAME=d3d12
|
||||
LIBVA_DRIVERS_PATH=@T@/va
|
||||
command: /nix/store/fake-nixos-vm/bin/run-komorebi-demo-vm -m 8192 -smp 6
|
||||
@@ -0,0 +1,12 @@
|
||||
run-kde would start run-kde-x86_64:
|
||||
host: WSL 2, KVM yes
|
||||
display: gtk
|
||||
gpu: off, because there is no @T@/absent, so WSL has no GPU
|
||||
environment:
|
||||
NIX_DISK_IMAGE=/state/komorebi-run-kde/disk.qcow2
|
||||
KOMOREBI_REPO=@T@/repo
|
||||
RUN_KDE_STATE=/state/komorebi-run-kde
|
||||
RUN_KDE_MEMORY=8192
|
||||
QEMU_NET_OPTS=hostfwd=tcp:127.0.0.1:2223-:22,hostfwd=tcp:127.0.0.1:3389-:3389
|
||||
QEMU_OPTS=-cpu host -display gtk -vga none -device virtio-vga,xres=1280,yres=800
|
||||
command: /nix/store/fake-nixos-vm/bin/run-komorebi-demo-vm -m 8192 -smp 6
|
||||
@@ -0,0 +1,12 @@
|
||||
run-kde would start run-kde-x86_64:
|
||||
host: WSL 2, KVM yes
|
||||
display: gtk
|
||||
gpu: off, because the host's OpenGL is software (llvmpipe (LLVM 21.1.8, 256 bits))
|
||||
environment:
|
||||
NIX_DISK_IMAGE=/state/komorebi-run-kde/disk.qcow2
|
||||
KOMOREBI_REPO=@T@/repo
|
||||
RUN_KDE_STATE=/state/komorebi-run-kde
|
||||
RUN_KDE_MEMORY=8192
|
||||
QEMU_NET_OPTS=hostfwd=tcp:127.0.0.1:2223-:22,hostfwd=tcp:127.0.0.1:3389-:3389
|
||||
QEMU_OPTS=-cpu host -display gtk -vga none -device virtio-vga,xres=1280,yres=800
|
||||
command: /nix/store/fake-nixos-vm/bin/run-komorebi-demo-vm -m 8192 -smp 6
|
||||
@@ -0,0 +1,134 @@
|
||||
# The NixOS VM tests. Every directory under `suites/` is one test, `checks.<system>.vm-<name>`
|
||||
# (Linux) and `legacyPackages.<system>.vm.<name>` (everywhere), so a new suite needs no edit to
|
||||
# the flake. See docs/dev/vm-tests.md.
|
||||
#
|
||||
# `hostPkgs` is the pkgs of the machine that runs QEMU; the guests are always Linux.
|
||||
# `komorebiModule` is the flake's NixOS module, `services.komorebi`, which every node imports: its
|
||||
# overlay builds `komorebi` and `komorebic` for the guest's system. `scale` says how much slower
|
||||
# than KVM that machine is (1.5 for KVM, nested or not, and for HVF on a Mac, and 8 for TCG), and every wait in the
|
||||
# suites is multiplied by it.
|
||||
{
|
||||
hostPkgs,
|
||||
komorebiModule,
|
||||
scale ? 1,
|
||||
}:
|
||||
let
|
||||
inherit (hostPkgs) lib;
|
||||
|
||||
# `komorebi-recorder`, when the run is given one: its repository is private, so it is not an
|
||||
# input of the flake. `KOMOREBI_RECORDER=$(nix build --print-out-paths ...)` and `--impure`.
|
||||
recorder =
|
||||
let
|
||||
path = builtins.getEnv "KOMOREBI_RECORDER";
|
||||
in
|
||||
if path == "" then null else builtins.storePath path;
|
||||
|
||||
# `E2E_ONLY=stacks,monocle` (with `--impure`; `KFDE_ONLY` is the older name) runs only the steps of
|
||||
# a suite whose name has one of the words; see `komorebi_vm.core.suite`
|
||||
only =
|
||||
let
|
||||
named = builtins.getEnv "E2E_ONLY";
|
||||
in
|
||||
if named != "" then named else builtins.getEnv "KFDE_ONLY";
|
||||
|
||||
# the library the suites import, built for the python of the test driver
|
||||
komorebiVm =
|
||||
ps:
|
||||
ps.buildPythonPackage {
|
||||
pname = "komorebi-vm";
|
||||
version = "0.1.0";
|
||||
pyproject = true;
|
||||
src = lib.fileset.toSource {
|
||||
root = ./lib;
|
||||
# not the unit tests: the VM never runs them (setuptools does not package them), so
|
||||
# editing one must not rebuild every suite; `libCheck` keeps them
|
||||
fileset = lib.fileset.difference ./lib ./lib/tests;
|
||||
};
|
||||
build-system = [ ps.setuptools ];
|
||||
dependencies = [ ps.pillow ];
|
||||
doCheck = false;
|
||||
};
|
||||
|
||||
# unit tests of the library against a fake machine, and the linters over it
|
||||
libCheck =
|
||||
let
|
||||
python = hostPkgs.python3.withPackages (ps: [
|
||||
ps.pytest
|
||||
(komorebiVm ps)
|
||||
]);
|
||||
in
|
||||
hostPkgs.runCommand "vm-lib"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
python
|
||||
hostPkgs.ruff
|
||||
hostPkgs.ty
|
||||
];
|
||||
src = lib.fileset.toSource {
|
||||
root = ./lib;
|
||||
fileset = ./lib;
|
||||
};
|
||||
}
|
||||
''
|
||||
cp -r $src lib && chmod -R u+w lib && cd lib
|
||||
ruff check .
|
||||
ruff format --check .
|
||||
ty check --python ${python} .
|
||||
pytest -q -p no:cacheprovider
|
||||
touch $out
|
||||
'';
|
||||
|
||||
suiteNames = lib.attrNames (
|
||||
lib.filterAttrs (_: type: type == "directory") (builtins.readDir ./suites)
|
||||
);
|
||||
|
||||
suiteDefs = lib.genAttrs suiteNames (name: import (./suites + "/${name}"));
|
||||
|
||||
mkSuite =
|
||||
name:
|
||||
let
|
||||
dir = ./suites + "/${name}";
|
||||
suite = suiteDefs.${name};
|
||||
in
|
||||
hostPkgs.testers.runNixOSTest {
|
||||
name = "komorebi-${name}";
|
||||
extraPythonPackages = ps: [ (komorebiVm ps) ];
|
||||
globalTimeout = builtins.ceil (suite.timeoutMinutes * 60 * scale);
|
||||
passthru.tier = suite.tier;
|
||||
|
||||
# the nodes import the module, `komorebiModule`, which adds its overlay to nixpkgs: the test
|
||||
# framework's pkgs, which cannot be changed, would refuse it
|
||||
node.specialArgs = { inherit komorebiModule; };
|
||||
node.pkgsReadOnly = false;
|
||||
|
||||
nodes.machine = {
|
||||
# a suite's `node`, if it has one, adds to the node of its kind
|
||||
imports = [ (./nodes + "/${suite.kind}.nix") ] ++ lib.optional (suite ? node) suite.node;
|
||||
environment.systemPackages = lib.optional (recorder != null) recorder;
|
||||
};
|
||||
|
||||
testScript = ''
|
||||
SCALE = ${toString scale}
|
||||
RECORDER = ${if recorder == null then "False" else "True"}
|
||||
''
|
||||
+ lib.optionalString (only != "") ''
|
||||
import os
|
||||
os.environ["E2E_ONLY"] = ${builtins.toJSON only}
|
||||
''
|
||||
+ builtins.readFile (dir + "/${suite.script or "test.py"}");
|
||||
};
|
||||
|
||||
suites = lib.genAttrs suiteNames mkSuite;
|
||||
in
|
||||
{
|
||||
inherit suites;
|
||||
lib = libCheck;
|
||||
|
||||
# the suites of each tier, for the CI matrix: { fast = [ "kwin" ... ]; slow = [ ... ]; }
|
||||
tiers = lib.groupBy (name: suiteDefs.${name}.tier) suiteNames;
|
||||
|
||||
# the guests of every suite, so that a Mac can build them on a Linux builder first
|
||||
guests = lib.mapAttrs (
|
||||
_: test: lib.mapAttrs (_: node: node.system.build.toplevel) test.nodes
|
||||
) suites;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
# vm-keys-skhd, vm-keys-whkd and vm-keys-sxhkd: the case `vm` of the key binding corpus
|
||||
# (komorebi-hotkeys/tests/fixtures/vm.*), in the format of the suite, installed by the NixOS module
|
||||
# (`services.komorebi.keybindings`, mode auto). Alt+J can be a static shortcut, which KWin runs
|
||||
# from the system profile; Alt+, cannot, so the module's daemon registers it and runs it. The Rust
|
||||
# tests and `keybindings-fixtures` check the plan; only a real session can say that what the
|
||||
# module builds and starts runs on a key, from each of the three formats.
|
||||
|
||||
from komorebi_vm import Checks
|
||||
from komorebi_vm.core.suite import platform_only, run_suite
|
||||
from komorebi_vm.platforms.kde.extras import keys_corpus as kde_keys_corpus
|
||||
|
||||
start_all()
|
||||
machine.wait_for_unit("multi-user.target")
|
||||
|
||||
checks = Checks()
|
||||
|
||||
run_suite(checks, platform_only("kde", kde_keys_corpus.run, machine, checks, SCALE))
|
||||
checks.finish()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Helpers for the NixOS VM tests of komorebi for KDE.
|
||||
|
||||
A suite imports what it needs from here:
|
||||
|
||||
* [`Checks`](komorebi_vm.core.checks.Checks) counts checks and fails at the end.
|
||||
* [`Kde`](komorebi_vm.kde.Kde) is a KWin session inside a test machine, with
|
||||
the tools to look at it (`kdotool`, `busctl`, `kscreen-doctor`, screenshots)
|
||||
and the komorebi daemon that runs in it.
|
||||
* [`Outputs`](komorebi_vm.kde.Outputs) are the session's outputs, which a suite
|
||||
disables, enables and scales to change the monitors under the daemon.
|
||||
* [`Keys`](komorebi_vm.keys.Keys) presses keys on the machine's keyboard.
|
||||
* [`daemon`](komorebi_vm.daemon) reads what the daemon logs about the events it
|
||||
handles and the frames it asks for.
|
||||
* [`pixels`](komorebi_vm.core.pixels) reads a screenshot: the color of a pixel, and
|
||||
the ring around a window.
|
||||
* [`latency`](komorebi_vm.latency) times the daemon's commands from a recording
|
||||
of the session bus.
|
||||
* [`RdpClient`](komorebi_vm.rdp.RdpClient) logs in to KRDP from FreeRDP on an X server of its own,
|
||||
and reads its picture back.
|
||||
* [`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, uinput
|
||||
from komorebi_vm.core import pixels
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.kde import Kde, Outputs
|
||||
from komorebi_vm.keys import Keys
|
||||
from komorebi_vm.machine import Machine
|
||||
from komorebi_vm.pointer import Pointer
|
||||
from komorebi_vm.rdp import RdpClient
|
||||
|
||||
__all__ = [
|
||||
"Checks",
|
||||
"Kde",
|
||||
"Keys",
|
||||
"Machine",
|
||||
"Outputs",
|
||||
"Pointer",
|
||||
"RdpClient",
|
||||
"Rect",
|
||||
"daemon",
|
||||
"latency",
|
||||
"pixels",
|
||||
"uinput",
|
||||
]
|
||||
@@ -0,0 +1,8 @@
|
||||
"""The core the ports share: the vocabulary and the helpers a scenario is made of.
|
||||
|
||||
kfde (KDE) and kfw (Windows) run the same scenarios, so this package is the same in both
|
||||
repositories (kfw vendors it with `scripts/sync-e2e-core`). Nothing in it may import from a port's
|
||||
own code (`komorebi_vm.kde`, `komorebi_vm.platforms`, a runner) or name a compositor, a window
|
||||
class or a tool of one port; what a port does differently is in its `Platform`, and what only a
|
||||
port can check is in its extras.
|
||||
"""
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Counted checks, so that one failure does not hide the ones after it."""
|
||||
|
||||
from collections.abc import Callable, Generator
|
||||
from contextlib import contextmanager
|
||||
|
||||
|
||||
class Checks:
|
||||
"""Collects the outcome of every check and fails once, at the end.
|
||||
|
||||
A suite is a long scenario: a failure in the middle should not stop the
|
||||
rest from running, because the rest says what else is broken. `finish`
|
||||
prints the totals and raises if any check failed.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.passed = 0
|
||||
self.failed = 0
|
||||
self.failures: list[str] = []
|
||||
self.skipped: list[str] = []
|
||||
self.known: list[str] = []
|
||||
self.scope = ""
|
||||
"""Where the checks being made come from (`shared`, or the name of a port), or empty. It
|
||||
prefixes the description of each check, and a subclass that records checks may read it."""
|
||||
|
||||
@contextmanager
|
||||
def scoped(self, scope: str) -> Generator[None]:
|
||||
"""Makes the checks inside the block those of `scope`, and puts the scope before it back
|
||||
after, so that scopes nest."""
|
||||
before, self.scope = self.scope, scope
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.scope = before
|
||||
|
||||
def labelled(self, description: str) -> str:
|
||||
"""The description with the scope in front of it, `[shared] ...` or `[<port>] ...`, when
|
||||
there is one."""
|
||||
return f"[{self.scope}] {description}" if self.scope else description
|
||||
|
||||
def ok(self, description: str) -> None:
|
||||
"""Records a check that passed."""
|
||||
self.passed += 1
|
||||
print(f" ok {self.labelled(description)}")
|
||||
|
||||
def bad(self, description: str) -> None:
|
||||
"""Records a check that failed."""
|
||||
self.failed += 1
|
||||
self.failures.append(self.labelled(description))
|
||||
print(f" FAIL {self.labelled(description)}")
|
||||
|
||||
def skip(self, description: str, reason: str) -> None:
|
||||
"""Records a check that was not made, and why: the platform cannot do what it asks."""
|
||||
self.skipped.append(f"{self.labelled(description)} ({reason})")
|
||||
print(f" skip {self.labelled(description)}: {reason}")
|
||||
|
||||
def known_failure(self, description: str, condition: bool, reason: str) -> bool:
|
||||
"""Records a check that is known to fail, with the reason, to follow up on later.
|
||||
|
||||
The suite does not fail while it does. When it holds, that is a failure, to say that
|
||||
the marker can go.
|
||||
"""
|
||||
if condition:
|
||||
self.bad(f"{description}: it holds now, so it is no longer a known failure")
|
||||
else:
|
||||
self.known.append(f"{self.labelled(description)} ({reason})")
|
||||
print(f" known failure {self.labelled(description)}: {reason}")
|
||||
return condition
|
||||
|
||||
def check(self, description: str, condition: bool | Callable[[], bool]) -> bool:
|
||||
"""Records `condition` (or what calling it returns) and returns it."""
|
||||
holds = condition() if callable(condition) else condition
|
||||
if holds:
|
||||
self.ok(description)
|
||||
else:
|
||||
self.bad(description)
|
||||
return holds
|
||||
|
||||
def finish(self) -> None:
|
||||
"""Prints `passed: N failed: M` and raises if any check failed.
|
||||
|
||||
The error names the checks that failed, so that the last lines of a failed run, which
|
||||
are all `nix build` shows, say which they were.
|
||||
"""
|
||||
print(f"passed: {self.passed} failed: {self.failed}")
|
||||
if self.skipped:
|
||||
print(f"skipped: {len(self.skipped)}")
|
||||
if self.known:
|
||||
print(f"known failures: {len(self.known)}")
|
||||
if self.failed:
|
||||
raise AssertionError(f"{self.failed} checks failed: {'; '.join(self.failures)}")
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Rectangles, in the pixels of a screen."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Rect:
|
||||
"""A window's position and size, in pixels."""
|
||||
|
||||
x: int
|
||||
y: int
|
||||
w: int
|
||||
h: int
|
||||
|
||||
def overlaps(self, other: "Rect") -> bool:
|
||||
"""Returns true if and only if the two rectangles share at least one pixel."""
|
||||
return (
|
||||
self.x < other.x + other.w
|
||||
and other.x < self.x + self.w
|
||||
and self.y < other.y + other.h
|
||||
and other.y < self.y + self.h
|
||||
)
|
||||
|
||||
def inside(self, area: "Rect", slack: int = 0) -> bool:
|
||||
"""Returns true if and only if every pixel of this rectangle is a pixel of `area`, give
|
||||
or take `slack` pixels at each edge."""
|
||||
return (
|
||||
self.x >= area.x - slack
|
||||
and self.y >= area.y - slack
|
||||
and self.x + self.w <= area.x + area.w + slack
|
||||
and self.y + self.h <= area.y + area.h + slack
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Reading what a screenshot shows: the color of a pixel, and the ring around a window."""
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
|
||||
Color = tuple[int, int, int]
|
||||
|
||||
|
||||
def pixel(image: Image.Image, x: int, y: int) -> Color:
|
||||
"""The color of the pixel at `(x, y)`, as red, green and blue."""
|
||||
value = image.convert("RGB").getpixel((x, y))
|
||||
assert isinstance(value, tuple)
|
||||
return (int(value[0]), int(value[1]), int(value[2]))
|
||||
|
||||
|
||||
def near(a: Color, b: Color, tolerance: int = 12) -> bool:
|
||||
"""Returns true if and only if the two colors differ by at most `tolerance` on every channel.
|
||||
|
||||
A screenshot is of a compositor that blends the shadow and the edge of a border into what is
|
||||
behind it, so a color is never asked for exactly.
|
||||
"""
|
||||
return all(abs(x - y) <= tolerance for x, y in zip(a, b, strict=True))
|
||||
|
||||
|
||||
def leftmost(image: Image.Image, y: int, color: Color, tolerance: int = 12) -> int | None:
|
||||
"""Returns the `x` of the leftmost pixel of row `y` that is near `color`, or `None`.
|
||||
|
||||
A window that moves across the screen has its left edge where this finds the first pixel of its
|
||||
color, which is how a test sees how far along it is.
|
||||
"""
|
||||
for x in range(image.width):
|
||||
if near(pixel(image, x, y), color, tolerance):
|
||||
return x
|
||||
return None
|
||||
|
||||
|
||||
def ring(image: Image.Image, frame: Rect, color: Color, margin: int = 5) -> list[str]:
|
||||
"""Returns what is wrong with the ring around a window: a line for each side that has none.
|
||||
|
||||
The ring is looked for `margin` pixels outside the middle of each of the four edges of
|
||||
`frame`, which is the window with its title bar, as the platform reports it. A side where that
|
||||
pixel is not near `color` is named, with the pixel it has. An empty list is a ring all round.
|
||||
"""
|
||||
middle_x = frame.x + frame.w // 2
|
||||
middle_y = frame.y + frame.h // 2
|
||||
sides = {
|
||||
"above": (middle_x, frame.y - margin),
|
||||
"below": (middle_x, frame.y + frame.h + margin),
|
||||
"left": (frame.x - margin, middle_y),
|
||||
"right": (frame.x + frame.w + margin, middle_y),
|
||||
}
|
||||
wrong = []
|
||||
for name, (x, y) in sides.items():
|
||||
found = pixel(image, x, y)
|
||||
if not near(found, color):
|
||||
wrong.append(f"{name}: ({x}, {y}) is {found}, not {color}")
|
||||
return wrong
|
||||
@@ -0,0 +1,319 @@
|
||||
"""What a scenario needs of a platform: the hands and the eyes, behind methods.
|
||||
|
||||
A scenario drives the daemon and looks at the desktop only through a
|
||||
[`Platform`](komorebi_vm.core.platform.Platform), so that the same scenario runs on KDE and on
|
||||
Windows. A platform may implement a method on the host (QMP on QEMU) or in the guest (an agent); a
|
||||
scenario cannot tell.
|
||||
|
||||
Only what a scenario uses today is here. A method is added with the first scenario that needs it,
|
||||
and takes the shape both platforms can give.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Protocol
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.snapshot import Snapshot
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Client:
|
||||
"""A window a scenario opened. `title` is its identity: a scenario gives each its own."""
|
||||
|
||||
title: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OsWindow:
|
||||
"""What the operating system says about a window, which is the oracle of a scenario.
|
||||
|
||||
The daemon's own state is the thing under test and is never its own oracle.
|
||||
"""
|
||||
|
||||
title: str
|
||||
frame: Rect
|
||||
"""The visible frame: the compositor's on KDE, the DWM's extended frame on Windows, without
|
||||
the invisible borders and the shadow. A scenario does not read the frame of a window that is
|
||||
minimized: it is where the system keeps it, which is not the same on every port."""
|
||||
focused: bool
|
||||
"""The window has the keyboard focus, as the operating system says. At most one window of a
|
||||
desktop does; none does while another program's window has it."""
|
||||
|
||||
|
||||
class Pointer(Protocol):
|
||||
"""A pointer a scenario moves and presses, in the pixels of the first display.
|
||||
|
||||
A drag is one press, a glide to the end with the button held, and one release, because a
|
||||
window manager that is asked to follow the pointer drops moves that come a round trip apart.
|
||||
"""
|
||||
|
||||
def move(self, x: int, y: int) -> None:
|
||||
"""Puts the pointer on the pixel (x, y)."""
|
||||
...
|
||||
|
||||
def down(self) -> None:
|
||||
"""Presses the left button."""
|
||||
...
|
||||
|
||||
def up(self) -> None:
|
||||
"""Lets go of the left button."""
|
||||
...
|
||||
|
||||
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."""
|
||||
...
|
||||
|
||||
|
||||
class Platform(Protocol):
|
||||
"""A machine with a desktop and a daemon to test."""
|
||||
|
||||
def has(self, feature: str) -> bool:
|
||||
"""Whether the platform can do what a scenario needs of it (`"pointer"`, `"lock"`), so
|
||||
that a scenario that needs it is skipped, with the reason, where it cannot."""
|
||||
...
|
||||
|
||||
@property
|
||||
def pointer(self) -> Pointer:
|
||||
"""The pointer. Only where `has("pointer")`."""
|
||||
...
|
||||
|
||||
@property
|
||||
def tolerance(self) -> int:
|
||||
"""How far a window's frame may be short of the one asked for, in pixels.
|
||||
|
||||
A client that sizes itself to a grid (a terminal's cells) ends up short of the tile; one
|
||||
that does not (a test window) has only the rounding of the system's own frame. The frame
|
||||
is never past what was asked, so a check that something is inside an area allows no slack
|
||||
for it, and a check that two sizes are the same allows this much.
|
||||
|
||||
It is a bound on what a client rounds to, not a measure of a change: a scenario that
|
||||
asks whether the daemon changed a size compares the daemon's layout (`latest_layout`,
|
||||
which no client rounds) and then that the frame follows it within this.
|
||||
"""
|
||||
...
|
||||
|
||||
def wait_for(self, predicate: "Predicate", timeout: float = 10) -> bool:
|
||||
"""Polls `predicate` until it holds or `timeout` seconds, scaled for this host, pass.
|
||||
|
||||
A predicate answers false for what it cannot tell yet. A port may treat a `komorebic`
|
||||
that fails, in a predicate, as a false (Windows does, while the host is busy), and one may
|
||||
not (KDE raises): a predicate does not rely on either.
|
||||
"""
|
||||
...
|
||||
|
||||
def start_komorebi(self) -> None:
|
||||
"""Starts the daemon from a clean state and waits until it answers."""
|
||||
...
|
||||
|
||||
def crash(self) -> None:
|
||||
"""Kills the daemon abruptly, as a crash does, and returns when it is gone. Nothing of
|
||||
what it had set up is put back: a window it hid is as it left it, until a daemon starts
|
||||
again and finds it."""
|
||||
...
|
||||
|
||||
def restart_with(self, config: dict[str, Any]) -> None:
|
||||
"""Stops the daemon if it runs, and starts it from a clean state with `config` as its
|
||||
`komorebi.json`, and waits until it answers.
|
||||
|
||||
Windows that are open stay open, and the new daemon takes up the ones that are in view.
|
||||
"""
|
||||
...
|
||||
|
||||
def rewrite_config(self, config: dict[str, Any]) -> None:
|
||||
"""Writes `config` over the `komorebi.json` that `restart_with` gave the daemon, which
|
||||
the daemon watches and reloads when it changes. It returns once the file is written; a
|
||||
scenario waits for the state to follow."""
|
||||
...
|
||||
|
||||
def komorebic(self, *args: str) -> str:
|
||||
"""Runs `komorebic` with `args` and returns what it printed. Fails if it does."""
|
||||
...
|
||||
|
||||
def komorebic_status(self, *args: str) -> tuple[int, str]:
|
||||
"""Runs `komorebic` with `args` and returns its exit status and what it printed, whether
|
||||
it succeeded or not."""
|
||||
...
|
||||
|
||||
def temp_path(self, name: str) -> str:
|
||||
"""A path, on the machine the daemon runs on, of a file `komorebic` and the daemon may
|
||||
write and read (`save-resize` takes one), in the form `komorebic` is given it."""
|
||||
...
|
||||
|
||||
def state(self) -> Snapshot:
|
||||
"""The daemon's state."""
|
||||
...
|
||||
|
||||
def spawn(
|
||||
self,
|
||||
title: str,
|
||||
app_id: str | None = None,
|
||||
exe: str | None = None,
|
||||
rename_to: str | None = None,
|
||||
after: float = 0,
|
||||
) -> Client:
|
||||
"""Opens a window with this title and waits until the platform has it, and raises if it
|
||||
never does: a scenario that waits for a window to stay unmanaged must be sure it is there.
|
||||
|
||||
A title is a name that no other window has, taken as it is: it is never a pattern.
|
||||
|
||||
`app_id` is the class of the window (its app id on Wayland, its window class on Windows)
|
||||
for a rule that matches by it; the platform's own when there is none.
|
||||
|
||||
`exe` is the name of the program that opens it, without an extension (`e2e-exe` is
|
||||
`e2e-exe.exe` on Windows and `e2e-exe` on Linux), for a rule that matches by it. The
|
||||
platform makes a program of that name, and `exe_id` spells the id of a rule for it.
|
||||
|
||||
`rename_to` is a title the window gives itself `after` seconds after it opens (a terminal
|
||||
escape on KDE, a title update on Windows), as a program that sets its title late does. The
|
||||
window is then known to the platform by the new title: `Client(rename_to)`.
|
||||
"""
|
||||
...
|
||||
|
||||
def exe_id(self, program: str) -> str:
|
||||
"""The `id` of a rule that matches the windows of the program `spawn(exe=program)` opens:
|
||||
the program's file name, which is `program` on Linux and `program.exe` on Windows."""
|
||||
...
|
||||
|
||||
def os_window(self, client: Client) -> OsWindow | None:
|
||||
"""What the operating system says about the window, or `None` if it has none."""
|
||||
...
|
||||
|
||||
def hidden(self, client: Client) -> bool:
|
||||
"""The window exists but is out of sight because the daemon put it away: the other windows
|
||||
of a stack, the windows of a workspace that is not the one its display shows, those
|
||||
behind a monocle.
|
||||
|
||||
It is false for a window the system does not have, for one the user minimized, and for one
|
||||
that floats. A scenario that asks for a window to be put away also asks the daemon where
|
||||
it is (`state()`), because a port may answer true for any window that is not on the
|
||||
screen, whoever took it off: on KDE that is one on a virtual desktop that is not shown,
|
||||
on Windows a cloaked one, which includes the windows of another virtual desktop. A scenario
|
||||
that asks for windows to be in view counts those the system has (`support.in_view`).
|
||||
"""
|
||||
...
|
||||
|
||||
def displays(self) -> list[Rect]:
|
||||
"""The displays the operating system has, left to right: each one's rectangle in the
|
||||
coordinates of the desktop. The daemon is not asked.
|
||||
|
||||
Displays are not the same size (the one `add_display` plugs in may be smaller than the
|
||||
first) and need not touch: a scenario uses each one's own rectangle and does not compute
|
||||
where the next begins."""
|
||||
...
|
||||
|
||||
def add_display(self) -> None:
|
||||
"""Plugs in another display, to the right of the others, and returns when the operating
|
||||
system has it. The daemon learns of it later, so a scenario waits for its state to follow.
|
||||
A platform may give it another size than the others; `displays()` says which."""
|
||||
...
|
||||
|
||||
def remove_display(self) -> None:
|
||||
"""Unplugs the last display (the rightmost, which is the one `add_display` plugged in last),
|
||||
and returns when the operating system no longer has it.
|
||||
|
||||
Only a display `add_display` plugged in is certain to be removable: Windows refuses
|
||||
any other, KDE unplugs the last of the outputs it has. A scenario unplugs a display only
|
||||
after it plugged one in, unless its suite started the platform with more than one."""
|
||||
...
|
||||
|
||||
def resizable_display(self) -> int | None:
|
||||
"""The place in `displays()` of a display whose mode (its resolution) can be changed, or
|
||||
`None` when the platform has none that can, and a scenario that needs one is skipped with
|
||||
the reason. A scenario plugs in a display with `add_display` before it asks."""
|
||||
...
|
||||
|
||||
def resize_display(self, index: int, width: int, height: int) -> None:
|
||||
"""Gives the display `resizable_display` named another mode, `width` by `height` pixels,
|
||||
and returns when the operating system has it: `displays()` says so. The daemon learns of
|
||||
it later, so a scenario waits for its state to follow."""
|
||||
...
|
||||
|
||||
def close(self, client: Client) -> None:
|
||||
"""Closes the window, as its close button would, and returns without waiting for it to be
|
||||
gone. Raises if there is no such window."""
|
||||
...
|
||||
|
||||
def minimize(self, client: Client) -> None:
|
||||
"""Minimizes the window, as its title bar button would. `activate` restores it. Raises if
|
||||
there is no such window."""
|
||||
...
|
||||
|
||||
def lock(self) -> None:
|
||||
"""Locks the screen, as the user's lock shortcut would, and returns when it is locked.
|
||||
Only where `has("lock")`."""
|
||||
...
|
||||
|
||||
def unlock(self) -> None:
|
||||
"""Unlocks the screen, as the user's password would, and returns when it is unlocked.
|
||||
Only where `has("lock")`."""
|
||||
...
|
||||
|
||||
def move_window(self, client: Client, x: int, y: int) -> None:
|
||||
"""Moves the window so that its top left corner is at (x, y) of the desktop, as the
|
||||
compositor or the shell would, not as the user's pointer would. The window keeps its
|
||||
size."""
|
||||
...
|
||||
|
||||
def put_file(self, path: str, data: bytes) -> None:
|
||||
"""Writes `data` to `path` on the machine, where the daemon can read it, and makes the
|
||||
directories above it. `path` is one `temp_path` made."""
|
||||
...
|
||||
|
||||
def wallpaper(self, display: int = 0) -> str:
|
||||
"""The path of the picture a display shows, as the operating system says it (the Plasma
|
||||
shell on KDE, `IDesktopWallpaper` on Windows), or the empty string when it does not know."""
|
||||
...
|
||||
|
||||
def set_wallpaper(self, path: str, display: int = 0) -> None:
|
||||
"""Sets the wallpaper of a display as the user does, and returns when it is set."""
|
||||
...
|
||||
|
||||
def resize_grab(self, frame: Rect, grab: str) -> tuple[int, int]:
|
||||
"""Where the pointer is pressed to take a window of this frame by `grab`: `left`, `right`,
|
||||
`top`, `bottom`, or a corner (`topleft`, `topright`, `bottomleft`, `bottomright`).
|
||||
|
||||
It is the platform's knowledge, because where a window's resize zone is differs: on KDE it
|
||||
is the gap outside the frame on every side (`resize.outside_grab`), on Windows the left,
|
||||
right and bottom zones are an invisible border outside the visible frame, and the top one
|
||||
is inside it.
|
||||
"""
|
||||
...
|
||||
|
||||
def fullscreen(self, client: Client, on: bool = True) -> None:
|
||||
"""Takes the window fullscreen, as the program's own key does it (`on`), or brings it back
|
||||
from fullscreen (`on` false). The daemon is not asked: it learns of it from the system, and
|
||||
has to leave the window alone. Returns when the system has done it."""
|
||||
...
|
||||
|
||||
def user_maximize(self, client: Client, on: bool = True) -> None:
|
||||
"""Maximizes the window, as its title bar button does (`on`), or restores it from being
|
||||
maximized (`on` false). The daemon is not asked: it learns of it from the system. Returns
|
||||
when the system has done it."""
|
||||
...
|
||||
|
||||
def work_area(self) -> Rect:
|
||||
"""The area of the first display that windows may take, in the coordinates of the
|
||||
desktop: the display less what the operating system keeps for itself (a panel, a dock, the
|
||||
taskbar), as the operating system says and not the daemon.
|
||||
|
||||
It is the whole display only where there is nothing of the kind. A scenario that asks
|
||||
whether a window is "inside the work area" asks this, so a platform that answers with the
|
||||
display where the system has a bar makes that check weaker than it says."""
|
||||
...
|
||||
|
||||
def activate(self, client: Client) -> None:
|
||||
"""Gives the window the focus, as a click on it would, and restores it if it was minimized.
|
||||
Raises if there is no such window."""
|
||||
...
|
||||
|
||||
def screenshot(self, name: str) -> Image.Image:
|
||||
"""The display as an image, kept under `name` with the other artifacts of the run."""
|
||||
...
|
||||
|
||||
|
||||
class Predicate(Protocol):
|
||||
def __call__(self) -> bool: ...
|
||||
@@ -0,0 +1 @@
|
||||
"""Scenarios that run on every platform, written against `komorebi_vm.core.platform.Platform`."""
|
||||
@@ -0,0 +1,41 @@
|
||||
"""A window that closes leaves the daemon's state, and the ones that are left share its room."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client], closing: Client) -> None:
|
||||
"""Closes `closing`, one of `clients`, which are tiled windows of the first workspace, and
|
||||
checks that the daemon let go of it and the others fill what it left.
|
||||
|
||||
The windows of `clients` that are put away (on another workspace) are left out of the frames.
|
||||
"""
|
||||
others = [c for c in clients if c != closing and not platform.hidden(c)]
|
||||
|
||||
def area(c: Client) -> int:
|
||||
window = platform.os_window(c)
|
||||
return window.frame.w * window.frame.h if window is not None else 0
|
||||
|
||||
before = sum(area(c) for c in others)
|
||||
managed = platform.state().managed()
|
||||
|
||||
platform.close(closing)
|
||||
checks.check(
|
||||
f"{closing.title} is gone",
|
||||
platform.wait_for(lambda: platform.os_window(closing) is None, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"the daemon manages one window fewer",
|
||||
platform.wait_for(lambda: platform.state().managed() == managed - 1, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"the windows that are left take more room between them",
|
||||
platform.wait_for(lambda: sum(area(c) for c in others) > before, timeout=20),
|
||||
)
|
||||
area_of_screen = platform.work_area()
|
||||
frames = [w.frame for c in others if (w := platform.os_window(c)) is not None]
|
||||
checks.check("... inside the work area", all(f.inside(area_of_screen) for f in frames))
|
||||
checks.check(
|
||||
"... and not on each other",
|
||||
not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
@@ -0,0 +1,428 @@
|
||||
"""Every layout, and a sweep of komorebic's commands: none may break the daemon.
|
||||
|
||||
After each command the same things have to be true: the daemon is alive, it answers `komorebic
|
||||
state`, and it manages every window the operating system has. A command is also expected to be
|
||||
understood (exit status 0). A command the port does not have (`error: unrecognized subcommand`) is
|
||||
skipped, with its name, which is what the behaviour matrix of the two ports is made of. What each
|
||||
command does is checked elsewhere; this says none of them breaks a running daemon.
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
|
||||
LAYOUTS: tuple[str, ...] = (
|
||||
"bsp",
|
||||
"columns",
|
||||
"rows",
|
||||
"vertical-stack",
|
||||
"horizontal-stack",
|
||||
"ultrawide-vertical-stack",
|
||||
"grid",
|
||||
"right-main-vertical-stack",
|
||||
"scrolling",
|
||||
)
|
||||
|
||||
# A command with an option that has a default is given the option here when one port requires some
|
||||
# argument: kfw's `toggle-focus-follows-mouse` prints its help and exits 2 without one, and kfde's
|
||||
# accepts it.
|
||||
#
|
||||
# Every command the ports share that changes something, in an order that leaves the daemon with
|
||||
# windows to act on. `{config}` is the path of a configuration file for `replace-configuration`.
|
||||
SWEEP: tuple[str, ...] = (
|
||||
"focus left",
|
||||
"focus right",
|
||||
"focus up",
|
||||
"focus down",
|
||||
"move left",
|
||||
"move right",
|
||||
"move up",
|
||||
"move down",
|
||||
"cycle-focus next",
|
||||
"cycle-focus previous",
|
||||
"cycle-move next",
|
||||
"cycle-move previous",
|
||||
"stack left",
|
||||
"cycle-stack next",
|
||||
"cycle-stack previous",
|
||||
"cycle-stack-index next",
|
||||
"focus-stack-window 0",
|
||||
"unstack",
|
||||
"stack-all",
|
||||
"unstack-all",
|
||||
"resize-edge left increase",
|
||||
"resize-edge right decrease",
|
||||
"resize-edge up increase",
|
||||
"resize-edge down decrease",
|
||||
"resize-axis horizontal increase",
|
||||
"resize-axis vertical decrease",
|
||||
"resize-delta 50",
|
||||
"resize-delta 100",
|
||||
"promote",
|
||||
"promote-swap",
|
||||
"promote-focus",
|
||||
"promote-window left",
|
||||
"retile",
|
||||
"flip-layout horizontal",
|
||||
"flip-layout vertical",
|
||||
"flip-layout horizontal-and-vertical",
|
||||
"flip-layout horizontal-and-vertical",
|
||||
"cycle-layout next",
|
||||
"cycle-layout previous",
|
||||
"layout-ratios --columns 0.6 0.4",
|
||||
"change-layout columns",
|
||||
"scrolling-layout-columns 2",
|
||||
"change-layout bsp",
|
||||
"preselect-direction left",
|
||||
"cancel-preselect",
|
||||
"toggle-monocle",
|
||||
"toggle-monocle",
|
||||
"toggle-maximize",
|
||||
"toggle-maximize",
|
||||
"toggle-float",
|
||||
"toggle-float",
|
||||
"toggle-lock",
|
||||
"toggle-lock",
|
||||
"toggle-tiling",
|
||||
"toggle-tiling",
|
||||
"toggle-pause",
|
||||
"toggle-pause",
|
||||
"toggle-workspace-layer",
|
||||
"toggle-workspace-layer",
|
||||
"toggle-window-container-behaviour",
|
||||
"toggle-window-container-behaviour",
|
||||
"toggle-float-override",
|
||||
"toggle-float-override",
|
||||
"toggle-workspace-window-container-behaviour",
|
||||
"toggle-workspace-window-container-behaviour",
|
||||
"toggle-workspace-float-override",
|
||||
"toggle-workspace-float-override",
|
||||
"ensure-named-workspaces 0 one two three",
|
||||
"workspace-name 0 0 one",
|
||||
"ensure-workspaces 0 3",
|
||||
"workspace-tiling 0 0 disable",
|
||||
"workspace-tiling 0 0 enable",
|
||||
"named-workspace-tiling one disable",
|
||||
"named-workspace-tiling one enable",
|
||||
"focus-workspace 1",
|
||||
"focus-workspace 0",
|
||||
"focus-last-workspace",
|
||||
"focus-last-workspace",
|
||||
"focus-workspaces 1",
|
||||
"focus-workspaces 0",
|
||||
"cycle-workspace next",
|
||||
"cycle-workspace previous",
|
||||
"cycle-empty-workspace next",
|
||||
"focus-workspace 0",
|
||||
"focus-named-workspace two",
|
||||
"focus-named-workspace one",
|
||||
"send-to-workspace 1",
|
||||
"focus-workspace 1",
|
||||
"move-to-workspace 0",
|
||||
"focus-workspace 0",
|
||||
"cycle-send-to-workspace next",
|
||||
"focus-workspace 1",
|
||||
"cycle-move-to-workspace previous",
|
||||
"focus-workspace 0",
|
||||
"send-to-last-workspace",
|
||||
"move-to-last-workspace",
|
||||
"focus-workspace 0",
|
||||
"new-workspace",
|
||||
"close-workspace",
|
||||
"focus-workspace 0",
|
||||
"workspace-layout 0 0 columns",
|
||||
"workspace-layout 0 0 bsp",
|
||||
"named-workspace-layout one columns",
|
||||
"named-workspace-layout one bsp",
|
||||
"workspace-layout-rule 0 0 2 rows",
|
||||
"workspace-layout-rule 0 0 3 columns",
|
||||
"clear-workspace-layout-rules 0 0",
|
||||
"named-workspace-layout-rule one 3 columns",
|
||||
"clear-named-workspace-layout-rules one",
|
||||
"workspace-layout 0 0 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",
|
||||
"monitor-work-area-offset 0 0 0 0 0",
|
||||
"workspace-work-area-offset 0 0 10 10 20 20",
|
||||
"workspace-work-area-offset 0 0 0 0 0 0",
|
||||
"toggle-window-based-work-area-offset",
|
||||
"toggle-window-based-work-area-offset",
|
||||
"focused-workspace-container-padding 20",
|
||||
"focused-workspace-container-padding 10",
|
||||
"focused-workspace-padding 20",
|
||||
"focused-workspace-padding 10",
|
||||
"adjust-container-padding increase 5",
|
||||
"adjust-container-padding decrease 5",
|
||||
"adjust-workspace-padding increase 5",
|
||||
"adjust-workspace-padding decrease 5",
|
||||
"container-padding 0 0 12",
|
||||
"container-padding 0 0 10",
|
||||
"workspace-padding 0 0 12",
|
||||
"workspace-padding 0 0 10",
|
||||
"named-workspace-container-padding one 12",
|
||||
"named-workspace-container-padding one 10",
|
||||
"named-workspace-padding one 12",
|
||||
"named-workspace-padding one 10",
|
||||
"cross-monitor-move-behaviour insert",
|
||||
"cross-monitor-move-behaviour swap",
|
||||
"toggle-cross-monitor-move-behaviour",
|
||||
"toggle-cross-monitor-move-behaviour",
|
||||
"monocle-focus-behaviour cycle",
|
||||
"toggle-monocle-focus-behaviour",
|
||||
"toggle-monocle-focus-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",
|
||||
"toggle-mouse-follows-focus",
|
||||
"focus-follows-mouse enable",
|
||||
"focus-follows-mouse disable",
|
||||
"toggle-focus-follows-mouse --implementation windows",
|
||||
"toggle-focus-follows-mouse --implementation windows",
|
||||
"transparency enable",
|
||||
"transparency-alpha 150",
|
||||
"toggle-transparency",
|
||||
"toggle-transparency",
|
||||
"transparency disable",
|
||||
"border enable",
|
||||
"border-width 8",
|
||||
"border-offset 1",
|
||||
"border-colour --window-kind single 10 20 30",
|
||||
"border disable",
|
||||
"animation enable",
|
||||
"animation-duration 120",
|
||||
"animation-fps 30",
|
||||
"animation-style --style linear",
|
||||
"animation disable",
|
||||
"session-float-rule",
|
||||
"session-float-rules",
|
||||
"clear-session-float-rules",
|
||||
"toggle-float",
|
||||
"ignore-rule exe nonexistent",
|
||||
"manage-rule exe nonexistent",
|
||||
"initial-workspace-rule exe nonexistent 0 1",
|
||||
"workspace-rule exe nonexistent 0 1",
|
||||
"initial-named-workspace-rule exe nonexistent two",
|
||||
"named-workspace-rule exe nonexistent two",
|
||||
"enforce-workspace-rules",
|
||||
"clear-workspace-rules 0 1",
|
||||
"clear-named-workspace-rules two",
|
||||
"clear-all-workspace-rules",
|
||||
"manage",
|
||||
"close",
|
||||
"retile",
|
||||
"replace-configuration {config}",
|
||||
"eager-focus foot",
|
||||
)
|
||||
|
||||
# What komorebic only prints.
|
||||
PRINTED: tuple[str, ...] = (
|
||||
"state",
|
||||
"global-state",
|
||||
"visible-windows",
|
||||
"monitor-information",
|
||||
"data-directory",
|
||||
"configuration",
|
||||
"generate-static-config",
|
||||
"static-config-schema",
|
||||
"application-specific-configuration-schema",
|
||||
"notification-schema",
|
||||
"socket-schema",
|
||||
"session-float-rules",
|
||||
)
|
||||
|
||||
|
||||
NOT_A_COMMAND = "unrecognized subcommand"
|
||||
|
||||
|
||||
def unhealthy(platform: Platform, clients: list[Client]) -> str | None:
|
||||
"""Why the daemon is not healthy, or `None`: it answers `state` and manages the windows the
|
||||
operating system has."""
|
||||
status, _ = platform.komorebic_status("state")
|
||||
if status != 0:
|
||||
return "it does not answer `komorebic state`"
|
||||
try:
|
||||
managed = platform.state().managed()
|
||||
except (AssertionError, ValueError, KeyError) as error:
|
||||
return f"its state cannot be read ({error})"
|
||||
present = sum(1 for c in clients if platform.os_window(c) is not None)
|
||||
if managed != present:
|
||||
return f"it manages {managed} windows and the operating system has {present}"
|
||||
return None
|
||||
|
||||
|
||||
FEWER = (3, 2, 1)
|
||||
"""The counts of windows below the one `layouts` starts with that it tries every layout with."""
|
||||
|
||||
|
||||
def _each_layout(
|
||||
platform: Platform, checks: Checks, clients: list[Client], label: str, area: Rect
|
||||
) -> None:
|
||||
"""Changes to every layout, with `clients` the windows there are, and checks them."""
|
||||
for layout in LAYOUTS:
|
||||
status, out = platform.komorebic_status("change-layout", layout)
|
||||
if status != 0 and NOT_A_COMMAND in out:
|
||||
checks.skip(f"change-layout {layout}{label}", "the port has no such layout")
|
||||
continue
|
||||
problems = []
|
||||
if status != 0:
|
||||
problems.append(f"exit {status}")
|
||||
platform.wait_for(lambda: unhealthy(platform, clients) is None, timeout=10)
|
||||
if (why := unhealthy(platform, clients)) is not None:
|
||||
problems.append(why)
|
||||
if layout != "scrolling":
|
||||
frames = {c.title: w.frame for c in clients if (w := platform.os_window(c)) is not None}
|
||||
problems += [
|
||||
f"{t} is outside the work area" for t, f in frames.items() if not f.inside(area, 2)
|
||||
]
|
||||
titles = list(frames)
|
||||
problems += [
|
||||
f"{a} and {b} overlap"
|
||||
for i, a in enumerate(titles)
|
||||
for b in titles[i + 1 :]
|
||||
if frames[a].overlaps(frames[b])
|
||||
]
|
||||
checks.check(
|
||||
f"change-layout {layout}{label}: " + ("; ".join(problems) or "ok"), not problems
|
||||
)
|
||||
|
||||
|
||||
def layouts(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Changes to every layout, and checks that the windows stay inside the work area and apart
|
||||
from each other, and that the daemon stays healthy. The scrolling layout is a strip whose
|
||||
columns can be past the edge, so its frames are not looked at.
|
||||
|
||||
It does the same with three, two and one windows (those of `FEWER` that `clients` has more
|
||||
than): the others are closed from the end, and opened again with their own titles at the end,
|
||||
with the layout `bsp`.
|
||||
"""
|
||||
area = platform.work_area()
|
||||
_each_layout(platform, checks, clients, "", area)
|
||||
closed: list[Client] = []
|
||||
for keep in (n for n in FEWER if n < len(clients)):
|
||||
for client in clients[keep:]:
|
||||
if client not in closed:
|
||||
platform.close(client)
|
||||
closed.append(client)
|
||||
left = clients[:keep]
|
||||
platform.wait_for(lambda n=keep: platform.state().managed() == n, timeout=20)
|
||||
_each_layout(platform, checks, left, f" with {keep} windows", area)
|
||||
if closed:
|
||||
platform.komorebic("change-layout", "bsp")
|
||||
for client in closed:
|
||||
platform.spawn(client.title)
|
||||
checks.check(
|
||||
"the windows that were closed are opened again and managed",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
unhealthy(platform, clients) is None
|
||||
and platform.state().managed() == len(clients)
|
||||
),
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def sweep(
|
||||
platform: Platform,
|
||||
checks: Checks,
|
||||
clients: list[Client],
|
||||
config: str,
|
||||
commands: Sequence[str] = SWEEP,
|
||||
) -> None:
|
||||
"""Runs every command of `commands` (`SWEEP`), and checks that it is understood and leaves the
|
||||
daemon healthy. `config` is the path, on the platform, of a file the daemon can be told to
|
||||
load.
|
||||
|
||||
The sweep has commands that name the second monitor (`send-to-monitor 1`), so it needs two
|
||||
displays: one is plugged in first if the platform has only one.
|
||||
"""
|
||||
if len(platform.displays()) < 2:
|
||||
platform.add_display()
|
||||
platform.wait_for(lambda: len(platform.state().monitors) >= 2, timeout=30)
|
||||
for line in commands:
|
||||
words = line.format(config=config).split()
|
||||
status, out = platform.komorebic_status(*words)
|
||||
if status != 0 and NOT_A_COMMAND in out:
|
||||
checks.skip(f"komorebic {line}", "the port has no such command")
|
||||
continue
|
||||
if status != 0:
|
||||
checks.bad(f"komorebic {line}: exit {status}: {' '.join(out.splitlines()[:2])}")
|
||||
continue
|
||||
platform.wait_for(lambda: unhealthy(platform, clients) is None, timeout=5)
|
||||
if (why := unhealthy(platform, clients)) is not None:
|
||||
checks.bad(f"komorebic {line}: afterwards {why}")
|
||||
continue
|
||||
checks.ok(f"komorebic {line}")
|
||||
|
||||
|
||||
def prints(platform: Platform, checks: Checks) -> None:
|
||||
"""Runs every command that only prints something, and checks that each exits 0."""
|
||||
for line in PRINTED:
|
||||
status, out = platform.komorebic_status(*line.split())
|
||||
if status != 0 and NOT_A_COMMAND in out:
|
||||
checks.skip(f"komorebic {line}", "the port has no such command")
|
||||
continue
|
||||
checks.check(f"komorebic {line}", status == 0)
|
||||
|
||||
|
||||
def unknown_monitor(
|
||||
platform: Platform, checks: Checks, clients: list[Client], known_failure: str | None = None
|
||||
) -> None:
|
||||
"""Sends the focused window to a monitor that does not exist, and checks that no window is lost.
|
||||
|
||||
A port may refuse the command or ignore it, but a window that was managed has to stay managed:
|
||||
a daemon that stops managing it leaves it on the screen with nothing tiling it. The platform
|
||||
has fewer than seven displays.
|
||||
|
||||
With `known_failure`, the reason a port is known to lose the window, the checks are recorded as
|
||||
known failures: they do not fail the suite, and one that holds says the marker can go. The
|
||||
window is lost then, so the scenario belongs at the end of a suite.
|
||||
"""
|
||||
managed = platform.state().managed()
|
||||
for command in ("send-to-monitor", "move-to-monitor"):
|
||||
platform.komorebic_status(command, "7")
|
||||
platform.wait_for(lambda: unhealthy(platform, clients) is None, timeout=5)
|
||||
description = (
|
||||
f"after {command} 7, which no display has, the daemon still manages every window"
|
||||
)
|
||||
holds = platform.state().managed() == managed and unhealthy(platform, clients) is None
|
||||
if known_failure is None:
|
||||
checks.check(description, holds)
|
||||
else:
|
||||
checks.known_failure(description, holds, known_failure)
|
||||
@@ -0,0 +1,77 @@
|
||||
"""The daemon reloads its `komorebi.json` when the file changes: names, layout, rules."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Platform
|
||||
from komorebi_vm.core.scenarios.support import QUIET
|
||||
|
||||
|
||||
def _config(names: list[str], layout: str, rule: str | None = None) -> dict[str, Any]:
|
||||
workspaces: list[dict[str, Any]] = [{"name": name, "layout": layout} for name in names]
|
||||
if rule is not None:
|
||||
matcher = {"kind": "Title", "id": rule, "matching_strategy": "StartsWith"}
|
||||
workspaces[1]["workspace_rules"] = [matcher]
|
||||
return {"monitors": [{"workspaces": workspaces}]}
|
||||
|
||||
|
||||
def _names(platform: Platform) -> list[str | None]:
|
||||
return [w.name for w in platform.state().monitors[0].workspaces]
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""Starts the daemon from a file with two workspaces, a window open, and rewrites the file
|
||||
three times: with new names and a third workspace and another layout, with a workspace rule
|
||||
that sends the windows of a title to the second workspace, and with the rule gone.
|
||||
|
||||
The daemon is left running on that file, with the window open on the first workspace, which
|
||||
is in view. The daemon must have been running, with no window but the one it is given.
|
||||
"""
|
||||
stay = platform.spawn("reload-stays")
|
||||
platform.restart_with(_config(["one", "two"], "BSP"))
|
||||
checks.check(
|
||||
"the daemon starts with the workspaces of the file",
|
||||
_names(platform)[:2] == ["one", "two"],
|
||||
)
|
||||
checks.check(
|
||||
"the window that was open is managed",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(stay.title) == 0, timeout=30),
|
||||
)
|
||||
|
||||
platform.rewrite_config(_config(["uno", "dos", "tres"], "Columns"))
|
||||
checks.check(
|
||||
"a file with other names and one workspace more is loaded",
|
||||
platform.wait_for(lambda: _names(platform) == ["uno", "dos", "tres"], timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
"... with the layout the file gives the first workspace",
|
||||
platform.wait_for(lambda: platform.state().workspace().layout == "Columns", timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
"... and the window that was open stays where it was",
|
||||
platform.state().workspace_of(stay.title) == 0 and not platform.hidden(stay),
|
||||
)
|
||||
|
||||
platform.rewrite_config(_config(["uno", "dos", "tres"], "Columns", rule="reload-sent"))
|
||||
sent = platform.spawn("reload-sent-1")
|
||||
checks.check(
|
||||
"a rule the file gained sends a window that opens to its workspace",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(sent.title) == 1, timeout=30),
|
||||
)
|
||||
|
||||
platform.rewrite_config(_config(["uno", "dos", "tres"], "Columns"))
|
||||
# the reload does not say when it is done: the next window shows whether the rule is
|
||||
platform.wait_for(lambda: False, timeout=QUIET)
|
||||
later = platform.spawn("reload-sent-2")
|
||||
checks.check(
|
||||
"once the file loses the rule, a window of that title stays on the first workspace",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(later.title) == 0, timeout=30),
|
||||
)
|
||||
|
||||
platform.komorebic("change-layout", "bsp")
|
||||
for client in (sent, later):
|
||||
platform.close(client)
|
||||
checks.check(
|
||||
"the two windows are closed",
|
||||
platform.wait_for(lambda: platform.state().managed() == 1, timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""A display whose mode changes: the daemon's monitor follows, and the windows stay put."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.hotplug import _in_one_of
|
||||
from komorebi_vm.core.scenarios.support import positions
|
||||
|
||||
|
||||
def _size_follows(platform: Platform, index: int, size: tuple[int, int]) -> bool:
|
||||
"""The operating system's display and the daemon's monitor both have this size."""
|
||||
displays, monitors = platform.displays(), platform.state().monitors
|
||||
return (
|
||||
index < len(displays)
|
||||
and index < len(monitors)
|
||||
and (displays[index].w, displays[index].h) == size
|
||||
and (monitors[index].size.w, monitors[index].size.h) == size
|
||||
)
|
||||
|
||||
|
||||
def _clear(platform: Platform, clients: list[Client]) -> bool:
|
||||
"""Every window is on a display, and none is over another."""
|
||||
frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
return _in_one_of(platform, clients, platform.displays()) and not any(
|
||||
a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]
|
||||
)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Changes the mode of a display to a smaller one and back, and checks that the daemon's
|
||||
monitor has the size of each, that the windows are inside the displays and apart while it is
|
||||
small, and that they are where they were when the display is as it was.
|
||||
|
||||
`clients` are windows the daemon manages, each in a container of its own. A second display is
|
||||
plugged in first if the platform has only one, and the platform says which display can change
|
||||
its mode: where none can, the scenario is skipped.
|
||||
"""
|
||||
if len(platform.displays()) < 2:
|
||||
platform.add_display()
|
||||
platform.wait_for(lambda: len(platform.state().monitors) == len(platform.displays()))
|
||||
index = platform.resizable_display()
|
||||
if index is None:
|
||||
checks.skip(
|
||||
"a display changes its mode", "the platform cannot change the mode of a display"
|
||||
)
|
||||
return
|
||||
before = platform.displays()[index]
|
||||
size = (1280, 720) if before.w > 1280 else (1024, 768)
|
||||
there = positions(platform, clients)
|
||||
|
||||
platform.resize_display(index, *size)
|
||||
checks.check(
|
||||
f"the display has the mode {size[0]}x{size[1]} and the daemon's monitor follows",
|
||||
platform.wait_for(lambda: _size_follows(platform, index, size), timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
"... every window is on a display and clear of the others",
|
||||
platform.wait_for(lambda: _clear(platform, clients), timeout=30),
|
||||
)
|
||||
|
||||
platform.resize_display(index, before.w, before.h)
|
||||
checks.check(
|
||||
"changed back, the display and the monitor have their size again",
|
||||
platform.wait_for(lambda: _size_follows(platform, index, (before.w, before.h)), timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
"... and every window is where it was",
|
||||
platform.wait_for(lambda: positions(platform, clients) == there, timeout=30),
|
||||
)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""A flipped layout is the layout mirrored, and flipping it back gives the layout back."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Flips the layout of the first workspace, which has `clients` tiled in a container each,
|
||||
horizontally and back."""
|
||||
area = platform.work_area()
|
||||
|
||||
def centres() -> dict[str, int]:
|
||||
found = {}
|
||||
for client in clients:
|
||||
window = platform.os_window(client)
|
||||
if window is not None:
|
||||
found[client.title] = window.frame.x + window.frame.w // 2
|
||||
return found
|
||||
|
||||
before = centres()
|
||||
|
||||
def mirrored() -> bool:
|
||||
now = centres()
|
||||
return len(now) == len(before) and all(
|
||||
abs((2 * area.x + area.w - before[t]) - now[t]) <= platform.tolerance for t in before
|
||||
)
|
||||
|
||||
platform.komorebic("flip-layout", "horizontal")
|
||||
checks.check(
|
||||
"after 'flip-layout horizontal' every window is where the mirror of its place is",
|
||||
platform.wait_for(mirrored, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and every window is where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
|
||||
platform.komorebic("flip-layout", "horizontal")
|
||||
checks.check(
|
||||
"flipped again, every window is where it was",
|
||||
platform.wait_for(
|
||||
lambda: all(abs(centres()[t] - before[t]) <= platform.tolerance for t in before),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""A window that floats leaves the tiling to the others, and goes back into it when it stops."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Floats the last of `clients`, which are tiled windows of the first workspace in a
|
||||
container each, with more than one of them, and then tiles it again."""
|
||||
target = clients[-1]
|
||||
others = clients[:-1]
|
||||
platform.activate(target)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title))
|
||||
|
||||
def area(c: Client) -> int:
|
||||
window = platform.os_window(c)
|
||||
return window.frame.w * window.frame.h if window is not None else 0
|
||||
|
||||
def floating() -> list[str]:
|
||||
return [w.title for w in platform.state().workspace().floating]
|
||||
|
||||
before = sum(area(c) for c in others)
|
||||
managed = platform.state().managed()
|
||||
|
||||
platform.komorebic("toggle-float")
|
||||
checks.check(
|
||||
f"after 'toggle-float' the daemon has {target.title} floating",
|
||||
platform.wait_for(lambda: floating() == [target.title], timeout=20),
|
||||
)
|
||||
checks.check("... and still manages every window", platform.state().managed() == managed)
|
||||
checks.check(
|
||||
"... the others take more room between them",
|
||||
platform.wait_for(lambda: sum(area(c) for c in others) > before, timeout=20),
|
||||
)
|
||||
frames = [w.frame for c in others if (w := platform.os_window(c)) is not None]
|
||||
checks.check(
|
||||
"... inside the work area and not on each other",
|
||||
all(f.inside(platform.work_area()) for f in frames)
|
||||
and not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
checks.check(
|
||||
f"... {target.title} is still there, and not put away",
|
||||
platform.os_window(target) is not None and not platform.hidden(target),
|
||||
)
|
||||
|
||||
platform.komorebic("toggle-float")
|
||||
checks.check(
|
||||
f"after another 'toggle-float' {target.title} floats no more",
|
||||
platform.wait_for(lambda: floating() == [], timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and every window is tiled where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""The focus moves where komorebic says, and the operating system and the daemon agree on it."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees, os_focused, positions
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Moves the focus among `clients`, which are tiled windows of the first workspace, each in a
|
||||
container of its own, with `focus` and `cycle-focus`."""
|
||||
first = clients[0].title
|
||||
before = positions(platform, clients)
|
||||
|
||||
platform.activate(clients[0])
|
||||
checks.check(
|
||||
f"{first} has the focus, and the daemon agrees",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, first)),
|
||||
)
|
||||
|
||||
platform.komorebic("focus", "right")
|
||||
checks.check(
|
||||
"after 'focus right' the operating system has given the focus to another window",
|
||||
platform.wait_for(lambda: os_focused(platform, clients) not in ("", first)),
|
||||
)
|
||||
moved_to = os_focused(platform, clients)
|
||||
checks.check(
|
||||
"... and the daemon's state focuses the same one",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, moved_to)),
|
||||
)
|
||||
|
||||
platform.komorebic("focus", "left")
|
||||
checks.check(
|
||||
"'focus left' gives the focus back",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, first)),
|
||||
)
|
||||
|
||||
# the next container is whichever follows in the daemon's own order
|
||||
order = [titles[0] for titles in platform.state().containers() if titles]
|
||||
after = order[(order.index(first) + 1) % len(order)]
|
||||
platform.komorebic("cycle-focus", "next")
|
||||
checks.check(
|
||||
f"'cycle-focus next' focuses {after}, the next container in the daemon's order",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, after)),
|
||||
)
|
||||
platform.komorebic("cycle-focus", "previous")
|
||||
checks.check(
|
||||
"'cycle-focus previous' goes back",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, first)),
|
||||
)
|
||||
checks.check("moving the focus moved no window", positions(platform, clients) == before)
|
||||
@@ -0,0 +1,89 @@
|
||||
"""With focus follows mouse on, the window under the pointer has the focus; with it off, not."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import QUIET
|
||||
|
||||
|
||||
def _middle(platform: Platform, client: Client) -> tuple[int, int] | None:
|
||||
window = platform.os_window(client)
|
||||
if window is None:
|
||||
return None
|
||||
return window.frame.x + window.frame.w // 2, window.frame.y + window.frame.h // 2
|
||||
|
||||
|
||||
def _focused(platform: Platform, client: Client) -> bool:
|
||||
window = platform.os_window(client)
|
||||
return window is not None and window.focused
|
||||
|
||||
|
||||
# how long a setting is given to be taken up before the pointer is moved. A port may read it a
|
||||
# moment after it is written, or follow the pointer after a delay of its own: this is more than
|
||||
# either, and it is scaled for the host like every wait
|
||||
SETTLE = 1
|
||||
|
||||
|
||||
def _settle(platform: Platform) -> None:
|
||||
"""Gives the platform the time to take up a setting: a pointer that is moved before is moved
|
||||
under the old one."""
|
||||
platform.wait_for(lambda: False, timeout=SETTLE)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, first: Client, second: Client) -> None:
|
||||
"""Turns focus follows mouse on, moves the pointer over `first` and `second` in turn, turns it
|
||||
off, and on again, and checks where the focus is.
|
||||
|
||||
`first` and `second` are two tiled windows in view, not on each other. The setting is left off
|
||||
at the end. The platform needs a pointer; without one the scenario says so and stops.
|
||||
"""
|
||||
if not platform.has("pointer"):
|
||||
print(" skipped: this platform has no pointer")
|
||||
return
|
||||
a, b = _middle(platform, first), _middle(platform, second)
|
||||
checks.check("both windows have a middle for the pointer", a is not None and b is not None)
|
||||
if a is None or b is None:
|
||||
return
|
||||
|
||||
platform.komorebic("focus-follows-mouse", "enable")
|
||||
_settle(platform)
|
||||
platform.pointer.move(*a)
|
||||
checks.check(
|
||||
"the pointer over the first window gives it the focus",
|
||||
platform.wait_for(lambda: _focused(platform, first), timeout=10),
|
||||
)
|
||||
platform.pointer.move(*b)
|
||||
checks.check(
|
||||
"over the second, the second",
|
||||
platform.wait_for(lambda: _focused(platform, second), timeout=10),
|
||||
)
|
||||
platform.pointer.move(*a)
|
||||
checks.check("and back", platform.wait_for(lambda: _focused(platform, first), timeout=10))
|
||||
checks.check(
|
||||
"the daemon follows: it has the first window focused",
|
||||
platform.wait_for(lambda: platform.state().focused_title() == first.title, timeout=10),
|
||||
)
|
||||
|
||||
# no `--implementation`: each port has one, and the command's default is it
|
||||
platform.komorebic("toggle-focus-follows-mouse")
|
||||
_settle(platform)
|
||||
platform.pointer.move(*b)
|
||||
checks.check(
|
||||
"turned off, the pointer over the second window no longer moves the focus",
|
||||
not platform.wait_for(lambda: _focused(platform, second), timeout=QUIET)
|
||||
and _focused(platform, first),
|
||||
)
|
||||
|
||||
platform.komorebic("focus-follows-mouse", "enable")
|
||||
_settle(platform)
|
||||
# the pointer rests over the second window: it has to go into a window to be followed. The
|
||||
# first window already has the focus, so there is nothing to wait for there: the pointer rests
|
||||
# over it for a moment, as a person's would, and a platform that follows the pointer by a
|
||||
# hover delay (Windows) has seen it enter that window before it enters the other
|
||||
platform.pointer.move(*a)
|
||||
_settle(platform)
|
||||
platform.pointer.move(*b)
|
||||
checks.check(
|
||||
"on again, the pointer over the second window gives it the focus",
|
||||
platform.wait_for(lambda: _focused(platform, second), timeout=10),
|
||||
)
|
||||
platform.komorebic("focus-follows-mouse", "disable")
|
||||
@@ -0,0 +1,73 @@
|
||||
"""A window the user takes fullscreen is left alone by the daemon, and goes back to its tile."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees
|
||||
|
||||
|
||||
def _covers(frame: Rect, display: Rect) -> bool:
|
||||
"""The frame has the whole display, give or take a pixel."""
|
||||
return (
|
||||
frame.x <= display.x + 1
|
||||
and frame.y <= display.y + 1
|
||||
and frame.x + frame.w >= display.x + display.w - 1
|
||||
and frame.y + frame.h >= display.y + display.h - 1
|
||||
)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Takes the last of `clients` fullscreen, opens a window, and brings it back.
|
||||
|
||||
`clients` are tiled windows of the first workspace on the first display, each in a container
|
||||
of its own. The window opened is closed at the end.
|
||||
"""
|
||||
target = clients[-1]
|
||||
count = platform.state().managed()
|
||||
display = platform.displays()[0]
|
||||
platform.activate(target)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title))
|
||||
# the daemon asks again for the frames of what it moved, for a little while after a command
|
||||
platform.wait_for(lambda: False, timeout=3)
|
||||
|
||||
def covers() -> bool:
|
||||
window = platform.os_window(target)
|
||||
return window is not None and _covers(window.frame, display)
|
||||
|
||||
platform.fullscreen(target)
|
||||
checks.check(
|
||||
"a window taken fullscreen covers the display",
|
||||
platform.wait_for(covers, timeout=20),
|
||||
)
|
||||
extra = platform.spawn("fullscreen-extra")
|
||||
checks.check(
|
||||
"the daemon manages a window that opens meanwhile",
|
||||
platform.wait_for(lambda: platform.state().managed() == count + 1, timeout=20),
|
||||
)
|
||||
platform.wait_for(lambda: False, timeout=3)
|
||||
checks.check("... and it does not take the window out of fullscreen", covers())
|
||||
|
||||
platform.fullscreen(target, on=False)
|
||||
|
||||
def in_a_tile() -> bool:
|
||||
window = platform.os_window(target)
|
||||
return (
|
||||
window is not None
|
||||
and window.frame.w < display.w - 100
|
||||
and window.frame.inside(display, 1)
|
||||
)
|
||||
|
||||
checks.check(
|
||||
"back from fullscreen it is in a tile, inside the display",
|
||||
platform.wait_for(in_a_tile, timeout=20),
|
||||
)
|
||||
frames = [w.frame for c in [*clients, extra] if (w := platform.os_window(c)) is not None]
|
||||
checks.check(
|
||||
"... not on any other window",
|
||||
not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
checks.check(
|
||||
"... and the daemon still has every window", platform.state().managed() == count + 1
|
||||
)
|
||||
platform.close(extra)
|
||||
platform.wait_for(lambda: platform.state().managed() == count, timeout=20)
|
||||
@@ -0,0 +1,78 @@
|
||||
"""`minimize`, `unmanage` and `manage`: the daemon lets go of the focused window, and takes it up
|
||||
again."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import describe, focus_agrees
|
||||
from komorebi_vm.core.scenarios.tiling import _where_the_layout_says
|
||||
|
||||
|
||||
def _on_a_tile(platform: Platform, client: Client) -> bool:
|
||||
"""The window is where the daemon's layout puts one of its tiles."""
|
||||
window = platform.os_window(client)
|
||||
layout = platform.state().workspace().latest_layout
|
||||
return window is not None and any(
|
||||
_where_the_layout_says(window.frame, tile, platform.tolerance) for tile in layout
|
||||
)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Runs `minimize`, `unmanage` and `manage` on the window that has the focus, which is one of
|
||||
`clients`: tiled windows of the first workspace, in a container each.
|
||||
|
||||
They take a window out of the daemon's hands, so a sweep of commands does not run them. The
|
||||
window is tiled again at the end.
|
||||
|
||||
There have to be two containers or more on the focused workspace. A window that is alone there
|
||||
stays on the tile it was put on, and an emptied workspace keeps its last layout (the daemon has
|
||||
nothing to calculate), so "not on a tile of the layout" could never hold: the scenario says so
|
||||
and stops, rather than fail on a precondition that was never met.
|
||||
"""
|
||||
tiled = len(platform.state().workspace().containers)
|
||||
if not checks.check(
|
||||
"the focused workspace has two tiled containers or more, for a window to be let go of"
|
||||
f" (it has {tiled})",
|
||||
tiled >= 2,
|
||||
):
|
||||
print(describe(platform, clients))
|
||||
return
|
||||
title = platform.state().focused_title()
|
||||
target = Client(title)
|
||||
before = platform.state().managed()
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, title), timeout=10)
|
||||
|
||||
def has_let_go() -> bool:
|
||||
return platform.state().managed() == before - 1 and platform.os_window(target) is not None
|
||||
|
||||
def has_it() -> bool:
|
||||
return platform.state().managed() == before and _on_a_tile(platform, target)
|
||||
|
||||
platform.komorebic("minimize")
|
||||
checks.check(
|
||||
f"minimize: the daemon lets go of {title}, which stays open",
|
||||
platform.wait_for(has_let_go, timeout=10),
|
||||
)
|
||||
platform.activate(target)
|
||||
checks.check(f"{title}, restored, is tiled again", platform.wait_for(has_it, timeout=10))
|
||||
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, title), timeout=10)
|
||||
platform.komorebic("unmanage")
|
||||
checks.check(
|
||||
f"unmanage: the daemon lets go of {title}, which stays open",
|
||||
platform.wait_for(has_let_go, timeout=10),
|
||||
)
|
||||
area = platform.work_area()
|
||||
|
||||
def left_alone() -> bool:
|
||||
window = platform.os_window(target)
|
||||
return (
|
||||
window is not None and window.frame.inside(area, 2) and not _on_a_tile(platform, target)
|
||||
)
|
||||
|
||||
if not checks.check(
|
||||
f"{title} is inside the work area and not on a tile of the layout",
|
||||
platform.wait_for(left_alone, timeout=10),
|
||||
):
|
||||
print(describe(platform, clients))
|
||||
platform.komorebic("manage")
|
||||
checks.check(f"manage: {title} is tiled again", platform.wait_for(has_it, timeout=10))
|
||||
@@ -0,0 +1,178 @@
|
||||
"""A display that is unplugged takes its windows to the other, and one plugged in is a monitor."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
|
||||
|
||||
def _monitors(platform: Platform) -> int:
|
||||
return len(platform.state().monitors)
|
||||
|
||||
|
||||
def _in_one_of(platform: Platform, clients: list[Client], displays: list[Rect]) -> bool:
|
||||
frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
return len(frames) == len(clients) and all(
|
||||
any(f.inside(d, 1) for d in displays) for f in frames
|
||||
)
|
||||
|
||||
|
||||
def _tiled_in(platform: Platform, clients: list[Client], area: Rect) -> bool:
|
||||
frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
return (
|
||||
len(frames) == len(clients)
|
||||
and all(f.inside(area, 1) for f in frames)
|
||||
and not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :])
|
||||
)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Unplugs a display, plugs one in again, and sends a window to it.
|
||||
|
||||
`clients` are windows the daemon manages, each in a container of its own, on any display. The
|
||||
platform has one display or more; one is plugged in first if it has only one.
|
||||
"""
|
||||
if len(platform.displays()) < 2:
|
||||
platform.add_display()
|
||||
checks.check(
|
||||
"the daemon has a monitor for each display",
|
||||
platform.wait_for(lambda: _monitors(platform) == len(platform.displays()), timeout=30),
|
||||
)
|
||||
managed = platform.state().managed()
|
||||
|
||||
platform.remove_display()
|
||||
checks.check(
|
||||
"after a display is unplugged the daemon has one monitor fewer",
|
||||
platform.wait_for(lambda: _monitors(platform) == len(platform.displays()), timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
"... every window is on the displays that are left, tiled and clear of each other",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
_in_one_of(platform, clients, platform.displays())
|
||||
and (
|
||||
len(platform.displays()) > 1
|
||||
or _tiled_in(platform, clients, platform.work_area())
|
||||
)
|
||||
),
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
"... and the daemon still manages every window",
|
||||
platform.wait_for(lambda: platform.state().managed() == managed, timeout=20),
|
||||
)
|
||||
|
||||
platform.add_display()
|
||||
checks.check(
|
||||
"after a display is plugged in the daemon has a monitor for it again",
|
||||
platform.wait_for(lambda: _monitors(platform) == len(platform.displays()), timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
"... still manages every window, each where it can be seen",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
platform.state().managed() == managed
|
||||
and _in_one_of(platform, clients, platform.displays())
|
||||
),
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
|
||||
# the focused window goes to the other monitor
|
||||
displays = platform.displays()
|
||||
focused = next(
|
||||
(c for c in clients if (w := platform.os_window(c)) is not None and w.focused), None
|
||||
)
|
||||
checks.check("a window has the focus", focused is not None)
|
||||
if focused is None:
|
||||
return
|
||||
window = platform.os_window(focused)
|
||||
assert window is not None
|
||||
here = next((i for i, d in enumerate(displays) if window.frame.inside(d, 1)), None)
|
||||
checks.check("it is on one of the displays", here is not None)
|
||||
if here is None:
|
||||
return
|
||||
there = 1 if here == 0 else 0
|
||||
platform.komorebic("move-to-monitor", str(there))
|
||||
checks.check(
|
||||
"after move-to-monitor it is on the other display",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
(w := platform.os_window(focused)) is not None
|
||||
and w.frame.inside(displays[there], 1)
|
||||
),
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _display_of(frame: Rect, displays: list[Rect]) -> int | None:
|
||||
"""The display the middle of the frame is on."""
|
||||
x, y = frame.x + frame.w // 2, frame.y + frame.h // 2
|
||||
for i, d in enumerate(displays):
|
||||
if d.x <= x < d.x + d.w and d.y <= y < d.y + d.h:
|
||||
return i
|
||||
return None
|
||||
|
||||
|
||||
def _split(platform: Platform, clients: list[Client]) -> dict[int, list[Client]]:
|
||||
"""The windows on each display, by the middle of their frames."""
|
||||
displays = platform.displays()
|
||||
found: dict[int, list[Client]] = {i: [] for i in range(len(displays))}
|
||||
for client in clients:
|
||||
window = platform.os_window(client)
|
||||
if window is not None and (i := _display_of(window.frame, displays)) is not None:
|
||||
found[i].append(client)
|
||||
return found
|
||||
|
||||
|
||||
def _containers(platform: Platform, monitor: int) -> int:
|
||||
return len(platform.state().workspace(monitor=monitor).containers)
|
||||
|
||||
|
||||
def _each_tiled_on_its_display(platform: Platform, clients: list[Client]) -> bool:
|
||||
displays = platform.displays()
|
||||
return all(_tiled_in(platform, on, displays[i]) for i, on in _split(platform, clients).items())
|
||||
|
||||
|
||||
def user_move(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""A window that something other than the daemon moves to the other display is tiled on that
|
||||
monitor, and the windows that are left are tiled on the first.
|
||||
|
||||
`clients` are windows the daemon manages, each in a container of its own, on the first display,
|
||||
two of them or more. A second display is plugged in first if the platform has only one. The
|
||||
window that moves is the last of `clients` on the first display, and it stays on the second.
|
||||
"""
|
||||
if len(platform.displays()) < 2:
|
||||
platform.add_display()
|
||||
platform.wait_for(lambda: _monitors(platform) == len(platform.displays()), timeout=30)
|
||||
displays = platform.displays()
|
||||
on_first = _split(platform, clients)[0]
|
||||
if len(on_first) < 2:
|
||||
checks.skip("a window moved to the other display", "fewer than two windows on the first")
|
||||
return
|
||||
window = on_first[-1]
|
||||
first, second = _containers(platform, 0), _containers(platform, 1)
|
||||
# the daemon asks again for the frames of the windows it moved, for a little while after a
|
||||
# command: a user moves a window later than that
|
||||
platform.wait_for(lambda: False, timeout=2)
|
||||
platform.move_window(window, displays[1].x + 180, displays[1].y + 300)
|
||||
checks.check(
|
||||
"the daemon has the window on the other monitor",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
_containers(platform, 0) == first - 1 and _containers(platform, 1) == second + 1
|
||||
),
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
"every window is tiled inside the display it is on, and the moved one is on the second",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
window in _split(platform, clients)[1]
|
||||
and _each_tiled_on_its_display(platform, clients)
|
||||
),
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,277 @@
|
||||
"""The `layout_flip` option of a workspace, in the config: the layout is mirrored from the start."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
|
||||
CLI = {
|
||||
"Horizontal": "horizontal",
|
||||
"Vertical": "vertical",
|
||||
"HorizontalAndVertical": "horizontal-and-vertical",
|
||||
}
|
||||
"""The values the option takes, and how `flip-layout` spells each."""
|
||||
|
||||
# (layout, windows, value of the option): where a flip along an axis shows. The columns are in a
|
||||
# row, so only a horizontal flip moves them; the rows are in a column, so only a vertical one does;
|
||||
# BSP with three windows has one tile on a side and two stacked on the other, so both do.
|
||||
CASES = [
|
||||
("Columns", 2, "Horizontal"),
|
||||
("BSP", 2, "Horizontal"),
|
||||
("Columns", 3, "Horizontal"),
|
||||
("Columns", 3, "Vertical"),
|
||||
("Columns", 3, "HorizontalAndVertical"),
|
||||
("Rows", 3, "Vertical"),
|
||||
("BSP", 3, "Horizontal"),
|
||||
("BSP", 3, "Vertical"),
|
||||
("BSP", 3, "HorizontalAndVertical"),
|
||||
]
|
||||
|
||||
Flip = tuple[bool, bool]
|
||||
"""Whether the layout is mirrored along x (left to right) and along y (top to bottom)."""
|
||||
|
||||
|
||||
def _flip(value: str | None) -> Flip:
|
||||
return (
|
||||
value in ("Horizontal", "HorizontalAndVertical"),
|
||||
value in ("Vertical", "HorizontalAndVertical"),
|
||||
)
|
||||
|
||||
|
||||
def _config(layout: str, value: str | None) -> dict[str, Any]:
|
||||
workspace: dict[str, Any] = {"name": "flip", "layout": layout}
|
||||
if value is not None:
|
||||
workspace["layout_flip"] = value
|
||||
return {"monitors": [{"workspaces": [workspace]}]}
|
||||
|
||||
|
||||
def _witnesses(layout: str, count: int) -> list[tuple[int, str]]:
|
||||
"""The containers whose side of the work area says which way the layout is mirrored, each with
|
||||
the axis. Unflipped, the first column is on the left, the first row at the top, the first BSP
|
||||
tile on the left and the second at the top right."""
|
||||
return {
|
||||
"Columns": [(0, "x")],
|
||||
"Rows": [(0, "y")],
|
||||
"BSP": [(0, "x")] + ([(1, "y")] if count >= 3 else []),
|
||||
}[layout]
|
||||
|
||||
|
||||
def _beyond_the_middle(platform: Platform, title: str, axis: str, area: Rect) -> bool | None:
|
||||
"""Whether the window is on the far side of the middle of the work area (right, or below)."""
|
||||
window = platform.os_window(Client(title))
|
||||
if window is None:
|
||||
return None
|
||||
f = window.frame
|
||||
if axis == "x":
|
||||
return 2 * f.x + f.w > 2 * area.x + area.w
|
||||
return 2 * f.y + f.h > 2 * area.y + area.h
|
||||
|
||||
|
||||
def _on_the_side(platform: Platform, layout: str, count: int, flip: Flip, area: Rect) -> bool:
|
||||
"""Every witness is on the side that a layout flipped as `flip` puts it."""
|
||||
order = [c[0] for c in platform.state().containers()]
|
||||
for index, axis in _witnesses(layout, count):
|
||||
if index >= len(order):
|
||||
return False
|
||||
side = _beyond_the_middle(platform, order[index], axis, area)
|
||||
if side is None or side != flip[0 if axis == "x" else 1]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _centres(platform: Platform, clients: list[Client]) -> dict[str, tuple[int, int]]:
|
||||
"""The middle of each window, doubled so that it is a whole number."""
|
||||
found = {}
|
||||
for client in clients:
|
||||
window = platform.os_window(client)
|
||||
if window is not None:
|
||||
f = window.frame
|
||||
found[client.title] = (2 * f.x + f.w, 2 * f.y + f.h)
|
||||
return found
|
||||
|
||||
|
||||
def _mirrored(
|
||||
platform: Platform,
|
||||
before: dict[str, tuple[int, int]],
|
||||
now: dict[str, tuple[int, int]],
|
||||
flip: Flip,
|
||||
area: Rect,
|
||||
) -> bool:
|
||||
"""Every window of `now` is where the mirror of its place in `before` along `flip` is."""
|
||||
middle = (2 * area.x + area.w, 2 * area.y + area.h)
|
||||
tolerance = 2 * platform.tolerance
|
||||
return len(now) == len(before) and all(
|
||||
t in now
|
||||
and abs((2 * middle[0] - x if flip[0] else x) - now[t][0]) <= tolerance
|
||||
and abs((2 * middle[1] - y if flip[1] else y) - now[t][1]) <= tolerance
|
||||
for t, (x, y) in before.items()
|
||||
)
|
||||
|
||||
|
||||
def _check_case(
|
||||
platform: Platform,
|
||||
checks: Checks,
|
||||
clients: list[Client],
|
||||
layout: str,
|
||||
value: str,
|
||||
compose: bool,
|
||||
) -> None:
|
||||
count = len(clients)
|
||||
label = f"{layout}, {count} windows, layout_flip {value}"
|
||||
area = platform.work_area()
|
||||
flip = _flip(value)
|
||||
unflipped: Flip = (False, False)
|
||||
|
||||
platform.restart_with(_config(layout, value))
|
||||
platform.wait_for(lambda: platform.state().managed() == count, timeout=30)
|
||||
checks.check(
|
||||
f"{label}: the daemon starts with the layout mirrored: the windows are where it says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
f"{label}: ... and on the side of the work area that the flip puts them",
|
||||
platform.wait_for(lambda: _on_the_side(platform, layout, count, flip, area), timeout=20),
|
||||
)
|
||||
mirrored = _centres(platform, clients)
|
||||
|
||||
# the command and the option are one flip: the command flips it off
|
||||
platform.komorebic("flip-layout", CLI[value])
|
||||
checks.check(
|
||||
f"{label}: 'flip-layout {CLI[value]}' turns it off: the windows are on the other side",
|
||||
platform.wait_for(
|
||||
lambda: _on_the_side(platform, layout, count, unflipped, area), timeout=20
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
f"{label}: ... each where the mirror of its place is",
|
||||
platform.wait_for(
|
||||
lambda: _mirrored(platform, mirrored, _centres(platform, clients), flip, area),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
f"{label}: ... and where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
platform.komorebic("flip-layout", CLI[value])
|
||||
checks.check(
|
||||
f"{label}: flipped again with the command, the windows are where the option put them",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
_mirrored(platform, mirrored, _centres(platform, clients), unflipped, area)
|
||||
and _on_the_side(platform, layout, count, flip, area)
|
||||
),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
|
||||
if compose:
|
||||
# on top of a horizontal flip, a vertical one is both
|
||||
platform.komorebic("flip-layout", "vertical")
|
||||
both = _flip("HorizontalAndVertical")
|
||||
checks.check(
|
||||
f"{label}: 'flip-layout vertical' adds to it: flipped along both axes",
|
||||
platform.wait_for(
|
||||
lambda: _on_the_side(platform, layout, count, both, area), timeout=20
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
f"{label}: ... the windows have only gone from top to bottom",
|
||||
platform.wait_for(
|
||||
lambda: _mirrored(
|
||||
platform, mirrored, _centres(platform, clients), (False, True), area
|
||||
),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _left_to_right(platform: Platform, workspace: int) -> list[str] | None:
|
||||
"""The titles of the containers of a workspace, ordered by where the window is, left to right;
|
||||
`None` when a window is not there."""
|
||||
order = [c[0] for c in platform.state().containers(workspace)]
|
||||
centres = _centres(platform, [Client(t) for t in order])
|
||||
if len(centres) != len(order):
|
||||
return None
|
||||
return sorted(order, key=lambda t: centres[t][0])
|
||||
|
||||
|
||||
def _two_workspaces(platform: Platform, checks: Checks, flipped: int) -> None:
|
||||
"""Two workspaces of columns, one of them flipped, each with two windows."""
|
||||
rule = {"kind": "Title", "id": "flip plain", "matching_strategy": "StartsWith"}
|
||||
workspaces: list[dict[str, Any]] = [
|
||||
{"name": "first", "layout": "Columns"},
|
||||
{"name": "second", "layout": "Columns", "workspace_rules": [rule]},
|
||||
]
|
||||
workspaces[flipped]["layout_flip"] = "Horizontal"
|
||||
homes = [platform.spawn("flip home 1"), platform.spawn("flip home 2")]
|
||||
plains = [platform.spawn("flip plain 1"), platform.spawn("flip plain 2")]
|
||||
platform.restart_with({"monitors": [{"workspaces": workspaces}]})
|
||||
label = f"layout_flip on workspace {flipped} of two"
|
||||
checks.check(
|
||||
f"{label}: the windows are on the workspaces the rule gives them",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
all(platform.state().workspace_of(c.title) == 0 for c in homes)
|
||||
and all(platform.state().workspace_of(c.title) == 1 for c in plains)
|
||||
),
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
for workspace in (0, 1):
|
||||
platform.komorebic("focus-workspace", str(workspace))
|
||||
members = homes if workspace == 0 else plains
|
||||
platform.wait_for(lambda m=members: not any(platform.hidden(c) for c in m), timeout=20)
|
||||
order = [c[0] for c in platform.state().containers(workspace)]
|
||||
want = order[::-1] if workspace == flipped else order
|
||||
checks.check(
|
||||
f"{label}: workspace {workspace} has its windows "
|
||||
+ ("mirrored" if workspace == flipped else "in the order of the layout"),
|
||||
platform.wait_for(lambda w=workspace, e=want: _left_to_right(platform, w) == e),
|
||||
)
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
for client in homes + plains:
|
||||
platform.close(client)
|
||||
platform.wait_for(lambda: platform.state().managed() == 0, timeout=30)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""Starts the daemon with `layout_flip` in the config of a workspace, for each value the
|
||||
option takes, and checks that the windows are mirrored as the value says, that `flip-layout`
|
||||
and the option are the one flip, and that the option is the workspace's own.
|
||||
|
||||
The daemon must be running and have no window open: `restart_with` makes a daemon that takes
|
||||
up every window in view, and opening the windows before it is the usual way to have them
|
||||
there. The daemon is left running on the last config this makes.
|
||||
|
||||
The option is `layout_flip` of a workspace in `komorebi.json` (`WorkspaceConfig` in
|
||||
`komorebi/src/static_config.rs`, which `Workspace::load_static_config` copies to the
|
||||
workspace, as `komorebic flip-layout` sets it). Its values are `Horizontal`, `Vertical` and
|
||||
`HorizontalAndVertical`: the layout is mirrored left to right, top to bottom, or both, which
|
||||
is what `Axis` means in `flip_layout`. `flip-layout X` along an axis the layout is already
|
||||
flipped along turns that flip off, and along another axis adds it, so that `flip-layout
|
||||
horizontal` on a layout the config flipped horizontally gives the layout back.
|
||||
|
||||
Where a flip shows depends on the layout: columns are only mirrored by a horizontal flip and
|
||||
rows by a vertical one (the layouts say so), and BSP with three windows by both. So each case
|
||||
looks at the windows whose side tells: the first column, the first row, and the first and
|
||||
second tile of BSP. A flip along an axis the layout does not have changes nothing, which a
|
||||
case checks too.
|
||||
|
||||
A window that was opened before the daemon is taken up by it, so the windows the cases use are
|
||||
the same ones, two and then three, and are closed at the end.
|
||||
"""
|
||||
clients = [platform.spawn("layout_flip 1"), platform.spawn("layout_flip 2")]
|
||||
for layout, count, value in CASES:
|
||||
if count == 3 and len(clients) == 2:
|
||||
clients.append(platform.spawn("layout_flip 3"))
|
||||
# the flip is added to by a command in one case, which has all of the axes to show it
|
||||
compose = (layout, count, value) == ("BSP", 3, "Horizontal")
|
||||
_check_case(platform, checks, clients, layout, value, compose)
|
||||
for client in clients:
|
||||
platform.close(client)
|
||||
platform.wait_for(lambda: platform.state().managed() == 0, timeout=30)
|
||||
for flipped in (0, 1):
|
||||
_two_workspaces(platform, checks, flipped)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Each layout the daemon has tiles the windows it is given: where it says, none over another."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.tiling import _where_the_layout_says
|
||||
|
||||
# the layouts both ports have, but for scrolling, which does not fit the work area
|
||||
LAYOUTS = (
|
||||
"bsp",
|
||||
"columns",
|
||||
"rows",
|
||||
"vertical-stack",
|
||||
"horizontal-stack",
|
||||
"ultrawide-vertical-stack",
|
||||
"grid",
|
||||
"right-main-vertical-stack",
|
||||
)
|
||||
|
||||
|
||||
def tiled(platform: Platform, clients: list[Client]) -> bool:
|
||||
"""Every window is where the daemon's own layout puts it, as the OS reports it."""
|
||||
workspace = platform.state().workspace()
|
||||
layout = workspace.latest_layout
|
||||
frames = [platform.os_window(c) for c in clients]
|
||||
if len(layout) != len(clients) or any(f is None for f in frames):
|
||||
return False
|
||||
by_title = {w.title: layout[i] for i, c in enumerate(workspace.containers) for w in c[:1]}
|
||||
return all(
|
||||
f is not None
|
||||
and f.title in by_title
|
||||
and _where_the_layout_says(f.frame, by_title[f.title], platform.tolerance)
|
||||
for f in frames
|
||||
)
|
||||
|
||||
|
||||
def _check_layout(platform: Platform, checks: Checks, clients: list[Client], layout: str) -> None:
|
||||
label = f"{layout}, {len(clients)} windows"
|
||||
platform.komorebic("change-layout", layout)
|
||||
checks.check(
|
||||
f"{label}: every window is where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
area = platform.work_area()
|
||||
frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
checks.check(f"{label}: ... inside the work area", all(f.inside(area) for f in frames))
|
||||
checks.check(
|
||||
f"{label}: ... and not on each other",
|
||||
not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
|
||||
|
||||
FEWER = (3, 2, 1)
|
||||
"""The counts of windows below the one the scenario starts with that every layout is tried with."""
|
||||
|
||||
|
||||
def _fewer(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Every layout with fewer windows: those of `FEWER` that `clients` has more than, the others
|
||||
closed from the end, and opened again with their own titles at the end."""
|
||||
closed: list[Client] = []
|
||||
for keep in (n for n in FEWER if n < len(clients)):
|
||||
for client in clients[keep:]:
|
||||
if client not in closed:
|
||||
platform.close(client)
|
||||
closed.append(client)
|
||||
left = clients[:keep]
|
||||
checks.check(
|
||||
f"{keep} windows are left managed",
|
||||
platform.wait_for(lambda n=keep: platform.state().managed() == n, timeout=20),
|
||||
)
|
||||
for layout in LAYOUTS:
|
||||
_check_layout(platform, checks, left, layout)
|
||||
platform.komorebic("change-layout", "bsp")
|
||||
for client in closed:
|
||||
platform.spawn(client.title)
|
||||
checks.check(
|
||||
"the windows that were closed are opened again and tiled",
|
||||
platform.wait_for(
|
||||
lambda: platform.state().managed() == len(clients) and tiled(platform, clients),
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Changes the layout of the first workspace to each of `LAYOUTS` with `clients`, which are
|
||||
tiled windows in a container each, and then with two windows more, which it closes, and with
|
||||
three, two and one windows of `clients`, which it closes, and opens again.
|
||||
|
||||
The layout is `bsp` again at the end.
|
||||
"""
|
||||
for layout in LAYOUTS:
|
||||
_check_layout(platform, checks, clients, layout)
|
||||
|
||||
more = [platform.spawn("layouts-extra1"), platform.spawn("layouts-extra2")]
|
||||
everyone = clients + more
|
||||
checks.check(
|
||||
"two windows more are managed",
|
||||
platform.wait_for(lambda: platform.state().managed() == len(everyone), timeout=20),
|
||||
)
|
||||
for layout in LAYOUTS:
|
||||
_check_layout(platform, checks, everyone, layout)
|
||||
|
||||
platform.komorebic("change-layout", "bsp")
|
||||
for client in more:
|
||||
platform.close(client)
|
||||
checks.check(
|
||||
"the two windows are closed and the others tiled again",
|
||||
platform.wait_for(
|
||||
lambda: platform.state().managed() == len(clients) and tiled(platform, clients),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
_fewer(platform, checks, clients)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""The daemon stops, its windows stay, and a daemon that starts again takes them up."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Stops the daemon and starts it again, with `clients` open, tiled windows of the first
|
||||
workspace.
|
||||
|
||||
What the daemon knew about workspaces is not asked for after the start, only that every window
|
||||
that was in view is managed and tiled again.
|
||||
"""
|
||||
seen = [c for c in clients if not platform.hidden(c)]
|
||||
platform.komorebic("stop")
|
||||
checks.check(
|
||||
"the daemon stops answering",
|
||||
platform.wait_for(lambda: platform.komorebic_status("state")[0] != 0, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"every window is still there",
|
||||
all(platform.os_window(c) is not None for c in clients),
|
||||
)
|
||||
|
||||
platform.start_komorebi()
|
||||
checks.check(
|
||||
"the daemon manages every window that was in view",
|
||||
platform.wait_for(lambda: platform.state().managed() >= len(seen), timeout=30),
|
||||
)
|
||||
area = platform.work_area()
|
||||
frames = [w.frame for c in seen if (w := platform.os_window(c)) is not None]
|
||||
checks.check("... they all have a frame", len(frames) == len(seen))
|
||||
checks.check("... inside the work area", all(f.inside(area) for f in frames))
|
||||
checks.check(
|
||||
"... and not on each other",
|
||||
not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
fresh = platform.spawn("after-the-restart")
|
||||
checks.check(
|
||||
"a window opened now is managed too",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(fresh.title) is not None),
|
||||
)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""A window that was put away on another workspace is not lost when the daemon restarts."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import describe, focus_agrees
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Sends the last of `clients`, which are tiled windows of workspace 0, to workspace 1,
|
||||
stops the daemon and starts it again.
|
||||
|
||||
Where the daemon puts the window afterwards is not asked for, only that it manages every
|
||||
window again and that the ones in view are inside the work area and clear of each other.
|
||||
"""
|
||||
target = clients[-1]
|
||||
platform.activate(target)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title))
|
||||
platform.komorebic("send-to-workspace", "1")
|
||||
checks.check(
|
||||
f"{target.title} is put away on workspace 1",
|
||||
platform.wait_for(lambda: platform.state().containers(1) == [[target.title]], timeout=20),
|
||||
)
|
||||
|
||||
platform.komorebic("stop")
|
||||
checks.check(
|
||||
"the daemon stops answering",
|
||||
platform.wait_for(lambda: platform.komorebic_status("state")[0] != 0, timeout=20),
|
||||
)
|
||||
platform.start_komorebi()
|
||||
checks.check(
|
||||
"the daemon manages every window again, the one that was put away too",
|
||||
platform.wait_for(lambda: platform.state().managed() >= len(clients), timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
f"... and it has {target.title} on a workspace",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(target.title) is not None),
|
||||
)
|
||||
area = platform.work_area()
|
||||
frames = [
|
||||
w.frame
|
||||
for c in clients
|
||||
if not platform.hidden(c) and (w := platform.os_window(c)) is not None
|
||||
]
|
||||
checks.check(
|
||||
"... the windows in view are inside the work area", all(f.inside(area) for f in frames)
|
||||
)
|
||||
checks.check(
|
||||
"... and not on each other",
|
||||
not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
|
||||
|
||||
def crash(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Turns a monocle on, which puts the other windows away, kills the daemon, and starts it
|
||||
again: nothing is left out of sight for the new daemon to find, and it manages every window.
|
||||
|
||||
`clients` are two windows or more, each in a container of its own. They are gathered on the
|
||||
first workspace, which is shown, first: a window another scenario left on a workspace that is
|
||||
not in view would be out of sight after the restart on a platform that keeps it there. The
|
||||
monocle is off at the end.
|
||||
"""
|
||||
target, other = clients[-1], clients[0]
|
||||
|
||||
def gather() -> None:
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
for client in clients:
|
||||
home = platform.state().workspace_of(client.title)
|
||||
if home not in (0, None):
|
||||
platform.komorebic("focus-workspace", str(home))
|
||||
platform.activate(client)
|
||||
platform.komorebic("move-to-workspace", "0")
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
platform.wait_for(
|
||||
lambda: all(platform.state().workspace_of(c.title) == 0 for c in clients), timeout=20
|
||||
)
|
||||
platform.wait_for(lambda: not any(platform.hidden(c) for c in clients), timeout=20)
|
||||
|
||||
gather()
|
||||
|
||||
def in_front() -> None:
|
||||
# a window that already has the focus gives the daemon no event: another one first
|
||||
platform.activate(other)
|
||||
platform.activate(target)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title))
|
||||
|
||||
def only_target_in_view() -> bool:
|
||||
return all(platform.hidden(c) for c in clients if c != target) and not platform.hidden(
|
||||
target
|
||||
)
|
||||
|
||||
in_front()
|
||||
platform.komorebic("toggle-monocle")
|
||||
checks.check(
|
||||
"with a monocle on, the other windows are out of sight",
|
||||
platform.wait_for(only_target_in_view, timeout=20),
|
||||
)
|
||||
platform.crash()
|
||||
checks.check(
|
||||
"the killed daemon no longer answers",
|
||||
platform.wait_for(lambda: platform.komorebic_status("state")[0] != 0, timeout=20),
|
||||
)
|
||||
|
||||
platform.start_komorebi()
|
||||
checks.check(
|
||||
"the next daemon manages every window",
|
||||
platform.wait_for(lambda: platform.state().managed() >= len(clients), timeout=30),
|
||||
)
|
||||
if not checks.check(
|
||||
"... and none is left out of sight",
|
||||
platform.wait_for(lambda: not any(platform.hidden(c) for c in clients), timeout=20),
|
||||
):
|
||||
print(describe(platform, clients))
|
||||
area = platform.work_area()
|
||||
frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
checks.check(
|
||||
"... inside the work area and not on each other",
|
||||
len(frames) == len(clients)
|
||||
and all(f.inside(area) for f in frames)
|
||||
and not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
|
||||
in_front()
|
||||
platform.komorebic("toggle-monocle")
|
||||
checks.check(
|
||||
"after a crash and a restart a monocle still puts the other windows away",
|
||||
platform.wait_for(only_target_in_view, timeout=20),
|
||||
)
|
||||
platform.komorebic("toggle-monocle")
|
||||
if not checks.check(
|
||||
"... and turned off, nothing is out of sight",
|
||||
platform.wait_for(lambda: not any(platform.hidden(c) for c in clients), timeout=20),
|
||||
):
|
||||
print(describe(platform, clients))
|
||||
@@ -0,0 +1,70 @@
|
||||
"""The screen is locked and unlocked: the lock screen is not tiled, nothing the daemon does while
|
||||
it is locked changes the layout, and the desktop is put right when it is unlocked."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
|
||||
|
||||
def _focus_agrees(platform: Platform, clients: list[Client]) -> bool:
|
||||
"""The window the daemon says has the focus is the one the operating system says does."""
|
||||
workspace = platform.state().workspace()
|
||||
if not workspace.containers:
|
||||
return False
|
||||
stack = workspace.containers[workspace.focused_container]
|
||||
top = stack[workspace.focused_windows[workspace.focused_container]].title
|
||||
return any(
|
||||
(w := platform.os_window(c)) is not None and w.focused and w.title == top for c in clients
|
||||
)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Locks the screen with `clients` tiled windows on the first workspace, moves the first
|
||||
while it is locked, unlocks, and checks the windows are in their tiles and the focus is
|
||||
agreed on.
|
||||
|
||||
The daemon must be running, with only `clients`, tiled. Needs `has("lock")`.
|
||||
"""
|
||||
checks.check(
|
||||
"the windows are tiled before the lock",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=30),
|
||||
)
|
||||
before = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
|
||||
platform.lock()
|
||||
checks.check(
|
||||
"while the screen is locked the daemon has the same windows: the lock screen is not one",
|
||||
platform.state().managed() == len(clients),
|
||||
)
|
||||
# a third of the way into the work area, and not on the tile the window is on
|
||||
area = platform.work_area()
|
||||
tile = platform.os_window(clients[0])
|
||||
assert tile is not None
|
||||
target = (area.x + area.w // 3, area.y + area.h // 3)
|
||||
if target == (tile.frame.x, tile.frame.y):
|
||||
target = (target[0] + 50, target[1] + 50)
|
||||
platform.move_window(clients[0], *target)
|
||||
moved = platform.wait_for(
|
||||
lambda: (
|
||||
(w := platform.os_window(clients[0])) is not None
|
||||
and (w.frame.x, w.frame.y) != (tile.frame.x, tile.frame.y)
|
||||
),
|
||||
timeout=10,
|
||||
)
|
||||
checks.check("the window was moved while the screen was locked", moved)
|
||||
after = [platform.os_window(c) for c in clients]
|
||||
checks.check(
|
||||
"the others did not move for it",
|
||||
all(w is not None and w.frame == f for w, f in zip(after[1:], before[1:], strict=True)),
|
||||
)
|
||||
|
||||
platform.unlock()
|
||||
checks.check(
|
||||
"once it is unlocked the window that was moved is in its tile again",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=30),
|
||||
)
|
||||
checks.check("... with the windows the daemon had", platform.state().managed() == len(clients))
|
||||
checks.check(
|
||||
"the daemon's idea of the focus is the operating system's",
|
||||
platform.wait_for(lambda: _focus_agrees(platform, clients), timeout=30),
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""A manage rule has a window managed that an ignore rule leaves alone, by title, class and exe."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import QUIET
|
||||
|
||||
|
||||
def _kinds(platform: Platform) -> list[tuple[str, str, dict[str, Any]]]:
|
||||
"""For each kind of rule: its name, the id of the rule, and what the window is opened with."""
|
||||
return [
|
||||
("title", "e2e-manage-title", {}),
|
||||
("class", "e2e-manage-class", {"app_id": "e2e-manage-class"}),
|
||||
("exe", platform.exe_id("e2e-manage-exe"), {"exe": "e2e-manage-exe"}),
|
||||
]
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""For each kind of rule, an ignore rule leaves a window alone and a manage rule for the same
|
||||
application then has the next one managed and tiled.
|
||||
|
||||
A window the daemon leaves alone does not make room for itself: the window that is tiled keeps
|
||||
its frame. The daemon must be running, with no window, and the rules are for names no other
|
||||
scenario uses, because `ignore-rule` drops a rule whose id an earlier rule has.
|
||||
"""
|
||||
base = platform.spawn("manage-base")
|
||||
platform.wait_for(lambda: platform.state().workspace_of(base.title) == 0, timeout=20)
|
||||
for kind, rule_id, how in _kinds(platform):
|
||||
title = rule_id if kind == "title" else f"manage-{kind}"
|
||||
platform.komorebic("ignore-rule", kind, rule_id)
|
||||
before = platform.os_window(base)
|
||||
ignored = platform.spawn(f"{title} ignored", **how)
|
||||
checks.check(
|
||||
f"a window an ignore rule by {kind} matches is not managed",
|
||||
not platform.wait_for(
|
||||
lambda c=ignored: platform.state().workspace_of(c.title) is not None,
|
||||
timeout=QUIET,
|
||||
),
|
||||
)
|
||||
after = platform.os_window(base)
|
||||
checks.check(
|
||||
f"... and the window that is tiled keeps its place ({kind})",
|
||||
before is not None and after is not None and before.frame == after.frame,
|
||||
)
|
||||
platform.close(ignored)
|
||||
platform.wait_for(lambda c=ignored: platform.os_window(c) is None, timeout=20)
|
||||
|
||||
platform.komorebic("manage-rule", kind, rule_id)
|
||||
managed: Client = platform.spawn(f"{title} managed", **how)
|
||||
checks.check(
|
||||
f"with a manage rule by {kind} too, a window it matches is managed",
|
||||
platform.wait_for(
|
||||
lambda c=managed: platform.state().workspace_of(c.title) == 0, timeout=20
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
f"... and tiled: {base.title} gives it room ({kind})",
|
||||
platform.wait_for(
|
||||
lambda b=before: (
|
||||
(a := platform.os_window(base)) is not None
|
||||
and b is not None
|
||||
and a.frame != b.frame
|
||||
),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
platform.close(managed)
|
||||
platform.wait_for(lambda c=managed: platform.state().workspace_of(c.title) is None)
|
||||
platform.close(base)
|
||||
platform.wait_for(lambda: platform.state().managed() == 0, timeout=20)
|
||||
@@ -0,0 +1,224 @@
|
||||
"""A maximized window has the work area, with the others left where they are behind it."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees, positions
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Toggles maximize on the last of `clients`, which are tiled windows of the first workspace,
|
||||
each in a container of its own, and toggles it off again."""
|
||||
target = clients[-1]
|
||||
others = [c for c in clients if c != target]
|
||||
platform.activate(target)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title))
|
||||
area = platform.work_area()
|
||||
behind = positions(platform, others)
|
||||
|
||||
def fills() -> bool:
|
||||
window = platform.os_window(target)
|
||||
return (
|
||||
window is not None
|
||||
and window.frame.w >= area.w - platform.tolerance
|
||||
and window.frame.h >= area.h - platform.tolerance
|
||||
)
|
||||
|
||||
def maximized() -> str | None:
|
||||
window = platform.state().workspace().maximized
|
||||
return window.title if window else None
|
||||
|
||||
platform.komorebic("toggle-maximize")
|
||||
checks.check(
|
||||
f"after 'toggle-maximize' {target.title} fills the work area",
|
||||
platform.wait_for(fills, timeout=20),
|
||||
)
|
||||
window = platform.os_window(target)
|
||||
checks.check(
|
||||
"... without going past the work area",
|
||||
window is not None and window.frame.inside(area),
|
||||
)
|
||||
checks.check(
|
||||
"... and the daemon has it as the maximized window",
|
||||
platform.wait_for(lambda: maximized() == target.title, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... the others stay where they were",
|
||||
positions(platform, others) == behind,
|
||||
)
|
||||
|
||||
platform.komorebic("toggle-maximize")
|
||||
checks.check(
|
||||
"toggled again, the daemon has no maximized window",
|
||||
platform.wait_for(lambda: maximized() is None, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and every window is tiled where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
|
||||
|
||||
# What is asked of the layout, which a maximized window is not in: none of it does anything. Not in
|
||||
# the list, because komorebi for Windows does not ignore them either: `toggle-float`, which floats
|
||||
# the maximized window (`user` ends with it), `stack left` and `stack right`, which stack the tiles
|
||||
# that are left, and `toggle-monocle`, which turns the monocle of the tiles that are left on while
|
||||
# the window stays maximized (`user` has it too).
|
||||
IGNORED = (
|
||||
"move left",
|
||||
"move right",
|
||||
"move up",
|
||||
"move down",
|
||||
"unstack",
|
||||
"cycle-move next",
|
||||
"promote",
|
||||
"resize-edge left increase",
|
||||
"send-to-workspace 1",
|
||||
"move-to-workspace 1",
|
||||
"toggle-lock",
|
||||
)
|
||||
|
||||
|
||||
def user(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""A window the user maximizes, not the command, is taken out of the layout like one that
|
||||
`toggle-maximize` maximized: the daemon has it as its maximized window, the others are left
|
||||
alone, what is asked of the layout does nothing, and it goes back to its tile when it is
|
||||
restored, by `toggle-maximize` or by the user.
|
||||
|
||||
`clients` are three tiled windows or more of the first workspace, each in a container of its
|
||||
own. The first workspace has the second one, so that `send-to-workspace 1` can name it.
|
||||
"""
|
||||
count = len(clients)
|
||||
target, other = clients[1], clients[-1]
|
||||
area = platform.work_area()
|
||||
tiles = positions(platform, clients)
|
||||
|
||||
def maximized() -> str | None:
|
||||
window = platform.state().workspace().maximized
|
||||
return window.title if window else None
|
||||
|
||||
def containers() -> int:
|
||||
return len(platform.state().workspace().containers)
|
||||
|
||||
def fills(client: Client) -> bool:
|
||||
window = platform.os_window(client)
|
||||
return (
|
||||
window is not None
|
||||
and window.frame.w >= area.w - 2 * platform.tolerance
|
||||
and window.frame.h >= area.h - 4 * platform.tolerance
|
||||
)
|
||||
|
||||
platform.user_maximize(target)
|
||||
checks.check(
|
||||
f"after the user maximizes {target.title} the daemon has it as its maximized window",
|
||||
platform.wait_for(lambda: maximized() == target.title, timeout=20),
|
||||
)
|
||||
checks.check("... it fills the work area", platform.wait_for(lambda: fills(target), timeout=10))
|
||||
checks.check(
|
||||
"... its tile is gone, and the daemon still has every window",
|
||||
containers() == count - 1 and platform.state().managed() == count,
|
||||
)
|
||||
|
||||
beside = positions(platform, [c for c in clients if c != target])
|
||||
for command in IGNORED:
|
||||
platform.komorebic_status(*command.split())
|
||||
platform.wait_for(lambda: False, timeout=1)
|
||||
checks.check(
|
||||
"what is asked of the layout does nothing: it is still maximized, and the others did not"
|
||||
" move",
|
||||
fills(target)
|
||||
and maximized() == target.title
|
||||
and positions(platform, [c for c in clients if c != target]) == beside,
|
||||
)
|
||||
workspace = platform.state().workspace()
|
||||
checks.check(
|
||||
"... and nothing floats or is in the monocle",
|
||||
containers() == count - 1 and workspace.floating == [] and workspace.monocle is None,
|
||||
)
|
||||
|
||||
# `toggle-monocle` is not ignored: the monocle of the tiles that are left comes on and goes off,
|
||||
# and the window stays maximized, as on komorebi for Windows
|
||||
platform.komorebic("toggle-monocle")
|
||||
checks.check(
|
||||
"toggle-monocle turns the monocle of the tiles that are left on, and the window stays"
|
||||
" maximized",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
platform.state().workspace().monocle is not None and maximized() == target.title
|
||||
),
|
||||
timeout=20,
|
||||
)
|
||||
and fills(target),
|
||||
)
|
||||
platform.komorebic("toggle-monocle")
|
||||
checks.check(
|
||||
"... and again turns it off, with the window still maximized",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
platform.state().workspace().monocle is None
|
||||
and maximized() == target.title
|
||||
and containers() == count - 1
|
||||
),
|
||||
timeout=20,
|
||||
)
|
||||
and fills(target),
|
||||
)
|
||||
|
||||
platform.komorebic("toggle-maximize")
|
||||
checks.check(
|
||||
f"toggle-maximize restores it: nothing is maximized and {target.title} is in its tile",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
maximized() is None
|
||||
and containers() == count
|
||||
and positions(platform, [target]) == {target.title: tiles[target.title]}
|
||||
),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
|
||||
platform.user_maximize(other)
|
||||
checks.check(
|
||||
f"the user maximizes {other.title} too",
|
||||
platform.wait_for(lambda: maximized() == other.title and containers() == count - 1),
|
||||
)
|
||||
platform.user_maximize(other, on=False)
|
||||
checks.check(
|
||||
f"restored by the user, {other.title} is back in its tile and nothing is maximized",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
maximized() is None
|
||||
and containers() == count
|
||||
and positions(platform, [other]) == {other.title: tiles[other.title]}
|
||||
),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
|
||||
# `toggle-float` is asked of the window in front, and that is the maximized one: it floats and
|
||||
# is not maximized any more, as on komorebi for Windows
|
||||
platform.user_maximize(target)
|
||||
platform.wait_for(lambda: maximized() == target.title, timeout=20)
|
||||
platform.komorebic("toggle-float")
|
||||
checks.check(
|
||||
f"toggle-float floats {target.title}, which the user maximized, and ends the maximize",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
maximized() is None
|
||||
and [w.title for w in platform.state().workspace().floating] == [target.title]
|
||||
and containers() == count - 1
|
||||
),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
platform.komorebic("toggle-float")
|
||||
checks.check(
|
||||
f"... and again puts {target.title} back in the layout",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
containers() == count
|
||||
and platform.state().workspace().floating == []
|
||||
and tiled(platform, clients)
|
||||
),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""A window that is minimized leaves its room to the others, and takes it back when restored."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Minimizes the first of `clients`, which are tiled windows of the first workspace in a
|
||||
container each, with more than two of them, and restores it."""
|
||||
target = clients[0]
|
||||
others = clients[1:]
|
||||
|
||||
def area(c: Client) -> int:
|
||||
window = platform.os_window(c)
|
||||
return window.frame.w * window.frame.h if window is not None else 0
|
||||
|
||||
before = sum(area(c) for c in others)
|
||||
platform.minimize(target)
|
||||
checks.check(
|
||||
f"with {target.title} minimized the others take more room between them",
|
||||
platform.wait_for(lambda: sum(area(c) for c in others) > before, timeout=20),
|
||||
)
|
||||
frames = [w.frame for c in others if (w := platform.os_window(c)) is not None]
|
||||
checks.check(
|
||||
"... inside the work area and not on each other",
|
||||
all(f.inside(platform.work_area()) for f in frames)
|
||||
and not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
|
||||
platform.activate(target)
|
||||
checks.check(
|
||||
f"restored, {target.title} and the others are tiled where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
checks.check(
|
||||
"... and not on each other",
|
||||
not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
@@ -0,0 +1,424 @@
|
||||
"""The commands that take the focus, a window or a workspace to another monitor."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import os_focused
|
||||
from komorebi_vm.core.snapshot import Snapshot
|
||||
|
||||
TITLES = ["monitors-1", "monitors-2", "monitors-3", "monitors-4"]
|
||||
SECOND = "monitors-second"
|
||||
"""The name of the second workspace of the second monitor, which `send-to-named-workspace` takes a
|
||||
window to."""
|
||||
SLACK = 2
|
||||
|
||||
Place = tuple[int, int]
|
||||
"""A monitor and a workspace of it, by the daemon's indexes."""
|
||||
|
||||
|
||||
def _display(platform: Platform, state: Snapshot, monitor: int) -> Rect:
|
||||
"""The display the daemon's monitor is, found by where its top left corner is: the daemon may
|
||||
number its monitors in another order than the displays are, left to right."""
|
||||
size = state.monitors[monitor].size
|
||||
return min(platform.displays(), key=lambda d: abs(d.x - size.x) + abs(d.y - size.y))
|
||||
|
||||
|
||||
def _monitor_of(platform: Platform, state: Snapshot, display: int) -> int:
|
||||
"""The daemon's index of the monitor that is `displays()[display]`."""
|
||||
wanted = platform.displays()[display]
|
||||
return min(
|
||||
range(len(state.monitors)),
|
||||
key=lambda m: (
|
||||
abs(state.monitors[m].size.x - wanted.x) + abs(state.monitors[m].size.y - wanted.y)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _places(state: Snapshot, titles: list[str]) -> dict[str, Place]:
|
||||
found = {}
|
||||
for m, monitor in enumerate(state.monitors):
|
||||
for w, workspace in enumerate(monitor.workspaces):
|
||||
for window in workspace.windows():
|
||||
if window.title in titles:
|
||||
found[window.title] = (m, w)
|
||||
return found
|
||||
|
||||
|
||||
def _view_problem(platform: Platform, titles: list[str]) -> str | None:
|
||||
"""What is wrong with the windows in view, from the operating system's side, or `None`.
|
||||
|
||||
On each monitor, the windows of the workspace it shows are inside its display and not on each
|
||||
other. The windows of the workspaces it does not show are not looked at: where a platform
|
||||
keeps them is its own business.
|
||||
"""
|
||||
state = platform.state()
|
||||
for m, monitor in enumerate(state.monitors):
|
||||
area = _display(platform, state, m)
|
||||
shown = monitor.workspaces[monitor.focused_workspace]
|
||||
frames = {}
|
||||
for window in shown.windows():
|
||||
if window.title not in titles:
|
||||
continue
|
||||
os_window = platform.os_window(Client(window.title))
|
||||
if os_window is None:
|
||||
return f"{window.title} has no window"
|
||||
if not os_window.frame.inside(area, SLACK):
|
||||
return f"{window.title} is not inside the display of monitor {m}"
|
||||
frames[window.title] = os_window.frame
|
||||
names = list(frames)
|
||||
for i, a in enumerate(names):
|
||||
for b in names[i + 1 :]:
|
||||
if frames[a].overlaps(frames[b]):
|
||||
return f"{a} and {b} are on each other"
|
||||
return None
|
||||
|
||||
|
||||
def _focus_problem(platform: Platform, monitor: int, title: str | None) -> str | None:
|
||||
"""What is wrong with the focus, or `None` when the daemon and the operating system agree
|
||||
that it is on `monitor`, on the window `title` (any window that monitor shows when `None`),
|
||||
and that window is inside that monitor's display."""
|
||||
state = platform.state()
|
||||
if state.focused_monitor != monitor:
|
||||
return f"the daemon has the focus on monitor {state.focused_monitor}"
|
||||
everyone = [
|
||||
Client(w.title) for m in state.monitors for ws in m.workspaces for w in ws.windows()
|
||||
]
|
||||
seen = os_focused(platform, everyone)
|
||||
wanted = title if title is not None else state.focused_title(monitor=monitor)
|
||||
if not seen:
|
||||
return "the operating system has no focused window"
|
||||
if seen != wanted:
|
||||
return f"the operating system has the focus on {seen} and the daemon on {wanted}"
|
||||
window = platform.os_window(Client(seen))
|
||||
if window is None or not window.frame.inside(_display(platform, state, monitor), SLACK):
|
||||
return f"{seen} has the focus but is not inside the display of monitor {monitor}"
|
||||
return None
|
||||
|
||||
|
||||
def _after(
|
||||
platform: Platform,
|
||||
checks: Checks,
|
||||
command: str,
|
||||
expected: dict[str, Place],
|
||||
monitor: int,
|
||||
title: str | None = None,
|
||||
shown: dict[int, int] | None = None,
|
||||
) -> None:
|
||||
"""Checks what `command` did: each of `expected` is on its monitor and workspace, in view
|
||||
where its monitor shows it, and the focus is on `monitor`."""
|
||||
titles = list(expected)
|
||||
failed_before = checks.failed
|
||||
checks.check(
|
||||
f"after '{command}' the daemon has every window on the monitor and the workspace that "
|
||||
"were asked for, and the others where they were",
|
||||
platform.wait_for(lambda: _places(platform.state(), titles) == expected, timeout=20),
|
||||
)
|
||||
for m, workspace in (shown or {}).items():
|
||||
checks.check(
|
||||
f"after '{command}' monitor {m} shows its workspace {workspace}",
|
||||
platform.wait_for(
|
||||
lambda m=m, w=workspace: platform.state().monitors[m].focused_workspace == w
|
||||
),
|
||||
)
|
||||
platform.wait_for(lambda: _view_problem(platform, titles) is None, timeout=20)
|
||||
problem = _view_problem(platform, titles)
|
||||
checks.check(
|
||||
f"after '{command}' the windows in view are tiled inside their own display: "
|
||||
f"{problem or 'ok'}",
|
||||
problem is None,
|
||||
)
|
||||
platform.wait_for(lambda: _focus_problem(platform, monitor, title) is None, timeout=20)
|
||||
problem = _focus_problem(platform, monitor, title)
|
||||
where = f"monitor {monitor}" + (f", on {title}" if title else "")
|
||||
checks.check(f"after '{command}' the focus is on {where}: {problem or 'ok'}", problem is None)
|
||||
if checks.failed > failed_before:
|
||||
print(_dump(platform))
|
||||
|
||||
|
||||
def _filled(platform: Platform, monitor: int) -> int:
|
||||
"""How many of a monitor's workspaces have a window."""
|
||||
return sum(1 for w in platform.state().monitors[monitor].workspaces if w.windows())
|
||||
|
||||
|
||||
def _shows_a_workspace(platform: Platform, monitor: int) -> bool:
|
||||
"""The monitor shows one of the workspaces it has."""
|
||||
state = platform.state().monitors[monitor]
|
||||
return 0 <= state.focused_workspace < len(state.workspaces)
|
||||
|
||||
|
||||
def _dump(platform: Platform) -> str:
|
||||
"""What the daemon has of each monitor: where it is, which workspace it shows, and the windows
|
||||
of each of its workspaces, for a failed check to print."""
|
||||
state = platform.state()
|
||||
lines = []
|
||||
for index, monitor in enumerate(state.monitors):
|
||||
shown = monitor.focused_workspace
|
||||
lines.append(
|
||||
f" monitor {index} at ({monitor.size.x}, {monitor.size.y}), shows workspace {shown}"
|
||||
+ (", focused" if index == state.focused_monitor else "")
|
||||
)
|
||||
for number, workspace in enumerate(monitor.workspaces):
|
||||
titles = [w.title for w in workspace.windows()]
|
||||
lines.append(f" workspace {number} {workspace.name or ''}: {titles}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _focus(platform: Platform, title: str, monitor: int) -> None:
|
||||
"""Gives a window the focus, and waits until the daemon has it."""
|
||||
platform.activate(Client(title))
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
platform.state().focused_monitor == monitor
|
||||
and platform.state().focused_title(monitor=monitor) == title
|
||||
),
|
||||
timeout=20,
|
||||
)
|
||||
|
||||
|
||||
def _plug(platform: Platform) -> bool:
|
||||
"""Plugs in a display if there is only one, and returns whether it did. Waits until the daemon
|
||||
has a monitor for each display."""
|
||||
plugged = len(platform.displays()) < 2
|
||||
if plugged:
|
||||
platform.add_display()
|
||||
platform.wait_for(
|
||||
lambda: len(platform.state().monitors) == len(platform.displays()), timeout=30
|
||||
)
|
||||
return plugged
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""Takes windows, workspaces and the focus from one monitor to the other with each command
|
||||
that does, and checks where each window is, and where the focus is, in the daemon's state and
|
||||
on the operating system's screen.
|
||||
|
||||
The daemon must be running. It may manage other windows, which stay out of the checks. The
|
||||
platform has one display or two; a second is plugged in when there is only one, and unplugged
|
||||
at the end, so that the machine has the number of displays it had. Both may have any size:
|
||||
each window is checked against the rectangle of the display its monitor is, not a constant.
|
||||
|
||||
Four windows are opened and then closed. The monitors are named by the daemon's index of
|
||||
them, `a` for the one on the first display and `b` for the other, and the commands count from
|
||||
0.
|
||||
|
||||
What the daemon does (`WindowManager::move_container_to_monitor` and the arms of
|
||||
`process_command`; the monitors and the workspaces count from 0), and so what is checked:
|
||||
|
||||
- `send-to-monitor` takes the focused window to the target monitor's shown workspace, which
|
||||
tiles it, and leaves the focus on the monitor it left; `move-to-monitor` does the same and
|
||||
the focus follows. The `cycle-` forms take the monitor after (or before) the focused one,
|
||||
counting round: with two monitors it is always the other.
|
||||
- `send-to-monitor-workspace` and `move-to-monitor-workspace` do the same to a workspace of
|
||||
the target monitor, which that monitor then shows (it is made if it was not there); the
|
||||
named forms look the name up on every monitor.
|
||||
- `focus-monitor` and `cycle-monitor` focus the monitor, and its focused window.
|
||||
`focus-monitor-workspace` shows a workspace of a monitor and focuses it.
|
||||
- `cycle-move-workspace-to-monitor` takes the focused workspace, with its windows, to the end
|
||||
of the other monitor's workspaces, shows it there and focuses the monitor. The monitor it
|
||||
left shows a workspace it has: the one before it (kfw), or, where the monitors share their
|
||||
workspaces and one with more makes the other have as many (KDE, whose virtual desktops
|
||||
are common to the outputs), the last of its empty ones. It is done here to a workspace the
|
||||
monitor can spare: done to the only workspace a monitor has, it leaves an empty one.
|
||||
|
||||
Surprising, and so not asserted: `focus-monitor` to a monitor with no window does not move the
|
||||
focus of the operating system, since there is no window to give it to, while the daemon's
|
||||
state has the monitor focused. For the same reason every window that is only sent here leaves
|
||||
another on its monitor. On a machine with one monitor the cycle forms name that monitor, and
|
||||
`cycle-send-to-monitor` puts the container at the back of its workspace. Nothing here unplugs
|
||||
a display to look at either. `focus-monitor-at-cursor` needs the pointer: see `at_cursor`.
|
||||
"""
|
||||
baseline = platform.state().managed()
|
||||
clients = [platform.spawn(title) for title in TITLES]
|
||||
names = list(TITLES)
|
||||
w1, w2, w3, w4 = names
|
||||
checks.check(
|
||||
"the daemon manages the four windows",
|
||||
platform.wait_for(lambda: platform.state().managed() == baseline + 4, timeout=30),
|
||||
)
|
||||
plugged = _plug(platform)
|
||||
state = platform.state()
|
||||
a, b = _monitor_of(platform, state, 0), _monitor_of(platform, state, 1)
|
||||
|
||||
# the windows that are not on the first display's first workspace are taken there
|
||||
platform.komorebic("focus-monitor", str(a))
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
for title in names:
|
||||
place = _places(platform.state(), names).get(title)
|
||||
if place is not None and place != (a, 0):
|
||||
_focus(platform, title, place[0])
|
||||
platform.komorebic("move-to-monitor-workspace", str(a), "0")
|
||||
platform.komorebic("ensure-named-workspaces", str(b), "monitors-first", SECOND)
|
||||
expected: dict[str, Place] = {title: (a, 0) for title in names}
|
||||
checks.check(
|
||||
"the four windows are on the first display's first workspace",
|
||||
platform.wait_for(lambda: _places(platform.state(), names) == expected, timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
"... in view and apart, on the first display",
|
||||
platform.wait_for(lambda: _view_problem(platform, names) is None, timeout=20),
|
||||
)
|
||||
|
||||
# send-to-monitor: the window goes, the focus stays
|
||||
_focus(platform, w4, a)
|
||||
platform.komorebic("send-to-monitor", str(b))
|
||||
expected[w4] = (b, 0)
|
||||
_after(platform, checks, f"send-to-monitor {b}", expected, a)
|
||||
|
||||
# the focus goes to a monitor and to the window it has
|
||||
platform.komorebic("focus-monitor", str(b))
|
||||
_after(platform, checks, f"focus-monitor {b}", expected, b, w4)
|
||||
platform.komorebic("focus-monitor", str(a))
|
||||
_after(platform, checks, f"focus-monitor {a}", expected, a)
|
||||
for way, monitor, title in (
|
||||
("next", b, w4),
|
||||
("next", a, None),
|
||||
("previous", b, w4),
|
||||
("previous", a, None),
|
||||
):
|
||||
platform.komorebic("cycle-monitor", way)
|
||||
_after(platform, checks, f"cycle-monitor {way}", expected, monitor, title)
|
||||
|
||||
# move-to-monitor and its cycle form: the window goes, the focus follows
|
||||
_focus(platform, w3, a)
|
||||
platform.komorebic("move-to-monitor", str(b))
|
||||
expected[w3] = (b, 0)
|
||||
_after(platform, checks, f"move-to-monitor {b}", expected, b, w3)
|
||||
platform.komorebic("cycle-move-to-monitor", "next")
|
||||
expected[w3] = (a, 0)
|
||||
_after(platform, checks, "cycle-move-to-monitor next", expected, a, w3)
|
||||
|
||||
# cycle-send-to-monitor: it goes, the focus stays
|
||||
platform.komorebic("cycle-send-to-monitor", "next")
|
||||
expected[w3] = (b, 0)
|
||||
_after(platform, checks, "cycle-send-to-monitor next", expected, a)
|
||||
|
||||
# a workspace of the target monitor: sent, it is shown there and the focus stays
|
||||
_focus(platform, w2, a)
|
||||
platform.komorebic("send-to-monitor-workspace", str(b), "1")
|
||||
expected[w2] = (b, 1)
|
||||
_after(platform, checks, f"send-to-monitor-workspace {b} 1", expected, a, shown={b: 1})
|
||||
|
||||
# focus-monitor-workspace shows a workspace of a monitor, and focuses it
|
||||
platform.komorebic("focus-monitor-workspace", str(b), "0")
|
||||
_after(platform, checks, f"focus-monitor-workspace {b} 0", expected, b, shown={b: 0})
|
||||
platform.komorebic("focus-monitor-workspace", str(b), "1")
|
||||
_after(platform, checks, f"focus-monitor-workspace {b} 1", expected, b, w2, shown={b: 1})
|
||||
platform.komorebic("focus-monitor-workspace", str(a), "0")
|
||||
_after(platform, checks, f"focus-monitor-workspace {a} 0", expected, a, shown={a: 0})
|
||||
|
||||
# move-to-monitor-workspace: the window goes, the target monitor shows its workspace, and the
|
||||
# focus follows
|
||||
platform.komorebic("focus-monitor-workspace", str(b), "1")
|
||||
platform.wait_for(lambda: _focus_problem(platform, b, w2) is None, timeout=20)
|
||||
platform.komorebic("move-to-monitor-workspace", str(a), "0")
|
||||
expected[w2] = (a, 0)
|
||||
_after(platform, checks, f"move-to-monitor-workspace {a} 0", expected, a, w2, shown={a: 0})
|
||||
_focus(platform, w1, a)
|
||||
platform.komorebic("move-to-monitor-workspace", str(b), "0")
|
||||
expected[w1] = (b, 0)
|
||||
_after(platform, checks, f"move-to-monitor-workspace {b} 0", expected, b, w1, shown={b: 0})
|
||||
|
||||
# sent back to the first monitor, the focus stays on the second
|
||||
platform.komorebic("send-to-monitor", str(a))
|
||||
expected[w1] = (a, 0)
|
||||
_after(platform, checks, f"send-to-monitor {a}", expected, b)
|
||||
|
||||
# a workspace by its name, which is on the second monitor: sent, it is shown, the focus stays
|
||||
_focus(platform, w1, a)
|
||||
platform.komorebic("send-to-named-workspace", SECOND)
|
||||
expected[w1] = (b, 1)
|
||||
_after(platform, checks, f"send-to-named-workspace {SECOND}", expected, a, shown={b: 1})
|
||||
_focus(platform, w2, a)
|
||||
platform.komorebic("move-to-named-workspace", SECOND)
|
||||
expected[w2] = (b, 1)
|
||||
_after(platform, checks, f"move-to-named-workspace {SECOND}", expected, b, w2, shown={b: 1})
|
||||
|
||||
# a workspace to the other monitor and back: the workspace with the two windows is the one
|
||||
# the second monitor can spare. A workspace that is moved goes to the end of the monitor's
|
||||
# (the counts are read now, not earlier: on a platform whose workspaces are shared by the
|
||||
# monitors, one monitor having more makes the other have as many, empty ones)
|
||||
filled_a = _filled(platform, a)
|
||||
at_a = len(platform.state().monitors[a].workspaces)
|
||||
platform.komorebic("cycle-move-workspace-to-monitor", "next")
|
||||
expected[w1] = expected[w2] = (a, at_a)
|
||||
_after(platform, checks, "cycle-move-workspace-to-monitor next", expected, a, shown={a: at_a})
|
||||
checks.check(
|
||||
"... the monitor it left still has a workspace to show",
|
||||
platform.wait_for(lambda: _shows_a_workspace(platform, b)),
|
||||
)
|
||||
at_b = len(platform.state().monitors[b].workspaces)
|
||||
platform.komorebic("cycle-move-workspace-to-monitor", "next")
|
||||
expected[w1] = expected[w2] = (b, at_b)
|
||||
_after(
|
||||
platform,
|
||||
checks,
|
||||
"cycle-move-workspace-to-monitor next, back",
|
||||
expected,
|
||||
b,
|
||||
shown={b: at_b},
|
||||
)
|
||||
checks.check(
|
||||
"... and the first monitor has the workspaces with windows it had",
|
||||
platform.wait_for(lambda: _filled(platform, a) == filled_a),
|
||||
)
|
||||
|
||||
for client in clients:
|
||||
platform.close(client)
|
||||
platform.wait_for(lambda: platform.state().managed() == baseline, timeout=30)
|
||||
platform.komorebic("focus-monitor", str(a))
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
if plugged:
|
||||
platform.remove_display()
|
||||
platform.wait_for(
|
||||
lambda: len(platform.state().monitors) == len(platform.displays()), timeout=30
|
||||
)
|
||||
checks.check(
|
||||
"the daemon has the windows it had before, and a monitor for each display",
|
||||
platform.state().managed() == baseline
|
||||
and len(platform.state().monitors) == len(platform.displays()),
|
||||
)
|
||||
|
||||
|
||||
def at_cursor(platform: Platform, checks: Checks) -> None:
|
||||
"""`focus-monitor-at-cursor` focuses the monitor the pointer is on.
|
||||
|
||||
Only where the platform has a pointer, which is in the pixels of the first display, so that
|
||||
the pointer can be put on the first monitor and not on the second: the focus is put on the
|
||||
second monitor with `focus-monitor`, the pointer on the first, and the command must bring the
|
||||
focus back to it.
|
||||
|
||||
The daemon's state has the focus on the monitor at once. Nothing is asserted of the focus of
|
||||
the operating system, because the code does only `focus_monitor` for this message and not the
|
||||
`update_focused_workspace` that the other focus commands do: the window that has the focus on
|
||||
the screen stays the one it was until the next focus event (it differs from the daemon's
|
||||
state in the meantime).
|
||||
"""
|
||||
if not platform.has("pointer"):
|
||||
checks.skip("focus-monitor-at-cursor", "the platform has no pointer")
|
||||
return
|
||||
plugged = _plug(platform)
|
||||
state = platform.state()
|
||||
a, b = _monitor_of(platform, state, 0), _monitor_of(platform, state, 1)
|
||||
first = platform.displays()[0]
|
||||
|
||||
platform.komorebic("focus-monitor", str(b))
|
||||
checks.check(
|
||||
"the focus is on the second monitor",
|
||||
platform.wait_for(lambda: platform.state().focused_monitor == b),
|
||||
)
|
||||
platform.pointer.move(first.x + first.w // 2, first.y + first.h // 2)
|
||||
platform.komorebic("focus-monitor-at-cursor")
|
||||
checks.check(
|
||||
"'focus-monitor-at-cursor' with the pointer on the first display focuses the first monitor",
|
||||
platform.wait_for(lambda: platform.state().focused_monitor == a),
|
||||
)
|
||||
platform.komorebic("focus-monitor-at-cursor")
|
||||
checks.check(
|
||||
"... and again, with the focus there already, it stays",
|
||||
platform.state().focused_monitor == a,
|
||||
)
|
||||
if plugged:
|
||||
platform.remove_display()
|
||||
platform.wait_for(
|
||||
lambda: len(platform.state().monitors) == len(platform.displays()), timeout=30
|
||||
)
|
||||
@@ -0,0 +1,122 @@
|
||||
"""In monocle one window has the work area and the others are put away; toggling gives it back."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees, os_focused, positions
|
||||
|
||||
# how much smaller than the work area a window in monocle may be: the padding of the layout
|
||||
PADDING = 120
|
||||
|
||||
|
||||
def _fills(platform: Platform, client: Client) -> bool:
|
||||
"""The window has the work area, up to the padding of the layout."""
|
||||
window = platform.os_window(client)
|
||||
area = platform.work_area()
|
||||
return (
|
||||
window is not None
|
||||
and window.frame.w >= area.w - PADDING
|
||||
and window.frame.h >= area.h - PADDING
|
||||
)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Toggles monocle on the focused one of `clients`, which are tiled windows of the first
|
||||
workspace, each in a container of its own, and toggles it off again."""
|
||||
last = clients[-1]
|
||||
platform.activate(last)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, last.title))
|
||||
before = positions(platform, clients)
|
||||
|
||||
def fills_the_work_area() -> bool:
|
||||
return _fills(platform, last)
|
||||
|
||||
platform.komorebic("toggle-monocle")
|
||||
checks.check(
|
||||
"in monocle the focused window fills the work area",
|
||||
platform.wait_for(fills_the_work_area, timeout=20),
|
||||
)
|
||||
window = platform.os_window(last)
|
||||
checks.check(
|
||||
"... without going past the work area",
|
||||
window is not None and window.frame.inside(platform.work_area()),
|
||||
)
|
||||
checks.check(
|
||||
"... the daemon's state has it as the monocle container",
|
||||
platform.wait_for(
|
||||
lambda: [w.title for w in platform.state().workspace().monocle or []] == [last.title]
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
"... and every other window is put away",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
all(platform.hidden(c) for c in clients if c != last) and not platform.hidden(last)
|
||||
)
|
||||
),
|
||||
)
|
||||
checks.check("... and it still has the focus", os_focused(platform, clients) == last.title)
|
||||
|
||||
platform.komorebic("toggle-monocle")
|
||||
checks.check(
|
||||
"toggling back puts every window in view again",
|
||||
platform.wait_for(lambda: not any(platform.hidden(c) for c in clients), timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... each on the tile it had",
|
||||
platform.wait_for(lambda: positions(platform, clients) == before, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and the state has no monocle container",
|
||||
platform.wait_for(lambda: platform.state().workspace().monocle is None),
|
||||
)
|
||||
|
||||
|
||||
def focus_behaviour(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""What `monocle-focus-behaviour` makes of focusing in a direction in a monocle: with `no-op`
|
||||
the window keeps the work area, and with `cycle` another window gets it.
|
||||
|
||||
`clients` are two or more tiled windows of the first workspace, each in a container of its
|
||||
own. The monocle is off and the behaviour is `no-op` at the end.
|
||||
"""
|
||||
first = clients[0]
|
||||
platform.activate(first)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, first.title))
|
||||
before = positions(platform, clients)
|
||||
|
||||
platform.komorebic("monocle-focus-behaviour", "no-op")
|
||||
platform.komorebic("toggle-monocle")
|
||||
platform.wait_for(lambda: _fills(platform, first), timeout=20)
|
||||
platform.komorebic("focus", "right")
|
||||
checks.check(
|
||||
"with the no-op behaviour, focusing in a direction leaves the window the work area",
|
||||
not platform.wait_for(lambda: os_focused(platform, clients) != first.title, timeout=3)
|
||||
and _fills(platform, first),
|
||||
)
|
||||
|
||||
platform.komorebic("monocle-focus-behaviour", "cycle")
|
||||
platform.komorebic("focus", "right")
|
||||
|
||||
def another_has_it() -> bool:
|
||||
title = os_focused(platform, clients)
|
||||
return title not in ("", first.title) and _fills(platform, Client(title))
|
||||
|
||||
checks.check(
|
||||
"with the cycle behaviour, focusing in a direction gives another window the work area",
|
||||
platform.wait_for(another_has_it, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and the daemon's state has that window as the monocle container",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
[w.title for w in platform.state().workspace().monocle or []]
|
||||
== [os_focused(platform, clients)]
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
platform.komorebic("toggle-monocle")
|
||||
platform.komorebic("monocle-focus-behaviour", "no-op")
|
||||
checks.check(
|
||||
"the windows are tiled again, each on the tile it had",
|
||||
platform.wait_for(lambda: positions(platform, clients) == before, timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Windows swap tiles on `move` and `cycle-move`, and the focus stays with the window."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees, positions
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Moves the first of `clients`, which are tiled windows of the first workspace, each in a
|
||||
container of its own, to the tile on its right and back."""
|
||||
first = clients[0].title
|
||||
platform.activate(clients[0])
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, first))
|
||||
before = positions(platform, clients)
|
||||
|
||||
def swapped_with_another() -> bool:
|
||||
now = positions(platform, clients)
|
||||
return any(
|
||||
title != first
|
||||
and now[first] == before[title]
|
||||
and now[title] == before[first]
|
||||
and now[first] != before[first]
|
||||
for title in before
|
||||
)
|
||||
|
||||
platform.komorebic("move", "right")
|
||||
checks.check(
|
||||
f"after 'move right' {first} and a neighbor have swapped tiles",
|
||||
platform.wait_for(swapped_with_another, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
f"... and {first} keeps the focus",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, first)),
|
||||
)
|
||||
others = {t: p for t, p in positions(platform, clients).items() if t != first}
|
||||
checks.check(
|
||||
"... and the other windows are on tiles of their own",
|
||||
len(set(others.values()) | {positions(platform, clients)[first]}) == len(clients),
|
||||
)
|
||||
|
||||
platform.komorebic("cycle-move", "previous")
|
||||
checks.check(
|
||||
"'cycle-move previous' puts every window back",
|
||||
platform.wait_for(lambda: positions(platform, clients) == before, timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,84 @@
|
||||
"""The padding of a workspace and of its containers moves the windows in from the edges and from
|
||||
each other."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
|
||||
|
||||
def run(
|
||||
platform: Platform,
|
||||
checks: Checks,
|
||||
clients: list[Client],
|
||||
configured: tuple[int, int] = (0, 0),
|
||||
) -> None:
|
||||
"""Raises the workspace padding and then the container padding of the first workspace, which
|
||||
has `clients` tiled in a container each, and sets them back to what the daemon says they were
|
||||
(`configured` is the workspace and container padding for a daemon that does not say)."""
|
||||
state = platform.state().workspace()
|
||||
workspace = configured[0] if state.workspace_padding is None else state.workspace_padding
|
||||
container = configured[1] if state.container_padding is None else state.container_padding
|
||||
print(f" padding of the workspace {workspace}, of its containers {container}")
|
||||
area = platform.work_area()
|
||||
# how much room the windows must lose or regain, in square pixels: a small part of the work
|
||||
# area, for the display is not the same size on every platform
|
||||
unit = area.w * area.h // 400
|
||||
|
||||
def frames() -> list[Rect]:
|
||||
return [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
|
||||
def margin() -> int:
|
||||
"""How far the windows are from the left edge of the work area: the padding of the
|
||||
workspace and that of the first container."""
|
||||
return min(f.x for f in frames()) - area.x
|
||||
|
||||
def room() -> int:
|
||||
return sum(f.w * f.h for f in frames())
|
||||
|
||||
def near(value: int, want: int) -> bool:
|
||||
return abs(value - want) <= 10
|
||||
|
||||
# what the windows are measured against is what these commands give, not what the config said
|
||||
platform.komorebic("focused-workspace-padding", str(workspace))
|
||||
platform.komorebic("focused-workspace-container-padding", str(container))
|
||||
checks.check(
|
||||
"the windows are inside the work area, tiled where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
start = margin()
|
||||
print(f" margin {start} with the padding as it is")
|
||||
base = room()
|
||||
|
||||
platform.komorebic("focused-workspace-padding", str(workspace + 40))
|
||||
checks.check(
|
||||
"a workspace padding 40 px more moves the windows 40 px in from the edge",
|
||||
platform.wait_for(lambda: near(margin(), start + 40), timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and they stay where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
|
||||
platform.komorebic("focused-workspace-padding", str(workspace))
|
||||
platform.komorebic("focused-workspace-container-padding", str(container + 30))
|
||||
checks.check(
|
||||
"a container padding 30 px more leaves the windows less room",
|
||||
platform.wait_for(lambda: room() < base - unit, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and none is over another, or outside the work area",
|
||||
all(f.inside(area) for f in frames())
|
||||
and not any(a.overlaps(b) for i, a in enumerate(frames()) for b in frames()[i + 1 :]),
|
||||
)
|
||||
|
||||
platform.komorebic("focused-workspace-container-padding", str(container))
|
||||
checks.check(
|
||||
"with the padding as it was, the windows are as far from the edge as they were",
|
||||
platform.wait_for(lambda: near(margin(), start), timeout=20),
|
||||
)
|
||||
print(f" margin {margin()} (was {start}), room {room()} (was {base})")
|
||||
checks.check(
|
||||
"... and have the room they had",
|
||||
platform.wait_for(lambda: abs(room() - base) <= unit // 2, timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""A paused daemon leaves new windows alone, and an unpaused one takes them up."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
from komorebi_vm.core.scenarios.support import QUIET
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Pauses the daemon, opens a window, unpauses it and opens another, with `clients` tiled
|
||||
on the first workspace. Closes both."""
|
||||
managed = platform.state().managed()
|
||||
|
||||
platform.komorebic("toggle-pause")
|
||||
paused = platform.spawn("while-paused")
|
||||
checks.check(
|
||||
"a window that opens while the daemon is paused is not managed",
|
||||
not platform.wait_for(lambda: platform.state().managed() > managed, timeout=QUIET),
|
||||
)
|
||||
|
||||
platform.komorebic("toggle-pause")
|
||||
after = platform.spawn("after-the-pause")
|
||||
checks.check(
|
||||
"after 'toggle-pause' again the next window is managed",
|
||||
platform.wait_for(lambda: platform.state().managed() > managed, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and every window it had is still tiled where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, [*clients, after]), timeout=20),
|
||||
)
|
||||
|
||||
platform.close(paused)
|
||||
platform.close(after)
|
||||
checks.check(
|
||||
"the two windows are closed and the daemon has the ones it had",
|
||||
platform.wait_for(lambda: platform.state().managed() == managed, timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Where in the layout a window that opens goes, as the placement rules of the config say."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
|
||||
CASES: list[tuple[str, Any, list[str], list[str], dict[str, str]]] = [
|
||||
# (what it says, the placement rules, the titles in the order they open, the order they end in,
|
||||
# the class of the windows that have one, by title)
|
||||
("no rules: after the one in focus", None, ["a", "b", "c"], ["a", "b", "c"], {}),
|
||||
("every window to the primary tile", "Primary", ["a", "b", "c"], ["c", "b", "a"], {}),
|
||||
("by the number of the place, counted from 1", 2, ["a", "b", "c"], ["a", "c", "b"], {}),
|
||||
("text that is a number is the same place", "2", ["a", "b", "c"], ["a", "c", "b"], {}),
|
||||
(
|
||||
"by the title: first, last, and after the one in focus",
|
||||
{
|
||||
"Primary": {"kind": "Title", "id": "special", "matching_strategy": "Equals"},
|
||||
"Last": [{"kind": "Title", "id": "chat", "matching_strategy": "Contains"}],
|
||||
},
|
||||
["one", "two", "special", "a chat room", "four"],
|
||||
["special", "one", "two", "a chat room", "four"],
|
||||
{},
|
||||
),
|
||||
(
|
||||
"by the class: first, and by the title: last",
|
||||
{
|
||||
"Primary": {"kind": "Class", "id": "special-class", "matching_strategy": "Equals"},
|
||||
"Last": [{"kind": "Title", "id": "chat", "matching_strategy": "Contains"}],
|
||||
},
|
||||
["one", "two", "three", "a chat room", "four"],
|
||||
["three", "one", "two", "a chat room", "four"],
|
||||
{"three": "special-class"},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def _config(rules: Any) -> dict[str, Any]:
|
||||
workspace: dict[str, Any] = {"name": "a", "layout": "BSP"}
|
||||
if rules is not None:
|
||||
workspace["initial_window_placement_rules"] = rules
|
||||
return {
|
||||
"default_workspace_padding": 10,
|
||||
"default_container_padding": 10,
|
||||
"monitors": [{"workspaces": [workspace]}],
|
||||
}
|
||||
|
||||
|
||||
def _order(platform: Platform) -> list[str]:
|
||||
return [titles[0] for titles in platform.state().containers()]
|
||||
|
||||
|
||||
def _settled(platform: Platform, title: str, count: int) -> None:
|
||||
"""Waits until `count` windows are managed and the last one to open has the focus."""
|
||||
platform.wait_for(lambda: platform.state().managed() == count, timeout=20)
|
||||
platform.wait_for(lambda: platform.state().focused_title() == title, timeout=20)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, known_failures: dict[str, str] | None = None) -> None:
|
||||
"""Starts the daemon with each case's rules, opens its windows one after the other, and checks
|
||||
the order they are in. A window that has a class in the case is opened with it, for a rule that
|
||||
matches by its class.
|
||||
|
||||
`known_failures` maps the description of a case to why a port is known to fail it, whether
|
||||
its daemon does not start with the rules or puts the windows in another order. The case is
|
||||
then recorded as a known failure, and the others run on.
|
||||
|
||||
Nothing else may be open: the daemon takes up every window in view, and the order would
|
||||
count it. The windows of a case are closed before the next one. A window is opened only after
|
||||
the one before is managed and has the focus, because "after the one in focus" depends on it.
|
||||
"""
|
||||
known = known_failures or {}
|
||||
for description, rules, titles, want, classes in CASES:
|
||||
reason = known.get(description)
|
||||
try:
|
||||
platform.restart_with(_config(rules))
|
||||
except Exception as error:
|
||||
if reason is None:
|
||||
raise
|
||||
checks.known_failure(description, False, f"{reason}; it did not start: {error}")
|
||||
continue
|
||||
clients: list[Client] = []
|
||||
for title in titles:
|
||||
clients.append(platform.spawn(title, app_id=classes.get(title)))
|
||||
_settled(platform, title, len(clients))
|
||||
got = _order(platform)
|
||||
message = f"{description}: {', '.join(want)} ({got})"
|
||||
if reason is None:
|
||||
checks.check(message, got == want)
|
||||
else:
|
||||
checks.known_failure(message, got == want, reason)
|
||||
for client in clients:
|
||||
platform.close(client)
|
||||
platform.wait_for(lambda: platform.state().managed() == 0, timeout=20)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""A promoted window takes the first tile, and keeps the focus."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Promotes the last of `clients`, which are tiled windows of the first workspace in a
|
||||
container each, with more than one of them."""
|
||||
target = clients[-1]
|
||||
platform.activate(target)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title))
|
||||
first = platform.state().workspace().latest_layout[0]
|
||||
|
||||
platform.komorebic("promote")
|
||||
checks.check(
|
||||
f"after 'promote' the daemon has {target.title} in the first container",
|
||||
platform.wait_for(lambda: platform.state().containers()[0] == [target.title], timeout=20),
|
||||
)
|
||||
|
||||
def on_the_first_tile() -> bool:
|
||||
window = platform.os_window(target)
|
||||
return window is not None and (window.frame.x, window.frame.y) == (first.x, first.y)
|
||||
|
||||
checks.check("... and the window is on the first tile", platform.wait_for(on_the_first_tile))
|
||||
checks.check(
|
||||
"... every window is where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and the window still has the focus",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title), timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""`komorebic query` answers with what the daemon's state says, and the resize a workspace has can
|
||||
be saved and loaded."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Platform
|
||||
from komorebi_vm.core.scenarios.commands import NOT_A_COMMAND
|
||||
from komorebi_vm.core.snapshot import Snapshot
|
||||
|
||||
# the layouts that `change-layout` takes by a name that is the lower case of the one a query gives
|
||||
BY_NAME = {"BSP": "bsp", "Columns": "columns", "Rows": "rows"}
|
||||
|
||||
|
||||
def _expected(state: Snapshot) -> dict[str, str]:
|
||||
"""What each query that depends on the focus should answer, from the daemon's own state."""
|
||||
monitor = state.monitors[state.focused_monitor]
|
||||
workspace = state.workspace(monitor=state.focused_monitor)
|
||||
expected = {
|
||||
"focused-monitor-index": str(state.focused_monitor),
|
||||
"focused-workspace-index": str(monitor.focused_workspace),
|
||||
"focused-workspace-name": workspace.name or str(monitor.focused_workspace),
|
||||
"focused-workspace-layout": workspace.layout,
|
||||
}
|
||||
if workspace.containers:
|
||||
container = workspace.containers[workspace.focused_container]
|
||||
expected["focused-container-index"] = str(workspace.focused_container)
|
||||
expected["focused-window-index"] = str(
|
||||
workspace.focused_windows[workspace.focused_container]
|
||||
)
|
||||
expected["focused-container-kind"] = "Stack" if len(container) > 1 else "Single"
|
||||
return expected
|
||||
|
||||
|
||||
def _query(platform: Platform, checks: Checks, state: Snapshot) -> None:
|
||||
for query, want in _expected(state).items():
|
||||
status, out = platform.komorebic_status("query", query)
|
||||
if status != 0 and NOT_A_COMMAND in out:
|
||||
checks.skip(f"query {query}", "the port has no such query")
|
||||
continue
|
||||
checks.check(f"query {query} answers {want!r}", status == 0 and out.strip() == want)
|
||||
|
||||
|
||||
def _layout(platform: Platform) -> list[Rect]:
|
||||
return platform.state().workspace().latest_layout
|
||||
|
||||
|
||||
def _round_trip(
|
||||
platform: Platform, checks: Checks, name: str, save: tuple[str, ...], load: tuple[str, ...]
|
||||
) -> None:
|
||||
"""Saves the resize, resizes the focused container, loads it, and checks that the layout is
|
||||
the one it was."""
|
||||
before = _layout(platform)
|
||||
status, _ = platform.komorebic_status(*save)
|
||||
platform.komorebic("resize-axis", "horizontal", "increase")
|
||||
resized = platform.wait_for(lambda: _layout(platform) != before, timeout=10)
|
||||
status_load, _ = platform.komorebic_status(*load)
|
||||
checks.check(
|
||||
f"{name}: a resize is undone by loading what was saved",
|
||||
status == 0
|
||||
and resized
|
||||
and status_load == 0
|
||||
and platform.wait_for(lambda: _layout(platform) == before, timeout=10),
|
||||
)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""Asks every query and checks the answer against the daemon's state, after changing the
|
||||
focus and the layout so that the answers are not the ones of a fresh daemon, and saves and
|
||||
loads the resize both ways.
|
||||
|
||||
The focused workspace has two containers or more. The focus and the layout are as they were at
|
||||
the end.
|
||||
"""
|
||||
_query(platform, checks, platform.state())
|
||||
status, out = platform.komorebic_status("query", "version")
|
||||
checks.check("query version answers", status == 0 and out.strip() != "")
|
||||
|
||||
workspace = platform.state().workspace()
|
||||
if len(workspace.containers) < 2:
|
||||
checks.skip("queries after a change, and the saved resize", "fewer than two containers")
|
||||
return
|
||||
|
||||
platform.komorebic("cycle-focus", "next")
|
||||
platform.wait_for(
|
||||
lambda: platform.state().workspace().focused_container != workspace.focused_container,
|
||||
timeout=10,
|
||||
)
|
||||
_query(platform, checks, platform.state())
|
||||
platform.komorebic("cycle-focus", "previous")
|
||||
|
||||
if workspace.layout in BY_NAME:
|
||||
other = "columns" if workspace.layout == "Rows" else "rows"
|
||||
platform.komorebic("change-layout", other)
|
||||
platform.wait_for(lambda: platform.state().workspace().layout != workspace.layout)
|
||||
_query(platform, checks, platform.state())
|
||||
platform.komorebic("change-layout", BY_NAME[workspace.layout])
|
||||
platform.wait_for(lambda: platform.state().workspace().layout == workspace.layout)
|
||||
|
||||
_round_trip(
|
||||
platform, checks, "quick-save-resize", ("quick-save-resize",), ("quick-load-resize",)
|
||||
)
|
||||
path = platform.temp_path("e2e-resize.json")
|
||||
_round_trip(platform, checks, "save-resize", ("save-resize", path), ("load-resize", path))
|
||||
@@ -0,0 +1,319 @@
|
||||
"""Dragging the edge two tiles share resizes both, and nothing else moves."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
|
||||
# how far outside a window's frame its resize border is pressed by a platform whose border is the
|
||||
# gap between two tiles (`outside_grab`)
|
||||
OFFSET = 4
|
||||
# the shortest drag, in pixels: far enough to be a drag on any display
|
||||
MIN_DRAG = 60
|
||||
# how far the edge may end up from where the pointer put it, in pixels
|
||||
SLACK = 6
|
||||
|
||||
|
||||
def _side_by_side(layout: list[Rect]) -> tuple[int, int] | None:
|
||||
"""The first pair of tiles of which the second is to the right of the first, with the same top,
|
||||
so that the edge between them is one the pointer can take."""
|
||||
for i, a in enumerate(layout):
|
||||
for j, b in enumerate(layout):
|
||||
if i != j and b.x >= a.x + a.w and a.y < b.y + b.h and b.y < a.y + a.h:
|
||||
return i, j
|
||||
return None
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client], dx: int | None = None) -> None:
|
||||
"""Drags the edge between a tile and the one to its right by `dx` pixels (a thirty-second of
|
||||
the work area's width, and at least `MIN_DRAG`, when it is not given), and checks that the
|
||||
two tiles moved the edge by what the pointer moved, that every other edge stayed, and that the
|
||||
windows still tile on the work area, as the operating system has them.
|
||||
|
||||
`clients` are the tiled windows of the first workspace, each in a container of its own.
|
||||
"""
|
||||
if not platform.has("pointer"):
|
||||
print(" skipped: this platform has no pointer")
|
||||
return
|
||||
if dx is None:
|
||||
dx = max(MIN_DRAG, platform.work_area().w // 32)
|
||||
state = platform.state()
|
||||
workspace = state.workspace()
|
||||
layout = workspace.latest_layout
|
||||
pair = _side_by_side(layout)
|
||||
checks.check("two tiles share a vertical edge", pair is not None)
|
||||
if pair is None:
|
||||
return
|
||||
left, right = pair
|
||||
titles = [c[0].title for c in workspace.containers]
|
||||
window = platform.os_window(Client(titles[left]))
|
||||
assert window is not None
|
||||
before = list(layout)
|
||||
grab = platform.resize_grab(window.frame, "right")
|
||||
|
||||
platform.pointer.drag(grab, (grab[0] + dx, grab[1]))
|
||||
|
||||
def edge_moved() -> bool:
|
||||
now = platform.state().workspace().latest_layout
|
||||
return len(now) == len(before) and abs(now[left].w - (before[left].w + dx)) <= SLACK
|
||||
|
||||
checks.check(
|
||||
f"the tile on the left of the edge is {dx} pixels wider",
|
||||
platform.wait_for(edge_moved, timeout=20),
|
||||
)
|
||||
now = platform.state().workspace().latest_layout
|
||||
print(f" tiles before {before}, after {now}")
|
||||
edge = before[left].x + before[left].w
|
||||
# the tiles on either side of the edge: every one that ends at it, and every one that starts
|
||||
# at or after it with the edge as its own left side (a column of tiles shares it)
|
||||
ends = [i for i, t in enumerate(before) if t.x + t.w == edge]
|
||||
starts = [i for i, t in enumerate(before) if t.x == before[right].x]
|
||||
checks.check(
|
||||
f"the tiles that end at the edge are {dx} pixels wider and start where they did",
|
||||
all(abs(now[i].w - (before[i].w + dx)) <= SLACK and now[i].x == before[i].x for i in ends),
|
||||
)
|
||||
checks.check(
|
||||
f"the tiles that start after the edge start {dx} pixels later and end where they did",
|
||||
all(
|
||||
abs(now[i].x - (before[i].x + dx)) <= SLACK
|
||||
and abs((now[i].x + now[i].w) - (before[i].x + before[i].w)) <= SLACK
|
||||
for i in starts
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
"no tile moved up or down or changed its height",
|
||||
all((now[i].y, now[i].h) == (before[i].y, before[i].h) for i in range(len(before))),
|
||||
)
|
||||
checks.check(
|
||||
"every tile that does not touch the edge is where it was",
|
||||
all(now[i] == before[i] for i in range(len(before)) if i not in ends and i not in starts),
|
||||
)
|
||||
area = platform.work_area()
|
||||
frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
checks.check("the windows are inside the work area", all(f.inside(area) for f in frames))
|
||||
checks.check(
|
||||
"and do not overlap",
|
||||
not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
|
||||
|
||||
GRABS = {
|
||||
"left": "L",
|
||||
"right": "R",
|
||||
"top": "T",
|
||||
"bottom": "B",
|
||||
"topleft": "LT",
|
||||
"topright": "RT",
|
||||
"bottomleft": "LB",
|
||||
"bottomright": "RB",
|
||||
}
|
||||
# how far apart two windows may be for one to be the neighbour of the other: twice the gap
|
||||
NEIGHBOUR = 80
|
||||
|
||||
|
||||
def _edges(r: Rect) -> dict[str, int]:
|
||||
return {"L": r.x, "T": r.y, "R": r.x + r.w, "B": r.y + r.h}
|
||||
|
||||
|
||||
def _tiles(platform: Platform) -> dict[str, Rect]:
|
||||
"""The daemon's layout: the tile it gave each container, by the title of its window in view."""
|
||||
workspace = platform.state().workspace()
|
||||
return {
|
||||
c[min(workspace.focused_windows[i], len(c) - 1)].title: workspace.latest_layout[i]
|
||||
for i, c in enumerate(workspace.containers)
|
||||
if i < len(workspace.latest_layout) and c
|
||||
}
|
||||
|
||||
|
||||
def _frames(platform: Platform, clients: list[Client]) -> dict[str, Rect]:
|
||||
return {c.title: w.frame for c in clients if (w := platform.os_window(c)) is not None}
|
||||
|
||||
|
||||
def _settled(platform: Platform, clients: list[Client]) -> dict[str, Rect]:
|
||||
"""The frames once they have stopped changing."""
|
||||
last = _frames(platform, clients)
|
||||
for _ in range(20):
|
||||
platform.wait_for(lambda: False, timeout=0.5)
|
||||
now = _frames(platform, clients)
|
||||
if now == last:
|
||||
return now
|
||||
last = now
|
||||
return last
|
||||
|
||||
|
||||
def outside_grab(r: Rect, grab: str) -> tuple[int, int]:
|
||||
"""Where the pointer is pressed for a grab by a platform whose resize border is the gap outside
|
||||
the frame, `OFFSET` pixels from it: what KDE has on every side."""
|
||||
left, right, top, bottom = r.x - OFFSET, r.x + r.w + OFFSET, r.y - OFFSET, r.y + r.h + OFFSET
|
||||
cx, cy = r.x + r.w // 2, r.y + r.h // 2
|
||||
return {
|
||||
"left": (left, cy),
|
||||
"right": (right, cy),
|
||||
"top": (cx, top),
|
||||
"bottom": (cx, bottom),
|
||||
"topleft": (left, top),
|
||||
"topright": (right, top),
|
||||
"bottomleft": (left, bottom),
|
||||
"bottomright": (right, bottom),
|
||||
}[grab]
|
||||
|
||||
|
||||
def _has_neighbour(edge: str, name: str, frames: dict[str, Rect]) -> bool:
|
||||
"""Is there another window within a gap's reach on that side of this one, overlapping it."""
|
||||
me = frames[name]
|
||||
for other, o in frames.items():
|
||||
if other == name:
|
||||
continue
|
||||
vertical = o.y < me.y + me.h and me.y < o.y + o.h
|
||||
horizontal = o.x < me.x + me.w and me.x < o.x + o.w
|
||||
if edge == "L" and vertical and 0 <= me.x - (o.x + o.w) <= NEIGHBOUR:
|
||||
return True
|
||||
if edge == "R" and vertical and 0 <= o.x - (me.x + me.w) <= NEIGHBOUR:
|
||||
return True
|
||||
if edge == "T" and horizontal and 0 <= me.y - (o.y + o.h) <= NEIGHBOUR:
|
||||
return True
|
||||
if edge == "B" and horizontal and 0 <= o.y - (me.y + me.h) <= NEIGHBOUR:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _stacked(layout: list[Rect]) -> tuple[int, int] | None:
|
||||
"""The first pair of tiles of which the second is below the first and overlaps it sideways."""
|
||||
for i, a in enumerate(layout):
|
||||
for j, b in enumerate(layout):
|
||||
if i != j and b.y >= a.y + a.h and a.x < b.x + b.w and b.x < a.x + a.w:
|
||||
return i, j
|
||||
return None
|
||||
|
||||
|
||||
def _cases(
|
||||
platform: Platform, layout: list[Rect], titles: list[str], area: Rect
|
||||
) -> list[tuple[str, str, int, int]]:
|
||||
"""Drags to make, as (window, grab, dx, dy), from the layout: both sides of an edge that two
|
||||
tiles share, a horizontal one, a corner next to two neighbours, and an edge of the screen."""
|
||||
cases: list[tuple[str, str, int, int]] = []
|
||||
if (pair := _side_by_side(layout)) is not None:
|
||||
a, b = pair
|
||||
cases += [
|
||||
(titles[a], "right", 72, 0),
|
||||
(titles[a], "right", -72, 0),
|
||||
(titles[b], "left", -72, 0),
|
||||
(titles[b], "left", -240, 0),
|
||||
]
|
||||
if (stack := _stacked(layout)) is not None:
|
||||
a, b = stack
|
||||
cases += [(titles[a], "bottom", 0, 72), (titles[b], "top", 0, -72)]
|
||||
for k, tile in enumerate(layout):
|
||||
right_of = any(
|
||||
i != k and tile.x >= t.x + t.w and t.y < tile.y + tile.h and tile.y < t.y + t.h
|
||||
for i, t in enumerate(layout)
|
||||
)
|
||||
above = any(
|
||||
i != k and t.y >= tile.y + tile.h and tile.x < t.x + t.w and t.x < tile.x + tile.w
|
||||
for i, t in enumerate(layout)
|
||||
)
|
||||
if right_of and above:
|
||||
cases.append((titles[k], "bottomleft", -72, 72))
|
||||
break
|
||||
first = min(range(len(layout)), key=lambda i: layout[i].x)
|
||||
if platform.resize_grab(layout[first], "left")[0] >= area.x:
|
||||
cases.append((titles[first], "left", -72, 0))
|
||||
return cases
|
||||
|
||||
|
||||
def _problems(
|
||||
platform: Platform,
|
||||
clients: list[Client],
|
||||
case: tuple[str, str, int, int],
|
||||
) -> list[str]:
|
||||
"""Makes a drag and says what is wrong with the outcome: the frame the user sees, the layout,
|
||||
the edges that were not dragged and the windows."""
|
||||
name, grab, dx, dy = case
|
||||
area = platform.work_area()
|
||||
platform.komorebic("retile")
|
||||
# the frames follow the tiles a moment later, and a press on a frame that is still on its way
|
||||
# lands on the window and not on its border (a drop on another tile, a swap)
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=10)
|
||||
before = _settled(platform, clients)
|
||||
tiles_before = _tiles(platform)
|
||||
|
||||
px, py = platform.resize_grab(before[name], grab)
|
||||
end = (max(area.x, px + dx), max(area.y, py + dy))
|
||||
platform.pointer.drag((px, py), end)
|
||||
platform.wait_for(lambda: _tiles(platform) != tiles_before, timeout=3)
|
||||
# a neighbour's frame follows its tile a moment later; it is read when it has
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=10)
|
||||
after = _settled(platform, clients)
|
||||
tiles_after = _tiles(platform)
|
||||
|
||||
held = GRABS[grab]
|
||||
want = {"L": dx, "R": dx, "T": dy, "B": dy}
|
||||
problems = []
|
||||
moved = {e: _edges(after[name])[e] - _edges(before[name])[e] for e in "LTRB"}
|
||||
for e in "LTRB":
|
||||
if e in held and _has_neighbour(e, name, before):
|
||||
if abs(moved[e] - want[e]) > platform.tolerance:
|
||||
problems.append(f"frame {e} moved {moved[e]}, the pointer moved {want[e]}")
|
||||
elif abs(moved[e]) > platform.tolerance:
|
||||
why = "was not dragged" if e not in held else "has no neighbour"
|
||||
problems.append(f"frame {e} moved {moved[e]} but {why}")
|
||||
|
||||
tile_moved = {e: _edges(tiles_after[name])[e] - _edges(tiles_before[name])[e] for e in "LTRB"}
|
||||
for e in "LTRB":
|
||||
if e in held and _has_neighbour(e, name, before):
|
||||
if abs(tile_moved[e] - want[e]) > 2:
|
||||
problems.append(f"tile {e} moved {tile_moved[e]}, the pointer moved {want[e]}")
|
||||
elif abs(tile_moved[e]) > 1:
|
||||
why = "was not dragged" if e not in held else "has no neighbour"
|
||||
problems.append(f"tile {e} moved {tile_moved[e]} but {why}")
|
||||
|
||||
# nothing else moves, but with a dragged edge: they share it
|
||||
follows = [m for m in tile_moved.values() if abs(m) > 1]
|
||||
for other in tiles_after:
|
||||
if other == name:
|
||||
continue
|
||||
for e in "LTRB":
|
||||
m = _edges(tiles_after[other])[e] - _edges(tiles_before[other])[e]
|
||||
if abs(m) > 1 and not any(abs(m - f) <= 2 for f in follows):
|
||||
problems.append(f"{other} tile {e} moved {m}: not with the dragged edge")
|
||||
|
||||
names = list(after)
|
||||
for i, a in enumerate(names):
|
||||
if not after[a].inside(area):
|
||||
problems.append(f"{a} {after[a]} is outside the work area")
|
||||
problems += [f"{a} and {b} overlap" for b in names[i + 1 :] if after[a].overlaps(after[b])]
|
||||
print(f" {case}: frame {before[name]} -> {after[name]}, tile edges {tile_moved}")
|
||||
return problems
|
||||
|
||||
|
||||
def edge_cases(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Drags both sides of an edge two tiles share, a horizontal edge, a corner and an edge of the
|
||||
screen, and checks, against the layout the daemon computed (`latest_layout`) and the frames the
|
||||
operating system has:
|
||||
|
||||
- a dragged edge that has a neighbour moves by what the pointer moved, and the neighbour's
|
||||
edge moves with it
|
||||
- a dragged edge with no neighbour does not move, and the window is put back
|
||||
- edges that were not dragged do not move, and every edge of another tile stays or moves with
|
||||
a dragged one
|
||||
- the windows still tile: inside the work area, not on each other
|
||||
|
||||
`clients` are the tiled windows of the first workspace, each in a container of its own, in a
|
||||
layout that has them side by side or stacked. The cases are made from the layout, so that
|
||||
a layout with no stacked tiles has no horizontal case. The layout is retiled before each one.
|
||||
"""
|
||||
if not platform.has("pointer"):
|
||||
print(" skipped: this platform has no pointer")
|
||||
return
|
||||
platform.komorebic("retile")
|
||||
platform.wait_for(lambda: len(_tiles(platform)) == len(clients), timeout=20)
|
||||
tiles = _tiles(platform)
|
||||
titles = list(tiles)
|
||||
layout = [tiles[t] for t in titles]
|
||||
for case in _cases(platform, layout, titles, platform.work_area()):
|
||||
problems = _problems(platform, clients, case)
|
||||
name, grab, dx, dy = case
|
||||
checks.check(
|
||||
f"{name}:{grab}:{dx},{dy}: " + ("as expected" if not problems else "; ".join(problems)),
|
||||
not problems,
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""The resize commands move an edge of the focused window, with no pointer."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees, layout_rect
|
||||
|
||||
# how much wider the window must get for the command to have done something
|
||||
MIN_STEP = 10
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Resizes the first of `clients`, which are tiled windows of the first workspace, with
|
||||
`resize-axis horizontal increase` and `decrease`."""
|
||||
target = clients[0]
|
||||
platform.activate(target)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title))
|
||||
|
||||
def width() -> int:
|
||||
window = platform.os_window(target)
|
||||
return window.frame.w if window is not None else 0
|
||||
|
||||
def clear() -> bool:
|
||||
frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
area = platform.work_area()
|
||||
return all(f.inside(area) for f in frames) and not any(
|
||||
a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]
|
||||
)
|
||||
|
||||
def asked() -> int:
|
||||
"""The width the daemon's layout gives the window, which no client rounds."""
|
||||
rect = layout_rect(platform, target)
|
||||
return rect.w if rect is not None else 0
|
||||
|
||||
before, asked_before = width(), asked()
|
||||
platform.komorebic("resize-axis", "horizontal", "increase")
|
||||
checks.check(
|
||||
f"after 'resize-axis horizontal increase' the layout gives {target.title} more width",
|
||||
platform.wait_for(lambda: asked() >= asked_before + MIN_STEP, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and the window is wider",
|
||||
platform.wait_for(lambda: width() >= before + MIN_STEP, timeout=20),
|
||||
)
|
||||
print(f" width {before} -> {width()}, asked {asked_before} -> {asked()}")
|
||||
checks.check(
|
||||
"... where the layout says, whatever the client rounds its size to",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
checks.check("... and every window is inside the work area, none over another", clear())
|
||||
|
||||
platform.komorebic("resize-axis", "horizontal", "decrease")
|
||||
checks.check(
|
||||
"after 'decrease' the layout gives it the width it had",
|
||||
platform.wait_for(lambda: asked() == asked_before, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and the window has the width it had, to what the client rounds to",
|
||||
platform.wait_for(lambda: abs(width() - before) <= platform.tolerance, timeout=20),
|
||||
)
|
||||
checks.check("... and every window is inside the work area, none over another", clear())
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Rules that match a window by its title decide where it goes, or that it is left alone."""
|
||||
|
||||
import json
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Platform
|
||||
from komorebi_vm.core.scenarios.support import QUIET
|
||||
|
||||
|
||||
def _on(platform: Platform, title: str) -> int | None:
|
||||
return platform.state().workspace_of(title)
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""Gives the daemon four rules, opens a window that each matches, and checks where it went.
|
||||
|
||||
An initial rule sends a window when it opens, so that moving it back leaves it there. A rule
|
||||
that is not initial sends it again whenever the rules are enforced, and at the next event (a
|
||||
window that opens); the same by the name of a workspace. An ignore rule leaves it alone. Once
|
||||
the rules are cleared the daemon's global state has none. The daemon must be running, on the
|
||||
first workspace, which is the one in view, with no window.
|
||||
"""
|
||||
|
||||
platform.komorebic("ensure-workspaces", "0", "3")
|
||||
platform.komorebic("initial-workspace-rule", "title", "sent-once", "0", "1")
|
||||
platform.komorebic("workspace-rule", "title", "sent-always", "0", "2")
|
||||
platform.komorebic("ignore-rule", "title", "left-alone")
|
||||
|
||||
once = platform.spawn("sent-once")
|
||||
checks.check(
|
||||
"a window an initial rule matches goes to the workspace the rule names",
|
||||
platform.wait_for(lambda: _on(platform, "sent-once") == 1, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... where it is put away while another workspace is in view",
|
||||
platform.wait_for(lambda: platform.hidden(once)),
|
||||
)
|
||||
platform.komorebic("focus-workspace", "1")
|
||||
checks.check(
|
||||
"... and in view when its workspace is",
|
||||
platform.wait_for(lambda: not platform.hidden(once)),
|
||||
)
|
||||
platform.komorebic("move-to-workspace", "0")
|
||||
checks.check(
|
||||
"moved back to the first workspace, it is there",
|
||||
platform.wait_for(lambda: _on(platform, "sent-once") == 0, timeout=20),
|
||||
)
|
||||
# an initial rule is for the window that opens; `enforce-workspace-rules` applies it again
|
||||
# on purpose, so what is checked is that the daemon does not send the window back on its own
|
||||
checks.check(
|
||||
"... and an initial rule does not send it there again on its own",
|
||||
not platform.wait_for(lambda: _on(platform, "sent-once") != 0, timeout=QUIET),
|
||||
)
|
||||
|
||||
always = platform.spawn("sent-always")
|
||||
checks.check(
|
||||
"a window a rule that is not initial matches goes to its workspace too",
|
||||
platform.wait_for(lambda: _on(platform, "sent-always") == 2, timeout=20),
|
||||
)
|
||||
platform.komorebic("focus-workspace", "2")
|
||||
platform.komorebic("move-to-workspace", "0")
|
||||
platform.wait_for(lambda: _on(platform, "sent-always") == 0, timeout=20)
|
||||
platform.komorebic("enforce-workspace-rules")
|
||||
checks.check(
|
||||
"... and when the rules are enforced it is sent back",
|
||||
platform.wait_for(lambda: _on(platform, "sent-always") == 2, timeout=20),
|
||||
)
|
||||
|
||||
managed = platform.state().managed()
|
||||
ignored = platform.spawn("left-alone")
|
||||
checks.check(
|
||||
"a window an ignore rule matches is not managed",
|
||||
platform.wait_for(lambda: platform.os_window(ignored) is not None)
|
||||
and platform.wait_for(lambda: platform.state().managed() == managed)
|
||||
and _on(platform, "left-alone") is None,
|
||||
)
|
||||
|
||||
platform.komorebic("workspace-name", "0", "2", "chat")
|
||||
platform.komorebic("named-workspace-rule", "title", "sent-named", "chat")
|
||||
named = platform.spawn("sent-named")
|
||||
checks.check(
|
||||
"a window a rule by the name of a workspace matches goes to that workspace",
|
||||
platform.wait_for(lambda: _on(platform, "sent-named") == 2, timeout=20),
|
||||
)
|
||||
platform.komorebic("focus-workspace", "2")
|
||||
# the always rule's window is on that workspace too: the focus is on the one to move
|
||||
platform.activate(named)
|
||||
platform.komorebic("move-to-workspace", "0")
|
||||
platform.wait_for(lambda: _on(platform, "sent-named") == 0, timeout=20)
|
||||
# a window that opens is an event, and a rule that is not initial is applied at every event
|
||||
poke = platform.spawn("sent-poke")
|
||||
checks.check(
|
||||
"a rule that is not initial sends the window back at the next event, a window that opens",
|
||||
platform.wait_for(lambda: _on(platform, "sent-named") == 2, timeout=30),
|
||||
)
|
||||
|
||||
platform.komorebic("clear-all-workspace-rules")
|
||||
state = json.loads(platform.komorebic("global-state"))
|
||||
if "workspace_rules" in state:
|
||||
checks.check(
|
||||
"once the rules are cleared the daemon's global state has none",
|
||||
not state["workspace_rules"],
|
||||
)
|
||||
else:
|
||||
checks.skip("the global state has no rule", "the port's global state has no such field")
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
# the title is the window's name here, so the first window of it goes before the next opens
|
||||
platform.close(once)
|
||||
platform.wait_for(lambda: platform.os_window(once) is None, timeout=20)
|
||||
later = platform.spawn("sent-once")
|
||||
checks.check(
|
||||
"once the rules are cleared, a window they matched stays on the workspace in view",
|
||||
platform.wait_for(lambda: _on(platform, "sent-once") == 0, timeout=20)
|
||||
and not platform.wait_for(lambda: _on(platform, "sent-once") != 0, timeout=QUIET),
|
||||
)
|
||||
for client in (always, ignored, later, named, poke):
|
||||
platform.close(client)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Rules that match a window by its class (the app id on Wayland, the window class on Windows)
|
||||
decide where it goes, or that it is left alone."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Platform
|
||||
from komorebi_vm.core.scenarios.support import QUIET
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""Gives the daemon a workspace rule and an ignore rule by class, opens a window of each
|
||||
class and one of neither, and checks where each went.
|
||||
|
||||
The daemon must be running, on the first workspace, which is the one in view, with no window,
|
||||
and with workspaces 0 and 1. The rules are cleared afterwards.
|
||||
"""
|
||||
platform.komorebic("ensure-workspaces", "0", "2")
|
||||
platform.komorebic("workspace-rule", "class", "e2e-sent", "0", "1")
|
||||
platform.komorebic("ignore-rule", "class", "e2e-left")
|
||||
|
||||
sent = platform.spawn("by-class-sent", app_id="e2e-sent")
|
||||
checks.check(
|
||||
"a window a class rule matches goes to the workspace the rule names",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(sent.title) == 1, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... where it is put away while another workspace is in view",
|
||||
platform.wait_for(lambda: platform.hidden(sent)),
|
||||
)
|
||||
|
||||
left = platform.spawn("by-class-left", app_id="e2e-left")
|
||||
checks.check(
|
||||
"a window an ignore rule by class matches is not managed",
|
||||
not platform.wait_for(
|
||||
lambda: platform.state().workspace_of(left.title) is not None, timeout=QUIET
|
||||
),
|
||||
)
|
||||
|
||||
plain = platform.spawn("by-class-plain", app_id="e2e-other")
|
||||
checks.check(
|
||||
"a window of another class stays on the first workspace",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(plain.title) == 0, timeout=20),
|
||||
)
|
||||
|
||||
platform.komorebic("clear-all-workspace-rules")
|
||||
for client in (sent, left, plain):
|
||||
platform.close(client)
|
||||
checks.check(
|
||||
"the three windows are closed",
|
||||
platform.wait_for(lambda: platform.state().managed() == 0, timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Rules that match a window by the program that opened it decide where it goes, or that it is
|
||||
left alone. The program is `e2e-exe-sent.exe` on Windows and `e2e-exe-sent` on Linux, and the
|
||||
rule's id is `platform.exe_id(program)`.
|
||||
|
||||
The names differ from those of `rules_class`: `ignore-rule` drops a rule whose id an earlier
|
||||
rule has, whatever its kind."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Platform
|
||||
from komorebi_vm.core.scenarios.support import QUIET
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""Gives the daemon a workspace rule and an ignore rule by exe, opens a window of each
|
||||
program and one of neither, and checks where each went.
|
||||
|
||||
The daemon must be running, on the first workspace, which is the one in view, with no window,
|
||||
and with workspaces 0 and 1. The rules are cleared afterwards.
|
||||
"""
|
||||
platform.komorebic("ensure-workspaces", "0", "2")
|
||||
platform.komorebic("workspace-rule", "exe", platform.exe_id("e2e-exe-sent"), "0", "1")
|
||||
platform.komorebic("ignore-rule", "exe", platform.exe_id("e2e-exe-left"))
|
||||
|
||||
sent = platform.spawn("by-exe-sent", exe="e2e-exe-sent")
|
||||
checks.check(
|
||||
"a window an exe rule matches goes to the workspace the rule names",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(sent.title) == 1, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... where it is put away while another workspace is in view",
|
||||
platform.wait_for(lambda: platform.hidden(sent)),
|
||||
)
|
||||
|
||||
left = platform.spawn("by-exe-left", exe="e2e-exe-left")
|
||||
checks.check(
|
||||
"a window an ignore rule by exe matches is not managed",
|
||||
not platform.wait_for(
|
||||
lambda: platform.state().workspace_of(left.title) is not None, timeout=QUIET
|
||||
),
|
||||
)
|
||||
|
||||
plain = platform.spawn("by-exe-plain", exe="e2e-exe-other")
|
||||
checks.check(
|
||||
"a window of another program stays on the first workspace",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(plain.title) == 0, timeout=20),
|
||||
)
|
||||
|
||||
platform.komorebic("clear-all-workspace-rules")
|
||||
for client in (sent, left, plain):
|
||||
platform.close(client)
|
||||
checks.check(
|
||||
"the three windows are closed",
|
||||
platform.wait_for(lambda: platform.state().managed() == 0, timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,247 @@
|
||||
"""In the scrolling layout the window that has the focus is in view, wherever the others are.
|
||||
|
||||
`run` checks that on the windows a suite has open. `columns` opens five windows of its own in two
|
||||
columns, and checks where the strip puts the ones that are out of view, that it scrolls with the
|
||||
focus and with `pan`, and the commands of the columns (`consume`, `expel`, `toggle-column-stack`,
|
||||
`scrolling-layout-full-width`). Both ports lay the strip out with the same model.
|
||||
"""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
from komorebi_vm.core.scenarios.monitors import _plug
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees
|
||||
|
||||
STRIP = 5
|
||||
|
||||
# how many pixels of a window that rests at an edge of the work area are on the screen: 5 of them by
|
||||
# design, and the paddings, what the compositor rounds and a terminal's grid of cells are the rest
|
||||
PARKED_AT_MOST = 30
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Changes the layout of the first workspace, which has `clients` tiled in a container each,
|
||||
to scrolling, gives each of them the focus in turn, and changes it back to bsp."""
|
||||
area = platform.work_area()
|
||||
|
||||
def in_view(client: Client) -> bool:
|
||||
window = platform.os_window(client)
|
||||
return window is not None and window.frame.inside(area)
|
||||
|
||||
platform.komorebic("change-layout", "scrolling")
|
||||
for client in clients:
|
||||
platform.activate(client)
|
||||
checks.check(
|
||||
f"in scrolling, {client.title} has the focus and is inside the work area",
|
||||
platform.wait_for(
|
||||
lambda c=client: focus_agrees(platform, clients, c.title) and in_view(c),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
|
||||
platform.komorebic("change-layout", "bsp")
|
||||
checks.check(
|
||||
"back in bsp every window is where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
|
||||
|
||||
def columns(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Five windows in two columns on a workspace with none: the last two are in view and the
|
||||
others are scrolled out, where the system keeps them; focusing to the far left and back, and
|
||||
`pan`, scroll the strip; then the commands of a column of several windows. The layout is bsp
|
||||
again and the windows are closed at the end."""
|
||||
area = platform.work_area()
|
||||
left, right = area.x, area.x + area.w
|
||||
tol = platform.tolerance
|
||||
titles = [f"strip{i}" for i in range(1, STRIP + 1)]
|
||||
|
||||
def frame(i: int) -> Rect:
|
||||
window = platform.os_window(Client(titles[i - 1]))
|
||||
return window.frame if window is not None else Rect(0, 0, 0, 0)
|
||||
|
||||
def in_view(i: int) -> bool:
|
||||
r = frame(i)
|
||||
return r.x >= left - tol and r.x + r.w <= right + tol
|
||||
|
||||
def out_of_view(i: int) -> bool:
|
||||
r = frame(i)
|
||||
return r.x >= right - PARKED_AT_MOST or r.x + r.w <= left + PARKED_AT_MOST
|
||||
|
||||
def agree(i: int) -> bool:
|
||||
return focus_agrees(platform, [Client(t) for t in titles], titles[i - 1])
|
||||
|
||||
def wait(predicate, timeout: float = 10) -> bool: # noqa: ANN001
|
||||
return platform.wait_for(predicate, timeout=timeout)
|
||||
|
||||
platform.komorebic("change-layout", "scrolling")
|
||||
platform.komorebic("scrolling-layout-columns", "2")
|
||||
opened = [platform.spawn(t) for t in titles]
|
||||
checks.check(
|
||||
"the daemon manages all five", wait(lambda: platform.state().managed() >= STRIP, 20)
|
||||
)
|
||||
checks.check(
|
||||
"the focused (last) window is in view, and so is the one before it",
|
||||
wait(lambda: in_view(5) and in_view(4), 20),
|
||||
)
|
||||
checks.check(
|
||||
"the first three are scrolled out of view",
|
||||
wait(lambda: all(out_of_view(i) for i in (1, 2, 3)), 20),
|
||||
)
|
||||
# the window rests with its right edge a few pixels inside the work area, as wide as the one
|
||||
# in view: nothing pulled it further onto the screen, and nothing was resized. A terminal draws
|
||||
# in whole cells, so its frame can be a cell narrower than the tile it was rested by
|
||||
checks.check(
|
||||
"the first window rests at the left edge, a few pixels of it on the screen or a cell short"
|
||||
f" of them (right edge at {frame(1).x + frame(1).w}), not pulled back",
|
||||
wait(lambda: left - tol < frame(1).x + frame(1).w <= left + PARKED_AT_MOST),
|
||||
)
|
||||
checks.check(
|
||||
f"... and it kept its width ({frame(1).w} against {frame(4).w})",
|
||||
wait(lambda: abs(frame(1).w - frame(4).w) <= tol),
|
||||
)
|
||||
checks.check("the system and the daemon agree on the focus", wait(lambda: agree(5)))
|
||||
|
||||
for _ in range(STRIP - 1):
|
||||
platform.komorebic("focus", "left")
|
||||
checks.check(
|
||||
"focusing to the far left scrolls the strip back: the first is in view",
|
||||
wait(lambda: in_view(1) and agree(1)),
|
||||
)
|
||||
checks.check("... and the last is past the right edge", wait(lambda: out_of_view(5)))
|
||||
for _ in range(STRIP - 1):
|
||||
platform.komorebic("focus", "right")
|
||||
checks.check(
|
||||
"walking right again reaches the last, in view", wait(lambda: agree(5) and in_view(5))
|
||||
)
|
||||
|
||||
# the view moves a column without the focus moving first
|
||||
platform.komorebic("pan", "left")
|
||||
checks.check(
|
||||
"panning left brings the third into view and puts the last out of it",
|
||||
wait(lambda: in_view(3) and out_of_view(5)),
|
||||
)
|
||||
checks.check(
|
||||
"... and the focus goes to the nearest column in view, the fourth", wait(lambda: agree(4))
|
||||
)
|
||||
platform.komorebic("pan", "right")
|
||||
checks.check("panning right puts the last in view again", wait(lambda: in_view(5)))
|
||||
|
||||
# a column of two windows: the fourth is put at the top of the column of the fifth
|
||||
platform.komorebic("focus", "right")
|
||||
wait(lambda: agree(5))
|
||||
platform.komorebic("consume", "left")
|
||||
checks.check(
|
||||
"consuming left puts the fourth above the fifth, in one column",
|
||||
wait(lambda: abs(frame(4).x - frame(5).x) <= tol and frame(4).y < frame(5).y),
|
||||
)
|
||||
checks.check(
|
||||
"... each with a share of the height of the column",
|
||||
wait(lambda: frame(4).h < area.h * 0.6 and frame(5).h < area.h * 0.6),
|
||||
)
|
||||
checks.check("... and the focus stays on the fifth", wait(lambda: agree(5)))
|
||||
|
||||
pair = [Client(titles[3]), Client(titles[4])]
|
||||
platform.komorebic("toggle-column-stack")
|
||||
checks.check(
|
||||
"stacking the column shows one window of the two",
|
||||
wait(lambda: sum(platform.hidden(c) for c in pair) == 1),
|
||||
)
|
||||
platform.komorebic("toggle-column-stack")
|
||||
checks.check(
|
||||
"spreading it out shows both again, one above the other",
|
||||
wait(lambda: not any(platform.hidden(c) for c in pair) and frame(4).y < frame(5).y),
|
||||
)
|
||||
|
||||
platform.komorebic("expel")
|
||||
checks.check(
|
||||
"expelling puts the focused window in a column of its own on the right",
|
||||
wait(lambda: frame(5).x > frame(4).x + tol and abs(frame(5).y - frame(4).y) <= tol),
|
||||
)
|
||||
|
||||
platform.komorebic("scrolling-layout-full-width")
|
||||
checks.check(
|
||||
"the full width makes the focused column as wide as the work area",
|
||||
wait(lambda: frame(5).w >= area.w - 60 and in_view(5)),
|
||||
)
|
||||
platform.komorebic("scrolling-layout-full-width")
|
||||
checks.check(
|
||||
"and again puts it back to the width it had",
|
||||
wait(lambda: abs(frame(5).w - frame(4).w) <= tol),
|
||||
)
|
||||
|
||||
platform.komorebic("change-layout", "bsp")
|
||||
for client in opened:
|
||||
platform.close(client)
|
||||
|
||||
|
||||
def two_monitors(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""A strip with a display next to it leaks no window onto it.
|
||||
|
||||
Five windows in two columns on the first monitor, with a second display on its right. A window
|
||||
shows on whichever display it overlaps, so one that rests past the right edge, or overhangs it,
|
||||
would be seen on the neighbour: the daemon hides it, or makes it narrower, instead. Scrolling
|
||||
with `focus` and `pan`, both ways, leaves no shown window on the second display, and no window
|
||||
that is shown past the right edge of the first. The layout is bsp again, the windows are
|
||||
closed, and the display is unplugged if the scenario plugged it, at the end."""
|
||||
plugged = _plug(platform)
|
||||
first, second = platform.displays()[0], platform.displays()[1]
|
||||
tol = platform.tolerance
|
||||
titles = [f"leak{i}" for i in range(1, STRIP + 1)]
|
||||
mine = [Client(t) for t in titles]
|
||||
|
||||
def leaks() -> list[str]:
|
||||
"""The windows that are shown and have a part on the second display, or reach past the
|
||||
right edge of the first."""
|
||||
out = []
|
||||
for client in mine:
|
||||
window = platform.os_window(client)
|
||||
if window is None or platform.hidden(client):
|
||||
continue
|
||||
frame = window.frame
|
||||
if frame.overlaps(second) or frame.x + frame.w > first.x + first.w + tol:
|
||||
out.append(f"{client.title} {frame}")
|
||||
return out
|
||||
|
||||
def settled(title: str) -> bool:
|
||||
return focus_agrees(platform, mine, title)
|
||||
|
||||
def quiet(step: str, title: str) -> None:
|
||||
platform.wait_for(lambda: settled(title), timeout=10)
|
||||
platform.wait_for(lambda: not leaks(), timeout=5)
|
||||
checks.check(f"{step}: no window is shown on the second display", not leaks())
|
||||
if leaks():
|
||||
print(" leaked: " + "; ".join(leaks()))
|
||||
|
||||
platform.komorebic("focus-monitor", "0")
|
||||
platform.komorebic("change-layout", "scrolling")
|
||||
platform.komorebic("scrolling-layout-columns", "2")
|
||||
opened = [platform.spawn(t) for t in titles]
|
||||
checks.check(
|
||||
"the daemon manages all five",
|
||||
platform.wait_for(lambda: platform.state().managed() >= STRIP, timeout=20),
|
||||
)
|
||||
quiet("with the strip at its right end", titles[-1])
|
||||
for i in range(STRIP - 1, 0, -1):
|
||||
platform.komorebic("focus", "left")
|
||||
quiet(f"focusing left to {titles[i - 1]}", titles[i - 1])
|
||||
for i in range(1, STRIP):
|
||||
platform.komorebic("focus", "right")
|
||||
quiet(f"focusing right to {titles[i]}", titles[i])
|
||||
platform.komorebic("pan", "left")
|
||||
platform.wait_for(lambda: not leaks(), timeout=10)
|
||||
checks.check("panning left: no window is shown on the second display", not leaks())
|
||||
platform.komorebic("pan", "right")
|
||||
platform.wait_for(lambda: not leaks(), timeout=10)
|
||||
checks.check("panning right: no window is shown on the second display", not leaks())
|
||||
|
||||
platform.komorebic("change-layout", "bsp")
|
||||
for client in opened:
|
||||
platform.close(client)
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
if plugged:
|
||||
platform.remove_display()
|
||||
platform.wait_for(
|
||||
lambda: len(platform.state().monitors) == len(platform.displays()), timeout=30
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""A stack shows one window and puts the others away, and the window in view has the focus."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees, os_focused
|
||||
|
||||
|
||||
def _sizes(platform: Platform) -> list[int]:
|
||||
return sorted(len(titles) for titles in platform.state().containers())
|
||||
|
||||
|
||||
def _away(platform: Platform, clients: list[Client]) -> list[str]:
|
||||
return [c.title for c in clients if platform.hidden(c)]
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Stacks the focused one of `clients` onto its neighbor, cycles the stack and takes it apart.
|
||||
|
||||
`clients` are three tiled windows of the first workspace, each in a container of its own,
|
||||
and the last of them has the focus.
|
||||
"""
|
||||
last = clients[-1]
|
||||
platform.activate(last)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, last.title))
|
||||
checks.check("there are three tiles", _sizes(platform) == [1, 1, 1])
|
||||
checks.check("nothing is put away yet", _away(platform, clients) == [])
|
||||
|
||||
platform.komorebic("stack", "left")
|
||||
checks.check(
|
||||
"two containers, one of them a stack of two",
|
||||
platform.wait_for(lambda: _sizes(platform) == [1, 2]),
|
||||
)
|
||||
checks.check(
|
||||
"exactly one window is put away",
|
||||
platform.wait_for(lambda: len(_away(platform, clients)) == 1),
|
||||
)
|
||||
shown = os_focused(platform, clients)
|
||||
checks.check(
|
||||
"the window in view has the focus", shown != "" and shown not in _away(platform, clients)
|
||||
)
|
||||
checks.check(
|
||||
"... and the daemon's state agrees",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, shown)),
|
||||
)
|
||||
frame = platform.os_window(Client(shown))
|
||||
|
||||
platform.komorebic("cycle-stack", "next")
|
||||
checks.check(
|
||||
"after 'cycle-stack next' the other window of the stack is in view and the first is away",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
os_focused(platform, clients) not in ("", shown)
|
||||
and _away(platform, clients) == [shown]
|
||||
)
|
||||
),
|
||||
)
|
||||
other = os_focused(platform, clients)
|
||||
checks.check(
|
||||
"... with the focus agreed",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, other)),
|
||||
)
|
||||
now = platform.os_window(Client(other))
|
||||
checks.check(
|
||||
"... and it fills the tile the first one had",
|
||||
frame is not None and now is not None and now.frame == frame.frame,
|
||||
)
|
||||
platform.komorebic("cycle-stack", "previous")
|
||||
checks.check(
|
||||
"cycling back, the first is in view again",
|
||||
platform.wait_for(
|
||||
lambda: os_focused(platform, clients) == shown and len(_away(platform, clients)) == 1
|
||||
),
|
||||
)
|
||||
|
||||
platform.komorebic("unstack")
|
||||
checks.check("three tiles again", platform.wait_for(lambda: _sizes(platform) == [1, 1, 1]))
|
||||
checks.check("nothing is put away", platform.wait_for(lambda: _away(platform, clients) == []))
|
||||
frames = [w.frame for c in clients if (w := platform.os_window(c)) is not None]
|
||||
checks.check(
|
||||
"and they tile, not on each other",
|
||||
len(frames) == len(clients)
|
||||
and not any(a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]),
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Workspace rules from the config: a window that was open before the daemon, and one after."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Platform
|
||||
|
||||
|
||||
def _config() -> dict[str, Any]:
|
||||
rule = {"kind": "Title", "id": "stays here", "matching_strategy": "StartsWith"}
|
||||
return {
|
||||
"monitors": [
|
||||
{
|
||||
"workspaces": [
|
||||
{"name": "web", "layout": "BSP"},
|
||||
{"name": "code", "layout": "BSP", "workspace_rules": [rule]},
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""Opens a window, starts the daemon with a rule that sends windows by their title to the
|
||||
second workspace, and checks where that window and one that opens afterwards are.
|
||||
|
||||
The daemon must be running with no window open. The rule is in the config file, not made with
|
||||
`komorebic`, so that what is checked is how the file is read at start.
|
||||
"""
|
||||
before = platform.spawn("stays here, from before")
|
||||
platform.restart_with(_config())
|
||||
checks.check(
|
||||
"a window that was open when the daemon started is on the workspace the file names",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(before.title) == 1, timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
"... where it is put away while the first workspace is in view",
|
||||
platform.wait_for(lambda: platform.hidden(before)),
|
||||
)
|
||||
after = platform.spawn("stays here, from after")
|
||||
checks.check(
|
||||
"a window that opens after the start goes to that workspace too",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(after.title) == 1, timeout=30),
|
||||
)
|
||||
other = platform.spawn("elsewhere")
|
||||
checks.check(
|
||||
"a window no rule names stays on the first",
|
||||
platform.wait_for(lambda: platform.state().workspace_of(other.title) == 0, timeout=30),
|
||||
)
|
||||
platform.komorebic("focus-workspace", "1")
|
||||
checks.check(
|
||||
"and the windows of the rule are in view when their workspace is",
|
||||
platform.wait_for(lambda: not platform.hidden(before) and not platform.hidden(after)),
|
||||
)
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
for client in (before, after, other):
|
||||
platform.close(client)
|
||||
platform.wait_for(lambda: platform.state().managed() == 0, timeout=20)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""The daemon's state names each window as it was opened: its title, its program and its class."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Platform
|
||||
|
||||
|
||||
def _window(platform: Platform, title: str): # noqa: ANN202
|
||||
for workspace in platform.state().workspace().windows():
|
||||
if workspace.title == title:
|
||||
return workspace
|
||||
return None
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""Opens a window with only a title, one with a class, and one made by a program of its own,
|
||||
and checks what the state says of each: the title as given, the class that was set, and the
|
||||
program (through `exe_id`, which is its file name on the platform).
|
||||
|
||||
The rules scenarios check that a rule finds a window by these; this checks that what the state
|
||||
shows of a window is what the window was given. The daemon must be running, with no window.
|
||||
"""
|
||||
plain = platform.spawn("fidelity plain")
|
||||
classed = platform.spawn("fidelity class", app_id="e2e-fidelity-class")
|
||||
made = platform.spawn("fidelity exe", exe="e2e-fidelity-exe")
|
||||
platform.wait_for(lambda: platform.state().managed() == 3, timeout=30)
|
||||
|
||||
found = _window(platform, plain.title)
|
||||
checks.check("the state has the title of a window as it was opened", found is not None)
|
||||
checks.check(
|
||||
"... and says what program opened it",
|
||||
found is not None and found.exe != "",
|
||||
)
|
||||
found = _window(platform, classed.title)
|
||||
checks.check(
|
||||
"the state has the class a window was given",
|
||||
found is not None and found.window_class == "e2e-fidelity-class",
|
||||
)
|
||||
found = _window(platform, made.title)
|
||||
checks.check(
|
||||
"the state has the program that opened a window, as its file name",
|
||||
found is not None and found.exe == platform.exe_id("e2e-fidelity-exe"),
|
||||
)
|
||||
for client in (plain, classed, made):
|
||||
platform.close(client)
|
||||
checks.check(
|
||||
"the three windows are closed",
|
||||
platform.wait_for(lambda: platform.state().managed() == 0, timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,81 @@
|
||||
"""What more than one scenario needs of a platform."""
|
||||
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
|
||||
# how long something that must not happen is waited for, in seconds (scaled for the host): a window
|
||||
# a rule leaves alone, a window that stays where it is. It is more than the daemon takes to act on
|
||||
# an event on either port, and the price of every such check
|
||||
QUIET = 3
|
||||
|
||||
|
||||
def describe(platform: Platform, clients: list[Client]) -> str:
|
||||
"""What the daemon and the system say of each of `clients`, for a failed check to print."""
|
||||
state = platform.state()
|
||||
layout = [str(r) for r in state.workspace().latest_layout]
|
||||
lines = [f" work area {platform.work_area()}; the layout {layout}"]
|
||||
for client in clients:
|
||||
window = platform.os_window(client)
|
||||
frame = window.frame if window is not None else None
|
||||
lines.append(
|
||||
f" {client.title}: workspace {state.workspace_of(client.title)},"
|
||||
f" hidden {platform.hidden(client)}, frame {frame}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def os_focused(platform: Platform, clients: list[Client]) -> str:
|
||||
"""The title of the window the operating system says has the focus, among `clients`.
|
||||
|
||||
The empty string when none of them does.
|
||||
"""
|
||||
for client in clients:
|
||||
window = platform.os_window(client)
|
||||
if window is not None and window.focused:
|
||||
return window.title
|
||||
return ""
|
||||
|
||||
|
||||
def in_view(platform: Platform, clients: list[Client]) -> list[str]:
|
||||
"""The titles of the windows of `clients` that are on the screen: the operating system has
|
||||
them, and the daemon has not put them away. Sorted.
|
||||
|
||||
A window the system does not have is not in view, though `Platform.hidden` says no for it
|
||||
too: a window that is gone must not count as one that is shown.
|
||||
"""
|
||||
return sorted(
|
||||
c.title for c in clients if platform.os_window(c) is not None and not platform.hidden(c)
|
||||
)
|
||||
|
||||
|
||||
def positions(platform: Platform, clients: list[Client]) -> dict[str, tuple[int, int]]:
|
||||
"""Where the operating system has each window, by title.
|
||||
|
||||
Only the position: a client may round its size to what suits it (a terminal's cells), and
|
||||
a window that moved is told by where it is.
|
||||
"""
|
||||
found = {}
|
||||
for client in clients:
|
||||
window = platform.os_window(client)
|
||||
if window is not None:
|
||||
found[client.title] = (window.frame.x, window.frame.y)
|
||||
return found
|
||||
|
||||
|
||||
def focus_agrees(platform: Platform, clients: list[Client], title: str) -> bool:
|
||||
"""The operating system and the daemon's state both have `title` focused."""
|
||||
return os_focused(platform, clients) == title and platform.state().focused_title() == title
|
||||
|
||||
|
||||
def layout_rect(platform: Platform, client: Client) -> Rect | None:
|
||||
"""The rectangle the daemon's layout gives the container of `client`, or `None` if the
|
||||
first workspace has no such container.
|
||||
|
||||
It is what the daemon asked for: the frame the operating system gives the window may be short
|
||||
of it by `platform.tolerance`, and is what the scenario then compares it with.
|
||||
"""
|
||||
workspace = platform.state().workspace()
|
||||
for i, stack in enumerate(workspace.containers):
|
||||
if any(w.title == client.title for w in stack) and i < len(workspace.latest_layout):
|
||||
return workspace.latest_layout[i]
|
||||
return None
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Windows that open are tiled: each where the layout says, none over another, all on screen."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
|
||||
|
||||
def _where_the_layout_says(frame: Rect, want: Rect, tolerance: int) -> bool:
|
||||
"""The same place, and the size up to `tolerance` short of what was asked for."""
|
||||
return (
|
||||
(frame.x, frame.y) == (want.x, want.y)
|
||||
and 0 <= want.w - frame.w <= tolerance
|
||||
and 0 <= want.h - frame.h <= tolerance
|
||||
)
|
||||
|
||||
|
||||
def run(
|
||||
platform: Platform, checks: Checks, titles: tuple[str, ...] = ("win1", "win2", "win3")
|
||||
) -> list[Client]:
|
||||
"""Opens a window for each title and checks, against the OS's own account of the frames, that
|
||||
the daemon has tiled them.
|
||||
|
||||
The daemon must be running, on a workspace with no window, with a tiling layout. Returns the
|
||||
windows it opened, for a scenario that goes on from them.
|
||||
"""
|
||||
clients = [platform.spawn(title) for title in titles]
|
||||
area = platform.work_area()
|
||||
|
||||
def managed() -> bool:
|
||||
return platform.state().managed() == len(titles)
|
||||
|
||||
checks.check("the daemon manages every window", platform.wait_for(managed, timeout=20))
|
||||
|
||||
def placed() -> bool:
|
||||
workspace = platform.state().workspace()
|
||||
layout = workspace.latest_layout
|
||||
frames = [platform.os_window(c) for c in clients]
|
||||
if len(layout) != len(titles) or any(f is None for f in frames):
|
||||
return False
|
||||
# the layout's rectangles are in the order of the containers, which is not the order the
|
||||
# windows opened in: each window is matched with its own container's rectangle
|
||||
by_title = {w.title: layout[i] for i, c in enumerate(workspace.containers) for w in c[:1]}
|
||||
return all(
|
||||
f is not None and _where_the_layout_says(f.frame, by_title[f.title], platform.tolerance)
|
||||
for f in frames
|
||||
)
|
||||
|
||||
checks.check(
|
||||
"every window is where the layout says, as the OS reports it",
|
||||
platform.wait_for(placed, timeout=20),
|
||||
)
|
||||
|
||||
frames = [f.frame for c in clients if (f := platform.os_window(c)) is not None]
|
||||
checks.check("the OS has a frame for every window", len(frames) == len(titles))
|
||||
for client, frame in zip(clients, frames, strict=False):
|
||||
checks.check(f"{client.title} is inside the work area", frame.inside(area))
|
||||
for i, a in enumerate(frames):
|
||||
for j in range(i + 1, len(frames)):
|
||||
checks.check(
|
||||
f"{clients[i].title} and {clients[j].title} do not overlap",
|
||||
not a.overlaps(frames[j]),
|
||||
)
|
||||
checks.check(
|
||||
"the windows share the work area: none takes all of its width",
|
||||
all(f.w < area.w - platform.tolerance for f in frames),
|
||||
)
|
||||
return clients
|
||||
@@ -0,0 +1,39 @@
|
||||
"""A workspace with tiling off leaves its windows where they are, and tiling it again tiles them."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
from komorebi_vm.core.scenarios.support import QUIET, positions
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Toggles tiling off on the first workspace, which has `clients` tiled in a container each,
|
||||
and on again, with a layout change in between that must not move anything."""
|
||||
before = positions(platform, clients)
|
||||
|
||||
platform.komorebic("toggle-tiling")
|
||||
checks.check(
|
||||
"after 'toggle-tiling' the daemon has the workspace untiled",
|
||||
platform.wait_for(lambda: not platform.state().workspace().tile, timeout=20),
|
||||
)
|
||||
checks.check("... and no window moved", positions(platform, clients) == before)
|
||||
platform.komorebic("change-layout", "columns")
|
||||
checks.check(
|
||||
"... a layout change does not move them either",
|
||||
not platform.wait_for(lambda: positions(platform, clients) != before, timeout=QUIET),
|
||||
)
|
||||
|
||||
platform.komorebic("toggle-tiling")
|
||||
checks.check(
|
||||
"'toggle-tiling' again has the workspace tiled",
|
||||
platform.wait_for(lambda: platform.state().workspace().tile, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and every window is where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
platform.komorebic("change-layout", "bsp")
|
||||
checks.check(
|
||||
"... and in bsp again",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""A rule decides when a window opens: a title change later does not make the daemon look again."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import QUIET
|
||||
|
||||
PENDING = "pending-rule"
|
||||
RENAMED = "renamed-rule"
|
||||
MANAGED = "managed-before"
|
||||
MANAGED_RENAMED = "managed-after"
|
||||
AFTER = 6
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""A window that opens with a title an ignore rule matches is left alone, and stays so when it
|
||||
gives itself another title; a window that is managed stays managed when it renames itself.
|
||||
|
||||
The daemon runs with its windows tiled; the windows are closed at the end, and the rule stays.
|
||||
"""
|
||||
platform.komorebic("ignore-rule", "title", PENDING)
|
||||
before = platform.state().managed()
|
||||
|
||||
platform.spawn(PENDING, rename_to=RENAMED, after=AFTER)
|
||||
renamed = Client(RENAMED)
|
||||
checks.check(
|
||||
"a window the ignore rule matches by its title is left alone",
|
||||
platform.state().workspace_of(PENDING) is None and platform.state().managed() == before,
|
||||
)
|
||||
checks.check(
|
||||
"it gives itself another title",
|
||||
platform.wait_for(lambda: platform.os_window(renamed) is not None, timeout=30),
|
||||
)
|
||||
checks.check(
|
||||
"... and the daemon leaves it alone: a rule decides when a window opens",
|
||||
not platform.wait_for(lambda: platform.state().managed() != before, timeout=QUIET),
|
||||
)
|
||||
platform.close(renamed)
|
||||
platform.wait_for(lambda: platform.os_window(renamed) is None, timeout=10)
|
||||
|
||||
platform.spawn(MANAGED, rename_to=MANAGED_RENAMED, after=AFTER)
|
||||
kept = Client(MANAGED_RENAMED)
|
||||
checks.check(
|
||||
"a window that is managed when it renames itself stays managed",
|
||||
platform.wait_for(lambda: platform.os_window(kept) is not None, timeout=30)
|
||||
and platform.wait_for(lambda: platform.state().managed() == before + 1, timeout=10),
|
||||
)
|
||||
platform.close(kept)
|
||||
checks.check(
|
||||
"closed, it leaves the daemon",
|
||||
platform.wait_for(
|
||||
lambda: platform.os_window(kept) is None and platform.state().managed() == before,
|
||||
timeout=10,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Wallpapers, and the colors of the borders that come from them.
|
||||
|
||||
A monitor's wallpaper is set when the daemon starts, and the wallpaper of a workspace replaces it
|
||||
while the workspace is shown. The borders of the windows take the colors of the wallpaper's
|
||||
palette, and follow it from workspace to workspace. A wallpaper the user changed by hand is put back
|
||||
when its workspace is shown again.
|
||||
|
||||
The pictures are a dozen bands of color each, since a palette wants at least eight: a warm one for
|
||||
the monitor, a cool one for the second workspace, and a green one the user sets by hand. Both ports
|
||||
read the same `wallpaper` of `komorebi.json`, and keep a palette for each picture.
|
||||
"""
|
||||
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from komorebi_vm.core import pixels
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
|
||||
|
||||
def picture(hue: tuple[int, int, int], ramp: int) -> bytes:
|
||||
"""A 192 by 108 PNG of diagonal bands of `hue`, going dark and light, `ramp` varying the hue."""
|
||||
data: list[tuple[int, int, int]] = []
|
||||
for y in range(108):
|
||||
for x in range(192):
|
||||
band = (x // 16 + y // 16) % 12
|
||||
shade = 40 + (band % 4) * 55
|
||||
red, green, blue = hue
|
||||
green = min(255, green + band * ramp)
|
||||
data.append(
|
||||
(min(255, red * shade // 255), min(255, green * shade // 255), blue * shade // 255)
|
||||
)
|
||||
image = Image.new("RGB", (192, 108))
|
||||
image.putdata(data)
|
||||
out = io.BytesIO()
|
||||
image.save(out, "PNG")
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _hue(red: int, blue: int) -> str:
|
||||
return "warm" if red > blue + 40 else "cool" if blue > red + 40 else "neither"
|
||||
|
||||
|
||||
def hue_of(image: Image.Image) -> str:
|
||||
"""Warm, cool or neither: the average color of a grid of points of the screen."""
|
||||
width, height = image.size
|
||||
points = [
|
||||
pixels.pixel(image, width * i // 10, height * j // 12)
|
||||
for i in range(1, 10)
|
||||
for j in range(1, 9)
|
||||
]
|
||||
return _hue(
|
||||
round(sum(p[0] for p in points) / len(points)),
|
||||
round(sum(p[2] for p in points) / len(points)),
|
||||
)
|
||||
|
||||
|
||||
def ring_hue(frame: Rect, image: Image.Image, reach: int = 12) -> str:
|
||||
"""The hue of the ring around a window: the colors within `reach` pixels outside the left edge
|
||||
of its frame, at its middle. Both ports draw the border outside the frame. What is inside it is
|
||||
the window's own, whatever its color, and is not read."""
|
||||
seen = set()
|
||||
for x in range(max(0, frame.x - reach), min(image.size[0], frame.x)):
|
||||
red, _, blue = pixels.pixel(image, x, frame.y + frame.h // 2)
|
||||
seen.add(_hue(red, blue))
|
||||
seen.discard("neither")
|
||||
return seen.pop() if len(seen) == 1 else "neither" if not seen else "mixed"
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks) -> None:
|
||||
"""The daemon starts with a wallpaper for the monitor and one for its second workspace; the
|
||||
scenario follows them from workspace to workspace, with the borders, and sets one by hand.
|
||||
The workspace is empty, and so it is when the scenario ends."""
|
||||
warm = platform.temp_path("wallpapers/warm.png")
|
||||
cool = platform.temp_path("wallpapers/my pictures/cool.png")
|
||||
other = platform.temp_path("wallpapers/other.png")
|
||||
platform.put_file(warm, picture((255, 0, 20), 20))
|
||||
platform.put_file(cool, picture((20, 80, 255), 14))
|
||||
platform.put_file(other, picture((60, 255, 60), 0))
|
||||
|
||||
def shows(path: str) -> bool:
|
||||
return platform.wallpaper() == path
|
||||
|
||||
def screen_is(hue: str, name: str) -> bool:
|
||||
"""Takes pictures of the screen until it is `hue`: one can catch the shell half way."""
|
||||
return platform.wait_for(lambda: hue_of(platform.screenshot(name)) == hue, timeout=20)
|
||||
|
||||
def has_ring(client: Client, hue: str, name: str) -> bool:
|
||||
"""The window has a ring of `hue` in a screenshot taken until it does. When it has not,
|
||||
what the last screenshot had is printed: the frame, and the colors it was read from."""
|
||||
|
||||
def ring() -> bool:
|
||||
window = platform.os_window(client)
|
||||
return window is not None and ring_hue(window.frame, platform.screenshot(name)) == hue
|
||||
|
||||
if platform.wait_for(ring, timeout=20):
|
||||
return True
|
||||
window = platform.os_window(client)
|
||||
if window is None:
|
||||
print(f" {client.title} has no window")
|
||||
else:
|
||||
image = platform.screenshot(name)
|
||||
f = window.frame
|
||||
y = f.y + f.h // 2
|
||||
row = [pixels.pixel(image, x, y) for x in range(max(0, f.x - 12), f.x + 4, 2)]
|
||||
print(f" {client.title} {f}: ring {ring_hue(f, image)}, wanted {hue}; pixels {row}")
|
||||
return False
|
||||
|
||||
platform.set_wallpaper(other)
|
||||
checks.check(
|
||||
"the screen shows a picture of the user's choice to begin with",
|
||||
platform.wait_for(lambda: shows(other), timeout=20),
|
||||
)
|
||||
|
||||
platform.restart_with(
|
||||
{
|
||||
"monitors": [
|
||||
{
|
||||
"wallpaper": {"path": warm},
|
||||
"workspaces": [
|
||||
{"name": "one"},
|
||||
{"name": "two", "wallpaper": {"path": cool}},
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
checks.check(
|
||||
"at start the screen shows the monitor's wallpaper",
|
||||
platform.wait_for(lambda: shows(warm), timeout=20),
|
||||
)
|
||||
checks.check("and the screen is warm", screen_is("warm", "wallpaper-a1"))
|
||||
|
||||
platform.komorebic("focus-workspace", "1")
|
||||
checks.check(
|
||||
"workspace two's own wallpaper is shown when it is (the path has a space in it)",
|
||||
platform.wait_for(lambda: shows(cool), timeout=10),
|
||||
)
|
||||
checks.check("and the screen is cool", screen_is("cool", "wallpaper-a2"))
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
checks.check(
|
||||
"back on workspace one, the monitor's wallpaper again",
|
||||
platform.wait_for(lambda: shows(warm), timeout=10),
|
||||
)
|
||||
|
||||
left = platform.spawn("wallpaper-left")
|
||||
checks.check(
|
||||
"on the warm workspace the focused window's ring is warm",
|
||||
has_ring(left, "warm", "wallpaper-c1"),
|
||||
)
|
||||
platform.komorebic("focus-workspace", "1")
|
||||
right = platform.spawn("wallpaper-right")
|
||||
checks.check("on the cool one it is cool", has_ring(right, "cool", "wallpaper-c2"))
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
checks.check("and warm again when the first is back", has_ring(left, "warm", "wallpaper-c3"))
|
||||
|
||||
platform.set_wallpaper(other)
|
||||
checks.check("the user changed it", platform.wait_for(lambda: shows(other), timeout=10))
|
||||
platform.komorebic("focus-workspace", "1")
|
||||
platform.wait_for(lambda: shows(cool), timeout=10)
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
checks.check(
|
||||
"showing the workspace again set it back",
|
||||
platform.wait_for(lambda: shows(warm), timeout=10),
|
||||
)
|
||||
|
||||
platform.close(left)
|
||||
platform.komorebic("focus-workspace", "1")
|
||||
platform.close(right)
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
@@ -0,0 +1,57 @@
|
||||
"""A window moved to a workspace takes the focus there, and the last workspace is one command
|
||||
away."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.layouts import tiled
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees, in_view
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Moves the last of `clients`, which are tiled windows of workspace 0 in a container each,
|
||||
to workspace 1 with `move-to-workspace`, goes back and forth with `focus-last-workspace`, and
|
||||
moves it home. Workspace 1 is empty."""
|
||||
target = clients[-1]
|
||||
rest = sorted(c.title for c in clients if c != target)
|
||||
everyone = sorted(c.title for c in clients)
|
||||
platform.activate(target)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title))
|
||||
|
||||
platform.komorebic("move-to-workspace", "1")
|
||||
checks.check(
|
||||
"after 'move-to-workspace 1' the window is there, in view, and the others are put away",
|
||||
platform.wait_for(lambda: in_view(platform, clients) == [target.title], timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... the daemon has it on workspace 1",
|
||||
platform.wait_for(lambda: platform.state().containers(1) == [[target.title]]),
|
||||
)
|
||||
checks.check(
|
||||
"... and it has the focus",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, target.title)),
|
||||
)
|
||||
|
||||
platform.komorebic("focus-last-workspace")
|
||||
checks.check(
|
||||
"'focus-last-workspace' brings the others back and puts the window away",
|
||||
platform.wait_for(lambda: in_view(platform, clients) == rest, timeout=20),
|
||||
)
|
||||
platform.komorebic("focus-last-workspace")
|
||||
checks.check(
|
||||
"... and again, it goes back to the window",
|
||||
platform.wait_for(lambda: in_view(platform, clients) == [target.title], timeout=20),
|
||||
)
|
||||
|
||||
platform.komorebic("move-to-workspace", "0")
|
||||
checks.check(
|
||||
"'move-to-workspace 0' has every window in view again",
|
||||
platform.wait_for(lambda: in_view(platform, clients) == everyone, timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... tiled where the layout says",
|
||||
platform.wait_for(lambda: tiled(platform, clients), timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"... and workspace 1 is empty",
|
||||
platform.wait_for(lambda: platform.state().containers(1) == []),
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""A window sent to another workspace is put away, and switching to it brings it and takes the
|
||||
others away."""
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client, Platform
|
||||
from komorebi_vm.core.scenarios.support import focus_agrees, in_view, os_focused
|
||||
|
||||
|
||||
def run(platform: Platform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Sends the focused one of `clients` to workspace 1, switches to it and back.
|
||||
|
||||
`clients` are tiled windows of workspace 0, each in a container of its own, with more than one
|
||||
of them. Workspace 1 is empty.
|
||||
"""
|
||||
last = clients[-1]
|
||||
rest = sorted(c.title for c in clients if c != last)
|
||||
platform.activate(last)
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, last.title))
|
||||
checks.check(
|
||||
"every window is in view", in_view(platform, clients) == sorted(c.title for c in clients)
|
||||
)
|
||||
|
||||
platform.komorebic("send-to-workspace", "1")
|
||||
checks.check(
|
||||
f"after 'send-to-workspace 1' {last.title} is put away",
|
||||
platform.wait_for(lambda: platform.hidden(last)),
|
||||
)
|
||||
checks.check(
|
||||
"... the daemon has it on workspace 1",
|
||||
platform.wait_for(lambda: platform.state().containers(1) == [[last.title]]),
|
||||
)
|
||||
checks.check(
|
||||
"... and the others are still in view",
|
||||
platform.wait_for(lambda: in_view(platform, clients) == rest),
|
||||
)
|
||||
|
||||
platform.komorebic("focus-workspace", "1")
|
||||
platform.wait_for(lambda: in_view(platform, clients) == [last.title])
|
||||
print(f" in view after the switch: {in_view(platform, clients)}")
|
||||
checks.check(
|
||||
"after 'focus-workspace 1' only the window sent there is in view",
|
||||
platform.wait_for(lambda: in_view(platform, clients) == [last.title]),
|
||||
)
|
||||
checks.check(
|
||||
"... it has the focus, and the daemon agrees",
|
||||
platform.wait_for(lambda: focus_agrees(platform, clients, last.title)),
|
||||
)
|
||||
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
checks.check(
|
||||
"after 'focus-workspace 0' the others are in view and the one sent away is put away",
|
||||
platform.wait_for(lambda: in_view(platform, clients) == rest),
|
||||
)
|
||||
checks.check(
|
||||
"... and one of them has the focus",
|
||||
platform.wait_for(lambda: os_focused(platform, clients) in rest),
|
||||
)
|
||||
@@ -0,0 +1,198 @@
|
||||
"""The daemon's state, in one shape for every port.
|
||||
|
||||
`komorebic state` prints a different JSON for each port. kfde serializes a window as
|
||||
`{id, rect, details: {title, exe, class, path}}`, kfw as `{hwnd, title, exe, class, rect}`; a
|
||||
monitor has `serial_number_id` on one and `device_id` on the other; and the state has fields only
|
||||
one of them has. A scenario must not care, so it reads a
|
||||
[`Snapshot`](komorebi_vm.core.snapshot.Snapshot): monitors, workspaces, containers and windows,
|
||||
with the same names and types whatever printed them.
|
||||
|
||||
`rect` is `{left, top, right, bottom}` on both ports, where `right` and `bottom` are the width and
|
||||
the height, which is what [`Rect`](komorebi_vm.core.geometry.Rect) takes.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Window:
|
||||
"""A window the daemon manages."""
|
||||
|
||||
id: int
|
||||
"""The daemon's id: the compositor's on kfde, the handle on kfw."""
|
||||
title: str
|
||||
exe: str
|
||||
window_class: str
|
||||
rect: Rect | None
|
||||
"""Where the daemon last saw the window. `None` when the state has no rect for it."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Workspace:
|
||||
"""A workspace of a monitor."""
|
||||
|
||||
name: str | None
|
||||
layout: str
|
||||
"""The layout's name: `BSP`, `Columns`, ... or `Custom`."""
|
||||
tile: bool
|
||||
containers: list[list[Window]]
|
||||
"""The tiled containers, in order, each with its stack of windows."""
|
||||
focused_container: int
|
||||
focused_windows: list[int]
|
||||
"""For each container, the place in it of the window that has the focus (a stack's top)."""
|
||||
monocle: list[Window] | None
|
||||
"""The windows of the monocle container, or `None` when the workspace is not in monocle."""
|
||||
maximized: Window | None
|
||||
floating: list[Window]
|
||||
latest_layout: list[Rect]
|
||||
"""The rectangles the layout last computed, one for each container."""
|
||||
workspace_padding: int | None = None
|
||||
"""The padding of the workspace, when the daemon says."""
|
||||
container_padding: int | None = None
|
||||
"""The padding of each of its containers, when the daemon says."""
|
||||
|
||||
def windows(self) -> list[Window]:
|
||||
"""Every window of the workspace: the tiled ones, the monocle ones, the maximized one and
|
||||
the floating ones."""
|
||||
found = [w for container in self.containers for w in container]
|
||||
found += self.monocle or []
|
||||
found += [self.maximized] if self.maximized is not None else []
|
||||
return found + self.floating
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Monitor:
|
||||
"""A monitor, with its workspaces."""
|
||||
|
||||
id: int
|
||||
size: Rect
|
||||
work_area: Rect
|
||||
workspaces: list[Workspace]
|
||||
focused_workspace: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Snapshot:
|
||||
"""The state of a daemon: its monitors, and which is focused."""
|
||||
|
||||
monitors: list[Monitor]
|
||||
focused_monitor: int
|
||||
paused: bool = False
|
||||
extra: dict[str, Any] = field(default_factory=dict, compare=False)
|
||||
"""What only this port's state has, such as `has_pending_raise_op` on kfw."""
|
||||
|
||||
def workspace(self, workspace: int | None = None, monitor: int = 0) -> Workspace:
|
||||
"""A workspace of a monitor, by position; the focused one when none is given."""
|
||||
m = self.monitors[monitor]
|
||||
return m.workspaces[m.focused_workspace if workspace is None else workspace]
|
||||
|
||||
def workspace_of(self, title: str, monitor: int = 0) -> int | None:
|
||||
"""The place of the workspace of a monitor that has a window with this title, or `None`."""
|
||||
for i, workspace in enumerate(self.monitors[monitor].workspaces):
|
||||
if any(w.title == title for w in workspace.windows()):
|
||||
return i
|
||||
return None
|
||||
|
||||
def containers(self, workspace: int | None = None, monitor: int = 0) -> list[list[str]]:
|
||||
"""The titles of the windows of each tiled container of a workspace."""
|
||||
return [[w.title for w in c] for c in self.workspace(workspace, monitor).containers]
|
||||
|
||||
def managed(self) -> int:
|
||||
"""The number of windows the daemon has, on every workspace of every monitor."""
|
||||
return sum(len(ws.windows()) for m in self.monitors for ws in m.workspaces)
|
||||
|
||||
def focused_title(self, workspace: int | None = None, monitor: int = 0) -> str:
|
||||
"""The title of the focused window of a workspace (the focused one when none is given): the
|
||||
focused window of its focused container. Empty if the workspace has no container."""
|
||||
ws = self.workspace(workspace, monitor)
|
||||
if not ws.containers:
|
||||
return ""
|
||||
index = min(ws.focused_container, len(ws.containers) - 1)
|
||||
container = ws.containers[index]
|
||||
if not container:
|
||||
return ""
|
||||
return container[min(ws.focused_windows[index], len(container) - 1)].title
|
||||
|
||||
|
||||
def _ring(value: dict[str, Any]) -> list[Any]:
|
||||
return list(value["elements"])
|
||||
|
||||
|
||||
def _focused(value: dict[str, Any]) -> int:
|
||||
return int(value.get("focused", 0))
|
||||
|
||||
|
||||
def _rect(value: dict[str, Any] | None) -> Rect | None:
|
||||
if value is None:
|
||||
return None
|
||||
return Rect(value["left"], value["top"], value["right"], value["bottom"])
|
||||
|
||||
|
||||
def _window(value: dict[str, Any]) -> Window:
|
||||
# kfde nests what it knows about the window under `details`; kfw puts it beside the handle
|
||||
details = value.get("details", value)
|
||||
return Window(
|
||||
id=int(value["id"] if "id" in value else value["hwnd"]),
|
||||
title=str(details.get("title", "")),
|
||||
exe=str(details.get("exe", "")),
|
||||
window_class=str(details.get("class", "")),
|
||||
rect=_rect(value.get("rect")),
|
||||
)
|
||||
|
||||
|
||||
def _layout(value: Any) -> str:
|
||||
# `{"Default": "BSP"}` for a built-in layout, `{"Custom": [...]}` for a custom one
|
||||
if isinstance(value, dict) and value:
|
||||
name, inner = next(iter(value.items()))
|
||||
return str(inner) if name == "Default" else str(name)
|
||||
return str(value)
|
||||
|
||||
|
||||
def _workspace(value: dict[str, Any]) -> Workspace:
|
||||
containers = [[_window(w) for w in _ring(c["windows"])] for c in _ring(value["containers"])]
|
||||
monocle = value.get("monocle_container")
|
||||
maximized = value.get("maximized_window")
|
||||
return Workspace(
|
||||
name=value.get("name"),
|
||||
layout=_layout(value.get("layout")),
|
||||
tile=bool(value.get("tile", True)),
|
||||
containers=containers,
|
||||
focused_container=_focused(value["containers"]),
|
||||
focused_windows=[_focused(c["windows"]) for c in _ring(value["containers"])],
|
||||
monocle=[_window(w) for w in _ring(monocle["windows"])] if monocle else None,
|
||||
maximized=_window(maximized) if maximized else None,
|
||||
floating=[_window(w) for w in _ring(value["floating_windows"])],
|
||||
latest_layout=[r for r in map(_rect, value.get("latest_layout", [])) if r is not None],
|
||||
workspace_padding=value.get("workspace_padding"),
|
||||
container_padding=value.get("container_padding"),
|
||||
)
|
||||
|
||||
|
||||
def _monitor(value: dict[str, Any]) -> Monitor:
|
||||
size = _rect(value["size"])
|
||||
work_area = _rect(value.get("work_area_size")) or size
|
||||
assert size is not None and work_area is not None
|
||||
return Monitor(
|
||||
id=int(value["id"]),
|
||||
size=size,
|
||||
work_area=work_area,
|
||||
workspaces=[_workspace(w) for w in _ring(value["workspaces"])],
|
||||
focused_workspace=_focused(value["workspaces"]),
|
||||
)
|
||||
|
||||
|
||||
_COMMON = {"monitors", "is_paused"}
|
||||
|
||||
|
||||
def parse(state: dict[str, Any]) -> Snapshot:
|
||||
"""Reads the JSON of `komorebic state`, from either port."""
|
||||
monitors = state["monitors"]
|
||||
return Snapshot(
|
||||
monitors=[_monitor(m) for m in _ring(monitors)],
|
||||
focused_monitor=_focused(monitors),
|
||||
paused=bool(state.get("is_paused", False)),
|
||||
extra={k: v for k, v in state.items() if k not in _COMMON},
|
||||
)
|
||||
@@ -0,0 +1,85 @@
|
||||
"""A suite as a list: shared scenarios, and what a platform adds to them.
|
||||
|
||||
A suite file says what runs, in order, and each step labels the checks it makes: `shared` for a
|
||||
scenario that runs on every platform, and a platform's own name for what only that platform can
|
||||
check. The output reads `[shared] ...` and `[<port>] ...`, and the same labels say, for each check,
|
||||
which port it belongs to.
|
||||
|
||||
Each step prints the time it took, so that a log says which scenario the time went to.
|
||||
|
||||
To run only some of the steps, set `E2E_ONLY` (or `KFDE_ONLY`, its older name) to a
|
||||
comma-separated list: a step runs when its
|
||||
name (`module.function`, as printed) contains one of the words, and a step made with `always=True`
|
||||
(what the others depend on, such as the one that opens the windows) runs whatever the list says.
|
||||
The steps that do not run are printed, and return `None`.
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
|
||||
# the variable that names the steps to run, and the older name of it
|
||||
ONLY = "E2E_ONLY"
|
||||
OLD_ONLY = "KFDE_ONLY"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Step:
|
||||
"""A thing to run, and the scope of the checks it makes."""
|
||||
|
||||
scope: str
|
||||
run: Callable[[], object]
|
||||
name: str = ""
|
||||
always: bool = False
|
||||
|
||||
|
||||
def _name(fn: Callable[..., object]) -> str:
|
||||
"""`module.function` of a scenario or an extra, for the line that says what runs."""
|
||||
module = (getattr(fn, "__module__", None) or "").rsplit(".", 1)[-1]
|
||||
return f"{module}.{getattr(fn, '__name__', '')}".strip(".")
|
||||
|
||||
|
||||
def shared(scenario: Callable[..., object], *args: object, always: bool = False) -> Step:
|
||||
"""A scenario of `komorebi_vm.core.scenarios`, called with `args`."""
|
||||
return Step("shared", lambda: scenario(*args), _name(scenario), always)
|
||||
|
||||
|
||||
def platform_only(
|
||||
scope: str, extra: Callable[..., object], *args: object, always: bool = False
|
||||
) -> Step:
|
||||
"""What one platform adds: an extra of that platform, called with `args`, under its name."""
|
||||
return Step(scope, lambda: extra(*args), _name(extra), always)
|
||||
|
||||
|
||||
def _variable() -> str:
|
||||
"""The name of the variable that is set: `E2E_ONLY` before `KFDE_ONLY`."""
|
||||
return ONLY if os.environ.get(ONLY) else OLD_ONLY
|
||||
|
||||
|
||||
def _wanted() -> list[str]:
|
||||
return [word.strip() for word in os.environ.get(_variable(), "").split(",") if word.strip()]
|
||||
|
||||
|
||||
def run_suite(checks: Checks, *steps: Step) -> list[object]:
|
||||
"""Runs the steps in order, each with its scope on `checks`, and returns what each returned,
|
||||
so that a later part of a suite can use the windows a scenario opened.
|
||||
|
||||
A step that the list leaves out is not run. A step that is run prints how long it took."""
|
||||
wanted = _wanted()
|
||||
results: list[object] = []
|
||||
for step in steps:
|
||||
if wanted and not step.always and not any(word in step.name for word in wanted):
|
||||
print(f"== [{step.scope}] {step.name}: left out by {_variable()}")
|
||||
results.append(None)
|
||||
continue
|
||||
if step.name:
|
||||
print(f"== [{step.scope}] {step.name}")
|
||||
started = time.monotonic()
|
||||
with checks.scoped(step.scope):
|
||||
results.append(step.run())
|
||||
if step.name:
|
||||
print(f" [{step.scope}] {step.name}: {time.monotonic() - started:.1f} s")
|
||||
return results
|
||||
@@ -0,0 +1,63 @@
|
||||
"""What the komorebi daemon logs about the events it handles.
|
||||
|
||||
A test reads the daemon's view of the desktop from its log
|
||||
([`Kde.komorebi_log`](komorebi_vm.kde.Kde.komorebi_log)), at the debug level
|
||||
the test nodes set (`services.komorebi.logLevel`): every event it handles is an
|
||||
info line, every focus change KWin reports names the window by the daemon's id
|
||||
and its title, and every frame the daemon asks KWin for is a debug line.
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
|
||||
_EVENT = re.compile(r"processing event: (\w+) for window (\d+) with notification (\w+)")
|
||||
_ACTIVATED = re.compile(r"KWin activated window (\d+) \((.*)\)$", re.MULTILINE)
|
||||
_REQUEST = re.compile(
|
||||
r"asking for window (\d+) to be at "
|
||||
r"Rect \{ left: (-?\d+), top: (-?\d+), right: (-?\d+), bottom: (-?\d+) \}"
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Event:
|
||||
"""A window event the daemon handled."""
|
||||
|
||||
kind: str
|
||||
"""The event (`Show`, `Destroy`, `FocusChange`, `Minimize`, `Restore`, `MaximizeChange`)."""
|
||||
window: int
|
||||
"""The daemon's id for the window."""
|
||||
notification: str
|
||||
"""The KWin signal it came from (`WindowAdded`, ...)."""
|
||||
|
||||
|
||||
def events(log: str) -> list[Event]:
|
||||
"""Returns the window events the daemon handled, in the order it handled them."""
|
||||
return [Event(kind, int(window), signal) for kind, window, signal in _EVENT.findall(log)]
|
||||
|
||||
|
||||
def window_ids(log: str) -> dict[str, int]:
|
||||
"""Returns the daemon's id for each window KWin has given the focus, by title.
|
||||
|
||||
A title that two windows had is the later one's.
|
||||
"""
|
||||
return {title: int(window) for window, title in _ACTIVATED.findall(log)}
|
||||
|
||||
|
||||
def requests(log: str) -> dict[int, Rect]:
|
||||
"""Returns the frame the daemon last asked KWin for, for each window, by the daemon's id."""
|
||||
return {
|
||||
int(window): Rect(int(x), int(y), int(w), int(h))
|
||||
for window, x, y, w, h in _REQUEST.findall(log)
|
||||
}
|
||||
|
||||
|
||||
def asked(log: str, title: str) -> Rect | None:
|
||||
"""Returns the frame the daemon last asked KWin for, for the window with this title.
|
||||
|
||||
`None` if KWin never gave the window the focus (which is how its title reaches the log), or
|
||||
the daemon never asked for a frame for it.
|
||||
"""
|
||||
window = window_ids(log).get(title)
|
||||
return requests(log).get(window) if window is not None else None
|
||||
@@ -0,0 +1,801 @@
|
||||
"""A KWin session inside a test machine, and the tools to look at it."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import shlex
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from itertools import count
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.machine import Machine
|
||||
|
||||
# a KWin script is told apart by its name in the journal, so each probe has a name of its own
|
||||
_PROBES = count(1)
|
||||
# how long what KWin said of the outputs is kept, in seconds
|
||||
SCREENS_TTL = 1.0
|
||||
|
||||
|
||||
class Outputs:
|
||||
"""The outputs of a KWin session, as `kscreen-doctor` lists and changes them.
|
||||
|
||||
A [`Kde`][] has one, as [`Kde.outputs`][]. Calling it gives the number of outputs KWin has
|
||||
enabled. An output is named as KWin names it (`Virtual-0`), and a disabled output keeps its
|
||||
name, so that it can be enabled again.
|
||||
"""
|
||||
|
||||
def __init__(self, kde: "Kde") -> None:
|
||||
self._kde = kde
|
||||
|
||||
def __call__(self) -> int:
|
||||
"""The number of outputs KWin has enabled."""
|
||||
return int(
|
||||
self._kde.sh("kscreen-doctor -j | jq '[.outputs[] | select(.enabled)] | length'")
|
||||
)
|
||||
|
||||
def names(self, *, enabled: bool = True) -> list[str]:
|
||||
"""The names of the outputs that are enabled (or, with `enabled` false, disabled), from
|
||||
left to right."""
|
||||
listed = self._kde.sh(
|
||||
f"kscreen-doctor -j | jq -r '[.outputs[] | select(.enabled == {str(enabled).lower()})]"
|
||||
" | sort_by(.pos.x) | .[].name'"
|
||||
)
|
||||
return listed.split()
|
||||
|
||||
def disable(self, name: str) -> None:
|
||||
"""Unplugs an output, as far as KWin can tell: it is disabled, and its windows go to the
|
||||
outputs that are left."""
|
||||
self._kde.sh(f"kscreen-doctor output.{name}.disable")
|
||||
self._kde.invalidate_screens()
|
||||
|
||||
def enable(self, name: str) -> None:
|
||||
"""Plugs an output back in, as far as KWin can tell."""
|
||||
self._kde.sh(f"kscreen-doctor output.{name}.enable")
|
||||
self._kde.invalidate_screens()
|
||||
|
||||
def scale(self, name: str, factor: float) -> None:
|
||||
"""Gives an output another scale: its size in pixels, as the windows see it, becomes
|
||||
its mode divided by `factor`."""
|
||||
self._kde.sh(f"kscreen-doctor output.{name}.scale.{factor:g}")
|
||||
self._kde.invalidate_screens()
|
||||
|
||||
|
||||
class Kde:
|
||||
"""One KWin session of the test user, with its own session bus and Wayland socket.
|
||||
|
||||
The node runs `kwin_wayland` and the bus as user units (see
|
||||
`nix/tests/vm/nodes/headless.nix`), so several sessions can run side by
|
||||
side under different names and none touches another. Every command is run
|
||||
as the test user, with the environment of the named session.
|
||||
|
||||
A session node has one more: the user's own Plasma session, which
|
||||
[`Kde.session`][] attaches to. Its bus is `$XDG_RUNTIME_DIR/bus` and its
|
||||
Wayland socket is whatever the user manager says it is.
|
||||
|
||||
`scale` multiplies every wait: 1 under KVM, more where the machine is
|
||||
slower (HVF on a Mac, TCG anywhere).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
machine: Machine,
|
||||
name: str,
|
||||
*,
|
||||
user: str = "komorebi",
|
||||
uid: int = 1000,
|
||||
scale: float = 1.0,
|
||||
bus: str | None = None,
|
||||
wayland_display: str | None = None,
|
||||
) -> None:
|
||||
self.machine = machine
|
||||
self.name = name
|
||||
self.user = user
|
||||
self.uid = uid
|
||||
self.scale = scale
|
||||
self._bus = bus
|
||||
self._wayland_display = wayland_display
|
||||
self._x_display: str | None = None
|
||||
|
||||
@classmethod
|
||||
def headless(
|
||||
cls,
|
||||
machine: Machine,
|
||||
name: str,
|
||||
*,
|
||||
size: tuple[int, int] = (1920, 1080),
|
||||
outputs: int = 1,
|
||||
xwayland: bool = False,
|
||||
scale: float = 1.0,
|
||||
user: str = "komorebi",
|
||||
uid: int = 1000,
|
||||
) -> "Kde":
|
||||
"""Starts `kwin_wayland --virtual` with `outputs` outputs of `size`, and waits for it.
|
||||
|
||||
With `xwayland`, KWin also runs XWayland, for X11 clients. It starts it when the first
|
||||
one connects and does not say where, so the session takes the first X11 socket of the
|
||||
machine: one session at a time can have XWayland.
|
||||
"""
|
||||
kde = cls(machine, name, user=user, uid=uid, scale=scale)
|
||||
machine.succeed(f"loginctl show-user {user} >/dev/null")
|
||||
width, height = size
|
||||
args = f"--width {width} --height {height} --output-count {outputs}"
|
||||
if xwayland:
|
||||
args += " --xwayland"
|
||||
kde.as_user(f"echo KWIN_ARGS={shlex.quote(args)} > {kde.runtime}/kwin-virtual-{name}.env")
|
||||
kde.systemctl("start", f"session-bus@{name}.service", f"kwin-virtual@{name}.service")
|
||||
if not kde.wait_for(lambda: kde.has_name("org.kde.KWin"), timeout=60):
|
||||
log = machine.execute(f"journalctl _UID={uid} --no-pager -n 40")[1]
|
||||
raise AssertionError(f"KWin did not come up:\n{log}")
|
||||
if xwayland:
|
||||
socket = "ls /tmp/.X11-unix | grep -E '^X[0-9]+$' | sort | head -n 1"
|
||||
if not kde.wait_for(lambda: machine.execute(socket)[1].strip() != "", timeout=10):
|
||||
raise AssertionError("KWin did not open an X11 socket")
|
||||
kde._x_display = ":" + machine.execute(socket)[1].strip()[1:]
|
||||
return kde
|
||||
|
||||
@classmethod
|
||||
def session(
|
||||
cls,
|
||||
machine: Machine,
|
||||
*,
|
||||
user: str = "komorebi",
|
||||
uid: int = 1000,
|
||||
scale: float = 1.0,
|
||||
timeout: float = 300,
|
||||
) -> "Kde":
|
||||
"""Attaches to the user's Plasma session once its desktop is up.
|
||||
|
||||
The session is up when the shell is running, the user manager knows the
|
||||
Wayland socket, the splash screen has gone, and the shell has made its
|
||||
panel. The splash screen is the condition a screenshot test depends on:
|
||||
it already has thousands of colors on it. The panel is the one a test of
|
||||
where a window is depends on: it takes room from the windows, and
|
||||
komorebi tiles the room that is left, if it starts after the panel.
|
||||
NixOS wraps its programs, so the processes
|
||||
are found by their command lines (`pgrep -x` would see only the wrapper's
|
||||
name), with the first letter in brackets so that the pattern does not
|
||||
match the shell that runs `pgrep`.
|
||||
"""
|
||||
kde = cls(machine, "session", user=user, uid=uid, scale=scale)
|
||||
kde._bus = f"unix:path={kde.runtime}/bus"
|
||||
if not kde.wait_for(lambda: kde.run("pgrep -f '[p]lasmashell'")[0] == 0, timeout=timeout):
|
||||
raise AssertionError("plasmashell did not start")
|
||||
|
||||
def display() -> str:
|
||||
out = kde.as_user("systemctl --user show-environment")
|
||||
return next(
|
||||
(
|
||||
line.split("=", 1)[1]
|
||||
for line in out.splitlines()
|
||||
if line.startswith("WAYLAND_DISPLAY=")
|
||||
),
|
||||
"",
|
||||
)
|
||||
|
||||
if not kde.wait_for(lambda: display() != "", timeout=timeout):
|
||||
raise AssertionError("the user manager never learned the Wayland display")
|
||||
kde._wayland_display = display()
|
||||
if not kde.wait_for(lambda: kde.run("pgrep -f '[k]splashqml'")[0] != 0, timeout=timeout):
|
||||
raise AssertionError("the splash screen did not go away")
|
||||
if not kde.wait_for(lambda: kde.panels() > 0, timeout=timeout):
|
||||
raise AssertionError("the shell never made a panel")
|
||||
return kde
|
||||
|
||||
def panels(self) -> int:
|
||||
"""Returns how many panels the Plasma shell has made, or 0 when it does not answer.
|
||||
|
||||
A panel takes room from the windows: the work area komorebi tiles is the screen less the
|
||||
panel. A test that reads where a tiled window ends has to wait for the panel, or komorebi
|
||||
tiles the window under it, and the bottom of a border is hidden by the panel.
|
||||
"""
|
||||
status, out = self.run(
|
||||
"busctl --user call org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell"
|
||||
" evaluateScript s 'print(panels().length)'"
|
||||
)
|
||||
found = re.search(r'^s "(\d+)', out.strip())
|
||||
return int(found.group(1)) if status == 0 and found else 0
|
||||
|
||||
def panel_has_room(self) -> bool:
|
||||
"""Returns true if and only if the daemon's work area is not the whole of its first monitor.
|
||||
|
||||
That is the daemon having learned that the panel takes room from the windows. It is not
|
||||
true when the daemon does not answer, or answers with something that is not its state.
|
||||
"""
|
||||
try:
|
||||
monitor = self.state()["monitors"]["elements"][0]
|
||||
except (AssertionError, ValueError, KeyError, IndexError):
|
||||
return False
|
||||
return monitor["work_area_size"] != monitor["size"]
|
||||
|
||||
def wait_for_panel_room(self, timeout: float = 30) -> bool:
|
||||
"""Waits until the daemon has the panel's room, and says whether it has.
|
||||
|
||||
The shell makes its panel (`Kde.panels`), KWin takes room for it a while later, and the
|
||||
daemon learns of that up to a second after, because the bridge looks at the work area once
|
||||
a second. A daemon that tiles before then puts the windows under the panel and tiles them
|
||||
again, and a test that reads where a window is, or what is round it, in between, reads
|
||||
the wrong tile. The windows are opened after this.
|
||||
|
||||
It is a wait and not a check: a session may never take the room (a machine too slow to
|
||||
lay the panel out, which TCG often is), so this ends after `timeout` seconds (times
|
||||
`scale`) and the test goes on, whichever it was. The daemon has to be running.
|
||||
"""
|
||||
return self.wait_for(self.panel_has_room, timeout=timeout)
|
||||
|
||||
@property
|
||||
def runtime(self) -> str:
|
||||
"""The test user's runtime directory."""
|
||||
return f"/run/user/{self.uid}"
|
||||
|
||||
@property
|
||||
def env(self) -> str:
|
||||
"""The `VAR=value` words that put a command inside this session."""
|
||||
profile = f"/etc/profiles/per-user/{self.user}"
|
||||
pairs = {
|
||||
"XDG_RUNTIME_DIR": self.runtime,
|
||||
"DBUS_SESSION_BUS_ADDRESS": self._bus
|
||||
or f"unix:path={self.runtime}/session-{self.name}.bus",
|
||||
"WAYLAND_DISPLAY": self._wayland_display or f"wayland-{self.name}",
|
||||
"KDE_SESSION_VERSION": "6",
|
||||
"XDG_CURRENT_DESKTOP": "KDE",
|
||||
"XDG_SESSION_TYPE": "wayland",
|
||||
"QT_QPA_PLATFORM": "wayland",
|
||||
"GDK_BACKEND": "wayland",
|
||||
# the user's, not those of root's shell, which a client would search and be refused
|
||||
"HOME": f"/home/{self.user}",
|
||||
"XDG_DATA_DIRS": f"{profile}/share:/run/current-system/sw/share",
|
||||
"XDG_CONFIG_DIRS": f"/etc/xdg:{profile}/etc/xdg:/run/current-system/sw/etc/xdg",
|
||||
}
|
||||
if self._x_display is not None:
|
||||
pairs["DISPLAY"] = self._x_display
|
||||
return " ".join(f"{key}={shlex.quote(value)}" for key, value in pairs.items())
|
||||
|
||||
def as_user(self, command: str) -> str:
|
||||
"""Runs `command` as the test user, and fails the test unless it succeeds."""
|
||||
return self.machine.succeed(self._wrap(command, session=False))
|
||||
|
||||
def run(self, command: str) -> tuple[int, str]:
|
||||
"""Runs `command` inside the session and returns its status and output."""
|
||||
return self.machine.execute(self._wrap(command))
|
||||
|
||||
def sh(self, command: str) -> str:
|
||||
"""Runs `command` inside the session, and fails the test unless it succeeds."""
|
||||
return self.machine.succeed(self._wrap(command))
|
||||
|
||||
def spawn(self, command: str, log: str = "/dev/null") -> None:
|
||||
"""Starts `command` in the background inside the session, as a client of KWin.
|
||||
|
||||
Its output goes to the file `log`, or nowhere.
|
||||
"""
|
||||
self.sh(f"setsid nohup {command} > {shlex.quote(log)} 2>&1 < /dev/null &")
|
||||
|
||||
def colored_window(self, title: str, color: str, timeout: float = 30) -> None:
|
||||
"""Opens a window that is one color all over, titled `title`, and waits for KWin to have it.
|
||||
|
||||
The window is a `foot` terminal with a background of `color` (`rrggbb`) that is not
|
||||
see-through, running `sleep 3000`: a test that wants to read its pixels from a screenshot
|
||||
wants one color and nothing else, and [`Kde.close_colored_windows`][] finds it by the
|
||||
command it runs, since NixOS wraps programs and their process names are not what they seem.
|
||||
"""
|
||||
words = f"foot -T {shlex.quote(title)} -o colors-dark.background={color}"
|
||||
self.spawn(f"{words} -o colors-dark.alpha=1.0 sleep 3000")
|
||||
self.wait_for(lambda: self.wid(title) != "", timeout=timeout)
|
||||
|
||||
def close_colored_windows(self) -> None:
|
||||
"""Closes every window [`Kde.colored_window`][] opened, and waits until they are gone."""
|
||||
self.run("pkill -f 'sleep 3000'")
|
||||
self.wait_for(lambda: self.run("pgrep -f 'sleep 3000'")[0] != 0, timeout=10)
|
||||
|
||||
def systemctl(self, *args: str) -> str:
|
||||
"""Runs `systemctl --user` as the test user."""
|
||||
return self.as_user("systemctl --user " + " ".join(args))
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stops the session's KWin and its bus."""
|
||||
self.systemctl(
|
||||
"stop", f"kwin-virtual@{self.name}.service", f"session-bus@{self.name}.service"
|
||||
)
|
||||
|
||||
def restart_kwin(self) -> None:
|
||||
"""Stops the session's KWin and starts a new one, on the same bus, and waits for it.
|
||||
|
||||
The bus outlives KWin, as it does when the compositor of a running session crashes or is
|
||||
replaced. The clients of the old KWin go with it.
|
||||
"""
|
||||
self.systemctl("restart", f"kwin-virtual@{self.name}.service")
|
||||
if not self.wait_for(lambda: self.has_name("org.kde.KWin"), timeout=60):
|
||||
log = self.machine.execute(f"journalctl _UID={self.uid} --no-pager -n 40")[1]
|
||||
raise AssertionError(f"KWin did not come back:\n{log}")
|
||||
|
||||
def start_komorebi(self, *args: str) -> None:
|
||||
"""Starts the daemon in this session, with `args`, as the user unit `komorebi@NAME`.
|
||||
|
||||
The unit runs the NixOS module's `execStart` with `args` after it, against this
|
||||
session's bus and KWin, and writes its log to a file that [`Kde.komorebi_log`][] reads,
|
||||
emptied on every start. `execStart` already has `--log-level`, from the node's
|
||||
`services.komorebi.logLevel` (debug), and `komorebi` refuses a second one.
|
||||
"""
|
||||
words = shlex.quote(" ".join(args))
|
||||
self.as_user(f"echo KOMOREBI_ARGS={words} > {self.runtime}/komorebi-{self.name}.env")
|
||||
self.systemctl("start", f"komorebi@{self.name}.service")
|
||||
|
||||
def kill_komorebi(self) -> None:
|
||||
"""Kills the daemon with `SIGKILL`, as a crash does, and waits for it to be gone.
|
||||
|
||||
Nothing of what the daemon had set up is put back: the user's `kwinrc`, the desktops it
|
||||
made and the windows it hid are as it left them.
|
||||
"""
|
||||
self.systemctl("kill", "--signal=KILL", f"komorebi@{self.name}.service")
|
||||
if not self.wait_for(lambda: not self.komorebi_running()):
|
||||
raise AssertionError("the daemon is still running after SIGKILL")
|
||||
|
||||
def stop_komorebi(self) -> None:
|
||||
"""Stops the daemon with `SIGTERM`, as a logout does, and waits for it to exit."""
|
||||
self.systemctl("stop", f"komorebi@{self.name}.service")
|
||||
|
||||
def spawn_komorebi(self, *args: str) -> None:
|
||||
"""Starts the daemon inside this session, in the background, with `args`.
|
||||
|
||||
This is for the session node's own Plasma session, with arguments of the test's own:
|
||||
the daemon is a client of the session's KWin and bus, as one started from a terminal
|
||||
there is. The module's unit runs a daemon there too, with its `execStart` as it is, so a
|
||||
suite that spawns its own sets `services.komorebi.enable = false` in its node. The log
|
||||
goes to the file [`Kde.komorebi_log`][] reads, emptied on every start.
|
||||
"""
|
||||
log = f"{self.runtime}/komorebi-{self.name}.log"
|
||||
self.spawn(shlex.join(["env", "NO_COLOR=1", "komorebi", *args]), log=log)
|
||||
|
||||
def kill_spawned_komorebi(self) -> None:
|
||||
"""Kills every daemon of the machine with `SIGKILL`, as a crash would, and waits for them
|
||||
to be gone: the one [`Kde.spawn_komorebi`][] started, which is not a unit to kill."""
|
||||
self.machine.execute("pkill -KILL -x komorebi")
|
||||
if not self.wait_for(lambda: self.machine.execute("pgrep -x komorebi")[0] != 0):
|
||||
raise AssertionError("komorebi is still running after SIGKILL")
|
||||
|
||||
def shortcut_actions(self, component: str = "komorebi") -> list[str]:
|
||||
"""The names of the actions `component` has in KDE's global shortcut daemon.
|
||||
|
||||
That is the empty list when the component has none, or there is no such component.
|
||||
"""
|
||||
status, out = self.run(
|
||||
"busctl --user --json=short call org.kde.kglobalaccel /kglobalaccel"
|
||||
f" org.kde.KGlobalAccel allActionsForComponent as 4 {shlex.quote(component)} '' '' ''"
|
||||
)
|
||||
if status != 0:
|
||||
return []
|
||||
return sorted(action[1] for action in json.loads(out)["data"][0])
|
||||
|
||||
def komorebi_running(self) -> bool:
|
||||
"""Returns true if and only if the daemon of this session is running."""
|
||||
unit = f"komorebi@{self.name}.service"
|
||||
command = self._wrap(f"systemctl --user is-active --quiet {unit}", session=False)
|
||||
return self.machine.execute(command)[0] == 0
|
||||
|
||||
def komorebi_log(self) -> str:
|
||||
"""The daemon's log since it was last started, or the empty string before that."""
|
||||
return self.machine.execute(f"cat {self.runtime}/komorebi-{self.name}.log")[1]
|
||||
|
||||
def komorebic(self, *args: str) -> str:
|
||||
"""Runs `komorebic` with `args` inside the session and returns what it printed.
|
||||
|
||||
It fails the test unless `komorebic` succeeds, as it does when no daemon answers.
|
||||
`komorebic` finds the daemon's socket in the user's runtime directory, which every session
|
||||
of the user shares, so one daemon at a time can answer it.
|
||||
"""
|
||||
return self.sh(shlex.join(["komorebic", *args]))
|
||||
|
||||
def state(self, attempts: int = 10) -> dict[str, Any]:
|
||||
"""The daemon's state, as `komorebic state` prints it.
|
||||
|
||||
The daemon answers a query when it can take hold of the window manager within a second,
|
||||
and answers nothing when it cannot, which is what a daemon busy with a window that has
|
||||
just opened does on a machine that is loaded or slow: `komorebic` then prints an empty
|
||||
line and succeeds. It also gives the daemon a second to answer, and fails when that is not
|
||||
enough. The query is asked again, a second (times `scale`) after an empty answer or a
|
||||
failure, up to `attempts` times, and fails the test if the daemon does not answer every
|
||||
time. An answer that is not JSON and not empty fails at once.
|
||||
"""
|
||||
for attempt in range(attempts):
|
||||
status, out = self.run(shlex.join(["komorebic", "state"]))
|
||||
if status == 0 and out.strip():
|
||||
return json.loads(out)
|
||||
if attempt + 1 < attempts:
|
||||
time.sleep(self.scale)
|
||||
raise AssertionError(
|
||||
f"the daemon did not answer `komorebic state`, {attempts} times: {status} {out!r}"
|
||||
)
|
||||
|
||||
def focused_title(self, workspace: int = 0) -> str:
|
||||
"""The title of the window the daemon has focused on a workspace of the first monitor.
|
||||
|
||||
That is the focused window of the workspace's focused container, as the daemon's state
|
||||
has it, or the empty string when the workspace has no container.
|
||||
"""
|
||||
containers = self._workspace(workspace)["containers"]
|
||||
if not containers["elements"]:
|
||||
return ""
|
||||
windows = containers["elements"][containers["focused"]]["windows"]
|
||||
return windows["elements"][windows["focused"]]["details"]["title"]
|
||||
|
||||
def containers(self, workspace: int = 0) -> list[list[str]]:
|
||||
"""The titles of the windows of each container of a workspace of the first monitor.
|
||||
|
||||
The containers are in the order of the layout, and the windows of a stack in the order of
|
||||
the stack. A workspace with no container gives an empty list.
|
||||
"""
|
||||
elements = self._workspace(workspace)["containers"]["elements"]
|
||||
return [
|
||||
[window["details"]["title"] for window in container["windows"]["elements"]]
|
||||
for container in elements
|
||||
]
|
||||
|
||||
def monocle(self, workspace: int = 0) -> list[str]:
|
||||
"""The titles of the windows of the monocle container of a workspace of the first monitor.
|
||||
|
||||
The windows are in the order of the stack. A workspace that is not in monocle gives an
|
||||
empty list.
|
||||
"""
|
||||
container = self._workspace(workspace)["monocle_container"]
|
||||
if container is None:
|
||||
return []
|
||||
return [window["details"]["title"] for window in container["windows"]["elements"]]
|
||||
|
||||
def managed(self, workspace: int = 0) -> int:
|
||||
"""The number of windows the daemon has on a workspace of the first monitor."""
|
||||
containers = self._workspace(workspace)["containers"]["elements"]
|
||||
return sum(len(container["windows"]["elements"]) for container in containers)
|
||||
|
||||
def managed_all(self) -> int:
|
||||
"""The number of windows the daemon has, on every workspace of every monitor.
|
||||
|
||||
That is the windows of the containers, the monocle container, the maximized window and
|
||||
the floating windows.
|
||||
"""
|
||||
total = 0
|
||||
for monitor in self.state()["monitors"]["elements"]:
|
||||
for workspace in monitor["workspaces"]["elements"]:
|
||||
for container in workspace["containers"]["elements"]:
|
||||
total += len(container["windows"]["elements"])
|
||||
if workspace["monocle_container"] is not None:
|
||||
total += len(workspace["monocle_container"]["windows"]["elements"])
|
||||
if workspace["maximized_window"] is not None:
|
||||
total += 1
|
||||
total += len(workspace["floating_windows"]["elements"])
|
||||
return total
|
||||
|
||||
def monitor_bridge(self, path: str) -> None:
|
||||
"""Starts recording the bridge's traffic on the session bus to `path`, in the background.
|
||||
|
||||
`dbus-monitor` records every call to the daemon's `org.komorebi.Bridge` interface and every
|
||||
reply on the bus, which [`latency.rounds`](komorebi_vm.latency.rounds) reads.
|
||||
"""
|
||||
rules = "\"type='method_call',interface='org.komorebi.Bridge'\" \"type='method_return'\""
|
||||
self.sh(f"setsid nohup dbus-monitor --session {rules} > {path} 2>&1 < /dev/null &")
|
||||
|
||||
def script_loaded(self, name: str = "komorebi-bridge") -> bool:
|
||||
"""Returns true if and only if KWin runs a script loaded under `name`."""
|
||||
status, out = self.run(
|
||||
"busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting"
|
||||
f" isScriptLoaded s {shlex.quote(name)}"
|
||||
)
|
||||
return status == 0 and out.strip() == "b true"
|
||||
|
||||
def wait_for(
|
||||
self,
|
||||
predicate: Callable[[], bool],
|
||||
timeout: float = 10,
|
||||
interval: float = 0.1,
|
||||
) -> bool:
|
||||
"""Polls `predicate` until it holds or `timeout` seconds (times `scale`) pass."""
|
||||
deadline = time.monotonic() + timeout * self.scale
|
||||
while True:
|
||||
if predicate():
|
||||
return True
|
||||
if time.monotonic() >= deadline:
|
||||
return False
|
||||
time.sleep(interval)
|
||||
|
||||
def has_name(self, name: str) -> bool:
|
||||
"""Returns true if and only if `name` is owned on the session bus."""
|
||||
status, _ = self.run(f"busctl --user --no-pager list | grep -q '^{name} '")
|
||||
return status == 0
|
||||
|
||||
def wid(self, title: str) -> str:
|
||||
"""The id of the first window whose title is exactly `title` (it is not a pattern), or the
|
||||
empty string."""
|
||||
literal = re.sub(r"([\\.+*?()|\[\]{}^$])", r"\\\1", title)
|
||||
pattern = shlex.quote(f"^{literal}$")
|
||||
return self.run(f"kdotool search --name {pattern} | head -1")[1].strip()
|
||||
|
||||
def wid_by_class(self, app: str) -> str:
|
||||
"""The id of the first window whose class is exactly `app`, or the empty string.
|
||||
|
||||
The class is the Wayland app id (`org.kde.konsole`), or the X11 class of a client
|
||||
on XWayland (`XTerm`).
|
||||
"""
|
||||
pattern = shlex.quote(f"^{app}$")
|
||||
return self.run(f"kdotool search --class {pattern} | head -1")[1].strip()
|
||||
|
||||
def rect(self, wid: str) -> Rect:
|
||||
"""The position and size KWin reports for the window, rounded to whole pixels.
|
||||
|
||||
At a fractional scale the frame is not a whole number of pixels in the logical
|
||||
coordinates KWin reports.
|
||||
"""
|
||||
out = self.sh(f"kdotool getwindowgeometry {shlex.quote(wid)}")
|
||||
position = size = None
|
||||
for line in out.splitlines():
|
||||
words = line.split()
|
||||
if words[:1] == ["Position:"]:
|
||||
position = words[1]
|
||||
elif words[:1] == ["Geometry:"]:
|
||||
size = words[1]
|
||||
if position is None or size is None:
|
||||
raise AssertionError(f"no geometry in {out!r}")
|
||||
x, y = (round(float(v)) for v in position.split(","))
|
||||
w, h = (round(float(v)) for v in size.split("x"))
|
||||
return Rect(x, y, w, h)
|
||||
|
||||
def title(self, wid: str) -> str:
|
||||
"""The title of the window."""
|
||||
return self.sh(f"kdotool getwindowname {shlex.quote(wid)}").strip().splitlines()[-1]
|
||||
|
||||
def active(self) -> str:
|
||||
"""The id of the window KWin has focused, or the empty string."""
|
||||
lines = self.run("kdotool getactivewindow")[1].strip().splitlines()
|
||||
return lines[-1] if lines else ""
|
||||
|
||||
def activate(self, wid: str) -> None:
|
||||
"""Asks KWin to give the window the focus, as a click on it would."""
|
||||
self.sh(f"kdotool windowactivate {shlex.quote(wid)}")
|
||||
|
||||
def minimize(self, wid: str) -> None:
|
||||
"""Asks KWin to minimize the window, as its title bar button would."""
|
||||
self.sh(f"kdotool windowminimize {shlex.quote(wid)}")
|
||||
|
||||
def maximize(self, wid: str) -> None:
|
||||
"""Asks KWin to maximize the window both ways, as its title bar button would.
|
||||
|
||||
It is the user's maximize: the daemon is not asked, and learns of it from KWin.
|
||||
"""
|
||||
for state in ("MAXIMIZED_VERT", "MAXIMIZED_HORZ"):
|
||||
self.sh(f"kdotool windowstate --add {state} {shlex.quote(wid)}")
|
||||
|
||||
def unmaximize(self, wid: str) -> None:
|
||||
"""Asks KWin to restore the window from being maximized, as its title bar button would."""
|
||||
for state in ("MAXIMIZED_VERT", "MAXIMIZED_HORZ"):
|
||||
self.sh(f"kdotool windowstate --remove {state} {shlex.quote(wid)}")
|
||||
|
||||
def fullscreen(self, wid: str, on: bool = True) -> None:
|
||||
"""Asks KWin to take the window fullscreen, or with `on` false to bring it back from it.
|
||||
|
||||
It is the user's fullscreen, as the program's own key does it: the daemon is not asked.
|
||||
"""
|
||||
flag = "--add" if on else "--remove"
|
||||
self.sh(f"kdotool windowstate {flag} FULLSCREEN {shlex.quote(wid)}")
|
||||
|
||||
def close(self, wid: str) -> None:
|
||||
"""Asks KWin to close the window, as its title bar button would."""
|
||||
self.sh(f"kdotool windowclose {shlex.quote(wid)}")
|
||||
|
||||
def shot(self, name: str) -> Image.Image:
|
||||
"""Takes a screenshot of the machine's display and returns it, as RGB.
|
||||
|
||||
The file is also kept as `NAME.png` in the test's output directory.
|
||||
"""
|
||||
self.machine.screenshot(name)
|
||||
return Image.open(self.machine.out_dir / f"{name}.png").convert("RGB")
|
||||
|
||||
def desk(self, wid: str) -> int:
|
||||
"""The number of the virtual desktop the window is on, counted from 1 as kdotool counts.
|
||||
|
||||
0 when kdotool cannot say (a window on every desktop, a window that is gone).
|
||||
"""
|
||||
lines = self.run(f"kdotool get_desktop_for_window {shlex.quote(wid)}")[1].split()
|
||||
return int(lines[-1]) if lines and lines[-1].isdigit() else 0
|
||||
|
||||
def shown(self) -> int:
|
||||
"""The number of the virtual desktop KWin shows, counted from 1.
|
||||
|
||||
With per-output virtual desktops, that is the desktop of the output KWin considers
|
||||
active; a suite with one output has no other.
|
||||
"""
|
||||
lines = self.run("kdotool get_desktop")[1].split()
|
||||
return int(lines[-1]) if lines and lines[-1].isdigit() else 0
|
||||
|
||||
def desktops(self) -> int:
|
||||
"""The number of virtual desktops KWin has."""
|
||||
out = self.run(
|
||||
"busctl --user get-property org.kde.KWin /VirtualDesktopManager"
|
||||
" org.kde.KWin.VirtualDesktopManager count"
|
||||
)[1].split()
|
||||
return int(out[-1]) if out and out[-1].isdigit() else 0
|
||||
|
||||
def desktop_names(self) -> list[str]:
|
||||
"""The names of the virtual desktops KWin has, in order.
|
||||
|
||||
The desktop at index `i` is the one `kdotool` calls `i + 1`.
|
||||
"""
|
||||
out = self.run(
|
||||
"busctl --user get-property org.kde.KWin /VirtualDesktopManager"
|
||||
" org.kde.KWin.VirtualDesktopManager desktops"
|
||||
)[1]
|
||||
# `a(uss) 2 0 "id" "Desktop 1" 1 "id" "Desktop 2"`: the signature, how many, then a
|
||||
# position, an id and a name for each
|
||||
words = shlex.split(out)
|
||||
return words[4::3]
|
||||
|
||||
def kwinrc(self, group: str, key: str) -> str | None:
|
||||
"""The value of `key` in `[group]` of the user's `kwinrc`, or None when it is not set."""
|
||||
status, text = self.machine.execute(f"cat /home/{self.user}/.config/kwinrc")
|
||||
if status != 0:
|
||||
return None
|
||||
current = None
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("[") and line.endswith("]"):
|
||||
current = line[1:-1]
|
||||
elif current == group and "=" in line:
|
||||
name, value = line.split("=", 1)
|
||||
if name.strip() == key:
|
||||
return value.strip()
|
||||
return None
|
||||
|
||||
def kwinrc_group(self, group: str) -> dict[str, str]:
|
||||
"""Every key of `[group]` of the user's `kwinrc` with its value, empty when there is none.
|
||||
|
||||
A suite that wants to know that komorebi put the user's settings back compares this before
|
||||
and after.
|
||||
"""
|
||||
status, text = self.machine.execute(f"cat /home/{self.user}/.config/kwinrc")
|
||||
keys: dict[str, str] = {}
|
||||
if status != 0:
|
||||
return keys
|
||||
current = None
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("[") and line.endswith("]"):
|
||||
current = line[1:-1]
|
||||
elif current == group and "=" in line:
|
||||
name, value = line.split("=", 1)
|
||||
keys[name.strip()] = value.strip()
|
||||
return keys
|
||||
|
||||
def effect_supported(self, name: str) -> bool:
|
||||
"""Returns true if and only if KWin found the effect installed when it started."""
|
||||
return self._effects("isEffectSupported", name)
|
||||
|
||||
def effect_loaded(self, name: str) -> bool:
|
||||
"""Returns true if and only if KWin has the effect loaded."""
|
||||
return self._effects("isEffectLoaded", name)
|
||||
|
||||
def unload_effect(self, name: str) -> None:
|
||||
"""Asks KWin to unload the effect, whoever loaded it."""
|
||||
self.sh(
|
||||
"busctl --user call org.kde.KWin /Effects org.kde.kwin.Effects unloadEffect s"
|
||||
f" {shlex.quote(name)}"
|
||||
)
|
||||
|
||||
def kwin_script(self, name: str, source: str, *, keep: bool = False) -> list[str]:
|
||||
"""Runs `source` as the KWin script `name` and returns the lines it reported.
|
||||
|
||||
The script reports with `report(...)`, which writes its arguments to KWin's log as one
|
||||
line marked with `name`, and ends with `report("done")`, which the lines are waited for.
|
||||
The script is unloaded afterwards, unless `keep` is set: a script that connects to a
|
||||
signal goes on reporting, and [`Kde.kwin_reports`][] reads what it reported since.
|
||||
"""
|
||||
path = f"/tmp/kwin-script-{name}.js"
|
||||
prelude = (
|
||||
"function report() { print("
|
||||
+ json.dumps(f"KS:{name} ")
|
||||
+ " + Array.prototype.slice.call(arguments).join(' ')); }\n"
|
||||
)
|
||||
self.as_user(f"printf %s {shlex.quote(prelude + source)} > {path}")
|
||||
reply = self.sh(
|
||||
"busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting loadScript ss"
|
||||
f" {path} {shlex.quote(name)}"
|
||||
).split()
|
||||
script = f"/Scripting/Script{reply[-1]}"
|
||||
self.sh(f"busctl --user call org.kde.KWin {script} org.kde.kwin.Script run")
|
||||
if not self.wait_for(lambda: "done" in self.kwin_reports(name)):
|
||||
raise AssertionError(f"the KWin script {name} never reported it was done")
|
||||
if not keep:
|
||||
self.sh(
|
||||
"busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting unloadScript s"
|
||||
f" {shlex.quote(name)}"
|
||||
)
|
||||
return [line for line in self.kwin_reports(name) if line != "done"]
|
||||
|
||||
_screens_cache: tuple[float, list[tuple[Rect, Rect]] | None] | None = None
|
||||
|
||||
def invalidate_screens(self) -> None:
|
||||
"""Forgets what [`Kde.screens`][] last said: the outputs changed."""
|
||||
self._screens_cache = None
|
||||
|
||||
def screens(self) -> list[tuple[Rect, Rect]] | None:
|
||||
"""What KWin says of each enabled output, left to right: its rectangle in the coordinates
|
||||
of the desktop, and the area of it that windows may take (KWin's placement area: the
|
||||
output less the panels, as the daemon's bridge reads it). `None` when KWin does not say.
|
||||
|
||||
A KWin script asks, because `kdotool` has no call for either, and a script is slow, so the
|
||||
answer is kept for a second, and forgotten when the outputs are changed through
|
||||
[`Outputs`][].
|
||||
"""
|
||||
now = time.monotonic()
|
||||
if self._screens_cache is not None and now - self._screens_cache[0] < SCREENS_TTL:
|
||||
return self._screens_cache[1]
|
||||
found = self._read_screens()
|
||||
self._screens_cache = (time.monotonic(), found)
|
||||
return found
|
||||
|
||||
def _read_screens(self) -> list[tuple[Rect, Rect]] | None:
|
||||
source = """
|
||||
for (var i = 0; i < workspace.screens.length; i++) {
|
||||
var s = workspace.screens[i];
|
||||
var g = s.geometry;
|
||||
var a = workspace.clientArea(
|
||||
KWin.PlacementArea, s, workspace.currentDesktopForScreen(s));
|
||||
report("screen", Math.round(g.x), Math.round(g.y), Math.round(g.width),
|
||||
Math.round(g.height), Math.round(a.x), Math.round(a.y), Math.round(a.width),
|
||||
Math.round(a.height));
|
||||
}
|
||||
report("done");
|
||||
"""
|
||||
try:
|
||||
lines = self.kwin_script(f"screens-{next(_PROBES)}", source)
|
||||
except AssertionError:
|
||||
return None
|
||||
found: list[tuple[Rect, Rect]] = []
|
||||
for line in lines:
|
||||
words = line.split()
|
||||
if words[:1] != ["screen"] or len(words) != 9:
|
||||
continue
|
||||
try:
|
||||
n = [int(word) for word in words[1:]]
|
||||
except ValueError:
|
||||
return None
|
||||
if n[2] <= 0 or n[3] <= 0 or n[6] <= 0 or n[7] <= 0:
|
||||
return None
|
||||
found.append((Rect(*n[0:4]), Rect(*n[4:8])))
|
||||
found.sort(key=lambda pair: (pair[0].x, pair[0].y))
|
||||
return found or None
|
||||
|
||||
def work_area(self) -> Rect | None:
|
||||
"""The area of the first (leftmost) output that windows may take, as KWin has it, or `None`
|
||||
when KWin does not say ([`Kde.screens`][])."""
|
||||
screens = self.screens()
|
||||
return screens[0][1] if screens else None
|
||||
|
||||
def kwin_reports(self, name: str) -> list[str]:
|
||||
"""Every line the KWin script `name` has reported so far ([`Kde.kwin_script`][])."""
|
||||
mark = f"KS:{name} "
|
||||
# the guest picks the lines: the whole journal of the user, read back through the test
|
||||
# driver on every call, is what made a run slower the longer it went
|
||||
log = self.machine.execute(
|
||||
f"journalctl _UID={self.uid} --no-pager -o cat | grep -F {shlex.quote(mark)}"
|
||||
)[1]
|
||||
return [line.split(mark, 1)[1] for line in log.splitlines() if mark in line]
|
||||
|
||||
@property
|
||||
def outputs(self) -> Outputs:
|
||||
"""The session's outputs: `kde.outputs()` is how many are enabled, and `kde.outputs` has
|
||||
the ones to enable, disable and scale ([`Outputs`][])."""
|
||||
return Outputs(self)
|
||||
|
||||
def _effects(self, method: str, name: str) -> bool:
|
||||
"""Asks KWin's `/Effects` object a yes or no question about the effect `name`."""
|
||||
status, out = self.run(
|
||||
f"busctl --user call org.kde.KWin /Effects org.kde.kwin.Effects {method} s"
|
||||
f" {shlex.quote(name)}"
|
||||
)
|
||||
return status == 0 and out.strip() == "b true"
|
||||
|
||||
def _workspace(self, workspace: int) -> dict[str, Any]:
|
||||
return self.state()["monitors"]["elements"][0]["workspaces"]["elements"][workspace]
|
||||
|
||||
def _wrap(self, command: str, session: bool = True) -> str:
|
||||
env = self.env if session else f"XDG_RUNTIME_DIR={shlex.quote(self.runtime)}"
|
||||
return f"runuser -u {self.user} -- env {env} sh -c {shlex.quote(command)}"
|
||||
@@ -0,0 +1,300 @@
|
||||
"""KDE as a [`Platform`](komorebi_vm.core.platform.Platform): a `Kde` session, seen through the
|
||||
neutral vocabulary."""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import shlex
|
||||
from typing import Any
|
||||
from urllib.parse import unquote
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from komorebi_vm.core import snapshot
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client, OsWindow, Predicate
|
||||
from komorebi_vm.core.platform import Pointer as PointerDevice
|
||||
from komorebi_vm.core.scenarios.resize import outside_grab
|
||||
from komorebi_vm.core.snapshot import Snapshot
|
||||
from komorebi_vm.kde import Kde
|
||||
|
||||
# foot sizes itself to whole cells of its font, so its frame can be short of the one asked for
|
||||
CELL = 24
|
||||
# the desktop that komorebi puts the windows it hides on, which is the last one
|
||||
PARK = "komorebi-park"
|
||||
# the file the daemon is started with, and where a program with a name of its own is made
|
||||
CONFIG = "/tmp/e2e-restart-config.json"
|
||||
BIN = "/tmp/e2e-bin"
|
||||
# what a program name may be made of: the same on every platform, so that a scenario cannot pass
|
||||
# one that another port rejects
|
||||
PROGRAM = re.compile(r"[A-Za-z0-9_-]+")
|
||||
|
||||
|
||||
class KdePlatform:
|
||||
"""The platform of a headless KWin session of the test machine."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
kde: Kde,
|
||||
size: tuple[int, int],
|
||||
pointer: PointerDevice | None = None,
|
||||
session: bool = False,
|
||||
) -> None:
|
||||
"""`session` is for a real Plasma session, which has a lock screen; the headless KWin of
|
||||
the other suites has none."""
|
||||
self.kde = kde
|
||||
self.session = session
|
||||
self.size = size
|
||||
self._pointer = pointer
|
||||
|
||||
def has(self, feature: str) -> bool:
|
||||
if feature == "lock":
|
||||
return self.session
|
||||
return feature == "pointer" and self._pointer is not None
|
||||
|
||||
@property
|
||||
def pointer(self) -> PointerDevice:
|
||||
if self._pointer is None:
|
||||
raise AssertionError("this session has no pointer device")
|
||||
return self._pointer
|
||||
|
||||
@property
|
||||
def tolerance(self) -> int:
|
||||
return CELL
|
||||
|
||||
def wait_for(self, predicate: Predicate, timeout: float = 10) -> bool:
|
||||
return self.kde.wait_for(predicate, timeout=timeout)
|
||||
|
||||
def start_komorebi(self) -> None:
|
||||
# a unit that is still stopping is not started again by `systemctl start`
|
||||
self.kde.wait_for(lambda: not self.kde.komorebi_running(), timeout=30)
|
||||
self.kde.start_komorebi()
|
||||
status = self.kde.wait_for(lambda: self.kde.run("komorebic state")[0] == 0, timeout=30)
|
||||
if not status:
|
||||
tail = "\n".join(self.kde.komorebi_log().splitlines()[-30:])
|
||||
raise AssertionError(f"the daemon did not answer komorebic; its log ends:\n{tail}")
|
||||
|
||||
def crash(self) -> None:
|
||||
self.kde.kill_komorebi()
|
||||
|
||||
def _restart_the_modules_daemon(self, config: dict[str, Any]) -> None:
|
||||
"""A real Plasma session has the module's unit run the daemon, with the user's own
|
||||
`komorebi.json`. The unit `komorebi@session` of a headless run has a bus of its own,
|
||||
and a daemon on it has no Plasma shell to talk to."""
|
||||
kde = self.kde
|
||||
kde.systemctl("stop", "komorebi.service")
|
||||
kde.wait_for(lambda: kde.run("komorebic state")[0] != 0, timeout=30)
|
||||
kde.close_colored_windows()
|
||||
kde.sh("mkdir -p ~/.config/komorebi")
|
||||
kde.sh(f"printf %s {shlex.quote(json.dumps(config))} > ~/.config/komorebi/komorebi.json")
|
||||
kde.systemctl("start", "komorebi.service")
|
||||
if not kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=60):
|
||||
raise AssertionError("the module's daemon did not answer komorebic")
|
||||
|
||||
def restart_with(self, config: dict[str, Any]) -> None:
|
||||
if self.session:
|
||||
self._restart_the_modules_daemon(config)
|
||||
return
|
||||
if self.kde.komorebi_running():
|
||||
self.kde.komorebic("stop")
|
||||
self.kde.wait_for(lambda: not self.kde.komorebi_running(), timeout=30)
|
||||
self.rewrite_config(config)
|
||||
self.kde.start_komorebi("--config", CONFIG)
|
||||
if not self.kde.wait_for(lambda: self.kde.run("komorebic state")[0] == 0, timeout=30):
|
||||
raise AssertionError("the daemon did not answer komorebic")
|
||||
|
||||
def rewrite_config(self, config: dict[str, Any]) -> None:
|
||||
self.kde.sh(f"printf %s {shlex.quote(json.dumps(config))} > {CONFIG}")
|
||||
|
||||
def komorebic(self, *args: str) -> str:
|
||||
return self.kde.komorebic(*args)
|
||||
|
||||
def komorebic_status(self, *args: str) -> tuple[int, str]:
|
||||
return self.kde.run(shlex.join(["komorebic", *args]))
|
||||
|
||||
def temp_path(self, name: str) -> str:
|
||||
return f"/tmp/{name}"
|
||||
|
||||
def state(self) -> Snapshot:
|
||||
return snapshot.parse(self.kde.state())
|
||||
|
||||
def spawn(
|
||||
self,
|
||||
title: str,
|
||||
app_id: str | None = None,
|
||||
exe: str | None = None,
|
||||
rename_to: str | None = None,
|
||||
after: float = 0,
|
||||
) -> Client:
|
||||
name = f"-a {shlex.quote(app_id)} " if app_id else ""
|
||||
program = "foot"
|
||||
if exe is not None:
|
||||
if not PROGRAM.fullmatch(exe):
|
||||
raise ValueError(f"not a program name: {exe!r}")
|
||||
# the daemon reads the executable from /proc, where a link shows its target: a copy
|
||||
# of the terminal is what has the name, made once: a copy that is running cannot be
|
||||
# written over
|
||||
program = f"{BIN}/{exe}"
|
||||
self.kde.sh(
|
||||
f"mkdir -p {BIN} && {{ test -x {program} || cp -L $(command -v foot) {program}; }}"
|
||||
)
|
||||
command = "sleep 3000"
|
||||
if rename_to is not None:
|
||||
# foot takes the title from the terminal escape OSC 0
|
||||
script = f'sleep {after}; printf "\\033]0;{rename_to}\\007"; sleep 3000'
|
||||
command = f"sh -c {shlex.quote(script)}"
|
||||
self.kde.spawn(f"{program} {name}-T {shlex.quote(title)} {command}")
|
||||
if not self.kde.wait_for(lambda: self.kde.wid(title) != "", timeout=30):
|
||||
raise AssertionError(f"no window titled {title!r} appeared")
|
||||
return Client(title)
|
||||
|
||||
def _wid(self, client: Client) -> str:
|
||||
"""The id of the window of `client`, which has to exist: a command for a window that is
|
||||
not there fails, as it does on every platform."""
|
||||
wid = self.kde.wid(client.title)
|
||||
if wid == "":
|
||||
raise AssertionError(f"no window titled {client.title!r}")
|
||||
return wid
|
||||
|
||||
def exe_id(self, program: str) -> str:
|
||||
return program
|
||||
|
||||
def os_window(self, client: Client) -> OsWindow | None:
|
||||
wid = self.kde.wid(client.title)
|
||||
if wid == "":
|
||||
return None
|
||||
return OsWindow(client.title, self.kde.rect(wid), self.kde.active() == wid)
|
||||
|
||||
def hidden(self, client: Client) -> bool:
|
||||
"""The window is on the parking desktop, or on a desktop that is not the one in view.
|
||||
|
||||
KDE keeps the windows of a workspace on a virtual desktop of its own and parks the ones a
|
||||
stack or a monocle puts away, so both are out of sight. That is every window that is on a
|
||||
desktop that is not shown, whoever put it there: this is the quirk
|
||||
`Platform.hidden` warns of. With more than one output, the desktop in view is that of
|
||||
the output KWin considers active, so only the windows of the first are certain.
|
||||
"""
|
||||
wid = self.kde.wid(client.title)
|
||||
if wid == "":
|
||||
return False
|
||||
desk = self.kde.desk(wid)
|
||||
names = self.kde.desktop_names()
|
||||
if PARK in names and desk == names.index(PARK) + 1:
|
||||
return True
|
||||
return desk != 0 and desk != self.kde.shown()
|
||||
|
||||
def displays(self) -> list[Rect]:
|
||||
"""The enabled outputs, as KWin has them, left to right.
|
||||
|
||||
Where KWin does not say, they are the size the session was started with, side by side
|
||||
from the left (at the scale of 1 that a scenario leaves them at).
|
||||
"""
|
||||
screens = self.kde.screens()
|
||||
if screens:
|
||||
return [display for display, _ in screens]
|
||||
width, height = self.size
|
||||
return [Rect(i * width, 0, width, height) for i in range(len(self.kde.outputs.names()))]
|
||||
|
||||
def add_display(self) -> None:
|
||||
"""Enables an output that was disabled, which is as near to a plug as KWin gets."""
|
||||
disabled = self.kde.outputs.names(enabled=False)
|
||||
if not disabled:
|
||||
raise AssertionError("every output is plugged in")
|
||||
self.kde.outputs.enable(disabled[0])
|
||||
self.kde.wait_for(lambda: self.kde.outputs() == len(self.kde.outputs.names()), timeout=20)
|
||||
|
||||
def remove_display(self) -> None:
|
||||
"""Disables the last of the enabled outputs, which is KWin's way to unplug one."""
|
||||
names = self.kde.outputs.names()
|
||||
if len(names) < 2:
|
||||
raise AssertionError("there is only one output to remove")
|
||||
self.kde.outputs.disable(names[-1])
|
||||
self.kde.wait_for(lambda: len(self.kde.outputs.names()) == len(names) - 1, timeout=20)
|
||||
|
||||
def resizable_display(self) -> int | None:
|
||||
"""None: the outputs of the headless KWin are virtual and have the one mode they were
|
||||
started with (`kscreen-doctor` can only change their scale, which is not a mode)."""
|
||||
return None
|
||||
|
||||
def resize_display(self, index: int, width: int, height: int) -> None:
|
||||
raise AssertionError("no output of this session has another mode to change to")
|
||||
|
||||
def close(self, client: Client) -> None:
|
||||
self.kde.close(self._wid(client))
|
||||
|
||||
def _session_id(self) -> str:
|
||||
"""The id of the user's Wayland session, which is the one that gets locked."""
|
||||
for line in self.kde.sh("loginctl list-sessions --no-legend").splitlines():
|
||||
words = line.split()
|
||||
if len(words) > 2 and words[2] == self.kde.user:
|
||||
shown = self.kde.sh(f"loginctl show-session {words[0]} -p Type --value")
|
||||
if shown.strip() == "wayland":
|
||||
return words[0]
|
||||
raise AssertionError("the user has no Wayland session")
|
||||
|
||||
def _locked(self, locked: bool) -> bool:
|
||||
shown = self.kde.sh(f"loginctl show-session {self._session_id()} -p LockedHint --value")
|
||||
return (shown.strip() == "yes") == locked
|
||||
|
||||
def lock(self) -> None:
|
||||
self.kde.sh(f"loginctl lock-session {self._session_id()}")
|
||||
if not self.kde.wait_for(lambda: self._locked(True), timeout=30):
|
||||
raise AssertionError("the screen did not lock")
|
||||
|
||||
def unlock(self) -> None:
|
||||
self.kde.sh(f"loginctl unlock-session {self._session_id()}")
|
||||
if not self.kde.wait_for(lambda: self._locked(False), timeout=30):
|
||||
raise AssertionError("the screen did not unlock")
|
||||
|
||||
def put_file(self, path: str, data: bytes) -> None:
|
||||
directory = shlex.quote(path.rsplit("/", 1)[0])
|
||||
encoded = base64.b64encode(data).decode()
|
||||
self.kde.sh(f"mkdir -p {directory} && chmod a+rx {directory}")
|
||||
self.kde.sh(
|
||||
f"echo {encoded} | base64 -d > {shlex.quote(path)} && chmod a+r {shlex.quote(path)}"
|
||||
)
|
||||
|
||||
def wallpaper(self, display: int = 0) -> str:
|
||||
shell = "org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell"
|
||||
out = self.kde.run(f"busctl --user call {shell} wallpaper u {display}")[1]
|
||||
image = re.search(r'"Image" s "([^"]*)"', out)
|
||||
url = image.group(1) if image else ""
|
||||
return unquote(url.removeprefix("file://"))
|
||||
|
||||
def set_wallpaper(self, path: str, display: int = 0) -> None:
|
||||
"""The shell may still be starting, or busy: the call is made again until it takes it."""
|
||||
command = f"plasma-apply-wallpaperimage {shlex.quote(path)}"
|
||||
if not self.kde.wait_for(lambda: self.kde.run(command)[0] == 0, timeout=60):
|
||||
raise AssertionError(f"the Plasma shell did not take the wallpaper {path}")
|
||||
|
||||
def resize_grab(self, frame: Rect, grab: str) -> tuple[int, int]:
|
||||
return outside_grab(frame, grab)
|
||||
|
||||
def move_window(self, client: Client, x: int, y: int) -> None:
|
||||
self.kde.sh(f"kdotool windowmove {self._wid(client)} {x} {y}")
|
||||
|
||||
def fullscreen(self, client: Client, on: bool = True) -> None:
|
||||
self.kde.fullscreen(self.kde.wid(client.title), on)
|
||||
|
||||
def user_maximize(self, client: Client, on: bool = True) -> None:
|
||||
wid = self.kde.wid(client.title)
|
||||
self.kde.maximize(wid) if on else self.kde.unmaximize(wid)
|
||||
|
||||
def work_area(self) -> Rect:
|
||||
"""What KWin says windows may take of the first output, which is the output less the
|
||||
panels and docks the shell has made (a headless session has none, so it is all of it).
|
||||
|
||||
Where KWin does not answer, the first output whole: a scenario then checks less, and does
|
||||
not fail for it.
|
||||
"""
|
||||
area = self.kde.work_area()
|
||||
return area if area is not None else Rect(0, 0, *self.size)
|
||||
|
||||
def minimize(self, client: Client) -> None:
|
||||
self.kde.minimize(self._wid(client))
|
||||
|
||||
def activate(self, client: Client) -> None:
|
||||
self.kde.activate(self._wid(client))
|
||||
|
||||
def screenshot(self, name: str) -> Image.Image:
|
||||
return self.kde.shot(name)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Key presses on the test machine's keyboard, as a person types them."""
|
||||
|
||||
from komorebi_vm.machine import Machine
|
||||
|
||||
# QEMU names the left Super key `meta_l`; the others are named as KDE writes them
|
||||
_MODIFIERS = {
|
||||
"alt": "alt",
|
||||
"ctrl": "ctrl",
|
||||
"shift": "shift",
|
||||
"meta": "meta_l",
|
||||
"super": "meta_l",
|
||||
}
|
||||
|
||||
|
||||
class Keys:
|
||||
"""The keyboard of a test machine.
|
||||
|
||||
A key press goes through QEMU's virtual keyboard (`machine.send_key`), so it
|
||||
reaches the guest's kernel as a key of a real keyboard and KWin sees it as
|
||||
it sees any other: a global shortcut fires on it, and a key that is not one
|
||||
goes to the focused window. QEMU holds the keys for 100 ms, less than the
|
||||
delay before a key repeats.
|
||||
|
||||
A combo is written as in KDE, in lower case, with `-` between the keys:
|
||||
`alt-h`, `meta-shift-j`, `esc`. The key names after the modifiers are
|
||||
QEMU's (`h`, `1`, `esc`, `ret`, `bracket_left`).
|
||||
"""
|
||||
|
||||
def __init__(self, machine: Machine) -> None:
|
||||
self.machine = machine
|
||||
|
||||
@staticmethod
|
||||
def qemu(combo: str) -> str:
|
||||
"""Returns `combo` as QEMU's `sendkey` writes it.
|
||||
|
||||
A modifier is any of `alt`, `ctrl`, `shift`, `meta` and `super`; the
|
||||
last word is the key, which QEMU must know.
|
||||
"""
|
||||
*modifiers, key = combo.lower().split("-")
|
||||
for modifier in modifiers:
|
||||
if modifier not in _MODIFIERS:
|
||||
raise ValueError(f"{modifier!r} in {combo!r} is not a modifier")
|
||||
if not key:
|
||||
raise ValueError(f"{combo!r} has no key")
|
||||
return "-".join([*(_MODIFIERS[m] for m in modifiers), key])
|
||||
|
||||
def send(self, combo: str) -> None:
|
||||
"""Presses the keys of `combo` together, and releases them."""
|
||||
self.machine.send_key(self.qemu(combo))
|
||||
@@ -0,0 +1,133 @@
|
||||
"""How long the commands of the daemon take to reach the windows of KWin.
|
||||
|
||||
[`Kde.monitor_bridge`](komorebi_vm.kde.Kde.monitor_bridge) records the bridge's
|
||||
traffic on the session bus with `dbus-monitor`: every `Event` call the script
|
||||
makes, with its JSON, and every reply on the bus, among them the daemon's answers
|
||||
to `Poll`, which carry the commands. Each line `dbus-monitor` prints for a message
|
||||
has the time the bus delivered it to the monitor.
|
||||
|
||||
A **round** starts when the daemon answers `Poll` with a batch that asks for a
|
||||
window to be somewhere it was not asked to be before, and ends with the last
|
||||
`geometry` event KWin reports for one of those windows before the next such batch
|
||||
(or within a cut-off). Its duration is how long the windows took to be where the
|
||||
daemon put them, the client's answer included.
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
|
||||
_HEADER = re.compile(r"^(method call|method return|signal|error) time=(\d+\.\d+) (.*)$")
|
||||
_STRING = ' string "'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Message:
|
||||
"""One D-Bus message, as `dbus-monitor` printed it."""
|
||||
|
||||
kind: str
|
||||
"""`method call`, `method return`, `signal` or `error`."""
|
||||
time: float
|
||||
"""When the bus delivered it, in seconds since the epoch."""
|
||||
member: str
|
||||
"""The method or signal, or the empty string for a reply."""
|
||||
body: str
|
||||
"""The first string argument, or the empty string."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Round:
|
||||
"""The windows of one batch of commands, from the batch to the last frame KWin reported."""
|
||||
|
||||
sent: float
|
||||
"""When the daemon's answer to `Poll` was delivered."""
|
||||
windows: int
|
||||
"""How many windows the batch moved."""
|
||||
seconds: float | None
|
||||
"""How long until the last of them reported its frame, or `None` if one never did."""
|
||||
|
||||
|
||||
def messages(text: str) -> list[Message]:
|
||||
"""Parses what `dbus-monitor` printed, in its default format."""
|
||||
out: list[Message] = []
|
||||
header: re.Match[str] | None = None
|
||||
body = ""
|
||||
|
||||
def flush() -> None:
|
||||
if header is not None:
|
||||
fields = header.group(3)
|
||||
member = re.search(r"member=(\S+)", fields)
|
||||
out.append(
|
||||
Message(header.group(1), float(header.group(2)), member[1] if member else "", body)
|
||||
)
|
||||
|
||||
for line in text.splitlines():
|
||||
if match := _HEADER.match(line):
|
||||
flush()
|
||||
header, body = match, ""
|
||||
elif header is not None and not body and line.startswith(_STRING) and line.endswith('"'):
|
||||
body = line[len(_STRING) : -1]
|
||||
flush()
|
||||
return out
|
||||
|
||||
|
||||
def _json(text: str) -> Any:
|
||||
try:
|
||||
return json.loads(text)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def rounds(text: str, cut_off: float = 2.0) -> list[Round]:
|
||||
"""Returns every round in what `dbus-monitor` printed, in order.
|
||||
|
||||
A batch that asks every window for the frame it was last asked for moves
|
||||
nothing, and is not a round. A round ends at the next round, or `cut_off`
|
||||
seconds after it started, whichever comes first.
|
||||
"""
|
||||
batches: list[tuple[float, dict[str, Rect]]] = []
|
||||
frames: list[tuple[float, str]] = []
|
||||
for message in messages(text):
|
||||
value = _json(message.body)
|
||||
if message.kind == "method return" and isinstance(value, list):
|
||||
geo = {
|
||||
command["id"]: Rect(command["x"], command["y"], command["w"], command["h"])
|
||||
for batch in value
|
||||
if isinstance(batch, dict)
|
||||
for command in batch.get("cmds", [])
|
||||
if command.get("op") == "geo"
|
||||
}
|
||||
if geo:
|
||||
batches.append((message.time, geo))
|
||||
elif message.member == "Event" and isinstance(value, dict):
|
||||
if value.get("type") == "geometry":
|
||||
frames.append((message.time, value["id"]))
|
||||
|
||||
asked: dict[str, Rect] = {}
|
||||
moving: list[tuple[float, set[str]]] = []
|
||||
for sent, geo in batches:
|
||||
moved = {uuid for uuid, rect in geo.items() if asked.get(uuid) != rect}
|
||||
asked.update(geo)
|
||||
if moved:
|
||||
moving.append((sent, moved))
|
||||
|
||||
out = []
|
||||
for i, (sent, moved) in enumerate(moving):
|
||||
end = sent + cut_off
|
||||
if i + 1 < len(moving):
|
||||
end = min(end, moving[i + 1][0])
|
||||
last = {uuid: t for t, uuid in frames if sent < t <= end and uuid in moved}
|
||||
seconds = max(last.values()) - sent if len(last) == len(moved) else None
|
||||
out.append(Round(sent, len(moved), seconds))
|
||||
return out
|
||||
|
||||
|
||||
def percentile(values: list[float], fraction: float) -> float:
|
||||
"""The value below which `fraction` of the values are (nearest rank)."""
|
||||
ordered = sorted(values)
|
||||
rank = min(len(ordered), max(1, math.ceil(fraction * len(ordered))))
|
||||
return ordered[rank - 1]
|
||||
@@ -0,0 +1,44 @@
|
||||
"""The part of the NixOS test driver's `Machine` that the library uses.
|
||||
|
||||
The driver's own class is not importable outside a test run, so the library
|
||||
depends on this protocol instead, and its unit tests pass a fake. The methods
|
||||
take only what the library passes; the driver's accept more (a timeout, whether
|
||||
to check the exit status), which does not stop its class from satisfying the
|
||||
protocol.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
class Machine(Protocol):
|
||||
"""A virtual machine the test can run commands on, as root."""
|
||||
|
||||
@property
|
||||
def out_dir(self) -> Path:
|
||||
"""The directory that screenshots and other artifacts go to."""
|
||||
...
|
||||
|
||||
def execute(self, command: str, /) -> tuple[int, str]:
|
||||
"""Runs `command` and returns its exit status and its output."""
|
||||
...
|
||||
|
||||
def succeed(self, *commands: str) -> str:
|
||||
"""Runs each command and fails the test unless it exits with status 0."""
|
||||
...
|
||||
|
||||
def fail(self, *commands: str) -> str:
|
||||
"""Runs each command and fails the test if it exits with status 0."""
|
||||
...
|
||||
|
||||
def copy_from_machine(self, source: str, /) -> None:
|
||||
"""Copies the file `source` of the machine into `out_dir`, under its own name."""
|
||||
...
|
||||
|
||||
def screenshot(self, filename: str, /) -> None:
|
||||
"""Saves a PNG of the machine's display as `filename` in `out_dir`."""
|
||||
...
|
||||
|
||||
def send_key(self, key: str, /) -> None:
|
||||
"""Presses the keys `key` names together on the machine's keyboard (QEMU's `sendkey`)."""
|
||||
...
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,7 @@
|
||||
"""What only KDE can check, each file after the shared scenario of the same name.
|
||||
|
||||
An extra has the shape of a scenario, `run(platform: KdePlatform, checks, ...)`, and takes the
|
||||
concrete platform so that it can use `platform.kde`: `kscreen-doctor`, `kdotool`, the daemon's log.
|
||||
A suite runs it with `platform_only("kde", ...)`. It does not repeat a check the shared scenario
|
||||
makes.
|
||||
"""
|
||||
@@ -0,0 +1,225 @@
|
||||
r"""`komorebic check` against a real (headless) KWin: what it finds of the desktop, and what it says
|
||||
when something is missing: no Plasma shell for the wallpapers, a stock effect shadowing komorebi's
|
||||
own, komorebi without its script in KWin, komorebi not running, no KWin on the bus. What only a
|
||||
real KWin can tell: that its version is read from what KWin says of itself, that the effects are
|
||||
komorebi's builds because of what they contain, that a daemon is told from its script by KWin's
|
||||
own answer, that a bus with no KWin on it is an error with an exit status that says so, and that
|
||||
the shortcut files the check compares with are in the directory `komorebic hotkeys compile`
|
||||
writes to in a session. The configuration and the exit status are covered by
|
||||
`komorebi/src/check.rs` and `komorebic/tests/linux_check.rs`, against no desktop.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import shlex
|
||||
import struct
|
||||
import zlib
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `check`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
kde = Kde.headless(machine, "main", size=(1920, 1080), scale=SCALE)
|
||||
|
||||
CONFIG = "/tmp/check-config.json"
|
||||
EMPTY_BUS = "/tmp/check-empty.bus"
|
||||
FLAT = "/tmp/check-flat.png"
|
||||
|
||||
def flat_png() -> bytes:
|
||||
"""A picture of one color all over: a wallpaper no theme can be made from."""
|
||||
raw = b"".join(b"\x00" + bytes([200, 40, 40]) * 8 for _ in range(8))
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
body = kind + data
|
||||
return (
|
||||
struct.pack(">I", len(data))
|
||||
+ body
|
||||
+ struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)
|
||||
)
|
||||
|
||||
header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", header)
|
||||
+ chunk(b"IDAT", zlib.compress(raw))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
kde.sh(f"echo {base64.b64encode(flat_png()).decode()} | base64 -d > {FLAT}")
|
||||
# borders and animation, which want their effects; a wallpaper, which wants the Plasma shell and
|
||||
# cannot make a theme; one workspace that is a layout and one that is only a name, which komorebi
|
||||
# does not tile
|
||||
kde.sh(
|
||||
"printf %s "
|
||||
+ shlex.quote(
|
||||
json.dumps(
|
||||
{
|
||||
"border": True,
|
||||
"animation": {"enabled": True, "style": "Linear"},
|
||||
"monitors": [
|
||||
{
|
||||
"wallpaper": {"path": FLAT},
|
||||
"workspaces": [{"name": "a", "layout": "BSP"}, {"name": "b"}],
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
+ f" > {CONFIG}"
|
||||
)
|
||||
|
||||
def check(bus: str | None = None, data_home: str | None = None) -> tuple[int, str]:
|
||||
"""Runs `komorebic check` on the session's bus, or on the bus at `bus`, with `data_home` as the
|
||||
user's data directory when KWin's environment does not name one."""
|
||||
prefix = f"DBUS_SESSION_BUS_ADDRESS=unix:path={bus} " if bus else ""
|
||||
prefix += f"XDG_DATA_HOME={data_home} " if data_home else ""
|
||||
status, out = kde.run(f"{prefix}komorebic check --komorebi-config {CONFIG}")
|
||||
print(out)
|
||||
return status, out
|
||||
|
||||
print("== 1. a desktop that is as it should be, with komorebi running")
|
||||
kde.start_komorebi("--config", CONFIG)
|
||||
checks.check(
|
||||
"the daemon answers komorebic",
|
||||
kde.wait_for(lambda: kde.run("komorebic state")[0] == 0, timeout=30),
|
||||
)
|
||||
checks.check("its script is in KWin", kde.wait_for(kde.script_loaded, timeout=30))
|
||||
status, out = check()
|
||||
checks.check("it passes: no errors", status == 0 and "\n0 error(s)" in out)
|
||||
checks.check(
|
||||
"it knows this is a KDE Plasma session on Wayland",
|
||||
"this is a KDE Plasma session" in out and "it is a Wayland session" in out,
|
||||
)
|
||||
checks.check("it knows KWin 6", re.search(r"ok +KWin 6\.", out) is not None)
|
||||
checks.check(
|
||||
"it sees komorebi, and its script in KWin",
|
||||
"komorebi is running, and its script is in KWin" in out,
|
||||
)
|
||||
checks.check(
|
||||
"it says what starts komorebi at login",
|
||||
re.search(r"ok +komorebi is started at login by ", out) is not None,
|
||||
)
|
||||
checks.check(
|
||||
"the border effect is komorebi's build",
|
||||
"the border effect is komorebi's build" in out,
|
||||
)
|
||||
checks.check(
|
||||
"the animation effect is komorebi's build",
|
||||
"the animation effect is komorebi's build" in out,
|
||||
)
|
||||
checks.check(
|
||||
"the configuration is read, and the workspace that is only a name is found",
|
||||
'workspace 1 of monitor 0 ("b") has no `layout`' in out,
|
||||
)
|
||||
checks.check(
|
||||
"wallpapers need the Plasma shell, which a headless KWin does not have",
|
||||
"the Plasma shell is not on the bus" in out,
|
||||
)
|
||||
checks.check(
|
||||
"a picture of one color cannot make a theme",
|
||||
f"no theme can be made from {FLAT}" in out,
|
||||
)
|
||||
|
||||
print("== 2. the stock animation effect in the user's own directory hides komorebi's")
|
||||
DATA = "/tmp/check-data"
|
||||
STOCK = f"{DATA}/kwin/effects/kwin4_effect_geometry_change/contents/code"
|
||||
kde.sh(f"mkdir -p {STOCK} && echo 'curve: QEasingCurve.OutExpo' > {STOCK}/main.js")
|
||||
status, out = check(data_home=DATA)
|
||||
checks.check(
|
||||
"the effect is the stock one, and the style is ignored",
|
||||
'the animation effect is the stock one: `animation.style` "Linear" is ignored' in out,
|
||||
)
|
||||
checks.check("and it says which copy hides which", "shadows" in out)
|
||||
kde.sh(f"rm -rf {DATA}")
|
||||
|
||||
print("== 3. komorebi is running and its script is not in KWin")
|
||||
kde.sh(
|
||||
"busctl --user call org.kde.KWin /Scripting org.kde.kwin.Scripting unloadScript s komorebi-bridge"
|
||||
)
|
||||
checks.check("KWin has let the script go", kde.wait_for(lambda: not kde.script_loaded()))
|
||||
status, out = check()
|
||||
checks.check(
|
||||
"it is an error, and the exit status says so",
|
||||
status == 1
|
||||
and re.search(r"error +komorebi is running but its script is not in KWin", out) is not None,
|
||||
)
|
||||
|
||||
print("== 4. komorebi is not running")
|
||||
kde.stop_komorebi()
|
||||
checks.check("the daemon is gone", kde.wait_for(lambda: not kde.komorebi_running(), timeout=30))
|
||||
status, out = check()
|
||||
checks.check(
|
||||
"a note, not an error",
|
||||
status == 0 and re.search(r"note +komorebi is not running", out) is not None,
|
||||
)
|
||||
|
||||
print("== 5. there is no KWin on the bus")
|
||||
pid = kde.sh(
|
||||
f"dbus-daemon --session --address=unix:path={EMPTY_BUS} --fork --print-pid"
|
||||
).strip()
|
||||
status, out = check(EMPTY_BUS)
|
||||
kde.run(f"kill {pid}")
|
||||
checks.check(
|
||||
"KWin missing is an error, and the desktop is looked at no further",
|
||||
status == 1
|
||||
and "KWin is not on the session bus" in out
|
||||
and "komorebi is running" not in out
|
||||
and "komorebi is not running" not in out,
|
||||
)
|
||||
|
||||
print("== 6. the key bindings")
|
||||
KEYS_HOME = "/tmp/check-keys-home"
|
||||
SHORTCUTS = "~/.local/share/kglobalaccel"
|
||||
STALE = "[Desktop Entry]\nX-Komorebi-Generated=true\n"
|
||||
|
||||
def check_keys() -> tuple[int, str]:
|
||||
"""Runs `komorebic check` on the key bindings alone, in a config home of their own."""
|
||||
status, out = kde.run(
|
||||
f"KOMOREBI_CONFIG_HOME={KEYS_HOME} komorebic check --configuration-only"
|
||||
)
|
||||
print(out)
|
||||
return status, out
|
||||
|
||||
kde.sh(f"mkdir -p {KEYS_HOME}")
|
||||
status, out = check_keys()
|
||||
checks.check(
|
||||
"without a key binding file it is a note, not an error",
|
||||
status == 0
|
||||
and re.search(r"note +there is no skhdrc, whkdrc or sxhkdrc in ", out) is not None,
|
||||
)
|
||||
|
||||
kde.sh(
|
||||
"printf %s "
|
||||
+ shlex.quote("alt - h : komorebic focus left\nalt - nosuchkey : komorebic focus up\n")
|
||||
+ f" > {KEYS_HOME}/skhdrc"
|
||||
)
|
||||
status, out = check_keys()
|
||||
checks.check(
|
||||
"the file is read, and the line it cannot read is a warning that does not fail the check",
|
||||
status == 0
|
||||
and "skhdrc has 1 key binding" in out
|
||||
and re.search(r"warning +1 line of it cannot be read and left out", out) is not None,
|
||||
)
|
||||
|
||||
# a shortcut file komorebi wrote that the file does not call for, in the directory of the session
|
||||
kde.sh(
|
||||
f"mkdir -p {SHORTCUTS} && printf %s {shlex.quote(STALE)} > {SHORTCUTS}/komorebi-stale.desktop"
|
||||
)
|
||||
status, out = check_keys()
|
||||
checks.check(
|
||||
"it says the shortcut files are not the ones `hotkeys compile` would write",
|
||||
status == 0
|
||||
and "the shortcut files are not the ones `komorebic hotkeys compile` would write" in out,
|
||||
)
|
||||
kde.sh(f"KOMOREBI_CONFIG_HOME={KEYS_HOME} komorebic hotkeys compile")
|
||||
status, out = check_keys()
|
||||
checks.check(
|
||||
"after `hotkeys compile` it does not: both use the directory of the session",
|
||||
status == 0 and "are not the ones" not in out,
|
||||
)
|
||||
|
||||
kde.stop()
|
||||
@@ -0,0 +1,98 @@
|
||||
r"""How real clients answer the frame komorebi asks for. KWin carries out a request at once; the
|
||||
client then decides the size it draws at, and that is the frame KWin reports. What only real
|
||||
clients can tell, and what the fake desktop of the Rust tests cannot know: Qt and KDE programs
|
||||
and X11 programs on XWayland take the frame exactly, also below the minimum size they report;
|
||||
foot sizes itself down to whole cells of its font; GTK 4 programs and Firefox never go below
|
||||
their minimum size. Every client keeps the position komorebi asked for. The output is large
|
||||
enough that some tiles are bigger and some smaller than the clients' minimums.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde, Rect, daemon
|
||||
|
||||
W, H = 3840, 2160
|
||||
CELL = 24
|
||||
|
||||
EXACT = ["org.kde.konsole", "org.kde.kate", "org.kde.dolphin", "XTerm"]
|
||||
WHOLE_CELLS = ["foot"]
|
||||
NOT_BELOW_MINIMUM = ["org.gnome.TextEditor", "org.gnome.Calculator", "firefox"]
|
||||
|
||||
CLIENTS = {
|
||||
"foot": "foot -T foot-term sleep 3000",
|
||||
"org.kde.konsole": "konsole --separate",
|
||||
"org.kde.dolphin": "dolphin --new-window /tmp",
|
||||
"org.kde.kate": "kate --new",
|
||||
"org.gnome.TextEditor": "gnome-text-editor --new-window",
|
||||
"org.gnome.Calculator": "gnome-calculator",
|
||||
"XTerm": "xterm -T xterm-x11",
|
||||
"firefox": "firefox --no-remote --profile /tmp/firefox-profile about:blank",
|
||||
}
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `client-geometry`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
kde = Kde.headless(machine, "main", size=(W, H), xwayland=True, scale=SCALE)
|
||||
kde.as_user("mkdir -p /tmp/firefox-profile")
|
||||
kde.start_komorebi()
|
||||
checks.check(
|
||||
"the daemon loaded its script into KWin",
|
||||
kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30),
|
||||
)
|
||||
|
||||
for app, command in CLIENTS.items():
|
||||
kde.spawn(command, log=f"/tmp/{app}.log")
|
||||
up = kde.wait_for(lambda app=app: kde.wid_by_class(app) != "", timeout=120)
|
||||
if not checks.check(f"{app} has a window", up):
|
||||
print(machine.execute(f"cat /tmp/{app}.log")[1])
|
||||
|
||||
def shown() -> int:
|
||||
return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show")
|
||||
|
||||
checks.check("the daemon tiles all eight", kde.wait_for(lambda: shown() >= 8, timeout=60))
|
||||
|
||||
def show(r: Rect | None) -> str:
|
||||
return "-" if r is None else f"{r.x},{r.y} {r.w}x{r.h}"
|
||||
|
||||
def snapshot() -> dict[str, Rect]:
|
||||
return {app: kde.rect(kde.wid_by_class(app)) for app in CLIENTS}
|
||||
|
||||
# the clients answer in their own time; the frames are final once they stop changing
|
||||
before: dict[str, Rect] = {}
|
||||
|
||||
def still() -> bool:
|
||||
nonlocal before
|
||||
now = snapshot()
|
||||
unchanged = now == before
|
||||
before = now
|
||||
return unchanged
|
||||
|
||||
kde.wait_for(still, timeout=60, interval=3)
|
||||
requests = list(daemon.requests(kde.komorebi_log()).values())
|
||||
|
||||
print(f" {'client':<22} {'asked':<22} {'has':<22}")
|
||||
for app, have in snapshot().items():
|
||||
asked = [r for r in requests if (r.x, r.y) == (have.x, have.y)]
|
||||
want = asked[0] if asked else None
|
||||
print(f" {app:<22} {show(want):<22} {show(have):<22}")
|
||||
if not checks.check(f"{app} is where komorebi put it", want is not None):
|
||||
continue
|
||||
assert want is not None
|
||||
if app in EXACT:
|
||||
checks.check(
|
||||
f"{app} takes the size it is asked for", (have.w, have.h) == (want.w, want.h)
|
||||
)
|
||||
elif app in WHOLE_CELLS:
|
||||
checks.check(
|
||||
f"{app} sizes itself down to whole cells",
|
||||
0 <= want.w - have.w < CELL and 0 <= want.h - have.h < CELL,
|
||||
)
|
||||
elif app in NOT_BELOW_MINIMUM:
|
||||
checks.check(
|
||||
f"{app} is never smaller than it is asked to be",
|
||||
have.w >= want.w and have.h >= want.h,
|
||||
)
|
||||
|
||||
kde.stop_komorebi()
|
||||
kde.stop()
|
||||
@@ -0,0 +1,194 @@
|
||||
"""What only KDE can tell about the commands, round the shared `commands` scenarios.
|
||||
|
||||
Every window the daemon has is a window KWin has, and the frame the daemon last asked KWin for is
|
||||
the one KWin carries out. The shared scenarios check the layouts with five, three, two and one
|
||||
windows and that every command is understood and leaves the daemon healthy, as the operating system
|
||||
sees it; what is here reads KWin (`kdotool`) and the daemon's log.
|
||||
|
||||
The suite runs `setup`, `layouts_by_count`, the shared `layouts` and `sweep`,
|
||||
`replace_configuration`, `bring_back`, the shared `handover`, `title_rule`, `prints` and
|
||||
`queries`, and `at_the_end`.
|
||||
The daemon runs on a session with two outputs, and `clients` are five windows on the first.
|
||||
"""
|
||||
|
||||
from komorebi_vm import daemon
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client
|
||||
from komorebi_vm.kde_platform import CELL, KdePlatform
|
||||
|
||||
OUTPUTS = 2
|
||||
LAYOUTS = (
|
||||
"bsp",
|
||||
"columns",
|
||||
"rows",
|
||||
"vertical-stack",
|
||||
"horizontal-stack",
|
||||
"ultrawide-vertical-stack",
|
||||
"grid",
|
||||
"right-main-vertical-stack",
|
||||
"scrolling",
|
||||
)
|
||||
|
||||
|
||||
def _live_windows(platform: KdePlatform) -> list[str]:
|
||||
"""The ids of the windows KWin has: every client of the suite is a foot."""
|
||||
return platform.kde.run("kdotool search --class foot")[1].split()
|
||||
|
||||
|
||||
def healthy(platform: KdePlatform) -> int:
|
||||
"""0 when the daemon is running, answers `komorebic state` and has every window KWin has.
|
||||
|
||||
Otherwise the reason: 1 not running, 2 no state, 3 not the windows KWin has.
|
||||
"""
|
||||
kde = platform.kde
|
||||
if not kde.komorebi_running():
|
||||
return 1
|
||||
if kde.run("komorebic state")[0] != 0:
|
||||
return 2
|
||||
if kde.managed_all() != len(_live_windows(platform)):
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
def _open_window(platform: KdePlatform, n: int) -> None:
|
||||
platform.spawn(f"win{n}")
|
||||
|
||||
|
||||
def _close_window(platform: KdePlatform, n: int) -> None:
|
||||
kde = platform.kde
|
||||
title = f"win{n}"
|
||||
kde.close(kde.wid(title))
|
||||
kde.wait_for(lambda: kde.wid(title) == "", timeout=10)
|
||||
|
||||
|
||||
def _where_asked(platform: KdePlatform, wid: str) -> str | None:
|
||||
"""None when KWin has the window where the daemon last asked, else what is wrong."""
|
||||
kde = platform.kde
|
||||
title = kde.title(wid)
|
||||
want, have = daemon.asked(kde.komorebi_log(), title), kde.rect(wid)
|
||||
if want is None:
|
||||
return f"{title}: the daemon never asked for a frame"
|
||||
if (have.x, have.y) != (want.x, want.y) or not (
|
||||
0 <= want.w - have.w < CELL and 0 <= want.h - have.h < CELL
|
||||
):
|
||||
return f"{title}: asked {want}, has {have}"
|
||||
return None
|
||||
|
||||
|
||||
def setup(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""The daemon answers with both outputs and has the five windows, as KWin has them."""
|
||||
kde = platform.kde
|
||||
checks.check(
|
||||
"the daemon answers komorebic, with both outputs",
|
||||
kde.wait_for(
|
||||
lambda: (
|
||||
kde.run("komorebic monitor-information")[0] == 0
|
||||
and len(kde.state()["monitors"]["elements"]) == OUTPUTS
|
||||
),
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
"five windows, and the daemon has all five",
|
||||
kde.wait_for(lambda: kde.managed() == len(clients) and healthy(platform) == 0, timeout=20),
|
||||
)
|
||||
|
||||
|
||||
def layouts_by_count(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Every layout with five, three, two and one windows: KWin has each window where the daemon
|
||||
last asked for it, and the daemon is healthy.
|
||||
|
||||
The shared `layouts` checks that the windows are inside the outputs and apart, at every one of
|
||||
those counts. The windows that were closed are opened again, and the layout is `bsp` at the
|
||||
end.
|
||||
"""
|
||||
kde = platform.kde
|
||||
for layout in LAYOUTS:
|
||||
kde.komorebic("change-layout", layout)
|
||||
verdict = []
|
||||
for keep in (5, 3, 2, 1):
|
||||
while kde.managed() > keep:
|
||||
_close_window(platform, kde.managed())
|
||||
kde.wait_for(lambda: healthy(platform) == 0, timeout=10)
|
||||
# the daemon retiles on the close; give KWin the time to carry it out
|
||||
kde.wait_for(
|
||||
lambda: all(_where_asked(platform, w) is None for w in _live_windows(platform)),
|
||||
timeout=10,
|
||||
)
|
||||
verdict += [
|
||||
f"{keep}w: {bad}"
|
||||
for w in _live_windows(platform)
|
||||
if (bad := _where_asked(platform, w))
|
||||
]
|
||||
if reason := healthy(platform):
|
||||
verdict.append(f"{keep}w: not healthy ({reason})")
|
||||
checks.check(
|
||||
f"{layout}: KWin has every window where the daemon last asked, with 5, 3, 2 and 1"
|
||||
" windows" + "".join(f"\n {v}" for v in verdict),
|
||||
verdict == [],
|
||||
)
|
||||
for n in range(kde.managed() + 1, len(clients) + 1):
|
||||
_open_window(platform, n)
|
||||
kde.wait_for(lambda: kde.managed() == len(clients), timeout=20)
|
||||
kde.komorebic("change-layout", "bsp")
|
||||
|
||||
|
||||
def replace_configuration(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""After the shared sweep ran `replace-configuration`, the window manager is made again from
|
||||
the file, whose first workspace is named `again`."""
|
||||
first = platform.kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0]
|
||||
checks.check(
|
||||
"replace-configuration made the window manager again from the file",
|
||||
first["name"] == "again",
|
||||
)
|
||||
|
||||
|
||||
def bring_back(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Puts the windows the sweep sent to other workspaces back on the first, a container each, and
|
||||
focuses it, so that the scenarios after it start from the windows the sweep left, on one
|
||||
workspace, as the shared `handover` needs (a window alone on its workspace has no layout to be
|
||||
left out of).
|
||||
"""
|
||||
|
||||
def count() -> int:
|
||||
return len(platform.state().workspace(0).windows())
|
||||
|
||||
for _ in clients:
|
||||
elsewhere = [
|
||||
i
|
||||
for i, ws in enumerate(platform.state().monitors[0].workspaces)
|
||||
if i != 0 and ws.windows()
|
||||
]
|
||||
if not elsewhere:
|
||||
break
|
||||
here = count()
|
||||
platform.komorebic("focus-workspace", str(elsewhere[0]))
|
||||
platform.komorebic("send-to-workspace", "0")
|
||||
platform.wait_for(lambda h=here: count() > h, timeout=10)
|
||||
platform.komorebic("focus-workspace", "0")
|
||||
state = platform.state
|
||||
checks.check(
|
||||
"the windows are back on the first workspace, in view, in a container each",
|
||||
platform.wait_for(
|
||||
lambda: (
|
||||
len(state().workspace(0).containers) >= 2
|
||||
and state().monitors[0].focused_workspace == 0
|
||||
),
|
||||
timeout=10,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def at_the_end(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""The daemon has every window KWin has, each is where the daemon last asked for it, and a
|
||||
clean stop leaves the daemon not running."""
|
||||
kde = platform.kde
|
||||
checks.check("the daemon has every window KWin has, and answers", healthy(platform) == 0)
|
||||
for wid in _live_windows(platform):
|
||||
print(f" {kde.title(wid)}: {kde.rect(wid)}")
|
||||
mismatch = [m for m in (_where_asked(platform, w) for w in _live_windows(platform)) if m]
|
||||
for m in mismatch:
|
||||
print(f" {m}")
|
||||
checks.check("every window is where the daemon last asked for it", mismatch == [])
|
||||
kde.komorebic("stop")
|
||||
checks.check("a clean stop", kde.wait_for(lambda: not kde.komorebi_running()))
|
||||
@@ -0,0 +1,268 @@
|
||||
"""What only KDE can tell about the daemon and a real KWin, round the shared scenarios of
|
||||
`core-e2e`.
|
||||
|
||||
The shared scenarios ask the operating system where the windows are and what has the focus. What
|
||||
is here reads the other side of the bridge: the frame the daemon last asked KWin for, the focus
|
||||
change it last handled (both from its log), the parking desktop, what KWin does when the daemon
|
||||
stops or crashes, and when KWin itself restarts.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
from komorebi_vm import daemon
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client
|
||||
from komorebi_vm.kde_platform import PARK, KdePlatform
|
||||
from komorebi_vm.platforms.kde.support import where_asked
|
||||
|
||||
OUTPUT_WIDTH = 1920
|
||||
|
||||
|
||||
def _where_asked(platform: KdePlatform, title: str) -> bool:
|
||||
return where_asked(platform, title)
|
||||
|
||||
|
||||
def _focus_agrees(platform: KdePlatform) -> bool:
|
||||
"""The window KWin has focused is the one the daemon last handled a focus change for."""
|
||||
kde = platform.kde
|
||||
log = kde.komorebi_log()
|
||||
focus_changes = [e.window for e in daemon.events(log) if e.kind == "FocusChange"]
|
||||
active = kde.active()
|
||||
if not focus_changes or active == "":
|
||||
return False
|
||||
return daemon.window_ids(log).get(kde.title(active)) == focus_changes[-1]
|
||||
|
||||
|
||||
def _answering(platform: KdePlatform) -> bool:
|
||||
"""`komorebic monitor-information` is answered, with the session's one output."""
|
||||
status, out = platform.kde.run("komorebic monitor-information")
|
||||
return status == 0 and json.loads(out)[0]["size"]["right"] == OUTPUT_WIDTH
|
||||
|
||||
|
||||
def _parked(platform: KdePlatform, clients: list[Client]) -> list[str]:
|
||||
"""The titles of these windows that are on the parking desktop, which is the last desktop."""
|
||||
kde = platform.kde
|
||||
names = kde.desktop_names()
|
||||
if PARK not in names:
|
||||
return []
|
||||
park = names.index(PARK) + 1
|
||||
return sorted(
|
||||
c.title for c in clients if kde.wid(c.title) != "" and kde.desk(kde.wid(c.title)) == park
|
||||
)
|
||||
|
||||
|
||||
def _on_a_workspace_desktop(platform: KdePlatform, clients: list[Client]) -> bool:
|
||||
"""Every one of these windows that is open is on a desktop that is a workspace."""
|
||||
kde = platform.kde
|
||||
return all(kde.desk(kde.wid(c.title)) in (1, 2) for c in clients if kde.wid(c.title) != "")
|
||||
|
||||
|
||||
def _managed(platform: KdePlatform, clients: list[Client]) -> bool:
|
||||
state = platform.state()
|
||||
return all(state.workspace_of(c.title) is not None for c in clients)
|
||||
|
||||
|
||||
def start(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""The daemon loaded its script into KWin, which runs it, and answers komorebic."""
|
||||
kde = platform.kde
|
||||
checks.check(
|
||||
"the daemon loaded its script into KWin",
|
||||
kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30),
|
||||
)
|
||||
checks.check("KWin runs the script", kde.script_loaded())
|
||||
checks.check(
|
||||
"the daemon is up and answering komorebic",
|
||||
kde.wait_for(lambda: _answering(platform), timeout=30),
|
||||
)
|
||||
|
||||
|
||||
def windows_where_asked(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Every window is where the daemon last asked KWin for it."""
|
||||
kde = platform.kde
|
||||
checks.check(
|
||||
"every window is where the daemon asked for it",
|
||||
kde.wait_for(lambda: all(_where_asked(platform, c.title) for c in clients), timeout=20),
|
||||
)
|
||||
|
||||
|
||||
def focus_agrees_with_the_log(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""KWin and the daemon agree on the focused window: the one the daemon last handled a focus
|
||||
change for, by its log."""
|
||||
checks.check(
|
||||
"KWin and the daemon agree on the focused window",
|
||||
platform.kde.wait_for(lambda: _focus_agrees(platform)),
|
||||
)
|
||||
|
||||
|
||||
def fixtures(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Keeps what `komorebic state` prints as files of the run, so that the unit tests of the
|
||||
neutral core (tests/fixtures) are of a real state and not of one written from the serializer,
|
||||
and stacks the windows with `stack left` and unstacks them."""
|
||||
kde = platform.kde
|
||||
out = kde.machine.out_dir
|
||||
(out / "state-kfde-tiled.json").write_text(json.dumps(kde.state(), indent=2))
|
||||
platform.activate(clients[-1])
|
||||
kde.komorebic("stack", "left")
|
||||
checks.check(
|
||||
"the windows are stacked",
|
||||
kde.wait_for(lambda: sorted(map(len, kde.containers())) == [1, 2]),
|
||||
)
|
||||
(out / "state-kfde-stack.json").write_text(json.dumps(kde.state(), indent=2))
|
||||
kde.komorebic("unstack")
|
||||
checks.check(
|
||||
"and unstacked",
|
||||
kde.wait_for(lambda: sorted(map(len, kde.containers())) == [1, 1, 1]),
|
||||
)
|
||||
|
||||
|
||||
# how many lines of the daemon's log `bridge_did_everything` has looked at
|
||||
_LOOKED_AT: dict[int, int] = {}
|
||||
_WINDOW_ID = re.compile(r'"id":"(\{[^}]+\})"')
|
||||
|
||||
|
||||
def bridge_did_everything(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""KWin carried out every command the daemon sent it since the last time this looked: the
|
||||
daemon logs a warning when the bridge could not do one.
|
||||
|
||||
A command for a window that is gone is not a failure: the daemon asks for the place of a window
|
||||
that a scenario closes a moment later, and KWin has nothing to place. Only a window that is
|
||||
still open counts.
|
||||
"""
|
||||
kde = platform.kde
|
||||
lines = kde.komorebi_log().splitlines()
|
||||
start = _LOOKED_AT.get(id(platform), 0)
|
||||
_LOOKED_AT[id(platform)] = len(lines)
|
||||
alive = set(kde.run("kdotool search --class foot")[1].split())
|
||||
failed = []
|
||||
for i in range(start, len(lines)):
|
||||
if "the bridge could not do" not in lines[i]:
|
||||
continue
|
||||
ids = set(_WINDOW_ID.findall(lines[i]))
|
||||
# a window id that is not written the way the daemon writes it is not a window that is gone
|
||||
known_form = all(a.startswith("{") for a in alive)
|
||||
if not ids or ids & alive or not known_form:
|
||||
failed.append(i)
|
||||
for i in failed[:3]:
|
||||
print(" " + "\n ".join(x[-200:] for x in lines[max(0, i - 3) : i + 1]))
|
||||
checks.check("KWin carried out every command since the last step", not failed)
|
||||
|
||||
|
||||
def no_window_is_left(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Closes `clients` that are open, and the daemon has no window."""
|
||||
kde = platform.kde
|
||||
for client in clients:
|
||||
if kde.wid(client.title) != "":
|
||||
platform.close(client)
|
||||
checks.check("no window is left", kde.wait_for(lambda: kde.managed_all() == 0, timeout=20))
|
||||
|
||||
|
||||
def _focus(platform: KdePlatform, client: Client, other: Client) -> None:
|
||||
"""Gives the window the focus and waits until the daemon has it focused too, so that a command
|
||||
that acts on the focused window acts on this one.
|
||||
|
||||
The other window is given the focus first: KWin sends no event for the focus of a window that
|
||||
already has it, and a daemon that has just started may have another one focused.
|
||||
"""
|
||||
platform.activate(other)
|
||||
platform.activate(client)
|
||||
platform.kde.wait_for(
|
||||
lambda: (
|
||||
platform.state().focused_title(monitor=platform.state().focused_monitor) == client.title
|
||||
),
|
||||
timeout=20,
|
||||
)
|
||||
|
||||
|
||||
def _diagnose(platform: KdePlatform, clients: list[Client], what: str) -> None:
|
||||
"""Prints where the daemon and KWin have the windows, for a failure to be read."""
|
||||
kde = platform.kde
|
||||
state = platform.state()
|
||||
desks = {c.title: kde.desk(kde.wid(c.title)) for c in clients if kde.wid(c.title) != ""}
|
||||
focus = state.focused_title(monitor=state.focused_monitor)
|
||||
active = kde.title(kde.active()) if kde.active() else ""
|
||||
print(f" {what}: desktops {kde.desktop_names()}, windows on {desks}, focus {focus!r},")
|
||||
print(f" KWin's active window is {active!r}")
|
||||
print(f" managed {[w.title for w in state.workspace().windows()]}")
|
||||
|
||||
|
||||
def _two_windows(platform: KdePlatform) -> list[Client]:
|
||||
clients = [platform.spawn("park1"), platform.spawn("park2")]
|
||||
platform.kde.wait_for(lambda: _managed(platform, clients), timeout=20)
|
||||
_focus(platform, clients[1], clients[0])
|
||||
return clients
|
||||
|
||||
|
||||
def parking(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""A clean stop undoes what a monocle did, and a crash with a monocle on leaves nothing stuck
|
||||
behind: the next start removes the stale parking desktop and brings the parked window back.
|
||||
|
||||
It opens two windows of its own."""
|
||||
kde = platform.kde
|
||||
two = _two_windows(platform)
|
||||
kde.komorebic("toggle-monocle")
|
||||
checks.check(
|
||||
"the window that is not in monocle is out of sight on a parking desktop",
|
||||
kde.wait_for(lambda: len(_parked(platform, two)) == 1),
|
||||
)
|
||||
_diagnose(platform, two, "monocle before the stop")
|
||||
kde.komorebic("stop")
|
||||
checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running()))
|
||||
checks.check(
|
||||
"the parking desktop is gone", kde.wait_for(lambda: PARK not in kde.desktop_names())
|
||||
)
|
||||
checks.check(
|
||||
"and every window is on a workspace's desktop",
|
||||
kde.wait_for(lambda: _on_a_workspace_desktop(platform, two)),
|
||||
)
|
||||
|
||||
platform.start_komorebi()
|
||||
checks.check("the daemon answers", kde.wait_for(lambda: _answering(platform), timeout=30))
|
||||
checks.check("it manages the two windows again", kde.wait_for(lambda: _managed(platform, two)))
|
||||
_focus(platform, two[1], two[0])
|
||||
kde.komorebic("toggle-monocle")
|
||||
checks.check(
|
||||
"a window is parked and a parking desktop exists",
|
||||
kde.wait_for(lambda: len(_parked(platform, two)) == 1),
|
||||
)
|
||||
_diagnose(platform, two, "monocle after the restart")
|
||||
kde.kill_komorebi()
|
||||
checks.check(
|
||||
"the daemon is dead and the parking desktop is still there, with a window on it",
|
||||
PARK in kde.desktop_names() and len(_parked(platform, two)) == 1,
|
||||
)
|
||||
platform.start_komorebi()
|
||||
checks.check(
|
||||
"the next start removed the stale parking desktop",
|
||||
kde.wait_for(lambda: _answering(platform) and PARK not in kde.desktop_names()),
|
||||
)
|
||||
checks.check(
|
||||
"and brought the parked window back",
|
||||
kde.wait_for(lambda: _on_a_workspace_desktop(platform, two)),
|
||||
)
|
||||
for client in two:
|
||||
platform.close(client)
|
||||
|
||||
|
||||
def leave_a_window(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Opens the window `afterwards`, which `stopped` finds still open after the daemon stops. The
|
||||
`kwin-restart` suite covers KWin restarting under the daemon."""
|
||||
platform.spawn("afterwards")
|
||||
checks.check(
|
||||
"a window opened is managed",
|
||||
platform.kde.wait_for(lambda: platform.kde.managed_all() >= 1, timeout=20),
|
||||
)
|
||||
|
||||
|
||||
def stopped(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""`komorebic stop` ends the daemon, removes its socket and its script, and leaves the window
|
||||
`afterwards` open."""
|
||||
kde = platform.kde
|
||||
kde.komorebic("stop")
|
||||
checks.check("the daemon exited", kde.wait_for(lambda: not kde.komorebi_running()))
|
||||
checks.check(
|
||||
"its socket is gone",
|
||||
kde.run(f"test -e {kde.runtime}/komorebi/komorebi.sock")[0] != 0,
|
||||
)
|
||||
checks.check("the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded()))
|
||||
checks.check("the window stays", kde.wid("afterwards") != "")
|
||||
@@ -0,0 +1,38 @@
|
||||
"""What only KDE can tell about dragging with a real pointer.
|
||||
|
||||
The pointer is a device made inside the guest. The shared `resize` makes the drags of the edges and
|
||||
corners of the tiles, against the daemon's layout and the frames the operating system has
|
||||
(`komorebi/tests/drag_resize.rs` checks the window manager's side against the fake); what is here is
|
||||
that the device puts the pointer to the pixel, which a drag at a gap of four pixels depends on.
|
||||
|
||||
The suite runs `pointer_is_exact` on a session with a pointer and three tiled windows, `win1` to
|
||||
`win3`, then the shared `resize.edge_cases`, `resize.run` and `focus_follows_mouse`.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client
|
||||
from komorebi_vm.kde_platform import KdePlatform
|
||||
|
||||
WINDOWS = 3
|
||||
|
||||
|
||||
def _where(platform: KdePlatform) -> tuple[int, int]:
|
||||
found = re.search(r"x:(-?\d+) y:(-?\d+)", platform.kde.sh("kdotool getmouselocation"))
|
||||
assert found, "kdotool says nowhere"
|
||||
return int(found.group(1)), int(found.group(2))
|
||||
|
||||
|
||||
def pointer_is_exact(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""The pointer goes where it is asked, to the pixel."""
|
||||
width, height = platform.size
|
||||
worst = 0
|
||||
for x, y in [(1, 1), (width - 2, 1), (width // 3, height // 2), (width - 2, height - 2)] + [
|
||||
(17, height - 2)
|
||||
]:
|
||||
platform.pointer.move(x, y)
|
||||
platform.kde.wait_for(lambda x=x, y=y: _where(platform) == (x, y), timeout=3)
|
||||
gx, gy = _where(platform)
|
||||
worst = max(worst, abs(gx - x), abs(gy - y))
|
||||
checks.check(f"the pointer is put within a pixel of where it is asked ({worst})", worst <= 1)
|
||||
@@ -0,0 +1,317 @@
|
||||
r"""What komorebi on Windows does itself and komorebi on KDE has the compositor do, in a real Plasma
|
||||
session whose machine has the effects installed (the module does that): what is on the screen,
|
||||
read from screenshots, not what komorebi wrote. Each feature is a section, and a run of the
|
||||
daemon:
|
||||
|
||||
A toggle-maximize: the window fills the work area, is the one on top, and goes back to its
|
||||
tile. It runs on the daemon the session started with the module's unit, as on a user's
|
||||
machine; the sections after it stop that daemon and start their own runs
|
||||
B transparency: unfocused windows are see-through, the focused one is not
|
||||
C border colors: every kind of window has its own: the focused window, the others, a locked
|
||||
container that does not have the focus, a stack and a monocled window that have it, and a
|
||||
floating window that has it
|
||||
D animation curves: two curves put a window in different places at the same moment
|
||||
E fullscreen: the shared `fullscreen` scenario, which the suite runs after these, on the
|
||||
windows they leave (`fullscreen_setup`)
|
||||
|
||||
Every window is a `foot` of one color all over (`Kde.colored_window`), and a color is read at the
|
||||
pixels just outside the frame of the window (`pixels.ring`). `komorebi/tests/maximize.rs`,
|
||||
`maximize_commands.rs` and `fullscreen.rs` check what the window manager does with a maximize and a
|
||||
fullscreen against the fake; section A checks that KWin's own maximize does it, and the shared
|
||||
`fullscreen` that a window KWin has taken fullscreen is left alone. The shared `maximizing` checks
|
||||
that the maximized window has the state and goes back to its tile; section A keeps what it reads in
|
||||
KWin: that it is on top, from a screenshot.
|
||||
"""
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde, pixels
|
||||
from komorebi_vm.core.platform import Client
|
||||
from komorebi_vm.kde_platform import KdePlatform
|
||||
|
||||
UNIT = "komorebi.service"
|
||||
# the daemon's log of the day, without colors, which every run of the unit adds to
|
||||
LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*"
|
||||
ROUNDED_CORNERS = "kwin4_effect_shapecorners"
|
||||
|
||||
BLUE = (0, 0, 255)
|
||||
SINGLE = (66, 165, 245)
|
||||
UNFOCUSED = (128, 128, 128)
|
||||
LOCKED = (158, 8, 8)
|
||||
STACK = (0, 165, 66)
|
||||
MONOCLE = (255, 51, 153)
|
||||
FLOATING = (245, 245, 165)
|
||||
RED = (255, 0, 0)
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `features`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
kde = Kde.session(machine, scale=SCALE)
|
||||
|
||||
def answering() -> bool:
|
||||
return kde.run("komorebic monitor-information")[0] == 0
|
||||
|
||||
def start_komorebi() -> None:
|
||||
kde.systemctl("start", UNIT)
|
||||
kde.wait_for(answering, timeout=60)
|
||||
# The shell's panel takes room from the windows a while after the shell has made it, and the
|
||||
# daemon learns that up to a second later. The windows are opened after that: before it they
|
||||
# are tiled under the panel and then again, and the ring is read in between.
|
||||
kde.wait_for_panel_room()
|
||||
# the effects are written, loaded and told to read their settings as the daemon starts
|
||||
time.sleep(2)
|
||||
|
||||
def stop_komorebi() -> None:
|
||||
kde.systemctl("stop", UNIT)
|
||||
kde.close_colored_windows()
|
||||
|
||||
def windows() -> None:
|
||||
"""Opens a red, a green and a blue window, in that order, and waits for them to be tiled."""
|
||||
for title, color in (("red", "ff0000"), ("green", "00ff00"), ("blue", "0000ff")):
|
||||
kde.colored_window(title, color)
|
||||
time.sleep(1)
|
||||
kde.wait_for(lambda: kde.managed() == 3, timeout=30)
|
||||
time.sleep(2)
|
||||
|
||||
def ring_wrong(title: str, color: tuple[int, int, int]) -> list[str]:
|
||||
"""What is wrong with the ring of `color` just outside the frame of the window with this title,
|
||||
in a screenshot taken now: a line for each side that has none."""
|
||||
wid = kde.wid(title)
|
||||
if wid == "":
|
||||
return [f"there is no window titled {title}"]
|
||||
return pixels.ring(kde.shot(f"ring-{title}"), kde.rect(wid), color)
|
||||
|
||||
def check_ring(description: str, title: str, color: tuple[int, int, int]) -> None:
|
||||
"""Waits for the window to have the ring, and says what is wrong when it does not."""
|
||||
ok = kde.wait_for(lambda: ring_wrong(title, color) == [], timeout=15)
|
||||
detail = ""
|
||||
if not ok:
|
||||
detail = (
|
||||
f"\n active: {active_title()!r}, komorebi's focus: {kde.focused_title()!r}"
|
||||
)
|
||||
detail += "".join(f"\n {w}" for w in ring_wrong(title, color))
|
||||
said = machine.execute(f"grep -h -i 'border effect\\|colour\\|effect' {LOG}")[1]
|
||||
detail += "".join(f"\n daemon: {line}" for line in said.splitlines()[-8:])
|
||||
checks.check(description + detail, ok)
|
||||
|
||||
def active_title() -> str:
|
||||
wid = kde.active()
|
||||
return kde.title(wid) if wid else ""
|
||||
|
||||
def focus(title: str) -> None:
|
||||
"""Gives the window the focus, and waits until komorebi has it focused too."""
|
||||
kde.activate(kde.wid(title))
|
||||
kde.wait_for(lambda: kde.focused_title() == title, timeout=10)
|
||||
|
||||
def near(pixel: object, want: tuple[int, int, int], tolerance: int = 14) -> bool:
|
||||
"""True if every channel of the pixel is within `tolerance` of `want`."""
|
||||
assert isinstance(pixel, tuple)
|
||||
return all(abs(got - wanted) <= tolerance for got, wanted in zip(pixel, want, strict=True))
|
||||
|
||||
def open_window(title: str, background: str) -> None:
|
||||
"""Opens a terminal with a plain background, so that a screenshot says which window is on top."""
|
||||
kde.spawn(
|
||||
f"foot -T {title} -o colors-dark.background={background} -o colors-dark.alpha=1.0"
|
||||
" sleep 3000"
|
||||
)
|
||||
kde.wait_for(lambda: kde.wid(title) != "", timeout=60)
|
||||
|
||||
print("== A. toggle-maximize")
|
||||
checks.check("the session started komorebi", kde.wait_for(answering, timeout=120))
|
||||
for count, (title, background) in enumerate(
|
||||
[("red", "ff0000"), ("green", "00ff00"), ("blue", "0000ff")], start=1
|
||||
):
|
||||
open_window(title, background)
|
||||
checks.check(
|
||||
f"komorebi manages {title}", kde.wait_for(lambda count=count: kde.managed() == count)
|
||||
)
|
||||
# komorebi tiles the windows, and the last one to open has the focus. The bridge asks again for the
|
||||
# position of a window that is not where komorebi put it for a second after it did (PLATFORM.md,
|
||||
# "How clients answer a frame"), which would put a window that is maximized in that second back
|
||||
# where its tile was: the test waits that second out, as a person would.
|
||||
kde.wait_for(lambda: kde.focused_title() == "blue", timeout=20)
|
||||
time.sleep(3 * SCALE)
|
||||
|
||||
area = kde.state()["monitors"]["elements"][0]["work_area_size"]
|
||||
blue = kde.wid("blue")
|
||||
tile = kde.rect(blue)
|
||||
print(f" the work area is {area['right']}x{area['bottom']}, blue's tile is {tile}")
|
||||
checks.check(
|
||||
"blue is a tile, not the whole work area",
|
||||
tile.w < area["right"] - 20 or tile.h < area["bottom"] - 20,
|
||||
)
|
||||
|
||||
kde.komorebic("toggle-maximize")
|
||||
|
||||
def fills_the_work_area() -> bool:
|
||||
"""KWin's maximize leaves the panel alone, which is at most 100 pixels of the screen."""
|
||||
r = kde.rect(blue)
|
||||
return (
|
||||
r.x <= area["left"] + 2
|
||||
and r.y <= area["top"] + 2
|
||||
and r.w >= area["right"] - 30
|
||||
and r.h >= area["bottom"] - 100
|
||||
)
|
||||
|
||||
filled = kde.wait_for(fills_the_work_area, timeout=20)
|
||||
maximized = kde.rect(blue)
|
||||
checks.check(
|
||||
f"the focused window fills the work area (blue is {maximized}, the area is {area})", filled
|
||||
)
|
||||
|
||||
# a pixel that is not the middle of the window: komorebi puts the pointer there (mouse follows
|
||||
# focus), and a screenshot has the white arrow on it
|
||||
image = kde.shot("maximized")
|
||||
print(f" the screenshot is {image.size[0]}x{image.size[1]}")
|
||||
inside = image.getpixel(
|
||||
(
|
||||
min(maximized.x + maximized.w // 4, image.width - 1),
|
||||
min(maximized.y + maximized.h // 4, image.height - 1),
|
||||
)
|
||||
)
|
||||
checks.check(f"and is the one on top ({inside})", near(inside, BLUE))
|
||||
|
||||
kde.komorebic("toggle-maximize")
|
||||
checks.check(
|
||||
"toggled back, it is in its tile again",
|
||||
kde.wait_for(lambda: kde.rect(blue) == tile, timeout=20),
|
||||
)
|
||||
|
||||
# the session started the module's unit when it logged in: section A used its daemon, and the
|
||||
# sections after it start their own runs
|
||||
stop_komorebi()
|
||||
|
||||
print("== B. transparency")
|
||||
start_komorebi()
|
||||
kde.komorebic("transparency-alpha", "100")
|
||||
kde.komorebic("transparency", "enable")
|
||||
windows()
|
||||
|
||||
def center_of(title: str) -> tuple[int, int]:
|
||||
frame = kde.rect(kde.wid(title))
|
||||
return frame.x + frame.w // 2, frame.y + frame.h // 2
|
||||
|
||||
def middle_of(title: str, color: tuple[int, int, int]) -> bool:
|
||||
"""Returns true if and only if the middle of the window is `color` in a screenshot now."""
|
||||
return pixels.near(pixels.pixel(kde.shot(f"middle-{title}"), *center_of(title)), color)
|
||||
|
||||
checks.check(
|
||||
"the focused window is its own color",
|
||||
kde.wait_for(lambda: middle_of("blue", BLUE), timeout=15),
|
||||
)
|
||||
checks.check(
|
||||
"an unfocused window is not: it lets the desktop through",
|
||||
kde.wait_for(lambda: not middle_of("red", RED), timeout=15),
|
||||
)
|
||||
kde.komorebic("transparency", "disable")
|
||||
checks.check(
|
||||
"with transparency off the unfocused window is opaque again",
|
||||
kde.wait_for(lambda: middle_of("red", RED), timeout=15),
|
||||
)
|
||||
kde.komorebic("toggle-transparency")
|
||||
checks.check(
|
||||
"toggled on, see-through again",
|
||||
kde.wait_for(lambda: not middle_of("red", RED), timeout=15),
|
||||
)
|
||||
stop_komorebi()
|
||||
|
||||
print("== C. border colors")
|
||||
start_komorebi()
|
||||
windows()
|
||||
checks.check(
|
||||
"komorebi's build of the border effect is on the bus (it takes a color for each window)",
|
||||
kde.run(
|
||||
"busctl --user introspect org.kde.KWin /org/komorebi/BorderColours | grep -q SetColours"
|
||||
)[0]
|
||||
== 0,
|
||||
)
|
||||
check_ring("the focused window has the focus color", "blue", SINGLE)
|
||||
check_ring("the others have the unfocused one", "green", UNFOCUSED)
|
||||
|
||||
# a locked container that does not have the focus
|
||||
focus("red")
|
||||
kde.komorebic("toggle-lock")
|
||||
focus("blue")
|
||||
check_ring("a locked container that does not have the focus is marked", "red", LOCKED)
|
||||
focus("red")
|
||||
kde.komorebic("toggle-lock")
|
||||
focus("blue")
|
||||
|
||||
# a stack that has the focus: blue goes into the container on its left
|
||||
kde.komorebic("stack", "left")
|
||||
check_ring("a stack with the focus has the stack color", "blue", STACK)
|
||||
kde.komorebic("unstack")
|
||||
|
||||
# a monocled window
|
||||
kde.komorebic("toggle-monocle")
|
||||
check_ring("a monocled window has the monocle color", "blue", MONOCLE)
|
||||
kde.komorebic("toggle-monocle")
|
||||
|
||||
# a floating window that has the focus
|
||||
kde.komorebic("toggle-float")
|
||||
check_ring("a floating window with the focus has the floating color", "blue", FLOATING)
|
||||
stop_komorebi()
|
||||
|
||||
print("== D. animation curves")
|
||||
# A 30 s animation, looked at a few seconds in: how far along the move is red, as seen on the
|
||||
# screen (the frames are already where they are going; only the picture is on its way). An ease out
|
||||
# is far along by then and a linear one has hardly started. Red is given the focus first so that
|
||||
# nothing hides its left edge, and the answer is a percentage of the way, so it does not depend on
|
||||
# how long the screenshot took.
|
||||
|
||||
def progress(style: str) -> int:
|
||||
"""How far along, in percent, red is a few seconds into a flip of the layout with `style`."""
|
||||
start_komorebi()
|
||||
kde.komorebic("animation-duration", "30000")
|
||||
kde.komorebic("animation-style", "--style", style)
|
||||
kde.komorebic("animation", "enable")
|
||||
kde.colored_window("red", "ff0000")
|
||||
time.sleep(1)
|
||||
kde.colored_window("blue", "0000ff")
|
||||
time.sleep(20 * SCALE)
|
||||
focus("red")
|
||||
time.sleep(2)
|
||||
here = kde.rect(kde.wid("red"))
|
||||
row = here.y + here.h // 2
|
||||
from_x = pixels.leftmost(kde.shot(f"curve-before-{style}"), row, RED)
|
||||
kde.komorebic("flip-layout", "horizontal")
|
||||
kde.wait_for(lambda: kde.rect(kde.wid("red")) != here, timeout=10)
|
||||
to = kde.rect(kde.wid("red"))
|
||||
time.sleep(5 * SCALE)
|
||||
now_x = pixels.leftmost(kde.shot(f"curve-{style}"), row, RED)
|
||||
print(
|
||||
f" {style}: red's left edge on the screen went from {from_x} to {now_x}; its frame"
|
||||
)
|
||||
print(f" goes from {here.x} to {to.x}")
|
||||
stop_komorebi()
|
||||
if from_x is None or now_x is None or to.x == here.x:
|
||||
return -1
|
||||
return (now_x - from_x) * 100 // (to.x - here.x)
|
||||
|
||||
linear = progress("linear")
|
||||
expo = progress("ease-out-expo")
|
||||
print(f" a few seconds into a 30 s move, red is this far along: {linear}% with Linear,")
|
||||
print(f" {expo}% with EaseOutExpo")
|
||||
checks.check("Linear is less than 60% of the way", 0 <= linear < 60)
|
||||
checks.check("EaseOutExpo is at least 20 points further along than Linear", expo >= linear + 20)
|
||||
|
||||
|
||||
def fullscreen_setup(machine: Any, scale: float) -> tuple[KdePlatform, list[Client]]:
|
||||
"""What the shared `fullscreen` needs: the daemon running, and a red, a green and a blue window
|
||||
open and tiled. When an earlier section stopped the daemon or closed the windows, they are
|
||||
started and opened again."""
|
||||
kde = Kde.session(machine, scale=scale)
|
||||
if kde.run("komorebic monitor-information")[0] != 0:
|
||||
kde.systemctl("start", UNIT)
|
||||
kde.wait_for(lambda: kde.run("komorebic monitor-information")[0] == 0, timeout=60)
|
||||
monitor = kde.state()["monitors"]["elements"][0]["size"]
|
||||
platform = KdePlatform(kde, (monitor["right"], monitor["bottom"]), session=True)
|
||||
clients = [Client(title) for title in ("red", "green", "blue")]
|
||||
for client in clients:
|
||||
if kde.wid(client.title) == "":
|
||||
platform.spawn(client.title)
|
||||
kde.wait_for(lambda: kde.managed() == 3, timeout=30)
|
||||
kde.wait_for(lambda: kde.focused_title() == "blue", timeout=20)
|
||||
return platform, clients
|
||||
@@ -0,0 +1,130 @@
|
||||
r"""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 typing import Any
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `focus-follows-mouse`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
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,
|
||||
)
|
||||
@@ -0,0 +1,164 @@
|
||||
"""What only KDE can tell about monitors that change, round the shared `hotplug` scenario.
|
||||
|
||||
A scale that `kscreen-doctor` changes reaches the daemon as a change of the monitor's size; KWin
|
||||
tells the daemon that a window is on another output when the daemon sent it there; and what the
|
||||
daemon believes of its monitors is what the compositor has.
|
||||
|
||||
The suite runs `setup`, `scale` and `sent_by_the_daemon`, then the shared `user_move`, then the
|
||||
shared `run`, which unplugs a display and plugs it in again, then `user_move` once more, then
|
||||
`after`. The daemon runs on a session with two outputs, and `clients` are three windows on the
|
||||
left one.
|
||||
"""
|
||||
|
||||
from komorebi_vm import daemon
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.geometry import Rect
|
||||
from komorebi_vm.core.platform import Client
|
||||
from komorebi_vm.kde_platform import KdePlatform
|
||||
|
||||
|
||||
def _monitor(platform: KdePlatform, idx: int) -> Rect:
|
||||
"""The bounds the daemon has for a monitor."""
|
||||
size = platform.kde.state()["monitors"]["elements"][idx]["size"]
|
||||
return Rect(size["left"], size["top"], size["right"], size["bottom"])
|
||||
|
||||
|
||||
def _containers_on(platform: KdePlatform, idx: int) -> int:
|
||||
"""How many containers the workspace in front of a monitor has in the daemon."""
|
||||
workspaces = platform.kde.state()["monitors"]["elements"][idx]["workspaces"]
|
||||
return len(workspaces["elements"][workspaces["focused"]]["containers"]["elements"])
|
||||
|
||||
|
||||
def _rects(platform: KdePlatform, clients: list[Client]) -> list[Rect]:
|
||||
"""The frames KWin has for the windows."""
|
||||
return [platform.kde.rect(platform.kde.wid(c.title)) for c in clients]
|
||||
|
||||
|
||||
def _tiled_in(platform: KdePlatform, clients: list[Client], area: Rect) -> bool:
|
||||
"""Every one of the windows is inside `area`, and none is on another.
|
||||
|
||||
A pixel is allowed at each edge: at a fractional scale KWin reports frames that are not whole
|
||||
pixels.
|
||||
"""
|
||||
frames = _rects(platform, clients)
|
||||
return all(r.inside(area, slack=1) for r in frames) and not any(
|
||||
a.overlaps(b) for i, a in enumerate(frames) for b in frames[i + 1 :]
|
||||
)
|
||||
|
||||
|
||||
def _on_the_right(platform: KdePlatform, clients: list[Client]) -> list[Client]:
|
||||
"""The windows that are on the right output, as KWin has them."""
|
||||
width = platform.size[0]
|
||||
pairs = zip(clients, _rects(platform, clients), strict=True)
|
||||
return [c for c, r in pairs if r.x >= width]
|
||||
|
||||
|
||||
def _output_changes(platform: KdePlatform) -> int:
|
||||
"""How many times KWin has told the daemon that a window is on another output."""
|
||||
events = daemon.events(platform.kde.komorebi_log())
|
||||
return sum(1 for e in events if e.kind == "OutputChange")
|
||||
|
||||
|
||||
def setup(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""The daemon has a monitor for each of the two outputs, with the size of its output, and the
|
||||
windows are on the left one."""
|
||||
width, height = platform.size
|
||||
checks.check(
|
||||
"the daemon answers komorebic, with both monitors",
|
||||
platform.wait_for(
|
||||
lambda: len(platform.state().monitors) == 2 and platform.komorebic("state") != "",
|
||||
timeout=30,
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
"the daemon has the three windows on the left monitor",
|
||||
platform.wait_for(
|
||||
lambda: _containers_on(platform, 0) == 3 and _containers_on(platform, 1) == 0
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
"the left monitor has the size of its output",
|
||||
_monitor(platform, 0) == Rect(0, 0, width, height),
|
||||
)
|
||||
checks.check(
|
||||
"the windows are tiled inside it",
|
||||
platform.wait_for(lambda: _tiled_in(platform, clients, _monitor(platform, 0))),
|
||||
)
|
||||
|
||||
|
||||
def scale(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""The scale of the left output changes to 1.5 and back, and the daemon follows both."""
|
||||
width, height = platform.size
|
||||
left = platform.kde.outputs.names()[0]
|
||||
resizes = lambda: platform.kde.komorebi_log().count("updated monitor size and work area") # noqa: E731
|
||||
before = resizes()
|
||||
platform.kde.outputs.scale(left, 1.5)
|
||||
smaller = Rect(0, 0, width * 2 // 3, height * 2 // 3)
|
||||
checks.check(
|
||||
f"the daemon has the new size of the monitor, {smaller}",
|
||||
platform.wait_for(lambda: _monitor(platform, 0) == smaller, timeout=20),
|
||||
)
|
||||
checks.check("it read the sizes again for it", resizes() > before)
|
||||
checks.check(
|
||||
"the windows are tiled again inside the monitor as it is now",
|
||||
platform.wait_for(lambda: _tiled_in(platform, clients, smaller)),
|
||||
)
|
||||
platform.kde.outputs.scale(left, 1)
|
||||
full = Rect(0, 0, width, height)
|
||||
checks.check(
|
||||
"the monitor has its size back, and the windows fill it again",
|
||||
platform.wait_for(
|
||||
lambda: _monitor(platform, 0) == full and _tiled_in(platform, clients, full),
|
||||
timeout=20,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def sent_by_the_daemon(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""`move-to-monitor 1` sends the focused window to the right output: KWin reports it there,
|
||||
and the daemon leaves it where it put it."""
|
||||
changes = _output_changes(platform)
|
||||
platform.komorebic("move-to-monitor", "1")
|
||||
checks.check(
|
||||
"the daemon has two containers on the left monitor and one on the right",
|
||||
platform.wait_for(
|
||||
lambda: _containers_on(platform, 0) == 2 and _containers_on(platform, 1) == 1
|
||||
),
|
||||
)
|
||||
checks.check(
|
||||
"KWin reported the window on the other output",
|
||||
platform.wait_for(lambda: _output_changes(platform) > changes),
|
||||
)
|
||||
moved = _on_the_right(platform, clients)
|
||||
checks.check(
|
||||
"the window is tiled on the right output",
|
||||
len(moved) == 1 and _tiled_in(platform, moved, _monitor(platform, 1)),
|
||||
)
|
||||
checks.check(
|
||||
"and it is still on the right monitor once KWin has said so",
|
||||
_containers_on(platform, 0) == 2 and _containers_on(platform, 1) == 1,
|
||||
)
|
||||
|
||||
|
||||
def after(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""After the display was unplugged and plugged in again the daemon is alive and agrees with
|
||||
KWin on the focus. The shared `user_move` runs once more before it, for a window the user moves
|
||||
to the other output."""
|
||||
kde = platform.kde
|
||||
|
||||
def focus_agrees() -> bool:
|
||||
# the focused window may be on either monitor: the shared scenario sent one to the other
|
||||
state = platform.state()
|
||||
return (
|
||||
kde.komorebi_running()
|
||||
and kde.active() != ""
|
||||
and kde.title(kde.active()) == state.focused_title(monitor=state.focused_monitor)
|
||||
)
|
||||
|
||||
checks.check(
|
||||
"the daemon is alive and its idea of the focus is KWin's", platform.wait_for(focus_agrees)
|
||||
)
|
||||
checks.check(
|
||||
"the daemon is running and answers",
|
||||
kde.komorebi_running() and kde.run("komorebic state")[0] == 0,
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
r"""vm-keys-skhd, vm-keys-whkd and vm-keys-sxhkd: the case `vm` of the key binding corpus
|
||||
(komorebi-hotkeys/tests/fixtures/vm.*), in the format of the suite, installed by the NixOS module
|
||||
(`services.komorebi.keybindings`, mode auto). Alt+J can be a static shortcut, which KWin runs
|
||||
from the system profile; Alt+, cannot, so the module's daemon registers it and runs it. The Rust
|
||||
tests and `keybindings-fixtures` check the plan; only a real session can say that what the
|
||||
module builds and starts runs on a key, from each of the three formats.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde, Keys
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `keys-corpus`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
kde = Kde.session(machine, scale=SCALE)
|
||||
keys = Keys(machine)
|
||||
|
||||
def ran(marker: str) -> bool:
|
||||
return machine.execute(f"test -e /tmp/{marker}")[0] == 0
|
||||
|
||||
def press(combo: str, marker: str) -> bool:
|
||||
keys.send(combo)
|
||||
return kde.wait_for(lambda: ran(marker), timeout=10)
|
||||
|
||||
shortcuts = machine.succeed("ls /run/current-system/sw/share/kglobalaccel")
|
||||
checks.check(
|
||||
"the module installed the static shortcut in the system profile",
|
||||
"komorebi-touch-tmp-keys-corpus-alt-j.desktop" in shortcuts.split(),
|
||||
)
|
||||
checks.check(
|
||||
"the module's daemon registered the key of the engine, and only that one",
|
||||
kde.wait_for(lambda: kde.shortcut_actions() == ["Alt+,"], timeout=60),
|
||||
)
|
||||
checks.check(
|
||||
"Alt+J runs its command, as a static shortcut", press("alt-j", "keys-corpus-alt-j")
|
||||
)
|
||||
checks.check(
|
||||
"Alt+, runs its command, through the engine", press("alt-comma", "keys-corpus-alt-comma")
|
||||
)
|
||||
@@ -0,0 +1,291 @@
|
||||
r"""The engine in a real Plasma session: the daemon registers the keys of a key binding file with
|
||||
KWin's global shortcut daemon and runs their commands. The Rust tests check the calls the
|
||||
engine's effects become; only KWin can say that a grabbed key reports its presses to the daemon,
|
||||
that the keys of a killed daemon stay registered until the next start takes them over, and that
|
||||
a stop gives them back.
|
||||
"""
|
||||
|
||||
import json
|
||||
import shlex
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde, Keys
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `keys-engine`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
kde = Kde.session(machine, scale=SCALE)
|
||||
keys = Keys(machine)
|
||||
|
||||
def ran(marker: str) -> bool:
|
||||
return machine.execute(f"test -e /tmp/{marker}")[0] == 0
|
||||
|
||||
def press(combo: str, marker: str) -> bool:
|
||||
keys.send(combo)
|
||||
return kde.wait_for(lambda: ran(marker), timeout=10)
|
||||
|
||||
def engine() -> dict[str, Any]:
|
||||
"""What the engine is doing: its `mode`, the keys it holds (`active`) and whether a chord
|
||||
`chain` is being typed. It is empty when no engine answers.
|
||||
|
||||
The engine answers once it has told kglobalaccel everything its last event needed, so what it
|
||||
says it holds is what KWin has grabbed. A key pressed before that is not the engine's yet and
|
||||
goes to the window, and how long the grab takes is how slow the machine is: the engine is
|
||||
asked, and no fixed time is waited.
|
||||
"""
|
||||
status, out = kde.run("komorebic hotkeys state")
|
||||
return (json.loads(out).get("engine") or {}) if status == 0 else {}
|
||||
|
||||
def in_mode(mode: str) -> bool:
|
||||
"""Waits for the engine to be in `mode`, with the keys of the mode grabbed."""
|
||||
return kde.wait_for(lambda: engine().get("mode") == mode, timeout=10)
|
||||
|
||||
def chain_is(on: bool, within: float = 10) -> bool:
|
||||
"""Waits for the engine to be in a chord chain (or, with `on` false, to be done with it, and to
|
||||
hold the keys of the mode again), for up to `within` seconds."""
|
||||
return kde.wait_for(lambda: engine().get("chain") is on, timeout=within)
|
||||
|
||||
def write(skhdrc: str) -> None:
|
||||
kde.sh(
|
||||
f"mkdir -p ~/.config/komorebi && printf '%s' {shlex.quote(skhdrc)} > ~/.config/komorebi/skhdrc"
|
||||
)
|
||||
|
||||
def start(skhdrc: str, *args: str) -> None:
|
||||
write(skhdrc)
|
||||
# no --keybindings: the daemon finds the skhdrc in the config directory
|
||||
kde.spawn_komorebi("--log-level", "debug", *args)
|
||||
if not kde.wait_for(lambda: "keys in kglobalaccel" in kde.komorebi_log(), timeout=60):
|
||||
raise AssertionError(f"the keys were not registered:\n{kde.komorebi_log()}")
|
||||
|
||||
def stop() -> None:
|
||||
"""Stops the daemon, and waits until it is gone: it takes its KWin script and its keys with
|
||||
it when it exits, and a daemon started before that would find them taken from it."""
|
||||
kde.komorebic("stop")
|
||||
if not kde.wait_for(lambda: machine.execute("pgrep -x komorebi")[0] != 0, timeout=10):
|
||||
raise AssertionError("the daemon did not stop")
|
||||
|
||||
start(
|
||||
"alt - h : touch /tmp/keys-engine-alt-h\n"
|
||||
"alt - r : komorebic retile\n"
|
||||
'alt - q : echo "$HOME" > /tmp/keys-engine-alt-q\n'
|
||||
)
|
||||
actions = kde.shortcut_actions()
|
||||
checks.check(
|
||||
f"the daemon registered its three keys ({actions})", actions == ["Alt+H", "Alt+Q", "Alt+R"]
|
||||
)
|
||||
checks.check("Alt+H runs its command", press("alt-h", "keys-engine-alt-h"))
|
||||
checks.check("Alt+Q runs its command through a shell", press("alt-q", "keys-engine-alt-q"))
|
||||
home = machine.succeed("cat /tmp/keys-engine-alt-q").strip()
|
||||
checks.check(f"the shell expanded $HOME ({home!r})", home == "/home/komorebi")
|
||||
keys.send("alt-r")
|
||||
checks.check(
|
||||
"Alt+R runs komorebic, which sends its message to the daemon",
|
||||
kde.wait_for(lambda: "processing command: Retile" in kde.komorebi_log(), timeout=10),
|
||||
)
|
||||
|
||||
# kglobalaccel keeps the keys of a daemon that was killed
|
||||
kde.kill_spawned_komorebi()
|
||||
checks.check("a killed daemon leaves its keys registered", kde.shortcut_actions() == actions)
|
||||
|
||||
# the next start takes over the keys it binds, and unregisters the others
|
||||
start("alt - j : touch /tmp/keys-engine-alt-j\nalt - h : touch /tmp/keys-engine-alt-h-again\n")
|
||||
actions = kde.shortcut_actions()
|
||||
checks.check(
|
||||
f"the next start leaves only its own keys ({actions})", actions == ["Alt+H", "Alt+J"]
|
||||
)
|
||||
checks.check("Alt+J runs its command", press("alt-j", "keys-engine-alt-j"))
|
||||
checks.check("Alt+H runs its new command", press("alt-h", "keys-engine-alt-h-again"))
|
||||
|
||||
# a stop gives every key back
|
||||
kde.komorebic("stop")
|
||||
checks.check(
|
||||
"komorebic stop stops the daemon",
|
||||
kde.wait_for(lambda: machine.execute("pgrep -x komorebi")[0] != 0, timeout=10),
|
||||
)
|
||||
checks.check("a stop unregisters every key", kde.shortcut_actions() == [])
|
||||
machine.succeed("rm /tmp/keys-engine-alt-j")
|
||||
keys.send("alt-j")
|
||||
checks.check(
|
||||
"Alt+J runs nothing once the daemon stopped",
|
||||
not kde.wait_for(lambda: ran("keys-engine-alt-j"), timeout=3),
|
||||
)
|
||||
|
||||
# modes: entering one grabs its keys, a bare H among them, and lets the others go to the window
|
||||
kde.spawn("stdbuf -oL wev", log="/tmp/wev.log")
|
||||
if not kde.wait_for(lambda: kde.wid_by_class("wev") != "", timeout=30):
|
||||
raise AssertionError("wev did not open")
|
||||
|
||||
def activate(wid: str) -> None:
|
||||
"""Gives the window the focus, asking again until KWin has: it lists a window before it
|
||||
can have the focus, and refuses to activate it until then."""
|
||||
if not kde.wait_for(
|
||||
lambda: (
|
||||
kde.run(f"kdotool windowactivate {shlex.quote(wid)}")[0] == 0
|
||||
and kde.active() == wid
|
||||
),
|
||||
timeout=30,
|
||||
):
|
||||
raise AssertionError(f"{wid} did not take the focus")
|
||||
|
||||
activate(kde.wid_by_class("wev"))
|
||||
|
||||
def typed(key: str) -> int:
|
||||
"""How many presses of `key` reached wev."""
|
||||
# wev prints a sym line after the press and after the release of a key
|
||||
presses = f"grep -A1 'state: 1 (pressed)' /tmp/wev.log | grep -cE 'sym: {key} +\\('"
|
||||
out = machine.execute(presses)[1].strip()
|
||||
return int(out or "0")
|
||||
|
||||
def reaches_wev(key: str, presses: int) -> bool:
|
||||
return kde.wait_for(lambda: typed(key) >= presses, timeout=5)
|
||||
|
||||
start(
|
||||
":: resize : touch /tmp/keys-modes-entered\n"
|
||||
"alt - r ; resize\n"
|
||||
"resize < h : touch /tmp/keys-modes-h\n"
|
||||
"resize < escape ; default\n"
|
||||
)
|
||||
keys.send("h")
|
||||
checks.check("in the default mode H reaches the focused window", reaches_wev("h", 1))
|
||||
checks.check("Alt+R enters the mode and runs its command", press("alt-r", "keys-modes-entered"))
|
||||
checks.check(
|
||||
"the daemon logs the mode it is in, and holds the keys of the mode",
|
||||
kde.wait_for(lambda: "the mode is now resize" in kde.komorebi_log()) and in_mode("resize"),
|
||||
)
|
||||
checks.check("in the mode H runs its binding", press("h", "keys-modes-h"))
|
||||
checks.check("and does not reach the window", typed("h") == 1)
|
||||
keys.send("esc")
|
||||
checks.check(
|
||||
"Escape goes back to the default mode, and gives the keys of the mode back",
|
||||
kde.wait_for(lambda: "the mode is now default" in kde.komorebi_log())
|
||||
and in_mode("default"),
|
||||
)
|
||||
keys.send("h")
|
||||
checks.check("back in the default mode H reaches the window again", reaches_wev("h", 2))
|
||||
stop()
|
||||
|
||||
# chord chains: the prefix grabs the keys that can come next, until a key, Escape or the timeout
|
||||
sxhkdrc = "/home/komorebi/.config/komorebi/sxhkdrc"
|
||||
chain = "alt + w ; {h,l}\n touch /tmp/keys-chords-{h,l}\n"
|
||||
kde.sh(f"printf '%s' {shlex.quote(chain)} > {sxhkdrc}")
|
||||
# The timeout is long, and is scaled like every wait, so that the keys of a chain are sent well
|
||||
# inside it however slowly the machine grabs them, and that Escape can be told from the timeout.
|
||||
CHORD_TIMEOUT = 3
|
||||
kde.spawn_komorebi(
|
||||
"--log-level",
|
||||
"debug",
|
||||
"--keybindings",
|
||||
sxhkdrc,
|
||||
"--chord-timeout",
|
||||
str(int(CHORD_TIMEOUT * 1000 * SCALE)),
|
||||
)
|
||||
if not kde.wait_for(lambda: "keys in kglobalaccel" in kde.komorebi_log(), timeout=60):
|
||||
raise AssertionError(f"the keys were not registered:\n{kde.komorebi_log()}")
|
||||
|
||||
def chain_begins() -> None:
|
||||
"""Presses Alt+W and waits until the engine has grabbed the keys that can come next.
|
||||
|
||||
A key pressed before that goes to the window, not to the chain.
|
||||
"""
|
||||
keys.send("alt-w")
|
||||
if not chain_is(True):
|
||||
raise AssertionError(
|
||||
f"Alt+W did not begin the chain ({engine()}):\n{kde.komorebi_log()}"
|
||||
)
|
||||
|
||||
def chain_ends() -> None:
|
||||
"""Waits until the chain is over and the engine holds Alt+W again, which a key pressed
|
||||
before that would not find."""
|
||||
if not chain_is(False):
|
||||
raise AssertionError(f"the chain did not end ({engine()}):\n{kde.komorebi_log()}")
|
||||
|
||||
h_before = typed("h")
|
||||
chain_begins()
|
||||
checks.check("Alt+W, H runs the binding of the chain", press("h", "keys-chords-h"))
|
||||
checks.check("the H of the chain does not reach the window", typed("h") == h_before)
|
||||
chain_ends()
|
||||
chain_begins()
|
||||
keys.send("esc")
|
||||
checks.check(
|
||||
"Escape ends the chain, which the timeout has not yet done",
|
||||
chain_is(False, within=CHORD_TIMEOUT / 2),
|
||||
)
|
||||
keys.send("h")
|
||||
checks.check("after Alt+W, Escape, H reaches the window", reaches_wev("h", h_before + 1))
|
||||
chain_begins()
|
||||
checks.check("the chain ends at its timeout", chain_is(False, within=CHORD_TIMEOUT + 1))
|
||||
keys.send("l")
|
||||
checks.check("after Alt+W and the timeout, L reaches the window", reaches_wev("l", 1))
|
||||
checks.check("and runs nothing", not ran("keys-chords-l"))
|
||||
stop()
|
||||
|
||||
# per-application bindings: a key is grabbed only while the focused application has an action
|
||||
start(
|
||||
'alt - g [\n "terminal" : touch /tmp/keys-scopes-terminal\n]\n'
|
||||
'alt - n [\n "wev" ~\n * : touch /tmp/keys-scopes-other\n]\n',
|
||||
"--app-alias",
|
||||
"terminal=foot",
|
||||
)
|
||||
kde.spawn("foot")
|
||||
if not kde.wait_for(lambda: kde.wid_by_class("foot") != "", timeout=30):
|
||||
raise AssertionError("foot did not open")
|
||||
wev, foot = kde.wid_by_class("wev"), kde.wid_by_class("foot")
|
||||
|
||||
def sees_focus(wid: str, app_id: str) -> bool:
|
||||
"""Activates the window and waits for the engine to log that its application has the focus."""
|
||||
activate(wid)
|
||||
|
||||
def seen() -> bool:
|
||||
lines = [x for x in kde.komorebi_log().splitlines() if "the focus is now" in x]
|
||||
return bool(lines) and f"({app_id}, " in lines[-1]
|
||||
|
||||
return kde.wait_for(seen, timeout=10)
|
||||
|
||||
def focus(wid: str, app_id: str) -> None:
|
||||
"""Activates the window, and returns once the engine has grabbed the keys that its
|
||||
application has an action for, and given the others back."""
|
||||
if not sees_focus(wid, app_id):
|
||||
raise AssertionError(f"the engine did not see {app_id} take the focus")
|
||||
# the engine logs the focus before it grabs and gives back the keys of the application, and
|
||||
# answers once it has: a key pressed before that would find the keys of the other window
|
||||
if not engine():
|
||||
raise AssertionError("the engine does not answer")
|
||||
|
||||
focus(wev, "wev")
|
||||
g_before, n_before = typed("g"), typed("n")
|
||||
keys.send("alt-g")
|
||||
checks.check(
|
||||
"in wev, Alt+G (for the terminal only) reaches wev", reaches_wev("g", g_before + 1)
|
||||
)
|
||||
keys.send("alt-n")
|
||||
checks.check("in wev, Alt+N (which wev ignores) reaches wev", reaches_wev("n", n_before + 1))
|
||||
checks.check("and runs nothing", not ran("keys-scopes-other"))
|
||||
focus(foot, "foot")
|
||||
checks.check(
|
||||
"in foot, Alt+G runs the terminal's binding, by the alias",
|
||||
press("alt-g", "keys-scopes-terminal"),
|
||||
)
|
||||
checks.check(
|
||||
"in foot, Alt+N runs the binding for every other application",
|
||||
press("alt-n", "keys-scopes-other"),
|
||||
)
|
||||
focus(wev, "wev")
|
||||
keys.send("alt-g")
|
||||
checks.check("back in wev, Alt+G reaches wev again", reaches_wev("g", g_before + 2))
|
||||
|
||||
# An engine that starts while the focused application has nothing to grab starts all the same:
|
||||
# the key bindings are read again with wev focused, and every binding is for the terminal.
|
||||
write('alt - j [\n "terminal" : touch /tmp/keys-scopes-reload\n]\n')
|
||||
reads = kde.komorebi_log().count("bindings for the engine")
|
||||
kde.komorebic("hotkeys", "reload")
|
||||
kde.wait_for(lambda: kde.komorebi_log().count("bindings for the engine") > reads, timeout=10)
|
||||
checks.check(
|
||||
"an engine that starts with nothing to grab goes on to see foot take the focus",
|
||||
sees_focus(foot, "foot") and bool(engine()),
|
||||
)
|
||||
checks.check(
|
||||
"and in foot, Alt+J runs the terminal's binding",
|
||||
press("alt-j", "keys-scopes-reload"),
|
||||
)
|
||||
stop()
|
||||
@@ -0,0 +1,50 @@
|
||||
r"""Static shortcuts in a real Plasma session: what `komorebic hotkeys compile` and
|
||||
`komorebic export-kde-shortcuts` write is run by KWin itself, with no komorebi
|
||||
process. The Rust tests check the files; only a KWin can say that it reads them
|
||||
and runs their commands on a key: the files in the system profile when the
|
||||
session starts, and a file written later once `--reload` has handed it over.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde, Keys
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `keys-static`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
kde = Kde.session(machine, scale=SCALE)
|
||||
keys = Keys(machine)
|
||||
|
||||
def ran(marker: str) -> bool:
|
||||
return machine.execute(f"test -e /tmp/{marker}")[0] == 0
|
||||
|
||||
def press(combo: str, marker: str) -> bool:
|
||||
keys.send(combo)
|
||||
return kde.wait_for(lambda: ran(marker), timeout=10)
|
||||
|
||||
print(kde.sh("ls /run/current-system/sw/share/kglobalaccel"))
|
||||
checks.check("Alt+J runs its command", press("alt-j", "keys-static-alt-j"))
|
||||
checks.check(
|
||||
"Alt+Shift+K runs a command that needs a shell",
|
||||
press("alt-shift-k", "keys-static-alt-shift-k"),
|
||||
)
|
||||
checks.check("Alt+P runs a command with a %", press("alt-p", "keys-static-alt-p"))
|
||||
date = machine.succeed("cat /tmp/keys-static-alt-p").strip()
|
||||
checks.check(f"the % reached the command as one % ({date!r})", date.isdigit())
|
||||
|
||||
# a binding written in the middle of the session, into the user's directory
|
||||
kde.sh("mkdir -p ~/.config/komorebi")
|
||||
kde.sh("echo 'alt - u : touch /tmp/keys-static-alt-u' > ~/.config/komorebi/skhdrc")
|
||||
print(kde.sh("komorebic export-kde-shortcuts --reload"))
|
||||
written = (
|
||||
"/home/komorebi/.local/share/kglobalaccel/komorebi-touch-tmp-keys-static-alt-u.desktop"
|
||||
)
|
||||
checks.check(
|
||||
"the file is in the user's kglobalaccel directory",
|
||||
machine.execute(f"test -e {written}")[0] == 0,
|
||||
)
|
||||
checks.check(
|
||||
"Alt+U runs its command once --reload has handed it over",
|
||||
press("alt-u", "keys-static-alt-u"),
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
r"""What the harness itself promises: a headless KWin comes up with the outputs asked for, a client
|
||||
gets a window on it, and the library sees both.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `kwin`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
kde = Kde.headless(machine, "main", size=(1280, 720), outputs=2, scale=SCALE)
|
||||
checks.check("KWin owns its name on the private bus", kde.has_name("org.kde.KWin"))
|
||||
checks.check("KWin has the two outputs that were asked for", lambda: kde.outputs() == 2)
|
||||
|
||||
kde.spawn("foot -T alpha sleep 3000")
|
||||
checks.check("a window appears", kde.wait_for(lambda: kde.wid("alpha") != "", timeout=30))
|
||||
wid = kde.wid("alpha")
|
||||
checks.check("the library reads its title back", lambda: kde.title(wid) == "alpha")
|
||||
rect = kde.rect(wid)
|
||||
print(f"alpha is at {rect}")
|
||||
checks.check("it has a size", rect.w > 0 and rect.h > 0)
|
||||
|
||||
other = Kde.headless(machine, "other", size=(800, 600), scale=SCALE)
|
||||
checks.check("a second session is its own KWin", lambda: other.outputs() == 1)
|
||||
checks.check("it does not see the first session's window", other.wid("alpha") == "")
|
||||
other.stop()
|
||||
|
||||
kde.stop()
|
||||
checks.check("stopping the session releases its name", not kde.has_name("org.kde.KWin"))
|
||||
@@ -0,0 +1,172 @@
|
||||
r"""The contract of KWin's per-output virtual desktops that komorebi's workspaces rely on, checked
|
||||
against a headless KWin with two outputs and no komorebi: workspace `i` is desktop `i`, and each
|
||||
output shows a desktop of its own. What has to hold, and what breaks if it does not:
|
||||
|
||||
- with `[Windows] PerOutputVirtualDesktops=true` in kwinrc, a script can show a desktop on one
|
||||
output and the other output keeps its own (otherwise a workspace switch switches every monitor);
|
||||
- KWin says so with `workspace.currentDesktopChanged`, which the bridge listens to;
|
||||
- KWin focuses a window of the desktop it switched an output to, by itself (komorebi asks for no
|
||||
focus after a switch it did not make);
|
||||
- activating a window on another desktop of its output (an app raising itself) makes KWin switch
|
||||
that output to the window's desktop (which komorebi then follows);
|
||||
- a window moved by a script so that its middle is on the other output keeps its desktops: KWin
|
||||
moves a window to the new output's desktop only during an interactive move;
|
||||
- a window put on another desktop from outside raises `desktopsChanged` on the window, which the
|
||||
bridge listens to.
|
||||
|
||||
docs/dev/PLATFORM.md records these as the facts of KWin that komorebi depends on.
|
||||
"""
|
||||
|
||||
from itertools import count
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `kwin-contract`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
# per-output desktops are read when KWin starts, as komorebi's users have them after their first run
|
||||
machine.succeed(
|
||||
"runuser -u komorebi -- sh -c 'mkdir -p ~/.config"
|
||||
' && printf "[Windows]\\nPerOutputVirtualDesktops=true\\n" > ~/.config/kwinrc\''
|
||||
)
|
||||
kde = Kde.headless(machine, "main", size=(1920, 1080), outputs=2, scale=SCALE)
|
||||
|
||||
# what every script is given: the desktop each output shows, and a window by its title
|
||||
HELPERS = """
|
||||
function cur() {
|
||||
return workspace.screens.map(function (o) {
|
||||
return workspace.currentDesktopForScreen(o).name;
|
||||
}).join("/");
|
||||
}
|
||||
function win(title) {
|
||||
return workspace.windowList().filter(function (w) { return w.caption === title; })[0];
|
||||
}
|
||||
function names(ds) {
|
||||
return ds.map(function (d) { return d.name; }).join(",");
|
||||
}
|
||||
"""
|
||||
|
||||
def script(name: str, body: str, keep: bool = False) -> list[str]:
|
||||
return kde.kwin_script(name, HELPERS + body + '\nreport("done");\n', keep=keep)
|
||||
|
||||
def shows() -> str:
|
||||
"""What each output shows, as `first/second`."""
|
||||
lines = script(f"shows-{next(counter)}", "report(cur());")
|
||||
return lines[0] if lines else ""
|
||||
|
||||
counter = count(1)
|
||||
|
||||
print("== 1. two outputs, one desktop, and per-output desktops on")
|
||||
outputs = script(
|
||||
"outputs", 'report(workspace.screens.map(function (o) { return o.name; }).join(" "));'
|
||||
)
|
||||
print(f" outputs: {outputs}")
|
||||
names_of = outputs[0].split() if outputs else []
|
||||
checks.check("KWin has two outputs", len(names_of) == 2)
|
||||
checks.check("and one desktop", kde.desktops() == 1)
|
||||
checks.check(
|
||||
"kwinrc has per-output desktops on",
|
||||
kde.kwinrc("Windows", "PerOutputVirtualDesktops") == "true",
|
||||
)
|
||||
|
||||
print("== 2. a desktop created over D-Bus is a desktop of every output")
|
||||
kde.sh(
|
||||
"busctl --user call org.kde.KWin /VirtualDesktopManager"
|
||||
" org.kde.KWin.VirtualDesktopManager createDesktop us 1 two > /dev/null"
|
||||
)
|
||||
checks.check("KWin has two desktops", kde.wait_for(lambda: kde.desktops() == 2))
|
||||
desktops = script("desktops", "report(names(workspace.desktops));")
|
||||
checks.check(f"the script sees them in order: {desktops}", desktops[-1:] == ["Desktop 1,two"])
|
||||
checks.check("both outputs show the first", shows() == "Desktop 1/Desktop 1")
|
||||
|
||||
print("== 3. one output shows another desktop, and the other keeps its own")
|
||||
script(
|
||||
"listen",
|
||||
'workspace.currentDesktopChanged.connect(function () { report("changed", cur()); });',
|
||||
keep=True,
|
||||
)
|
||||
script(
|
||||
"switch",
|
||||
"workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);",
|
||||
)
|
||||
checks.check(
|
||||
"the first output shows the second desktop, and the second output the first",
|
||||
kde.wait_for(lambda: shows() == "two/Desktop 1"),
|
||||
)
|
||||
checks.check(
|
||||
"KWin said so with currentDesktopChanged",
|
||||
kde.wait_for(lambda: "changed two/Desktop 1" in kde.kwin_reports("listen")),
|
||||
)
|
||||
script(
|
||||
"back", "workspace.setCurrentDesktopForScreen(workspace.desktops[0], workspace.screens[0]);"
|
||||
)
|
||||
checks.check("and back", kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1"))
|
||||
|
||||
print("== 4. KWin focuses a window of the desktop it switched an output to")
|
||||
for title in ["w1", "w2"]:
|
||||
kde.spawn(f"foot -T {title} sleep 3000")
|
||||
kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30)
|
||||
script(
|
||||
"place",
|
||||
"""
|
||||
var d = workspace.desktops;
|
||||
var w1 = win("w1"), w2 = win("w2");
|
||||
w1.desktops = [d[0]];
|
||||
w1.frameGeometry = { x: 100, y: 100, width: 600, height: 400 };
|
||||
w2.desktops = [d[1]];
|
||||
w2.frameGeometry = { x: 800, y: 100, width: 600, height: 400 };
|
||||
workspace.activeWindow = w1;
|
||||
""",
|
||||
)
|
||||
checks.check(
|
||||
"w1 has the focus, on the first desktop",
|
||||
kde.wait_for(lambda: kde.title(kde.active()) == "w1"),
|
||||
)
|
||||
script(
|
||||
"to-two",
|
||||
"workspace.setCurrentDesktopForScreen(workspace.desktops[1], workspace.screens[0]);",
|
||||
)
|
||||
checks.check(
|
||||
"after the first output shows the second desktop, w2, which is on it, has the focus",
|
||||
kde.wait_for(lambda: kde.active() != "" and kde.title(kde.active()) == "w2"),
|
||||
)
|
||||
|
||||
print("== 5. activating a window on another desktop of its output switches that output to it")
|
||||
script("raise", 'workspace.activeWindow = win("w1");')
|
||||
checks.check(
|
||||
"the first output shows the first desktop again",
|
||||
kde.wait_for(lambda: shows() == "Desktop 1/Desktop 1"),
|
||||
)
|
||||
checks.check("and w1 has the focus", kde.wait_for(lambda: kde.title(kde.active()) == "w1"))
|
||||
|
||||
print("== 6. a window a script moves onto the other output keeps its desktops")
|
||||
script("cross", 'win("w1").frameGeometry = { x: 2300, y: 100, width: 600, height: 400 };')
|
||||
|
||||
def where_w1() -> str:
|
||||
lines = script(
|
||||
f"where-{next(counter)}",
|
||||
'var w = win("w1"); report(w.output.name + " " + names(w.desktops));',
|
||||
)
|
||||
return lines[0] if lines else ""
|
||||
|
||||
second = names_of[1] if len(names_of) == 2 else "?"
|
||||
checks.check(
|
||||
f"w1 is on {second} now, and still on the first desktop only",
|
||||
kde.wait_for(lambda: where_w1() == f"{second} Desktop 1"),
|
||||
)
|
||||
|
||||
print("== 7. a window put on another desktop from outside says so")
|
||||
script(
|
||||
"watch",
|
||||
'var w = win("w1"); w.desktopsChanged.connect(function () { report("moved", names(w.desktops)); });',
|
||||
keep=True,
|
||||
)
|
||||
kde.sh(f"kdotool set_desktop_for_window {kde.wid('w1')} 2")
|
||||
checks.check(
|
||||
"w1's desktopsChanged was raised, with the second desktop",
|
||||
kde.wait_for(lambda: "moved two" in kde.kwin_reports("watch")),
|
||||
)
|
||||
|
||||
kde.stop()
|
||||
@@ -0,0 +1,128 @@
|
||||
r"""The daemon reads a real KWin through its script. What only a real KWin can tell: that the script
|
||||
loads and reports the desktop, that KWin's signals reach the window manager as the events
|
||||
`komorebi/src/kwin/state.rs` and `komorebi/tests/wm_events.rs` feed it by hand, in the order KWin
|
||||
raised them (KWin activates a new window before it announces it), that a window giving itself
|
||||
another title is reported, and that it takes its script out of KWin when it stops.
|
||||
"""
|
||||
|
||||
import shlex
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde, daemon
|
||||
from komorebi_vm.daemon import Event
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `kwin-events`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
kde = Kde.headless(machine, "main", size=(1280, 720), scale=SCALE)
|
||||
|
||||
def daemon_log() -> str:
|
||||
return kde.komorebi_log()
|
||||
|
||||
def handled(event: Event) -> bool:
|
||||
return event in daemon.events(daemon_log())
|
||||
|
||||
kde.spawn("foot -T before sleep 3000")
|
||||
checks.check(
|
||||
"a window is open before komorebi starts",
|
||||
kde.wait_for(lambda: kde.wid("before") != "", timeout=30),
|
||||
)
|
||||
before = kde.wid("before")
|
||||
|
||||
kde.start_komorebi()
|
||||
checks.check(
|
||||
"the daemon loaded its script into KWin",
|
||||
kde.wait_for(lambda: "loaded the KWin bridge script" in daemon_log(), timeout=30),
|
||||
)
|
||||
checks.check("KWin runs the script", kde.script_loaded())
|
||||
checks.check(
|
||||
"the script reported the window that was already open",
|
||||
kde.wait_for(lambda: "1 valid windows identified" in daemon_log(), timeout=10),
|
||||
)
|
||||
checks.check("the daemon is still running", kde.komorebi_running())
|
||||
|
||||
print("== a window opens")
|
||||
kde.spawn("foot -T alpha sleep 3000")
|
||||
checks.check("KWin has it", kde.wait_for(lambda: kde.wid("alpha") != "", timeout=30))
|
||||
alpha = kde.wid("alpha")
|
||||
checks.check(
|
||||
"KWin's focus on it reached the daemon, by title",
|
||||
kde.wait_for(lambda: "alpha" in daemon.window_ids(daemon_log()), timeout=10),
|
||||
)
|
||||
ids = daemon.window_ids(daemon_log())
|
||||
n = ids.get("alpha", -1)
|
||||
shown = Event("Show", n, "WindowAdded")
|
||||
focused = Event("FocusChange", n, "WindowActivated")
|
||||
checks.check(
|
||||
"the daemon handled a Show for it", kde.wait_for(lambda: handled(shown), timeout=10)
|
||||
)
|
||||
checks.check("... and a FocusChange", kde.wait_for(lambda: handled(focused), timeout=10))
|
||||
seen = daemon.events(daemon_log())
|
||||
checks.check(
|
||||
"the Show came first, although KWin activates a window before it announces it",
|
||||
shown in seen and focused in seen and seen.index(shown) < seen.index(focused),
|
||||
)
|
||||
|
||||
print("== the focus moves")
|
||||
kde.activate(before)
|
||||
checks.check(
|
||||
"the window that was open before is focused, and the daemon knows it",
|
||||
kde.wait_for(lambda: "before" in daemon.window_ids(daemon_log()), timeout=10),
|
||||
)
|
||||
m = daemon.window_ids(daemon_log()).get("before", -1)
|
||||
checks.check(
|
||||
"a FocusChange for it",
|
||||
kde.wait_for(lambda: handled(Event("FocusChange", m, "WindowActivated")), timeout=10),
|
||||
)
|
||||
|
||||
print("== minimize, restore, close")
|
||||
kde.minimize(alpha)
|
||||
checks.check(
|
||||
"minimizing is a Minimize",
|
||||
kde.wait_for(lambda: handled(Event("Minimize", n, "WindowMinimized")), timeout=10),
|
||||
)
|
||||
kde.activate(alpha)
|
||||
checks.check(
|
||||
"activating a minimized window brings it back: a Restore",
|
||||
kde.wait_for(lambda: handled(Event("Restore", n, "WindowRestored")), timeout=10),
|
||||
)
|
||||
kde.close(alpha)
|
||||
checks.check(
|
||||
"closing is a Destroy",
|
||||
kde.wait_for(lambda: handled(Event("Destroy", n, "WindowRemoved")), timeout=10),
|
||||
)
|
||||
mine = [e.kind for e in daemon.events(daemon_log()) if e.window == n]
|
||||
print(f" the events of alpha, in order: {mine}")
|
||||
in_order = [kind for kind in mine if kind in ("Show", "Minimize", "Restore", "Destroy")]
|
||||
checks.check(
|
||||
"alpha's events came in the order they happened",
|
||||
in_order == ["Show", "Minimize", "Restore", "Destroy"],
|
||||
)
|
||||
|
||||
print("== a window gives itself another title")
|
||||
rename = 'sleep 4; printf "\\033]0;beta-renamed\\007"; sleep 3000'
|
||||
kde.spawn(f"foot -T beta sh -c {shlex.quote(rename)}")
|
||||
checks.check(
|
||||
"KWin's focus on it reached the daemon, by title",
|
||||
kde.wait_for(lambda: "beta" in daemon.window_ids(daemon_log()), timeout=30),
|
||||
)
|
||||
b = daemon.window_ids(daemon_log()).get("beta", -1)
|
||||
checks.check(
|
||||
"KWin has it under its new title",
|
||||
kde.wait_for(lambda: kde.wid("beta-renamed") != "", timeout=20),
|
||||
)
|
||||
checks.check(
|
||||
"the title change is a TitleUpdate",
|
||||
kde.wait_for(lambda: handled(Event("TitleUpdate", b, "CaptionChanged")), timeout=10),
|
||||
)
|
||||
|
||||
print("== stop")
|
||||
kde.stop_komorebi()
|
||||
checks.check("the daemon exited", not kde.komorebi_running())
|
||||
checks.check(
|
||||
"the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded(), timeout=10)
|
||||
)
|
||||
checks.check("the windows are still there", kde.wid("before") != "")
|
||||
|
||||
kde.stop()
|
||||
@@ -0,0 +1,115 @@
|
||||
"""What only KDE can tell about KWin restarting under a running daemon.
|
||||
|
||||
As when the compositor of a session crashes or is replaced: the session bus stays, KWin leaves it
|
||||
and comes back, and the clients of the old KWin go with it. What only a real KWin can tell is that
|
||||
the daemon sees KWin go and come back on the bus, that it takes every window of the old KWin out of
|
||||
its layout, that it loads its script into the new KWin, and that it tiles what opens there, right
|
||||
away. Twice, as the spike did.
|
||||
"""
|
||||
|
||||
from komorebi_vm import daemon
|
||||
from komorebi_vm.core.checks import Checks
|
||||
from komorebi_vm.core.platform import Client
|
||||
from komorebi_vm.kde_platform import KdePlatform
|
||||
from komorebi_vm.platforms.kde import support
|
||||
|
||||
|
||||
def run(platform: KdePlatform, checks: Checks, clients: list[Client]) -> None:
|
||||
"""Three windows, KWin restarts, windows open in the new KWin, and it restarts again. The
|
||||
daemon must not be running, with no window open. The daemon is stopped at the end."""
|
||||
kde = platform.kde
|
||||
W = platform.size[0] # noqa: N806
|
||||
|
||||
def daemon_log() -> str:
|
||||
return kde.komorebi_log()
|
||||
|
||||
def loads() -> int:
|
||||
"""How many times the daemon has loaded its script into a KWin."""
|
||||
return daemon_log().count("loaded the KWin bridge script")
|
||||
|
||||
def where_asked(title: str) -> bool:
|
||||
return support.where_asked(platform, title)
|
||||
|
||||
def open_window(title: str) -> None:
|
||||
kde.spawn(f"foot -T {title} sleep 3000")
|
||||
kde.wait_for(lambda: kde.wid(title) != "", timeout=30)
|
||||
kde.wait_for(lambda: title in daemon.window_ids(daemon_log()), timeout=10)
|
||||
|
||||
def destroyed(titles: list[str]) -> bool:
|
||||
"""The daemon took every one of these windows out of its layout."""
|
||||
log = daemon_log()
|
||||
ids = daemon.window_ids(log)
|
||||
gone = {e.window for e in daemon.events(log) if e.kind == "Destroy"}
|
||||
return all(ids.get(title) in gone for title in titles)
|
||||
|
||||
def alone(title: str) -> bool:
|
||||
"""The window is where the daemon asked, and the only one: it has the whole width."""
|
||||
return where_asked(title) and kde.rect(kde.wid(title)).w > W - 100
|
||||
|
||||
def side_by_side(a: str, b: str) -> bool:
|
||||
if not (where_asked(a) and where_asked(b)):
|
||||
return False
|
||||
ra, rb = kde.rect(kde.wid(a)), kde.rect(kde.wid(b))
|
||||
return not ra.overlaps(rb) and ra.w < W - 20 and rb.w < W - 20
|
||||
|
||||
def restart(old: list[str], loaded: int) -> None:
|
||||
kde.restart_kwin()
|
||||
checks.check(
|
||||
"the daemon saw KWin go",
|
||||
kde.wait_for(lambda: "KWin went away" in daemon_log(), timeout=10),
|
||||
)
|
||||
checks.check(
|
||||
"every window of the old KWin left the layout", kde.wait_for(lambda: destroyed(old))
|
||||
)
|
||||
checks.check(
|
||||
"the daemon loaded its script into the new KWin",
|
||||
kde.wait_for(lambda: loads() == loaded, timeout=30),
|
||||
)
|
||||
checks.check("the new KWin runs the script", kde.wait_for(kde.script_loaded))
|
||||
checks.check("the daemon is still running", kde.komorebi_running())
|
||||
|
||||
print("== 1. three windows are tiled")
|
||||
platform.start_komorebi()
|
||||
checks.check(
|
||||
"the daemon loaded its script into KWin", kde.wait_for(lambda: loads() == 1, timeout=30)
|
||||
)
|
||||
before = ["pre1", "pre2", "pre3"]
|
||||
for title in before:
|
||||
open_window(title)
|
||||
checks.check(
|
||||
"every window is where the daemon asked for it",
|
||||
kde.wait_for(lambda: all(where_asked(t) for t in before), timeout=20),
|
||||
)
|
||||
|
||||
print("== 2. KWin restarts")
|
||||
restart(before, loaded=2)
|
||||
checks.check("the windows of the old KWin are gone", all(kde.wid(t) == "" for t in before))
|
||||
|
||||
print("== 3. windows open in the new KWin")
|
||||
open_window("post1")
|
||||
checks.check("the first is tiled on its own", kde.wait_for(lambda: alone("post1"), timeout=20))
|
||||
open_window("post2")
|
||||
checks.check(
|
||||
"the second is tiled next to it",
|
||||
kde.wait_for(lambda: side_by_side("post1", "post2"), timeout=20),
|
||||
)
|
||||
for title in ["post1", "post2"]:
|
||||
asked = daemon.asked(daemon_log(), title)
|
||||
print(f" {title}: asked {asked}, has {kde.rect(kde.wid(title))}")
|
||||
|
||||
print("== 4. KWin restarts again, with one window open")
|
||||
kde.close(kde.wid("post2"))
|
||||
checks.check(
|
||||
"the window that is left has the screen", kde.wait_for(lambda: alone("post1"), timeout=20)
|
||||
)
|
||||
restart(["post1"], loaded=3)
|
||||
open_window("again")
|
||||
checks.check(
|
||||
"a window opened in the third KWin is tiled",
|
||||
kde.wait_for(lambda: alone("again"), timeout=20),
|
||||
)
|
||||
|
||||
print("== 5. stop")
|
||||
kde.stop_komorebi()
|
||||
checks.check("the daemon exited", not kde.komorebi_running())
|
||||
checks.check("the script is no longer in KWin", kde.wait_for(lambda: not kde.script_loaded()))
|
||||
@@ -0,0 +1,82 @@
|
||||
r"""How long a retile takes to reach the windows of a real KWin, measured on the session bus: from
|
||||
the moment the daemon answers the bridge's held call with a batch of new frames, to the last
|
||||
frame KWin reports for one of the windows it moved, the client's answer included. Every number
|
||||
here comes from KWin and real clients; the Rust tests cannot measure it. The output is large, so
|
||||
that ten windows in komorebi's default layout all have room.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from komorebi_vm import Checks, Kde, daemon, latency
|
||||
|
||||
W, H = 3840, 2160
|
||||
WINDOWS = 10
|
||||
ROUNDS = 10
|
||||
BUS_LOG = "/tmp/komorebi-bus.log"
|
||||
|
||||
|
||||
def run(machine: Any, checks: Checks, scale: float) -> None:
|
||||
"""Runs the checks of the suite `latency`, which the suite script calls."""
|
||||
SCALE = scale # noqa: N806
|
||||
kde = Kde.headless(machine, "main", size=(W, H), scale=SCALE)
|
||||
kde.start_komorebi()
|
||||
checks.check(
|
||||
"the daemon loaded its script into KWin",
|
||||
kde.wait_for(lambda: "loaded the KWin bridge script" in kde.komorebi_log(), timeout=30),
|
||||
)
|
||||
kde.monitor_bridge(BUS_LOG)
|
||||
|
||||
titles = [f"w{n}" for n in range(1, WINDOWS + 1)]
|
||||
for title in titles:
|
||||
kde.spawn(f"foot -T {title} sleep 3000")
|
||||
kde.wait_for(lambda title=title: kde.wid(title) != "", timeout=30)
|
||||
|
||||
def shown() -> int:
|
||||
return sum(1 for e in daemon.events(kde.komorebi_log()) if e.kind == "Show")
|
||||
|
||||
checks.check(f"the daemon tiles all {WINDOWS}", kde.wait_for(lambda: shown() >= WINDOWS))
|
||||
|
||||
def measured() -> list[latency.Round]:
|
||||
return latency.rounds(machine.succeed(f"cat {BUS_LOG}"))
|
||||
|
||||
def settled_after(count: int) -> bool:
|
||||
"""A round after the first `count` is over: its windows all reported, and then 0.3 s passed."""
|
||||
done = measured()
|
||||
if len(done) <= count or done[-1].seconds is None:
|
||||
return False
|
||||
now = float(machine.succeed("date +%s.%N"))
|
||||
return now - (done[-1].sent + done[-1].seconds) > 0.3
|
||||
|
||||
kde.wait_for(lambda: settled_after(0), timeout=10)
|
||||
start = len(measured())
|
||||
|
||||
# each round takes one window out of the layout and puts it back: two retiles
|
||||
for title in titles[:ROUNDS]:
|
||||
wid = kde.wid(title)
|
||||
count = len(measured())
|
||||
kde.minimize(wid)
|
||||
kde.wait_for(lambda count=count: settled_after(count), timeout=10)
|
||||
count = len(measured())
|
||||
kde.activate(wid)
|
||||
kde.wait_for(lambda count=count: settled_after(count), timeout=10)
|
||||
|
||||
# the rounds before `start` tiled the windows as they opened
|
||||
rounds = measured()[start:]
|
||||
settled = [r.seconds * 1000 for r in rounds if r.seconds is not None]
|
||||
moved = sum(r.windows for r in rounds) / max(1, len(rounds))
|
||||
print(
|
||||
f" {len(rounds)} retiles, {moved:.1f} windows moved by each on average, scale {SCALE}"
|
||||
)
|
||||
if settled:
|
||||
p50, p95 = latency.percentile(settled, 0.5), latency.percentile(settled, 0.95)
|
||||
print(f" from the batch to the last frame: p50 {p50:.1f} ms, p95 {p95:.1f} ms,")
|
||||
print(f" max {max(settled):.1f} ms, min {min(settled):.1f} ms")
|
||||
checks.check(f"{2 * ROUNDS} retiles were measured", len(rounds) == 2 * ROUNDS)
|
||||
checks.check("every window of every retile reported its frame", len(settled) == len(rounds))
|
||||
checks.check(
|
||||
"a retile reaches the windows within 100 ms (times the machine's scale), at p95",
|
||||
bool(settled) and latency.percentile(settled, 0.95) <= 100 * SCALE,
|
||||
)
|
||||
|
||||
kde.stop_komorebi()
|
||||
kde.stop()
|
||||
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user