From b762a5ca4d11036dc6dcc04587a7f90ca5a02643 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 20:00:00 -0700 Subject: [PATCH] feat(platform): a Linux host with its own clock, process and shell The rest of the host (apps, capture, power, session, trace) is still the unsupported host's, and is replaced one module at a time. --- komorebi-recorder/src/platform/linux/clock.rs | 68 ++++++++++++++++++ komorebi-recorder/src/platform/linux/mod.rs | 23 ++++++ .../src/platform/linux/process.rs | 58 +++++++++++++++ komorebi-recorder/src/platform/linux/shell.rs | 72 +++++++++++++++++++ komorebi-recorder/src/platform/mod.rs | 9 ++- 5 files changed, 228 insertions(+), 2 deletions(-) create mode 100644 komorebi-recorder/src/platform/linux/clock.rs create mode 100644 komorebi-recorder/src/platform/linux/mod.rs create mode 100644 komorebi-recorder/src/platform/linux/process.rs create mode 100644 komorebi-recorder/src/platform/linux/shell.rs diff --git a/komorebi-recorder/src/platform/linux/clock.rs b/komorebi-recorder/src/platform/linux/clock.rs new file mode 100644 index 00000000..9ebf0481 --- /dev/null +++ b/komorebi-recorder/src/platform/linux/clock.rs @@ -0,0 +1,68 @@ +//! The master clock on Linux: `CLOCK_MONOTONIC`, the clock PipeWire stamps its buffers with and +//! the journal's `__MONOTONIC_TIMESTAMP` is on. +//! +//! Every time in a session is nanoseconds on this clock (see [`crate::clock`]). It does not count +//! the time the machine is suspended, so a sleep shows up as the wall clock moving on while this +//! one does not. [`reference_clocks`] reads `CLOCK_BOOTTIME`, which does count it. +//! +//! The same items exist on macOS and Windows. + +use crate::clock::Timebase; +use crate::platform::ClockKind; + +/// Which clock the master clock is: [`ClockKind::Monotonic`], recorded as `host.clock` in the +/// manifest. +pub const KIND: ClockKind = ClockKind::Monotonic; + +/// Returns the identity timebase: [`now_ns`] is already in nanoseconds. +#[must_use] +pub fn timebase() -> Timebase { + Timebase { numer: 1, denom: 1 } +} + +fn read(clock: libc::clockid_t) -> u64 { + let mut ts = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: `ts` is a valid out pointer for the duration of the call + let status = unsafe { libc::clock_gettime(clock, &raw mut ts) }; + if status != 0 { + return 0; + } + ts.tv_sec as u64 * 1_000_000_000 + ts.tv_nsec as u64 +} + +/// Returns the raw `CLOCK_MONOTONIC` reading in nanoseconds, which pauses while the machine is +/// suspended. +#[must_use] +pub fn now_ticks() -> u64 { + read(libc::CLOCK_MONOTONIC) +} + +/// Returns nanoseconds on the host monotonic clock: the master clock every record in a session is +/// on. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::platform::clock::now_ns; +/// +/// let first = now_ns(); +/// assert!(first > 0); +/// assert!(now_ns() >= first); +/// ``` +#[must_use] +pub fn now_ns() -> u64 { + timebase().ticks_to_ns(now_ticks()) +} + +/// Returns `CLOCK_BOOTTIME`, which counts the time the machine is suspended. +#[must_use] +pub fn reference_clocks() -> Vec { + vec![crate::clock::ReferenceClock { + name: "CLOCK_BOOTTIME".to_string(), + counts_sleep: true, + ns: read(libc::CLOCK_BOOTTIME), + }] +} diff --git a/komorebi-recorder/src/platform/linux/mod.rs b/komorebi-recorder/src/platform/linux/mod.rs new file mode 100644 index 00000000..0688afca --- /dev/null +++ b/komorebi-recorder/src/platform/linux/mod.rs @@ -0,0 +1,23 @@ +//! Linux, as KDE Plasma: the host that records komorebi for KDE. +//! +//! The master clock, the child processes and the shell are Linux's own. The rest of the host +//! (`apps`, `capture`, `power`, `session`, `trace`) is still the `unsupported` host's, and is +//! replaced one module at a time as each is written (see `docs/PLATFORM.md`). + +// the pieces of the fallback that Linux has its own version of are not used +#[allow(dead_code)] +#[path = "../unsupported.rs"] +mod fallback; + +pub mod clock; +pub mod process; +pub mod shell; + +pub use fallback::apps; +pub use fallback::capture; +pub use fallback::power; +pub use fallback::session; +pub use fallback::trace; + +/// Nothing to do first. +pub fn init() {} diff --git a/komorebi-recorder/src/platform/linux/process.rs b/komorebi-recorder/src/platform/linux/process.rs new file mode 100644 index 00000000..f17f13c2 --- /dev/null +++ b/komorebi-recorder/src/platform/linux/process.rs @@ -0,0 +1,58 @@ +//! Starting and stopping child processes the way Linux wants it. +//! +//! The recorder runs `log stream` children (`crate::sources::oslog`) and, from the recorder window, +//! the viewer. [`isolate`] starts one so that a terminal's Ctrl-C reaches only the recorder, +//! [`terminate`] asks it to stop and [`was_terminated`] tells a child that was asked to stop from +//! one that failed. The same three functions exist on Windows, where the means differ. + +use std::process::Child; +use std::process::Command; +use std::process::ExitStatus; + +/// Puts the child in its own process group, so a terminal Ctrl-C reaches only the recorder, which +/// can then drain and stop these children in order instead of losing their tail. +/// +/// This must be called before the child is spawned. It returns `command` for chaining. On Windows +/// the child also gets no console window of its own. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::platform::process::{isolate, terminate, was_terminated}; +/// use std::process::Command; +/// +/// let mut command = Command::new("sleep"); +/// command.arg("30"); +/// let mut child = isolate(&mut command).spawn()?; +/// +/// // asked to stop with SIGTERM, which `was_terminated` recognizes +/// terminate(&mut child); +/// let status = child.wait()?; +/// assert!(!status.success()); +/// assert!(was_terminated(&status)); +/// # Ok::<(), Box>(()) +/// ``` +pub fn isolate(command: &mut Command) -> &mut Command { + std::os::unix::process::CommandExt::process_group(command, 0) +} + +/// Asks a child to stop, as politely as the OS allows (`SIGTERM`), so it flushes what it buffered. +/// +/// This only sends the signal: it does not wait for the child, so the caller must `wait` for it, +/// and does not report a failure to signal it. On Windows there is no polite signal, and the child +/// is killed. +pub fn terminate(child: &mut Child) { + // SAFETY: signalling a child process we spawned and still own + unsafe { + libc::kill(child.id() as i32, libc::SIGTERM); + } +} + +/// Returns `true` if and only if the child ended because [`terminate`] asked it to (it was +/// killed by `SIGTERM`), which is not a failure. +/// +/// On Windows this is always `false`: Windows reports no signal, so it cannot tell. +#[must_use] +pub fn was_terminated(status: &ExitStatus) -> bool { + std::os::unix::process::ExitStatusExt::signal(status) == Some(libc::SIGTERM) +} diff --git a/komorebi-recorder/src/platform/linux/shell.rs b/komorebi-recorder/src/platform/linux/shell.rs new file mode 100644 index 00000000..3ed37998 --- /dev/null +++ b/komorebi-recorder/src/platform/linux/shell.rs @@ -0,0 +1,72 @@ +//! Showing a folder, asking for one, and naming the OS, the way a Plasma desktop does it. + +use std::path::Path; +use std::path::PathBuf; +use std::process::Command; + +/// What this host calls its file manager, for button labels. +pub const FILE_MANAGER: &str = "file manager"; + +/// Returns the distribution's `PRETTY_NAME` or, failing that, its `VERSION_ID`, from +/// `/etc/os-release`. +#[must_use] +pub fn os_version() -> Option { + let text = std::fs::read_to_string("/etc/os-release") + .or_else(|_| std::fs::read_to_string("/usr/lib/os-release")) + .ok()?; + os_release_field(&text, "PRETTY_NAME").or_else(|| os_release_field(&text, "VERSION_ID")) +} + +fn os_release_field(text: &str, key: &str) -> Option { + text.lines().find_map(|line| { + let value = line.strip_prefix(key)?.strip_prefix('=')?; + let value = value.trim().trim_matches('"').trim_matches('\''); + (!value.is_empty()).then(|| value.to_string()) + }) +} + +/// Asks `xdg-open` to show `path`, which Plasma hands to Dolphin. +pub fn reveal(path: &Path) { + let _ = Command::new("xdg-open").arg(path).spawn(); +} + +/// Asks for a folder with `kdialog`, or `zenity` where there is no `kdialog`. +/// +/// Returns `None` if neither is installed or the dialog was cancelled. +#[must_use] +pub fn pick_folder(prompt: &str) -> Option { + let asked = Command::new("kdialog") + .args(["--title", prompt, "--getexistingdirectory"]) + .output() + .or_else(|_| { + Command::new("zenity") + .args(["--file-selection", "--directory", "--title", prompt]) + .output() + }) + .ok()?; + if !asked.status.success() { + return None; + } + let text = String::from_utf8(asked.stdout).ok()?; + let text = text.trim(); + (!text.is_empty()).then(|| PathBuf::from(text)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pretty_name_is_read_without_its_quotes() { + let text = "NAME=\"NixOS\"\nPRETTY_NAME=\"NixOS 25.11 (Xantusia)\"\nVERSION_ID=\"25.11\"\n"; + assert_eq!( + os_release_field(text, "PRETTY_NAME").as_deref(), + Some("NixOS 25.11 (Xantusia)") + ); + assert_eq!( + os_release_field(text, "VERSION_ID").as_deref(), + Some("25.11") + ); + assert_eq!(os_release_field(text, "MISSING"), None); + } +} diff --git a/komorebi-recorder/src/platform/mod.rs b/komorebi-recorder/src/platform/mod.rs index 800f74ee..2f33da9e 100644 --- a/komorebi-recorder/src/platform/mod.rs +++ b/komorebi-recorder/src/platform/mod.rs @@ -40,9 +40,14 @@ mod macos; #[cfg(target_os = "macos")] use macos as imp; -#[cfg(not(any(target_os = "macos", windows)))] +#[cfg(target_os = "linux")] +mod linux; +#[cfg(target_os = "linux")] +use linux as imp; + +#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] mod unsupported; -#[cfg(not(any(target_os = "macos", windows)))] +#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))] use unsupported as imp; // not `windows`: that would be ambiguous with the `windows` crate in every `use` of this module