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.
This commit is contained in:
LGUG2Z committed 2026-10-28 20:15:44 -07:00
1 parent b39b17dd6e
commit b762a5ca4d
5 files changed
+228 -2

No files matched your search

@@ -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<crate::clock::ReferenceClock> {
vec![crate::clock::ReferenceClock {
name: "CLOCK_BOOTTIME".to_string(),
counts_sleep: true,
ns: read(libc::CLOCK_BOOTTIME),
}]
}
@@ -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() {}
@@ -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<dyn std::error::Error>>(())
/// ```
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)
}
@@ -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<String> {
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<String> {
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<PathBuf> {
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);
}
}
+7 -2
View File
@@ -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