mirror of
https://github.com/LGUG2Z/komorebi.git
synced 2026-12-02 21:24:12 +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,107 @@
|
||||
# KRDP, Plasma's RDP server, in the Plasma session of every user who logs in. The session guest
|
||||
# of plasma-vm.nix enables it, and so does the VM suite `rdp`, which checks that a client can log
|
||||
# in and get a picture of the desktop (docs/dev/PLATFORM.md says what it does not check).
|
||||
#
|
||||
# The password is not in the repository: the unit starts once the user has written one to
|
||||
# ~/.config/komorebi-vm/rdp-password, and a client logs in with the user's name and that password.
|
||||
# A guest whose password comes from outside, as the demo guest's does (run-kde.nix), names a file
|
||||
# of the guest in `passwordFile`, which the unit reads in place of that one when it is there.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
cfg = config.komorebi.krdp;
|
||||
|
||||
# KRDP asks for the H.264 Constrained Baseline profile and nothing else. A guest whose VA-API
|
||||
# drives the host's encoder (virgl, with the QEMU of run-kde.nix) lists Main and High and no
|
||||
# Constrained Baseline, so ffmpeg's h264_vaapi finds no profile it can use and KRDP encodes on
|
||||
# the CPUs. Main is in RDP's H.264 mode as well, and the software encoder takes it too.
|
||||
krdp = pkgs.kdePackages.krdp.overrideAttrs (old: {
|
||||
postPatch = (old.postPatch or "") + ''
|
||||
substituteInPlace src/VideoStreamSurface.cpp --replace-fail H264Baseline H264Main
|
||||
'';
|
||||
});
|
||||
|
||||
startKrdp = pkgs.writeShellScript "krdp-start" ''
|
||||
set -eu
|
||||
dir=$HOME/.config/komorebi-vm
|
||||
password_file=$dir/rdp-password
|
||||
${lib.optionalString (cfg.passwordFile != null) ''
|
||||
if [ -r ${lib.escapeShellArg cfg.passwordFile} ]; then
|
||||
password_file=${lib.escapeShellArg cfg.passwordFile}
|
||||
fi
|
||||
''}
|
||||
mkdir -p "$dir"
|
||||
# krdpserver refuses to run without a TLS certificate and key (its --help promises a temporary
|
||||
# one, but it only checks that the files exist), so make a throwaway self-signed pair
|
||||
if [ ! -f "$dir/rdp.crt" ] || [ ! -f "$dir/rdp.key" ]; then
|
||||
${pkgs.openssl}/bin/openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -subj /CN=komorebi-vm \
|
||||
-addext subjectAltName=DNS:localhost,IP:127.0.0.1 -keyout "$dir/rdp.key" -out "$dir/rdp.crt"
|
||||
chmod 600 "$dir/rdp.key"
|
||||
fi
|
||||
# --plasma asks KWin for the screen and for input directly, with no portal prompt to click
|
||||
exec ${krdp}/bin/krdpserver --plasma --address 0.0.0.0 --port 3389 \
|
||||
--certificate "$dir/rdp.crt" --certificate-key "$dir/rdp.key" \
|
||||
--username "$USER" --password "$(cat "$password_file")"
|
||||
'';
|
||||
in
|
||||
{
|
||||
options.komorebi.krdp = {
|
||||
enable = lib.mkEnableOption "KRDP, an RDP server, in every Plasma session";
|
||||
|
||||
passwordFile = lib.mkOption {
|
||||
type = lib.types.nullOr lib.types.str;
|
||||
default = null;
|
||||
example = "/run/run-kde-guest/rdp-password";
|
||||
description = ''
|
||||
The path, in the guest, of a file with the password a client logs in with. It is a path in
|
||||
the running guest and not a file of the Nix store, so that no password is part of the
|
||||
system. The unit reads it in place of `~/.config/komorebi-vm/rdp-password` when it exists,
|
||||
and starts when either exists.
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
environment.systemPackages = [
|
||||
krdp
|
||||
# A client, to try the server from inside the guest. FreeRDP decodes H.264 with OpenH264
|
||||
# when it is built with it, and OpenH264 shows nothing of the video KRDP sends; without it,
|
||||
# FreeRDP decodes with FFmpeg (the VM suite `rdp`, docs/dev/PLATFORM.md).
|
||||
(pkgs.freerdp.override { openh264 = null; })
|
||||
];
|
||||
|
||||
# krdp streams the screen through pipewire
|
||||
services.pipewire = {
|
||||
enable = true;
|
||||
wireplumber.enable = true;
|
||||
};
|
||||
security.rtkit.enable = true;
|
||||
|
||||
networking.firewall.allowedTCPPorts = [ 3389 ];
|
||||
|
||||
systemd.user.services.krdp = {
|
||||
description = "RDP into this Plasma session";
|
||||
wantedBy = [ "plasma-workspace.target" ];
|
||||
after = [ "plasma-core.target" ];
|
||||
# with no password the unit is skipped, not failed: `systemctl --user start krdp` once the
|
||||
# file is there
|
||||
unitConfig.ConditionPathExists =
|
||||
if cfg.passwordFile == null then
|
||||
"%h/.config/komorebi-vm/rdp-password"
|
||||
else
|
||||
[
|
||||
"|%h/.config/komorebi-vm/rdp-password"
|
||||
"|${cfg.passwordFile}"
|
||||
];
|
||||
serviceConfig = {
|
||||
ExecStart = startKrdp;
|
||||
Restart = "on-failure";
|
||||
RestartSec = 3;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
mesa: let go of the fence a surface is flushed or processed again over
|
||||
|
||||
vlVaSurfaceFlush() (the upload of an image, the clear of a new surface) and the end of a
|
||||
video-processing pass (vl_compositor_proc: the scale_vaapi of FFmpeg, the blit of
|
||||
vaPutImage) flush into surf->pipe_fence, which gets the new fence of the flush and loses
|
||||
the old one. The only places that let go of it are vaSyncSurface() and the destruction of
|
||||
the surface, so a surface that is flushed again before a sync, which one of a pool is,
|
||||
leaves the fence it had behind.
|
||||
|
||||
With virgl a fence owns a file descriptor: the sync_file that the kernel returns for the
|
||||
out-fence of the execbuffer (VIRTGPU_EXECBUF_FENCE_FD_OUT), closed when the fence is freed.
|
||||
The guest's KRDP kept one open for every frame it captured until it had 1024 of them,
|
||||
after which every ioctl failed with EMFILE ("got error from kernel - expect bad rendering
|
||||
24") and the picture froze.
|
||||
|
||||
Release the fence a flush is about to replace. The newer one covers it: both are fences of
|
||||
the same context.
|
||||
|
||||
--- a/src/gallium/frontends/va/surface.c 2026-10-28 17:58:18.769410786 -0700
|
||||
+++ b/src/gallium/frontends/va/surface.c 2026-10-28 17:58:30.469583700 -0700
|
||||
@@ -812,6 +812,14 @@
|
||||
void
|
||||
vlVaSurfaceFlush(vlVaDriver *drv, vlVaSurface *surf)
|
||||
{
|
||||
+ /* A flush makes a new fence, which replaces the one in the surface: the one of the last flush
|
||||
+ * is what vaSyncSurface waits for, and it is only let go of there and when the surface is
|
||||
+ * destroyed. Replaced without a release, its fence is never freed, and with a driver whose
|
||||
+ * fences hold a file descriptor (virgl: a sync_file) a surface that is flushed again and
|
||||
+ * again, as the ones of a pool are, leaves one open a time until there are no more. */
|
||||
+ if (surf->pipe_fence)
|
||||
+ drv->pipe->screen->fence_reference(drv->pipe->screen, &surf->pipe_fence, NULL);
|
||||
+
|
||||
drv->pipe->flush(drv->pipe, &surf->pipe_fence,
|
||||
drv->has_external_handles ? 0 : PIPE_FLUSH_ASYNC);
|
||||
}
|
||||
--- a/src/gallium/auxiliary/vl/vl_compositor_proc.c 2026-10-28 17:58:18.771011962 -0700
|
||||
+++ b/src/gallium/auxiliary/vl/vl_compositor_proc.c 2026-10-28 17:58:30.814280800 -0700
|
||||
@@ -185,8 +185,17 @@
|
||||
struct pipe_picture_desc *picture)
|
||||
{
|
||||
struct vl_compositor_proc *proc = (struct vl_compositor_proc *)codec;
|
||||
+ struct pipe_context *context = proc->b.context;
|
||||
|
||||
- proc->b.context->flush(proc->b.context, picture->out_pipe_fence, picture->flush_flags);
|
||||
+ /* out_pipe_fence is the pipe_fence of the target surface (vlVaEndPicture, vlVaPutImage), and
|
||||
+ * the flush makes a new fence for it. The last one is what a sync waits for, so the one it
|
||||
+ * replaces is let go of here: left, it is never freed, and with virgl its fence is a
|
||||
+ * sync_file, one more of them open for every frame of a pooled surface that is processed
|
||||
+ * again before it is synced. */
|
||||
+ if (picture->out_pipe_fence && *picture->out_pipe_fence)
|
||||
+ context->screen->fence_reference(context->screen, picture->out_pipe_fence, NULL);
|
||||
+
|
||||
+ context->flush(context, picture->out_pipe_fence, picture->flush_flags);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
vl/compositor: give the graphics RGB to YUV conversion its matrix
|
||||
|
||||
compositor_proc_process_frame() fills a matrix for each conversion: for RGB to RGB and
|
||||
YUV to RGB it fills both yuv2rgb and csc_matrix, for RGB to YUV only rgb2yuv. The compute
|
||||
compositor reads rgb2yuv, but the graphics compositor uploads csc_matrix (set_csc_matrix()
|
||||
in vl_compositor_gfx.c) to the constants of its fragment shaders, and for RGB to YUV
|
||||
csc_matrix still held what vl_compositor_init_state() put in it, the YUV to RGB matrix of
|
||||
BT.709 for NV12. Only radeonsi sets prefer_compute_for_multimedia, so every other driver
|
||||
takes the graphics path: on virgl scale_vaapi=format=nv12 of an RGB surface (what
|
||||
KPipeWire and KRDP do with every frame of a screen) gave Y = 1.164 R + 1.793 B - 0.973,
|
||||
that is 0 for a gray of 0 to 118 and a wrong picture above.
|
||||
|
||||
Fill csc_matrix with the RGB to YUV matrix too, as the other conversions do.
|
||||
|
||||
diff --git a/src/gallium/auxiliary/vl/vl_compositor_proc.c b/src/gallium/auxiliary/vl/vl_compositor_proc.c
|
||||
index 7de461e..d794038 100644
|
||||
--- a/src/gallium/auxiliary/vl/vl_compositor_proc.c
|
||||
+++ b/src/gallium/auxiliary/vl/vl_compositor_proc.c
|
||||
@@ -93,6 +93,11 @@ compositor_proc_process_frame(struct pipe_video_codec *codec,
|
||||
/* RGB to YUV */
|
||||
vl_csc_get_rgbyuv_matrix(param->out_matrix_coefficients, src->buffer_format, dst->buffer_format,
|
||||
param->in_color_range, param->out_color_range, &proc->cstate.rgb2yuv);
|
||||
+ /* The compute compositor reads rgb2yuv, but the graphics one (the only one that drivers
|
||||
+ * without prefer_compute_for_multimedia, like virgl, ever use) uploads csc_matrix to its
|
||||
+ * shader constants, and it still held the YUV to RGB default of vl_compositor_init_state():
|
||||
+ * the RGB to YUV fragment shaders then made nonsense of the picture. */
|
||||
+ memcpy(&proc->cstate.csc_matrix, &proc->cstate.rgb2yuv, sizeof(vl_csc_matrix));
|
||||
}
|
||||
|
||||
vl_csc_get_primaries_matrix(param->in_color_primaries, param->out_color_primaries,
|
||||
@@ -0,0 +1,57 @@
|
||||
{ lib, pkgs, ... }:
|
||||
|
||||
# The Plasma session guest as a plain disk image, for a hypervisor with a GPU: UTM on Apple Silicon
|
||||
# runs QEMU with virtio-gpu-gl (virgl over ANGLE/CoreGL), which the QEMU in nixpkgs, and so the
|
||||
# 9p-booted `plasma-vm-session`, cannot: that one composites with llvmpipe on the CPU.
|
||||
#
|
||||
# This is the same session as plasma-vm.nix (komorebi from the module, KRDP), booted from its own
|
||||
# disk by UEFI instead of from a kernel and the host's /nix/store. docs/dev/utm.md says how to
|
||||
# install it onto a disk image and point UTM at it.
|
||||
{
|
||||
imports = [ ./plasma-vm.nix ];
|
||||
|
||||
komorebi.plasmaVm.session = true;
|
||||
|
||||
networking.hostName = lib.mkOverride 40 "plasma-utm";
|
||||
|
||||
boot.loader = {
|
||||
grub = {
|
||||
enable = true;
|
||||
efiSupport = true;
|
||||
efiInstallAsRemovable = true;
|
||||
device = "nodev";
|
||||
};
|
||||
efi.canTouchEfiVariables = false;
|
||||
timeout = 1;
|
||||
};
|
||||
|
||||
boot.initrd.availableKernelModules = [
|
||||
"virtio_pci"
|
||||
"virtio_blk"
|
||||
"virtio_net"
|
||||
"virtio_scsi"
|
||||
"xhci_pci"
|
||||
"usbhid"
|
||||
];
|
||||
# kms from the start, so that sddm has a screen to start on
|
||||
boot.initrd.kernelModules = [ "virtio_gpu" ];
|
||||
boot.kernelParams = [ "console=tty0" ];
|
||||
boot.growPartition = true;
|
||||
|
||||
fileSystems."/" = {
|
||||
device = "/dev/disk/by-label/nixos";
|
||||
fsType = "ext4";
|
||||
autoResize = true;
|
||||
};
|
||||
fileSystems."/boot" = {
|
||||
device = "/dev/disk/by-label/ESP";
|
||||
fsType = "vfat";
|
||||
};
|
||||
|
||||
# the window follows the guest's resolution, and the clipboard is shared
|
||||
services.spice-vdagentd.enable = true;
|
||||
services.qemuGuest.enable = true;
|
||||
|
||||
# to check that the session really is on the GPU: `eglinfo | grep -i renderer` says virgl
|
||||
environment.systemPackages = [ pkgs.mesa-demos ];
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
hostPkgs,
|
||||
...
|
||||
}:
|
||||
|
||||
# A NixOS Plasma 6 guest to develop and test against a real KWin, with komorebi installed by the
|
||||
# flake's module, `services.komorebi`, from the flake's packages. The flake builds it for an Apple
|
||||
# silicon Mac, which runs it under QEMU with HVF, and for a Linux machine, which runs it under QEMU
|
||||
# with KVM; docs/dev/utm.md says how to build and run it. The system of the guest and the packages
|
||||
# of the machine that runs QEMU (`hostPkgs`) come from the flake, so that one file serves them all.
|
||||
#
|
||||
# The guest mounts the repository at /repo, and keeps its disk in the directory it is started
|
||||
# from, which is best .vm (gitignored):
|
||||
#
|
||||
# nix build .#nixosConfigurations.plasma-vm.config.system.build.vm -o .vm/result-plasma-vm
|
||||
# cd .vm && KOMOREBI_REPO=$PWD/.. ./result-plasma-vm/bin/run-plasma-vm-vm
|
||||
#
|
||||
# The console, in the terminal that runs the guest, is logged in as the user `komorebi`. ssh is
|
||||
# forwarded to localhost:2222 (2223 for the session), for the keys in ~/.ssh/authorized_keys of
|
||||
# that user, which the guest's disk keeps.
|
||||
#
|
||||
# The session variant is the one to live in: Plasma logs in by itself, the module's unit runs
|
||||
# komorebi in it, and it can be reached over RDP (krdp.nix).
|
||||
let
|
||||
cfg = config.komorebi.plasmaVm;
|
||||
|
||||
# The guest's one display, a virtio-gpu, so that KWin has a DRM device to draw on. The machine of
|
||||
# an aarch64 guest has no display of its own. The machine of an x86_64 guest has a VGA, which QEMU
|
||||
# adds unless it is told not to, and KWin would draw on it as well as on the virtio-gpu: a second
|
||||
# head. An x86_64 guest gets `virtio-vga`, a virtio-gpu that is also the VGA, in its place.
|
||||
gpu =
|
||||
args:
|
||||
if pkgs.stdenv.hostPlatform.isx86_64 then
|
||||
[
|
||||
"-vga none"
|
||||
"-device virtio-vga${args}"
|
||||
]
|
||||
else
|
||||
[ "-device virtio-gpu-pci${args}" ];
|
||||
in
|
||||
{
|
||||
imports = [ ./krdp.nix ];
|
||||
|
||||
options.komorebi.plasmaVm = {
|
||||
session = lib.mkEnableOption ''
|
||||
a full autologin Plasma Wayland session (sddm + plasmashell), in addition to the headless
|
||||
`kwin_wayland --virtual` workflow that is always available from the console and over ssh
|
||||
'';
|
||||
|
||||
display = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
Whether the runner gives the guest its display device, a virtio-gpu. A guest that sets this
|
||||
to false is started with a display device of its own choosing, which can then differ from
|
||||
one start to the next: `run-kde` starts the demo guest (run-kde.nix) with a software
|
||||
`virtio-vga` or with a `virtio-vga-gl` that renders on the host's GPU, from one closure and
|
||||
one disk.
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkMerge [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
networking.hostName = "plasma-vm";
|
||||
|
||||
services.desktopManager.plasma6.enable = true;
|
||||
programs.dconf.enable = true;
|
||||
# mesa (llvmpipe over the virtio-gpu render node) so kwin can composite with GL
|
||||
hardware.graphics.enable = true;
|
||||
fonts.enableDefaultPackages = true;
|
||||
|
||||
# komorebi and komorebic, from the flake's packages; the unit starts with a Plasma session
|
||||
services.komorebi.enable = true;
|
||||
|
||||
services.openssh = {
|
||||
enable = true;
|
||||
settings = {
|
||||
PasswordAuthentication = false;
|
||||
PermitRootLogin = "no";
|
||||
};
|
||||
};
|
||||
|
||||
# the way in before any key is in ~/.ssh/authorized_keys: there is no password anywhere
|
||||
services.getty.autologinUser = "komorebi";
|
||||
|
||||
users.users.komorebi = {
|
||||
isNormalUser = true;
|
||||
uid = 1000;
|
||||
extraGroups = [
|
||||
"wheel"
|
||||
"video"
|
||||
"render"
|
||||
];
|
||||
# keep a user manager (and XDG_RUNTIME_DIR) alive across ssh sessions
|
||||
linger = true;
|
||||
};
|
||||
security.sudo.wheelNeedsPassword = false;
|
||||
|
||||
nix.settings.experimental-features = [
|
||||
"nix-command"
|
||||
"flakes"
|
||||
];
|
||||
|
||||
environment.systemPackages = with pkgs; [
|
||||
# clients to tile: Qt/KDE, GTK3/4 (CSD), Electron-ish via firefox, plain wayland, XWayland
|
||||
kdePackages.konsole
|
||||
kdePackages.dolphin
|
||||
kdePackages.kate
|
||||
kdePackages.spectacle
|
||||
firefox
|
||||
gnome-text-editor
|
||||
gnome-calculator
|
||||
foot
|
||||
xterm
|
||||
|
||||
# poking at KWin
|
||||
kdePackages.qttools # qdbus6
|
||||
dbus
|
||||
jq
|
||||
kdotool
|
||||
strace
|
||||
|
||||
# installing plasma-utm onto a disk image (docs/dev/utm.md)
|
||||
nixos-install-tools
|
||||
dosfstools
|
||||
parted
|
||||
e2fsprogs
|
||||
|
||||
# building komorebi from /repo in the guest
|
||||
rustc
|
||||
cargo
|
||||
gcc
|
||||
pkg-config
|
||||
git
|
||||
rsync
|
||||
htop
|
||||
];
|
||||
|
||||
environment.sessionVariables = {
|
||||
# kwin refuses to load animating effects (including the stock scripted ones) under software
|
||||
# rendering; llvmpipe is all this vm has
|
||||
KWIN_EFFECTS_FORCE_ANIMATIONS = "1";
|
||||
# always build in guest-local storage; /repo is a 9p mount and is slow for target dirs
|
||||
CARGO_TARGET_DIR = "/home/komorebi/target";
|
||||
};
|
||||
|
||||
virtualisation.vmVariant = {
|
||||
virtualisation = {
|
||||
host.pkgs = hostPkgs;
|
||||
qemu.forceAccel = true;
|
||||
cores = 6;
|
||||
memorySize = 8192;
|
||||
diskSize = 20 * 1024;
|
||||
graphics = false;
|
||||
# no display, but a gpu so there is a drm render node
|
||||
qemu.options = lib.mkIf (cfg.display && !cfg.session) (gpu "");
|
||||
forwardPorts = [
|
||||
{
|
||||
from = "host";
|
||||
host.address = "127.0.0.1";
|
||||
host.port = if cfg.session then 2223 else 2222;
|
||||
guest.port = 22;
|
||||
}
|
||||
];
|
||||
sharedDirectories.repo = {
|
||||
# the runner says so when it is not set
|
||||
source = "\${KOMOREBI_REPO:?set KOMOREBI_REPO to the root of the repository}";
|
||||
target = "/repo";
|
||||
writable = true;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
(lib.mkIf cfg.session {
|
||||
# a separate disk image (named after the host) and ssh port so both vms can run at once
|
||||
networking.hostName = lib.mkForce "plasma-vm-session";
|
||||
services.displayManager = {
|
||||
sddm = {
|
||||
enable = true;
|
||||
wayland.enable = true;
|
||||
};
|
||||
autoLogin = {
|
||||
enable = true;
|
||||
user = "komorebi";
|
||||
};
|
||||
defaultSession = "plasma";
|
||||
};
|
||||
# kwin drives virtio-gpu through drm on the primary node; that is the only place mesa's software
|
||||
# rasterizer can allocate buffers (see docs/dev/PLATFORM.md: the headless --virtual backend
|
||||
# cannot)
|
||||
virtualisation.vmVariant.virtualisation.qemu.options = lib.mkIf cfg.display (
|
||||
gpu ",xres=1920,yres=1080"
|
||||
);
|
||||
# an idle lock screen or dimmed display changes how kwin animates and what screenshots show
|
||||
environment.etc."xdg/kscreenlockerrc".text = ''
|
||||
[Daemon]
|
||||
Autolock=false
|
||||
LockOnResume=false
|
||||
'';
|
||||
# and so does a display that has gone to sleep: with the output off, KWin sends no frame
|
||||
# callbacks, so clients stop answering resizes and every window stays where it was while komorebi
|
||||
# asks for another place (found on the UTM guest after it sat idle: black screenshots, nothing tiled)
|
||||
environment.etc."xdg/powerdevilrc".text = ''
|
||||
[AC][Display]
|
||||
DimDisplayWhenIdle=false
|
||||
TurnOffDisplayWhenIdle=false
|
||||
|
||||
[AC][SuspendAndShutdown]
|
||||
AutoSuspendAction=0
|
||||
'';
|
||||
|
||||
komorebi.krdp.enable = true;
|
||||
|
||||
# only the host's loopback reaches it
|
||||
virtualisation.vmVariant.virtualisation.forwardPorts = [
|
||||
{
|
||||
from = "host";
|
||||
host.address = "127.0.0.1";
|
||||
host.port = 3389;
|
||||
guest.port = 3389;
|
||||
}
|
||||
];
|
||||
})
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
virtio-gpu: let virglrenderer use video encode and decode
|
||||
|
||||
virglrenderer can pass a guest's VA-API video encode and decode to the host's
|
||||
(virtio_gpu_drv_video in Mesa), but only when asked: with
|
||||
VIRGL_RENDERER_USE_VIDEO, and with a get_drm_fd callback to say which DRM node to
|
||||
open the host's video device on. QEMU passes neither, so a guest's vainfo lists
|
||||
VideoProc and no encoder. VIRGL_RENDERER_USE_VIDEO is only defined with
|
||||
VIRGL_RENDERER_UNSTABLE_APIS, which the build has to set.
|
||||
|
||||
--- a/hw/display/virtio-gpu-virgl.c 2026-10-28 15:30:25.853615969 -0700
|
||||
+++ b/hw/display/virtio-gpu-virgl.c 2026-10-28 15:30:25.853715164 -0700
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "qemu/osdep.h"
|
||||
#include "qemu/error-report.h"
|
||||
#include "qemu/iov.h"
|
||||
+#include "qemu/drm.h"
|
||||
#include "trace.h"
|
||||
#include "hw/virtio/virtio.h"
|
||||
#include "hw/virtio/virtio-gpu.h"
|
||||
@@ -1345,6 +1346,18 @@
|
||||
return qemu_console_gl_ctx_make_current(g->parent_obj.scanout[scanout_idx].con, qctx);
|
||||
}
|
||||
|
||||
+#ifdef VIRGL_RENDERER_USE_VIDEO
|
||||
+/*
|
||||
+ * virglrenderer opens the host's video encoder and decoder (VA-API) on a DRM
|
||||
+ * node of its caller's choosing, and disables video when it has none to ask
|
||||
+ * for. It owns the fd it gets and closes it.
|
||||
+ */
|
||||
+static int virgl_get_drm_fd(void *opaque)
|
||||
+{
|
||||
+ return qemu_drm_rendernode_open(NULL);
|
||||
+}
|
||||
+#endif
|
||||
+
|
||||
static struct virgl_renderer_callbacks virtio_gpu_3d_cbs = {
|
||||
#if VIRGL_VERSION_MAJOR >= 1
|
||||
.version = 3,
|
||||
@@ -1453,6 +1466,10 @@
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
+#ifdef VIRGL_RENDERER_USE_VIDEO
|
||||
+ virtio_gpu_3d_cbs.get_drm_fd = virgl_get_drm_fd;
|
||||
+ flags |= VIRGL_RENDERER_USE_VIDEO;
|
||||
+#endif
|
||||
#ifdef VIRGL_RENDERER_D3D11_SHARE_TEXTURE
|
||||
if (qemu_egl_angle_d3d) {
|
||||
flags |= VIRGL_RENDERER_D3D11_SHARE_TEXTURE;
|
||||
@@ -0,0 +1,441 @@
|
||||
# The demo guest of `run-kde`: a Plasma session in which komorebi tiles a few windows that open by
|
||||
# themselves, with a cheat sheet to start from. It is a module to put on the session guest
|
||||
# (plasma-vm.nix with `session` and not `display`: the flake's `run-kde-x86_64` and
|
||||
# `run-kde-aarch64`), and the VM suite `run-kde` puts it on the session node, so that what the
|
||||
# command starts is what CI boots.
|
||||
#
|
||||
# The closure is the same for everyone: no password, no key and no configuration of a person is in
|
||||
# it. The host shares a directory, which the guest mounts at /run/run-kde, with
|
||||
#
|
||||
# rdp-password the password a client logs in to RDP with
|
||||
# ssh_key.pub the public key that may log in over ssh
|
||||
#
|
||||
# and the guest takes them at boot (`run-kde-credentials`). What a person's own run needs at start
|
||||
# up, the memory, the ports, the display device and the repository, comes from the environment of
|
||||
# the runner, which `run-kde` sets (docs/dev/utm.md, docs/trying-it.md). The guest shows a window
|
||||
# through QEMU or is reached over RDP, and the terminal of whoever starts it is its console.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
# where the host's directory is mounted, and where the guest keeps what it takes from it
|
||||
shared = "/run/run-kde";
|
||||
taken = "/run/run-kde-guest";
|
||||
|
||||
user = "komorebi";
|
||||
|
||||
cheatSheet = pkgs.writeText "run-kde-cheat-sheet.txt" ''
|
||||
komorebi for KDE tiles the windows of this Plasma session.
|
||||
|
||||
The windows that opened by themselves (two terminals, Kate and Dolphin) share
|
||||
the screen. Open another one and it takes a tile of its own; close one and the
|
||||
others grow. This window is not tiled: komorebi leaves it alone. Press q to
|
||||
close it, and run `run-kde-cheat-sheet` in a terminal to open it again.
|
||||
|
||||
Start with these. Alt is either Alt key.
|
||||
|
||||
alt + h, j, k, l focus the window to the left, below, above, right
|
||||
alt + shift + h, j, k, l move the window that way
|
||||
alt + shift + return promote the window to the biggest tile
|
||||
alt + t take the window out of the tiles and back in
|
||||
alt + shift + f toggle monocle: the window fills the screen
|
||||
alt + 1 ... 9 show workspace 1 ... 9, each with its own layout
|
||||
alt + shift + 1 ... 9 move the window to that workspace
|
||||
alt + x, alt + y flip the layout horizontally, vertically
|
||||
|
||||
Or type the same in a terminal: `komorebic` is the program that every key
|
||||
runs.
|
||||
|
||||
komorebic state everything komorebi knows, as JSON
|
||||
komorebic change-layout columns bsp, rows, grid, scrolling, ...
|
||||
komorebic toggle-monocle
|
||||
komorebic retile put every window back in its tile
|
||||
komorebic border off borders are drawn by a KWin effect
|
||||
komorebic --help
|
||||
|
||||
komorebic reads its configuration from ~/.config/komorebi unless it is told
|
||||
where, and this machine starts komorebi with a file of its own, so tell it:
|
||||
|
||||
KOMOREBI_CONFIG_HOME=/etc/run-kde/config-home komorebic check
|
||||
|
||||
The key bindings komorebi reads are the whole of the file below, written in
|
||||
skhd's format. The repository is mounted at /repo: edit komorebi there and
|
||||
build it in this machine with `cargo`.
|
||||
|
||||
${builtins.readFile ../../docs/skhdrc.sample}
|
||||
'';
|
||||
|
||||
# the file the module starts the daemon with, which is the `--config` of its command line, and
|
||||
# the directory `komorebic check` reads to see what the daemon runs: it looks in the config
|
||||
# home, not at the daemon's command line
|
||||
configHome =
|
||||
let
|
||||
words = lib.splitString " " config.services.komorebi.execStart;
|
||||
at = lib.lists.findFirstIndex (word: word == "--config") null words;
|
||||
in
|
||||
pkgs.linkFarm "run-kde-config-home" [
|
||||
{
|
||||
name = "komorebi.json";
|
||||
path = builtins.elemAt words (at + 1);
|
||||
}
|
||||
{
|
||||
name = "skhdrc";
|
||||
path = ../../docs/skhdrc.sample;
|
||||
}
|
||||
];
|
||||
|
||||
# What the window shows: the graphics line, which the guest looks up when it has started, the
|
||||
# text above, and what `komorebic check` finds now.
|
||||
cheatSheetCommand = pkgs.writeShellApplication {
|
||||
name = "run-kde-cheat-sheet";
|
||||
runtimeInputs = [
|
||||
pkgs.coreutils
|
||||
pkgs.less
|
||||
config.services.komorebi.package
|
||||
];
|
||||
text = ''
|
||||
text=$(mktemp)
|
||||
{
|
||||
printf 'Graphics: %s\n\n' "$(cat "''${XDG_RUNTIME_DIR:-/tmp}/run-kde-renderer" 2>/dev/null || echo "not known yet")"
|
||||
cat ${cheatSheet}
|
||||
printf '\nkomorebic check\n\n'
|
||||
NO_COLOR=1 KOMOREBI_CONFIG_HOME=${configHome} komorebic check 2>&1 || true
|
||||
} > "$text"
|
||||
exec less -R "$text"
|
||||
'';
|
||||
};
|
||||
|
||||
# The windows of the demo, opened once the shell has its panel: a window that is tiled before
|
||||
# komorebi knows what room the panel takes is tiled under it, and nothing tiles it again.
|
||||
demo = pkgs.writeShellApplication {
|
||||
name = "run-kde-demo";
|
||||
runtimeInputs = [
|
||||
pkgs.coreutils
|
||||
pkgs.jq
|
||||
config.services.komorebi.package
|
||||
];
|
||||
text = ''
|
||||
panel=0
|
||||
for _ in $(seq 1 120); do
|
||||
if komorebic state 2>/dev/null |
|
||||
jq -e '.monitors.elements[0] | .work_area_size != .size' > /dev/null 2>&1; then
|
||||
panel=1
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
[ "$panel" = 1 ] || echo "komorebi does not know the panel's room: the windows may be tiled under it"
|
||||
|
||||
tiled() {
|
||||
local n
|
||||
n=$(komorebic state 2>/dev/null |
|
||||
jq '[.monitors.elements[].workspaces.elements[] | .containers.elements[].windows.elements[]] | length' 2> /dev/null || true)
|
||||
echo "''${n:-0}"
|
||||
}
|
||||
|
||||
# starts a program in a scope of its own, which outlives this script, and waits until komorebi
|
||||
# has a tile for it
|
||||
open() {
|
||||
local before
|
||||
before=$(tiled)
|
||||
systemd-run --user --scope --quiet -- "$@" &
|
||||
for _ in $(seq 1 60); do
|
||||
[ "$(tiled)" -gt "$before" ] && return 0
|
||||
sleep 1
|
||||
done
|
||||
echo "no tile for $1 after a minute"
|
||||
}
|
||||
|
||||
dir=$HOME
|
||||
[ -d /repo ] && dir=/repo
|
||||
|
||||
open konsole --workdir "$dir"
|
||||
open konsole
|
||||
open kate
|
||||
open dolphin "$dir"
|
||||
|
||||
# the cheat sheet says what KWin draws with, which the guest looks up once KWin has started
|
||||
for _ in $(seq 1 60); do
|
||||
[ -s "$XDG_RUNTIME_DIR/run-kde-renderer" ] && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
systemd-run --user --scope --quiet -- foot --app-id komorebi-cheat-sheet \
|
||||
--title "komorebi cheat sheet" --window-size-chars 100x34 -o main.font=monospace:size=10 \
|
||||
run-kde-cheat-sheet &
|
||||
sleep 1
|
||||
'';
|
||||
};
|
||||
|
||||
# What KWin draws with, which is what the cheat sheet and the console say: "GPU" when the host's
|
||||
# GPU renders for it (virgl) and "software" when the guest's CPUs do (llvmpipe).
|
||||
report = pkgs.writeShellApplication {
|
||||
name = "run-kde-report";
|
||||
runtimeInputs = [
|
||||
pkgs.coreutils
|
||||
pkgs.gnused
|
||||
pkgs.kdePackages.qttools
|
||||
];
|
||||
text = ''
|
||||
export XDG_RUNTIME_DIR=/run/user/${toString config.users.users.${user}.uid}
|
||||
export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus
|
||||
renderer=
|
||||
for _ in $(seq 1 300); do
|
||||
renderer=$(qdbus org.kde.KWin /KWin supportInformation 2> /dev/null |
|
||||
sed -n 's/^OpenGL renderer string: //p' | head -n 1 || true)
|
||||
[ -n "$renderer" ] && break
|
||||
sleep 1
|
||||
done
|
||||
[ -n "$renderer" ] || exit 0
|
||||
case $renderer in
|
||||
*llvmpipe* | *softpipe* | *swrast*) kind=software ;;
|
||||
*) kind=GPU ;;
|
||||
esac
|
||||
line="$kind (''${renderer%% *}): $renderer"
|
||||
printf '%s\n' "$line" > "$XDG_RUNTIME_DIR/run-kde-renderer"
|
||||
echo "run-kde: KWin draws with $line"
|
||||
'';
|
||||
};
|
||||
in
|
||||
{
|
||||
imports = [ ./krdp.nix ];
|
||||
|
||||
komorebi.krdp = {
|
||||
enable = true;
|
||||
passwordFile = "${taken}/rdp-password";
|
||||
};
|
||||
|
||||
services.komorebi = {
|
||||
config = {
|
||||
border = true;
|
||||
border_width = 6;
|
||||
border_offset = 5;
|
||||
default_workspace_padding = 15;
|
||||
default_container_padding = 15;
|
||||
animation = {
|
||||
enabled = true;
|
||||
style = "EaseOutExpo";
|
||||
duration = 250;
|
||||
};
|
||||
# this window is the guide to the others, and is not one of them
|
||||
ignore_rules = [
|
||||
{
|
||||
kind = "Class";
|
||||
id = "komorebi-cheat-sheet";
|
||||
matching_strategy = "Equals";
|
||||
}
|
||||
];
|
||||
monitors = [
|
||||
{
|
||||
workspaces = [
|
||||
{
|
||||
name = "I";
|
||||
layout = "BSP";
|
||||
}
|
||||
{
|
||||
name = "II";
|
||||
layout = "VerticalStack";
|
||||
}
|
||||
{
|
||||
name = "III";
|
||||
layout = "HorizontalStack";
|
||||
}
|
||||
{
|
||||
name = "IV";
|
||||
layout = "Columns";
|
||||
}
|
||||
{
|
||||
name = "V";
|
||||
layout = "Rows";
|
||||
}
|
||||
{
|
||||
name = "VI";
|
||||
layout = "Grid";
|
||||
}
|
||||
{
|
||||
name = "VII";
|
||||
layout = "RightMainVerticalStack";
|
||||
}
|
||||
{
|
||||
name = "VIII";
|
||||
layout = "Scrolling";
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# the module's default mode, with the sample bindings of docs/skhdrc.sample
|
||||
keybindings = {
|
||||
format = "skhd";
|
||||
file = ../../docs/skhdrc.sample;
|
||||
};
|
||||
};
|
||||
|
||||
environment.systemPackages = [
|
||||
cheatSheetCommand
|
||||
pkgs.foot
|
||||
pkgs.jq
|
||||
pkgs.kdePackages.dolphin
|
||||
pkgs.kdePackages.kate
|
||||
pkgs.kdePackages.konsole
|
||||
pkgs.kdePackages.qttools
|
||||
pkgs.less
|
||||
];
|
||||
environment.etc."run-kde/cheat-sheet.txt".source = cheatSheet;
|
||||
environment.etc."run-kde/config-home".source = configHome;
|
||||
|
||||
# The host's password and key, taken from the directory it shares. The files may belong to a user
|
||||
# of the host who is not the guest's user, so the guest copies them, as root, and gives them the
|
||||
# owner and the mode that RDP's unit and ssh want. Before the login, so that the unit that reads
|
||||
# the password finds it, and before ssh. A guest that is started with no directory has neither,
|
||||
# and RDP does not start.
|
||||
systemd.services.run-kde-credentials = {
|
||||
description = "Take the RDP password and the ssh key that the host shares";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
before = [
|
||||
"display-manager.service"
|
||||
"sshd.service"
|
||||
];
|
||||
unitConfig = {
|
||||
ConditionPathExists = shared;
|
||||
RequiresMountsFor = shared;
|
||||
};
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
};
|
||||
path = [ pkgs.coreutils ];
|
||||
script = ''
|
||||
install -d -m 0755 ${taken} ${taken}/authorized_keys.d
|
||||
if [ -r ${shared}/rdp-password ]; then
|
||||
install -m 0400 -o ${user} -g ${config.users.users.${user}.group} \
|
||||
${shared}/rdp-password ${taken}/rdp-password
|
||||
fi
|
||||
if [ -r ${shared}/ssh_key.pub ]; then
|
||||
install -m 0644 ${shared}/ssh_key.pub ${taken}/authorized_keys.d/${user}
|
||||
fi
|
||||
'';
|
||||
};
|
||||
services.openssh.authorizedKeysFiles = [ "${taken}/authorized_keys.d/%u" ];
|
||||
|
||||
systemd.services.run-kde-report = {
|
||||
description = "Say what KWin draws with";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "user@${toString config.users.users.${user}.uid}.service" ];
|
||||
serviceConfig = {
|
||||
# simple, so that waiting for KWin does not hold up the machine's start
|
||||
Type = "simple";
|
||||
User = user;
|
||||
ExecStart = lib.getExe report;
|
||||
# the line goes to the console, which is the terminal of whoever started the guest
|
||||
StandardOutput = "journal+console";
|
||||
};
|
||||
};
|
||||
|
||||
# The windows of the demo, once the session is up. The unit does not wait for the panel, the
|
||||
# script does, since only komorebi can say that it knows the panel's room.
|
||||
systemd.user.services.run-kde-demo = {
|
||||
description = "Open the windows of the demo";
|
||||
wantedBy = [ "plasma-workspace.target" ];
|
||||
after = [
|
||||
"plasma-core.target"
|
||||
"komorebi.service"
|
||||
];
|
||||
# the PATH a terminal in the session has, as the module's unit has it
|
||||
enableDefaultPath = false;
|
||||
environment.PATH = lib.concatStringsSep ":" [
|
||||
"/run/wrappers/bin"
|
||||
"/etc/profiles/per-user/%u/bin"
|
||||
"/run/current-system/sw/bin"
|
||||
];
|
||||
serviceConfig = {
|
||||
Type = "simple";
|
||||
ExecStart = lib.getExe demo;
|
||||
# the windows are in scopes of their own, and stay when the script is done
|
||||
KillMode = "process";
|
||||
};
|
||||
};
|
||||
|
||||
# Mesa's video compositor (vl_compositor) never loads an RGB to YUV matrix on a driver that takes
|
||||
# its graphics path, which virgl does: the draw multiplies by the YUV to RGB one of its initial
|
||||
# state, and the NV12 that scale_vaapi makes of the screen, which KRDP encodes, is the wrong
|
||||
# picture (nix/dev/mesa-virgl-rgb-yuv-csc.patch). `builtins.path` makes the patch a store path of
|
||||
# its own, so that Mesa is built once for any way of reading this file. There is no binary cache:
|
||||
# this is a build of Mesa from source.
|
||||
#
|
||||
# The same driver leaks a sync_file, an out-fence of the kernel, for every picture it converts or
|
||||
# uploads: the surface keeps the fence of its last flush in `pipe_fence`, and the next flush of
|
||||
# it stores a new one over it, so the first is never released, and its file descriptor is never
|
||||
# closed. A KRDP session ran out of descriptors (1024) after about 950 frames, and the stream
|
||||
# froze (nix/dev/mesa-virgl-fence-leak.patch).
|
||||
hardware.graphics.package = pkgs.mesa.overrideAttrs (old: {
|
||||
patches = (old.patches or [ ]) ++ [
|
||||
(builtins.path {
|
||||
path = ./mesa-virgl-rgb-yuv-csc.patch;
|
||||
name = "mesa-virgl-rgb-yuv-csc.patch";
|
||||
})
|
||||
(builtins.path {
|
||||
path = ./mesa-virgl-fence-leak.patch;
|
||||
name = "mesa-virgl-fence-leak.patch";
|
||||
})
|
||||
];
|
||||
});
|
||||
|
||||
# What only the runner, which is the machine of the person who starts the guest, can say. The
|
||||
# ports are forwarded and the display device is added on its command line, and the memory is
|
||||
# sized to what that machine has: the shared memory that virtiofs needs is a backend of the
|
||||
# size of the guest's memory, which nixpkgs would fix at the size of `memorySize`.
|
||||
virtualisation.vmVariant.virtualisation = {
|
||||
forwardPorts = lib.mkForce [ ];
|
||||
# `run-kde` says whether KVM is there, and `--tcg` lets it start without
|
||||
qemu.forceAccel = lib.mkForce false;
|
||||
qemu.enableSharedMemory = false;
|
||||
# QEMU never asks virglrenderer for the host's video encoder, so the guest's VA-API lists none
|
||||
# and KRDP encodes H.264 on the guest's CPUs. The patch does (nix/dev/qemu-virgl-video.patch);
|
||||
# VIRGL_RENDERER_USE_VIDEO is only defined with VIRGL_RENDERER_UNSTABLE_APIS. Only the runner
|
||||
# has it: there is no binary cache, so it is a QEMU built from source. The virglrenderer under
|
||||
# it has four patches, in this order, for a host whose encoder is the d3d12 one of WSL 2:
|
||||
# chroma-format the guest's Mesa and virglrenderer number the chroma format of a codec
|
||||
# differently: 4:2:0 was read as 4:2:2, and the encoder refused every codec
|
||||
# video-memory-upload
|
||||
# the d3d12 driver has no dma-bufs, so the picture to encode goes to the
|
||||
# surface through memory
|
||||
# h264-packed-sps Mesa's VA-API takes the level of the stream from a packed SPS, which
|
||||
# virglrenderer never sent: level 0 crashed the d3d12 encoder
|
||||
# ubo0-constants a constant buffer 0 bound as a buffer was never read by the shader, so the
|
||||
# colour matrix of an RGB to YUV conversion was zero
|
||||
qemu.package =
|
||||
(pkgs.qemu_kvm.override {
|
||||
virglrenderer = pkgs.virglrenderer.overrideAttrs (old: {
|
||||
patches = (old.patches or [ ]) ++ [
|
||||
./virglrenderer-chroma-format.patch
|
||||
./virglrenderer-video-memory-upload.patch
|
||||
./virglrenderer-h264-packed-sps.patch
|
||||
./virglrenderer-ubo0-constants.patch
|
||||
];
|
||||
});
|
||||
}).overrideAttrs
|
||||
(old: {
|
||||
patches = (old.patches or [ ]) ++ [ ./qemu-virgl-video.patch ];
|
||||
configureFlags = (old.configureFlags or [ ]) ++ [
|
||||
"--extra-cflags=-DVIRGL_RENDERER_UNSTABLE_APIS"
|
||||
];
|
||||
doCheck = false;
|
||||
});
|
||||
qemu.options = [
|
||||
"-object memory-backend-memfd,id=mem0,size=\${RUN_KDE_MEMORY:-8192}M,share=on"
|
||||
"-machine memory-backend=mem0"
|
||||
];
|
||||
sharedDirectories.run-kde = {
|
||||
source = "\${RUN_KDE_STATE:?set RUN_KDE_STATE to the directory with the password and the key}";
|
||||
target = shared;
|
||||
};
|
||||
# a mount under /run is hidden when the root file system's /run is replaced by a tmpfs, which
|
||||
# happens before the units run
|
||||
fileSystems.${shared}.neededForBoot = lib.mkForce false;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
virglrenderer: read the chroma format of a video codec in the guest's numbering
|
||||
|
||||
The guest's Mesa (26.2.5) sends a video codec's chroma format as the number of its own
|
||||
pipe_video_chroma_format, which since the enum moved to u_format.h is NONE, 400,
|
||||
420, 422, 440, 444 (0 to 5). The enum of virglrenderer, generated by
|
||||
u_format_table.py, is 400, 420, 422, 444, 440, NONE, so 4:2:0, which is 2, is read as
|
||||
4:2:2 and VA-API's encoder, which has no 4:2:2, refuses the codec: "format 0x2 not
|
||||
supported, supported formats: 0x1". The guest's encode then returns no data at all.
|
||||
|
||||
This reads the number as Mesa's. It is for a guest whose Mesa numbers it that way: a
|
||||
guest whose Mesa still numbers it as virglrenderer does would be read wrongly.
|
||||
|
||||
|
||||
diff --git a/src/vrend/vrend_decode.c b/src/vrend/vrend_decode.c
|
||||
index 7774a25..c6eb8f2 100644
|
||||
--- a/src/vrend/vrend_decode.c
|
||||
+++ b/src/vrend/vrend_decode.c
|
||||
@@ -1766,6 +1766,26 @@ static int vrend_decode_get_pipe_resource_layout(struct vrend_context *ctx, cons
|
||||
#ifdef ENABLE_VIDEO
|
||||
/* video codec related functions */
|
||||
|
||||
+/*
|
||||
+ * The chroma format of a codec comes from the guest as the number of its own enum, and the enum
|
||||
+ * of Mesa since its pipe_video_chroma_format moved to u_format.h is numbered NONE, 400, 420, 422,
|
||||
+ * 440, 444 (0 to 5), where this one, which u_format_table.py generates, is 400, 420, 422, 444, 440,
|
||||
+ * NONE. Taken as is, 4:2:0, which is 2, is 4:2:2 here, and the host's encoder, which has no 4:2:2,
|
||||
+ * refuses the codec ("format 0x2 not supported, supported formats: 0x1"), after which the guest
|
||||
+ * encodes nothing.
|
||||
+ */
|
||||
+static uint32_t vrend_decode_chroma_format(uint32_t guest_format)
|
||||
+{
|
||||
+ switch (guest_format) {
|
||||
+ case 1: return PIPE_VIDEO_CHROMA_FORMAT_400;
|
||||
+ case 2: return PIPE_VIDEO_CHROMA_FORMAT_420;
|
||||
+ case 3: return PIPE_VIDEO_CHROMA_FORMAT_422;
|
||||
+ case 4: return PIPE_VIDEO_CHROMA_FORMAT_440;
|
||||
+ case 5: return PIPE_VIDEO_CHROMA_FORMAT_444;
|
||||
+ default: return PIPE_VIDEO_CHROMA_FORMAT_NONE;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
static int vrend_decode_create_video_codec(struct vrend_context *ctx,
|
||||
const uint32_t *buf,
|
||||
uint32_t length)
|
||||
@@ -1778,7 +1798,8 @@ static int vrend_decode_create_video_codec(struct vrend_context *ctx,
|
||||
uint32_t handle = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_HANDLE);
|
||||
uint32_t profile = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_PROFILE);
|
||||
uint32_t entrypoint = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_ENTRYPOINT);
|
||||
- uint32_t chroma_fmt = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_CHROMA_FMT);
|
||||
+ uint32_t chroma_fmt = vrend_decode_chroma_format(
|
||||
+ get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_CHROMA_FMT));
|
||||
uint32_t level = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_LEVEL);
|
||||
uint32_t width = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_WIDTH);
|
||||
uint32_t height = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_HEIGHT);
|
||||
@@ -0,0 +1,192 @@
|
||||
virglrenderer: send the SPS of an H.264 stream to encode to the host's VA-API
|
||||
|
||||
Mesa's VA-API takes the level (and the profile) of an H.264 stream to encode only from
|
||||
the packed sequence header: vlVaHandleVAEncSequenceParameterBufferTypeH264() does not
|
||||
set seq.level_idc, and vlVaHandleVAEncPackedHeaderDataBufferTypeH264() parses it from
|
||||
the application's SPS. The video protocol carries no SPS and no level, and virglrenderer
|
||||
sends no packed header, so on a host whose encoder needs the level, the d3d12 driver of
|
||||
WSL 2, seq.level_idc is 0 and d3d12_video_encoder_convert_level_h264() reaches
|
||||
UNREACHABLE("Unsupported H264 level"), which segfaults QEMU in vaEndPicture().
|
||||
|
||||
On an IDR frame, build a minimal SPS (profile, level, order count type, reference
|
||||
frames, size, cropping) and give it to VA-API as a packed sequence header. The level is
|
||||
the smallest of Table A-1 that holds the frame size and the macroblock rate. The d3d12
|
||||
encoder writes the SPS and PPS it encodes itself: the packed header only has to say what
|
||||
it needs to know.
|
||||
|
||||
|
||||
diff --git a/src/vrend/virgl_video.c b/src/vrend/virgl_video.c
|
||||
index 8b47837..8b71ebe 100644
|
||||
--- a/src/vrend/virgl_video.c
|
||||
+++ b/src/vrend/virgl_video.c
|
||||
@@ -1550,6 +1550,161 @@ err:
|
||||
return err;
|
||||
}
|
||||
|
||||
+/*
|
||||
+ * Mesa's VA-API takes the profile and the level of an H.264 stream to encode only from the
|
||||
+ * packed sequence header (vlVaHandleVAEncPackedHeaderDataBufferTypeH264 parses the SPS of the
|
||||
+ * application), and not from the sequence parameter. Nothing in the video protocol carries the
|
||||
+ * SPS or the level of the guest's, and the level of the codec is not one: with no packed header
|
||||
+ * seq.level_idc is 0, which the d3d12 encoder (WSL 2) does not take, and it crashes in
|
||||
+ * d3d12_video_encoder_convert_level_h264(). The d3d12 encoder writes the SPS and the PPS it
|
||||
+ * encodes itself, and the headers of the application only tell it to, so the SPS here only has to
|
||||
+ * say what the encoder needs: the profile, the level, the order count type, the number of
|
||||
+ * reference frames, the size and the cropping.
|
||||
+ */
|
||||
+struct h264_bits {
|
||||
+ uint8_t *buf;
|
||||
+ unsigned size; /* bytes in buf */
|
||||
+ unsigned pos; /* bits written */
|
||||
+};
|
||||
+
|
||||
+static void h264_put_bits(struct h264_bits *w, uint32_t value, unsigned nbits)
|
||||
+{
|
||||
+ while (nbits--) {
|
||||
+ if (w->pos / 8 < w->size) {
|
||||
+ if (value >> nbits & 1)
|
||||
+ w->buf[w->pos / 8] |= 0x80 >> (w->pos % 8);
|
||||
+ else
|
||||
+ w->buf[w->pos / 8] &= ~(0x80 >> (w->pos % 8));
|
||||
+ }
|
||||
+ w->pos++;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/* Exp-Golomb ue(v) */
|
||||
+static void h264_put_ue(struct h264_bits *w, uint32_t value)
|
||||
+{
|
||||
+ uint32_t v = value + 1;
|
||||
+ unsigned nbits = 0;
|
||||
+
|
||||
+ while (v >> nbits)
|
||||
+ nbits++;
|
||||
+ h264_put_bits(w, 0, nbits - 1);
|
||||
+ h264_put_bits(w, v, nbits);
|
||||
+}
|
||||
+
|
||||
+/* the smallest level that holds the frame size and the macroblock rate (Table A-1) */
|
||||
+static uint32_t h264_level_idc(uint32_t width_mbs, uint32_t height_mbs,
|
||||
+ uint32_t fps)
|
||||
+{
|
||||
+ static const struct { uint8_t idc; uint32_t max_mbps; uint32_t max_fs; } levels[] = {
|
||||
+ { 10, 1485, 99 }, { 11, 3000, 396 }, { 12, 6000, 396 },
|
||||
+ { 13, 11880, 396 }, { 20, 11880, 396 }, { 21, 19800, 792 },
|
||||
+ { 22, 20250, 1620 }, { 30, 40500, 1620 }, { 31, 108000, 3600 },
|
||||
+ { 32, 216000, 5120 }, { 40, 245760, 8192 }, { 41, 245760, 8192 },
|
||||
+ { 42, 522240, 8704 }, { 50, 589824, 22080 }, { 51, 983040, 36864 },
|
||||
+ { 52, 2073600, 36864 }, { 60, 4177920, 139264 },
|
||||
+ };
|
||||
+ uint32_t mbs = width_mbs * height_mbs;
|
||||
+ unsigned i;
|
||||
+
|
||||
+ if (!fps)
|
||||
+ fps = 30;
|
||||
+
|
||||
+ for (i = 0; i < ARRAY_SIZE(levels); i++) {
|
||||
+ if (mbs <= levels[i].max_fs && (uint64_t)mbs * fps <= levels[i].max_mbps)
|
||||
+ return levels[i].idc;
|
||||
+ }
|
||||
+
|
||||
+ return levels[ARRAY_SIZE(levels) - 1].idc;
|
||||
+}
|
||||
+
|
||||
+static void h264_encode_render_packed_sps(
|
||||
+ struct virgl_video_codec *codec,
|
||||
+ const struct virgl_h264_enc_picture_desc *desc)
|
||||
+{
|
||||
+ uint8_t data[64] = { 0 };
|
||||
+ struct h264_bits w = { data, sizeof(data), 0 };
|
||||
+ uint32_t profile_idc, fps, level_idc, width_mbs, height_mbs, poc_type;
|
||||
+ const struct virgl_h264_enc_rate_control *rc = &desc->rate_ctrl[0];
|
||||
+ VAEncPackedHeaderParameterBuffer hdr;
|
||||
+ VABufferID bufs[2];
|
||||
+ VAStatus va_stat;
|
||||
+ unsigned nbytes;
|
||||
+
|
||||
+ switch (codec->profile) {
|
||||
+ case PIPE_VIDEO_PROFILE_MPEG4_AVC_BASELINE:
|
||||
+ profile_idc = 66;
|
||||
+ break;
|
||||
+ case PIPE_VIDEO_PROFILE_MPEG4_AVC_MAIN:
|
||||
+ profile_idc = 77;
|
||||
+ break;
|
||||
+ default:
|
||||
+ profile_idc = 100;
|
||||
+ break;
|
||||
+ }
|
||||
+
|
||||
+ width_mbs = (codec->width + 15) / 16;
|
||||
+ height_mbs = (codec->height + 15) / 16;
|
||||
+ fps = rc->frame_rate_den ? rc->frame_rate_num / rc->frame_rate_den : 0;
|
||||
+ level_idc = h264_level_idc(width_mbs, height_mbs, fps);
|
||||
+ /* the order count types that the SPS below can say, 0 and 2 */
|
||||
+ poc_type = desc->seq.pic_order_cnt_type == 2 ? 2 : 0;
|
||||
+
|
||||
+ h264_put_bits(&w, 0x00000001, 32); /* start code */
|
||||
+ h264_put_bits(&w, 0x67, 8); /* nal_ref_idc 3, SPS */
|
||||
+ h264_put_bits(&w, profile_idc, 8);
|
||||
+ h264_put_bits(&w, desc->seq.enc_constraint_set_flags & 0x3f, 6);
|
||||
+ h264_put_bits(&w, 0, 2); /* reserved_zero_2bits */
|
||||
+ h264_put_bits(&w, level_idc, 8);
|
||||
+ h264_put_ue(&w, 0); /* seq_parameter_set_id */
|
||||
+ if (profile_idc == 100) {
|
||||
+ h264_put_ue(&w, 1); /* chroma_format_idc: 4:2:0 */
|
||||
+ h264_put_ue(&w, 0); /* bit_depth_luma_minus8 */
|
||||
+ h264_put_ue(&w, 0); /* bit_depth_chroma_minus8 */
|
||||
+ h264_put_bits(&w, 0, 1); /* qpprime_y_zero_transform_bypass */
|
||||
+ h264_put_bits(&w, 0, 1); /* seq_scaling_matrix_present */
|
||||
+ }
|
||||
+ h264_put_ue(&w, 0); /* log2_max_frame_num_minus4 */
|
||||
+ h264_put_ue(&w, poc_type);
|
||||
+ if (poc_type == 0)
|
||||
+ h264_put_ue(&w, 0); /* log2_max_pic_order_cnt_lsb_minus4 */
|
||||
+ h264_put_ue(&w, codec->max_references);
|
||||
+ h264_put_bits(&w, 0, 1); /* gaps_in_frame_num_value_allowed */
|
||||
+ h264_put_ue(&w, width_mbs - 1);
|
||||
+ h264_put_ue(&w, height_mbs - 1);
|
||||
+ h264_put_bits(&w, 1, 1); /* frame_mbs_only_flag */
|
||||
+ h264_put_bits(&w, 1, 1); /* direct_8x8_inference_flag */
|
||||
+ h264_put_bits(&w, desc->seq.enc_frame_cropping_flag ? 1 : 0, 1);
|
||||
+ if (desc->seq.enc_frame_cropping_flag) {
|
||||
+ h264_put_ue(&w, desc->seq.enc_frame_crop_left_offset);
|
||||
+ h264_put_ue(&w, desc->seq.enc_frame_crop_right_offset);
|
||||
+ h264_put_ue(&w, desc->seq.enc_frame_crop_top_offset);
|
||||
+ h264_put_ue(&w, desc->seq.enc_frame_crop_bottom_offset);
|
||||
+ }
|
||||
+ h264_put_bits(&w, 0, 1); /* vui_parameters_present_flag */
|
||||
+ h264_put_bits(&w, 1, 1); /* rbsp_stop_one_bit */
|
||||
+ nbytes = (w.pos + 7) / 8;
|
||||
+ if (nbytes > sizeof(data))
|
||||
+ return;
|
||||
+
|
||||
+ memset(&hdr, 0, sizeof(hdr));
|
||||
+ hdr.type = VAEncPackedHeaderSequence;
|
||||
+ hdr.bit_length = nbytes * 8;
|
||||
+ hdr.has_emulation_bytes = 0;
|
||||
+
|
||||
+ vaCreateBuffer(va_dpy, codec->va_ctx, VAEncPackedHeaderParameterBufferType,
|
||||
+ sizeof(hdr), 1, &hdr, &bufs[0]);
|
||||
+ vaCreateBuffer(va_dpy, codec->va_ctx, VAEncPackedHeaderDataBufferType,
|
||||
+ nbytes, 1, data, &bufs[1]);
|
||||
+
|
||||
+ va_stat = vaRenderPicture(va_dpy, codec->va_ctx, bufs, 2);
|
||||
+ if (VA_STATUS_SUCCESS != va_stat)
|
||||
+ virgl_error("render h264 packed sps failed, err = 0x%x\n", va_stat);
|
||||
+
|
||||
+ vaDestroyBuffer(va_dpy, bufs[0]);
|
||||
+ vaDestroyBuffer(va_dpy, bufs[1]);
|
||||
+}
|
||||
+
|
||||
static int h264_encode_render_sequence(
|
||||
struct virgl_video_codec *codec,
|
||||
struct virgl_video_buffer *source,
|
||||
@@ -1591,6 +1746,8 @@ static int h264_encode_render_sequence(
|
||||
goto error;
|
||||
}
|
||||
|
||||
+ h264_encode_render_packed_sps(codec, desc);
|
||||
+
|
||||
va_stat = vaRenderPicture(va_dpy, codec->va_ctx, &rc_param_buf, 1);
|
||||
if (VA_STATUS_SUCCESS != va_stat) {
|
||||
virgl_error("render h264 rate control param failed, err = 0x%x\n", va_stat);
|
||||
@@ -0,0 +1,105 @@
|
||||
vrend: read constant buffer 0 bound as a buffer into the default uniforms
|
||||
|
||||
A guest binds the constant buffer 0 of a shader either as inline constants
|
||||
(SET_CONSTANT_BUFFER) or as a buffer resource (SET_UNIFORM_BUFFER). A shader reads its
|
||||
constant buffer 0 from the default uniform block (fsconst0[] and the like), which vrend
|
||||
fills only from the inline constants, and vrend binds UBOs only for the buffers from 1:
|
||||
a buffer bound at index 0 was never seen by the shader, and its constants stayed zero.
|
||||
|
||||
Mesa's vl_compositor binds the colour matrix of an RGB to YUV conversion that way, so
|
||||
with the virgl driver the conversion (scale_vaapi from RGB to NV12 in FFmpeg, which
|
||||
KRDP uses) multiplied by a zero matrix and wrote zeros: a solid green picture.
|
||||
|
||||
Remember when the constant buffer 0 is set whether it is a buffer, and at the draw read
|
||||
it (glGetBufferSubData) into the uniforms with glUniform4uiv. It is read at every draw,
|
||||
since the guest can write to the buffer without binding it again. The conversion then
|
||||
writes what Mesa's matrix gives: the luma of a ramp goes from 0 0 0 to 0 124 255. What
|
||||
is left is Mesa's: the graphics path of vl_compositor_convert_rgb_to_yuv() never loads
|
||||
an RGB to YUV matrix, and the one that is sent is the YUV to RGB matrix of the
|
||||
compositor's initial state.
|
||||
|
||||
diff --git a/src/vrend/vrend_renderer.c b/src/vrend/vrend_renderer.c
|
||||
index 4bf88e0..a5166c4 100644
|
||||
--- a/src/vrend/vrend_renderer.c
|
||||
+++ b/src/vrend/vrend_renderer.c
|
||||
@@ -735,6 +735,8 @@ struct vrend_sub_context {
|
||||
|
||||
struct vrend_constants consts[PIPE_SHADER_TYPES];
|
||||
bool const_dirty[PIPE_SHADER_TYPES];
|
||||
+ /* constant buffer 0 was last bound as a buffer resource, not as inline constants */
|
||||
+ bool const0_from_buffer[PIPE_SHADER_TYPES];
|
||||
|
||||
struct pipe_constant_buffer cbs[PIPE_SHADER_TYPES][PIPE_MAX_CONSTANT_BUFFERS];
|
||||
uint32_t const_bufs_used_mask[PIPE_SHADER_TYPES];
|
||||
@@ -3486,6 +3488,7 @@ void vrend_set_constants(struct vrend_context *ctx,
|
||||
|
||||
consts = &ctx->sub->consts[shader];
|
||||
ctx->sub->const_dirty[shader] = true;
|
||||
+ ctx->sub->const0_from_buffer[shader] = false;
|
||||
|
||||
/* avoid reallocations by only growing the buffer */
|
||||
if (consts->num_allocated_consts < num_constant) {
|
||||
@@ -3517,6 +3520,9 @@ void vrend_set_uniform_buffer(struct vrend_context *ctx,
|
||||
struct pipe_constant_buffer *cbs = &ctx->sub->cbs[shader][index];
|
||||
const uint32_t mask = 1u << index;
|
||||
|
||||
+ if (index == 0)
|
||||
+ ctx->sub->const0_from_buffer[shader] = res_handle != 0;
|
||||
+
|
||||
if (res_handle) {
|
||||
res = vrend_renderer_ctx_res_lookup(ctx, res_handle);
|
||||
|
||||
@@ -5352,9 +5358,53 @@ static GLuint vrend_draw_bind_ubo_shader(struct vrend_sub_context *sub_ctx,
|
||||
return next_ubo_id;
|
||||
}
|
||||
|
||||
+/*
|
||||
+ * A guest can bind constant buffer 0 as a buffer resource (SET_UNIFORM_BUFFER) instead of as
|
||||
+ * inline constants (SET_CONSTANT_BUFFER): Mesa's vl_compositor does for the colour matrix of an
|
||||
+ * RGB to YUV conversion. A shader reads its constant buffer 0 as the default uniform block
|
||||
+ * (fsconst0[]), which only the inline constants fill, and the UBOs are for the buffers from 1:
|
||||
+ * the matrix stayed zero, and the conversion wrote zeros. Read the buffer into the uniforms. It
|
||||
+ * is read at every draw, as the guest can write to the buffer without binding it again. Returns
|
||||
+ * whether the constants came from the buffer.
|
||||
+ */
|
||||
+static bool vrend_draw_bind_const0_buffer(struct vrend_sub_context *sub_ctx,
|
||||
+ int shader_type)
|
||||
+{
|
||||
+ const struct vrend_shader_selector *sel = sub_ctx->shaders[shader_type];
|
||||
+ const struct pipe_constant_buffer *cb = &sub_ctx->cbs[shader_type][0];
|
||||
+ const struct vrend_resource *res = (const struct vrend_resource *)cb->buffer;
|
||||
+ unsigned num_consts, bytes;
|
||||
+ uint32_t *data;
|
||||
+
|
||||
+ if (!sub_ctx->const0_from_buffer[shader_type] || !sel || !sel->sinfo.num_consts ||
|
||||
+ sub_ctx->prog->const_location[shader_type] == -1 ||
|
||||
+ !(sub_ctx->const_bufs_used_mask[shader_type] & 1) ||
|
||||
+ !res || !has_bit(res->storage_bits, VREND_STORAGE_GL_BUFFER))
|
||||
+ return false;
|
||||
+
|
||||
+ num_consts = sel->sinfo.num_consts;
|
||||
+ bytes = num_consts * 4 * sizeof(uint32_t);
|
||||
+ data = calloc(1, bytes);
|
||||
+ if (!data)
|
||||
+ return true;
|
||||
+
|
||||
+ glBindBuffer(GL_COPY_READ_BUFFER, res->gl_id);
|
||||
+ glGetBufferSubData(GL_COPY_READ_BUFFER, cb->buffer_offset,
|
||||
+ MIN2(bytes, cb->buffer_size), data);
|
||||
+ glBindBuffer(GL_COPY_READ_BUFFER, 0);
|
||||
+
|
||||
+ glUniform4uiv(sub_ctx->prog->const_location[shader_type], num_consts, data);
|
||||
+ free(data);
|
||||
+
|
||||
+ return true;
|
||||
+}
|
||||
+
|
||||
static void vrend_draw_bind_const_shader(struct vrend_sub_context *sub_ctx,
|
||||
int shader_type, bool new_program)
|
||||
{
|
||||
+ if (vrend_draw_bind_const0_buffer(sub_ctx, shader_type))
|
||||
+ return;
|
||||
+
|
||||
if (sub_ctx->consts[shader_type].consts &&
|
||||
sub_ctx->shaders[shader_type] &&
|
||||
(sub_ctx->prog->const_location[shader_type] != -1) &&
|
||||
@@ -0,0 +1,237 @@
|
||||
virglrenderer: upload the picture to encode through memory
|
||||
|
||||
virglrenderer shares a video buffer with the host's VA-API driver as a dma-buf: it
|
||||
exports the VA surface (vaExportSurfaceHandle) and imports it into EGL to copy the
|
||||
guest's picture in. The d3d12 driver on WSL 2 has no dma-bufs, so the export fails
|
||||
("export surface failed, err = 0x6"), nothing is uploaded and the encoder returns an
|
||||
empty bitstream.
|
||||
|
||||
When the first export fails, read the planes of the guest's picture back from their
|
||||
textures (glReadPixels, into the planes of a VAImage) and write them to the surface
|
||||
through vaDeriveImage(), as FFmpeg's hwupload does; where the driver cannot derive an
|
||||
image, a vaCreateImage() image is copied with vaPutImage(). On the d3d12 driver the
|
||||
vaPutImage() copy came out with an all-zero luma plane (the chroma was right), where
|
||||
the derived image encodes exactly: a luma ramp through the encoder comes back as
|
||||
43 125 207 for 43 125 207. Where the export works nothing changes: it is tried first,
|
||||
and given up on only after it has failed.
|
||||
|
||||
diff --git a/src/vrend/virgl_video.c b/src/vrend/virgl_video.c
|
||||
index dc1e8cd..8b47837 100644
|
||||
--- a/src/vrend/virgl_video.c
|
||||
+++ b/src/vrend/virgl_video.c
|
||||
@@ -438,12 +438,100 @@ static void destroy_video_dma_buf(struct virgl_video_dma_buf *dmabuf)
|
||||
}
|
||||
}
|
||||
|
||||
+/*
|
||||
+ * Upload the picture to encode through memory, for a host that cannot export
|
||||
+ * a video buffer as a dma-buf: the d3d12 driver on WSL 2 has no dma-bufs, and
|
||||
+ * vaExportSurfaceHandle() fails on it. The callback reads the planes of the
|
||||
+ * guest's picture into a VAImage, which vaPutImage() copies to the surface,
|
||||
+ * as FFmpeg's hwupload does.
|
||||
+ */
|
||||
+static void encode_upload_picture_cpu(struct virgl_video_codec *codec,
|
||||
+ struct virgl_video_buffer *buffer)
|
||||
+{
|
||||
+ VAStatus va_stat;
|
||||
+ VAImageFormat fmt;
|
||||
+ VAImage image;
|
||||
+ void *data = NULL;
|
||||
+ uint8_t *dst[3] = { NULL, NULL, NULL };
|
||||
+ unsigned pitches[3] = { 0, 0, 0 };
|
||||
+ unsigned i;
|
||||
+ int ret;
|
||||
+ bool derived = false;
|
||||
+
|
||||
+ if (!callbacks || !callbacks->encode_read_picture)
|
||||
+ return;
|
||||
+
|
||||
+ memset(&fmt, 0, sizeof(fmt));
|
||||
+ fmt.byte_order = VA_LSB_FIRST;
|
||||
+ fmt.bits_per_pixel = 12;
|
||||
+ switch (buffer->format) {
|
||||
+ case PIPE_FORMAT_NV12:
|
||||
+ fmt.fourcc = VA_FOURCC_NV12;
|
||||
+ break;
|
||||
+ case PIPE_FORMAT_NV21:
|
||||
+ fmt.fourcc = VA_FOURCC_NV21;
|
||||
+ break;
|
||||
+ default:
|
||||
+ virgl_error("upload through memory: pipe format %d not supported\n",
|
||||
+ buffer->format);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ /*
|
||||
+ * Write to the surface itself when the driver can show it as an image, as FFmpeg's
|
||||
+ * hwupload does. On the d3d12 driver the picture of an image made with vaCreateImage() and
|
||||
+ * copied by vaPutImage() came out with an all-zero luma plane (the chroma was right),
|
||||
+ * where the same planes written through vaDeriveImage() encode exactly.
|
||||
+ */
|
||||
+ va_stat = vaDeriveImage(va_dpy, buffer->va_sfc, &image);
|
||||
+ if (VA_STATUS_SUCCESS == va_stat) {
|
||||
+ derived = true;
|
||||
+ } else {
|
||||
+ va_stat = vaCreateImage(va_dpy, &fmt, buffer->width, buffer->height, &image);
|
||||
+ if (VA_STATUS_SUCCESS != va_stat) {
|
||||
+ virgl_error("create image failed, err = 0x%x\n", va_stat);
|
||||
+ return;
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ va_stat = vaMapBuffer(va_dpy, image.buf, &data);
|
||||
+ if (VA_STATUS_SUCCESS != va_stat || !data) {
|
||||
+ virgl_error("map image failed, err = 0x%x\n", va_stat);
|
||||
+ goto destroy_image;
|
||||
+ }
|
||||
+
|
||||
+ for (i = 0; i < image.num_planes && i < ARRAY_SIZE(dst); i++) {
|
||||
+ dst[i] = (uint8_t *)data + image.offsets[i];
|
||||
+ pitches[i] = image.pitches[i];
|
||||
+ }
|
||||
+
|
||||
+ ret = callbacks->encode_read_picture(codec, buffer, image.num_planes,
|
||||
+ dst, pitches);
|
||||
+ vaUnmapBuffer(va_dpy, image.buf);
|
||||
+ if (ret) {
|
||||
+ virgl_error("read picture failed, err = %d\n", ret);
|
||||
+ goto destroy_image;
|
||||
+ }
|
||||
+
|
||||
+ if (!derived) {
|
||||
+ va_stat = vaPutImage(va_dpy, buffer->va_sfc, image.image_id,
|
||||
+ 0, 0, buffer->width, buffer->height,
|
||||
+ 0, 0, buffer->width, buffer->height);
|
||||
+ if (VA_STATUS_SUCCESS != va_stat)
|
||||
+ virgl_error("put image failed, err = 0x%x\n", va_stat);
|
||||
+ }
|
||||
+
|
||||
+destroy_image:
|
||||
+ vaDestroyImage(va_dpy, image.image_id);
|
||||
+}
|
||||
+
|
||||
static void encode_upload_picture(struct virgl_video_codec *codec,
|
||||
struct virgl_video_buffer *buffer)
|
||||
{
|
||||
VAStatus va_stat;
|
||||
+ static bool dmabuf_unsupported;
|
||||
|
||||
- if (!callbacks || !callbacks->encode_upload_picture)
|
||||
+ if (!callbacks)
|
||||
return;
|
||||
|
||||
va_stat = vaSyncSurface(va_dpy, buffer->va_sfc);
|
||||
@@ -452,11 +540,20 @@ static void encode_upload_picture(struct virgl_video_codec *codec,
|
||||
return;
|
||||
}
|
||||
|
||||
- if (!buffer->dmabuf)
|
||||
+ /* once a surface cannot be exported none can: go through memory */
|
||||
+ if (!buffer->dmabuf && !dmabuf_unsupported && callbacks->encode_upload_picture) {
|
||||
buffer->dmabuf = export_video_dma_buf(buffer, VIRGL_VIDEO_DMABUF_WRITE_ONLY);
|
||||
+ if (!buffer->dmabuf) {
|
||||
+ dmabuf_unsupported = true;
|
||||
+ virgl_warn("cannot export a video buffer as a dma-buf, "
|
||||
+ "uploading the pictures to encode through memory\n");
|
||||
+ }
|
||||
+ }
|
||||
|
||||
if (buffer->dmabuf)
|
||||
callbacks->encode_upload_picture(codec, buffer->dmabuf);
|
||||
+ else
|
||||
+ encode_upload_picture_cpu(codec, buffer);
|
||||
}
|
||||
|
||||
static void encode_completed(struct virgl_video_codec *codec,
|
||||
diff --git a/src/vrend/virgl_video.h b/src/vrend/virgl_video.h
|
||||
index e954559..c39d33d 100644
|
||||
--- a/src/vrend/virgl_video.h
|
||||
+++ b/src/vrend/virgl_video.h
|
||||
@@ -115,6 +115,16 @@ struct virgl_video_callbacks {
|
||||
void (*encode_upload_picture)(struct virgl_video_codec *codec,
|
||||
const struct virgl_video_dma_buf *dmabuf);
|
||||
|
||||
+ /* Read the picture data to be encoded into memory, plane by plane, for
|
||||
+ * a host whose video buffers cannot be exported as dma-bufs (the d3d12
|
||||
+ * driver of WSL 2): plane i is written to dst[i], pitches[i] bytes a row.
|
||||
+ * Returns 0 when the planes are filled. */
|
||||
+ int (*encode_read_picture)(struct virgl_video_codec *codec,
|
||||
+ struct virgl_video_buffer *buffer,
|
||||
+ unsigned num_planes,
|
||||
+ uint8_t * const *dst,
|
||||
+ const unsigned *pitches);
|
||||
+
|
||||
/* Callback when encoding is complete, used to download the encoded data
|
||||
* and reference picture */
|
||||
void (*encode_completed)(struct virgl_video_codec *codec,
|
||||
diff --git a/src/vrend/vrend_video.c b/src/vrend/vrend_video.c
|
||||
index 57341d8..dc30c55 100644
|
||||
--- a/src/vrend/vrend_video.c
|
||||
+++ b/src/vrend/vrend_video.c
|
||||
@@ -293,6 +293,58 @@ static void vrend_video_enocde_upload_picture(
|
||||
sync_video_buffer_to_dmabuf(buf, dmabuf);
|
||||
}
|
||||
|
||||
+/*
|
||||
+ * The picture to encode is the planes of a video buffer the guest rendered to, which are
|
||||
+ * textures here (R8 for the luma, RG8 for the chroma of NV12). Read them into the planes of a
|
||||
+ * VAImage, for a host that cannot share its video buffer as a dma-buf.
|
||||
+ */
|
||||
+static int vrend_video_encode_read_picture(
|
||||
+ struct virgl_video_codec *codec,
|
||||
+ struct virgl_video_buffer *vbuf,
|
||||
+ unsigned num_planes,
|
||||
+ uint8_t * const *dst,
|
||||
+ const unsigned *pitches)
|
||||
+{
|
||||
+ struct vrend_video_buffer *buf = vrend_video_buffer(vbuf);
|
||||
+ int ret = 0;
|
||||
+
|
||||
+ (void)codec;
|
||||
+
|
||||
+ if (!buf)
|
||||
+ return -1;
|
||||
+
|
||||
+ glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||
+ glPixelStorei(GL_PACK_ALIGNMENT, 1);
|
||||
+
|
||||
+ for (unsigned i = 0; i < num_planes && i < buf->num_planes; i++) {
|
||||
+ struct vrend_video_plane *plane = &buf->planes[i];
|
||||
+ struct vrend_resource *res;
|
||||
+ /* NV12 and NV21 have a plane of one byte a pixel, and one of two */
|
||||
+ const unsigned bytes_per_pixel = i ? 2 : 1;
|
||||
+
|
||||
+ res = vrend_renderer_ctx_res_lookup(buf->ctx->ctx, plane->res_handle);
|
||||
+ if (!res) {
|
||||
+ virgl_error("%s: res %d not found\n", __func__, plane->res_handle);
|
||||
+ ret = -1;
|
||||
+ continue;
|
||||
+ }
|
||||
+
|
||||
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, plane->framebuffer);
|
||||
+ glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
|
||||
+ GL_TEXTURE_2D, res->gl_id, 0);
|
||||
+
|
||||
+ glPixelStorei(GL_PACK_ROW_LENGTH, pitches[i] / bytes_per_pixel);
|
||||
+ glReadPixels(0, 0, res->base.width0, res->base.height0,
|
||||
+ i ? GL_RG : GL_RED, GL_UNSIGNED_BYTE, dst[i]);
|
||||
+ }
|
||||
+
|
||||
+ glPixelStorei(GL_PACK_ROW_LENGTH, 0);
|
||||
+ glPixelStorei(GL_PACK_ALIGNMENT, 4);
|
||||
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
+
|
||||
+ return ret;
|
||||
+}
|
||||
+
|
||||
static void vrend_video_encode_completed(
|
||||
struct virgl_video_codec *codec,
|
||||
const struct virgl_video_dma_buf *src_buf,
|
||||
@@ -349,6 +401,7 @@ static void vrend_video_encode_completed(
|
||||
static struct virgl_video_callbacks video_callbacks = {
|
||||
.decode_completed = vrend_video_decode_completed,
|
||||
.encode_upload_picture = vrend_video_enocde_upload_picture,
|
||||
+ .encode_read_picture = vrend_video_encode_read_picture,
|
||||
.encode_completed = vrend_video_encode_completed,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# The init of the guest that scripts/wsl2-probe.sh boots (nix/dev/wsl2-probe.nix puts the
|
||||
# interpreter, PATH and `probe_loop` in front of this text). The kernel command line chooses what
|
||||
# it does:
|
||||
#
|
||||
# probe.mode=bench runs the CPU loop, prints the CPU, and powers off (the default)
|
||||
# probe.mode=hold prints a line every second for probe.hold seconds, then powers off: it
|
||||
# keeps a window open long enough to be seen
|
||||
# probe.mode=virtiofs loads the kernel's virtio and virtiofs modules, mounts the share that
|
||||
# the host serves with virtiofsd (tag probe.fstag, default probe), reads
|
||||
# probe.token's file and writes one, then powers off
|
||||
# probe.loops=N the number of iterations of the loop (default 600000)
|
||||
# probe.hold=N the number of seconds of the hold mode (default 8)
|
||||
# probe.serial=DEV a serial device the lines are copied to, for a run whose console is the
|
||||
# screen (default none: the console is the serial port)
|
||||
#
|
||||
# Every line that matters starts with `PROBE:` so that the host can find it in the console.
|
||||
|
||||
mount -t proc proc /proc
|
||||
mount -t sysfs sysfs /sys
|
||||
mount -t devtmpfs devtmpfs /dev
|
||||
exec </dev/console >/dev/console 2>&1
|
||||
|
||||
# param NAME DEFAULT: the value NAME has on the kernel command line
|
||||
param() {
|
||||
value=$(tr ' ' '\n' </proc/cmdline | sed -n "s/^$1=//p" | tail -n 1)
|
||||
echo "${value:-$2}"
|
||||
}
|
||||
|
||||
mode=$(param probe.mode bench)
|
||||
hold=$(param probe.hold 8)
|
||||
loops=$(param probe.loops 600000)
|
||||
serial=$(param probe.serial none)
|
||||
fstag=$(param probe.fstag probe)
|
||||
token=$(param probe.token none)
|
||||
|
||||
# to the console, and to the serial port that the host reads when the console is the screen
|
||||
say() {
|
||||
echo "PROBE:$*"
|
||||
[ -c "/dev/$serial" ] && echo "PROBE:$*" >"/dev/$serial"
|
||||
}
|
||||
|
||||
say "START kernel=$(uname -r) machine=$(uname -m) mode=$mode"
|
||||
say "CPU_MODEL=$(grep -m1 -E '^(model name|Processor|CPU part)' /proc/cpuinfo | cut -d: -f2- | sed 's/^ *//')"
|
||||
say "CPU_FLAGS=$(grep -m1 -E '^(flags|Features)' /proc/cpuinfo | cut -d: -f2- | sed 's/^ *//')"
|
||||
say "CPU_COUNT=$(grep -c '^processor' /proc/cpuinfo)"
|
||||
say "MEM_KB=$(grep -m1 '^MemTotal' /proc/meminfo | tr -s ' ' | cut -d' ' -f2)"
|
||||
|
||||
if [ "$mode" = bench ]; then
|
||||
say "LOOP_ITERATIONS=$loops"
|
||||
say "LOOP_MS=$(probe_loop "$loops")"
|
||||
fi
|
||||
|
||||
if [ "$mode" = virtiofs ]; then
|
||||
# virtio's PCI transport, FUSE and virtiofs are modules in this kernel, as they are in the real
|
||||
# guest's, whose initrd loads them before it mounts /nix/store
|
||||
for module in virtio_pci virtiofs; do
|
||||
if text=$(modprobe "$module" 2>&1); then
|
||||
say "MODULE_$module=loaded"
|
||||
elif [ "$module" = virtio_pci ] && [ -d /sys/bus/pci/drivers/virtio-pci ]; then
|
||||
# a kernel that has the transport built in (the aarch64 one) has no module of it
|
||||
say "MODULE_$module=built in"
|
||||
else
|
||||
say "MODULE_$module=failed: $text"
|
||||
fi
|
||||
done
|
||||
say "FILESYSTEMS=$(grep -E 'virtiofs|fuse' /proc/filesystems | tr -s '\t\n' ' ')"
|
||||
mkdir -p /store /share
|
||||
|
||||
# the host's /nix/store, read-only: the guest's busybox is read through it and checksummed
|
||||
if text=$(mount -t virtiofs -o ro probestore /store 2>&1); then
|
||||
say "STORE_MOUNT=ok"
|
||||
say "STORE_SHA256=$(sha256sum "/store/$(param probe.storefile none)" 2>&1 | cut -d' ' -f1)"
|
||||
if echo x >/store/probe-write 2>/dev/null; then
|
||||
say "STORE_WRITE=allowed"
|
||||
else
|
||||
say "STORE_WRITE=refused"
|
||||
fi
|
||||
else
|
||||
say "STORE_MOUNT=failed: $text"
|
||||
say "DEVICES=$(cd /sys/bus/virtio/devices 2>&1 && echo *)"
|
||||
fi
|
||||
|
||||
# a writable directory: the guest reads the file the host made and writes one of its own
|
||||
if text=$(mount -t virtiofs "$fstag" /share 2>&1); then
|
||||
say "SHARE_MOUNT=ok"
|
||||
say "SHARE_LISTING=$(cd /share && echo *)"
|
||||
say "SHARE_READ=$(cat /share/token 2>&1)"
|
||||
say "SHARE_READ_OWNER=$(stat -c '%u:%g %a' /share/token 2>&1)"
|
||||
if text=$({ echo "$token" >/share/from-guest; } 2>&1); then
|
||||
say "SHARE_WRITE=ok"
|
||||
else
|
||||
say "SHARE_WRITE=failed: $text"
|
||||
fi
|
||||
say "SHARE_WRITE_OWNER=$(stat -c '%u:%g %a' /share/from-guest 2>&1)"
|
||||
else
|
||||
say "SHARE_MOUNT=failed: $text"
|
||||
fi
|
||||
sync
|
||||
fi
|
||||
|
||||
if [ "$mode" = hold ]; then
|
||||
n=0
|
||||
while [ "$n" -lt "$hold" ]; do
|
||||
say "ALIVE $n of $hold seconds: this window is the guest of wsl2-probe, it closes by itself"
|
||||
sleep 1
|
||||
n=$((n + 1))
|
||||
done
|
||||
fi
|
||||
|
||||
say "DONE"
|
||||
sync
|
||||
poweroff -f
|
||||
# a kernel that does not power off on request is stopped by the host's timeout
|
||||
sleep 600
|
||||
@@ -0,0 +1,22 @@
|
||||
# A CPU loop that scripts/wsl2-probe.sh times in three places: on the host, in a guest under
|
||||
# KVM and in a guest under TCG. busybox's ash runs it, so the same interpreter runs the same
|
||||
# instructions everywhere and only the way the CPU is provided differs.
|
||||
#
|
||||
# `probe_loop N` counts to N and prints the milliseconds it took, read from /proc/uptime, whose
|
||||
# resolution is 10 ms: a loop shorter than about a second says little.
|
||||
|
||||
# the uptime in centiseconds; the 1 in front of the fraction keeps ash from reading 08 as octal
|
||||
probe_centis() {
|
||||
read -r up _ </proc/uptime
|
||||
echo $((${up%.*} * 100 + 1${up#*.} - 100))
|
||||
}
|
||||
|
||||
probe_loop() {
|
||||
start=$(probe_centis)
|
||||
i=0
|
||||
while [ "$i" -lt "$1" ]; do
|
||||
i=$((i + 1))
|
||||
done
|
||||
end=$(probe_centis)
|
||||
echo $(((end - start) * 10))
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
pkgs,
|
||||
# the revision the probe says it came from; the checks pass a constant, so that they are the
|
||||
# same derivations for every commit
|
||||
rev,
|
||||
}:
|
||||
|
||||
# scripts/wsl2-probe.sh, with the tools it uses from nixpkgs, and the tiny guest it boots.
|
||||
#
|
||||
# The guest is a kernel from the binary cache and an initrd made here of a static busybox, the
|
||||
# kernel modules that virtiofs needs, and the init in wsl2-probe-init.sh: nothing in it is built
|
||||
# from source, so the first run is a download. docs/dev/wsl2-probe.md says what the probe does.
|
||||
let
|
||||
inherit (pkgs) lib;
|
||||
|
||||
busybox = pkgs.pkgsStatic.busybox;
|
||||
|
||||
# the kernel is the one the real guest boots (the default of NixOS), so that what the probe's
|
||||
# guest can do with virtiofs is what the real guest's kernel can do
|
||||
kernel = pkgs.linuxPackages.kernel;
|
||||
|
||||
# the file of the kernel package that QEMU boots
|
||||
kernelImage = if pkgs.stdenv.hostPlatform.isAarch64 then "Image" else "bzImage";
|
||||
|
||||
# virtio's PCI transport, FUSE and virtiofs are modules of that kernel, not built in; this is
|
||||
# the closure of them in the shape the NixOS initrd uses (modules.dep included, for modprobe)
|
||||
modules = pkgs.makeModulesClosure {
|
||||
kernel = pkgs.aggregateModules [ (lib.getOutput "modules" kernel) ];
|
||||
firmware = pkgs.runCommand "wsl2-probe-no-firmware" { } "mkdir -p $out";
|
||||
rootModules = [
|
||||
"virtio_pci"
|
||||
"virtiofs"
|
||||
];
|
||||
};
|
||||
|
||||
# the loop that the host and the guest both time, which busybox's ash runs in both
|
||||
loop = pkgs.writeTextFile {
|
||||
name = "wsl2-probe-loop.sh";
|
||||
text = builtins.readFile ./wsl2-probe-loop.sh;
|
||||
checkPhase = ''
|
||||
${lib.getExe pkgs.shellcheck} --shell=sh "$target"
|
||||
'';
|
||||
};
|
||||
|
||||
init = pkgs.writeTextFile {
|
||||
name = "wsl2-probe-init";
|
||||
executable = true;
|
||||
text = ''
|
||||
#!${busybox}/bin/sh
|
||||
PATH=${busybox}/bin
|
||||
# shellcheck source=/dev/null
|
||||
. ${loop}
|
||||
${builtins.readFile ./wsl2-probe-init.sh}
|
||||
'';
|
||||
checkPhase = ''
|
||||
${lib.getExe pkgs.shellcheck} --shell=sh "$target"
|
||||
'';
|
||||
};
|
||||
|
||||
initrd = pkgs.makeInitrd {
|
||||
contents = [
|
||||
{
|
||||
object = init;
|
||||
symlink = "/init";
|
||||
}
|
||||
{
|
||||
object = "${modules}/lib/modules";
|
||||
symlink = "/lib/modules";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
guest = pkgs.runCommand "wsl2-probe-guest" { } ''
|
||||
mkdir -p $out
|
||||
ln -s ${kernel}/${kernelImage} $out/kernel
|
||||
ln -s ${initrd}/initrd $out/initrd
|
||||
ln -s ${busybox}/bin/busybox $out/busybox
|
||||
ln -s ${loop} $out/loop.sh
|
||||
'';
|
||||
|
||||
probe = pkgs.writeShellApplication {
|
||||
name = "wsl2-probe";
|
||||
runtimeInputs = with pkgs; [
|
||||
# QEMU with GTK and VirGL, which the real guest uses, and the daemon that serves the guest's
|
||||
# /nix/store and shared directories
|
||||
qemu_kvm
|
||||
virtiofsd
|
||||
# eglinfo and glxinfo
|
||||
mesa-demos
|
||||
socat
|
||||
# what the script needs of a system, the same on every distribution
|
||||
coreutils
|
||||
findutils
|
||||
gawk
|
||||
gnugrep
|
||||
gnused
|
||||
iproute2
|
||||
jq
|
||||
procps
|
||||
util-linux
|
||||
];
|
||||
# the script sets its own options: a probe that stops at the first failure answers nothing
|
||||
bashOptions = [ ];
|
||||
text = ''
|
||||
export WSL2_PROBE_GUEST=${guest}
|
||||
export WSL2_PROBE_REV=${rev}
|
||||
${builtins.readFile ../../scripts/wsl2-probe.sh}
|
||||
'';
|
||||
meta = {
|
||||
description = "Probes a NixOS-WSL2 machine for KVM, WSLg, a GPU and RDP, for a Plasma guest";
|
||||
mainProgram = "wsl2-probe";
|
||||
};
|
||||
};
|
||||
in
|
||||
{
|
||||
inherit guest probe;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{ kde-rounded-corners, fetchFromGitHub }:
|
||||
|
||||
# 0.11.0 is the release that draws the outline in the right place on KWin 6.8: 6.8 inverted the
|
||||
# texture coordinates of the offscreen window, and with Breeze's shadow (deeper below a window than
|
||||
# above it) the whole ring of 0.10.0 lands about 24px too low, across the title bar ("KWin 6.8
|
||||
# compatibility for inverted texture coordinates"). nixpkgs has 0.11.0 too (2026-10-28; it had
|
||||
# 0.10.0 at d3b13ad of 2026-10-24), and the version and the source are set here all the same: the
|
||||
# patch below is written for the 0.11.0 source.
|
||||
kde-rounded-corners.overrideAttrs (old: {
|
||||
version = "0.11.0";
|
||||
|
||||
# per-window outline colors, set over D-Bus (org.komorebi.BorderColours1): komorebi colors a
|
||||
# window by what it is to the layout (the focused one on each monitor, a stack, a monocle, a
|
||||
# floating window, a locked container), which "the active window" cannot say. Without this the
|
||||
# effect still works, with the colors of the settings for the active and the other windows. The
|
||||
# patch also redraws a window from a fresh texture when only its opacity changes, which the
|
||||
# effect's texture would not show otherwise.
|
||||
patches = (old.patches or [ ]) ++ [ ./kde-rounded-corners/komorebi-border-colours.patch ];
|
||||
|
||||
src = fetchFromGitHub {
|
||||
owner = "matinlotfali";
|
||||
repo = "KDE-Rounded-Corners";
|
||||
rev = "v0.11.0";
|
||||
hash = "sha256-rdVXukBh7doyuZaFGVQghwKqkWGtuLOXxJgvZbZG0hQ=";
|
||||
};
|
||||
|
||||
# KWin loads every effect that is enabled by default when it starts, with the settings the effect
|
||||
# has then, and at its defaults this one draws a one pixel black outline inside every window,
|
||||
# over its title bar. Disabled by default, it stays unloaded until it is asked for (`loadEffect`
|
||||
# on KWin's `/Effects`), which can happen after its settings are written. KWin reads the flag
|
||||
# from the metadata compiled into the plugin.
|
||||
postPatch = (old.postPatch or "") + ''
|
||||
substituteInPlace src/metadata.json \
|
||||
--replace-fail '"EnabledByDefault": true' '"EnabledByDefault": false'
|
||||
'';
|
||||
})
|
||||
@@ -0,0 +1,218 @@
|
||||
komorebi-border-colours.patch, for KDE Rounded Corners 0.11.0
|
||||
(https://github.com/matinlotfali/KDE-Rounded-Corners), applied by
|
||||
nix/kde-rounded-corners.nix. It gives each window's outer outline the color
|
||||
komorebi sets for it over D-Bus (org.komorebi.BorderColours1 at
|
||||
/org/komorebi/BorderColours, on KWin's name org.kde.KWin); a window without one
|
||||
is drawn with the colors of the settings. It also redirects a window drawn
|
||||
through the effect again when the window's opacity changes, so that a change
|
||||
of opacity alone shows.
|
||||
|
||||
This patch is a derivative work of KDE Rounded Corners, which is distributed
|
||||
under the GNU General Public License version 3, and it is distributed under
|
||||
the same license.
|
||||
|
||||
SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under
|
||||
the terms of the GNU General Public License as published by the Free Software
|
||||
Foundation, version 3.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with
|
||||
this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
diff -ruN a/src/CMakeLists.txt b/src/CMakeLists.txt
|
||||
--- a/src/CMakeLists.txt 2026-10-26 21:49:20
|
||||
+++ b/src/CMakeLists.txt 2026-10-26 21:49:44
|
||||
@@ -5,6 +5,7 @@
|
||||
Shader.cpp
|
||||
Window.h
|
||||
Window.cpp
|
||||
+ WindowColours.h
|
||||
TileChecker.h
|
||||
TileChecker.cpp
|
||||
FloatColor.h
|
||||
diff -ruN a/src/Effect.cpp b/src/Effect.cpp
|
||||
--- a/src/Effect.cpp 2026-10-26 21:49:20
|
||||
+++ b/src/Effect.cpp 2026-10-26 23:24:01
|
||||
@@ -27,6 +27,7 @@
|
||||
#include "Config.h"
|
||||
#include "Utils.h"
|
||||
#include "Window.h"
|
||||
+#include "WindowColours.h"
|
||||
#include "WindowManager.h"
|
||||
#if QT_VERSION_MAJOR >= 6
|
||||
#include <core/output.h>
|
||||
@@ -87,6 +88,9 @@
|
||||
|
||||
ShapeCorners::Effect::Effect()
|
||||
{
|
||||
+ // komorebi tells this effect which colour each window's border is
|
||||
+ WindowColours::instance().registerOnBus();
|
||||
+
|
||||
// Read configuration and initialize the effect.
|
||||
reconfigure(ReconfigureAll);
|
||||
|
||||
@@ -98,11 +102,33 @@
|
||||
m_windowManager = std::make_unique<WindowManager>();
|
||||
// Connect the windowAdded signal to handle new windows.
|
||||
connect(KWin::effects, &KWin::EffectsHandler::windowAdded, this, &Effect::windowAdded);
|
||||
+ // A window drawn through this effect is drawn from a texture that has the window's opacity
|
||||
+ // in it, and that is made again only when the window's contents change or it is resized: a
|
||||
+ // change of opacity alone (komorebi's transparency) would not show. Redirect it afresh.
|
||||
+ const auto refreshOnOpacity = [this](KWin::EffectWindow *kwindow, qreal, qreal) {
|
||||
+ auto *window = m_windowManager->findWindow(kwindow);
|
||||
+ if (window == nullptr || !window->hasEffect()) {
|
||||
+ return;
|
||||
+ }
|
||||
+ unredirect(kwindow);
|
||||
+ redirect(kwindow);
|
||||
+ setShader(kwindow, m_shaderManager.GetShader().get());
|
||||
+ kwindow->addRepaintFull();
|
||||
+ };
|
||||
+ for (auto *kwindow: KWin::effects->stackingOrder()) {
|
||||
+ connect(kwindow, &KWin::EffectWindow::windowOpacityChanged, this, refreshOnOpacity);
|
||||
+ }
|
||||
+ connect(KWin::effects, &KWin::EffectsHandler::windowAdded, this,
|
||||
+ [this, refreshOnOpacity](KWin::EffectWindow *kwindow) {
|
||||
+ connect(kwindow, &KWin::EffectWindow::windowOpacityChanged, this, refreshOnOpacity);
|
||||
+ });
|
||||
}
|
||||
}
|
||||
|
||||
ShapeCorners::Effect::~Effect()
|
||||
{
|
||||
+ WindowColours::instance().unregisterFromBus();
|
||||
+
|
||||
// If the shader manager is valid, then the effect has been active, so some cleanup is needed.
|
||||
if (m_shaderManager.IsValid()) {
|
||||
// Restore Breeze outline setting when effect is unloaded:
|
||||
diff -ruN a/src/Shader.cpp b/src/Shader.cpp
|
||||
--- a/src/Shader.cpp 2026-10-26 21:49:20
|
||||
+++ b/src/Shader.cpp 2026-10-26 21:49:44
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "Config.h"
|
||||
#include "Utils.h"
|
||||
#include "Window.h"
|
||||
+#include "WindowColours.h"
|
||||
#include "WindowConfig.h"
|
||||
#if QT_VERSION_MAJOR >= 6
|
||||
#include <core/pixelgrid.h>
|
||||
@@ -160,8 +161,10 @@
|
||||
m_shader->setUniform(m_shader_secondOutlineColor1, secondOutline.color1.toQColor());
|
||||
m_shader->setUniform(m_shader_secondOutlineColor2, secondOutline.color2.toQColor());
|
||||
m_shader->setUniform(m_shader_secondOutlineAngle, secondOutline.angle);
|
||||
- m_shader->setUniform(m_shader_outerOutlineColor1, outerOutline.color1.toQColor());
|
||||
- m_shader->setUniform(m_shader_outerOutlineColor2, outerOutline.color2.toQColor());
|
||||
+ // a colour komorebi gave this window wins over the active and inactive settings
|
||||
+ const auto given = ShapeCorners::WindowColours::instance().colourFor(window.w);
|
||||
+ m_shader->setUniform(m_shader_outerOutlineColor1, given ? *given : outerOutline.color1.toQColor());
|
||||
+ m_shader->setUniform(m_shader_outerOutlineColor2, given ? *given : outerOutline.color2.toQColor());
|
||||
m_shader->setUniform(m_shader_outerOutlineAngle, outerOutline.angle);
|
||||
} else {
|
||||
const QColor transparent(0, 0, 0, 0);
|
||||
diff -ruN a/src/WindowColours.h b/src/WindowColours.h
|
||||
--- a/src/WindowColours.h 1969-12-31 16:00:00
|
||||
+++ b/src/WindowColours.h 2026-10-26 23:12:15
|
||||
@@ -0,0 +1,98 @@
|
||||
+/**
|
||||
+ * @file WindowColours.h
|
||||
+ * @brief Per-window colours for the outer outline, set from outside over D-Bus (komorebi).
|
||||
+ *
|
||||
+ * A tiling window manager knows better than "the active window" which windows are what: the
|
||||
+ * focused one on each monitor, a stack, a monocled window, a floating window, a locked container.
|
||||
+ * It says so, and this effect draws the outer outline of each window it has a colour for in that
|
||||
+ * colour. Windows it has none for are drawn as the settings say.
|
||||
+ *
|
||||
+ * The object is on the session bus at /org/komorebi/BorderColours, interface
|
||||
+ * org.komorebi.BorderColours1, reached through KWin's own name (org.kde.KWin).
|
||||
+ */
|
||||
+
|
||||
+#pragma once
|
||||
+
|
||||
+#include <QColor>
|
||||
+#include <QDBusConnection>
|
||||
+#include <QHash>
|
||||
+#include <QList>
|
||||
+#include <QObject>
|
||||
+#include <QStringList>
|
||||
+#include <QUuid>
|
||||
+#include <optional>
|
||||
+
|
||||
+#if QT_VERSION_MAJOR >= 6
|
||||
+#include <effect/effecthandler.h>
|
||||
+#include <effect/effectwindow.h>
|
||||
+#else
|
||||
+#include <kwineffects.h>
|
||||
+#endif
|
||||
+
|
||||
+namespace ShapeCorners
|
||||
+{
|
||||
+ class WindowColours final : public QObject
|
||||
+ {
|
||||
+ Q_OBJECT
|
||||
+ Q_CLASSINFO("D-Bus Interface", "org.komorebi.BorderColours1")
|
||||
+
|
||||
+ public:
|
||||
+ static WindowColours &instance()
|
||||
+ {
|
||||
+ static WindowColours colours;
|
||||
+ return colours;
|
||||
+ }
|
||||
+
|
||||
+ void registerOnBus()
|
||||
+ {
|
||||
+ QDBusConnection::sessionBus().registerObject(QStringLiteral("/org/komorebi/BorderColours"), this,
|
||||
+ QDBusConnection::ExportAllSlots);
|
||||
+ }
|
||||
+
|
||||
+ void unregisterFromBus()
|
||||
+ {
|
||||
+ QDBusConnection::sessionBus().unregisterObject(QStringLiteral("/org/komorebi/BorderColours"));
|
||||
+ m_colours.clear();
|
||||
+ }
|
||||
+
|
||||
+ /// The colour this window's outer outline is to be drawn in, if it was given one
|
||||
+ [[nodiscard]]
|
||||
+ std::optional<QColor> colourFor(const KWin::EffectWindow *window) const
|
||||
+ {
|
||||
+ if (m_colours.isEmpty()) {
|
||||
+ return std::nullopt;
|
||||
+ }
|
||||
+ const auto found = m_colours.constFind(window->internalId());
|
||||
+ if (found == m_colours.constEnd()) {
|
||||
+ return std::nullopt;
|
||||
+ }
|
||||
+ return *found;
|
||||
+ }
|
||||
+
|
||||
+ public Q_SLOTS:
|
||||
+ /// Replace the colours of every window at once: window uuids (as KWin writes them, with or
|
||||
+ /// without braces) and 0xRRGGBB values, in step. Windows not named go back to the settings.
|
||||
+ void SetColours(const QStringList &windows, const QList<uint> &rgb)
|
||||
+ {
|
||||
+ QHash<QUuid, QColor> colours;
|
||||
+ for (qsizetype i = 0; i < windows.size() && i < rgb.size(); ++i) {
|
||||
+ const auto id = QUuid::fromString(windows[i]);
|
||||
+ if (!id.isNull()) {
|
||||
+ colours.insert(id, QColor::fromRgb(rgb[i] & 0xFFFFFF));
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ if (colours == m_colours) {
|
||||
+ return;
|
||||
+ }
|
||||
+ m_colours = colours;
|
||||
+
|
||||
+ for (auto *window: KWin::effects->stackingOrder()) {
|
||||
+ window->addRepaintFull();
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ private:
|
||||
+ QHash<QUuid, QColor> m_colours;
|
||||
+ };
|
||||
+} // namespace ShapeCorners
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
||||
{
|
||||
lib,
|
||||
stdenvNoCC,
|
||||
fetchFromGitHub,
|
||||
}:
|
||||
|
||||
# "Geometry Change" by Peter Fajdiga (GPLv3): animates windows that are moved or resized by programs
|
||||
# or scripts, which stock KWin does not. It is a scripted (JS) effect package, so installing it is
|
||||
# only a copy into `share/kwin/effects`; kwin discovers it at startup, not afterwards. Its metadata
|
||||
# already says `"EnabledByDefault": false`, so KWin does not load it until it is asked for.
|
||||
stdenvNoCC.mkDerivation {
|
||||
pname = "kwin-effect-geometry-change";
|
||||
version = "1.5";
|
||||
|
||||
src = fetchFromGitHub {
|
||||
owner = "peterfajdiga";
|
||||
repo = "kwin4_effect_geometry_change";
|
||||
rev = "398491e8a3f5b9bb785850439abd41820f3c5986";
|
||||
hash = "sha256-aJx3hDzIk/bQrrRvs/CPigJ0miTgqxd8OI9I6kuiXkk=";
|
||||
};
|
||||
|
||||
# `Curve`: any of Qt's easing curves by name, which is how komorebi's `animation.style` reaches the
|
||||
# effect (it has one fixed curve, an ease out exponential, and no setting for it)
|
||||
patches = [ ./kwin-effect-geometry-change/curve.patch ];
|
||||
|
||||
dontBuild = true;
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
mkdir -p $out/share/kwin/effects/kwin4_effect_geometry_change
|
||||
cp -r package/* $out/share/kwin/effects/kwin4_effect_geometry_change/
|
||||
runHook postInstall
|
||||
'';
|
||||
|
||||
meta = {
|
||||
description = "KWin effect that animates windows moved or resized by programs or scripts";
|
||||
homepage = "https://github.com/peterfajdiga/kwin4_effect_geometry_change";
|
||||
license = lib.licenses.gpl3Only;
|
||||
platforms = lib.platforms.linux;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
curve.patch, for Geometry Change at revision 398491e
|
||||
(https://github.com/peterfajdiga/kwin4_effect_geometry_change), applied by
|
||||
nix/kwin-effect-geometry-change.nix. It adds a Curve setting: any of Qt's
|
||||
easing curves by name (OutExpo, InOutSine, ...), which is how komorebi sets
|
||||
the curve of its animations. An unknown or missing name is the effect's own
|
||||
curve, OutExpo.
|
||||
|
||||
This patch is a derivative work of Geometry Change, which is distributed under
|
||||
the GNU General Public License version 3, and it is distributed under the same
|
||||
license.
|
||||
|
||||
SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under
|
||||
the terms of the GNU General Public License as published by the Free Software
|
||||
Foundation, version 3.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with
|
||||
this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
diff -ruN a/package/contents/code/main.js b/package/contents/code/main.js
|
||||
--- a/package/contents/code/main.js 2026-10-26 21:55:40
|
||||
+++ b/package/contents/code/main.js 2026-10-26 21:55:40
|
||||
@@ -17,6 +17,12 @@
|
||||
this.duration = animationTime(duration);
|
||||
this.excludedWindowClasses = effect.readConfig("ExcludedWindowClasses", "krunner,yakuake").split(",");
|
||||
this.crossFade = effect.readConfig("CrossFade", false);
|
||||
+ // komorebi: any of Qt's easing curves by name ("OutExpo", "InOutSine", ...), which is how it
|
||||
+ // says what its `animation.style` is; an unknown or missing name is the effect's own curve
|
||||
+ this.curve = QEasingCurve[effect.readConfig("Curve", "OutExpo")];
|
||||
+ if (this.curve === undefined) {
|
||||
+ this.curve = QEasingCurve.OutExpo;
|
||||
+ }
|
||||
}
|
||||
|
||||
manage(window) {
|
||||
@@ -128,7 +134,7 @@
|
||||
animate({
|
||||
window: window,
|
||||
duration: this.duration,
|
||||
- curve: QEasingCurve.OutExpo,
|
||||
+ curve: this.curve,
|
||||
animations: animations,
|
||||
});
|
||||
}
|
||||
diff -ruN a/package/contents/config/main.xml b/package/contents/config/main.xml
|
||||
--- a/package/contents/config/main.xml 2026-10-26 22:29:29
|
||||
+++ b/package/contents/config/main.xml 2026-10-26 22:29:29
|
||||
@@ -14,5 +14,8 @@
|
||||
<entry name="CrossFade" type="Bool">
|
||||
<default>false</default>
|
||||
</entry>
|
||||
+ <entry name="Curve" type="String">
|
||||
+ <default>OutExpo</default>
|
||||
+ </entry>
|
||||
</group>
|
||||
</kcfg>
|
||||
@@ -0,0 +1,566 @@
|
||||
# `services.komorebi`: komorebi in the Plasma session of every user of a NixOS machine. The flake
|
||||
# exports this module as `nixosModules.default` and `nixosModules.komorebi`, together with its
|
||||
# overlay, which provides `pkgs.komorebi-full` (see docs/installation.md). What the module
|
||||
# guarantees, and what enforces each guarantee, is in docs/dev/ARCHITECTURE.md; its tests are
|
||||
# nix/tests/nixos-module.nix and the VM suite `module`.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
cfg = config.services.komorebi;
|
||||
|
||||
jsonFormat = pkgs.formats.json { };
|
||||
|
||||
# The options `just nixgen` makes from `schema.json`, which type `config`
|
||||
komorebiOptionsModule = import ./komorebi-options.nix { inherit 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;
|
||||
|
||||
# A komorebi.json, checked against the schema the Rust types make (`schema.json`). Comment
|
||||
# lines are taken out first: komorebi reads JSON with comments, and the schema checker does not.
|
||||
validateJsonFile =
|
||||
{
|
||||
name,
|
||||
jsonFile,
|
||||
}:
|
||||
pkgs.runCommand "validated-${name}" { nativeBuildInputs = [ pkgs.check-jsonschema ]; } ''
|
||||
grep -v '^\s*//' ${jsonFile} > clean.json
|
||||
check-jsonschema --schemafile ${../schema.json} clean.json
|
||||
cp clean.json $out
|
||||
'';
|
||||
|
||||
fetchAppSpecificSource =
|
||||
source:
|
||||
pkgs.fetchurl {
|
||||
url = "https://raw.githubusercontent.com/${source.owner}/${source.repo}/${source.rev}/${source.path}";
|
||||
inherit (source) hash;
|
||||
};
|
||||
|
||||
applicationSpecificConfigFiles = map fetchAppSpecificSource cfg.applicationSpecificConfiguration.sources;
|
||||
|
||||
# one file is a path, several are a list of paths
|
||||
appSpecificPaths =
|
||||
if builtins.length applicationSpecificConfigFiles == 1 then
|
||||
"${builtins.head applicationSpecificConfigFiles}"
|
||||
else
|
||||
map (f: "${f}") applicationSpecificConfigFiles;
|
||||
|
||||
shouldUseAppSpecific =
|
||||
cfg.applicationSpecificConfiguration.enable && applicationSpecificConfigFiles != [ ];
|
||||
|
||||
# What `config` and `applicationSpecificConfiguration` make: the komorebi.json as an attribute
|
||||
# set, with no null in it, or null when there is nothing to write
|
||||
configAttrs =
|
||||
if cfg.config == null && !shouldUseAppSpecific then
|
||||
null
|
||||
else
|
||||
filterNulls (
|
||||
(if cfg.config == null then { } else cfg.config)
|
||||
// lib.optionalAttrs shouldUseAppSpecific { app_specific_configuration_path = appSpecificPaths; }
|
||||
);
|
||||
|
||||
# the file the daemon is given: the one `configFile` names, or the one the options make, each
|
||||
# checked against the schema
|
||||
komorebiConfigFile =
|
||||
if cfg.configFile != null then
|
||||
validateJsonFile {
|
||||
name = "komorebi.json";
|
||||
jsonFile = cfg.configFile;
|
||||
}
|
||||
else if configAttrs != null then
|
||||
validateJsonFile {
|
||||
name = "komorebi.json";
|
||||
jsonFile = jsonFormat.generate "komorebi.json" configAttrs;
|
||||
}
|
||||
else
|
||||
null;
|
||||
|
||||
kb = cfg.keybindings;
|
||||
|
||||
# key bindings are configured when any of the three is set; the assertions say what is missing
|
||||
keybindingsSet = kb.format != null || kb.text != null || kb.file != null;
|
||||
# the file the daemon reads, named after its format so that it reads as one
|
||||
keybindingsFile =
|
||||
if kb.file != null then kb.file else pkgs.writeText "komorebi-${toString kb.format}rc" kb.text;
|
||||
|
||||
# `komorebic hotkeys compile`: the static shortcuts of the file, in share/kglobalaccel, where KWin
|
||||
# finds them in the system profile, and what komorebic had to say about the file
|
||||
compiled = pkgs.runCommand "komorebi-keybindings" { } ''
|
||||
mkdir -p $out/share/kglobalaccel
|
||||
if ! ${lib.getExe' cfg.package "komorebic"} hotkeys compile \
|
||||
--format ${toString kb.format} --mode ${kb.mode} ${lib.optionalString kb.strict "--strict"} \
|
||||
${keybindingsFile} --output $out/share/kglobalaccel 2> $out/diagnostics.txt; then
|
||||
cat $out/diagnostics.txt >&2
|
||||
exit 1
|
||||
fi
|
||||
cat $out/diagnostics.txt >&2
|
||||
'';
|
||||
|
||||
keybindingsArgs = [
|
||||
"--keybindings"
|
||||
"${keybindingsFile}"
|
||||
"--keybindings-format"
|
||||
(toString kb.format)
|
||||
"--keybindings-mode"
|
||||
kb.mode
|
||||
"--chord-timeout"
|
||||
(toString kb.chordTimeout)
|
||||
]
|
||||
++ lib.concatMap (name: [
|
||||
"--app-alias"
|
||||
(lib.escapeShellArg "${name}=${lib.concatStringsSep "," kb.appAliases.${name}}")
|
||||
]) (lib.attrNames kb.appAliases);
|
||||
|
||||
# the KWin versions komorebi supports, and the KWin of this system
|
||||
supportedKwin = import ./supported-kwin.nix;
|
||||
kwinVersion = pkgs.kdePackages.kwin.version;
|
||||
kwinUntested = lib.versionOlder supportedKwin.testedMax kwinVersion;
|
||||
in
|
||||
{
|
||||
options.services.komorebi = {
|
||||
enable = lib.mkEnableOption "komorebi, the tiling window manager, in the Plasma session of every user";
|
||||
|
||||
package = lib.mkPackageOption pkgs "komorebi-full" {
|
||||
extraDescription = ''
|
||||
It must have `bin/komorebi`, which the unit runs, and `bin/komorebic`. The module installs
|
||||
both in the system profile.
|
||||
'';
|
||||
};
|
||||
|
||||
logLevel = lib.mkOption {
|
||||
type = lib.types.enum [
|
||||
"error"
|
||||
"warn"
|
||||
"info"
|
||||
"debug"
|
||||
"trace"
|
||||
];
|
||||
default = "info";
|
||||
description = ''
|
||||
How much the daemon logs: its `--log-level`. The log goes to the journal of the unit
|
||||
(`journalctl --user -u komorebi`) and to the daemon's log files, which `komorebic log`
|
||||
follows.
|
||||
'';
|
||||
};
|
||||
|
||||
configFile = lib.mkOption {
|
||||
type = lib.types.nullOr lib.types.path;
|
||||
default = null;
|
||||
example = lib.literalExpression "./komorebi.json";
|
||||
description = ''
|
||||
The `komorebi.json` the daemon is configured by, checked against the schema of
|
||||
`komorebi.json` when the system is built. The unit starts komorebi with it, as `--config`,
|
||||
in place of the `komorebi.json` the daemon looks for in `~/.config/komorebi`
|
||||
(`$KOMOREBI_CONFIG_HOME`). The file is in the Nix store, so it does not change under the
|
||||
daemon: a new file is read when the daemon starts again. `komorebic configuration` still
|
||||
shows the file of the config home, which the daemon does not read while this is set. With
|
||||
neither `configFile` nor `config`, the daemon reads the file of the config home, if there
|
||||
is one. Ignored by `config`, which is ignored when this is set.
|
||||
'';
|
||||
};
|
||||
|
||||
config = lib.mkOption {
|
||||
type = lib.types.nullOr komorebiOptionsModule.options.komorebi.type;
|
||||
default = null;
|
||||
example = lib.literalExpression ''
|
||||
{
|
||||
default_workspace_padding = 15;
|
||||
monitors = [
|
||||
{
|
||||
workspaces = [
|
||||
{ name = "web"; layout = "BSP"; }
|
||||
{ name = "code"; layout = "Columns"; }
|
||||
];
|
||||
}
|
||||
];
|
||||
}
|
||||
'';
|
||||
description = ''
|
||||
The configuration of komorebi, written as Nix: every key of `komorebi.json`, typed from
|
||||
the schema, so a layout that does not exist or a value of the wrong kind does not
|
||||
evaluate. The module writes it as a `komorebi.json`, checks that against the schema, and
|
||||
starts komorebi with it as `--config`. Ignored if `configFile` is set. A key you leave
|
||||
out is the default the schema gives it, if it gives one, and the daemon's own otherwise.
|
||||
'';
|
||||
};
|
||||
|
||||
applicationSpecificConfiguration = {
|
||||
enable = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = "Whether to use the sources of application specific configuration.";
|
||||
};
|
||||
|
||||
sources = lib.mkOption {
|
||||
type = lib.types.listOf (
|
||||
lib.types.submodule {
|
||||
options = {
|
||||
owner = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "GitHub repository owner.";
|
||||
example = "LGUG2Z";
|
||||
};
|
||||
repo = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "GitHub repository name.";
|
||||
example = "komorebi-application-specific-configuration";
|
||||
};
|
||||
rev = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "Git revision (commit hash, tag, or branch).";
|
||||
example = "09ebdcd95780b168cecde2f2d49096a58e91365f";
|
||||
};
|
||||
path = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "applications.json";
|
||||
description = "Path to the JSON file within the repository.";
|
||||
};
|
||||
hash = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "SHA256 hash of the file, for reproducibility.";
|
||||
example = "sha256-gfYubJpVEU6vxdd/vqujQhQX8mdAEE9ImugqdIyTQKk=";
|
||||
};
|
||||
};
|
||||
}
|
||||
);
|
||||
default = [ ];
|
||||
description = ''
|
||||
Files of application specific configuration, each fetched from GitHub, which the module
|
||||
gives the daemon as `app_specific_configuration_path` of the configuration it writes
|
||||
(it replaces the value `config` has for that key). There are none by default: no
|
||||
community file for KDE Plasma is known. Ignored when `configFile` is set.
|
||||
'';
|
||||
example = lib.literalExpression ''
|
||||
[
|
||||
{
|
||||
owner = "myuser";
|
||||
repo = "my-komorebi-rules";
|
||||
rev = "0123456789abcdef0123456789abcdef01234567";
|
||||
path = "applications.json";
|
||||
hash = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
|
||||
}
|
||||
]
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
effects.borders = {
|
||||
enable = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
Install the KWin effect that draws komorebi's borders, KDE Rounded Corners. This is
|
||||
installation only: whether borders are drawn is komorebi's setting (`komorebic border`),
|
||||
which asks KWin to load the effect when it is on. KWin finds effects when it starts, so
|
||||
an effect installed by a switch to a new system is found after the next login.
|
||||
|
||||
Without the effect, komorebi draws no border and leaves no room for one.
|
||||
'';
|
||||
};
|
||||
|
||||
package = lib.mkPackageOption pkgs "kde-rounded-corners-komorebi" {
|
||||
extraDescription = ''
|
||||
It must have `lib/qt-6/plugins/kwin/effects/plugins/kwin4_effect_shapecorners.so`, built
|
||||
against the KWin of the system and not loaded by default. The default is KDE Rounded
|
||||
Corners 0.11.0, which draws correctly on KWin 6.8.
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
effects.animation = {
|
||||
enable = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
Install the KWin effect that animates komorebi's windows going to their places, Geometry
|
||||
Change. This is installation only: whether windows are animated is komorebi's setting
|
||||
(`komorebic animation`), which asks KWin to load the effect when it is on. KWin finds
|
||||
effects when it starts, so an effect installed by a switch to a new system is found
|
||||
after the next login.
|
||||
|
||||
Without the effect, windows jump to their places.
|
||||
'';
|
||||
};
|
||||
|
||||
package = lib.mkPackageOption pkgs "kwin-effect-geometry-change-komorebi" {
|
||||
extraDescription = ''
|
||||
It must have `share/kwin/effects/kwin4_effect_geometry_change`, a scripted effect that
|
||||
is not loaded by default.
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
internal.configAttrs = lib.mkOption {
|
||||
type = lib.types.nullOr lib.types.attrs;
|
||||
readOnly = true;
|
||||
internal = true;
|
||||
description = ''
|
||||
What `config` and `applicationSpecificConfiguration` make, before it is written as JSON:
|
||||
the `komorebi.json` as an attribute set with no null in it, or null when neither is set.
|
||||
The tests of the module read it, so that they need not build the file.
|
||||
'';
|
||||
};
|
||||
|
||||
execStart = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
readOnly = true;
|
||||
description = ''
|
||||
The command line the unit starts komorebi with: `bin/komorebi` of `package`, with
|
||||
`logLevel`, with `--config` and the checked `komorebi.json` when `configFile` or `config` is
|
||||
set, and with the key bindings when there are some. The module sets it, and setting it
|
||||
anywhere else is an error. A unit of your own that runs komorebi somewhere else, as the VM
|
||||
tests do in their headless sessions, starts it with this, the way the module does.
|
||||
'';
|
||||
};
|
||||
|
||||
keybindings = {
|
||||
format = lib.mkOption {
|
||||
type = lib.types.nullOr (
|
||||
lib.types.enum [
|
||||
"skhd"
|
||||
"whkd"
|
||||
"sxhkd"
|
||||
]
|
||||
);
|
||||
default = null;
|
||||
example = "skhd";
|
||||
description = ''
|
||||
The format of the key bindings: that of skhd's skhdrc, whkd's whkdrc or sxhkd's sxhkdrc.
|
||||
Required with `text` or `file`.
|
||||
'';
|
||||
};
|
||||
|
||||
text = lib.mkOption {
|
||||
type = lib.types.nullOr lib.types.lines;
|
||||
default = null;
|
||||
example = ''
|
||||
alt - h : komorebic focus left
|
||||
alt - l : komorebic focus right
|
||||
'';
|
||||
description = ''
|
||||
The key bindings, written in `format`. Set this or `file`, not both. skhd's `.load`,
|
||||
which reads another file, is refused: the file would not be in the store.
|
||||
'';
|
||||
};
|
||||
|
||||
file = lib.mkOption {
|
||||
type = lib.types.nullOr lib.types.path;
|
||||
default = null;
|
||||
example = lib.literalExpression "./skhdrc";
|
||||
description = "A file of key bindings, written in `format`. Set this or `text`, not both.";
|
||||
};
|
||||
|
||||
mode = lib.mkOption {
|
||||
type = lib.types.enum [
|
||||
"auto"
|
||||
"engine"
|
||||
"static"
|
||||
];
|
||||
default = "engine";
|
||||
description = ''
|
||||
Which bindings KDE runs by itself, as static shortcuts that the module installs in the
|
||||
system profile, and which the daemon registers and runs (the engine). `engine`: every
|
||||
binding is the engine's. `auto`: every binding that can be a static shortcut is one (one
|
||||
combo, pressed, the same in every application, in a file with no modes, blacklist or
|
||||
pause binding), and the engine runs the others. `static`: only static shortcuts; what
|
||||
needs the engine is left out, with a warning. A static shortcut works with no komorebi
|
||||
running and shows in System Settings, but takes about 0.2 s to run its command; the
|
||||
engine takes a few milliseconds.
|
||||
'';
|
||||
};
|
||||
|
||||
chordTimeout = lib.mkOption {
|
||||
type = lib.types.ints.positive;
|
||||
default = 3000;
|
||||
description = "How long, in milliseconds, the engine waits for the next key of a chord chain.";
|
||||
};
|
||||
|
||||
layout = lib.mkOption {
|
||||
type = lib.types.enum [ "us" ];
|
||||
default = "us";
|
||||
description = ''
|
||||
The keyboard layout positional key names are read with: skhd's macOS keycodes (`0x21`)
|
||||
and whkd's `oem_*` keys, and the symbol a shifted key types. `us` is the only one.
|
||||
'';
|
||||
};
|
||||
|
||||
strict = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = false;
|
||||
description = ''
|
||||
Fail the build when something in the key bindings is not realized the way the file's own
|
||||
hotkey daemon realizes it: a diagnostic of `komorebic hotkeys compile` that is a warning
|
||||
or an error. The diagnostics are in the build log and in `diagnostics.txt` of the
|
||||
`komorebi-keybindings` package either way.
|
||||
'';
|
||||
};
|
||||
|
||||
appAliases = lib.mkOption {
|
||||
type = lib.types.attrsOf (lib.types.listOf lib.types.str);
|
||||
default = { };
|
||||
example = {
|
||||
firefox = [
|
||||
"firefox-esr"
|
||||
"librewolf"
|
||||
];
|
||||
};
|
||||
description = ''
|
||||
Other names of an application, for the bindings that are for one application: an skhdrc
|
||||
or a whkdrc names applications as macOS or Windows does, and KDE knows them by their
|
||||
executable, app id or desktop entry.
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
kwin.untestedIsError = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = false;
|
||||
description = ''
|
||||
Refuse a KWin newer than the newest one komorebi has been tested with (`testedMax` in
|
||||
the repository's `nix/supported-kwin.nix`), instead of warning about it. A KWin older than
|
||||
the oldest one komorebi supports (`min`) is refused either way.
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkMerge [
|
||||
{
|
||||
services.komorebi.execStart = lib.concatStringsSep " " (
|
||||
[
|
||||
(lib.getExe' cfg.package "komorebi")
|
||||
"--log-level"
|
||||
cfg.logLevel
|
||||
]
|
||||
++ lib.optionals (komorebiConfigFile != null) [
|
||||
"--config"
|
||||
"${komorebiConfigFile}"
|
||||
]
|
||||
++ lib.optionals keybindingsSet keybindingsArgs
|
||||
);
|
||||
services.komorebi.internal.configAttrs = configAttrs;
|
||||
}
|
||||
|
||||
(lib.mkIf cfg.enable {
|
||||
assertions = [
|
||||
{
|
||||
assertion = config.services.desktopManager.plasma6.enable;
|
||||
message = ''
|
||||
services.komorebi needs Plasma 6: komorebi runs in a Plasma Wayland session, and the
|
||||
session starts it. Set services.desktopManager.plasma6.enable = true.
|
||||
'';
|
||||
}
|
||||
{
|
||||
assertion = keybindingsSet -> (kb.text != null) != (kb.file != null);
|
||||
message = ''
|
||||
services.komorebi.keybindings needs exactly one of text and file: the key bindings
|
||||
themselves, or the file they are in.
|
||||
'';
|
||||
}
|
||||
{
|
||||
assertion = keybindingsSet -> kb.format != null;
|
||||
message = ''
|
||||
services.komorebi.keybindings needs a format: "skhd", "whkd" or "sxhkd".
|
||||
'';
|
||||
}
|
||||
{
|
||||
assertion =
|
||||
!(
|
||||
keybindingsSet
|
||||
&& kb.format == "skhd"
|
||||
&& lib.any (line: lib.hasPrefix ".load" (lib.trim line)) (
|
||||
lib.splitString "\n" (if kb.text != null then kb.text else builtins.readFile kb.file)
|
||||
)
|
||||
);
|
||||
message = ''
|
||||
services.komorebi.keybindings: skhd's .load is not supported. It reads another file,
|
||||
which would not be in the store; put its bindings in this one.
|
||||
'';
|
||||
}
|
||||
{
|
||||
assertion = lib.versionAtLeast kwinVersion supportedKwin.min;
|
||||
message = ''
|
||||
services.komorebi needs KWin ${supportedKwin.min} or newer, and pkgs.kdePackages.kwin is
|
||||
${kwinVersion}. Use a nixpkgs with Plasma ${supportedKwin.min} or newer.
|
||||
'';
|
||||
}
|
||||
{
|
||||
assertion = !(cfg.kwin.untestedIsError && kwinUntested);
|
||||
message = ''
|
||||
pkgs.kdePackages.kwin is ${kwinVersion}, and komorebi has been tested with KWin
|
||||
${supportedKwin.testedMax} and older. services.komorebi.kwin.untestedIsError is true, so
|
||||
this is an error; set it to false to build the system with a warning instead.
|
||||
'';
|
||||
}
|
||||
];
|
||||
|
||||
warnings =
|
||||
lib.optional (
|
||||
cfg.configFile != null && cfg.config != null
|
||||
) "services.komorebi.config is ignored: services.komorebi.configFile is set."
|
||||
++
|
||||
lib.optional (cfg.configFile != null && cfg.applicationSpecificConfiguration.sources != [ ])
|
||||
"services.komorebi.applicationSpecificConfiguration is ignored: services.komorebi.configFile is set."
|
||||
++
|
||||
lib.optional
|
||||
(
|
||||
cfg.configFile == null
|
||||
&& cfg.config != null
|
||||
&& (cfg.config.border or null) == true
|
||||
&& !cfg.effects.borders.enable
|
||||
)
|
||||
"services.komorebi.config sets border to true, but services.komorebi.effects.borders.enable is false: without the effect, komorebi draws no border."
|
||||
++ lib.optional (kwinUntested && !cfg.kwin.untestedIsError) ''
|
||||
pkgs.kdePackages.kwin is ${kwinVersion}, and komorebi has been tested with KWin
|
||||
${supportedKwin.testedMax} and older. Set services.komorebi.kwin.untestedIsError = true
|
||||
to make this an error.
|
||||
'';
|
||||
|
||||
environment.systemPackages = [
|
||||
cfg.package
|
||||
]
|
||||
++ lib.optional cfg.effects.borders.enable cfg.effects.borders.package
|
||||
++ lib.optional cfg.effects.animation.enable cfg.effects.animation.package
|
||||
++ lib.optional keybindingsSet compiled;
|
||||
|
||||
# A user unit, so it runs for every user who logs in to Plasma. plasma-workspace.target is
|
||||
# the target of a Plasma session's services, and plasma-core.target, which it requires, is
|
||||
# ordered after KWin's service: the daemon exits when KWin is not on the session bus.
|
||||
systemd.user.services.komorebi = {
|
||||
description = "komorebi, the tiling window manager";
|
||||
wantedBy = [ "plasma-workspace.target" ];
|
||||
after = [ "plasma-core.target" ];
|
||||
# NixOS gives a unit a PATH made of a few store paths; this is the PATH a terminal in the
|
||||
# user's session has
|
||||
enableDefaultPath = false;
|
||||
environment.PATH = lib.concatStringsSep ":" [
|
||||
"/run/wrappers/bin"
|
||||
"/etc/profiles/per-user/%u/bin"
|
||||
"/run/current-system/sw/bin"
|
||||
];
|
||||
serviceConfig = {
|
||||
ExecStart = cfg.execStart;
|
||||
# kglobalaccel keeps the keys of a daemon that died until they are unregistered: without
|
||||
# this they would stay swallowed, running nothing, until the next start
|
||||
ExecStopPost = "${lib.getExe' cfg.package "komorebic"} hotkeys release";
|
||||
Restart = "on-failure";
|
||||
# what komorebi exits with when it is stopped with SIGTERM, as systemd stops a unit
|
||||
SuccessExitStatus = 130;
|
||||
};
|
||||
};
|
||||
})
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[
|
||||
"crates/komorebi-backend",
|
||||
"crates/komorebi-collections",
|
||||
"crates/komorebi-config",
|
||||
"crates/komorebi-core",
|
||||
"crates/komorebi-protocol",
|
||||
"crates/komorebi-settings",
|
||||
"crates/komorebi-transport",
|
||||
"crates/komorebi-version",
|
||||
"crates/komorebic-core",
|
||||
"komorebi-client",
|
||||
"komorebi-layouts",
|
||||
"komorebi-scrolling",
|
||||
"komorebi-themes",
|
||||
"komorebic"
|
||||
]
|
||||
@@ -0,0 +1,15 @@
|
||||
# The versions of KWin komorebi supports. The NixOS module checks the KWin of a system against
|
||||
# them (nix/nixos-module.nix). The file is a plain attribute set, so a script or a CI job can
|
||||
# read it without the flake:
|
||||
#
|
||||
# nix eval --raw --file nix/supported-kwin.nix testedMax
|
||||
{
|
||||
# The oldest KWin komorebi runs on. The bridge reads the work area of each output for the
|
||||
# virtual desktop that output shows, which needs the per-output virtual desktops of KWin 6.8.
|
||||
min = "6.8";
|
||||
|
||||
# The newest KWin that every VM suite has passed against. A commit that raises it says which
|
||||
# suites ran, and against which nixpkgs (CONTRIBUTING.md).
|
||||
# 2026-10-28: every VM suite, nixpkgs-unstable f05535a (2026-10-27), KWin 6.8.2.
|
||||
testedMax = "6.8.2";
|
||||
}
|
||||
@@ -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)
|
||||
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