diff --git a/README.md b/README.md index 2babe4c0..39eca8cd 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,8 @@ without a checkout of the toolchain. the settings of KWin's it needs in the user's `kwinrc`, the parking desktop it 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 look they make (`border_manager`, `animation`), 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 @@ -259,7 +260,9 @@ komorebi gives each window the border color of what it is to the layout: the foc window, the others, a locked container, a floating window. `border`, `border-colour`, `border-width` and `border-offset` set it. Windows going to their places are animated by another effect, Geometry Change, which `animation`, -`animation-duration` and `animation-style` turn on and set. +`animation-duration` and `animation-style` turn on and set. `transparency` makes +the windows that do not have the focus see-through, by the opacity KWin gives a +window. ## Documentation diff --git a/docs/cli/toggle-transparency.md b/docs/cli/toggle-transparency.md new file mode 100644 index 00000000..cc11e291 --- /dev/null +++ b/docs/cli/toggle-transparency.md @@ -0,0 +1,10 @@ +```text +Toggle transparency for unfocused windows + +Usage: toggle-transparency + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/transparency-alpha.md b/docs/cli/transparency-alpha.md new file mode 100644 index 00000000..479bf9e2 --- /dev/null +++ b/docs/cli/transparency-alpha.md @@ -0,0 +1,14 @@ +```text +Set the alpha value for unfocused window transparency + +Usage: transparency-alpha + +Arguments: + + Alpha + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/transparency.md b/docs/cli/transparency.md new file mode 100644 index 00000000..77908627 --- /dev/null +++ b/docs/cli/transparency.md @@ -0,0 +1,14 @@ +```text +Enable or disable transparency for unfocused windows + +Usage: transparency + +Arguments: + + [possible values: enable, disable] + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 388c7245..133797fa 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -70,6 +70,8 @@ grows with the code: each part of the daemon that is added has its place here. - **Look**: how the compositor is asked to dress the windows, which it draws ([`Look`]): a border, with its width, its corner radius and two colors, and the animation of windows going to their places, with its duration and its easing curve. +- **Opacity**: how opaque a window is drawn, 0 to 255, a property of the window in the compositor, + which [`transparency_manager`] sets for the windows that do not have the focus. - **Effect**: a plugin of the compositor that changes how windows are drawn. KDE Rounded Corners is the effect that draws the border, and Geometry Change the one that animates windows. - **Compositor**: the program that owns the screen and the windows. On KDE Plasma it is @@ -822,6 +824,25 @@ once, when the effect is the stock one: every border is then the focused or the the look. [PLATFORM.md](PLATFORM.md#kwin-effects) has the effect, its settings and what was measured. +## Transparency + +The opacity of a window is a property KWin has, so komorebi sets it ([`Backend::set_opacity`], +which the KWin backend sends the bridge as an `opacity` command: `alpha / 255`) and the compositor +draws the window so. [`transparency_manager`] holds the settings, as statics that `Transparency`, +`ToggleTransparency` and `TransparencyAlpha` set and the `transparency` and `transparency_alpha` +keys of the file give a value, and the rules for the ignored windows (`TRANSPARENCY_BLACKLIST`, set +by the `transparency_ignore_rules` of the file). [`transparency_manager::apply`] is called +before the first layout and after every event and every message: it works out +[`transparency_manager::transparent_windows`], on the workspace each monitor shows (the window in +front in every container, unless the container has the focus on the focused monitor; a monocled +window only on a monitor that is not the focused one; none on a workspace that does not tile; none +that a rule ignores), and sends the backend only what differs +from what the window manager kept in [`WindowManager::opacity_applied`]. A window that should not +be see-through any more is made opaque, and with transparency off every window is. When komorebi +stops, [`transparency_manager::restore`] makes every window it changed opaque again. The border +effect draws a window from a texture that has its opacity in it, and the build komorebi installs +draws it again when the opacity changes ([PLATFORM.md](PLATFORM.md#the-patches)). + ## The NixOS module The flake exports one module under two names, `nixosModules.default` and @@ -918,6 +939,8 @@ module's unit. - [`border_manager`](../../komorebi/src/border_manager/mod.rs): the border settings, and the [`Look`] they make, which it asks the backend for. - [`animation`](../../komorebi/src/animation/mod.rs): the animation settings, which the look has. +- [`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, its settings and the state komorebi keeps of it. - [`process_command`](../../komorebi/src/process_command.rs): the thread that listens on the @@ -1067,6 +1090,10 @@ the fake. The window manager is its only caller, through [`backend`]. The contra | A command that changes a stack is carried out with the animation off, and the animation is on again after it | framework path: the arms of [`WindowManager::process_command`] for the stack messages swap `ANIMATION_ENABLED_GLOBAL` for false and put the value back | `the_animation_is_on_again_after_a_command_that_changes_a_stack` | none | | The `animation` key of the file is the animation settings, and a file without it leaves them | framework path: `StaticConfig::apply_globals` sets them only when the key is there, and `duration` and `style` only when the key has one | `the_animation_key_of_the_file_is_the_animation_settings` | none | | Every style is a curve Qt has | test: [`AnimationStyle::qt_curve`] is a `match` of every style, and the test checks each against its name without the "Ease" | `every_style_is_a_curve_qt_has`, the doctest of `qt_curve`, `vm-features` (section D: two curves are in different places at the same moment) | a cubic Bézier is an ease out | +| Only the windows the rules make see-through are, and only while transparency is on | framework path: [`transparency_manager::apply`] asks [`transparency_manager::transparent_windows`] and sends the difference from [`WindowManager::opacity_applied`] | `unfocused_windows_are_transparent_and_the_focused_one_is_not`, `turning_transparency_off_makes_everything_opaque_again`, `a_monocled_window_is_not_transparent`, `windows_the_rules_ignore_keep_their_opacity`, `vm-features` (section B) | none | +| The `transparency` keys of the file are the settings, and a key the file leaves out has the default | framework path: `StaticConfig::apply_globals` stores `transparency` and `transparency_alpha` whether the file has them or not, and adds the ignore rules to `TRANSPARENCY_BLACKLIST` | `the_transparency_keys_of_the_file_are_the_transparency_settings` | none | +| A window komorebi made see-through is opaque again when komorebi exits | framework path: [`WindowManager::stop`] and `main.rs` call [`transparency_manager::restore`] | `what_komorebi_made_see_through_is_opaque_again_when_it_exits` | `SIGKILL`: the windows stay as they were drawn | +| What the backend sends for an opacity is what the bridge sets | tests: the `opacity` command of [`fixtures`] is what the backend's test sends and what the bridge's test answers with, checking the window's `opacity` | `the_commands_of_a_session_go_to_the_bridge_as_the_bridges_tests_answer_it`, `what the bridge sends for a session is what the daemon's tests read`, `a window is given the opacity it is asked for, and one KWin has not got is given back` | none | | The effect komorebi loaded is unloaded, and the user's settings of it are put back, when komorebi stops using it or exits | framework path: the effect's state unloads what komorebi loaded, and [`Kwinrc`] puts the group back | `one_group_can_be_put_back_while_the_others_stay_changed`, `vm-look` | `SIGKILL`: the next run puts the settings back when it stops | | Queries never block on the compositor | convention only | none | the KWin backend's `cursor_pos` waits up to 250 ms | | Only the backend module reaches the compositor | convention only | none | none | @@ -1202,7 +1229,9 @@ A window is shown, and ends up on a tile: [`komorebi/tests/animation.rs`](../../komorebi/tests/animation.rs), the messages that set the animation, [`komorebi/tests/animation_config.rs`](../../komorebi/tests/animation_config.rs), its key of the file, and [`komorebi/tests/animation_stack.rs`](../../komorebi/tests/animation_stack.rs), - the stack commands that turn it off; [`komorebi/tests/border_colours.rs`](../../komorebi/tests/border_colours.rs) and + the stack commands that turn it off; [`komorebi/tests/transparency.rs`](../../komorebi/tests/transparency.rs) + and [`komorebi/tests/transparency_config.rs`](../../komorebi/tests/transparency_config.rs), + transparency and its keys of the file; [`komorebi/tests/border_colours.rs`](../../komorebi/tests/border_colours.rs) and [`komorebi/tests/borders_off.rs`](../../komorebi/tests/borders_off.rs), the color of each window's border, and none with borders off; [`nix/tests/vm/suites/look`](../../nix/tests/vm/suites/look/test.py), the border in a real @@ -1293,6 +1322,12 @@ A window is shown, and ends up on a tile: [`border_manager::send_notification`]: ../../komorebi/src/border_manager/mod.rs [`BORDER_DRAWN`]: ../../komorebi/src/border_manager/mod.rs [`animation`]: ../../komorebi/src/animation/mod.rs +[`transparency_manager`]: ../../komorebi/src/transparency_manager.rs +[`transparency_manager::apply`]: ../../komorebi/src/transparency_manager.rs +[`transparency_manager::transparent_windows`]: ../../komorebi/src/transparency_manager.rs +[`transparency_manager::restore`]: ../../komorebi/src/transparency_manager.rs +[`Backend::set_opacity`]: ../../komorebi/src/backend/mod.rs +[`WindowManager::opacity_applied`]: ../../komorebi/src/window_manager.rs [`animation::movement_animation`]: ../../komorebi/src/animation/mod.rs [`animation::movement_style`]: ../../komorebi/src/animation/mod.rs [`AnimationStyle::qt_curve`]: ../../komorebi/src/core/animation.rs diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index a27a3457..8645d6d9 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -460,6 +460,15 @@ one of Qt's curves, and is drawn as an ease out, the kind of curve a window movi wants. The stock Geometry Change has one curve, an exponential ease out, so komorebi's build of it reads a `Curve` setting ([PLATFORM.md](PLATFORM.md#the-patches)). +## Why does the window manager keep the opacity it gave each window? + +So that the backend is told only what changed. `transparency_manager::apply` +([`transparency_manager.rs`](../../komorebi/src/transparency_manager.rs)) is called after every +event and every message, and most of them change no window's opacity: the window manager keeps +the opacity it gave each window that is not opaque (`WindowManager::opacity_applied`), sends the +difference, makes a window opaque again when it should no longer be see-through (and only if it is +still there), and makes every one opaque when it stops. + ## Why 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 6828f6fd..9e5f1849 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -345,6 +345,10 @@ What the KWin scripting API offers a script, and what it does not, at time of wr uses, which `tsc` checks it against with ECMAScript 2016's library and nothing else. Node and TypeScript are needed only for those checks: in the session the bridge needs KWin alone. +- A window's `opacity` is a number from 0 to 1 that a script may set: `Window.opacity` is KWin's + own property, so komorebi sets the opacity of a window by setting it, and the effect that + draws the border has to draw the window again when it changes + ([The patches](#the-patches)). - `callDBus` sends a JavaScript number as a 32-bit integer, and a call whose arguments do not match the method's signature fails without a word. The bridge sends every argument as a JSON string. diff --git a/docs/index.md b/docs/index.md index 01f8824e..3d1d7be6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -59,8 +59,10 @@ explains the files of rules for particular applications it can name. [Quickstart and autostart](usage/quickstart-and-autostart.md) explains how to write an example configuration, how to start komorebi with Plasma without the module, and how to replace the configuration of a running daemon. -[Borders](usage/borders.md) explains how komorebi has KWin draw a border around each window, and -[Animation](usage/animation.md) how it has KWin animate the windows going to their places. +[Borders](usage/borders.md) explains how komorebi has KWin draw a border around each window, +[Animation](usage/animation.md) how it has KWin animate the windows going to their places, and +[Transparency](usage/transparency.md) how it makes the windows that do not have the focus +see-through. [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 b68694f1..1d226dfd 100644 --- a/docs/usage/configuration.md +++ b/docs/usage/configuration.md @@ -120,6 +120,17 @@ runs. settings as they are, and one that has it and leaves out `duration` or `style` leaves that one as it is; a value given for every kind of animation takes the settings of single kinds away. +### Transparency + +| Key | Default | What it does | +|---|---|---| +| `transparency` | `false` | Whether the windows that do not have the focus are see-through | +| `transparency_alpha` | `200` | How opaque they are, from 0 to 255 | +| `transparency_ignore_rules` | none | Rules for the windows that are never see-through | + +[Transparency](transparency.md) explains which windows are see-through. `transparency_ignore_rules` +is a list of rules, which [Rules](#rules) describes, and has no command. + ### Rules | Key | What it does | diff --git a/docs/usage/transparency.md b/docs/usage/transparency.md new file mode 100644 index 00000000..9adaf46c --- /dev/null +++ b/docs/usage/transparency.md @@ -0,0 +1,63 @@ +# Transparency + +komorebi can make the windows that do not have the focus see-through, so that the one you are +working in stands out. It does not draw anything itself: the opacity of a window is a property +KWin has, which komorebi sets. Transparency is off by default. + +## Turning it on + +[`komorebic transparency`](../cli/transparency.md) turns transparency on or off, +[`komorebic toggle-transparency`](../cli/toggle-transparency.md) switches it, and +[`komorebic transparency-alpha`](../cli/transparency-alpha.md) sets how opaque a see-through window +is, from 0 (not there at all) to 255 (not see-through): 200 by default. + +```sh +komorebic transparency enable +komorebic transparency-alpha 150 +komorebic toggle-transparency +``` + +## In komorebi.json + +The same settings are keys of [`komorebi.json`](configuration.md#transparency): `transparency`, +`transparency_alpha` and `transparency_ignore_rules`, a list of rules, as [Rules](rules.md) +explains them, for the windows that are never see-through. + +```json +{ + "transparency": true, + "transparency_alpha": 150, + "transparency_ignore_rules": [ + { "kind": "Exe", "id": "mpv", "matching_strategy": "Equals" } + ] +} +``` + +The file sets them when the daemon starts and when the file changes. A file that leaves out +`transparency` or `transparency_alpha` has the defaults, off and 200, so a change made with a +command does not survive the file changing. The ignore rules add up, as the other rules do. + +## Which windows are see-through + +On the workspace each monitor shows, the window in front in every container is see-through unless +its container has the focus on the focused monitor. A window on a monitor that is not the focused +one is see-through, whatever its container. On a workspace with a monocle the monocled window is +the only one that counts: it is opaque on the focused monitor and see-through on another. A +workspace that does not tile has no see-through windows, and neither does a window that a rule +keeps out of it: the rules are the `transparency_ignore_rules` of +[`komorebi.json`](configuration.md#transparency), which no command sets. + +Windows that are not in front, such as the other windows of a stack, are not on the screen and +are left as they are. With transparency off, every window is opaque. + +## What is put back + +When komorebi exits, every window it made see-through is opaque again. A window that closes needs +nothing. + +## The border + +The border effect draws a window from a texture that has the window's opacity in it. The build +of the effect that the flake installs draws a window again when its opacity changes, so the border +and the window change together. With the stock effect a change of opacity alone does not show +until the window changes. diff --git a/komorebi/src/backend/fake.rs b/komorebi/src/backend/fake.rs index 507e6235..2b78102c 100644 --- a/komorebi/src/backend/fake.rs +++ b/komorebi/src/backend/fake.rs @@ -70,6 +70,8 @@ pub enum Command { /// [`Backend::set_border_colours`]: the colors of each window's border, when they are not the /// ones given before. BorderColours(Vec<(u32, u32)>), + /// [`Backend::set_opacity`]: the window, and how opaque it was asked to be. + SetOpacity(u32, u8), } #[derive(Default)] @@ -93,6 +95,8 @@ struct State { window_ws: HashMap, /// the desktop each monitor (by id) shows shown: HashMap, + /// how opaque each window was last asked to be + opacity: HashMap, /// the border color each window was last given, `0xRRGGBB` border_colours: HashMap, /// the look last applied, so that asking for it again is not a command @@ -368,6 +372,12 @@ impl FakeBackend { state.shown.insert(monitor_id, idx); } + /// Returns how opaque the window manager last asked this window to be, 255 being not see-through + /// at all, which is what a window is until it is asked otherwise. + pub fn opacity_of(&self, id: u32) -> u8 { + self.state.lock().opacity.get(&id).copied().unwrap_or(255) + } + /// Returns the border color the window manager last gave this window, `0xRRGGBB`, if it gave /// it one. pub fn border_colour_of(&self, id: u32) -> Option { @@ -604,6 +614,12 @@ impl Backend for FakeBackend { Ok(state.borders_drawn && look.border.is_some()) } + fn set_opacity(&self, id: u32, alpha: u8) -> eyre::Result<()> { + self.record(id, Command::SetOpacity(id, alpha), |state| { + state.opacity.insert(id, alpha); + }) + } + fn set_border_colours(&self, colours: &[(u32, u32)]) -> eyre::Result { let mut state = self.state.lock(); let colours_now: HashMap = colours.iter().copied().collect(); @@ -945,6 +961,19 @@ mod tests { Ok(()) } + #[test] + fn a_window_is_opaque_until_it_is_asked_to_be_otherwise() -> eyre::Result<()> { + let fake = fake_with(&[1]); + assert_eq!(fake.opacity_of(1), 255); + + fake.set_opacity(1, 100)?; + + assert_eq!(fake.opacity_of(1), 100); + assert_eq!(fake.commands(), [Command::SetOpacity(1, 100)]); + assert!(fake.set_opacity(9, 100).is_err()); + Ok(()) + } + #[test] fn window_commands_leave_out_the_look() -> eyre::Result<()> { let fake = fake_with(&[1]); diff --git a/komorebi/src/backend/mod.rs b/komorebi/src/backend/mod.rs index 6e6291de..f5b6d53d 100644 --- a/komorebi/src/backend/mod.rs +++ b/komorebi/src/backend/mod.rs @@ -442,6 +442,31 @@ pub trait Backend: Send + Sync + 'static { Ok(false) } + /// Asks the compositor to draw the window with this opacity: 255 is not see-through at all. + /// The default does nothing. + /// + /// # Errors + /// + /// When the window does not exist or is no longer alive. + /// + /// # Example + /// + /// ```rust + /// use komorebi::backend::Backend; + /// use komorebi::backend::fake::FakeBackend; + /// + /// let fake = FakeBackend::with_one_monitor(); + /// fake.open_window(7, "foot", "foot", "a terminal"); + /// assert_eq!(fake.opacity_of(7), 255); + /// + /// fake.set_opacity(7, 150)?; + /// assert_eq!(fake.opacity_of(7), 150); + /// # Ok::<(), color_eyre::eyre::Report>(()) + /// ``` + fn set_opacity(&self, _id: u32, _alpha: u8) -> 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/core/mod.rs b/komorebi/src/core/mod.rs index 31b7ee52..e0c9d464 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -473,6 +473,9 @@ pub enum SocketMessage { // WatchConfiguration(bool), // CompleteConfiguration, // AltFocusHack(bool), + Transparency(bool), + ToggleTransparency, + TransparencyAlpha(u8), Animation(bool, Option), AnimationDuration(u64, Option), AnimationFps(u64), diff --git a/komorebi/src/kwin/bridge.js b/komorebi/src/kwin/bridge.js index 9b6dd047..fc1ac17d 100644 --- a/komorebi/src/kwin/bridge.js +++ b/komorebi/src/kwin/bridge.js @@ -80,9 +80,10 @@ * What the daemon sends: the answer to `Poll` is a list of batches, each a list of commands. A * window command names the window by its `id`: `geo` sets its frame, `min` minimizes it (`v`) or * brings it back, `maximize` maximizes it (`v`) or restores it, `desktop` puts it on the desktop - * `v` (and on no other), and `activate`, `raise` and `close` do what they say. `output_desktop` - * shows the desktop `v` on one output, leaving the others as they are. A cursor query is - * numbered by `token` so that its answer can be matched. + * `v` (and on no other), `opacity` draws it with the opacity `v` (0 to 1, 1 being not see-through + * at all), and `activate`, `raise` and `close` do what they say. `output_desktop` shows the desktop + * `v` on one output, leaving the others as they are. A cursor query is numbered by `token` so that + * its answer can be matched. * * @typedef {{ op: "cursor", token: number }} CursorQuery * @typedef {{ op: "output_desktop", output: string, v: string }} OutputDesktop @@ -93,7 +94,8 @@ * @typedef {{ op: "raise", id: string }} Raise * @typedef {{ op: "close", id: string }} Close * @typedef {{ op: "desktop", id: string, v: string }} SetDesktop - * @typedef {SetFrame | SetMinimized | SetMaximized | Activate | Raise | Close | SetDesktop} WindowCommand + * @typedef {{ op: "opacity", id: string, v: number }} SetOpacity + * @typedef {SetFrame | SetMinimized | SetMaximized | Activate | Raise | Close | SetDesktop | SetOpacity} WindowCommand * @typedef {CursorQuery | OutputDesktop | WindowCommand} Command * @typedef {{ batch: number, cmds: Command[] }} Batch */ @@ -470,6 +472,9 @@ function applyOne(c) { w.desktops = [d]; break; } + case "opacity": + w.opacity = c.v; + break; default: return false; } diff --git a/komorebi/src/kwin/bridge.test.js b/komorebi/src/kwin/bridge.test.js index 1a40b856..6cc02dd4 100644 --- a/komorebi/src/kwin/bridge.test.js +++ b/komorebi/src/kwin/bridge.test.js @@ -80,6 +80,7 @@ function window({ skipTaskbar: false, skipPager: false, skipSwitcher: false, + opacity: 1, fullScreen: false, maximizeMode: 0, minSize: { width: 0, height: 0 }, @@ -310,7 +311,7 @@ test("what the bridge sends for a session is what the daemon's tests read", () = // the client took the frame it was given to whole cells of its font terminal.frameGeometry = geometry(480.4, 270, 956, 532); - const [cursorQuery, windowCommands, workspaceCommands] = commands; + const [cursorQuery, windowCommands, workspaceCommands, opacityCommand] = commands; assert.equal(k.events().at(-1).seq, cursorQuery.after_seq); k.workspace.cursorPos = { x: 1200, y: 700.5 }; k.answer([cursorQuery.batch]); @@ -336,6 +337,13 @@ test("what the bridge sends for a session is what the daemon's tests read", () = k.workspace.setCurrentDesktopForScreen(first, DP1); assert.deepStrictEqual(k.events(), events); + + // and made see-through, which KWin does not report + assert.equal(k.events().at(-1).seq, opacityCommand.after_seq); + k.answer([opacityCommand.batch]); + assert.equal(editor.opacity, 0.2); + assert.deepStrictEqual(k.events(), events); + assert.deepStrictEqual(editor.frameGeometry, geometry(0, 0, 960, 1050)); assert.equal(k.workspace.activeWindow, editor); assert.deepStrictEqual(k.raised, [editor]); @@ -577,6 +585,17 @@ test("a command for a window KWin no longer has is given back, and the rest are assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 3, cmds: [gone], seq: 2 }); }); +test("a window is given the opacity it is asked for, and one KWin has not got is given back", () => { + const w = window({ id: "{w}" }); + const k = kwin({ windows: [w] }); + const gone = { op: "opacity", id: "{gone}", v: 0.5 }; + + k.answer([{ batch: 2, cmds: [{ op: "opacity", id: "{w}", v: 0.8 }, gone] }]); + + assert.equal(w.opacity, 0.8); + assert.deepStrictEqual(k.events().at(-1), { type: "failed", batch: 2, cmds: [gone], seq: 2 }); +}); + test("a command KWin throws on is printed and given back as failed", () => { const w = window({ id: "{w}" }); const k = kwin({ windows: [w] }); diff --git a/komorebi/src/kwin/fixtures/commands.json b/komorebi/src/kwin/fixtures/commands.json index 7d2c43a9..18f92e86 100644 --- a/komorebi/src/kwin/fixtures/commands.json +++ b/komorebi/src/kwin/fixtures/commands.json @@ -32,5 +32,14 @@ {"op": "output_desktop", "output": "DP-1", "v": "desktop-2"} ] } + }, + { + "after_seq": 20, + "batch": { + "batch": 4, + "cmds": [ + {"op": "opacity", "id": "{0e5a1c3b-0000-4000-8000-00000000000a}", "v": 0.2} + ] + } } ] diff --git a/komorebi/src/kwin/kwin-api.d.ts b/komorebi/src/kwin/kwin-api.d.ts index 7ff59960..63ba329e 100644 --- a/komorebi/src/kwin/kwin-api.d.ts +++ b/komorebi/src/kwin/kwin-api.d.ts @@ -74,6 +74,8 @@ interface KWinWindow { readonly skipPager: boolean; readonly skipSwitcher: boolean; minimized: boolean; + /** How opaque the window is drawn, 0 to 1: 1 is not see-through at all. */ + opacity: number; readonly fullScreen: boolean; /** `KWin::MaximizeMode`: 0 restored, 1 vertically, 2 horizontally, 3 both ways. */ readonly maximizeMode: number; diff --git a/komorebi/src/kwin/mod.rs b/komorebi/src/kwin/mod.rs index 09261fca..0fa16c67 100644 --- a/komorebi/src/kwin/mod.rs +++ b/komorebi/src/kwin/mod.rs @@ -902,6 +902,13 @@ impl Backend for KWinBackend { })? } + fn set_opacity(&self, id: u32, alpha: u8) -> eyre::Result<()> { + self.command( + id, + |uuid| json!({ "op": "opacity", "id": uuid, "v": f64::from(alpha) / 255.0 }), + ) + } + fn set_border_colours(&self, colours: &[(u32, u32)]) -> eyre::Result { let shared = self.shared.clone(); @@ -1037,7 +1044,7 @@ mod tests { serde_json::from_str(include_str!("fixtures/commands.json")).unwrap(); // what the window manager asks of the backend, batch by batch - let asks: [fn(&KWinBackend); 3] = [ + let asks: [fn(&KWinBackend); 4] = [ |backend| { // nothing answers the query here, so the pointer is where the snapshot had it assert_eq!(backend.cursor_pos(), Some((481, 525))); @@ -1069,6 +1076,10 @@ mod tests { assert_eq!(backend.window_workspace(1), Some(1)); assert_eq!(backend.current_workspaces(), [(monitor, 1)]); }, + |backend| { + // 51 of 255 is a fifth + backend.set_opacity(1, 51).unwrap(); + }, ]; assert_eq!(asks.len(), commands.len()); diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 6cf0d5ba..36d4c566 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -13,7 +13,8 @@ //! //! 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, and [`animation`] holds how windows are animated going to their places. +//! the borders, [`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 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 @@ -68,6 +69,7 @@ pub mod process_command; pub mod process_event; pub mod state; pub mod static_config; +pub mod transparency_manager; pub mod window; pub mod window_manager; pub mod window_manager_event; @@ -151,6 +153,8 @@ lazy_static! { Arc::new(Mutex::new(HashMap::new())); /// Windows that are tiled even when an ignore rule covers them (`ManageRule`) static ref MANAGE_IDENTIFIERS: Arc>> = Arc::new(Mutex::new(vec![])); + /// Windows that are never made see-through, whatever the rules of the transparency say + pub static ref TRANSPARENCY_BLACKLIST: Arc>> = Arc::new(Mutex::new(vec![])); /// Windows that are never tiled, unless a manage rule says otherwise. Most of what would belong /// here (the panel, krunner, popups) is not a normal window and is filtered before rules run. pub static ref IGNORE_IDENTIFIERS: Arc>> = Arc::new(Mutex::new( diff --git a/komorebi/src/main.rs b/komorebi/src/main.rs index e40a9965..1a2e7fec 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/main.rs @@ -234,10 +234,12 @@ fn main() -> eyre::Result<()> { wm.lock().retile_all(false)?; - // and what the windows that are already there look like: their border colors + // and what the windows that are already there look like: their border colors, how see-through + // they are { - let wm = wm.lock(); + let mut wm = wm.lock(); border_manager::update_colours(&wm); + komorebi::transparency_manager::apply(&mut wm); } listen_for_commands(wm.clone()); @@ -256,6 +258,7 @@ fn main() -> eyre::Result<()> { { let mut wm = wm.lock(); wm.restore_all_windows(false)?; + komorebi::transparency_manager::restore(&mut wm); } backend::backend().shutdown(); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 664a164c..bde3b7ec 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -11,8 +11,8 @@ //! - **VisibleWindows**: what the compositor says about each window that can be seen on the //! workspace each monitor shows, by the id of the monitor, as JSON. //! - **Query**: one value as text, the answer to a [`StateQuery`]. -//! - **GlobalState**: the ignore and the manage rules and the data directory ([`GlobalState`]), as -//! JSON. +//! - **GlobalState**: the ignore and the manage rules, the transparency settings and the data +//! directory ([`GlobalState`]), as JSON. //! - **SessionFloatRules**: the float rules **SessionFloatRule** added, as JSON. //! - **DebugWindow**: what [`Window::should_manage`] read of a window and which rules matched it //! ([`RuleDebug`]), as JSON, or nothing for a window that is not there. @@ -182,6 +182,10 @@ //! handled. **BorderColour** sets the color of the border of one kind of window //! ([`WindowKind`]), and every message, once handled, tells the backend the color of each //! window's border ([`border_manager::update_colours`]). +//! - **Transparency** and **ToggleTransparency** set whether the windows that do not have the +//! focus are see-through, and **TransparencyAlpha** how opaque they are, 0 to 255; every message, +//! once handled, has [`transparency_manager::apply`] make the windows as see-through as that +//! says. //! - **Animation** sets whether windows are animated going to their places, **AnimationDuration** //! for how long, **AnimationStyle** the easing curve, and **AnimationFps** the frame rate that is //! stored and has nothing to map to (the compositor animates at the refresh rate of the @@ -240,6 +244,7 @@ use crate::notify_subscribers; use crate::state::GlobalState; use crate::state::State; use crate::static_config::StaticConfig; +use crate::transparency_manager; use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; @@ -1971,6 +1976,16 @@ impl WindowManager { border_manager::destroy_all_borders()?; } } + SocketMessage::Transparency(enable) => { + transparency_manager::TRANSPARENCY_ENABLED.store(enable, Ordering::SeqCst); + } + SocketMessage::ToggleTransparency => { + let current = transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst); + transparency_manager::TRANSPARENCY_ENABLED.store(!current, Ordering::SeqCst); + } + SocketMessage::TransparencyAlpha(alpha) => { + transparency_manager::TRANSPARENCY_ALPHA.store(alpha, Ordering::SeqCst); + } SocketMessage::BorderColour(kind, r, g, b) => match kind { WindowKind::Single => { border_manager::FOCUSED.store(border_manager::pack(r, g, b), Ordering::SeqCst); @@ -2050,6 +2065,7 @@ impl WindowManager { border_manager::send_notification(); border_manager::update_colours(self); + transparency_manager::apply(self); tracing::info!("processed command: {message}"); diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index e74b0d14..990457ce 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -50,7 +50,8 @@ //! Once an event about a managed window has been handled, every subscriber is sent a notification //! of it ([`notify_subscribers`]), the backend is asked for the look again //! ([`border_manager::send_notification`]), which it does nothing about unless a setting changed, -//! and told the color of each window's border ([`border_manager::update_colours`]). +//! told the color of each window's border ([`border_manager::update_colours`]), and the windows are +//! made as see-through as the settings say ([`transparency_manager::apply`]). //! //! [`Window::should_manage`]: crate::window::Window::should_manage //! [`Monitor::assign_windows_to_workspaces`]: crate::monitor::Monitor::assign_windows_to_workspaces @@ -68,6 +69,7 @@ use crate::core::Layout; use crate::core::WindowContainerBehaviour; use crate::notify_subscribers; use crate::state::State; +use crate::transparency_manager; use crate::window::RuleDebug; use crate::window::should_act; use crate::window_manager::WindowManager; @@ -145,6 +147,7 @@ impl WindowManager { // other windows are in view border_manager::send_notification(); border_manager::update_colours(self); + transparency_manager::apply(self); return result; } @@ -517,6 +520,7 @@ impl WindowManager { border_manager::send_notification(); border_manager::update_colours(self); + transparency_manager::apply(self); Ok(()) } diff --git a/komorebi/src/state.rs b/komorebi/src/state.rs index 0752382a..5f360b1a 100644 --- a/komorebi/src/state.rs +++ b/komorebi/src/state.rs @@ -5,8 +5,8 @@ //! subscribers in every [`Notification`]. [`State::has_been_modified`] decides whether an event or //! a message changed it, for the subscribers that want a notification only then. //! -//! [`GlobalState`] is what the daemon has besides the window manager, the rules and the data -//! directory, which it writes in answer to `GlobalState`. +//! [`GlobalState`] is what the daemon has besides the window manager, the rules, the transparency +//! and the data directory, which it writes in answer to `GlobalState`. //! //! [`SocketMessage::State`]: crate::core::SocketMessage::State //! [`Notification`]: crate::Notification @@ -16,6 +16,7 @@ use crate::DISPLAY_INDEX_PREFERENCES; use crate::HOME_DIR; use crate::IGNORE_IDENTIFIERS; use crate::MANAGE_IDENTIFIERS; +use crate::TRANSPARENCY_BLACKLIST; use crate::WORKSPACE_MATCHING_RULES; use crate::core::MonocleFocusBehaviour; use crate::core::MoveBehaviour; @@ -36,8 +37,8 @@ use std::path::PathBuf; /// What the daemon has that is not part of the window manager, as it answers /// [`SocketMessage::GlobalState`](crate::core::SocketMessage::GlobalState): the ignore and the manage -/// rules, the indices the user gave the monitors, the workspace rules, and the configuration and -/// the data directories +/// rules, what the transparency is, the indices the user gave the monitors, the workspace rules, +/// and the configuration and the data directories /// /// # Example /// @@ -49,6 +50,9 @@ use std::path::PathBuf; /// let json = serde_json::to_string(&state.ignore_identifiers)?; /// assert!(json.contains(r#""id":"org.kde.plasmashell""#), "{json}"); /// assert!(state.manage_identifiers.is_empty()); +/// // nothing is see-through until it is asked for +/// assert!(!state.transparency_enabled); +/// assert_eq!(state.transparency_alpha, 200); /// assert!(state.display_index_preferences.is_empty()); /// assert!(state.workspace_rules.is_empty()); /// assert_eq!(state.configuration_dir, *komorebi::HOME_DIR); @@ -72,6 +76,12 @@ pub struct GlobalState { // pub stackbar_tab_width: i32, // pub stackbar_height: i32, // pub remove_titlebars: bool, + /// Whether the windows that do not have the focus are see-through + pub transparency_enabled: bool, + /// How opaque a see-through window is, from 0 to 255 + pub transparency_alpha: u8, + /// The rules for the windows that are never see-through + pub transparency_blacklist: Vec, // #[serde(alias = "float_identifiers")] pub ignore_identifiers: Vec, pub manage_identifiers: Vec, @@ -91,6 +101,11 @@ pub struct GlobalState { impl Default for GlobalState { fn default() -> Self { Self { + transparency_enabled: crate::transparency_manager::TRANSPARENCY_ENABLED + .load(std::sync::atomic::Ordering::SeqCst), + transparency_alpha: crate::transparency_manager::TRANSPARENCY_ALPHA + .load(std::sync::atomic::Ordering::SeqCst), + transparency_blacklist: TRANSPARENCY_BLACKLIST.lock().clone(), ignore_identifiers: IGNORE_IDENTIFIERS.lock().clone(), manage_identifiers: MANAGE_IDENTIFIERS.lock().clone(), display_index_preferences: DISPLAY_INDEX_PREFERENCES.read().clone(), diff --git a/komorebi/src/static_config.rs b/komorebi/src/static_config.rs index 82274dc1..ff369109 100644 --- a/komorebi/src/static_config.rs +++ b/komorebi/src/static_config.rs @@ -36,6 +36,7 @@ use crate::IGNORE_IDENTIFIERS; use crate::LAYOUT_DEFAULTS; use crate::MANAGE_IDENTIFIERS; use crate::REGEX_IDENTIFIERS; +use crate::TRANSPARENCY_BLACKLIST; use crate::WORKSPACE_MATCHING_RULES; use crate::animation::ANIMATION_DURATION_GLOBAL; use crate::animation::ANIMATION_DURATION_PER_ANIMATION; @@ -72,6 +73,7 @@ use crate::core::config_generation::WorkspaceMatchingRule; use crate::core::pathext::ResolvedPathBuf; use crate::monitor::Monitor; use crate::ring::Ring; +use crate::transparency_manager; use crate::window::AspectRatio; use crate::window::PredefinedAspectRatio; use crate::window_manager::WindowManager; @@ -444,6 +446,15 @@ pub struct StaticConfig { // /// Active window border implementation (default: Komorebi) // #[serde(skip_serializing_if = "Option::is_none")] // pub border_implementation: Option, + /// Add transparency to unfocused windows (default: false) + #[serde(skip_serializing_if = "Option::is_none")] + pub transparency: Option, + /// Alpha value for unfocused window transparency [[0-255]] (default: 200) + #[serde(skip_serializing_if = "Option::is_none")] + pub transparency_alpha: Option, + /// Individual window transparency ignore rules + #[serde(skip_serializing_if = "Option::is_none")] + pub transparency_ignore_rules: Option>, /// Global default workspace padding #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(extend("default" = DEFAULT_WORKSPACE_PADDING)))] @@ -624,6 +635,13 @@ impl From<&WindowManager> for StaticConfig { border_offset: Option::from(border_manager::BORDER_OFFSET.load(Ordering::SeqCst)), border_radius: Option::from(border_manager::BORDER_RADIUS.load(Ordering::SeqCst)), border: Option::from(border_manager::BORDER_ENABLED.load(Ordering::SeqCst)), + transparency: Option::from( + transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst), + ), + transparency_alpha: Option::from( + transparency_manager::TRANSPARENCY_ALPHA.load(Ordering::SeqCst), + ), + transparency_ignore_rules: None, // border_style: Option::from(STYLE.load()), // border_z_order: None, // border_implementation: Option::from(IMPLEMENTATION.load()), @@ -796,6 +814,11 @@ impl StaticConfig { // border_manager::send_notification(None); // } // + transparency_manager::TRANSPARENCY_ENABLED + .store(self.transparency.unwrap_or(false), Ordering::SeqCst); + transparency_manager::TRANSPARENCY_ALPHA + .store(self.transparency_alpha.unwrap_or(200), Ordering::SeqCst); + let mut ignore_identifiers = IGNORE_IDENTIFIERS.lock(); let mut regex_identifiers = REGEX_IDENTIFIERS.lock(); let mut manage_identifiers = MANAGE_IDENTIFIERS.lock(); @@ -803,6 +826,7 @@ impl StaticConfig { // let mut object_name_change_identifiers = OBJECT_NAME_CHANGE_ON_LAUNCH.lock(); // let mut object_name_change_title_ignore_list = OBJECT_NAME_CHANGE_TITLE_IGNORE_LIST.lock(); // let mut layered_identifiers = LAYERED_WHITELIST.lock(); + let mut transparency_blacklist = TRANSPARENCY_BLACKLIST.lock(); // let mut slow_application_identifiers = SLOW_APPLICATION_IDENTIFIERS.lock(); let mut floating_applications = FLOATING_APPLICATIONS.lock(); // let mut no_titlebar_applications = NO_TITLEBAR.lock(); @@ -857,6 +881,10 @@ impl StaticConfig { // )?; // } // + if let Some(rules) = &mut self.transparency_ignore_rules { + populate_rules(rules, &mut transparency_blacklist, &mut regex_identifiers)?; + } + // // if let Some(rules) = &mut self.slow_application_identifiers { // populate_rules( // rules, @@ -1055,6 +1083,7 @@ impl StaticConfig { .unmanaged_window_operation_behaviour .unwrap_or(OperationBehaviour::Op), resize_delta: value.resize_delta.unwrap_or(DEFAULT_RESIZE_DELTA), + opacity_applied: HashMap::new(), mouse_follows_focus: value .mouse_follows_focus .unwrap_or(DEFAULT_MOUSE_FOLLOWS_FOCUS), diff --git a/komorebi/src/transparency_manager.rs b/komorebi/src/transparency_manager.rs new file mode 100644 index 00000000..a2d4ac87 --- /dev/null +++ b/komorebi/src/transparency_manager.rs @@ -0,0 +1,153 @@ +//! Transparency for the windows that do not have the focus (`transparency`, `transparency_alpha`, +//! `transparency_ignore_rules`, `komorebic transparency`). +//! +//! komorebi decides which windows are see-through, and the compositor draws them so: the opacity +//! of a window is a property of KWin's, which the backend sets. [`apply`] is called whenever +//! anything could have changed, and sends only what differs from what it sent before. +//! +//! The rules, on the workspace each monitor shows: the focused window of every container is +//! see-through unless the container has the focus on the focused monitor; a monocled window is +//! opaque, unless it is on a monitor that is not the focused one; a workspace that does not tile +//! has no transparent windows; ignored windows never are. These are the rules of komorebi for +//! Windows, where the settings come from. + +use crate::REGEX_IDENTIFIERS; +use crate::TRANSPARENCY_BLACKLIST; +use crate::backend::backend; +use crate::window::Window; +use crate::window::should_act; +use crate::window_manager::WindowManager; +use std::collections::HashSet; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicU8; +use std::sync::atomic::Ordering; + +pub static TRANSPARENCY_ENABLED: AtomicBool = AtomicBool::new(false); +pub static TRANSPARENCY_ALPHA: AtomicU8 = AtomicU8::new(200); + +/// The opacity of a window that is not see-through at all. +const OPAQUE: u8 = 255; + +/// Returns true if and only if `transparency_ignore_rules` match the window. A window whose title, +/// executable, class or path cannot be read is not ignored. +fn ignored(window: Window) -> bool { + let blacklist = TRANSPARENCY_BLACKLIST.lock(); + if blacklist.is_empty() { + return false; + } + + let (Some(title), Some(exe), Some(class), Some(path)) = + (window.title(), window.exe(), window.class(), window.path()) + else { + return false; + }; + + let regex_identifiers = REGEX_IDENTIFIERS.lock(); + should_act( + &title, + &exe, + &[class.as_str()], + &path.to_string_lossy(), + &blacklist, + ®ex_identifiers, + ) + .is_some() +} + +/// Returns the windows that should be see-through now, by the rules in the [module docs](self), +/// whether transparency is on or not. +pub fn transparent_windows(wm: &WindowManager) -> Vec { + let mut out = vec![]; + let focused_monitor_idx = wm.focused_monitor_idx(); + + for (monitor_idx, monitor) in wm.monitors().iter().enumerate() { + let on_focused_monitor = monitor_idx == focused_monitor_idx; + + // only what each monitor shows; the rest is not on screen + let Some(workspace) = monitor.focused_workspace() else { + continue; + }; + + if !workspace.tile { + continue; + } + + if let Some(monocle) = &workspace.monocle_container { + if !on_focused_monitor + && let Some(window) = monocle.focused_window() + && !ignored(*window) + { + out.push(window.id); + } + + continue; + } + + for (idx, container) in workspace.containers().iter().enumerate() { + if on_focused_monitor && idx == workspace.focused_container_idx() { + continue; + } + + if let Some(window) = container.focused_window() + && !ignored(*window) + { + out.push(window.id); + } + } + } + + out +} + +/// Makes the windows as see-through as the settings and the state of the window manager say. +/// +/// The backend is told only what differs from what it was last told, which the window manager +/// keeps in [`WindowManager::opacity_applied`]: windows that should not be see-through any more +/// are made opaque, and the others are given [`TRANSPARENCY_ALPHA`]. With transparency off, every +/// window is opaque. A failure is logged. +pub fn apply(wm: &mut WindowManager) { + let alpha = TRANSPARENCY_ALPHA.load(Ordering::SeqCst); + let wanted: HashSet = if TRANSPARENCY_ENABLED.load(Ordering::SeqCst) { + transparent_windows(wm).into_iter().collect() + } else { + HashSet::new() + }; + + // opaque again: everything that was see-through and should not be any more + let no_longer: Vec = wm + .opacity_applied + .keys() + .filter(|id| !wanted.contains(id)) + .copied() + .collect(); + for id in no_longer { + if backend().is_window(id) + && let Err(error) = backend().set_opacity(id, OPAQUE) + { + tracing::warn!("could not make window {id} opaque: {error}"); + } + wm.opacity_applied.remove(&id); + } + + for id in wanted { + if wm.opacity_applied.get(&id) == Some(&alpha) { + continue; + } + + match backend().set_opacity(id, alpha) { + Ok(()) => { + wm.opacity_applied.insert(id, alpha); + } + Err(error) => tracing::warn!("could not make window {id} transparent: {error}"), + } + } +} + +/// Makes every window komorebi made see-through opaque again, when komorebi exits. +pub fn restore(wm: &mut WindowManager) { + for (id, _) in wm.opacity_applied.drain() { + if backend().is_window(id) { + let _ = backend().set_opacity(id, OPAQUE); + } + } +} diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index d504a120..df144fa6 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -195,6 +195,11 @@ impl Window { backend().set_rect(self.id, rect) } + /// Asks the compositor to draw the window with this opacity, 255 being not see-through at all + pub fn set_opacity(self, alpha: u8) -> eyre::Result<()> { + backend().set_opacity(self.id, alpha) + } + pub fn focus(self, mouse_follows_focus: bool) -> eyre::Result<()> { backend().focus(self.id, mouse_follows_focus) } diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index a073f5b5..a07ae74c 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -138,6 +138,9 @@ pub struct WindowManager { pub monocle_focus_behaviour: MonocleFocusBehaviour, /// Whether the pointer is moved to the window that is given the focus, which is the default pub mouse_follows_focus: bool, + /// The opacity each window was last given by [`crate::transparency_manager`], for the ones that + /// are not opaque + pub opacity_applied: HashMap, pub work_area_offset: Option, /// The events the backend has reported and the window manager has yet to handle, from /// [`crate::window_manager_event_listener`] @@ -227,6 +230,7 @@ impl WindowManager { cross_monitor_move_behaviour: Default::default(), cross_boundary_behaviour: Default::default(), monocle_focus_behaviour: MonocleFocusBehaviour::default(), + opacity_applied: HashMap::new(), mouse_follows_focus: true, work_area_offset: None, incoming_events: incoming, @@ -1307,10 +1311,11 @@ impl WindowManager { } /// Stops the daemon: brings back the windows it has hidden, unless `ignore_restore` is set - /// ([`WindowManager::restore_all_windows`]), connects to every subscriber and closes the - /// connection without writing anything, removes the command socket, lets the backend give up - /// what it set up in the compositor (the desktop hidden windows are parked on), and exits the - /// process with status 0 + /// ([`WindowManager::restore_all_windows`]), makes every window komorebi made see-through + /// opaque again ([`crate::transparency_manager::restore`]), connects to every subscriber and + /// closes the connection without writing anything, removes the command socket, lets the + /// backend give up what it set up in the compositor (the desktop hidden windows are parked + /// on), and exits the process with status 0 /// /// # Errors /// @@ -1323,6 +1328,8 @@ impl WindowManager { self.restore_all_windows(ignore_restore)?; + crate::transparency_manager::restore(self); + let sockets = SUBSCRIPTION_SOCKETS.lock(); for path in (*sockets).values() { if let Ok(stream) = UnixStream::connect(path) { diff --git a/komorebi/tests/config_parity.rs b/komorebi/tests/config_parity.rs index e11bd04c..54a9b77d 100644 --- a/komorebi/tests/config_parity.rs +++ b/komorebi/tests/config_parity.rs @@ -45,10 +45,6 @@ const WINDOWS_ONLY: &[&str] = &[ const NOT_YET: &[&str] = &[ // a color for each kind of window's border, whose type is komorebi-themes' (49) "border_colours", - // transparency (47) - "transparency", - "transparency_alpha", - "transparency_ignore_rules", // focus follows mouse (48) "focus_follows_mouse", // themes (49) diff --git a/komorebi/tests/transparency.rs b/komorebi/tests/transparency.rs new file mode 100644 index 00000000..016a6b6f --- /dev/null +++ b/komorebi/tests/transparency.rs @@ -0,0 +1,185 @@ +//! Transparency for the windows that do not have focus, against an in-memory desktop. +//! +//! Window ids are in the 30_000s; the transparency settings and the rule tables are process-wide, +//! so the tests take turns. + +use komorebi::TRANSPARENCY_BLACKLIST; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::ApplicationIdentifier; +use komorebi::core::SocketMessage; +use komorebi::core::config_generation::IdWithIdentifier; +use komorebi::core::config_generation::MatchingRule; +use komorebi::core::config_generation::MatchingStrategy; +use komorebi::state::GlobalState; +use komorebi::transparency_manager; +use komorebi::transparency_manager::TRANSPARENCY_ALPHA; +use komorebi::transparency_manager::TRANSPARENCY_ENABLED; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use std::sync::Arc; + +fn added(id: u32) -> WindowManagerEvent { + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + ) +} + +fn focused(id: u32) -> WindowManagerEvent { + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(id), + ) +} + +fn desktop() -> (Arc, WindowManager) { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let (_sender, receiver) = crossbeam_channel::bounded(1); + static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let socket = std::path::PathBuf::from(format!( + "/tmp/kmf-{}-{}.sock", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + )); + + let wm = with_backend(fake.clone(), || { + let mut wm = WindowManager::new(receiver, Some(socket)).unwrap(); + wm.init().unwrap(); + wm + }); + + (fake, wm) +} + +fn tiled(first: u32, count: u32) -> (Arc, WindowManager) { + let (fake, mut wm) = desktop(); + with_backend(fake.clone(), || { + for id in first..first + count { + fake.open_window(id, "foot", "foot", &format!("terminal {id}")); + wm.process_event(added(id)).unwrap(); + } + }); + (fake, wm) +} + +fn command(fake: &Arc, wm: &mut WindowManager, message: SocketMessage) { + with_backend(fake.clone(), || wm.process_command(message, Vec::new())).unwrap(); +} + +static TRANSPARENCY: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// The settings are process-wide, as they are on Windows: one test at a time, from the defaults +fn transparency_settings() -> std::sync::MutexGuard<'static, ()> { + let guard = TRANSPARENCY.lock().unwrap_or_else(|e| e.into_inner()); + TRANSPARENCY_ENABLED.store(false, std::sync::atomic::Ordering::SeqCst); + TRANSPARENCY_ALPHA.store(200, std::sync::atomic::Ordering::SeqCst); + TRANSPARENCY_BLACKLIST.lock().clear(); + guard +} + +#[test] +fn unfocused_windows_are_transparent_and_the_focused_one_is_not() { + let _settings = transparency_settings(); + let (fake, mut wm) = tiled(30_001, 3); + command(&fake, &mut wm, SocketMessage::Transparency(true)); + command(&fake, &mut wm, SocketMessage::TransparencyAlpha(150)); + + // 30_003 is the one with focus + assert_eq!(fake.opacity_of(30_003), 255); + assert_eq!(fake.opacity_of(30_001), 150); + assert_eq!(fake.opacity_of(30_002), 150); + + // focus moves: the opacity goes with it + with_backend(fake.clone(), || wm.process_event(focused(30_001))).unwrap(); + assert_eq!(fake.opacity_of(30_001), 255); + assert_eq!(fake.opacity_of(30_003), 150); +} + +#[test] +fn turning_transparency_off_makes_everything_opaque_again() { + let _settings = transparency_settings(); + let (fake, mut wm) = tiled(30_011, 2); + command(&fake, &mut wm, SocketMessage::Transparency(true)); + assert_eq!(fake.opacity_of(30_011), 200, "the default alpha"); + + command(&fake, &mut wm, SocketMessage::ToggleTransparency); + assert_eq!(fake.opacity_of(30_011), 255); + assert_eq!(fake.opacity_of(30_012), 255); + + command(&fake, &mut wm, SocketMessage::ToggleTransparency); + assert_eq!(fake.opacity_of(30_011), 200); +} + +#[test] +fn a_monocled_window_is_not_transparent() { + let _settings = transparency_settings(); + let (fake, mut wm) = tiled(30_021, 3); + command(&fake, &mut wm, SocketMessage::Transparency(true)); + command(&fake, &mut wm, SocketMessage::ToggleMonocle); + + assert_eq!(fake.opacity_of(30_023), 255, "the one filling the screen"); +} + +#[test] +fn windows_the_rules_ignore_keep_their_opacity() { + let _settings = transparency_settings(); + let (fake, mut wm) = desktop(); + with_backend(fake.clone(), || { + fake.open_window(30_031, "foot", "foot", "terminal"); + fake.open_window(30_032, "mpv", "mpv-player", "video"); + fake.open_window(30_033, "foot", "foot", "terminal 2"); + wm.process_event(added(30_031)).unwrap(); + wm.process_event(added(30_032)).unwrap(); + wm.process_event(added(30_033)).unwrap(); + }); + + TRANSPARENCY_BLACKLIST + .lock() + .push(MatchingRule::Simple(IdWithIdentifier { + kind: ApplicationIdentifier::Class, + id: String::from("mpv-player"), + matching_strategy: Some(MatchingStrategy::Equals), + })); + + command(&fake, &mut wm, SocketMessage::Transparency(true)); + + assert_eq!(fake.opacity_of(30_031), 200); + assert_eq!( + fake.opacity_of(30_032), + 255, + "a video player is never see-through" + ); + + TRANSPARENCY_BLACKLIST.lock().clear(); +} + +#[test] +fn what_komorebi_made_see_through_is_opaque_again_when_it_exits() { + let _settings = transparency_settings(); + let (fake, mut wm) = tiled(30_041, 2); + command(&fake, &mut wm, SocketMessage::Transparency(true)); + assert_eq!(fake.opacity_of(30_041), 200); + + with_backend(fake.clone(), || transparency_manager::restore(&mut wm)); + + assert_eq!(fake.opacity_of(30_041), 255); + assert!(wm.opacity_applied.is_empty()); +} + +#[test] +fn the_global_state_says_what_the_transparency_is() { + let _settings = transparency_settings(); + let (fake, mut wm) = desktop(); + assert!(!GlobalState::default().transparency_enabled); + + command(&fake, &mut wm, SocketMessage::Transparency(true)); + command(&fake, &mut wm, SocketMessage::TransparencyAlpha(90)); + + let state = GlobalState::default(); + assert!(state.transparency_enabled); + assert_eq!(state.transparency_alpha, 90); +} diff --git a/komorebi/tests/transparency_config.rs b/komorebi/tests/transparency_config.rs new file mode 100644 index 00000000..2fb104c6 --- /dev/null +++ b/komorebi/tests/transparency_config.rs @@ -0,0 +1,128 @@ +//! The transparency keys of `komorebi.json` are the transparency settings: the file sets them when +//! the daemon starts and when it is read again (a message that tiles and applies the opacity), a key +//! it leaves out has the default, the ignore rules keep windows opaque, and the settings come out +//! again in the configuration the daemon generates. +//! +//! This file has one test because it changes the process-wide transparency settings, which every +//! other test that tiles windows would see. + +use color_eyre::eyre; +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::SocketMessage; +use komorebi::static_config::StaticConfig; +use komorebi::transparency_manager; +use komorebi::window::Window; +use komorebi::window_manager::WindowManager; +use komorebi::window_manager_event::KWinNotification; +use komorebi::window_manager_event::SystemNotification; +use komorebi::window_manager_event::WindowManagerEvent; +use parking_lot::Mutex; +use std::os::unix::net::UnixListener; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +fn write_config(name: &str, json: &str) -> PathBuf { + let path = PathBuf::from(format!( + "/tmp/kmb-transp-{name}-{}.json", + std::process::id() + )); + std::fs::write(&path, json).unwrap(); + path +} + +#[test] +fn the_transparency_keys_of_the_file_are_the_transparency_settings() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + + let path = write_config( + "on", + r#"{ + "transparency": true, + "transparency_alpha": 120, + "transparency_ignore_rules": [ + { "kind": "Exe", "id": "mpv", "matching_strategy": "Equals" } + ] + }"#, + ); + let (_sender, receiver) = crossbeam_channel::bounded(1); + let socket = PathBuf::from(format!("/tmp/kmb-transp-{}.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(Mutex::new(wm)); + StaticConfig::postload(&path, &wm).unwrap(); + let _ = std::fs::remove_file(&socket); + + assert!(transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst)); + assert_eq!( + transparency_manager::TRANSPARENCY_ALPHA.load(Ordering::SeqCst), + 120 + ); + + // two windows, one of which the rules keep opaque, and the one without the focus is see-through + with_backend(fake.clone(), || { + for (id, exe) in [(46_001, "mpv"), (46_002, "foot"), (46_003, "foot")] { + fake.open_window(id, exe, exe, &format!("window {id}")); + wm.lock() + .process_event(WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(id), + )) + .unwrap(); + } + }); + assert_eq!(fake.opacity_of(46_002), 120, "a window without the focus"); + assert_eq!(fake.opacity_of(46_003), 255, "the one with the focus"); + assert_eq!(fake.opacity_of(46_001), 255, "a window the rules ignore"); + + // and they come out again in the generated configuration + let generated = StaticConfig::from(&*wm.lock()); + assert_eq!(generated.transparency, Some(true)); + assert_eq!(generated.transparency_alpha, Some(120)); + + // a file that is read again and leaves the keys out has the defaults + let empty = write_config("empty", "{}"); + with_backend(fake.clone(), || { + wm.lock() + .process_command( + SocketMessage::ReloadStaticConfiguration(empty.clone()), + vec![], + ) + .unwrap(); + }); + assert!(!transparency_manager::TRANSPARENCY_ENABLED.load(Ordering::SeqCst)); + assert_eq!( + transparency_manager::TRANSPARENCY_ALPHA.load(Ordering::SeqCst), + 200 + ); + assert_eq!(fake.opacity_of(46_002), 255, "opaque again"); + + // the ignore rules add up, and are not asked again + let more = write_config( + "more", + r#"{ "transparency_ignore_rules": [ + { "kind": "Exe", "id": "mpv", "matching_strategy": "Equals" }, + { "kind": "Class", "id": "vlc", "matching_strategy": "Equals" } + ] }"#, + ); + with_backend(fake.clone(), || { + wm.lock() + .process_command( + SocketMessage::ReloadStaticConfiguration(more.clone()), + vec![], + ) + .unwrap(); + }); + assert_eq!(komorebi::TRANSPARENCY_BLACKLIST.lock().len(), 2); + + for file in [path, empty, more] { + let _ = std::fs::remove_file(file); + } +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 6082125e..18fe4dc9 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -69,6 +69,8 @@ //! - `border` sets whether the compositor draws a border around each window, `border-colour` the //! color of the border of a kind of window, and `border-width` and `border-offset` the room the //! layout leaves for it. +//! - `transparency` and `toggle-transparency` set whether the windows that do not have the focus +//! are see-through, and `transparency-alpha` how opaque they are. //! - `animation`, `animation-duration` and `animation-style` set whether windows are animated going //! to their places, for how long and with what easing, and `animation-fps` the frame rate that //! is stored and ignored. @@ -213,6 +215,7 @@ gen_enum_subcommand_args! { CycleLayout: CycleDirection, // WatchConfiguration: BooleanState, MouseFollowsFocus: BooleanState, + Transparency: BooleanState, Query: StateQuery, CrossMonitorMoveBehaviour: MoveBehaviour, UnmanagedWindowOperationBehaviour: OperationBehaviour, @@ -758,6 +761,12 @@ struct BorderOffset { offset: i32, } +#[derive(Parser)] +struct TransparencyAlpha { + /// Alpha + alpha: u8, +} + #[derive(Parser)] struct Animation { #[clap(value_enum)] @@ -1229,6 +1238,14 @@ enum SubCommand { // /// Set the border implementation // #[clap(arg_required_else_help = true)] // BorderImplementation(BorderImplementation), + /// Enable or disable transparency for unfocused windows + #[clap(arg_required_else_help = true)] + Transparency(Transparency), + /// Set the alpha value for unfocused window transparency + #[clap(arg_required_else_help = true)] + TransparencyAlpha(TransparencyAlpha), + /// Toggle transparency for unfocused windows + ToggleTransparency, /// Enable or disable movement animations #[clap(arg_required_else_help = true)] Animation(Animation), @@ -2065,6 +2082,15 @@ fn main() -> eyre::Result<()> { SubCommand::BorderOffset(args) => { send_message(&SocketMessage::BorderOffset(args.offset))?; } + SubCommand::Transparency(args) => { + send_message(&SocketMessage::Transparency(args.boolean_state.into()))?; + } + SubCommand::TransparencyAlpha(args) => { + send_message(&SocketMessage::TransparencyAlpha(args.alpha))?; + } + SubCommand::ToggleTransparency => { + send_message(&SocketMessage::ToggleTransparency)?; + } SubCommand::Animation(args) => { send_message(&SocketMessage::Animation( args.boolean_state.into(), diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index 91356662..689b9ec0 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -512,6 +512,23 @@ fn the_border_subcommands_send_what_they_are_given() { ); } +#[test] +fn the_transparency_subcommands_send_what_they_are_given() { + sends( + &["transparency", "enable"], + r#"{"type":"Transparency","content":true}"#, + ); + sends( + &["transparency", "disable"], + r#"{"type":"Transparency","content":false}"#, + ); + sends( + &["transparency-alpha", "150"], + r#"{"type":"TransparencyAlpha","content":150}"#, + ); + sends(&["toggle-transparency"], r#"{"type":"ToggleTransparency"}"#); +} + #[test] fn the_animation_subcommands_send_what_they_are_given() { sends( @@ -1190,11 +1207,14 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "toggle-mouse-follows-focus.md", "toggle-pause.md", "toggle-tiling.md", + "toggle-transparency.md", "toggle-window-based-work-area-offset.md", "toggle-window-container-behaviour.md", "toggle-workspace-float-override.md", "toggle-workspace-layer.md", "toggle-workspace-window-container-behaviour.md", + "transparency-alpha.md", + "transparency.md", "unmanage.md", "unmanaged-window-operation-behaviour.md", "unstack-all.md", diff --git a/nix/komorebi-options.nix b/nix/komorebi-options.nix index fd0d39a8..2030a384 100644 --- a/nix/komorebi-options.nix +++ b/nix/komorebi-options.nix @@ -1,4 +1,4 @@ -# schema-sha256: 775a2171f74c90914b3de3fd6eed52485bd52cc19c881c90c56f60c36b91611e +# schema-sha256: f46c8e0d1557a1e36d2bd123a2d02a4238b28f07146beafb9b5c5fb5825b09df { lib, ... }: let animationStyle = ( @@ -633,6 +633,21 @@ in default = "CenterAndResize"; description = "Determines the placement of a new window when toggling to float"; }; + transparency = lib.mkOption { + type = (lib.types.nullOr lib.types.bool); + default = null; + description = "Add transparency to unfocused windows (default: false)"; + }; + transparency_alpha = lib.mkOption { + type = (lib.types.nullOr lib.types.int); + default = null; + description = "Alpha value for unfocused window transparency [[0-255]] (default: 200)"; + }; + transparency_ignore_rules = lib.mkOption { + type = (lib.types.nullOr (lib.types.listOf matchingRule)); + default = null; + description = "Individual window transparency ignore rules"; + }; unmanaged_window_operation_behaviour = lib.mkOption { type = ( lib.types.nullOr ( diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 330ecbe7..f3553c04 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -325,6 +325,11 @@ mouse-follows-focus enable mouse-follows-focus disable toggle-mouse-follows-focus toggle-mouse-follows-focus +transparency enable +transparency-alpha 150 +toggle-transparency +toggle-transparency +transparency disable border enable border-width 8 border-offset 1 diff --git a/nix/tests/vm/suites/features/test.py b/nix/tests/vm/suites/features/test.py index 65aa672d..06dec37c 100644 --- a/nix/tests/vm/suites/features/test.py +++ b/nix/tests/vm/suites/features/test.py @@ -6,6 +6,7 @@ # A toggle-maximize: the window fills the work area, is the one on top, and goes back to its # tile. It runs on the daemon the session started with the module's unit, as on a user's # machine; the sections after it stop that daemon and start their own runs +# B transparency: unfocused windows are see-through, the focused one is not # C border colors: every kind of window has its own: the focused window, the others, a locked # container that does not have the focus, a stack and a monocled window that have it, and a # floating window that has it @@ -195,6 +196,43 @@ checks.check( # sections after it start their own runs stop_komorebi() +print("== B. transparency") +start_komorebi() +kde.komorebic("transparency-alpha", "100") +kde.komorebic("transparency", "enable") +windows() + + +def center_of(title: str) -> tuple[int, int]: + frame = kde.rect(kde.wid(title)) + return frame.x + frame.w // 2, frame.y + frame.h // 2 + + +def middle_of(title: str, color: tuple[int, int, int]) -> bool: + """Returns true if and only if the middle of the window is `color` in a screenshot now.""" + return pixels.near(pixels.pixel(kde.shot(f"middle-{title}"), *center_of(title)), color) + + +checks.check( + "the focused window is its own color", + kde.wait_for(lambda: middle_of("blue", BLUE), timeout=15), +) +checks.check( + "an unfocused window is not: it lets the desktop through", + kde.wait_for(lambda: not middle_of("red", RED), timeout=15), +) +kde.komorebic("transparency", "disable") +checks.check( + "with transparency off the unfocused window is opaque again", + kde.wait_for(lambda: middle_of("red", RED), timeout=15), +) +kde.komorebic("toggle-transparency") +checks.check( + "toggled on, see-through again", + kde.wait_for(lambda: not middle_of("red", RED), timeout=15), +) +stop_komorebi() + print("== C. border colors") start_komorebi() windows() diff --git a/schema.json b/schema.json index 7f7f6eff..4cba76af 100644 --- a/schema.json +++ b/schema.json @@ -303,6 +303,33 @@ ], "default": "CenterAndResize" }, + "transparency": { + "description": "Add transparency to unfocused windows (default: false)", + "type": [ + "boolean", + "null" + ] + }, + "transparency_alpha": { + "description": "Alpha value for unfocused window transparency [[0-255]] (default: 200)", + "type": [ + "integer", + "null" + ], + "format": "uint8", + "maximum": 255, + "minimum": 0 + }, + "transparency_ignore_rules": { + "description": "Individual window transparency ignore rules", + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/$defs/MatchingRule" + } + }, "unmanaged_window_operation_behaviour": { "description": "Determine what happens when commands are sent while an unmanaged window is in the foreground", "anyOf": [