diff --git a/README.md b/README.md index 85a4e45d..bda25691 100644 --- a/README.md +++ b/README.md @@ -83,8 +83,9 @@ without a checkout of the toolchain. daemon, reads its answers, subscribes to its notifications, and re-exports the types they are made of. - [`komorebic`](komorebic): the command line. A subcommand that asks something - of the daemon is one message on its socket; `start`, `configuration`, `log`, - `data-directory`, `completions` and the hidden `docgen` work without the daemon. + of the daemon is one message on its socket; `quickstart`, `enable-autostart`, + `disable-autostart`, `start`, `configuration`, `log`, `data-directory`, `completions` and + the hidden `docgen` work without the daemon. - [`version`](version): the version string every binary reports. The layouts, which turn a work area and a number of containers into a rectangle @@ -206,7 +207,9 @@ can be in files of their own, which `app_specific_configuration_path` names. `workspace-layout-rule` makes a workspace change layout with the number of windows it has, as the file's `layout_rules` do, and `generate-static-config` prints the settings the daemon -has as a `komorebi.json`. The Rust types that read the file describe it as a JSON Schema +has as a `komorebi.json`, and `replace-configuration` makes the daemon start over from +another file. `quickstart` writes an example configuration, and `enable-autostart` an +autostart entry that has Plasma start komorebi at login. The Rust types that read the file describe it as a JSON Schema (`schema.json`, written by `just jsonschema` and printed by `static-config-schema`), and the module's `config` option is typed from that schema (`nix/komorebi-options.nix`, written by `just nixgen`), so a configuration written in Nix is checked when it is evaluated. diff --git a/docs/cli/disable-autostart.md b/docs/cli/disable-autostart.md new file mode 100644 index 00000000..c1591f54 --- /dev/null +++ b/docs/cli/disable-autostart.md @@ -0,0 +1,10 @@ +```text +Removes the XDG autostart entry + +Usage: disable-autostart + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/enable-autostart.md b/docs/cli/enable-autostart.md new file mode 100644 index 00000000..e4b0bf2a --- /dev/null +++ b/docs/cli/enable-autostart.md @@ -0,0 +1,13 @@ +```text +Writes an XDG autostart entry so komorebi starts with the Plasma session + +Usage: enable-autostart [OPTIONS] + +Options: + -c, --config + Path to a static configuration JSON file + + -h, --help + Print help + +``` diff --git a/docs/cli/quickstart.md b/docs/cli/quickstart.md new file mode 100644 index 00000000..f481b72b --- /dev/null +++ b/docs/cli/quickstart.md @@ -0,0 +1,10 @@ +```text +Gather example configurations for a new-user quickstart + +Usage: quickstart + +Options: + -h, --help + Print help + +``` diff --git a/docs/cli/replace-configuration.md b/docs/cli/replace-configuration.md new file mode 100644 index 00000000..71f407fc --- /dev/null +++ b/docs/cli/replace-configuration.md @@ -0,0 +1,14 @@ +```text +Replace the configuration of a running instance of komorebi from a static configuration file + +Usage: replace-configuration + +Arguments: + + Static configuration JSON file from which the configuration should be loaded + +Options: + -h, --help + Print help + +``` diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index edd1c7c1..5cf83348 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -683,6 +683,16 @@ defaults. A **rule** is an entry of one of the process-wide lists. A workspace's `layout_rules`, `work_area_offset_rules` and `window_container_behaviour_rules` are fields of the [`Workspace`], which [`Workspace::update`] reads each time it tiles. +`ReplaceConfiguration` is the third way in: [`WindowManager::process_command`] checks that the file +reads as a [`StaticConfig`], pauses the old window manager and brings back the windows it hid +([`WindowManager::restore_all_windows`]), makes a new window manager from the file +([`StaticConfig::preload`], [`WindowManager::init`], [`StaticConfig::reload`]) over the same command +socket, and puts it where the old one was, so the daemon starts over from the file, with the +windows the backend has, all of them in view, and a watcher on the new file. A file that does not read is logged and the old window manager stays. +`komorebic quickstart` writes the example file of the docs and `komorebic/applications.json` into +the config home, compiled into the binary, and asks before it writes over a file; +`komorebic enable-autostart` writes the XDG autostart entry that has Plasma start the daemon at login. + The same types describe the file as a JSON Schema, which `schemars` derives: `komorebic static-config-schema` prints the schema of [`StaticConfig`], `application-specific-configuration-schema` that of an applications file, and `notification-schema` and `socket-schema` those of a @@ -711,6 +721,10 @@ goes the other way, for `GenerateStaticConfig`. | `schema.json` and `schema.asc.json` are what the Rust types print | Nix check `schema-fresh`, and a test that compares them with `komorebic`'s output | `schema-fresh`, `the_schema_files_of_the_repository_are_what_the_subcommands_print` | `just jsonschema` | | The options the module is typed with are made from the committed schema | the hash of `schema.json` in the first line of `nix/komorebi-options.nix`, compared by `schema-fresh` | `schema-fresh` | `just nixgen` | | The example, in Nix and in JSON, follows the schema, and says the same in both | Nix check `nix-options-validation`: the options evaluated against the Nix example, both examples checked with `check-jsonschema`, and one contained in the other | `nix-options-validation` | none | +| Replacing the configuration with a file that does not read leaves the window manager as it was | framework path: the arm reads the file as a [`StaticConfig`] before it makes anything | `replacing_the_configuration_makes_the_window_manager_again_from_the_new_file` | none | +| Replacing the configuration leaves no window hidden | framework path: the arm brings back the windows the old window manager hid ([`WindowManager::restore_all_windows`]) before the new one reads the desktop | `replacing_the_configuration_makes_the_window_manager_again_from_the_new_file` | none | +| `quickstart` never writes over a file without being told to | framework path: every file goes through `write_file_with_prompt`, which keeps the file unless the answer is `y` or `yes` | `quickstart_writes_the_example_files_and_asks_before_it_overwrites_one` | none | +| The entry `enable-autostart` writes is one the session runs | VM test: systemd's autostart generator makes a unit of it, which starts a daemon | `autostart_writes_an_xdg_entry_that_starts_komorebi_and_takes_it_away_again`, `vm-module` | none | | A file that cannot be read changes nothing | framework path: [`StaticConfig::reload`] reads and parses the file before it applies anything | `a_configuration_that_cannot_be_read_changes_nothing`, `the_daemon_follows_the_file_it_is_given_when_the_file_changes` | none | | The daemon applies a change to its file, written in place or replaced by a rename | framework path: the watcher sends `ReloadStaticConfiguration` to the daemon's own socket | `the_daemon_follows_the_file_it_is_given_when_the_file_changes`, `vm-module` | none: the file has to be the one the daemon was started with | | A monitor takes the entry its display index preference gives it, else the first nobody has | framework path: [`StaticConfig::postload`] and [`StaticConfig::reload`] choose the entry by serial number id first | `a_monitor_takes_the_configuration_its_display_index_preference_gives_it` | none | @@ -1022,7 +1036,8 @@ A window is shown, and ends up on a tile: daemon following a file, and [`komorebi/tests/config_parity.rs`](../../komorebi/tests/config_parity.rs) the files of other platforms and the example, which load; - [`komorebi/tests/schemas.rs`](../../komorebi/tests/schemas.rs) the schemas the daemon answers + [`komorebi/tests/replace_configuration.rs`](../../komorebi/tests/replace_configuration.rs) + the `ReplaceConfiguration` message; [`komorebi/tests/schemas.rs`](../../komorebi/tests/schemas.rs) the schemas the daemon answers with; [`schema.json`](../../schema.json), [`schema.asc.json`](../../schema.asc.json) and [`nix/komorebi-options.nix`](../../nix/komorebi-options.nix), which are generated; [`nix/tests/default.nix`](../../nix/tests/default.nix) and diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 20d961f5..7013b377 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -363,3 +363,12 @@ installed with `cargo install`). `just nixgen` writes the hash of `schema.json` of the file, and the check `schema-fresh` compares that with the hash of the committed schema, and the schema with what `komorebic static-config-schema` prints. A change to a key that leaves the schema or the options behind fails the check, with no tool but the build. + +## Why does `komorebic` write an autostart entry, as well as the module having a unit? + +The module is NixOS, and the daemon runs on other distributions too. An XDG autostart entry is +what a Plasma session runs at login for a program that is not part of it, so +`komorebic enable-autostart` writes one, with the `komorebi.json` it is given if any. The entry is +ordered after `plasma-workspace` (`X-KDE-autostart-after`), as the module's unit is ordered after +`plasma-core.target`: the daemon exits when KWin is not on the session bus. The entry and the +unit do not go together, since the session bus gives its name to one komorebi. diff --git a/docs/dev/PLATFORM.md b/docs/dev/PLATFORM.md index 99a188bb..40f44843 100644 --- a/docs/dev/PLATFORM.md +++ b/docs/dev/PLATFORM.md @@ -233,6 +233,7 @@ since a read right after `createDesktop` has to see the new desktop. | Path | What | Lifetime | |---|---|---| | `$KOMOREBI_CONFIG_HOME/komorebi.json` (`~/.config/komorebi/komorebi.json`) | komorebi's configuration, which komorebi never writes: read when the daemon starts, and again when it changes. `--config` names another file | the user's | +| `$XDG_CONFIG_HOME/autostart/komorebi.desktop` (`~/.config/autostart/komorebi.desktop`) | the XDG autostart entry `komorebic enable-autostart` writes: `Exec=komorebi`, or `komorebi --config "FILE"`, and `X-KDE-autostart-after=plasma-workspace`, which a Plasma session starts komorebi from at login | the user's; `komorebic disable-autostart` removes it | | `$XDG_CONFIG_HOME/kwinrc` (`~/.config/kwinrc`) | KWin's configuration: komorebi sets `PerOutputVirtualDesktops=true` in `[Windows]`, changing that line or adding it and nothing else, and writes the file beside it first and renames it over it | put back as it was when the daemon stops | | `$XDG_RUNTIME_DIR/komorebi/kwinrc-backup.json` | the value each key of `kwinrc` had before komorebi first changed it | removed when the values are put back; one a crash left behind is used by the next run | | `$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 | @@ -300,6 +301,15 @@ When set to anything but the empty string, the log the daemon prints on its stan has no ANSI colors, which is what standard output redirected to a file wants. The VM tests set it. The log files are not affected: one has colors and the other none. +## The autostart entry + +At time of writing (2026-10-27), on a Plasma session of a NixOS machine, systemd's autostart +generator makes a user unit of the entry `komorebic enable-autostart` writes, +`app-komorebi@autostart.service`, when the user manager reloads (`systemctl --user +daemon-reload`), and starting that unit starts a daemon that follows the file the entry gave it +(`vm-module`, which does this on x86_64). The test starts the unit by hand, since the session it +runs in has logged in already: it does not show that the next login starts it. + ## Watching the configuration The daemon watches `komorebi.json` with `hotwatch` 0.5, over `notify` 6.1, which on Linux is diff --git a/docs/example-configurations.md b/docs/example-configurations.md index 8fe9f096..15303d33 100644 --- a/docs/example-configurations.md +++ b/docs/example-configurations.md @@ -63,8 +63,9 @@ different layout. This page has the file as it is: } ``` -Put it where the daemon looks for it, `~/.config/komorebi/komorebi.json`, or give it to the daemon -with `komorebic start --config`. [Configuration](usage/configuration.md) explains every key and +`komorebic quickstart` writes it, and the `applications.json` below, where the daemon looks for +them ([Quickstart and autostart](usage/quickstart-and-autostart.md)). Or put it there yourself, +`~/.config/komorebi/komorebi.json`, or give it to the daemon with `komorebic start --config`. [Configuration](usage/configuration.md) explains every key and where the daemon looks. The settings of a monitor with more than one entry in `monitors`, and of each workspace, are there too. @@ -72,8 +73,9 @@ each workspace, are there too. `app_specific_configuration_path` names a file of rules for the applications that need them, which the repository has a start of in -[`komorebic/applications.json`](../komorebic/applications.json). Put a copy where the example -says, `~/.config/komorebi/applications.json`; a path with no file behind it is skipped. +[`komorebic/applications.json`](../komorebic/applications.json). `komorebic quickstart` puts a copy +where the example says, `~/.config/komorebi/applications.json`; a path with no file behind it is +skipped. [Application specific configuration](usage/application-specific-configuration.md) explains the format. diff --git a/docs/index.md b/docs/index.md index c6a3da2a..6a7e1ed1 100644 --- a/docs/index.md +++ b/docs/index.md @@ -54,6 +54,9 @@ are KWin's virtual desktops, and how to show another or move a window to one. how it is reloaded when it changes, [Example configurations](example-configurations.md) has one to start from, and [Application specific configuration](usage/application-specific-configuration.md) 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. [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/installation.md b/docs/installation.md index f700648e..4acfe947 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -157,8 +157,9 @@ cargo install --locked --path komorebic `cargo` installs both in `~/.cargo/bin`, which has to be on your `PATH`. Start komorebi from a terminal in your Plasma session with [`komorebic start`](cli/start.md). -To start it with every Plasma session instead, write the unit the NixOS module defines, without -the NixOS paths, to `~/.config/systemd/user/komorebi.service`: +To start it with every Plasma session instead, `komorebic enable-autostart` writes an autostart +entry ([Quickstart and autostart](usage/quickstart-and-autostart.md)), or you can write the unit +the NixOS module defines, without the NixOS paths, to `~/.config/systemd/user/komorebi.service`: ```ini [Unit] diff --git a/docs/usage/quickstart-and-autostart.md b/docs/usage/quickstart-and-autostart.md new file mode 100644 index 00000000..2b22f36a --- /dev/null +++ b/docs/usage/quickstart-and-autostart.md @@ -0,0 +1,57 @@ +# Quickstart and autostart + +## Quickstart + +[`komorebic quickstart`](../cli/quickstart.md) writes two example files into the config home +(`~/.config/komorebi`, or `$KOMOREBI_CONFIG_HOME`), which it makes if it has to: + +- `komorebi.json`, which is [`docs/komorebi.example.json`](../example-configurations.md): + eight workspaces on the first monitor, each with another layout, and some padding; +- `applications.json`, which is + [`komorebic/applications.json`](application-specific-configuration.md#the-file-komorebi-ships), + the rules `komorebi.json` names for the applications that need them. + +When a file is there already, `quickstart` asks before it writes over it, and leaves the file +alone unless the answer is `y` or `yes`. It prints the files it wrote, and then tells you to run +`komorebic start`. + +```sh +komorebic quickstart +komorebic start +``` + +## Starting komorebi with Plasma + +On NixOS, [the module](../installation.md#nixos) starts komorebi with every Plasma session. +Elsewhere, [`komorebic enable-autostart`](../cli/enable-autostart.md) writes an XDG autostart +entry, `~/.config/autostart/komorebi.desktop` (`$XDG_CONFIG_HOME/autostart`), which Plasma runs at +login, after its workspace has started: + +```sh +komorebic enable-autostart +komorebic enable-autostart --config ~/mine.json +``` + +The entry runs `komorebi`, or `komorebi --config` with the file `--config` names, as the session +finds `komorebi` on its `PATH`. [`komorebic disable-autostart`](../cli/disable-autostart.md) takes +the entry away again, and says so when there is none. + +Do not use both the module and the entry: the session bus gives its name to one komorebi, and the +second exits. + +## Starting over with another file + +[`komorebic replace-configuration`](../cli/replace-configuration.md) makes the running daemon start +over from another `komorebi.json`: + +```sh +komorebic replace-configuration ~/work.json +``` + +The daemon makes its window manager again from the file, as it does at start: it brings back +the windows it had hidden, the back of a stack, so that none is out of sight, loads the monitors +and the windows that are open from KWin, gives the monitors the entries of the file and tiles +them, and from then on watches the new file and not the one it had. It is not the same as +changing the file the daemon watches, which [Configuration](configuration.md#changing-the-file) +describes: the windows that were in a workspace go where the new file puts them, not where they +were. A file that is not a `komorebi.json` is logged, and the daemon carries on as it was. diff --git a/docs/usage/running-komorebi.md b/docs/usage/running-komorebi.md index b037b6b4..fb48f273 100644 --- a/docs/usage/running-komorebi.md +++ b/docs/usage/running-komorebi.md @@ -36,7 +36,8 @@ session. Outside a Plasma session it exits with an error that says what is missi `komorebic start` prints. `--config` gives the daemon the `komorebi.json` to read -([Configuration](configuration.md) says where it looks otherwise): +([Configuration](configuration.md) says where it looks otherwise), and +[`komorebic quickstart`](quickstart-and-autostart.md) writes one to start from: ```sh komorebic start --config ~/mine.json diff --git a/komorebi/src/core/mod.rs b/komorebi/src/core/mod.rs index 201e0f25..1c234313 100644 --- a/komorebi/src/core/mod.rs +++ b/komorebi/src/core/mod.rs @@ -464,6 +464,7 @@ pub enum SocketMessage { ToggleWorkspaceLayer, // Configuration // ReloadConfiguration, + ReplaceConfiguration(#[serde_as(as = "ResolvedPathBuf")] PathBuf), ReloadStaticConfiguration(#[serde_as(as = "ResolvedPathBuf")] PathBuf), // WatchConfiguration(bool), // CompleteConfiguration, diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 03e2fb05..a82ebe42 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -74,7 +74,12 @@ //! [`WindowManager::clear_workspace_layout_rules`]). //! - **ReloadStaticConfiguration** applies a `komorebi.json` to the window manager //! ([`WindowManager::reload_static_configuration`]). The daemon sends itself this message when -//! the file it was started with changes. +//! the file it was started with changes. **ReplaceConfiguration** makes the window manager +//! again from a `komorebi.json`, which loads the monitors and the windows from the backend as +//! the daemon does when it starts, and watches that file instead of the one it had. The old +//! window manager is paused and brings back the windows it hid (the back of a stack), so that +//! every window is in view for the new one to find; a file that is not a `komorebi.json` is +//! logged and changes nothing. //! - **PreselectDirection** reserves the place on one side of the focused container for the next //! window ([`WindowManager::preselect_container_in_direction`]), unless a place is reserved //! already, and **CancelPreselect** gives the reserved place up. @@ -207,6 +212,7 @@ use crate::static_config::StaticConfig; use crate::window::RuleDebug; use crate::window::Window; use crate::window_manager::WindowManager; +use crate::window_manager_event_listener; use crate::workspace::WorkspaceLayer; use crate::workspace::WorkspaceWindowLocation; use color_eyre::eyre; @@ -921,6 +927,38 @@ impl WindowManager { let mut display_index_preferences = DISPLAY_INDEX_PREFERENCES.write(); display_index_preferences.insert(index_preference, display.clone()); } + SocketMessage::ReplaceConfiguration(ref config) => { + // Check that this is a valid static config file first + if StaticConfig::read(config).is_ok() { + // Pause so that restored windows come to the foreground from all workspaces + self.is_paused = true; + // Bring all windows to the foreground + self.restore_all_windows(false)?; + + // Create a new wm from the config path + let mut wm = StaticConfig::preload( + config, + window_manager_event_listener::event_rx(), + self.command_listener.try_clone().ok(), + )?; + + // Initialize the new wm + wm.init()?; + + wm.restore_all_windows(true)?; + + // This is equivalent to StaticConfig::postload for this use case + StaticConfig::reload(config, &mut wm)?; + + // Set self to the new wm instance + *self = wm; + } else { + tracing::warn!( + "not replacing the configuration: {} is not a komorebi.json", + config.display() + ); + } + } SocketMessage::NewWorkspace => { self.new_workspace()?; } diff --git a/komorebi/tests/replace_configuration.rs b/komorebi/tests/replace_configuration.rs new file mode 100644 index 00000000..240c4981 --- /dev/null +++ b/komorebi/tests/replace_configuration.rs @@ -0,0 +1,160 @@ +//! `ReplaceConfiguration` against an in-memory desktop: the window manager that is running is +//! made again from another `komorebi.json`, with the windows the desktop has. +//! +//! The settings a file sets are process-wide, so this file is one test. Window ids are in the +//! 41_000s. + +use komorebi::backend::fake::FakeBackend; +use komorebi::backend::with_backend; +use komorebi::core::OperationDirection; +use komorebi::core::Rect; +use komorebi::core::SocketMessage; +use komorebi::static_config::StaticConfig; +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::os::unix::net::UnixListener; +use std::path::PathBuf; +use std::sync::Arc; + +fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect { + Rect { + left, + top, + right, + bottom, + } +} + +fn write(name: &str, json: &str) -> PathBuf { + let path = PathBuf::from(format!("/tmp/kmr-{}-{name}.json", std::process::id())); + std::fs::write(&path, json).unwrap(); + path +} + +fn workspace_names(wm: &WindowManager) -> Vec> { + wm.monitors()[0] + .workspaces() + .iter() + .map(|workspace| workspace.name.clone()) + .collect() +} + +#[test] +fn replacing_the_configuration_makes_the_window_manager_again_from_the_new_file() { + let fake = Arc::new(FakeBackend::with_one_monitor()); + let first = write( + "first", + r#"{ "resize_delta": 100, "monitors": [ { "workspaces": [ { "name": "one", "layout": "BSP" } ] } ] }"#, + ); + let socket = PathBuf::from(format!("/tmp/kmr-{}.sock", std::process::id())); + let (_sender, receiver) = crossbeam_channel::bounded(1); + + let mut wm = with_backend(fake.clone(), || { + let mut wm = + StaticConfig::preload(&first, receiver, Some(UnixListener::bind(&socket).unwrap())) + .unwrap(); + wm.init().unwrap(); + wm + }); + fake.open_window(41_001, "foot", "foot", "terminal"); + with_backend(fake.clone(), || { + wm.process_event(WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(41_001), + )) + }) + .unwrap(); + assert_eq!(wm.resize_delta, 100); + assert_eq!(fake.rect_of(41_001), Some(rect(10, 10, 1900, 1030))); + + let second = write( + "second", + r#"{ + "resize_delta": 30, + "default_workspace_padding": 0, + "default_container_padding": 0, + "monitors": [ { "workspaces": [ { "name": "uno", "layout": "Columns" }, { "name": "dos" } ] } ] + }"#, + ); + with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::ReplaceConfiguration(second.clone()), + Vec::new(), + ) + }) + .unwrap(); + + // a window manager made from the new file, which found the window the desktop has + assert_eq!(wm.resize_delta, 30); + assert_eq!( + workspace_names(&wm), + [Some(String::from("uno")), Some(String::from("dos"))] + ); + assert_eq!(fake.rect_of(41_001), Some(rect(0, 0, 1920, 1050))); + assert!(wm.monitors()[0].workspaces()[0].contains_window(41_001)); + + // a file that is not a configuration changes nothing, and does not stop the daemon + let broken = write("broken", r#"{ "resize_delta": "wide" "#); + with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::ReplaceConfiguration(broken.clone()), + Vec::new(), + ) + }) + .unwrap(); + assert_eq!(wm.resize_delta, 30); + assert_eq!(workspace_names(&wm).len(), 2); + + // the back window of a stack is out of sight, and the new window manager would not find it + // there: the old one brings it back before the new one looks at the desktop + fake.open_window(41_002, "foot", "foot", "terminal"); + for event in [ + WindowManagerEvent::Show( + SystemNotification::KWin(KWinNotification::WindowAdded), + Window::from(41_002), + ), + WindowManagerEvent::FocusChange( + SystemNotification::KWin(KWinNotification::WindowActivated), + Window::from(41_002), + ), + ] { + fake.set_foreground(Some(41_002)); + with_backend(fake.clone(), || wm.process_event(event)).unwrap(); + } + with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::StackWindow(OperationDirection::Left), + Vec::new(), + ) + }) + .unwrap(); + assert_eq!( + [41_001, 41_002] + .iter() + .filter(|id| fake.is_hidden(**id)) + .count(), + 1 + ); + + with_backend(fake.clone(), || { + wm.process_command( + SocketMessage::ReplaceConfiguration(second.clone()), + Vec::new(), + ) + }) + .unwrap(); + assert!(!fake.is_hidden(41_001) && !fake.is_hidden(41_002)); + assert_eq!( + wm.focused_workspace().unwrap().containers().len(), + 2, + "the new window manager found both windows, each with a tile" + ); + + let _ = std::fs::remove_file(&socket); + for path in [first, second, broken] { + let _ = std::fs::remove_file(path); + } +} diff --git a/komorebic/src/main.rs b/komorebic/src/main.rs index 6b41585c..ae2794f0 100644 --- a/komorebic/src/main.rs +++ b/komorebic/src/main.rs @@ -75,13 +75,17 @@ //! `workspace-layout-rule` and `named-workspace-layout-rule` make a workspace change layout once //! it has so many windows, and `clear-workspace-layout-rules` and //! `clear-named-workspace-layout-rules` take those rules away. `generate-static-config` prints the -//! settings of the daemon as a `komorebi.json`. +//! settings of the daemon as a `komorebi.json`, and `replace-configuration` makes the daemon +//! start over with another one. //! //! `subscribe-socket` and `unsubscribe-socket` add and remove a subscriber: a program that listens //! on a socket in the daemon's data directory, to which the daemon sends a notification after each //! event and each message it handles. //! -//! The others work without the daemon: `start` runs `komorebi` in the background, with the +//! The others work without the daemon: `quickstart` writes an example `komorebi.json` and +//! `applications.json` in the config home, `enable-autostart` and `disable-autostart` write and +//! remove the entry that has Plasma start komorebi at login, `start` runs `komorebi` in the +//! background, with the //! `komorebi.json` it is given with `--config`, `configuration` shows the path of the //! `komorebi.json` the daemon reads, `log` follows its log, `data-directory` shows where its //! socket is, `completions` prints a completion script for a shell, and `static-config-schema`, @@ -616,6 +620,21 @@ struct LoadResize { path: PathBuf, } +#[derive(Parser)] +struct ReplaceConfiguration { + /// Static configuration JSON file from which the configuration should be loaded + #[clap(value_parser = replace_env_in_path)] + path: PathBuf, +} + +#[derive(Parser)] +struct EnableAutostart { + /// Path to a static configuration JSON file + #[clap(action, short, long)] + #[clap(value_parser = replace_env_in_path)] + config: Option, +} + #[derive(Parser)] struct EagerFocus { /// Case-sensitive exe identifier @@ -665,6 +684,8 @@ enum SubCommand { /// Generate komorebic CLI completions for the target shell #[clap(arg_required_else_help = true)] Completions(Completions), + /// Gather example configurations for a new-user quickstart + Quickstart, /// Start komorebi as a background process Start(Start), /// Stop the komorebi process @@ -1032,6 +1053,9 @@ enum SubCommand { MouseFollowsFocus(MouseFollowsFocus), /// Toggle mouse follows focus on all workspaces ToggleMouseFollowsFocus, + /// Replace the configuration of a running instance of komorebi from a static configuration file + #[clap(arg_required_else_help = true)] + ReplaceConfiguration(ReplaceConfiguration), /// Generate a JSON Schema for applications.json #[clap(alias = "asc-schema")] ApplicationSpecificConfigurationSchema, @@ -1043,6 +1067,18 @@ enum SubCommand { StaticConfigSchema, /// Generates a static configuration JSON file based on the current window manager state GenerateStaticConfig, + /// Writes an XDG autostart entry so komorebi starts with the Plasma session + EnableAutostart(EnableAutostart), + /// Removes the XDG autostart entry + DisableAutostart, +} + +/// `~/.config/autostart/komorebi.desktop`, which Plasma runs at login +fn autostart_entry() -> PathBuf { + dirs::config_dir() + .expect("there is no config directory") + .join("autostart") + .join("komorebi.desktop") } fn print_query(message: &SocketMessage) { @@ -1094,6 +1130,87 @@ fn main() -> eyre::Result<()> { let mut cli = Opts::command(); clap_complete::generate(args.shell, &mut cli, "komorebic", &mut std::io::stdout()); } + SubCommand::Quickstart => { + fn write_file_with_prompt( + path: &PathBuf, + content: &str, + created_files: &mut Vec, + ) -> eyre::Result<()> { + if path.exists() { + print!( + "{} will be overwritten, do you want to continue? (y/N): ", + path.display() + ); + std::io::stdout().flush()?; + let mut input = String::new(); + std::io::stdin().read_line(&mut input)?; + let trimmed = input.trim().to_lowercase(); + if trimmed == "y" || trimmed == "yes" { + std::fs::write(path, content)?; + created_files.push(path.display().to_string()); + } else { + println!("Skipping {}", path.display()); + } + } else { + std::fs::write(path, content)?; + created_files.push(path.display().to_string()); + } + Ok(()) + } + + std::fs::create_dir_all(&*HOME_DIR)?; + std::fs::create_dir_all(&*komorebi_client::DATA_DIR)?; + + let komorebi_json = include_str!("../../docs/komorebi.example.json").to_string(); + let komorebi_path = HOME_DIR.join("komorebi.json"); + let applications_path = HOME_DIR.join("applications.json"); + + let mut written_files = Vec::new(); + + write_file_with_prompt(&komorebi_path, &komorebi_json, &mut written_files)?; + + let applications_json = include_str!("../applications.json"); + write_file_with_prompt(&applications_path, applications_json, &mut written_files)?; + if written_files.is_empty() { + println!("\nNo files were written.") + } else { + println!( + "\nThe following example files were written:\n{}", + written_files.join("\n") + ); + } + + println!("\nYou can now run: komorebic start"); + } + SubCommand::EnableAutostart(args) => { + let exec = match args.config { + None => String::from("komorebi"), + Some(config) => format!("komorebi --config \"{}\"", config.display()), + }; + + let target = autostart_entry(); + if let Some(dir) = target.parent() { + std::fs::create_dir_all(dir)?; + } + + std::fs::write( + &target, + format!( + "[Desktop Entry]\nType=Application\nName=komorebi\nComment=A tiling window manager for KDE Plasma\nExec={exec}\nX-KDE-autostart-after=plasma-workspace\nTerminal=false\n" + ), + )?; + + println!("Wrote {}", target.display()); + } + SubCommand::DisableAutostart => { + let target = autostart_entry(); + if target.exists() { + std::fs::remove_file(&target)?; + println!("Deleted {}", target.display()); + } else { + println!("There is no autostart entry at {}", target.display()); + } + } SubCommand::Start(args) => { let mut command = &mut Command::new("komorebi"); @@ -1675,6 +1792,9 @@ fn main() -> eyre::Result<()> { SubCommand::GenerateStaticConfig => { print_query(&SocketMessage::GenerateStaticConfig); } + SubCommand::ReplaceConfiguration(args) => { + send_message(&SocketMessage::ReplaceConfiguration(args.path))?; + } SubCommand::QuickSaveResize => { send_message(&SocketMessage::QuickSave)?; } diff --git a/komorebic/tests/cli.rs b/komorebic/tests/cli.rs index c5d0c9b0..e04eb624 100644 --- a/komorebic/tests/cli.rs +++ b/komorebic/tests/cli.rs @@ -678,6 +678,130 @@ fn configuration_shows_the_path_of_komorebi_json_when_there_is_one() { } } +#[test] +fn replace_configuration_sends_the_path_it_is_given_with_the_variables_replaced() { + let runtime = Runtime::new(); + let daemon = runtime.serve(""); + + let output = runtime.komorebic_with_config_home( + &runtime.0, + &["replace-configuration", "$KOMOREBI_CONFIG_HOME/other.json"], + ); + + assert!(output.status.success(), "{output:?}"); + assert_eq!( + daemon.join().unwrap(), + format!( + r#"{{"type":"ReplaceConfiguration","content":"{}/other.json"}}"#, + runtime.0.display() + ) + ); + assert_eq!(stdout(&output), ""); +} + +/// Runs `komorebic quickstart` in the config home `home`, which answers `answers` to its questions +fn quickstart(runtime: &Runtime, home: &Path, answers: &str) -> Output { + let mut child = Command::new(env!("CARGO_BIN_EXE_komorebic")) + .arg("quickstart") + .env("XDG_RUNTIME_DIR", &runtime.0) + .env("KOMOREBI_CONFIG_HOME", home) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(answers.as_bytes()) + .unwrap(); + child.wait_with_output().unwrap() +} + +#[test] +fn quickstart_writes_the_example_files_and_asks_before_it_overwrites_one() { + let runtime = Runtime::new(); + let home = runtime.0.join("config"); + std::fs::create_dir_all(&home).unwrap(); + + let output = quickstart(&runtime, &home, ""); + assert!(output.status.success(), "{output:?}"); + let example = include_str!("../../docs/komorebi.example.json"); + assert_eq!( + std::fs::read_to_string(home.join("komorebi.json")).unwrap(), + example + ); + assert_eq!( + std::fs::read_to_string(home.join("applications.json")).unwrap(), + include_str!("../applications.json") + ); + assert!(stdout(&output).contains("The following example files were written")); + assert!(stdout(&output).contains("komorebic start")); + + // a file that is there is kept unless the answer is yes + std::fs::write(home.join("komorebi.json"), "{}").unwrap(); + std::fs::write(home.join("applications.json"), "{}").unwrap(); + let output = quickstart(&runtime, &home, "n\nyes\n"); + assert!(output.status.success(), "{output:?}"); + assert_eq!( + std::fs::read_to_string(home.join("komorebi.json")).unwrap(), + "{}" + ); + assert_eq!( + std::fs::read_to_string(home.join("applications.json")).unwrap(), + include_str!("../applications.json") + ); + assert!(stdout(&output).contains("Skipping")); +} + +#[test] +fn autostart_writes_an_xdg_entry_that_starts_komorebi_and_takes_it_away_again() { + let runtime = Runtime::new(); + let config_dir = runtime.0.join("xdg"); + let entry = config_dir.join("autostart").join("komorebi.desktop"); + let run = |args: &[&str]| { + Command::new(env!("CARGO_BIN_EXE_komorebic")) + .args(args) + .env("XDG_RUNTIME_DIR", &runtime.0) + .env("XDG_CONFIG_HOME", &config_dir) + .output() + .unwrap() + }; + + let output = run(&["disable-autostart"]); + assert!(output.status.success(), "{output:?}"); + assert!(stdout(&output).contains("There is no autostart entry")); + + let output = run(&["enable-autostart"]); + assert!(output.status.success(), "{output:?}"); + let text = std::fs::read_to_string(&entry).unwrap(); + assert!(text.starts_with("[Desktop Entry]\n"), "{text}"); + assert!(text.contains("\nExec=komorebi\n"), "{text}"); + assert!( + text.contains("\nX-KDE-autostart-after=plasma-workspace\n"), + "{text}" + ); + + // `--config` is what the daemon is started with + let output = run(&[ + "enable-autostart", + "--config", + "/etc/komorebi/komorebi.json", + ]); + assert!(output.status.success(), "{output:?}"); + assert!( + std::fs::read_to_string(&entry) + .unwrap() + .contains("\nExec=komorebi --config \"/etc/komorebi/komorebi.json\"\n") + ); + + let output = run(&["disable-autostart"]); + assert!(output.status.success(), "{output:?}"); + assert!(stdout(&output).starts_with("Deleted "), "{output:?}"); + assert!(!entry.exists()); +} + #[test] fn a_config_home_that_is_not_a_directory_is_refused() { let runtime = Runtime::new(); @@ -883,8 +1007,10 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "cycle-stack.md", "cycle-workspace.md", "data-directory.md", + "disable-autostart.md", "display-index-preference.md", "eager-focus.md", + "enable-autostart.md", "ensure-named-workspaces.md", "ensure-workspaces.md", "flip-layout.md", @@ -935,6 +1061,8 @@ fn docgen_writes_the_help_of_every_subcommand_in_a_text_fence() { "query.md", "quick-load-resize.md", "quick-save-resize.md", + "quickstart.md", + "replace-configuration.md", "resize-axis.md", "resize-delta.md", "resize-edge.md", diff --git a/nix/tests/vm/suites/commands/test.py b/nix/tests/vm/suites/commands/test.py index 376feb8d..ced4ee2a 100644 --- a/nix/tests/vm/suites/commands/test.py +++ b/nix/tests/vm/suites/commands/test.py @@ -334,8 +334,14 @@ manage-rule exe nonexistent manage close retile +replace-configuration /tmp/e2e-config.json eager-focus foot """ +kde.sh( + "printf %s " + + shlex.quote('{ "monitors": [ { "workspaces": [ { "name": "again", "layout": "BSP" } ] } ] }') + + " > /tmp/e2e-config.json" +) for line in SWEEP.strip().splitlines(): status, out = kde.run(shlex.join(["komorebic", *line.split()])) if status != 0: @@ -346,6 +352,12 @@ for line in SWEEP.strip().splitlines(): continue checks.ok(f"komorebic {line}") +first_workspace = kde.state()["monitors"]["elements"][0]["workspaces"]["elements"][0] +checks.check( + "replace-configuration made the window manager again from the file", + first_workspace["name"] == "again", +) + print("== 3b. minimize, unmanage and manage the focused window") focused = kde.active() title = kde.title(focused) diff --git a/nix/tests/vm/suites/module/test.py b/nix/tests/vm/suites/module/test.py index 1ff8a71f..e86c9d6e 100644 --- a/nix/tests/vm/suites/module/test.py +++ b/nix/tests/vm/suites/module/test.py @@ -4,7 +4,8 @@ # opened in the session, that it runs with the module's log level, the `komorebi.json` the module # wrote from its `config`, and the PATH of the user's session, that systemd starts it again when # it is killed, and that a clean stop is not a failure. Once the unit is stopped, the daemon is -# started with a `komorebi.json` of the user's, which it follows when the file changes. The +# started with a `komorebi.json` of the user's, which it follows when the file changes, and +# `komorebic enable-autostart` writes the entry systemd's autostart generator makes a unit of. The # options and the unit the module writes are checked without a machine by `nixos-module-eval` # (`nix/tests/nixos-module.nix`). import json @@ -188,4 +189,30 @@ checks.check( kde.komorebic("stop") checks.check("that daemon stops", kde.wait_for(lambda: not answering(), timeout=30)) +print("== 6. an autostart entry is run by the session") +ENTRY = "/home/komorebi/.config/autostart/komorebi.desktop" +AUTOSTART = "app-komorebi@autostart.service" +kde.komorebic("enable-autostart", "--config", MINE) +checks.check( + "komorebic enable-autostart writes the entry, with the file it is given", + f'Exec=komorebi --config "{MINE}"' in machine.succeed(f"cat {ENTRY}"), +) +kde.systemctl("daemon-reload") +status, unit_text = kde.run(f"systemctl --user cat {AUTOSTART}") +print(unit_text) +checks.check( + "systemd's autostart generator makes a unit of it, which runs komorebi", + status == 0 and "komorebi" in unit_text, +) +kde.systemctl("start", AUTOSTART) +checks.check("... which starts a daemon that answers", kde.wait_for(answering, timeout=60)) +checks.check("... with the file the entry gave it", resize_delta() == 33) +kde.komorebic("stop") +checks.check("that daemon stops", kde.wait_for(lambda: not answering(), timeout=30)) +kde.komorebic("disable-autostart") +checks.check( + "komorebic disable-autostart takes the entry away", + machine.execute(f"test -e {ENTRY}")[0] != 0, +) + checks.finish()