From 2b116ea2a38777fb8f685364e9707745db200504 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 21:20:46 -0700 Subject: [PATCH] feat(kwin): wallpapers for monitors and workspaces Plasma keeps one wallpaper for each screen, not for each virtual desktop, so a workspace that wants a picture of its own has nowhere to keep it in the shell. komorebi sets the wallpaper of a screen when a workspace comes into view: the workspace's own, else its monitor's. It does so however the workspace came into view (a komorebic command, a pager, an application raising a window) and for the workspace in front when it starts. A monitor and a workspace with no wallpaper are left alone. The Plasma shell sets it over D-Bus, with the call plasma-apply-wallpaperimage makes, but for one screen. Backend::set_wallpaper asks for it every time a workspace comes into view, and the KWin backend asks the shell what the screen shows first, so a picture the user changed by hand is put back and one that is already right is not touched. The request runs in the background, so switching workspaces never waits for the shell, and goes on trying for about half a minute when the shell is not up yet. A wallpaper also gives the borders the colors of the palette made from its picture, unless it says generate_theme is false, and theme_options choose the variant and the color each border takes. The colors change before the workspace is shown, so its borders are right at once. komorebi.json takes the wallpaper of a monitor and the wallpaper of a workspace, and a file that is read again shows the wallpaper of the workspace each monitor has in front at once. vm-wallpaper runs against the real shell: set at start and by workspace, a switch komorebi did not make, the colors of the borders, a wallpaper changed by hand, the palette cache, and komorebi that starts before the shell. --- README.md | 9 +- docs/dev/ARCHITECTURE.md | 46 +- docs/dev/DESIGN.md | 30 ++ docs/dev/PLATFORM.md | 25 ++ docs/index.md | 5 +- docs/usage/configuration.md | 9 +- docs/usage/wallpapers.md | 70 +++ flake.nix | 4 +- komorebi/src/backend/fake.rs | 20 + komorebi/src/backend/mod.rs | 37 +- komorebi/src/kwin/mod.rs | 127 ++++++ komorebi/src/kwin/wallpaper.rs | 155 +++++++ komorebi/src/lib.rs | 7 +- komorebi/src/monitor.rs | 9 +- komorebi/src/process_event.rs | 6 +- komorebi/src/state.rs | 2 + komorebi/src/static_config.rs | 76 ++++ komorebi/src/window_manager.rs | 53 ++- komorebi/src/workspace.rs | 64 ++- komorebi/tests/maximize_commands.rs | 2 +- komorebi/tests/wallpaper.rs | 517 ++++++++++++++++++++++ nix/komorebi-options.nix | 304 ++++++++----- nix/tests/vm/suites/wallpaper/default.nix | 9 + nix/tests/vm/suites/wallpaper/test.py | 259 +++++++++++ schema.json | 171 +++++++ 25 files changed, 1881 insertions(+), 135 deletions(-) create mode 100644 docs/usage/wallpapers.md create mode 100644 komorebi/src/kwin/wallpaper.rs create mode 100644 komorebi/tests/wallpaper.rs create mode 100644 nix/tests/vm/suites/wallpaper/default.nix create mode 100644 nix/tests/vm/suites/wallpaper/test.py diff --git a/README.md b/README.md index 6638a548..ffa7aaea 100644 --- a/README.md +++ b/README.md @@ -71,8 +71,9 @@ without a checkout of the toolchain. hides the back of a stack and the windows behind a monocle on, and the borders and animations it has KWin draw (`kwin`), the border and animation settings and the look they make (`border_manager`, `animation`), the colors a theme gives the - borders (`theme_manager`), the opacity of the windows that do not have the focus - (`transparency_manager`), + borders (`theme_manager`), the wallpapers of monitors and workspaces, which it has + the Plasma shell show (`kwin::wallpaper`), the opacity of the windows that do not + have the focus (`transparency_manager`), the model of what it tiles (`monitor`, `workspace`, `container`, `window`), the window manager that keeps the model (`window_manager`), loads it from the backend (`desktop`) and changes it when the compositor reports an event @@ -265,7 +266,9 @@ animated by another effect, Geometry Change, which `animation`, the windows that do not have the focus see-through, by the opacity KWin gives a window, and `focus-follows-mouse` has KWin give the focus to the window under the pointer, by its own focus policy. A theme gives the borders their colors, and -the palette of a picture is made and kept in the cache directory. +the palette of a picture is made and kept in the cache directory. A monitor or a workspace +can have a wallpaper, which the Plasma shell is asked to show when the workspace comes into view, +and which gives the borders the colors of its palette. ## Documentation diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 93070d08..2869dc27 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -19,6 +19,8 @@ grows with the code: each part of the daemon that is added has its place here. compositor's `u32` id. - **Monitor**: a connected output, with its bounds and its work area (its bounds minus the panels). +- **Wallpaper**: the picture a monitor shows while one of its workspaces is in front, and the theme + made of it. A workspace's own wins over its monitor's. - **Workspace**: the containers a monitor shows, in order, and the layout that tiles them. A monitor has a ring of workspaces and shows one of them. Workspace `i` is the compositor's desktop `i` on that monitor. A workspace can have a name, which the named @@ -842,6 +844,31 @@ name in another folder, has a palette of its own. A picture it cannot make a pal cannot be read, or has fewer than eight colors) has none, and the borders keep their colors. [DESIGN.md](DESIGN.md#why-is-a-palette-kept-by-the-hash-of-its-picture) has the reason. +## Wallpapers + +A [`Monitor`] has a [`Wallpaper`] and so can each of its workspaces: the `wallpaper` of an entry of +`monitors` and of `workspaces` in `komorebi.json`, which [`StaticConfig::postload`] and +[`StaticConfig::reload`] give them. [`Workspace::apply_wallpaper`] asks the backend to show the workspace's own wallpaper +or else its monitor's ([`Backend::set_wallpaper`]), and, unless the wallpaper says +`generate_theme: false`, makes a theme of the palette of the picture +([`theme_manager::wallpaper_palette`]), with the variant and the colors of its `theme_options`, and +hands it to [`theme_manager::send_notification`]: the colors are the borders' before the +workspace is shown. It is called wherever a workspace comes into view. [`Workspace::restore`], which +[`Monitor::load_focused_workspace`] calls for komorebi's own switches, calls it; +[`WindowManager::adopt_workspace_change`] calls it for a switch something else made, and +[`WindowManager::retile_all`] for the workspace in front at the start, and +[`WindowManager::apply_wallpaper_for_monitor_workspace`], which [`StaticConfig::reload`] calls for the +workspace each monitor shows, has a reloaded file's wallpapers shown at once. A monitor and a +workspace without a wallpaper are not asked about. + +Plasma has one wallpaper for each screen, which the shell, a process of its own, keeps. The KWin +backend does not set it from the thread of the window manager: [`Backend::set_wallpaper`] notes the +wish for the output (by name, which is how the shell tells screens apart) and starts a task on the +runtime, which asks the shell what the screen shows and sets the picture only if it differs, with +the plugin that shows a picture, filling the screen ([`kwin::wallpaper`]). A shell that is not +there yet is tried again for about half a minute, with longer waits, and the failure is said once. +[PLATFORM.md](PLATFORM.md#the-plasma-shell) has what the shell is asked. + ## Transparency The opacity of a window is a property KWin has, so komorebi sets it ([`Backend::set_opacity`], @@ -973,6 +1000,8 @@ module's unit. - [`animation`](../../komorebi/src/animation/mod.rs): the animation settings, which the look has. - [`theme_manager`](../../komorebi/src/theme_manager.rs): a theme's colors for the borders, and the palettes made from pictures. +- [`kwin::wallpaper`](../../komorebi/src/kwin/wallpaper.rs): the Plasma shell's side of a + wallpaper: the screen of an output, what it shows, and the picture set. - [`transparency_manager`](../../komorebi/src/transparency_manager.rs): which windows are see-through, and the opacity they are given. - [`kwin::effects`](../../komorebi/src/kwin/effects.rs): the KWin effect that draws the border, @@ -1129,6 +1158,12 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A theme gives every kind of border a color, the one it names or the theme's default | framework path: [`theme_manager::send_notification`] stores a color for each of the six kinds, from the theme's own defaults for the ones the message does not name | `a_named_theme_colours_every_kind_of_border` | none | | The `border_colours` of the file are the border colors, and a theme in the file wins over them | framework path: `StaticConfig::apply_globals` stores each color the file names, and then calls [`theme_manager::send_notification`] for the `theme` | `the_colour_and_theme_keys_of_the_file_are_the_border_colours` | none | | A picture's palette is made again when the picture changes, and is not mistaken for another picture's | framework path: [`theme_manager::palette_file`] names the file by a hash of the picture's path, size and time of last change, and the variant | the doctest of `palette_file` | the hash is not a proof of identity | +| A workspace that comes into view has its wallpaper set, its own before its monitor's, however it came into view; none is touched for a workspace and a monitor without one | framework path: [`Workspace::restore`], [`WindowManager::adopt_workspace_change`] and [`WindowManager::retile_all`] call [`Workspace::apply_wallpaper`], which takes `self.wallpaper` before the monitor's | `a_wallpaper_is_set_when_its_workspace_comes_into_view_by_whoever_brings_it`, `no_wallpaper_is_touched_that_was_not_asked_for`, `vm-wallpaper` (sections A and B) | none | +| The borders have the colors of the wallpaper in front, and keep theirs when it asks for no theme or has no palette | framework path: [`Workspace::apply_wallpaper`] sends a theme only for a wallpaper that does not say `generate_theme: false` and has a palette | `the_borders_take_their_colours_from_the_wallpaper_and_follow_it`, `a_wallpaper_that_asks_for_no_theme_leaves_the_borders_alone`, `a_wallpaper_that_is_not_a_picture_still_sets_and_does_not_break_the_window_manager`, `theme_options_choose_the_variant_and_the_colour_each_border_takes`, `vm-wallpaper` (section C) | none | +| A wallpaper the screen shows already is not set again, and one the user changed by hand is set back | framework path: [`kwin::wallpaper`]`::apply` compares what the shell answers with the picture, the fill and the plugin | `vm-wallpaper` (section D) | the comparison alone has no test | +| Any path is a URL the shell can read, and the name of an output cannot end the string it is in in the shell's script | framework path: `kwin::wallpaper::file_url` percent-encodes every byte but a few ASCII ones, and the script writes the name as a JSON string | `a_path_becomes_a_url_the_shell_can_read`, `the_name_of_an_output_cannot_end_the_string_it_is_in`, `vm-wallpaper` (a path with a space in it) | none | +| Setting a wallpaper never holds up the window manager | framework path: [`Backend::set_wallpaper`] of the KWin backend notes the wish and spawns the request on the runtime | none | the monitor and the path are checked before it returns | +| The KWin backend refuses a wallpaper for a monitor it does not have and for a path that is no file | framework path: `set_wallpaper` of the KWin backend looks the monitor up in its table and checks the path | `a_wallpaper_is_refused_for_a_monitor_kwin_lacks_and_for_a_path_that_is_no_file` | none | | A window komorebi made see-through is opaque again when komorebi exits | framework path: [`WindowManager::stop`] and `main.rs` call [`transparency_manager::restore`] | `what_komorebi_made_see_through_is_opaque_again_when_it_exits` | `SIGKILL`: the windows stay as they were drawn | | What the backend sends for an opacity is what the bridge sets | tests: the `opacity` command of [`fixtures`] is what the backend's test sends and what the bridge's test answers with, checking the window's `opacity` | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a window is given the opacity it is asked for, and one KWin has not got is given back` | none | | The user's focus policy is put back when focus follows mouse is turned off and when komorebi exits | framework path: [`Kwinrc`] records the first value of each key it sets, `set_focus_follows_mouse(false)` puts the two keys back with [`Kwinrc::restore_keys`] and `shutdown` puts back all | `one_key_can_be_put_back_while_the_others_in_its_group_stay_changed`, `what_komorebi_changed_is_put_back_exactly_and_what_it_added_is_removed`, `vm-focus-follows-mouse` | `SIGKILL`: the next run puts it back when it stops | @@ -1283,7 +1318,10 @@ A window is shown, and ends up on a tile: [`nix/tests/vm/suites/features`](../../nix/tests/vm/suites/features/test.py), the colors of the kinds of window; [`nix/tests/vm/suites/focus-follows-mouse`](../../nix/tests/vm/suites/focus-follows-mouse/test.py), focus follows mouse with a real pointer, which [`Pointer`](../../nix/tests/vm/lib/komorebi_vm/pointer.py) - moves from inside the guest. + moves from inside the guest; [`komorebi/tests/wallpaper.rs`](../../komorebi/tests/wallpaper.rs), the + wallpapers and the colors made of them, against the fake; and + [`nix/tests/vm/suites/wallpaper`](../../nix/tests/vm/suites/wallpaper/test.py), against the + real Plasma shell. - [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager driven end to end against the fake. - [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket, @@ -1373,6 +1411,11 @@ A window is shown, and ends up on a tile: [`theme_manager::CURRENT_THEME`]: ../../komorebi/src/theme_manager.rs [`theme_manager::wallpaper_palette`]: ../../komorebi/src/theme_manager.rs [`theme_manager::palette_file`]: ../../komorebi/src/theme_manager.rs +[`Wallpaper`]: ../../komorebi/src/static_config.rs +[`Workspace::apply_wallpaper`]: ../../komorebi/src/workspace.rs +[`Workspace::restore`]: ../../komorebi/src/workspace.rs +[`Backend::set_wallpaper`]: ../../komorebi/src/backend/mod.rs +[`kwin::wallpaper`]: ../../komorebi/src/kwin/wallpaper.rs [`komorebi_themes::generate_base16_palette`]: https://github.com/LGUG2Z/komorebi/tree/f08aa55511d77ca56ab0e789efabeb0a237a463e/komorebi-themes [`WindowManager::focus_follows_mouse`]: ../../komorebi/src/window_manager.rs [`Backend::set_focus_follows_mouse`]: ../../komorebi/src/backend/mod.rs @@ -1513,6 +1556,7 @@ A window is shown, and ends up on a tile: [`Monitor::load_focused_workspace`]: ../../komorebi/src/monitor.rs [`WindowManager::sync_workspace_desktops`]: ../../komorebi/src/window_manager.rs [`WindowManager::adopt_workspace_change`]: ../../komorebi/src/window_manager.rs +[`WindowManager::apply_wallpaper_for_monitor_workspace`]: ../../komorebi/src/window_manager.rs [`WindowManager::focus_workspace`]: ../../komorebi/src/window_manager.rs [`WindowManager::move_container_to_workspace`]: ../../komorebi/src/window_manager.rs [`WindowManager::monitor_workspace_index_by_name`]: ../../komorebi/src/window_manager.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index dd957777..06ccc62c 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -490,6 +490,36 @@ outlives a login; the runtime directory, where the socket is, does not. The file picture, a hash of its path, size and time of last change, and the variant. A palette that cannot be kept is made again the next time. komorebi for Windows keeps them by file name alone. +## Why does komorebi set the wallpaper when a workspace comes into view? + +Because Plasma keeps one wallpaper for each screen, not for each virtual desktop, and a +workspace is a virtual desktop. The shell shows what it was last told, whatever desktop is shown, +so komorebi tells it again as the workspace changes, as komorebi does on Windows and macOS. It does +so wherever a workspace comes into view (its own switches, a pager's, an application raising a +window of another workspace, and the start), since all of them change what the screen should show. +The picture fills the screen, as komorebi's wallpapers do on Windows. + +## Why does komorebi ask the shell what the screen shows before it sets a wallpaper? + +Because the workspace's wallpaper is asked for every time the workspace comes into view, and the +user may have changed the wallpaper by hand since: a wallpaper that is not the one komorebi wants +is put back, and one that already is, in the same plugin and fill mode, is not touched, so a +switch between two workspaces with the same picture changes nothing on the screen. + +## Why is the wallpaper set in the background, and tried again? + +Because the shell is another process, which may be slow, and may still be starting when komorebi is +(a session that has just logged in). Switching workspaces never waits for it: the backend notes the +wish for the output and a task on the runtime does the asking, so the request that runs last finds +the newest wish. A shell that is not there is asked again for about half a minute, with longer +waits, and then komorebi says once that it leaves wallpapers alone until the shell answers. + +## Why does a wallpaper hand its theme to the borders by a call, and not by a message? + +Because on Windows the theme of a wallpaper is sent to komorebi's own socket, and a message to +itself does nothing a call does not do. The call is made before the workspace is shown, so the +colors are the borders' by the time the first window of the workspace is given one. + ## Why are the effects patched? Because the stock effects lack what komorebi needs of them. Each patch leaves the effect diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 14fdfd16..8709ef5f 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -233,6 +233,7 @@ What komorebi calls: | `org.kde.KWin` | `/org/komorebi/BorderColours` | `org.komorebi.BorderColours1` | `SetColours(asau)`: the UUID of each window and its color, `0xRRGGBB` | when the color of a window's border changes; the object is komorebi's build of the border effect ([The patches](#the-patches)) | | `org.kde.KWin` | `/KWin` | `org.kde.KWin` | `reconfigure()` | after komorebi changed `kwinrc`, at start and at exit | | `org.kde.KWin` | `/VirtualDesktopManager` | `org.kde.KWin.VirtualDesktopManager` | the properties `desktops` and `count`, `createDesktop(us)`, `setDesktopName(ss)`, `removeDesktop(s)` | when a workspace has no desktop, and at start; `createDesktop` also for the parking desktop, the first time a window is hidden, and `removeDesktop` for it when komorebi stops and for one a killed run left | +| `org.kde.plasmashell` | `/PlasmaShell` | `org.kde.PlasmaShell` | `evaluateScript(s) -> s`, `wallpaper(u) -> a{sv}`, `setWallpaper(sa{sv}u)` | when a workspace with a wallpaper comes into view ([The Plasma shell](#the-plasma-shell)) | The property `desktops` is introspected as `a(iss)`, a position, an id and a name for each desktop, and the value on the wire is `a(uss)`: komorebi reads it as that. It is read uncached, @@ -252,6 +253,7 @@ since a read right after `createDesktop` has to see the new desktop. | `$XDG_RUNTIME_DIR/komorebi/bridge.js` | the script KWin loads, with its configuration (the D-Bus names and the hold time of `Poll`) on its first line | written at every start; the directory is removed at logout | | `$XDG_RUNTIME_DIR/komorebi/komorebi.sock` | the command socket | bound once the daemon is connected to KWin, after a file left there is removed; removed when the daemon stops | | `$XDG_RUNTIME_DIR/komorebi/NAME` | the socket of a subscriber, which the subscriber binds and names in its subscription | removed by the daemon, with the subscriber, when it cannot connect to it | +| `$XDG_CACHE_HOME/komorebi` (`~/.cache/komorebi`) | the palettes made from wallpapers, a file for each picture and variant, `NAME-HASH.base16.VARIANT.json` | never removed by komorebi; made again when the picture's path, size or time of last change differ | | `$XDG_DATA_HOME/komorebi/komorebi.log.YYYY-MM-DD` | the daemon's log, with colors, which `komorebic log` follows | a file a day (the UTC date), never removed by komorebi | | `$XDG_DATA_HOME/komorebi/komorebi_plaintext.log.YYYY-MM-DD` | the same log without colors | as above | @@ -546,6 +548,29 @@ seconds, and the effect eases out exponentially, nearly over after a third of it screenshot of a session a few seconds into a 30 s animation shows a window that has not got to its place, and the same move with animation off is there at once. +## The Plasma shell + +The wallpaper of a screen is the Plasma shell's, not KWin's: the shell, `plasmashell` on the +session bus as `org.kde.plasmashell`, keeps one wallpaper for each screen, not for each virtual +desktop. At time of writing (2026-10-27) komorebi asks it three things over `/PlasmaShell`, in +`org.kde.PlasmaShell`, for the output a workspace's monitor is (the name KWin gives it, `DP-1`): + +1. `evaluateScript("print(screenForConnector(\"DP-1\"))")`: the number the shell gives the + screen, which it numbers itself and names by connector; `-1` when it has none. The name goes + into the script as a JSON string. +2. `wallpaper(screen)`: what the screen shows, as `a{sv}`, in which `wallpaperPlugin` is the + plugin (`org.kde.image` for a picture), `Image` the picture's URL and `FillMode` a Qt + `Image.fillMode` (2 is `PreserveAspectCrop`: the picture fills the screen and is cropped where it + does not fit). +3. `setWallpaper("org.kde.image", {Image: URL, FillMode: 2}, screen)`: what + `plasma-apply-wallpaperimage` calls, for one screen. It is made only when the answer to 2 is + not already the picture, in that plugin, with that fill. + +The URL is `file://` and the path, with every byte but an ASCII letter or digit, `-`, `.`, `_`, `~` +and `/` percent-encoded, so a path with a space in it works. A session with no Plasma shell (a +headless one, or one with another shell) has no such name on the bus: every call fails, and komorebi +tries again, then leaves wallpapers alone ([DESIGN.md](DESIGN.md#why-is-the-wallpaper-set-in-the-background-and-tried-again)). + ## Rendering in virtual machines and over RDP At time of writing (2026-10-27): diff --git a/docs/index.md b/docs/index.md index 284a0548..6542999d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -63,8 +63,9 @@ configuration of a running daemon. [Animation](usage/animation.md) how it has KWin animate the windows going to their places, and [Transparency](usage/transparency.md) how it makes the windows that do not have the focus see-through, [Focus follows mouse](usage/focus-follows-mouse.md) how it has KWin give the focus -to the window under the pointer, and [Themes](usage/themes.md) how a theme gives the borders their -colors. +to the window under the pointer, [Themes](usage/themes.md) how a theme gives the borders their +colors, and [Wallpapers](usage/wallpapers.md) how a monitor or a workspace shows a picture of its own, +and what it does to the borders. [Subscribing to notifications](usage/subscribing-to-notifications.md) explains how a program such as a status bar follows what komorebi does. The [CLI reference](cli/start.md) has a page for every `komorebic` command, generated from its help. diff --git a/docs/usage/configuration.md b/docs/usage/configuration.md index 0e9a51ae..755ab493 100644 --- a/docs/usage/configuration.md +++ b/docs/usage/configuration.md @@ -41,8 +41,8 @@ These stay as they were when the file leaves them out: `default_workspace_paddin `default_container_padding`, `display_index_preferences`, the four settings of the borders, each color of `border_colours` the file does not name, the theme and the animation, when the file has no `animation`. The rules add up, as -[Rules](#rules) says. A workspace the file lists gets its name, padding, offsets and rules from -its entry, and its layout when the entry names one; a workspace the file does not list is left as +[Rules](#rules) says. A workspace the file lists gets its name, padding, offsets, rules and +wallpaper from its entry, and its layout when the entry names one; a workspace the file does not list is left as it is. [`komorebic generate-static-config`](../cli/generate-static-config.md) prints the settings the @@ -165,7 +165,9 @@ A monitor that has no preference takes the first entry nobody's preference names other monitor has taken. A monitor entry can also have a `floating_layer_behaviour`, which is the one its workspaces take -unless they have their own, and which comes before the one for every monitor. +unless they have their own, and which comes before the one for every monitor, and a `wallpaper`, +the picture the monitor shows while one of its workspaces is in front, unless that workspace has +one of its own ([Wallpapers](wallpapers.md)). A monitor takes as many workspaces as its entry lists, and KWin gets a virtual desktop for each, named for it. A workspace has these keys: @@ -189,6 +191,7 @@ named for it. A workspace has these keys: | `window_container_behaviour_rules` | none | `{ "2": "Append" }`: the behavior the workspace has once it has 2 containers or more | | `float_override` | the default | Whether every window that opens on this workspace floats | | `floating_layer_behaviour` | the default | What a window that opens while this workspace is on its floating layer gets: `Tile` or `Float` | +| `wallpaper` | none | The picture the monitor shows while this workspace is in front, instead of its monitor's: `{ "path": "~/Pictures/sea.png" }`, and `generate_theme` and `theme_options` for the borders' colors ([Wallpapers](wallpapers.md)) | A workspace that names no `layout` and does not say `"tile": true` does not tile: its windows stay where they open. A workspace with `layout_rules` tiles. Otherwise a workspace tiles. diff --git a/docs/usage/wallpapers.md b/docs/usage/wallpapers.md new file mode 100644 index 00000000..5a003b63 --- /dev/null +++ b/docs/usage/wallpapers.md @@ -0,0 +1,70 @@ +# Wallpapers + +A monitor, or a workspace of it, can have a wallpaper: the picture the monitor shows while that +workspace is in front. A workspace's own wallpaper is shown instead of its monitor's, and a +workspace that has none shows its monitor's. komorebi sets the wallpaper when a workspace comes +into view, however it comes: a [`komorebic`](../cli/focus-workspace.md) command, or a pager, a +shortcut, or an application raising a window of another workspace. It sets it when it starts too, +for the workspace that is in front. A monitor and a workspace with no wallpaper are left alone. + +Plasma keeps one wallpaper for each screen, not for each virtual desktop, so komorebi changes the +screen's wallpaper as its workspace changes, as komorebi does on Windows and macOS. + +## Setting wallpapers + +The wallpapers are in `komorebi.json` ([Configuration](configuration.md)): a `wallpaper` in the +entry of a monitor and one in the entry of a workspace. The first entry of `monitors` is the first +monitor, and so on; the entries of `workspaces` are the workspaces of that monitor, in order. A +file that is read again, because it changed, shows the new wallpaper of the workspace in front at +once. + +```json +{ + "monitors": [ + { + "wallpaper": { "path": "~/Pictures/dunes.png" }, + "workspaces": [ + { "name": "code" }, + { "name": "chat", + "wallpaper": { "path": "~/Pictures/sea.png", + "theme_options": { "theme_variant": "Light", "single_border": "Base09" } } } + ] + } + ] +} +``` + +A `path` may start with `~` or have environment variables in it (`$HOME`), and may have spaces in +it. The picture fills the screen and is cropped where it does not fit. The monitor has the +`dunes.png` of the example, and the second workspace has `sea.png`. + +A request for a wallpaper never holds up komorebi: switching workspaces does not wait for the +Plasma shell. The shell is asked what the screen shows before it is told anything, so a wallpaper +you changed by hand is put back when its workspace is shown again, and a wallpaper that is already +right is not touched. + +## The colors of the borders + +A wallpaper also gives the borders their colors, unless it says `"generate_theme": false`. The +palette of the picture, made by the generator komorebi for Windows uses, is a Base16 theme, so the +borders of a workspace with a warm picture are warm and those of a workspace with a cool picture +are cool ([Themes](themes.md) has what the six kinds of border take by default). They change with +the workspace, so the colors are right when the workspace comes into view. + +`theme_options` choose the variant of the palette, `"theme_variant": "Dark"` (the default) or +`"Light"`, and which color of the palette each kind of border takes, `single_border`, +`stack_border`, `monocle_border`, `floating_border`, `unfocused_border` and +`unfocused_locked_border`, each one of `Base00` to `Base0F`. `bar_accent` is read and not used: +there is no komorebi bar here. + +A palette takes seconds to make for a large picture, so each one is kept in +`$XDG_CACHE_HOME/komorebi` (`~/.cache/komorebi`), in a file named for the picture, a hash of its +path, size and time of last change, and the variant. A picture with fewer than eight colors has no +palette: its wallpaper is set, and the borders keep the colors they had. + +## When the Plasma shell is not there + +The shell is another process, and komorebi may start before it does. komorebi asks again for about +half a minute, with longer waits between the tries, and then says once, in its log, that it is +leaving wallpapers alone until the shell answers. A session with no Plasma shell has no wallpapers +to set, and nothing else in komorebi is affected. diff --git a/flake.nix b/flake.nix index ad5ef4c1..1fea2fec 100644 --- a/flake.nix +++ b/flake.nix @@ -52,7 +52,9 @@ || (pkgs.lib.hasSuffix ".json" path) # the page of the docs that shows the example configuration, which a test compares # with the example file - || (pkgs.lib.hasSuffix "docs/example-configurations.md" path); + || (pkgs.lib.hasSuffix "docs/example-configurations.md" path) + # the example a test loads, to see that the docs show one that works + || (pkgs.lib.hasSuffix "docs/usage/wallpapers.md" path); }; commonArgs = { diff --git a/komorebi/src/backend/fake.rs b/komorebi/src/backend/fake.rs index 95f99aab..a0edd408 100644 --- a/komorebi/src/backend/fake.rs +++ b/komorebi/src/backend/fake.rs @@ -35,6 +35,8 @@ use crate::core::Rect; use color_eyre::eyre; use parking_lot::Mutex; use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; /// A command the window manager sent to the backend. #[derive(Clone, Debug, PartialEq)] @@ -74,6 +76,8 @@ pub enum Command { SetOpacity(u32, u8), /// [`Backend::set_focus_follows_mouse`]: whether it was turned on or off. FocusFollowsMouse(bool), + /// [`Backend::set_wallpaper`]: the monitor, and the picture it was asked to show. + SetWallpaper(u32, PathBuf), } #[derive(Default)] @@ -101,6 +105,8 @@ struct State { opacity: HashMap, /// the border color each window was last given, `0xRRGGBB` border_colours: HashMap, + /// the wallpaper the WM last asked for on each monitor + wallpapers: HashMap, /// the look last applied, so that asking for it again is not a command last_look: Option, /// whether the compositor has an effect that draws borders @@ -386,6 +392,11 @@ impl FakeBackend { self.state.lock().border_colours.get(&id).copied() } + /// Returns the wallpaper the window manager last asked this monitor to show, if it asked. + pub fn wallpaper_of(&self, monitor_id: u32) -> Option { + self.state.lock().wallpapers.get(&monitor_id).cloned() + } + /// Says whether the compositor has an effect that draws borders. Without one, which is how a /// fake starts, [`Backend::apply_look`] answers false however much of a border it is asked /// for, as it does on a machine where the effect is not installed. @@ -624,6 +635,15 @@ impl Backend for FakeBackend { Ok(()) } + fn set_wallpaper(&self, monitor_id: u32, path: &Path) -> eyre::Result<()> { + let mut state = self.state.lock(); + state.wallpapers.insert(monitor_id, path.to_path_buf()); + state + .commands + .push(Command::SetWallpaper(monitor_id, path.to_path_buf())); + Ok(()) + } + fn set_opacity(&self, id: u32, alpha: u8) -> eyre::Result<()> { self.record(id, Command::SetOpacity(id, alpha), |state| { state.opacity.insert(id, alpha); diff --git a/komorebi/src/backend/mod.rs b/komorebi/src/backend/mod.rs index 5ad5d595..4a50d29e 100644 --- a/komorebi/src/backend/mod.rs +++ b/komorebi/src/backend/mod.rs @@ -44,7 +44,8 @@ //! sees that it is drawn ([`Backend::apply_look`]); the window manager is told whether the //! compositor draws a border, because a border that is drawn takes room around each window, which //! the layout leaves. The color of each window's border is another request -//! ([`Backend::set_border_colours`]), which a compositor may not be able to honor. +//! ([`Backend::set_border_colours`]), which a compositor may not be able to honor. The wallpaper +//! of a monitor is a request of the same kind ([`Backend::set_wallpaper`]). #![deny(missing_docs)] @@ -52,6 +53,7 @@ use crate::core::Rect; use color_eyre::eyre; use parking_lot::RwLock; use std::cell::RefCell; +use std::path::Path; use std::sync::Arc; pub mod fake; @@ -491,6 +493,39 @@ pub trait Backend: Send + Sync + 'static { Ok(()) } + /// Shows this picture as the wallpaper of a monitor, filling the screen. The window manager + /// asks for it every time a workspace of the monitor comes into view, since the user may have + /// changed the wallpaper by hand since, so a backend does nothing when the monitor already + /// shows the picture. The picture may take a moment to appear: this returns once it has been + /// asked for. The default does nothing. + /// + /// # Errors + /// + /// When the monitor is not one the compositor has, or the path is not a file. + /// + /// # Example + /// + /// ```rust + /// use komorebi::backend::Backend; + /// use komorebi::backend::fake::Command; + /// use komorebi::backend::fake::FakeBackend; + /// use std::path::Path; + /// + /// let fake = FakeBackend::with_one_monitor(); + /// assert_eq!(fake.wallpaper_of(1), None); + /// + /// fake.set_wallpaper(1, Path::new("/pictures/dunes.png"))?; + /// assert_eq!(fake.wallpaper_of(1), Some("/pictures/dunes.png".into())); + /// assert_eq!( + /// fake.commands(), + /// [Command::SetWallpaper(1, "/pictures/dunes.png".into())] + /// ); + /// # Ok::<(), color_eyre::eyre::Report>(()) + /// ``` + fn set_wallpaper(&self, _monitor_id: u32, _path: &Path) -> eyre::Result<()> { + Ok(()) + } + // ---- provided ------------------------------------------------------------------------------ /// Called once as komorebi exits, after the window manager has put back what it moved, so that diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index 2f1b941f..6a3bf91b 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -58,6 +58,11 @@ //! (`nix/kde-rounded-corners.nix`) also takes a color for each window, which the backend gives it //! by KWin's UUID of the window ([`Backend::set_border_colours`]). //! +//! Wallpapers are not KWin's: the Plasma shell, another process, keeps them, one for each screen +//! and not for each desktop. The backend asks the shell over D-Bus to show a monitor's wallpaper +//! ([`Backend::set_wallpaper`]), without holding up the window manager, and tries again for a +//! while when the shell is not there yet. +//! //! `docs/dev/PLATFORM.md` has the D-Bus names, the files and the environment variables involved, //! and `docs/dev/DESIGN.md` the reasons for this design. @@ -66,6 +71,7 @@ mod effects; mod kwinrc; pub mod state; +mod wallpaper; use crate::DATA_DIR; use crate::backend::Backend; @@ -139,6 +145,13 @@ struct Shared { kwinrc: Option, /// what komorebi has told the border effect, and has to undo when it exits effects: tokio::sync::Mutex, + /// the wallpaper last asked for on each output (by name), which is what the shell is made to + /// show whenever it gets round to it + wallpapers: Mutex>, + /// one request to the Plasma shell at a time, so that the last one asked for is the last done + wallpaper_turn: tokio::sync::Mutex<()>, + /// whether a failure to set a wallpaper has been said (it is said once) + wallpaper_failed: AtomicBool, } impl Shared { @@ -342,6 +355,9 @@ pub fn connect() -> eyre::Result> { connection: Mutex::new(None), kwinrc: kwinrc::Kwinrc::user(&DATA_DIR), effects: tokio::sync::Mutex::new(effects::EffectsState::default()), + wallpapers: Mutex::new(HashMap::new()), + wallpaper_turn: tokio::sync::Mutex::new(()), + wallpaper_failed: AtomicBool::new(false), }); let (started_tx, started_rx) = std::sync::mpsc::channel::>(); @@ -567,6 +583,56 @@ fn sweep_stale_park(shared: &Arc) { }); } +/// Have the Plasma shell show the wallpaper wanted on an output. If the shell is not there (yet), +/// try again for a while: komorebi may well have started before it. +async fn keep_wallpaper(shared: Arc, output: String) { + // once the shell has been found missing it is not waited for again on every request + let attempts = if shared.wallpaper_failed.load(Ordering::SeqCst) { + 1 + } else { + 8 + }; + let mut wait = Duration::from_millis(500); + + for attempt in 1..=attempts { + let Some(wanted) = shared.wallpapers.lock().get(&output).cloned() else { + return; + }; + + let result = { + let _turn = shared.wallpaper_turn.lock().await; + match shared.connection().await { + Ok(connection) => wallpaper::apply(&connection, &output, &wanted).await, + Err(error) => Err(error), + } + }; + + match result { + Ok(changed) => { + if changed { + tracing::info!("the wallpaper of {output} is {}", wanted.display()); + } + shared.wallpaper_failed.store(false, Ordering::SeqCst); + return; + } + Err(error) if attempt == attempts => { + if !shared.wallpaper_failed.swap(true, Ordering::SeqCst) { + tracing::warn!( + "gave up setting the wallpaper of {output} ({error}): is the Plasma shell \ + running? Wallpapers are left alone until it answers" + ); + } + return; + } + Err(error) => { + tracing::debug!("could not set the wallpaper of {output} yet: {error}"); + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(8)); + } + } + } +} + async fn desktop_manager(shared: &Shared) -> eyre::Result> { let connection = shared.connection().await?; // uncached: a property read right after createDesktop must not return the list from before it @@ -935,6 +1001,42 @@ impl Backend for KWinBackend { })? } + fn set_wallpaper(&self, monitor_id: u32, path: &std::path::Path) -> eyre::Result<()> { + if !self.shared.alive.load(Ordering::SeqCst) { + eyre::bail!("KWin is gone"); + } + + let output = self + .shared + .table + .lock() + .monitors() + .into_iter() + .find(|m| m.id == monitor_id) + .map(|m| m.name) + .ok_or_eyre("there is no such monitor")?; + + if !path.is_file() { + eyre::bail!("{} is not a file", path.display()); + } + + self.shared + .wallpapers + .lock() + .insert(output.clone(), path.to_path_buf()); + + // Plasma's shell is another process, and may be slow, or still starting: do not hold up + // the window manager for it. The request that runs last finds the newest wish. (Asked + // for every time a workspace comes into view, because the user may have changed the + // wallpaper by hand since: the shell is asked what it shows, and only told if it differs.) + let shared = self.shared.clone(); + self.shared + .handle + .spawn(async move { keep_wallpaper(shared, output).await }); + + Ok(()) + } + fn set_border_colours(&self, colours: &[(u32, u32)]) -> eyre::Result { let shared = self.shared.clone(); @@ -1045,6 +1147,9 @@ mod tests { connection: Mutex::new(None), kwinrc: None, effects: tokio::sync::Mutex::new(effects::EffectsState::default()), + wallpapers: Mutex::new(HashMap::new()), + wallpaper_turn: tokio::sync::Mutex::new(()), + wallpaper_failed: AtomicBool::new(false), }); (runtime, KWinBackend { shared }) @@ -1180,6 +1285,28 @@ mod tests { assert_eq!(next_poll(&runtime, &backend), json!([])); } + #[test] + fn a_wallpaper_is_refused_for_a_monitor_kwin_lacks_and_for_a_path_that_is_no_file() { + let (_runtime, backend) = offline(); + + // no snapshot yet: there is no monitor + let nowhere = backend.set_wallpaper(1, std::path::Path::new("/nonexistent/a.png")); + assert!(nowhere.unwrap_err().to_string().contains("no such monitor")); + + let events: Vec = + serde_json::from_str(include_str!("fixtures/events.json")).unwrap(); + backend + .shared + .table + .lock() + .handle(&events[0], Instant::now()); + let monitor = backend.monitors().unwrap()[0].id; + + let missing = backend.set_wallpaper(monitor, std::path::Path::new("/nonexistent/a.png")); + assert!(missing.unwrap_err().to_string().contains("is not a file")); + assert!(backend.shared.wallpapers.lock().is_empty()); + } + /// zbus does not end a held call when its caller leaves the bus, so the `Poll` of the bridge of /// a KWin that has gone is still waiting when the next bridge calls. Were it given the /// commands, they would be answered to nobody and lost. diff --git a/komorebi/src/kwin/wallpaper.rs b/komorebi/src/kwin/wallpaper.rs new file mode 100644 index 00000000..0c88d8f4 --- /dev/null +++ b/komorebi/src/kwin/wallpaper.rs @@ -0,0 +1,155 @@ +//! The wallpaper of a monitor, set through the Plasma shell. +//! +//! Plasma keeps one wallpaper for each screen, not for each virtual desktop, so komorebi sets a +//! monitor's wallpaper whenever one of its workspaces comes into view: the workspace's wallpaper, +//! else the monitor's, when there is one. The Plasma shell, a separate process, sets it over D-Bus +//! with `org.kde.PlasmaShell.setWallpaper`: the call `plasma-apply-wallpaperimage` makes, but for +//! one screen instead of all of them. [`apply`] finds the shell's screen for an output, asks what +//! it shows, and changes it only when it shows something else. +//! +//! The shell may not be running (a headless session, a session that has not finished starting, or +//! another shell). [`apply`] then fails, and the KWin backend tries again for about half a minute +//! before it leaves the wallpaper alone and logs that once. +//! +//! # What is guaranteed, and by what +//! +//! | Rule | Enforced by | Proof | +//! |---|---|---| +//! | The name of an output cannot end the string it is in, in the script sent to the shell | [`screen_script`] writes it as a JSON string | `kwin::wallpaper::tests::the_name_of_an_output_cannot_end_the_string_it_is_in` | +//! | Any path is a URL the shell can read | [`file_url`] percent-encodes every byte but ASCII letters, digits and `-._~/` | `kwin::wallpaper::tests::a_path_becomes_a_url_the_shell_can_read` | +//! | A wallpaper the screen already shows is not set again, and one the user changed by hand is set back | [`apply`] compares with what the shell answers | the second half: the `vm-wallpaper` VM suite; the first: no test | + +#![deny(missing_docs)] + +use color_eyre::eyre; +use std::collections::HashMap; +use std::path::Path; +use zbus::Connection; +use zbus::proxy::Proxy; +use zbus::zvariant::OwnedValue; +use zbus::zvariant::Value; + +/// The Plasma shell's name on the session bus. +const SHELL: &str = "org.kde.plasmashell"; +/// The object of the shell that sets wallpapers. +const PATH: &str = "/PlasmaShell"; +/// The interface of [`PATH`]. +const INTERFACE: &str = "org.kde.PlasmaShell"; + +/// The wallpaper plugin that shows a picture. +const PLUGIN: &str = "org.kde.image"; + +/// Qt's `Image.PreserveAspectCrop`: the picture fills the screen and is cropped where it does not +/// fit, as komorebi's wallpapers do on Windows (`DWPOS_FILL`). +const FILL_MODE: i32 = 2; + +/// Returns the `file://` URL of a path, which is how Plasma keeps the picture. +/// +/// Every byte of the path other than an ASCII letter or digit, `-`, `.`, `_`, `~` and `/` is +/// percent-encoded, so `/a/b c.png` is `file:///a/b%20c.png`. Covered by +/// `kwin::wallpaper::tests::a_path_becomes_a_url_the_shell_can_read`. +pub fn file_url(path: &Path) -> String { + use std::os::unix::ffi::OsStrExt; + + let mut url = String::from("file://"); + for &byte in path.as_os_str().as_bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => { + url.push(byte as char); + } + _ => url.push_str(&format!("%{byte:02X}")), + } + } + url +} + +/// Returns the Plasma shell script, for `evaluateScript`, that prints the number the shell gives an +/// output (`-1` for none). +/// +/// The shell numbers its screens itself, and identifies them by the connector's name, which is the +/// name KWin gives the output. +fn screen_script(output: &str) -> String { + let name = serde_json::to_string(output).unwrap_or_else(|_| "\"\"".into()); + format!("print(screenForConnector({name}))") +} + +/// Returns true if and only if the shell's answer about a screen's wallpaper is the picture at +/// `url`, shown by [`PLUGIN`] with [`FILL_MODE`]. +fn shows(current: &HashMap, url: &str) -> bool { + let text = |key: &str| { + current + .get(key) + .and_then(|v| String::try_from(v.try_clone().ok()?).ok()) + }; + let fill = current + .get("FillMode") + .and_then(|v| i32::try_from(v.try_clone().ok()?).ok()); + + text("wallpaperPlugin").as_deref() == Some(PLUGIN) + && text("Image").as_deref() == Some(url) + && fill == Some(FILL_MODE) +} + +/// Makes `path` the wallpaper of the output with this name, unless it already is, and returns true +/// if and only if it changed the wallpaper. +/// +/// # Errors +/// +/// Returns an error when a call to the shell fails (it is not on the bus, for one), when its answer +/// for the screen of the output is not a number, and when it has no screen for the output. +pub async fn apply(connection: &Connection, output: &str, path: &Path) -> eyre::Result { + let proxy = Proxy::new(connection, SHELL, PATH, INTERFACE).await?; + + let answer: String = proxy + .call("evaluateScript", &(screen_script(output),)) + .await?; + let screen: i64 = answer.trim().parse().map_err(|_| { + eyre::Report::msg(format!( + "the Plasma shell answered {answer:?} for the screen of {output}" + )) + })?; + let Ok(screen) = u32::try_from(screen) else { + eyre::bail!("the Plasma shell has no screen for {output}"); + }; + + let url = file_url(path); + let current: HashMap = proxy.call("wallpaper", &(screen,)).await?; + if shows(¤t, &url) { + return Ok(false); + } + + let mut parameters: HashMap<&str, Value<'_>> = HashMap::new(); + parameters.insert("Image", Value::from(url)); + parameters.insert("FillMode", Value::from(FILL_MODE)); + proxy + .call_method("setWallpaper", &(PLUGIN, parameters, screen)) + .await?; + + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_path_becomes_a_url_the_shell_can_read() { + assert_eq!(file_url(Path::new("/tmp/a.png")), "file:///tmp/a.png"); + assert_eq!( + file_url(Path::new("/home/me/My Pictures/sea & sky.png")), + "file:///home/me/My%20Pictures/sea%20%26%20sky.png" + ); + // not ASCII: each byte of the UTF-8 is escaped + assert_eq!(file_url(Path::new("/tmp/é.png")), "file:///tmp/%C3%A9.png"); + } + + #[test] + fn the_name_of_an_output_cannot_end_the_string_it_is_in() { + assert_eq!( + screen_script("DP-1"), + r#"print(screenForConnector("DP-1"))"# + ); + let hostile = screen_script(r#"x"); evil("#); + assert_eq!(hostile, r#"print(screenForConnector("x\"); evil("))"#); + } +} diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index bc50d3c1..ab9cae26 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -13,8 +13,11 @@ //! //! On KDE Plasma the backend is [`kwin::KWinBackend`], which talks to a script it loads into KWin. //! The compositor also draws what the windows look like: [`border_manager`] asks the backend for -//! the borders, [`theme_manager`] colors them from a theme, [`animation`] holds how windows are animated going to their places, and -//! [`transparency_manager`] makes the windows that do not have the focus see-through. +//! the borders, [`theme_manager`] colors them from a theme, [`animation`] holds how windows are +//! animated going to their places, and [`transparency_manager`] makes the windows that do not have +//! the focus see-through. A monitor or a workspace can also have a wallpaper +//! ([`static_config::Wallpaper`]), which the backend has the Plasma shell show when the +//! workspace comes into view ([`backend::Backend::set_wallpaper`]). //! //! The daemon also listens on a socket, `komorebi.sock` in [`struct@DATA_DIR`], for the messages //! in [`core::SocketMessage`]: [`process_command`] reads them and answers, with the window diff --git a/komorebi/src/monitor.rs b/komorebi/src/monitor.rs index d2e1484b..281ebc29 100644 --- a/komorebi/src/monitor.rs +++ b/komorebi/src/monitor.rs @@ -24,6 +24,7 @@ use crate::core::Layout; use crate::core::OperationDirection; use crate::core::Rect; use crate::ring::Ring; +use crate::static_config::Wallpaper; use crate::workspace::Workspace; use crate::workspace::WorkspaceGlobals; use crate::workspace::WorkspaceLayer; @@ -75,6 +76,8 @@ pub struct Monitor { /// shows again #[serde(skip_serializing_if = "Option::is_none")] pub last_focused_workspace: Option, + /// The wallpaper this monitor shows, unless the workspace in front has one of its own + pub wallpaper: Option, /// Whether a window that opens on a workspace on its floating layer floats, for the /// workspaces of this monitor that have no behaviour of their own pub floating_layer_behaviour: Option, @@ -105,6 +108,7 @@ pub fn new( last_focused_workspace: None, container_padding: None, workspace_padding: None, + wallpaper: None, floating_layer_behaviour: None, } } @@ -134,6 +138,7 @@ impl Monitor { container_padding: None, workspace_padding: None, last_focused_workspace: None, + wallpaper: None, floating_layer_behaviour: None, } } @@ -155,6 +160,7 @@ impl Monitor { last_focused_workspace: None, container_padding: None, workspace_padding: None, + wallpaper: None, floating_layer_behaviour: None, } } @@ -241,6 +247,7 @@ impl Monitor { pub fn load_focused_workspace(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> { let focused_idx = self.focused_workspace_idx(); let monitor_id = self.id; + let monitor_wp = self.wallpaper.clone(); // a window moved to this workspace has to be on its desktop before the desktop is shown // and a window of it focused, or focusing it would take the monitor back to the desktop it @@ -252,7 +259,7 @@ impl Monitor { } if let Some(workspace) = self.workspaces_mut().get_mut(focused_idx) { - workspace.restore(mouse_follows_focus)?; + workspace.restore(mouse_follows_focus, monitor_id, &monitor_wp)?; } Ok(()) diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 990457ce..632a58ec 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -35,8 +35,8 @@ //! - **WorkspaceChange**: a monitor shows another workspace, because something other than komorebi //! switched it (a pager, a shortcut, an app raising a window of another desktop). The window //! manager follows ([`WindowManager::adopt_workspace_change`]) and asks the compositor for -//! nothing: it has already shown the windows and chosen which to focus. komorebi's own switch -//! comes back as one too, and changes nothing. +//! nothing but the wallpaper of the workspace: it has already shown the windows and chosen which +//! to focus. komorebi's own switch comes back as one too, and changes nothing. //! - **WorkspaceMove**: a window was put on the desktop of another workspace by something other //! than komorebi. It moves to that workspace, and whichever of the two is in front is tiled //! again. @@ -144,7 +144,7 @@ impl WindowManager { if let WindowManagerEvent::WorkspaceChange(_, monitor_id, idx) = event { let result = self.adopt_workspace_change(monitor_id, idx); - // other windows are in view + // the workspace may have a wallpaper, and so a theme, and other windows are in view border_manager::send_notification(); border_manager::update_colours(self); transparency_manager::apply(self); diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 72fc5695..fe19bff7 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -219,6 +219,7 @@ impl From<&WindowManager> for State { layer: workspace.layer, floating_layer_behaviour: workspace.floating_layer_behaviour, globals: workspace.globals, + wallpaper: workspace.wallpaper.clone(), workspace_config: None, preselected_container_idx: None, promotion_swap_container_idx: None, @@ -231,6 +232,7 @@ impl From<&WindowManager> for State { // workspace_names: monitor.workspace_names.clone(), container_padding: monitor.container_padding, workspace_padding: monitor.workspace_padding, + wallpaper: monitor.wallpaper.clone(), floating_layer_behaviour: monitor.floating_layer_behaviour, }) .collect::>(); diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index 024c3f9f..d5a6aba9 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -127,6 +127,70 @@ pub struct BorderColours { pub unfocused_locked: Option, } +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Theme options +pub struct ThemeOptions { + /// Specify Light or Dark variant for theme generation + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::ThemeVariant::Dark)))] + pub theme_variant: Option, + /// Border color when the container contains a single window + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] + pub single_border: Option, + /// Border color when the container contains multiple windows + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0B)))] + pub stack_border: Option, + /// Border color when the container is in monocle mode + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0F)))] + pub monocle_border: Option, + /// Border color when the window is floating + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base09)))] + pub floating_border: Option, + /// Border color when the container is unfocused + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base01)))] + pub unfocused_border: Option, + /// Border color when the container is unfocused and locked + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base08)))] + pub unfocused_locked_border: Option, + // /// Stackbar focused tab text colour (default: Base0B) + // #[serde(skip_serializing_if = "Option::is_none")] + // pub stackbar_focused_text: Option, + // /// Stackbar unfocused tab text colour (default: Base05) + // #[serde(skip_serializing_if = "Option::is_none")] + // pub stackbar_unfocused_text: Option, + // /// Stackbar tab background colour (default: Base01) + // #[serde(skip_serializing_if = "Option::is_none")] + // pub stackbar_background: Option, + /// Komorebi status bar accent + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = komorebi_themes::Base16Value::Base0D)))] + pub bar_accent: Option, +} + +#[serde_with::serde_as] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +/// Wallpaper configuration +pub struct Wallpaper { + /// Path to the wallpaper image file + #[serde_as(as = "ResolvedPathBuf")] + pub path: PathBuf, + /// Generate and apply Base16 theme for this wallpaper + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(extend("default" = true)))] + pub generate_theme: Option, + /// Specify theme options + #[serde(skip_serializing_if = "Option::is_none")] + pub theme_options: Option, +} + // serde_as must be before derive #[serde_with::serde_as] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -199,6 +263,9 @@ pub struct WorkspaceConfig { #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] pub floating_layer_behaviour: Option, + /// Specify a wallpaper for this workspace + #[serde(skip_serializing_if = "Option::is_none")] + pub wallpaper: Option, } impl From<&Workspace> for WorkspaceConfig { @@ -297,6 +364,7 @@ impl From<&Workspace> for WorkspaceConfig { tile, layout_flip: value.layout_flip, floating_layer_behaviour: value.floating_layer_behaviour, + wallpaper: None, } } } @@ -323,6 +391,9 @@ pub struct MonitorConfig { /// Workspace padding (default: global) #[serde(skip_serializing_if = "Option::is_none")] pub workspace_padding: Option, + /// Specify a wallpaper for this monitor + #[serde(skip_serializing_if = "Option::is_none")] + pub wallpaper: Option, /// Determine what happens to a new window when the Floating workspace layer is active #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = FloatingLayerBehaviour::Tile)))] @@ -366,6 +437,7 @@ impl From<&Monitor> for MonitorConfig { window_based_work_area_offset_limit: Some(value.window_based_work_area_offset_limit), container_padding, workspace_padding, + wallpaper: value.wallpaper.clone(), floating_layer_behaviour: value.floating_layer_behaviour, window_hiding_position: None, } @@ -1279,6 +1351,7 @@ impl StaticConfig { .unwrap_or(1); monitor.container_padding = monitor_config.container_padding; monitor.workspace_padding = monitor_config.workspace_padding; + monitor.wallpaper = monitor_config.wallpaper.clone(); monitor.floating_layer_behaviour = monitor_config.floating_layer_behaviour; monitor.update_workspaces_globals(offset); @@ -1402,6 +1475,7 @@ impl StaticConfig { .unwrap_or(1); monitor.container_padding = monitor_config.container_padding; monitor.workspace_padding = monitor_config.workspace_padding; + monitor.wallpaper = monitor_config.wallpaper.clone(); monitor.floating_layer_behaviour = monitor_config.floating_layer_behaviour; monitor.update_workspaces_globals(offset); @@ -1479,6 +1553,8 @@ impl StaticConfig { for i in 0..monitor_count { wm.update_focused_workspace_by_monitor_idx(i)?; + let ws_idx = wm.focused_workspace_idx_for_monitor_idx(i)?; + wm.apply_wallpaper_for_monitor_workspace(i, ws_idx)?; } // to update the borders diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index 0fdf6343..42ada02b 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -1950,8 +1950,9 @@ impl WindowManager { } /// Tiles the focused workspace of every monitor, without the resize adjustments of its - /// containers unless `preserve_resize_dimensions` is set, and asks the backend for the look - /// again ([`border_manager::destroy_all_borders`]) + /// containers unless `preserve_resize_dimensions` is set, sets the wallpaper each of them is + /// to show ([`Workspace::apply_wallpaper`]), and asks the backend for the look again + /// ([`border_manager::destroy_all_borders`]) #[tracing::instrument(skip(self))] pub fn retile_all(&mut self, preserve_resize_dimensions: bool) -> eyre::Result<()> { let offset = self.work_area_offset; @@ -1966,6 +1967,8 @@ impl WindowManager { let focused_workspace_idx = monitor.focused_workspace_idx(); monitor.update_workspace_globals(focused_workspace_idx, offset); + let monitor_id = monitor.id; + let monitor_wp = monitor.wallpaper.clone(); let workspace = monitor .focused_workspace_mut() .ok_or_eyre("there is no workspace")?; @@ -1975,6 +1978,12 @@ impl WindowManager { workspace.resize_dimensions.fill(None); } + if (workspace.wallpaper.is_some() || monitor_wp.is_some()) + && let Err(error) = workspace.apply_wallpaper(monitor_id, &monitor_wp) + { + tracing::error!("failed to apply wallpaper: {}", error); + } + workspace.update()?; } @@ -3213,6 +3222,16 @@ impl WindowManager { monitor.focus_workspace(idx)?; monitor.update_focused_workspace(offset)?; + // komorebi's own switches set the wallpaper as the workspace is restored; somebody else's + // (a pager, a shortcut) comes here instead + let monitor_wp = monitor.wallpaper.clone(); + if let Some(workspace) = monitor.workspaces().get(idx) + && (workspace.wallpaper.is_some() || monitor_wp.is_some()) + && let Err(error) = workspace.apply_wallpaper(monitor_id, &monitor_wp) + { + tracing::error!("failed to apply wallpaper: {error}"); + } + self.update_known_window_ids(); Ok(()) @@ -3915,6 +3934,36 @@ impl WindowManager { Ok(()) } + + /// Sets the wallpaper the monitor at `monitor_idx` is to show for its workspace at + /// `workspace_idx`, and gives the borders the colors of its theme ([`Workspace::apply_wallpaper`]). + /// A reloaded configuration calls it for the workspace each monitor shows, so that the + /// wallpapers it gives are shown at once. + /// + /// # Errors + /// + /// There is no monitor at `monitor_idx` or no workspace at `workspace_idx`. + #[tracing::instrument(skip(self))] + pub fn apply_wallpaper_for_monitor_workspace( + &mut self, + monitor_idx: usize, + workspace_idx: usize, + ) -> eyre::Result<()> { + let monitor = self + .monitors_mut() + .get_mut(monitor_idx) + .ok_or_eyre("there is no monitor")?; + + let monitor_id = monitor.id; + let monitor_wp = monitor.wallpaper.clone(); + + let workspace = monitor + .workspaces() + .get(workspace_idx) + .ok_or_eyre("there is no workspace")?; + + workspace.apply_wallpaper(monitor_id, &monitor_wp) + } } #[cfg(test)] diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index bedb8767..f5a30722 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -25,11 +25,15 @@ use crate::core::Rect; use crate::core::WindowContainerBehaviour; use crate::lockable_sequence::LockableSequence; use crate::ring::Ring; +use crate::static_config::Wallpaper; use crate::static_config::WorkspaceConfig; +use crate::theme_manager; use crate::window::Window; use crate::window::WindowDetails; use color_eyre::eyre; use color_eyre::eyre::OptionExt; +use komorebi_themes::KomorebiTheme; +use komorebi_themes::KomorebiThemeCustom; use serde::Deserialize; use serde::Serialize; use std::collections::HashMap; @@ -101,6 +105,8 @@ pub struct Workspace { /// Whether a window that opens while this workspace is on its floating layer floats, when it /// is not the monitor's or the window manager's default pub floating_layer_behaviour: Option, + /// The wallpaper this workspace shows instead of its monitor's + pub wallpaper: Option, /// The entry of `komorebi.json` this workspace was loaded from, which keeps the rules that /// send windows to it #[serde(skip_serializing_if = "Option::is_none")] @@ -165,6 +171,7 @@ impl Default for Workspace { window_container_behaviour_rules: None, floating_windows: Default::default(), float_override: None, + wallpaper: None, workspace_config: None, preselected_container_idx: None, promotion_swap_container_idx: None, @@ -338,6 +345,7 @@ impl Workspace { self.float_override = config.float_override; self.layout_flip = config.layout_flip; self.floating_layer_behaviour = config.floating_layer_behaviour; + self.wallpaper = config.wallpaper.clone(); // Load layout options directly (LayoutOptions is used in both config and runtime) self.layout_options = config.layout_options; @@ -993,7 +1001,13 @@ impl Workspace { /// itself has hidden (the back of a stack stays hidden). While there is a monocle container /// only its window is restored and focused, for the other containers are out of sight behind /// it. A maximized window is restored and given the focus ahead of the containers' windows. - pub fn restore(&mut self, mouse_follows_focus: bool) -> eyre::Result<()> { + /// It sets the wallpaper the monitor is to show ([`Workspace::apply_wallpaper`]). + pub fn restore( + &mut self, + mouse_follows_focus: bool, + monitor_id: u32, + monitor_wp: &Option, + ) -> eyre::Result<()> { if let Some(container) = &mut self.monocle_container { container.restore()?; @@ -1001,7 +1015,7 @@ impl Workspace { window.focus(mouse_follows_focus)?; } - return Ok(()); + return self.apply_wallpaper(monitor_id, monitor_wp); } let idx = self.focused_container_idx(); @@ -1046,7 +1060,7 @@ impl Workspace { floating_window.focus(mouse_follows_focus)?; } - Ok(()) + self.apply_wallpaper(monitor_id, monitor_wp) } pub fn remove_focused_container(&mut self) -> Option { @@ -1759,6 +1773,46 @@ impl Workspace { vec } + + /// Has the monitor show this workspace's wallpaper, or else the monitor's `monitor_wp`, and + /// gives the borders the colors of the palette of the picture unless the wallpaper asks for no + /// theme. Nothing is done for a workspace and a monitor that have no wallpaper. + /// + /// A failure to set the wallpaper is logged and does not make this fail, and the colors are + /// still changed: the picture may be shown a moment later, when the Plasma shell is up. The + /// colors are changed before this returns, so the borders drawn for the workspace that comes + /// into view are right at once. + pub fn apply_wallpaper( + &self, + monitor_id: u32, + monitor_wp: &Option, + ) -> eyre::Result<()> { + if let Some(wallpaper) = self.wallpaper.as_ref().or(monitor_wp.as_ref()) { + if let Err(error) = backend().set_wallpaper(monitor_id, &wallpaper.path) { + tracing::error!("failed to set wallpaper: {error}"); + } + + if wallpaper.generate_theme.unwrap_or(true) { + let options = wallpaper.theme_options.as_ref(); + let variant = options.and_then(|o| o.theme_variant).unwrap_or_default(); + + if let Some(palette) = theme_manager::wallpaper_palette(&wallpaper.path, variant) { + theme_manager::send_notification(KomorebiTheme::Custom(KomorebiThemeCustom { + colours: Box::new(palette), + single_border: options.and_then(|o| o.single_border), + stack_border: options.and_then(|o| o.stack_border), + monocle_border: options.and_then(|o| o.monocle_border), + floating_border: options.and_then(|o| o.floating_border), + unfocused_border: options.and_then(|o| o.unfocused_border), + unfocused_locked_border: options.and_then(|o| o.unfocused_locked_border), + bar_accent: options.and_then(|o| o.bar_accent), + })); + } + } + } + + Ok(()) + } } impl Workspace { @@ -3058,7 +3112,7 @@ mod tests { -> eyre::Result<()> { let (fake, mut workspace) = workspace_with_a_stack(&[461, 462, 463]); - with_backend(fake.clone(), || workspace.restore(false))?; + with_backend(fake.clone(), || workspace.restore(false, 0, &None))?; assert!(fake.is_hidden(462), "the back of the stack stays hidden"); assert!(!fake.is_hidden(463) && !fake.is_hidden(461)); @@ -3101,7 +3155,7 @@ mod tests { "leaving the workspace hides the monocle window too" ); - with_backend(fake.clone(), || workspace.restore(false))?; + with_backend(fake.clone(), || workspace.restore(false, 0, &None))?; assert!(!fake.is_hidden(483), "the window in monocle is shown"); assert!( diff --git a/komorebi/tests/maximize_commands.rs b/komorebi/tests/maximize_commands.rs index 7dd78e5b..ca5f6d9c 100644 --- a/komorebi/tests/maximize_commands.rs +++ b/komorebi/tests/maximize_commands.rs @@ -322,7 +322,7 @@ fn a_maximized_window_is_hidden_with_its_workspace_and_shown_and_focused_with_it assert!(fake.is_hidden(36_071) && fake.is_hidden(36_072)); fake.clear_commands(); - with_backend(fake.clone(), || workspace.restore(true)).unwrap(); + with_backend(fake.clone(), || workspace.restore(true, 0, &None)).unwrap(); assert!(!fake.is_hidden(36_072), "the maximized window is shown"); assert!( fake.window_commands() diff --git a/komorebi/tests/wallpaper.rs b/komorebi/tests/wallpaper.rs new file mode 100644 index 00000000..fcf915b0 --- /dev/null +++ b/komorebi/tests/wallpaper.rs @@ -0,0 +1,517 @@ +//! Wallpapers, and the themes made from them. +//! +//! A monitor or a workspace can have a wallpaper; it is set when the workspace comes into view, +//! however it came (komorebi's own switch, or a pager's), and a palette made from it gives the +//! borders their colors. The colors are process-wide, so this file is one binary and its tests +//! take turns. + +use color_eyre::eyre; +use komorebi::backend::fake::Command; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::border_manager; +use komorebi::core::SocketMessage; +use komorebi::static_config::StaticConfig; +use komorebi::static_config::ThemeOptions; +use komorebi::static_config::Wallpaper; +use komorebi::theme_manager; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use komorebi_themes::ThemeVariant; +use parking_lot::Mutex; +use std::os::unix::net::UnixListener; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +const MONITOR: u32 = 1; + +static TURN: Mutex<()> = Mutex::new(()); + +/// Waits for the turn of a test, and makes the palettes it keeps go to a directory of this run's. +/// +/// A palette is kept in the user's cache directory, which a build in a sandbox has no right to +/// make, and the tests that keep one would otherwise leave a file in the cache of whoever runs +/// them. The environment is only touched by the test that has the turn, and no other thread of +/// this binary reads it. +fn take_turn() -> parking_lot::MutexGuard<'static, ()> { + let turn = TURN.lock(); + let cache = std::env::temp_dir().join(format!("kmf-wallpaper-cache-{}", std::process::id())); + // SAFETY: see above + unsafe { std::env::set_var("XDG_CACHE_HOME", cache) }; + turn +} + +// ---- pictures --------------------------------------------------------------------------------- + +fn crc32(bytes: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in bytes { + crc ^= u32::from(b); + for _ in 0..8 { + crc = if crc & 1 == 1 { + (crc >> 1) ^ 0xEDB8_8320 + } else { + crc >> 1 + }; + } + } + !crc +} + +fn adler32(bytes: &[u8]) -> u32 { + let (mut a, mut b) = (1u32, 0u32); + for &x in bytes { + a = (a + u32::from(x)) % 65521; + b = (b + a) % 65521; + } + (b << 16) | a +} + +/// A PNG of `width` by `height`, each pixel from `pixel(x, y)`, with the data stored, not packed: +/// the tests need a picture, not a good one +fn write_png(path: &Path, width: u32, height: u32, pixel: impl Fn(u32, u32) -> [u8; 3]) { + let mut raw = Vec::new(); + for y in 0..height { + raw.push(0); + for x in 0..width { + raw.extend_from_slice(&pixel(x, y)); + } + } + + let mut zlib = vec![0x78, 0x01]; + let mut chunks = raw.chunks(65_535).peekable(); + while let Some(chunk) = chunks.next() { + zlib.push(u8::from(chunks.peek().is_none())); + zlib.extend_from_slice(&(chunk.len() as u16).to_le_bytes()); + zlib.extend_from_slice(&(!(chunk.len() as u16)).to_le_bytes()); + zlib.extend_from_slice(chunk); + } + zlib.extend_from_slice(&adler32(&raw).to_be_bytes()); + + let chunk = |kind: &[u8; 4], data: &[u8]| { + let mut out = (data.len() as u32).to_be_bytes().to_vec(); + out.extend_from_slice(kind); + out.extend_from_slice(data); + out.extend_from_slice(&crc32(&out[4..]).to_be_bytes()); + out + }; + + let mut header = Vec::new(); + header.extend_from_slice(&width.to_be_bytes()); + header.extend_from_slice(&height.to_be_bytes()); + header.extend_from_slice(&[8, 2, 0, 0, 0]); + + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + png.extend(chunk(b"IHDR", &header)); + png.extend(chunk(b"IDAT", &zlib)); + png.extend(chunk(b"IEND", &[])); + std::fs::write(path, png).unwrap(); +} + +/// Pictures that are warm, and cool. The palette is made of at least eight colors of the picture, +/// so each has a dozen of them, in bands. +struct Pictures { + dir: PathBuf, + warm: PathBuf, + cool: PathBuf, +} + +impl Pictures { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("kmf-wallpaper-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (warm, cool) = (dir.join("warm.png"), dir.join("cool.png")); + + // red to yellow, and blue to cyan, going dark and light + let band = |hue: [u8; 3], i: u32| { + let shade = 40 + (i % 4) * 55; + hue.map(|c| ((u32::from(c) * shade) / 255).min(255) as u8) + }; + write_png(&warm, 96, 96, |x, y| { + let i = (x / 8 + y / 8) % 12; + band([255, (i * 20).min(255) as u8, 20], i) + }); + write_png(&cool, 96, 96, |x, y| { + let i = (x / 8 + y / 8) % 12; + band([20, (80 + i * 14).min(255) as u8, 255], i) + }); + + Self { dir, warm, cool } + } +} + +impl Drop for Pictures { + fn drop(&mut self) { + for path in [&self.warm, &self.cool] { + let _ = std::fs::remove_file(theme_manager::palette_file(path, ThemeVariant::Dark)); + let _ = std::fs::remove_file(theme_manager::palette_file(path, ThemeVariant::Light)); + } + let _ = std::fs::remove_dir_all(&self.dir); + if let Some(cache) = theme_manager::palette_file(&self.warm, ThemeVariant::Dark).parent() { + let _ = std::fs::remove_dir(cache); + } + } +} + +fn wallpaper(path: &Path, generate_theme: Option) -> Wallpaper { + Wallpaper { + path: path.to_path_buf(), + generate_theme, + theme_options: None, + } +} + +// ---- the desktop ------------------------------------------------------------------------------ + +fn desktop() -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = PathBuf::from(format!("/tmp/kmf-wallpaper-{}.sock", std::process::id())); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +fn command(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +fn workspace_changed(idx: usize) -> WindowManagerEvent { + WindowManagerEvent::WorkspaceChange( + SystemNotification::KWin(KWinNotification::WorkspaceChanged), + MONITOR, + idx, + ) +} + +fn focused_border() -> u32 { + border_manager::FOCUSED.load(Ordering::SeqCst) +} + +// ---- tests ------------------------------------------------------------------------------------ + +#[test] +fn a_wallpaper_is_set_when_its_workspace_comes_into_view_by_whoever_brings_it() { + let _turn = take_turn(); + let pictures = Pictures::new("set"); + let (fake, mut wm) = desktop(); + + // the monitor has the warm one, and workspace 1 has the cool one of its own + let monitor = wm.monitors_mut().get_mut(0).unwrap(); + assert_eq!(monitor.id, MONITOR); + monitor.wallpaper = Some(wallpaper(&pictures.warm, Some(false))); + monitor.ensure_workspace_count(3); + monitor.workspaces_mut()[1].wallpaper = Some(wallpaper(&pictures.cool, Some(false))); + + // komorebi's own switch + command(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)); + assert_eq!(fake.wallpaper_of(MONITOR), Some(pictures.cool.clone())); + + // back to a workspace that has none of its own: the monitor's + command(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(0)); + assert_eq!(fake.wallpaper_of(MONITOR), Some(pictures.warm.clone())); + + // and a switch somebody else made (a pager, a shortcut) comes as an event + with_backend(fake.clone(), || wm.process_event(workspace_changed(1))).unwrap(); + assert_eq!(fake.wallpaper_of(MONITOR), Some(pictures.cool.clone())); + + with_backend(fake.clone(), || wm.process_event(workspace_changed(2))).unwrap(); + assert_eq!( + fake.wallpaper_of(MONITOR), + Some(pictures.warm.clone()), + "a workspace with none of its own has the monitor's" + ); +} + +#[test] +fn no_wallpaper_is_touched_that_was_not_asked_for() { + let _turn = take_turn(); + let (fake, mut wm) = desktop(); + wm.monitors_mut()[0].ensure_workspace_count(2); + + command(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)); + command(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(0)); + + assert!( + !fake + .commands() + .iter() + .any(|c| matches!(c, Command::SetWallpaper(..))), + "{:?}", + fake.commands() + ); +} + +#[test] +fn the_borders_take_their_colours_from_the_wallpaper_and_follow_it() { + let _turn = take_turn(); + let pictures = Pictures::new("theme"); + let (fake, mut wm) = desktop(); + + let monitor = wm.monitors_mut().get_mut(0).unwrap(); + monitor.ensure_workspace_count(2); + monitor.workspaces_mut()[0].wallpaper = Some(wallpaper(&pictures.warm, None)); + monitor.workspaces_mut()[1].wallpaper = Some(wallpaper(&pictures.cool, None)); + + // what an earlier test left behind is not what this one starts from + border_manager::FOCUSED.store(0x0001_0203, Ordering::SeqCst); + let before = focused_border(); + + // what starting up does: the wallpaper of the workspace that is in front is set + with_backend(fake.clone(), || wm.retile_all(false)).unwrap(); + let warm = focused_border(); + assert_eq!(fake.wallpaper_of(MONITOR), Some(pictures.warm.clone())); + assert_ne!( + warm, before, + "the warm wallpaper did not change the focused border" + ); + + command(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)); + let cool = focused_border(); + assert_ne!(cool, warm, "two different wallpapers gave the same border"); + + // a pager's switch brings the first one's colors back + with_backend(fake.clone(), || wm.process_event(workspace_changed(0))).unwrap(); + assert_eq!(focused_border(), warm); + + // the palette was kept, and is the same when read again + let palette = theme_manager::palette_file(&pictures.warm, ThemeVariant::Dark); + assert!(palette.is_file(), "{} was not kept", palette.display()); + command(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(1)); + command(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(0)); + assert_eq!( + focused_border(), + warm, + "the cached palette gave other colors" + ); +} + +#[test] +fn a_wallpaper_that_asks_for_no_theme_leaves_the_borders_alone() { + let _turn = take_turn(); + let pictures = Pictures::new("notheme"); + let (fake, mut wm) = desktop(); + + wm.monitors_mut()[0].workspaces_mut()[0].wallpaper = + Some(wallpaper(&pictures.cool, Some(false))); + let before = focused_border(); + + with_backend(fake.clone(), || wm.retile_all(false)).unwrap(); + + assert_eq!(fake.wallpaper_of(MONITOR), Some(pictures.cool.clone())); + assert_eq!(focused_border(), before); +} + +#[test] +fn a_wallpaper_that_is_not_a_picture_still_sets_and_does_not_break_the_window_manager() { + let _turn = take_turn(); + let pictures = Pictures::new("broken"); + let broken = pictures.dir.join("broken.png"); + std::fs::write(&broken, b"this is not a picture").unwrap(); + let (fake, mut wm) = desktop(); + + wm.monitors_mut()[0].workspaces_mut()[0].wallpaper = Some(wallpaper(&broken, None)); + let before = focused_border(); + + with_backend(fake.clone(), || wm.retile_all(false)).unwrap(); + + assert_eq!(fake.wallpaper_of(MONITOR), Some(broken.clone())); + assert_eq!(focused_border(), before, "no palette, no new colors"); + // and the window manager still answers + command(&fake, &mut wm, SocketMessage::FocusWorkspaceNumber(0)); +} + +#[test] +fn theme_options_choose_the_variant_and_the_colour_each_border_takes() { + let _turn = take_turn(); + let pictures = Pictures::new("options"); + + // what the focused border is, with these options, once the wallpaper is in front + let focused_with = |options: Option| { + let (fake, mut wm) = desktop(); + wm.monitors_mut()[0].workspaces_mut()[0].wallpaper = Some(Wallpaper { + path: pictures.warm.clone(), + generate_theme: None, + theme_options: options, + }); + with_backend(fake.clone(), || wm.retile_all(false)).unwrap(); + focused_border() + }; + let options = |variant, single| ThemeOptions { + theme_variant: variant, + single_border: single, + stack_border: None, + monocle_border: None, + floating_border: None, + unfocused_border: None, + unfocused_locked_border: None, + bar_accent: None, + }; + + let by_default = focused_with(None); + let another_colour = focused_with(Some(options( + None, + Some(komorebi_themes::Base16Value::Base08), + ))); + let light = focused_with(Some(options(Some(ThemeVariant::Light), None))); + + assert_ne!( + another_colour, by_default, + "asking for another color of the palette changed nothing" + ); + assert_ne!(light, by_default, "the light variant is the dark one"); + assert_eq!( + by_default, + focused_with(Some(options(Some(ThemeVariant::Dark), None))) + ); +} + +#[test] +fn the_wallpaper_example_in_the_docs_loads() { + let docs = Path::new(env!("CARGO_MANIFEST_DIR")).join("../docs/usage/wallpapers.md"); + let docs = std::fs::read_to_string(docs).unwrap(); + let json = docs + .split("```json\n") + .nth(1) + .and_then(|rest| rest.split("```").next()) + .expect("docs/usage/wallpapers.md has no json example"); + + let config: StaticConfig = serde_json::from_str(json).unwrap(); + let monitor = &config.monitors.unwrap()[0]; + + let on_monitor = monitor.wallpaper.as_ref().expect("the monitor's wallpaper"); + assert!(on_monitor.path.ends_with("Pictures/dunes.png")); + assert!( + !on_monitor.path.starts_with("~"), + "the home directory was not resolved: {:?}", + on_monitor.path + ); + + let chat = monitor.workspaces[1] + .wallpaper + .as_ref() + .expect("a workspace's wallpaper"); + let options = chat.theme_options.as_ref().unwrap(); + assert_eq!(options.theme_variant, Some(ThemeVariant::Light)); + assert_eq!( + options.single_border, + Some(komorebi_themes::Base16Value::Base09) + ); +} + +#[test] +fn the_wallpapers_of_the_file_are_on_the_monitor_and_its_workspaces_and_a_reload_shows_them() { + let _turn = take_turn(); + let pictures = Pictures::new("file"); + let fake = Arc::new(FakeBackend::with_one_monitor()); + + let file = |first: &Path, second: &Path| { + format!( + r#"{{ "monitors": [ {{ + "wallpaper": {{ "path": {first:?}, "generate_theme": false }}, + "workspaces": [ + {{ "name": "code" }}, + {{ "name": "chat", "wallpaper": {{ "path": {second:?}, "generate_theme": false }} }} + ] }} ] }}"# + ) + }; + let path = PathBuf::from(format!( + "/tmp/kmf-wallpaper-file-{}.json", + std::process::id() + )); + std::fs::write(&path, file(&pictures.warm, &pictures.cool)).unwrap(); + + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = PathBuf::from(format!( + "/tmp/kmf-wallpaper-file-{}.sock", + std::process::id() + )); + let listener = UnixListener::bind(&socket).unwrap(); + let wm = with_backend(fake.clone(), || -> eyre::Result { + let mut wm = StaticConfig::preload(&path, receiver, Some(listener))?; + wm.init()?; + Ok(wm) + }) + .unwrap(); + let wm = Arc::new(parking_lot::Mutex::new(wm)); + with_backend(fake.clone(), || StaticConfig::postload(&path, &wm)).unwrap(); + let _ = std::fs::remove_file(&socket); + + { + let wm = wm.lock(); + let monitor = &wm.monitors()[0]; + assert_eq!(monitor.workspaces().len(), 2); + assert_eq!( + monitor.wallpaper.as_ref().map(|w| w.path.clone()), + Some(pictures.warm.clone()) + ); + assert!(monitor.workspaces()[0].wallpaper.is_none()); + assert_eq!( + monitor.workspaces()[1] + .wallpaper + .as_ref() + .map(|w| w.path.clone()), + Some(pictures.cool.clone()) + ); + } + + // the first layout shows the monitor's wallpaper, and the workspace's own shows with it + with_backend(fake.clone(), || wm.lock().retile_all(false)).unwrap(); + assert_eq!(fake.wallpaper_of(MONITOR), Some(pictures.warm.clone())); + command( + &fake, + &mut wm.lock(), + SocketMessage::FocusWorkspaceNumber(1), + ); + assert_eq!(fake.wallpaper_of(MONITOR), Some(pictures.cool.clone())); + + // the file is read again with the pictures the other way round: the workspace in front shows + // its new one at once + std::fs::write(&path, file(&pictures.cool, &pictures.warm)).unwrap(); + with_backend(fake.clone(), || { + StaticConfig::reload(&path, &mut wm.lock()).unwrap(); + }); + assert_eq!(fake.wallpaper_of(MONITOR), Some(pictures.warm.clone())); + let _ = std::fs::remove_file(&path); + + // the configuration the daemon generates has the monitor's wallpaper + let generated = StaticConfig::from(&*wm.lock()); + let monitor = &generated.monitors.unwrap()[0]; + assert_eq!( + monitor.wallpaper.as_ref().map(|w| w.path.clone()), + Some(pictures.cool.clone()) + ); +} + +#[test] +fn the_wallpapers_are_in_the_state() { + let _turn = take_turn(); + let (_fake, mut wm) = desktop(); + + let monitor = wm.monitors_mut().get_mut(0).unwrap(); + monitor.wallpaper = Some(wallpaper(Path::new("/pictures/dunes.png"), None)); + monitor.ensure_workspace_count(2); + monitor.workspaces_mut()[1].wallpaper = Some(wallpaper(Path::new("/pictures/sea.png"), None)); + + let state = serde_json::to_value(komorebi::state::State::from(&wm)).unwrap(); + let monitor = &state["monitors"]["elements"][0]; + + assert_eq!(monitor["wallpaper"]["path"], "/pictures/dunes.png"); + assert_eq!( + monitor["workspaces"]["elements"][0]["wallpaper"], + serde_json::Value::Null + ); + assert_eq!( + monitor["workspaces"]["elements"][1]["wallpaper"]["path"], + "/pictures/sea.png" + ); +} diff --git a/nix/komorebi-options.nix b/nix/komorebi-options.nix index fbe9f390..8a161491 100644 --- a/nix/komorebi-options.nix +++ b/nix/komorebi-options.nix @@ -1,4 +1,4 @@ -# schema-sha256: 475a8bc02a8f0e0e68cc0fbb41bd949ff7743feda00fac5c4bf02565d2848561 +# schema-sha256: be9289ac70f6f47d7d8aebee0d7c67a2fa0d54456d9306ce6c634ef6e7748ddf { lib, ... }: let animationStyle = ( @@ -266,6 +266,80 @@ let }; } ); + wallpaper = ( + lib.types.submodule { + options = { + generate_theme = lib.mkOption { + type = (lib.types.nullOr lib.types.bool); + default = true; + description = "Generate and apply Base16 theme for this wallpaper"; + }; + path = lib.mkOption { + type = pathBuf; + description = "Path to the wallpaper image file"; + }; + theme_options = lib.mkOption { + type = ( + lib.types.nullOr ( + lib.types.submodule { + options = { + bar_accent = lib.mkOption { + type = (lib.types.nullOr base16Value); + default = "Base0D"; + description = "Komorebi status bar accent"; + }; + floating_border = lib.mkOption { + type = (lib.types.nullOr base16Value); + default = "Base09"; + description = "Border color when the window is floating"; + }; + monocle_border = lib.mkOption { + type = (lib.types.nullOr base16Value); + default = "Base0F"; + description = "Border color when the container is in monocle mode"; + }; + single_border = lib.mkOption { + type = (lib.types.nullOr base16Value); + default = "Base0D"; + description = "Border color when the container contains a single window"; + }; + stack_border = lib.mkOption { + type = (lib.types.nullOr base16Value); + default = "Base0B"; + description = "Border color when the container contains multiple windows"; + }; + theme_variant = lib.mkOption { + type = ( + lib.types.nullOr ( + lib.types.enum [ + "Dark" + "Light" + ] + ) + ); + default = "Dark"; + description = "Specify Light or Dark variant for theme generation"; + }; + unfocused_border = lib.mkOption { + type = (lib.types.nullOr base16Value); + default = "Base01"; + description = "Border color when the container is unfocused"; + }; + unfocused_locked_border = lib.mkOption { + type = (lib.types.nullOr base16Value); + default = "Base08"; + description = "Border color when the container is unfocused and locked"; + }; + }; + } + ) + ); + default = null; + description = "Specify theme options"; + }; + }; + } + ); windowContainerBehaviour = ( lib.types.enum [ "Create" @@ -573,6 +647,11 @@ in default = "Tile"; description = "Determine what happens to a new window when the Floating workspace layer is active"; }; + wallpaper = lib.mkOption { + type = (lib.types.nullOr wallpaper); + default = null; + description = "Specify a wallpaper for this monitor"; + }; window_based_work_area_offset = lib.mkOption { type = (lib.types.nullOr rect); default = null; @@ -677,6 +756,11 @@ in default = true; description = "Enable or disable tiling for the workspace"; }; + wallpaper = lib.mkOption { + type = (lib.types.nullOr wallpaper); + default = null; + description = "Specify a wallpaper for this workspace"; + }; window_container_behaviour = lib.mkOption { type = (lib.types.nullOr windowContainerBehaviour); default = "Create"; @@ -762,114 +846,6 @@ in ] ); }; - monocle_border = lib.mkOption { - type = ( - lib.types.nullOr ( - lib.types.oneOf [ - (lib.types.nullOr catppuccinValue) - (lib.types.nullOr base16Value) - ] - ) - ); - default = null; - }; - colours = lib.mkOption { - type = ( - lib.types.nullOr ( - lib.types.submodule { - options = { - base_00 = lib.mkOption { - type = colour; - description = "Base00"; - }; - base_01 = lib.mkOption { - type = colour; - description = "Base01"; - }; - base_02 = lib.mkOption { - type = colour; - description = "Base02"; - }; - base_03 = lib.mkOption { - type = colour; - description = "Base03"; - }; - base_04 = lib.mkOption { - type = colour; - description = "Base04"; - }; - base_05 = lib.mkOption { - type = colour; - description = "Base05"; - }; - base_06 = lib.mkOption { - type = colour; - description = "Base06"; - }; - base_07 = lib.mkOption { - type = colour; - description = "Base07"; - }; - base_08 = lib.mkOption { - type = colour; - description = "Base08"; - }; - base_09 = lib.mkOption { - type = colour; - description = "Base09"; - }; - base_0a = lib.mkOption { - type = colour; - description = "Base0A"; - }; - base_0b = lib.mkOption { - type = colour; - description = "Base0B"; - }; - base_0c = lib.mkOption { - type = colour; - description = "Base0C"; - }; - base_0d = lib.mkOption { - type = colour; - description = "Base0D"; - }; - base_0e = lib.mkOption { - type = colour; - description = "Base0E"; - }; - base_0f = lib.mkOption { - type = colour; - description = "Base0F"; - }; - }; - } - ) - ); - default = null; - }; - unfocused_locked_border = lib.mkOption { - type = ( - lib.types.nullOr ( - lib.types.oneOf [ - (lib.types.nullOr catppuccinValue) - (lib.types.nullOr base16Value) - ] - ) - ); - default = null; - }; - unfocused_border = lib.mkOption { - type = ( - lib.types.nullOr ( - lib.types.oneOf [ - (lib.types.nullOr catppuccinValue) - (lib.types.nullOr base16Value) - ] - ) - ); - default = null; - }; name = lib.mkOption { type = ( lib.types.nullOr ( @@ -1167,6 +1143,92 @@ in ); default = null; }; + colours = lib.mkOption { + type = ( + lib.types.nullOr ( + lib.types.submodule { + options = { + base_00 = lib.mkOption { + type = colour; + description = "Base00"; + }; + base_01 = lib.mkOption { + type = colour; + description = "Base01"; + }; + base_02 = lib.mkOption { + type = colour; + description = "Base02"; + }; + base_03 = lib.mkOption { + type = colour; + description = "Base03"; + }; + base_04 = lib.mkOption { + type = colour; + description = "Base04"; + }; + base_05 = lib.mkOption { + type = colour; + description = "Base05"; + }; + base_06 = lib.mkOption { + type = colour; + description = "Base06"; + }; + base_07 = lib.mkOption { + type = colour; + description = "Base07"; + }; + base_08 = lib.mkOption { + type = colour; + description = "Base08"; + }; + base_09 = lib.mkOption { + type = colour; + description = "Base09"; + }; + base_0a = lib.mkOption { + type = colour; + description = "Base0A"; + }; + base_0b = lib.mkOption { + type = colour; + description = "Base0B"; + }; + base_0c = lib.mkOption { + type = colour; + description = "Base0C"; + }; + base_0d = lib.mkOption { + type = colour; + description = "Base0D"; + }; + base_0e = lib.mkOption { + type = colour; + description = "Base0E"; + }; + base_0f = lib.mkOption { + type = colour; + description = "Base0F"; + }; + }; + } + ) + ); + default = null; + }; + bar_accent = lib.mkOption { + type = ( + lib.types.nullOr ( + lib.types.oneOf [ + (lib.types.nullOr catppuccinValue) + (lib.types.nullOr base16Value) + ] + ) + ); + default = null; + }; floating_border = lib.mkOption { type = ( lib.types.nullOr ( @@ -1178,6 +1240,17 @@ in ); default = null; }; + monocle_border = lib.mkOption { + type = ( + lib.types.nullOr ( + lib.types.oneOf [ + (lib.types.nullOr catppuccinValue) + (lib.types.nullOr base16Value) + ] + ) + ); + default = null; + }; single_border = lib.mkOption { type = ( lib.types.nullOr ( @@ -1189,7 +1262,18 @@ in ); default = null; }; - bar_accent = lib.mkOption { + unfocused_locked_border = lib.mkOption { + type = ( + lib.types.nullOr ( + lib.types.oneOf [ + (lib.types.nullOr catppuccinValue) + (lib.types.nullOr base16Value) + ] + ) + ); + default = null; + }; + unfocused_border = lib.mkOption { type = ( lib.types.nullOr ( lib.types.oneOf [ diff --git a/nix/tests/vm/suites/wallpaper/default.nix b/nix/tests/vm/suites/wallpaper/default.nix new file mode 100644 index 00000000..0616ca83 --- /dev/null +++ b/nix/tests/vm/suites/wallpaper/default.nix @@ -0,0 +1,9 @@ +{ + tier = "slow"; + kind = "session"; + timeoutMinutes = 15; + # The session has the Plasma shell, which keeps the wallpapers, and the module installs the + # border effect. The module's unit starts komorebi when the session does; the test stops that + # daemon and starts its own runs of it, with the wallpapers it writes to the user's + # `komorebi.json`. +} diff --git a/nix/tests/vm/suites/wallpaper/test.py b/nix/tests/vm/suites/wallpaper/test.py new file mode 100644 index 00000000..ff6462b5 --- /dev/null +++ b/nix/tests/vm/suites/wallpaper/test.py @@ -0,0 +1,259 @@ +# Wallpapers, and the borders' colors that come from them, in a real Plasma session: what the shell +# shows and what is on the screen, read from the shell's D-Bus API and from screenshots. +# +# A a monitor's wallpaper is set at start, and a workspace's own replaces it when it is shown +# B a switch komorebi did not make (a pager's) sets the wallpaper too +# C the borders take the colors of the wallpaper's palette, and follow it from workspace to +# workspace +# D a wallpaper the user changed by hand is put back when its workspace is shown again +# E the palette cache, and a path with a space in it (the second picture's) +# F komorebi that starts before the Plasma shell does +# +# 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 test sets by hand. +import base64 +import io +import re +import shlex +import time + +from PIL import Image + +from komorebi_vm import Checks, Kde, Rect, pixels + +UNIT = "komorebi.service" +SHELL_UNIT = "plasma-plasmashell.service" +# the daemon's log of the day, without colors, which every run of the unit adds to +LOG = "/home/komorebi/.local/share/komorebi/komorebi_plaintext.log.*" +CONFIG = "/home/komorebi/.config/komorebi/komorebi.json" +PICTURES = "/tmp/wallpapers" +WARM = f"{PICTURES}/warm.png" +COOL = f"{PICTURES}/my pictures/cool.png" +OTHER = f"{PICTURES}/other.png" +WARM_URL = f"file://{PICTURES}/warm.png" +COOL_URL = f"file://{PICTURES}/my%20pictures/cool.png" +# `Image.PreserveAspectCrop`, which is how komorebi has the shell fill the screen +FILL = 2 + +start_all() +machine.wait_for_unit("multi-user.target") + +checks = Checks() +kde = Kde.session(machine, scale=SCALE) + + +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 put(path: str, data: bytes) -> None: + """Writes `data` to `path` in the machine, where the test user can read it.""" + directory = shlex.quote(path.rsplit("/", 1)[0]) + encoded = base64.b64encode(data).decode() + machine.succeed(f"mkdir -p {directory} && chmod a+rx {directory}") + machine.succeed(f"echo {encoded} | base64 -d > {shlex.quote(path)}") + machine.succeed(f"chmod a+r {shlex.quote(path)}") + + +def running() -> bool: + return kde.run(f"systemctl --user is-active --quiet {UNIT}")[0] == 0 + + +def answering() -> bool: + return kde.run("komorebic monitor-information")[0] == 0 + + +def start_komorebi() -> None: + kde.systemctl("start", UNIT) + kde.wait_for(answering, timeout=60) + time.sleep(2) + + +def stop_komorebi() -> None: + kde.systemctl("stop", UNIT) + kde.close_colored_windows() + + +def shell_wallpaper() -> tuple[str, int]: + """What the shell shows on its first screen: the picture's URL, and the fill mode.""" + out = kde.run( + "busctl --user call org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell wallpaper u 0" + )[1] + image = re.search(r'"Image" s "([^"]*)"', out) + fill = re.search(r'"FillMode" i (\d+)', out) + return (image.group(1) if image else "", int(fill.group(1)) if fill else -1) + + +def shows(url: str) -> bool: + return shell_wallpaper()[0] == url + + +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) + ] + red = sum(p[0] for p in points) / len(points) + blue = sum(p[2] for p in points) / len(points) + return "warm" if red > blue + 40 else "cool" if blue > red + 40 else "neither" + + +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 kde.wait_for(lambda: hue_of(kde.shot(name)) == hue, timeout=20) + + +def ring_hue(frame: Rect, image: Image.Image) -> str: + """The hue of the ring just outside the left edge of a frame.""" + red, _, blue = pixels.pixel(image, frame.x - 5, frame.y + frame.h // 2) + return "warm" if red > blue + 40 else "cool" if blue > red + 40 else "neither" + + +def has_ring(title: str, hue: str, name: str) -> bool: + """Returns true if the window has a ring of `hue` in a screenshot taken until it does.""" + return kde.wait_for( + lambda: ring_hue(kde.rect(kde.wid(title)), kde.shot(name)) == hue, timeout=20 + ) + + +print("== the pictures, and the wallpapers of the configuration") +put(WARM, picture((255, 0, 20), 20)) +put(COOL, picture((20, 80, 255), 14)) +put(OTHER, picture((60, 255, 60), 0)) +kde.sh(f"mkdir -p {shlex.quote(CONFIG.rsplit('/', 1)[0])}") +config = ( + '{ "monitors": [ { "wallpaper": { "path": "' + WARM + '" },' + ' "workspaces": [ { "name": "one" },' + ' { "name": "two", "wallpaper": { "path": "' + COOL + '" } } ] } ] }' +) +kde.sh(f"echo {shlex.quote(config)} > {CONFIG}") +kde.sh("rm -rf ~/.cache/komorebi") + +# the session started the module's unit when it logged in: this test starts its own runs +stop_komorebi() +kde.sh(f"plasma-apply-wallpaperimage {shlex.quote(OTHER)}") +checks.check( + "the shell shows a picture of the user's choice to begin with", + kde.wait_for(lambda: shows(f"file://{OTHER}"), timeout=20), +) + +print("== A. set at start, and by workspace") +start_komorebi() +checks.check( + "at start the shell shows the monitor's wallpaper", + kde.wait_for(lambda: shows(WARM_URL), timeout=20), +) +checks.check("it fills the screen", shell_wallpaper()[1] == FILL) +checks.check("and the screen is warm", screen_is("warm", "a1")) + +began = time.monotonic() +kde.komorebic("focus-workspace", "1") +checks.check( + "workspace two's own wallpaper is shown when it is (the path has a space in it)", + kde.wait_for(lambda: shows(COOL_URL), timeout=10), +) +took = time.monotonic() - began +checks.check(f"it took under two seconds ({took:.1f} s)", took < 2 * max(1, SCALE)) +checks.check("and the screen is cool", screen_is("cool", "a2")) + +kde.komorebic("focus-workspace", "0") +checks.check( + "back on workspace one, the monitor's wallpaper again", + kde.wait_for(lambda: shows(WARM_URL), timeout=10), +) + +print("== B. a switch somebody else made") +kde.sh("kdotool set_desktop 2") +checks.check( + "the desktop was changed outside komorebi, and its wallpaper came with it", + kde.wait_for(lambda: shows(COOL_URL), timeout=10), +) +kde.sh("kdotool set_desktop 1") +checks.check("and back", kde.wait_for(lambda: shows(WARM_URL), timeout=10)) + +print("== C. the borders follow the wallpaper") +kde.colored_window("left", "303030") +time.sleep(1.5) +checks.check( + "on the warm workspace the focused window's ring is warm", has_ring("left", "warm", "c1") +) +kde.komorebic("focus-workspace", "1") +time.sleep(2) +kde.colored_window("right", "303030") +time.sleep(2) +checks.check("on the cool one it is cool", has_ring("right", "cool", "c2")) +kde.komorebic("focus-workspace", "0") +time.sleep(2.5) +checks.check("and warm again when the first is back", has_ring("left", "warm", "c3")) + +print("== D. a wallpaper changed by hand is put back") +kde.sh(f"plasma-apply-wallpaperimage {shlex.quote(OTHER)}") +checks.check( + "the user changed it", + kde.wait_for(lambda: shows(f"file://{OTHER}"), timeout=10), +) +kde.komorebic("focus-workspace", "1") +time.sleep(1) +kde.komorebic("focus-workspace", "0") +checks.check( + "showing the workspace again set it back", + kde.wait_for(lambda: shows(WARM_URL), timeout=10), +) + +print("== E. the palette is kept") +cache = kde.sh("ls ~/.cache/komorebi 2>/dev/null || true").split() +print(f" the cache: {cache}") +checks.check( + "a palette for each wallpaper is in the cache, named for the picture", + any(n.startswith("warm-") for n in cache) and any(n.startswith("cool-") for n in cache), +) +daemon_log = machine.execute(f"cat {LOG}")[1] +checks.check( + "komorebi did not complain", + "failed to set wallpaper" not in daemon_log + and "gave up setting the wallpaper" not in daemon_log, +) +stop_komorebi() + +print("== F. komorebi starts before the Plasma shell") +kde.sh(f"plasma-apply-wallpaperimage {shlex.quote(OTHER)}") +kde.systemctl("stop", SHELL_UNIT) +checks.check( + "the shell is gone", kde.wait_for(lambda: not kde.has_name("org.kde.plasmashell"), timeout=20) +) +start_komorebi() +time.sleep(3) +checks.check("no shell to answer: komorebi is still managing", answering()) +kde.systemctl("start", SHELL_UNIT) +checks.check( + "the shell is back", kde.wait_for(lambda: kde.has_name("org.kde.plasmashell"), timeout=60) +) +checks.check( + "once the shell is up the wallpaper is set", + kde.wait_for(lambda: shows(WARM_URL), timeout=60), +) +daemon_log = machine.execute(f"cat {LOG}")[1] +checks.check( + "and komorebi did not give up and say so", "gave up setting the wallpaper" not in daemon_log +) +stop_komorebi() + +checks.finish() diff --git a/schema.json b/schema.json index 429fb275..a75ef311 100644 --- a/schema.json +++ b/schema.json @@ -3159,6 +3159,17 @@ ], "default": "Tile" }, + "wallpaper": { + "description": "Specify a wallpaper for this monitor", + "anyOf": [ + { + "$ref": "#/$defs/Wallpaper" + }, + { + "type": "null" + } + ] + }, "window_based_work_area_offset": { "description": "Window based work area offset", "anyOf": [ @@ -3459,6 +3470,155 @@ "columns" ] }, + "ThemeOptions": { + "description": "Theme options", + "type": "object", + "properties": { + "bar_accent": { + "description": "Komorebi status bar accent", + "anyOf": [ + { + "$ref": "#/$defs/Base16Value" + }, + { + "type": "null" + } + ], + "default": "Base0D" + }, + "floating_border": { + "description": "Border color when the window is floating", + "anyOf": [ + { + "$ref": "#/$defs/Base16Value" + }, + { + "type": "null" + } + ], + "default": "Base09" + }, + "monocle_border": { + "description": "Border color when the container is in monocle mode", + "anyOf": [ + { + "$ref": "#/$defs/Base16Value" + }, + { + "type": "null" + } + ], + "default": "Base0F" + }, + "single_border": { + "description": "Border color when the container contains a single window", + "anyOf": [ + { + "$ref": "#/$defs/Base16Value" + }, + { + "type": "null" + } + ], + "default": "Base0D" + }, + "stack_border": { + "description": "Border color when the container contains multiple windows", + "anyOf": [ + { + "$ref": "#/$defs/Base16Value" + }, + { + "type": "null" + } + ], + "default": "Base0B" + }, + "theme_variant": { + "description": "Specify Light or Dark variant for theme generation", + "anyOf": [ + { + "$ref": "#/$defs/ThemeVariant" + }, + { + "type": "null" + } + ], + "default": "Dark" + }, + "unfocused_border": { + "description": "Border color when the container is unfocused", + "anyOf": [ + { + "$ref": "#/$defs/Base16Value" + }, + { + "type": "null" + } + ], + "default": "Base01" + }, + "unfocused_locked_border": { + "description": "Border color when the container is unfocused and locked", + "anyOf": [ + { + "$ref": "#/$defs/Base16Value" + }, + { + "type": "null" + } + ], + "default": "Base08" + } + } + }, + "ThemeVariant": { + "description": "Theme variant", + "oneOf": [ + { + "description": "Dark variant", + "type": "string", + "const": "Dark" + }, + { + "description": "Light variant", + "type": "string", + "const": "Light" + } + ] + }, + "Wallpaper": { + "description": "Wallpaper configuration", + "type": "object", + "properties": { + "generate_theme": { + "description": "Generate and apply Base16 theme for this wallpaper", + "type": [ + "boolean", + "null" + ], + "default": true + }, + "path": { + "description": "Path to the wallpaper image file", + "$ref": "#/$defs/PathBuf" + }, + "theme_options": { + "description": "Specify theme options", + "anyOf": [ + { + "$ref": "#/$defs/ThemeOptions" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "path" + ] + }, "WindowContainerBehaviour": { "description": "Window container behavior when a new window is opened", "oneOf": [ @@ -3611,6 +3771,17 @@ ], "default": true }, + "wallpaper": { + "description": "Specify a wallpaper for this workspace", + "anyOf": [ + { + "$ref": "#/$defs/Wallpaper" + }, + { + "type": "null" + } + ] + }, "window_container_behaviour": { "description": "Determine what happens when a new window is opened", "anyOf": [