Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f89833a62e | |||
| 198986efac | |||
| d1178ff8ba |
Generated
+1
-1
@@ -572,7 +572,7 @@ checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fluxo-rs"
|
name = "fluxo-rs"
|
||||||
version = "0.5.0"
|
version = "0.5.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bluer",
|
"bluer",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "fluxo-rs"
|
name = "fluxo-rs"
|
||||||
version = "0.5.0"
|
version = "0.5.1"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
|
|||||||
+48
-24
@@ -1,8 +1,16 @@
|
|||||||
|
//! Configuration loading + top-level `Config` struct.
|
||||||
|
//!
|
||||||
|
//! Every module section `#[derive(Deserialize)]`s its own struct with `serde`
|
||||||
|
//! defaults, so missing TOML sections/fields simply fall back to baked-in
|
||||||
|
//! values. The live `Config` is held behind an `Arc<RwLock<_>>` by the daemon
|
||||||
|
//! and replaced atomically on reload (see [`crate::daemon::reload_config`]).
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use tracing::{debug, info, warn};
|
use tracing::{debug, info, warn};
|
||||||
|
|
||||||
|
/// Top-level parsed `config.toml`. Each field corresponds to a `[section]`.
|
||||||
#[derive(Deserialize, Default, Clone)]
|
#[derive(Deserialize, Default, Clone)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -56,8 +64,10 @@ pub struct Config {
|
|||||||
pub dnd: DndConfig,
|
pub dnd: DndConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Process-wide settings that aren't tied to a single module.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct GeneralConfig {
|
pub struct GeneralConfig {
|
||||||
|
/// Shell command spawned by [`crate::utils::show_menu`] for interactive pickers.
|
||||||
pub menu_command: String,
|
pub menu_command: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,6 +79,9 @@ impl Default for GeneralConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Which Waybar `SIGRTMIN+N` signal each module should trigger, if any.
|
||||||
|
///
|
||||||
|
/// `None` disables signalling for that module entirely.
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[derive(Deserialize, Default, Clone)]
|
#[derive(Deserialize, Default, Clone)]
|
||||||
pub struct SignalsConfig {
|
pub struct SignalsConfig {
|
||||||
@@ -89,6 +102,7 @@ pub struct SignalsConfig {
|
|||||||
pub dnd: Option<i32>,
|
pub dnd: Option<i32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Network module config. `format` tokens: `interface`, `ip`, `rx`, `tx`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct NetworkConfig {
|
pub struct NetworkConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -105,6 +119,7 @@ impl Default for NetworkConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// CPU module config. `format` tokens: `usage`, `temp`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct CpuConfig {
|
pub struct CpuConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -121,6 +136,7 @@ impl Default for CpuConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Memory module config. `format` tokens: `used`, `total` (gigabytes).
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct MemoryConfig {
|
pub struct MemoryConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -137,6 +153,7 @@ impl Default for MemoryConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// GPU module config with per-vendor format strings.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct GpuConfig {
|
pub struct GpuConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -159,6 +176,7 @@ impl Default for GpuConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sys module config. `format` tokens: `uptime`, `load1`, `load5`, `load15`, `procs`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct SysConfig {
|
pub struct SysConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -175,6 +193,7 @@ impl Default for SysConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Disk module config. `format` tokens: `mount`, `used`, `total`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct DiskConfig {
|
pub struct DiskConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -191,6 +210,7 @@ impl Default for DiskConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Btrfs pool module config. `format` tokens: `used`, `total`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct PoolConfig {
|
pub struct PoolConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -207,6 +227,7 @@ impl Default for PoolConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Battery/power module config. `format` tokens: `percentage`, `icon`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct PowerConfig {
|
pub struct PowerConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -223,6 +244,7 @@ impl Default for PowerConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Audio module config, one format per (sink|source) × (muted|unmuted) state.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct AudioConfig {
|
pub struct AudioConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -245,6 +267,8 @@ impl Default for AudioConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Bluetooth module config. Plugin line tokens: `alias`, `left`, `right`,
|
||||||
|
/// `anc`, `mac`. Plain connect line tokens: `alias`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct BtConfig {
|
pub struct BtConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -267,6 +291,7 @@ impl Default for BtConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Gamemode indicator config (active/inactive glyphs).
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct GameConfig {
|
pub struct GameConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -285,6 +310,8 @@ impl Default for GameConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// MPRIS module config. `format` tokens: `artist`, `title`, `album`,
|
||||||
|
/// `status_icon`. Optional marquee scrolling when `scroll = true`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct MprisConfig {
|
pub struct MprisConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -321,6 +348,7 @@ impl Default for MprisConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Backlight module config. `format` tokens: `percentage`, `icon`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct BacklightConfig {
|
pub struct BacklightConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -337,6 +365,7 @@ impl Default for BacklightConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Keyboard layout module config. `format` tokens: `layout`.
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct KeyboardConfig {
|
pub struct KeyboardConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -353,6 +382,7 @@ impl Default for KeyboardConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Do-Not-Disturb indicator config (dnd/normal glyphs).
|
||||||
#[derive(Deserialize, Clone)]
|
#[derive(Deserialize, Clone)]
|
||||||
pub struct DndConfig {
|
pub struct DndConfig {
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
@@ -397,41 +427,31 @@ impl Config {
|
|||||||
/// Check if a module is enabled in the configuration.
|
/// Check if a module is enabled in the configuration.
|
||||||
/// Returns false if the module is explicitly disabled; true if enabled or unknown.
|
/// Returns false if the module is explicitly disabled; true if enabled or unknown.
|
||||||
pub fn is_module_enabled(&self, module_name: &str) -> bool {
|
pub fn is_module_enabled(&self, module_name: &str) -> bool {
|
||||||
|
macro_rules! gen_enabled_match {
|
||||||
|
($( { $feature:literal, $field:ident, $state:ty, [$($name:literal),+], [$($sig_name:literal),+], $module:path, $signal:ident, [$($default_arg:literal),*], $config:ident } )*) => {
|
||||||
match module_name {
|
match module_name {
|
||||||
#[cfg(feature = "mod-network")]
|
$(
|
||||||
"net" | "network" => self.network.enabled,
|
#[cfg(feature = $feature)]
|
||||||
#[cfg(feature = "mod-hardware")]
|
$($name)|+ => self.$config.enabled,
|
||||||
"cpu" => self.cpu.enabled,
|
)*
|
||||||
#[cfg(feature = "mod-hardware")]
|
// Dispatch-only modules (no watch channel)
|
||||||
"mem" | "memory" => self.memory.enabled,
|
#[cfg(feature = "mod-audio")]
|
||||||
#[cfg(feature = "mod-hardware")]
|
"mic" => self.audio.enabled,
|
||||||
"gpu" => self.gpu.enabled,
|
|
||||||
#[cfg(feature = "mod-hardware")]
|
|
||||||
"sys" => self.sys.enabled,
|
|
||||||
#[cfg(feature = "mod-hardware")]
|
|
||||||
"disk" => self.disk.enabled,
|
|
||||||
#[cfg(feature = "mod-hardware")]
|
#[cfg(feature = "mod-hardware")]
|
||||||
"pool" | "btrfs" => self.pool.enabled,
|
"pool" | "btrfs" => self.pool.enabled,
|
||||||
#[cfg(feature = "mod-hardware")]
|
#[cfg(feature = "mod-hardware")]
|
||||||
"power" => self.power.enabled,
|
"power" => self.power.enabled,
|
||||||
#[cfg(feature = "mod-hardware")]
|
#[cfg(feature = "mod-hardware")]
|
||||||
"game" => self.game.enabled,
|
"game" => self.game.enabled,
|
||||||
#[cfg(feature = "mod-audio")]
|
|
||||||
"vol" | "audio" | "mic" => self.audio.enabled,
|
|
||||||
#[cfg(feature = "mod-bt")]
|
|
||||||
"bt" | "bluetooth" => self.bt.enabled,
|
|
||||||
#[cfg(feature = "mod-dbus")]
|
|
||||||
"mpris" => self.mpris.enabled,
|
|
||||||
#[cfg(feature = "mod-dbus")]
|
|
||||||
"backlight" => self.backlight.enabled,
|
|
||||||
#[cfg(feature = "mod-dbus")]
|
|
||||||
"kbd" | "keyboard" => self.keyboard.enabled,
|
|
||||||
#[cfg(feature = "mod-dbus")]
|
|
||||||
"dnd" => self.dnd.enabled,
|
|
||||||
_ => true,
|
_ => true,
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for_each_watched_module!(gen_enabled_match)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Warn-log any `{token}` placeholders used in format strings that the
|
||||||
|
/// corresponding module does not know how to fill in.
|
||||||
pub fn validate(&self) {
|
pub fn validate(&self) {
|
||||||
#[cfg(feature = "mod-network")]
|
#[cfg(feature = "mod-network")]
|
||||||
validate_format(
|
validate_format(
|
||||||
@@ -508,6 +528,8 @@ impl Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resolve the default config path: `$XDG_CONFIG_HOME/fluxo/config.toml`
|
||||||
|
/// (or `~/.config/fluxo/config.toml`).
|
||||||
pub fn default_config_path() -> PathBuf {
|
pub fn default_config_path() -> PathBuf {
|
||||||
let config_dir = std::env::var("XDG_CONFIG_HOME")
|
let config_dir = std::env::var("XDG_CONFIG_HOME")
|
||||||
.map(PathBuf::from)
|
.map(PathBuf::from)
|
||||||
@@ -518,6 +540,8 @@ pub fn default_config_path() -> PathBuf {
|
|||||||
config_dir.join("fluxo/config.toml")
|
config_dir.join("fluxo/config.toml")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Load and validate the config, falling back to [`Config::default`] when
|
||||||
|
/// the file is missing or malformed. Never panics.
|
||||||
pub fn load_config(custom_path: Option<PathBuf>) -> Config {
|
pub fn load_config(custom_path: Option<PathBuf>) -> Config {
|
||||||
let config_path = custom_path.unwrap_or_else(default_config_path);
|
let config_path = custom_path.unwrap_or_else(default_config_path);
|
||||||
|
|
||||||
|
|||||||
+59
-17
@@ -1,3 +1,18 @@
|
|||||||
|
//! Daemon entry point: orchestrates polling tasks, signal handling, config
|
||||||
|
//! hot-reloading, and the IPC server.
|
||||||
|
//!
|
||||||
|
//! Layout of [`run_daemon`]:
|
||||||
|
//!
|
||||||
|
//! 1. **Channels** — `watch::channel()` pairs for every module that pushes
|
||||||
|
//! state from a background task.
|
||||||
|
//! 2. **Polling / event tasks** — one per module; each writes into its sender,
|
||||||
|
//! the signaler and request handlers read from the matching receiver.
|
||||||
|
//! 3. **Config watchers** — filesystem notifier + `SIGHUP` handler refresh the
|
||||||
|
//! [`Config`] in place so modules see updates immediately.
|
||||||
|
//! 4. **Signaler** — watches all state receivers and pokes Waybar.
|
||||||
|
//! 5. **IPC loop** — `UnixListener` accepting client requests; each connection
|
||||||
|
//! dispatches to [`crate::registry::dispatch`] and returns JSON.
|
||||||
|
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::ipc::socket_path;
|
use crate::ipc::socket_path;
|
||||||
#[cfg(feature = "mod-audio")]
|
#[cfg(feature = "mod-audio")]
|
||||||
@@ -31,7 +46,11 @@ use tokio::time::{Duration, sleep};
|
|||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
use tracing::{debug, error, info};
|
use tracing::{debug, error, info};
|
||||||
|
|
||||||
/// Spawn a health-tracked polling loop. `$poll_expr` is awaited each cycle.
|
/// Spawn a health-tracked polling loop.
|
||||||
|
///
|
||||||
|
/// Each iteration: skip if in backoff, else await `$poll_expr` and feed the
|
||||||
|
/// `Result` to [`crate::health::handle_poll_result`]. The loop breaks when
|
||||||
|
/// `$token` is cancelled.
|
||||||
macro_rules! spawn_poll_loop {
|
macro_rules! spawn_poll_loop {
|
||||||
($name:expr, $interval:expr, $health:expr, $token:expr, $poll_expr:expr) => {
|
($name:expr, $interval:expr, $health:expr, $token:expr, $poll_expr:expr) => {
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
@@ -51,7 +70,10 @@ macro_rules! spawn_poll_loop {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawn a health-tracked polling loop with an extra trigger channel for early wake-up.
|
/// Spawn a health-tracked polling loop with an extra trigger channel.
|
||||||
|
///
|
||||||
|
/// Identical to [`spawn_poll_loop`] but `$trigger` can wake the loop early —
|
||||||
|
/// used by the Bluetooth daemon when a client forces an immediate refresh.
|
||||||
macro_rules! spawn_poll_loop_triggered {
|
macro_rules! spawn_poll_loop_triggered {
|
||||||
($name:expr, $interval:expr, $health:expr, $token:expr, $trigger:expr, $poll_expr:expr) => {
|
($name:expr, $interval:expr, $health:expr, $token:expr, $trigger:expr, $poll_expr:expr) => {
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
@@ -72,7 +94,10 @@ macro_rules! spawn_poll_loop_triggered {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawn a simple polling loop without health tracking.
|
/// Spawn a polling loop with no health tracking.
|
||||||
|
///
|
||||||
|
/// Used for internal daemons (hardware fast/slow) whose poll functions are
|
||||||
|
/// infallible and whose failures don't drive client-visible backoff.
|
||||||
macro_rules! spawn_poll_loop_simple {
|
macro_rules! spawn_poll_loop_simple {
|
||||||
($name:expr, $interval:expr, $token:expr, $poll_expr:expr) => {
|
($name:expr, $interval:expr, $token:expr, $poll_expr:expr) => {
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
@@ -104,6 +129,11 @@ fn get_config_path(custom_path: Option<PathBuf>) -> PathBuf {
|
|||||||
custom_path.unwrap_or_else(crate::config::default_config_path)
|
custom_path.unwrap_or_else(crate::config::default_config_path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Run the daemon to completion.
|
||||||
|
///
|
||||||
|
/// Sets up the socket, spawns all enabled module tasks, hooks up config
|
||||||
|
/// hot-reloading, and finally enters the IPC accept loop. Returns only on
|
||||||
|
/// a fatal error or `Ctrl+C`.
|
||||||
pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
||||||
let sock_path = socket_path();
|
let sock_path = socket_path();
|
||||||
|
|
||||||
@@ -191,7 +221,8 @@ pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
|||||||
path: sock_path.clone(),
|
path: sock_path.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Signal handling for graceful shutdown
|
// Ctrl+C triggers a graceful shutdown by cancelling this token; every
|
||||||
|
// spawned polling task checks it in its `select!`.
|
||||||
let cancel_token = CancellationToken::new();
|
let cancel_token = CancellationToken::new();
|
||||||
let token_clone = cancel_token.clone();
|
let token_clone = cancel_token.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
@@ -204,7 +235,6 @@ pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
|||||||
let config = Arc::new(RwLock::new(crate::config::load_config(config_path.clone())));
|
let config = Arc::new(RwLock::new(crate::config::load_config(config_path.clone())));
|
||||||
spawn_config_watchers(&config, &resolved_config_path);
|
spawn_config_watchers(&config, &resolved_config_path);
|
||||||
|
|
||||||
// 1. Network Task
|
|
||||||
#[cfg(feature = "mod-network")]
|
#[cfg(feature = "mod-network")]
|
||||||
if config.read().await.network.enabled {
|
if config.read().await.network.enabled {
|
||||||
let mut daemon = NetworkDaemon::new();
|
let mut daemon = NetworkDaemon::new();
|
||||||
@@ -219,7 +249,7 @@ pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Fast Hardware Task (CPU, Mem, Load)
|
// Fast-cycle hardware (cpu/mem/load) polled at 1 Hz.
|
||||||
#[cfg(feature = "mod-hardware")]
|
#[cfg(feature = "mod-hardware")]
|
||||||
{
|
{
|
||||||
let cfg = config.read().await;
|
let cfg = config.read().await;
|
||||||
@@ -237,7 +267,7 @@ pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Slow Hardware Task (GPU, Disks)
|
// Slow-cycle hardware (gpu/disks) polled every 5 s — expensive to sample.
|
||||||
#[cfg(feature = "mod-hardware")]
|
#[cfg(feature = "mod-hardware")]
|
||||||
{
|
{
|
||||||
let cfg = config.read().await;
|
let cfg = config.read().await;
|
||||||
@@ -255,7 +285,6 @@ pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Bluetooth Task
|
|
||||||
#[cfg(feature = "mod-bt")]
|
#[cfg(feature = "mod-bt")]
|
||||||
if config.read().await.bt.enabled {
|
if config.read().await.bt.enabled {
|
||||||
let mut daemon = BtDaemon::new();
|
let mut daemon = BtDaemon::new();
|
||||||
@@ -270,41 +299,38 @@ pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Audio Thread (Event driven)
|
// Event-driven subsystems — these spawn their own threads internally and
|
||||||
|
// push into their watch sender as events arrive (no polling loop).
|
||||||
#[cfg(feature = "mod-audio")]
|
#[cfg(feature = "mod-audio")]
|
||||||
if config.read().await.audio.enabled {
|
if config.read().await.audio.enabled {
|
||||||
let audio_daemon = AudioDaemon::new();
|
let audio_daemon = AudioDaemon::new();
|
||||||
audio_daemon.start(&audio_tx, audio_cmd_rx);
|
audio_daemon.start(&audio_tx, audio_cmd_rx);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5.1 Backlight Thread (Event driven)
|
|
||||||
#[cfg(feature = "mod-dbus")]
|
#[cfg(feature = "mod-dbus")]
|
||||||
if config.read().await.backlight.enabled {
|
if config.read().await.backlight.enabled {
|
||||||
let backlight_daemon = BacklightDaemon::new();
|
let backlight_daemon = BacklightDaemon::new();
|
||||||
backlight_daemon.start(backlight_tx);
|
backlight_daemon.start(backlight_tx);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5.2 Keyboard Thread (Event driven)
|
|
||||||
#[cfg(feature = "mod-dbus")]
|
#[cfg(feature = "mod-dbus")]
|
||||||
if config.read().await.keyboard.enabled {
|
if config.read().await.keyboard.enabled {
|
||||||
let keyboard_daemon = KeyboardDaemon::new();
|
let keyboard_daemon = KeyboardDaemon::new();
|
||||||
keyboard_daemon.start(keyboard_tx);
|
keyboard_daemon.start(keyboard_tx);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5.3 DND Thread (Event driven)
|
|
||||||
#[cfg(feature = "mod-dbus")]
|
#[cfg(feature = "mod-dbus")]
|
||||||
if config.read().await.dnd.enabled {
|
if config.read().await.dnd.enabled {
|
||||||
let dnd_daemon = DndDaemon::new();
|
let dnd_daemon = DndDaemon::new();
|
||||||
dnd_daemon.start(dnd_tx);
|
dnd_daemon.start(dnd_tx);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5.4 MPRIS Thread
|
|
||||||
#[cfg(feature = "mod-dbus")]
|
#[cfg(feature = "mod-dbus")]
|
||||||
if config.read().await.mpris.enabled {
|
if config.read().await.mpris.enabled {
|
||||||
let mpris_daemon = MprisDaemon::new();
|
let mpris_daemon = MprisDaemon::new();
|
||||||
mpris_daemon.start(mpris_tx);
|
mpris_daemon.start(mpris_tx);
|
||||||
|
|
||||||
// Scroll ticker for MPRIS marquee animation
|
// Ticks the scroll offset forward for the marquee animation.
|
||||||
let scroll_config = Arc::clone(&config);
|
let scroll_config = Arc::clone(&config);
|
||||||
let scroll_rx = receivers.mpris.clone();
|
let scroll_rx = receivers.mpris.clone();
|
||||||
let scroll_state = Arc::clone(&mpris_scroll);
|
let scroll_state = Arc::clone(&mpris_scroll);
|
||||||
@@ -319,7 +345,6 @@ pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Waybar Signaler Task
|
|
||||||
let signaler = WaybarSignaler::new();
|
let signaler = WaybarSignaler::new();
|
||||||
let sig_config = Arc::clone(&config);
|
let sig_config = Arc::clone(&config);
|
||||||
let sig_receivers = receivers.clone();
|
let sig_receivers = receivers.clone();
|
||||||
@@ -332,8 +357,14 @@ pub async fn run_daemon(config_path: Option<PathBuf>) -> Result<()> {
|
|||||||
run_ipc_loop(listener, receivers, config, config_path, cancel_token).await
|
run_ipc_loop(listener, receivers, config, config_path, cancel_token).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Spawn background tasks that hot-reload the daemon's [`Config`].
|
||||||
|
///
|
||||||
|
/// Installs a `notify`-based filesystem watcher on the config file's parent
|
||||||
|
/// directory, plus a `SIGHUP` handler — either triggers a reload of the
|
||||||
|
/// shared `Arc<RwLock<Config>>`.
|
||||||
fn spawn_config_watchers(config: &Arc<RwLock<Config>>, resolved_path: &std::path::Path) {
|
fn spawn_config_watchers(config: &Arc<RwLock<Config>>, resolved_path: &std::path::Path) {
|
||||||
// File watcher (hot reload on modify/create)
|
// `notify` recursively tracks the parent dir so atomic-write editors
|
||||||
|
// (which rename a new file into place) still get picked up.
|
||||||
let watcher_config = Arc::clone(config);
|
let watcher_config = Arc::clone(config);
|
||||||
let watcher_path = resolved_path.to_path_buf();
|
let watcher_path = resolved_path.to_path_buf();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
@@ -359,6 +390,7 @@ fn spawn_config_watchers(config: &Arc<RwLock<Config>>, resolved_path: &std::path
|
|||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
_ = ev_rx.recv() => {
|
_ = ev_rx.recv() => {
|
||||||
|
// Coalesce rapid editor writes into one reload.
|
||||||
sleep(Duration::from_millis(100)).await;
|
sleep(Duration::from_millis(100)).await;
|
||||||
while ev_rx.try_recv().is_ok() {}
|
while ev_rx.try_recv().is_ok() {}
|
||||||
reload_config(&watcher_config, Some(watcher_path.clone())).await;
|
reload_config(&watcher_config, Some(watcher_path.clone())).await;
|
||||||
@@ -367,7 +399,6 @@ fn spawn_config_watchers(config: &Arc<RwLock<Config>>, resolved_path: &std::path
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// SIGHUP handler
|
|
||||||
let hup_config = Arc::clone(config);
|
let hup_config = Arc::clone(config);
|
||||||
let hup_path = resolved_path.to_path_buf();
|
let hup_path = resolved_path.to_path_buf();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
@@ -381,6 +412,12 @@ fn spawn_config_watchers(config: &Arc<RwLock<Config>>, resolved_path: &std::path
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Accept loop for the client Unix socket.
|
||||||
|
///
|
||||||
|
/// Each client request spawns a short-lived task that reads one line, looks
|
||||||
|
/// up the module via [`crate::registry::dispatch`], and writes the JSON
|
||||||
|
/// response back. Broken-pipe errors are logged at `debug` — they just mean
|
||||||
|
/// the client timed out before we responded.
|
||||||
async fn run_ipc_loop(
|
async fn run_ipc_loop(
|
||||||
listener: UnixListener,
|
listener: UnixListener,
|
||||||
receivers: AppReceivers,
|
receivers: AppReceivers,
|
||||||
@@ -447,6 +484,7 @@ async fn run_ipc_loop(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Re-read the configuration file and swap it into the shared lock.
|
||||||
pub async fn reload_config(config_lock: &Arc<RwLock<Config>>, path: Option<PathBuf>) {
|
pub async fn reload_config(config_lock: &Arc<RwLock<Config>>, path: Option<PathBuf>) {
|
||||||
info!("Reloading configuration...");
|
info!("Reloading configuration...");
|
||||||
let new_config = crate::config::load_config(path);
|
let new_config = crate::config::load_config(path);
|
||||||
@@ -455,6 +493,10 @@ pub async fn reload_config(config_lock: &Arc<RwLock<Config>>, path: Option<PathB
|
|||||||
info!("Configuration reloaded successfully.");
|
info!("Configuration reloaded successfully.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Evaluate a module with its signaler-default args and return the JSON body.
|
||||||
|
///
|
||||||
|
/// Used by the [`crate::signaler`] to decide whether the module's output has
|
||||||
|
/// actually changed before sending Waybar a signal.
|
||||||
pub async fn evaluate_module_for_signaler(
|
pub async fn evaluate_module_for_signaler(
|
||||||
module_name: &str,
|
module_name: &str,
|
||||||
state: &AppReceivers,
|
state: &AppReceivers,
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
|
//! Error types used across the crate.
|
||||||
|
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
|
/// Canonical error type for all fluxo subsystems.
|
||||||
|
///
|
||||||
|
/// Errors are categorised so that [`FluxoError::is_transient`] can distinguish
|
||||||
|
/// temporary runtime failures (retried with backoff) from permanent ones.
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub enum FluxoError {
|
pub enum FluxoError {
|
||||||
@@ -41,6 +47,9 @@ pub enum FluxoError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FluxoError {
|
impl FluxoError {
|
||||||
|
/// Returns `true` for errors that represent likely-transient failures
|
||||||
|
/// (IO, external systems, hardware) and should trigger exponential backoff
|
||||||
|
/// rather than permanent cooldown.
|
||||||
pub fn is_transient(&self) -> bool {
|
pub fn is_transient(&self) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
self,
|
self,
|
||||||
@@ -54,4 +63,5 @@ impl FluxoError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Crate-wide `Result` alias using [`FluxoError`].
|
||||||
pub type Result<T> = std::result::Result<T, FluxoError>;
|
pub type Result<T> = std::result::Result<T, FluxoError>;
|
||||||
|
|||||||
@@ -1,3 +1,10 @@
|
|||||||
|
//! Per-module health tracking and exponential backoff.
|
||||||
|
//!
|
||||||
|
//! Both the IPC request handler (for on-demand module evaluation) and the
|
||||||
|
//! background polling loops consult this module. Transient errors increment a
|
||||||
|
//! failure counter that grows the cooldown window; permanent errors trigger an
|
||||||
|
//! immediate long cooldown.
|
||||||
|
|
||||||
use crate::output::WaybarOutput;
|
use crate::output::WaybarOutput;
|
||||||
use crate::state::{AppReceivers, ModuleHealth};
|
use crate::state::{AppReceivers, ModuleHealth};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -101,6 +108,10 @@ pub async fn handle_poll_result(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Serialise a response to return while a module is cooling down.
|
||||||
|
///
|
||||||
|
/// If a cached successful output exists, it is returned with a `warning` CSS
|
||||||
|
/// class appended; otherwise a generic "Cooling down" placeholder is emitted.
|
||||||
pub fn backoff_response(module_name: &str, cached: Option<WaybarOutput>) -> String {
|
pub fn backoff_response(module_name: &str, cached: Option<WaybarOutput>) -> String {
|
||||||
if let Some(mut cached) = cached {
|
if let Some(mut cached) = cached {
|
||||||
let class = cached.class.unwrap_or_default();
|
let class = cached.class.unwrap_or_default();
|
||||||
@@ -113,6 +124,10 @@ pub fn backoff_response(module_name: &str, cached: Option<WaybarOutput>) -> Stri
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Serialise a fallback response for a module that errored this request.
|
||||||
|
///
|
||||||
|
/// Prefers showing the last successful cached output (with a `warning` class)
|
||||||
|
/// over a bare error text, to keep the bar visually stable.
|
||||||
pub fn error_response(
|
pub fn error_response(
|
||||||
module_name: &str,
|
module_name: &str,
|
||||||
e: &crate::error::FluxoError,
|
e: &crate::error::FluxoError,
|
||||||
|
|||||||
+11
-1
@@ -1,8 +1,16 @@
|
|||||||
|
//! Client/daemon Unix socket IPC.
|
||||||
|
//!
|
||||||
|
//! Requests are newline-terminated `module arg1 arg2...` lines; responses are
|
||||||
|
//! the daemon's JSON payload written until EOF.
|
||||||
|
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::os::unix::net::UnixStream;
|
use std::os::unix::net::UnixStream;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tracing::debug;
|
use tracing::debug;
|
||||||
|
|
||||||
|
/// Returns the path to the daemon's Unix socket.
|
||||||
|
///
|
||||||
|
/// Prefers `$XDG_RUNTIME_DIR/fluxo.sock`, falling back to `/tmp/fluxo.sock`.
|
||||||
pub fn socket_path() -> String {
|
pub fn socket_path() -> String {
|
||||||
if let Ok(dir) = std::env::var("XDG_RUNTIME_DIR") {
|
if let Ok(dir) = std::env::var("XDG_RUNTIME_DIR") {
|
||||||
format!("{}/fluxo.sock", dir)
|
format!("{}/fluxo.sock", dir)
|
||||||
@@ -11,13 +19,15 @@ pub fn socket_path() -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Send a module invocation to the daemon and return its response body.
|
||||||
|
///
|
||||||
|
/// Blocks for up to 5 seconds waiting for the daemon to reply.
|
||||||
pub fn request_data(module: &str, args: &[&str]) -> anyhow::Result<String> {
|
pub fn request_data(module: &str, args: &[&str]) -> anyhow::Result<String> {
|
||||||
let sock = socket_path();
|
let sock = socket_path();
|
||||||
debug!(module, ?args, "Connecting to daemon socket: {}", sock);
|
debug!(module, ?args, "Connecting to daemon socket: {}", sock);
|
||||||
let mut stream = UnixStream::connect(&sock)?;
|
let mut stream = UnixStream::connect(&sock)?;
|
||||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||||
|
|
||||||
// Send module and args
|
|
||||||
let mut request = module.to_string();
|
let mut request = module.to_string();
|
||||||
for arg in args {
|
for arg in args {
|
||||||
request.push(' ');
|
request.push(' ');
|
||||||
|
|||||||
@@ -1,3 +1,10 @@
|
|||||||
|
//! Central declarative macro that registers every watched module.
|
||||||
|
//!
|
||||||
|
//! Every piece of per-module boilerplate (AppReceivers field, IPC dispatch arm,
|
||||||
|
//! signaler future binding, signaler select arm, config enabled-lookup, default
|
||||||
|
//! signaler args) is generated from this single table. Adding a new module is
|
||||||
|
//! a one-line edit here plus writing the module file itself.
|
||||||
|
|
||||||
/// Central module registry. Defines all modules with watch channels in one place.
|
/// Central module registry. Defines all modules with watch channels in one place.
|
||||||
///
|
///
|
||||||
/// Invoke with a callback macro name. The callback receives repeated entries of the form:
|
/// Invoke with a callback macro name. The callback receives repeated entries of the form:
|
||||||
|
|||||||
+30
-11
@@ -1,3 +1,17 @@
|
|||||||
|
//! `fluxo` — high-performance daemon/client for Waybar custom modules.
|
||||||
|
//!
|
||||||
|
//! The binary has two faces:
|
||||||
|
//! * `fluxo daemon` — starts a long-lived process that polls system state
|
||||||
|
//! (network, cpu, audio, bluetooth, …) on background tasks and exposes the
|
||||||
|
//! results over a Unix socket. It also sends `SIGRTMIN+N` signals to Waybar
|
||||||
|
//! when module output changes, so the bar refreshes instantly.
|
||||||
|
//! * `fluxo <module> [args]` — a tiny client that asks the daemon to evaluate
|
||||||
|
//! a single module and prints the Waybar-compatible JSON to stdout.
|
||||||
|
//!
|
||||||
|
//! Modules are feature-gated at compile time (`mod-audio`, `mod-bt`, `mod-dbus`,
|
||||||
|
//! `mod-hardware`, `mod-network`) and registered centrally via the
|
||||||
|
//! [`for_each_watched_module!`] macro in [`mod@macros`].
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
mod macros;
|
mod macros;
|
||||||
mod config;
|
mod config;
|
||||||
@@ -79,14 +93,15 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(module) = &cli.module {
|
if let Some(module) = &cli.module {
|
||||||
// Special case for client-side Bluetooth menu which requires UI
|
// Bluetooth menu is handled client-side: it needs access to the user's
|
||||||
|
// menu command (rofi/dmenu/wofi) which the daemon has no business spawning.
|
||||||
#[cfg(feature = "mod-bt")]
|
#[cfg(feature = "mod-bt")]
|
||||||
if module == "bt" && cli.args.first().map(|s| s.as_str()) == Some("menu") {
|
if module == "bt" && cli.args.first().map(|s| s.as_str()) == Some("menu") {
|
||||||
let config = config::load_config(None);
|
let config = config::load_config(None);
|
||||||
let mut items = Vec::new();
|
let mut items = Vec::new();
|
||||||
|
|
||||||
// Parse menu_data to get connected and paired devices
|
// Ask the daemon for the device list; tuples are (alias, mac).
|
||||||
let mut connected: Vec<(String, String)> = Vec::new(); // (alias, mac)
|
let mut connected: Vec<(String, String)> = Vec::new();
|
||||||
let mut paired: Vec<(String, String)> = Vec::new();
|
let mut paired: Vec<(String, String)> = Vec::new();
|
||||||
|
|
||||||
if let Ok(json_str) = ipc::request_data("bt", &["menu_data"])
|
if let Ok(json_str) = ipc::request_data("bt", &["menu_data"])
|
||||||
@@ -106,9 +121,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Per-device sections for connected devices
|
|
||||||
for (alias, mac) in &connected {
|
for (alias, mac) in &connected {
|
||||||
// Get modes for this specific device
|
|
||||||
if let Ok(json_str) = ipc::request_data("bt", &["get_modes", mac])
|
if let Ok(json_str) = ipc::request_data("bt", &["get_modes", mac])
|
||||||
&& let Ok(val) = serde_json::from_str::<serde_json::Value>(&json_str)
|
&& let Ok(val) = serde_json::from_str::<serde_json::Value>(&json_str)
|
||||||
&& let Some(modes_str) = val.get("text").and_then(|t| t.as_str())
|
&& let Some(modes_str) = val.get("text").and_then(|t| t.as_str())
|
||||||
@@ -121,7 +134,6 @@ fn main() {
|
|||||||
items.push(format!("Disconnect {} [{}]", alias, mac));
|
items.push(format!("Disconnect {} [{}]", alias, mac));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Separator and paired devices for connecting
|
|
||||||
if !paired.is_empty() {
|
if !paired.is_empty() {
|
||||||
items.push("--- Connect Device ---".to_string());
|
items.push("--- Connect Device ---".to_string());
|
||||||
for (alias, mac) in &paired {
|
for (alias, mac) in &paired {
|
||||||
@@ -134,7 +146,7 @@ fn main() {
|
|||||||
utils::show_menu("BT Menu: ", &items, &config.general.menu_command)
|
utils::show_menu("BT Menu: ", &items, &config.general.menu_command)
|
||||||
{
|
{
|
||||||
if selected.contains(": Mode: ") {
|
if selected.contains(": Mode: ") {
|
||||||
// "<alias>: Mode: <mode> [<MAC>]"
|
// Parse "<alias>: Mode: <mode> [<MAC>]".
|
||||||
if let Some(bracket_start) = selected.rfind('[')
|
if let Some(bracket_start) = selected.rfind('[')
|
||||||
&& let Some(bracket_end) = selected.rfind(']')
|
&& let Some(bracket_end) = selected.rfind(']')
|
||||||
{
|
{
|
||||||
@@ -149,7 +161,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if selected.starts_with("Disconnect ") {
|
} else if selected.starts_with("Disconnect ") {
|
||||||
// "Disconnect <alias> [<MAC>]"
|
// Parse "Disconnect <alias> [<MAC>]".
|
||||||
if let Some(bracket_start) = selected.rfind('[')
|
if let Some(bracket_start) = selected.rfind('[')
|
||||||
&& let Some(bracket_end) = selected.rfind(']')
|
&& let Some(bracket_end) = selected.rfind(']')
|
||||||
{
|
{
|
||||||
@@ -157,7 +169,7 @@ fn main() {
|
|||||||
handle_ipc_response(ipc::request_data("bt", &["disconnect", mac]));
|
handle_ipc_response(ipc::request_data("bt", &["disconnect", mac]));
|
||||||
}
|
}
|
||||||
} else if selected == "--- Connect Device ---" {
|
} else if selected == "--- Connect Device ---" {
|
||||||
// separator, do nothing
|
// section header
|
||||||
} else if let Some(mac_start) = selected.rfind('(')
|
} else if let Some(mac_start) = selected.rfind('(')
|
||||||
&& let Some(mac_end) = selected.rfind(')')
|
&& let Some(mac_end) = selected.rfind(')')
|
||||||
{
|
{
|
||||||
@@ -171,8 +183,8 @@ fn main() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generic module dispatch
|
// `vol` and `mic` both dispatch to the audio module; we just prepend
|
||||||
// Translate module-specific shorthand targets
|
// the "sink" / "source" argument so the server picks the right device.
|
||||||
let (actual_module, actual_args) = if module == "vol" {
|
let (actual_module, actual_args) = if module == "vol" {
|
||||||
let mut new_args = vec!["sink".to_string()];
|
let mut new_args = vec!["sink".to_string()];
|
||||||
new_args.extend(cli.args.clone());
|
new_args.extend(cli.args.clone());
|
||||||
@@ -193,6 +205,13 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Post-process the daemon's response for direct output to Waybar.
|
||||||
|
///
|
||||||
|
/// Normal spaces are replaced with figure-spaces (U+2007) so Waybar's
|
||||||
|
/// proportional font does not jitter between updates, and the text is wrapped
|
||||||
|
/// in zero-width spaces (U+200B) as a cosmetic padding trick. Markup strings
|
||||||
|
/// (containing `<`) pass through untouched. On IPC failure an `error` output
|
||||||
|
/// is emitted and the client exits non-zero.
|
||||||
fn handle_ipc_response(response: anyhow::Result<String>) {
|
fn handle_ipc_response(response: anyhow::Result<String>) {
|
||||||
match response {
|
match response {
|
||||||
Ok(json_str) => match serde_json::from_str::<serde_json::Value>(&json_str) {
|
Ok(json_str) => match serde_json::from_str::<serde_json::Value>(&json_str) {
|
||||||
|
|||||||
+55
-38
@@ -143,16 +143,50 @@ impl HardwareDaemon {
|
|||||||
async fn poll_gpu(&mut self, gpu: &mut crate::state::GpuState) {
|
async fn poll_gpu(&mut self, gpu: &mut crate::state::GpuState) {
|
||||||
gpu.active = false;
|
gpu.active = false;
|
||||||
|
|
||||||
if (self.gpu_vendor.as_deref() == Some("NVIDIA") || self.gpu_vendor.is_none())
|
match self.gpu_vendor.as_deref() {
|
||||||
&& let Ok(output) = tokio::process::Command::new("nvidia-smi")
|
Some("NVIDIA") => {
|
||||||
|
Self::poll_nvidia(gpu).await;
|
||||||
|
}
|
||||||
|
Some("AMD") => {
|
||||||
|
Self::poll_amd(gpu);
|
||||||
|
}
|
||||||
|
Some("Intel") => {
|
||||||
|
Self::poll_intel(gpu);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
// Detection pass: try each vendor, cache the first that responds.
|
||||||
|
Self::poll_nvidia(gpu).await;
|
||||||
|
if gpu.active {
|
||||||
|
self.gpu_vendor = Some("NVIDIA".to_string());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Self::poll_amd(gpu);
|
||||||
|
if gpu.active {
|
||||||
|
self.gpu_vendor = Some("AMD".to_string());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Self::poll_intel(gpu);
|
||||||
|
if gpu.active {
|
||||||
|
self.gpu_vendor = Some("Intel".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn poll_nvidia(gpu: &mut crate::state::GpuState) {
|
||||||
|
let Ok(output) = tokio::process::Command::new("nvidia-smi")
|
||||||
.args([
|
.args([
|
||||||
"--query-gpu=utilization.gpu,memory.used,memory.total,temperature.gpu,name",
|
"--query-gpu=utilization.gpu,memory.used,memory.total,temperature.gpu,name",
|
||||||
"--format=csv,noheader,nounits",
|
"--format=csv,noheader,nounits",
|
||||||
])
|
])
|
||||||
.output()
|
.output()
|
||||||
.await
|
.await
|
||||||
&& output.status.success()
|
else {
|
||||||
{
|
return;
|
||||||
|
};
|
||||||
|
if !output.status.success() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||||
if let Some(line) = stdout.lines().next() {
|
if let Some(line) = stdout.lines().next() {
|
||||||
let parts: Vec<&str> = line.split(',').collect();
|
let parts: Vec<&str> = line.split(',').collect();
|
||||||
@@ -164,42 +198,30 @@ impl HardwareDaemon {
|
|||||||
gpu.vram_total = parts[2].trim().parse::<f64>().unwrap_or(0.0) / 1024.0;
|
gpu.vram_total = parts[2].trim().parse::<f64>().unwrap_or(0.0) / 1024.0;
|
||||||
gpu.temp = parts[3].trim().parse().unwrap_or(0.0);
|
gpu.temp = parts[3].trim().parse().unwrap_or(0.0);
|
||||||
gpu.model = parts[4].trim().to_string();
|
gpu.model = parts[4].trim().to_string();
|
||||||
self.gpu_vendor = Some("NVIDIA".to_string());
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.gpu_vendor.as_deref() == Some("AMD")
|
fn poll_amd(gpu: &mut crate::state::GpuState) {
|
||||||
|| self.gpu_vendor.as_deref() == Some("Intel")
|
|
||||||
|| self.gpu_vendor.is_none()
|
|
||||||
{
|
|
||||||
for i in 0..=3 {
|
for i in 0..=3 {
|
||||||
let base = format!("/sys/class/drm/card{}/device", i);
|
let base = format!("/sys/class/drm/card{}/device", i);
|
||||||
|
let Ok(usage_str) = std::fs::read_to_string(format!("{}/gpu_busy_percent", base))
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
if (self.gpu_vendor.as_deref() == Some("AMD") || self.gpu_vendor.is_none())
|
|
||||||
&& let Ok(usage_str) =
|
|
||||||
std::fs::read_to_string(format!("{}/gpu_busy_percent", base))
|
|
||||||
{
|
|
||||||
gpu.active = true;
|
gpu.active = true;
|
||||||
gpu.vendor = "AMD".to_string();
|
gpu.vendor = "AMD".to_string();
|
||||||
gpu.usage = usage_str.trim().parse().unwrap_or(0.0);
|
gpu.usage = usage_str.trim().parse().unwrap_or(0.0);
|
||||||
|
|
||||||
if let Ok(mem_used) =
|
if let Ok(mem_used) = std::fs::read_to_string(format!("{}/mem_info_vram_used", base)) {
|
||||||
std::fs::read_to_string(format!("{}/mem_info_vram_used", base))
|
gpu.vram_used =
|
||||||
{
|
mem_used.trim().parse::<f64>().unwrap_or(0.0) / 1024.0 / 1024.0 / 1024.0;
|
||||||
gpu.vram_used = mem_used.trim().parse::<f64>().unwrap_or(0.0)
|
|
||||||
/ 1024.0
|
|
||||||
/ 1024.0
|
|
||||||
/ 1024.0;
|
|
||||||
}
|
}
|
||||||
if let Ok(mem_total) =
|
if let Ok(mem_total) = std::fs::read_to_string(format!("{}/mem_info_vram_total", base))
|
||||||
std::fs::read_to_string(format!("{}/mem_info_vram_total", base))
|
|
||||||
{
|
{
|
||||||
gpu.vram_total = mem_total.trim().parse::<f64>().unwrap_or(0.0)
|
gpu.vram_total =
|
||||||
/ 1024.0
|
mem_total.trim().parse::<f64>().unwrap_or(0.0) / 1024.0 / 1024.0 / 1024.0;
|
||||||
/ 1024.0
|
|
||||||
/ 1024.0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Ok(entries) = std::fs::read_dir(format!("{}/hwmon", base)) {
|
if let Ok(entries) = std::fs::read_dir(format!("{}/hwmon", base)) {
|
||||||
@@ -212,18 +234,16 @@ impl HardwareDaemon {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
gpu.model = "AMD GPU".to_string();
|
gpu.model = "AMD GPU".to_string();
|
||||||
self.gpu_vendor = Some("AMD".to_string());
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if self.gpu_vendor.as_deref() == Some("Intel") || self.gpu_vendor.is_none() {
|
fn poll_intel(gpu: &mut crate::state::GpuState) {
|
||||||
let freq_path =
|
for i in 0..=3 {
|
||||||
if std::path::Path::new(&format!("{}/gt_cur_freq_mhz", base)).exists() {
|
let base = format!("/sys/class/drm/card{}/device", i);
|
||||||
|
let freq_path = if std::path::Path::new(&format!("{}/gt_cur_freq_mhz", base)).exists() {
|
||||||
Some(format!("{}/gt_cur_freq_mhz", base))
|
Some(format!("{}/gt_cur_freq_mhz", base))
|
||||||
} else if std::path::Path::new(&format!(
|
} else if std::path::Path::new(&format!("/sys/class/drm/card{}/gt_cur_freq_mhz", i))
|
||||||
"/sys/class/drm/card{}/gt_cur_freq_mhz",
|
|
||||||
i
|
|
||||||
))
|
|
||||||
.exists()
|
.exists()
|
||||||
{
|
{
|
||||||
Some(format!("/sys/class/drm/card{}/gt_cur_freq_mhz", i))
|
Some(format!("/sys/class/drm/card{}/gt_cur_freq_mhz", i))
|
||||||
@@ -254,11 +274,8 @@ impl HardwareDaemon {
|
|||||||
gpu.vram_used = 0.0;
|
gpu.vram_used = 0.0;
|
||||||
gpu.vram_total = 0.0;
|
gpu.vram_total = 0.0;
|
||||||
gpu.model = format!("Intel iGPU ({}MHz)", cur_freq);
|
gpu.model = format!("Intel iGPU ({}MHz)", cur_freq);
|
||||||
self.gpu_vendor = Some("Intel".to_string());
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,3 +1,17 @@
|
|||||||
|
//! Waybar module implementations.
|
||||||
|
//!
|
||||||
|
//! Each submodule exposes a [`WaybarModule`] type (CPU, network, audio, …)
|
||||||
|
//! and is feature-gated by a `mod-<kind>` flag. The [`WaybarModule`] trait is
|
||||||
|
//! what [`crate::registry::dispatch`] uses to evaluate a module on demand.
|
||||||
|
//!
|
||||||
|
//! Modules come in two flavours:
|
||||||
|
//!
|
||||||
|
//! * **Watched** — the daemon spawns a background polling/event task that
|
||||||
|
//! pushes state into a `watch::Receiver`, which the module reads lock-free
|
||||||
|
//! (network, cpu, audio, bluetooth, …).
|
||||||
|
//! * **Dispatch-only** — evaluated on demand only, without a watch channel
|
||||||
|
//! (power, game, btrfs).
|
||||||
|
|
||||||
#[cfg(feature = "mod-audio")]
|
#[cfg(feature = "mod-audio")]
|
||||||
pub mod audio;
|
pub mod audio;
|
||||||
#[cfg(feature = "mod-dbus")]
|
#[cfg(feature = "mod-dbus")]
|
||||||
@@ -36,7 +50,14 @@ use crate::error::Result as FluxoResult;
|
|||||||
use crate::output::WaybarOutput;
|
use crate::output::WaybarOutput;
|
||||||
use crate::state::AppReceivers;
|
use crate::state::AppReceivers;
|
||||||
|
|
||||||
|
/// Common interface implemented by every Waybar module.
|
||||||
|
///
|
||||||
|
/// Given the current daemon config, the shared state receivers, and any
|
||||||
|
/// caller-supplied arguments, a module produces a single [`WaybarOutput`].
|
||||||
|
/// Implementations must be cheap to evaluate — they are invoked on every
|
||||||
|
/// client request and on every signaler state change.
|
||||||
pub trait WaybarModule {
|
pub trait WaybarModule {
|
||||||
|
/// Evaluate the module and return its rendered output.
|
||||||
fn run(
|
fn run(
|
||||||
&self,
|
&self,
|
||||||
config: &Config,
|
config: &Config,
|
||||||
|
|||||||
+78
-40
@@ -201,39 +201,99 @@ impl MprisDaemon {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn listen_loop(tx: &watch::Sender<MprisState>) -> anyhow::Result<()> {
|
async fn listen_loop(tx: &watch::Sender<MprisState>) -> anyhow::Result<()> {
|
||||||
|
use futures::StreamExt;
|
||||||
|
|
||||||
let connection = Connection::session().await?;
|
let connection = Connection::session().await?;
|
||||||
|
|
||||||
info!("Connected to D-Bus for MPRIS monitoring");
|
info!("Connected to D-Bus for MPRIS monitoring");
|
||||||
|
|
||||||
// Periodically poll for the active player and update the MPRIS state.
|
|
||||||
// This avoids complex dynamic signal tracking across ephemeral player instances.
|
|
||||||
|
|
||||||
let dbus_proxy = DBusProxy::new(&connection).await?;
|
let dbus_proxy = DBusProxy::new(&connection).await?;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
// Discovery pass: find an active MPRIS player.
|
||||||
let names = dbus_proxy.list_names().await?;
|
let names = dbus_proxy.list_names().await?;
|
||||||
let mut active_player = None;
|
let active_player = names
|
||||||
|
.into_iter()
|
||||||
|
.find(|n| n.starts_with("org.mpris.MediaPlayer2."));
|
||||||
|
|
||||||
for name in names {
|
let Some(player_name) = active_player else {
|
||||||
if name.starts_with("org.mpris.MediaPlayer2.") {
|
send_stopped_if_changed(tx);
|
||||||
active_player = Some(name);
|
// No player — wait and re-discover.
|
||||||
break; // Just grab the first active player for now
|
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||||
}
|
continue;
|
||||||
}
|
};
|
||||||
|
|
||||||
if let Some(player_name) = active_player {
|
let player_proxy = match MprisPlayerProxy::builder(&connection)
|
||||||
if let Ok(player_proxy) = MprisPlayerProxy::builder(&connection)
|
|
||||||
.destination(player_name.clone())?
|
.destination(player_name.clone())?
|
||||||
.build()
|
.build()
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
let status = player_proxy.playback_status().await.unwrap_or_default();
|
Ok(p) => p,
|
||||||
let metadata = player_proxy.metadata().await.unwrap_or_default();
|
Err(_) => {
|
||||||
|
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Initial fetch and then signal-driven updates via PropertiesChanged.
|
||||||
|
update_from_player(&player_proxy, tx).await;
|
||||||
|
|
||||||
|
let mut status_stream = player_proxy.receive_playback_status_changed().await;
|
||||||
|
let mut metadata_stream = player_proxy.receive_metadata_changed().await;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
Some(_) = status_stream.next() => {
|
||||||
|
update_from_player(&player_proxy, tx).await;
|
||||||
|
}
|
||||||
|
Some(_) = metadata_stream.next() => {
|
||||||
|
update_from_player(&player_proxy, tx).await;
|
||||||
|
}
|
||||||
|
_ = tokio::time::sleep(Duration::from_secs(10)) => {
|
||||||
|
// Heartbeat: verify the player is still on the bus.
|
||||||
|
let current = dbus_proxy.list_names().await.unwrap_or_default();
|
||||||
|
if !current.iter().any(|n| n == &player_name) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_from_player(player: &MprisPlayerProxy<'_>, tx: &watch::Sender<MprisState>) {
|
||||||
|
let status = player.playback_status().await.unwrap_or_default();
|
||||||
|
let metadata = player.metadata().await.unwrap_or_default();
|
||||||
|
|
||||||
let is_playing = status == "Playing";
|
let is_playing = status == "Playing";
|
||||||
let is_paused = status == "Paused";
|
let is_paused = status == "Paused";
|
||||||
let is_stopped = status == "Stopped";
|
let is_stopped = status == "Stopped";
|
||||||
|
|
||||||
|
let (artist, title, album) = parse_metadata(&metadata);
|
||||||
|
|
||||||
|
let current = tx.borrow();
|
||||||
|
if current.is_playing != is_playing
|
||||||
|
|| current.is_paused != is_paused
|
||||||
|
|| current.is_stopped != is_stopped
|
||||||
|
|| current.title != title
|
||||||
|
|| current.artist != artist
|
||||||
|
|| current.album != album
|
||||||
|
{
|
||||||
|
drop(current);
|
||||||
|
let _ = tx.send(MprisState {
|
||||||
|
is_playing,
|
||||||
|
is_paused,
|
||||||
|
is_stopped,
|
||||||
|
artist,
|
||||||
|
title,
|
||||||
|
album,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_metadata(
|
||||||
|
metadata: &std::collections::HashMap<String, zbus::zvariant::Value<'_>>,
|
||||||
|
) -> (String, String, String) {
|
||||||
let mut artist = String::new();
|
let mut artist = String::new();
|
||||||
let mut title = String::new();
|
let mut title = String::new();
|
||||||
let mut album = String::new();
|
let mut album = String::new();
|
||||||
@@ -262,27 +322,10 @@ impl MprisDaemon {
|
|||||||
album = a.to_string();
|
album = a.to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only send if changed
|
(artist, title, album)
|
||||||
let current = tx.borrow();
|
|
||||||
if current.is_playing != is_playing
|
|
||||||
|| current.is_paused != is_paused
|
|
||||||
|| current.is_stopped != is_stopped
|
|
||||||
|| current.title != title
|
|
||||||
|| current.artist != artist
|
|
||||||
|| current.album != album
|
|
||||||
{
|
|
||||||
drop(current); // Drop borrow before send
|
|
||||||
let _ = tx.send(MprisState {
|
|
||||||
is_playing,
|
|
||||||
is_paused,
|
|
||||||
is_stopped,
|
|
||||||
artist,
|
|
||||||
title,
|
|
||||||
album,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} else {
|
fn send_stopped_if_changed(tx: &watch::Sender<MprisState>) {
|
||||||
let current = tx.borrow();
|
let current = tx.borrow();
|
||||||
if !current.is_stopped || !current.title.is_empty() {
|
if !current.is_stopped || !current.title.is_empty() {
|
||||||
drop(current);
|
drop(current);
|
||||||
@@ -296,8 +339,3 @@ impl MprisDaemon {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,12 +1,22 @@
|
|||||||
|
//! JSON payload returned to Waybar custom modules.
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// A Waybar custom module return value.
|
||||||
|
///
|
||||||
|
/// Serialises to the schema Waybar's `return-type: json` expects — the
|
||||||
|
/// optional fields are omitted from the output when unset.
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
|
||||||
pub struct WaybarOutput {
|
pub struct WaybarOutput {
|
||||||
|
/// Primary text shown in the bar.
|
||||||
pub text: String,
|
pub text: String,
|
||||||
|
/// Tooltip text shown on hover.
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub tooltip: Option<String>,
|
pub tooltip: Option<String>,
|
||||||
|
/// CSS class applied to the module (for styling).
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub class: Option<String>,
|
pub class: Option<String>,
|
||||||
|
/// Optional 0-100 value usable by bar progress indicators.
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub percentage: Option<u8>,
|
pub percentage: Option<u8>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,11 @@
|
|||||||
|
//! Central module dispatch: name → [`WaybarModule::run`] lookup.
|
||||||
|
//!
|
||||||
|
//! The `dispatch` function is called by the IPC request handler with a module
|
||||||
|
//! name (e.g. `"cpu"`, `"vol"`) and returns the rendered [`WaybarOutput`]. All
|
||||||
|
//! per-module match arms are generated by [`for_each_watched_module!`];
|
||||||
|
//! dispatch-only modules without a watch channel (power/game/btrfs) are
|
||||||
|
//! listed manually.
|
||||||
|
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::error::{FluxoError, Result as FluxoResult};
|
use crate::error::{FluxoError, Result as FluxoResult};
|
||||||
use crate::output::WaybarOutput;
|
use crate::output::WaybarOutput;
|
||||||
@@ -6,8 +14,14 @@ use crate::state::AppReceivers;
|
|||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
use crate::modules::WaybarModule;
|
use crate::modules::WaybarModule;
|
||||||
|
|
||||||
|
/// Expands the module registry into a single [`dispatch`] match and a
|
||||||
|
/// [`signaler_default_args`] lookup.
|
||||||
macro_rules! gen_dispatch {
|
macro_rules! gen_dispatch {
|
||||||
($( { $feature:literal, $field:ident, $state:ty, [$($name:literal),+], [$($sig_name:literal),+], $module:path, $signal:ident, [$($default_arg:literal),*], $config:ident } )*) => {
|
($( { $feature:literal, $field:ident, $state:ty, [$($name:literal),+], [$($sig_name:literal),+], $module:path, $signal:ident, [$($default_arg:literal),*], $config:ident } )*) => {
|
||||||
|
/// Look up a module by name and render its [`WaybarOutput`].
|
||||||
|
///
|
||||||
|
/// Returns [`FluxoError::Disabled`] when the module is disabled in
|
||||||
|
/// config, and [`FluxoError::Ipc`] when the name is unknown.
|
||||||
pub async fn dispatch(
|
pub async fn dispatch(
|
||||||
module_name: &str,
|
module_name: &str,
|
||||||
#[allow(unused)] config: &Config,
|
#[allow(unused)] config: &Config,
|
||||||
|
|||||||
+24
-1
@@ -1,3 +1,11 @@
|
|||||||
|
//! Waybar signalling: watch state channels, send `SIGRTMIN+N` on changes.
|
||||||
|
//!
|
||||||
|
//! Waybar's custom modules use `signal = N` to rerun their command when they
|
||||||
|
//! receive `SIGRTMIN+N`. This task subscribes to every watched module's
|
||||||
|
//! `watch::Receiver`, evaluates the module when its channel fires, and only
|
||||||
|
//! signals Waybar when the rendered output actually changed. A 50 ms per-signal
|
||||||
|
//! debounce prevents storms during rapid state churn.
|
||||||
|
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
use crate::state::AppReceivers;
|
use crate::state::AppReceivers;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -7,6 +15,10 @@ use tokio::sync::RwLock;
|
|||||||
use tokio::time::{Duration, Instant, sleep};
|
use tokio::time::{Duration, Instant, sleep};
|
||||||
use tracing::{debug, warn};
|
use tracing::{debug, warn};
|
||||||
|
|
||||||
|
/// Sends real-time signals to the Waybar process.
|
||||||
|
///
|
||||||
|
/// Resolves Waybar's PID lazily and caches it — the PID is invalidated on
|
||||||
|
/// signal failure (e.g. Waybar was restarted) and rediscovered via `sysinfo`.
|
||||||
pub struct WaybarSignaler {
|
pub struct WaybarSignaler {
|
||||||
cached_pid: Option<i32>,
|
cached_pid: Option<i32>,
|
||||||
sys: System,
|
sys: System,
|
||||||
@@ -14,6 +26,7 @@ pub struct WaybarSignaler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl WaybarSignaler {
|
impl WaybarSignaler {
|
||||||
|
/// Create a new signaler with no cached PID.
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
cached_pid: None,
|
cached_pid: None,
|
||||||
@@ -65,9 +78,19 @@ impl WaybarSignaler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Generates [`WaybarSignaler::run`] from the central module registry.
|
||||||
|
///
|
||||||
|
/// For each watched module we emit:
|
||||||
|
/// * a cfg-gated `watch::Receiver::changed()` future (or `pending::<()>` when
|
||||||
|
/// the feature is disabled, so the `tokio::select!` arm compiles uniformly),
|
||||||
|
/// * a `select!` arm that re-evaluates the module and signals Waybar once per
|
||||||
|
/// changed output.
|
||||||
macro_rules! gen_signaler_run {
|
macro_rules! gen_signaler_run {
|
||||||
($( { $feature:literal, $field:ident, $state:ty, [$($name:literal),+], [$($sig_name:literal),+], $module:path, $signal:ident, [$($default_arg:literal),*], $config:ident } )*) => {
|
($( { $feature:literal, $field:ident, $state:ty, [$($name:literal),+], [$($sig_name:literal),+], $module:path, $signal:ident, [$($default_arg:literal),*], $config:ident } )*) => {
|
||||||
impl WaybarSignaler {
|
impl WaybarSignaler {
|
||||||
|
/// Run the signaler event loop forever.
|
||||||
|
///
|
||||||
|
/// Consumes `self`; intended to be spawned as a long-lived task.
|
||||||
pub async fn run(mut self, config_lock: Arc<RwLock<Config>>, mut receivers: AppReceivers) {
|
pub async fn run(mut self, config_lock: Arc<RwLock<Config>>, mut receivers: AppReceivers) {
|
||||||
let mut last_outputs: HashMap<&'static str, String> = HashMap::new();
|
let mut last_outputs: HashMap<&'static str, String> = HashMap::new();
|
||||||
|
|
||||||
@@ -128,7 +151,7 @@ macro_rules! gen_signaler_run {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_ = sleep(Duration::from_secs(5)) => {
|
_ = sleep(Duration::from_secs(5)) => {
|
||||||
// loop and refresh config
|
// heartbeat: re-read signals config on each iteration
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,27 @@
|
|||||||
|
//! Shared state types exchanged between daemon tasks and modules.
|
||||||
|
//!
|
||||||
|
//! Every "watched" module has a `watch::Receiver<StateType>` held by
|
||||||
|
//! [`AppReceivers`]; background tasks write into the paired sender. Readers
|
||||||
|
//! (the request handler, the signaler) take a cheap snapshot via
|
||||||
|
//! `Receiver::borrow()` and render their output from it.
|
||||||
|
|
||||||
use crate::output::WaybarOutput;
|
use crate::output::WaybarOutput;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::{RwLock, mpsc, watch};
|
use tokio::sync::{RwLock, mpsc, watch};
|
||||||
use tokio::time::Instant;
|
use tokio::time::Instant;
|
||||||
|
|
||||||
|
/// Generates the [`AppReceivers`] struct, with one `watch::Receiver` field
|
||||||
|
/// per watched module (cfg-gated by feature flag).
|
||||||
macro_rules! gen_app_receivers {
|
macro_rules! gen_app_receivers {
|
||||||
($( { $feature:literal, $field:ident, $state:ty, [$($name:literal),+], [$($sig_name:literal),+], $module:path, $signal:ident, [$($default_arg:literal),*], $config:ident } )*) => {
|
($( { $feature:literal, $field:ident, $state:ty, [$($name:literal),+], [$($sig_name:literal),+], $module:path, $signal:ident, [$($default_arg:literal),*], $config:ident } )*) => {
|
||||||
|
/// Bundle of every watch-channel receiver and control-channel handle.
|
||||||
|
///
|
||||||
|
/// Cloned into each IPC request handler and each module daemon so that
|
||||||
|
/// they can snapshot state without locking. Per-module receivers are
|
||||||
|
/// generated from [`for_each_watched_module!`]; the remaining fields
|
||||||
|
/// (`health`, `bt_cycle`, `audio_cmd_tx`, `mpris_scroll_*`) are shared
|
||||||
|
/// control state.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AppReceivers {
|
pub struct AppReceivers {
|
||||||
$(
|
$(
|
||||||
@@ -28,6 +44,7 @@ macro_rules! gen_app_receivers {
|
|||||||
}
|
}
|
||||||
for_each_watched_module!(gen_app_receivers);
|
for_each_watched_module!(gen_app_receivers);
|
||||||
|
|
||||||
|
/// Runtime health statistics used for backoff decisions.
|
||||||
#[derive(Clone, Default)]
|
#[derive(Clone, Default)]
|
||||||
pub struct ModuleHealth {
|
pub struct ModuleHealth {
|
||||||
pub consecutive_failures: u32,
|
pub consecutive_failures: u32,
|
||||||
@@ -36,6 +53,7 @@ pub struct ModuleHealth {
|
|||||||
pub last_successful_output: Option<WaybarOutput>,
|
pub last_successful_output: Option<WaybarOutput>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Current default audio sink + source plus all available devices.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct AudioState {
|
pub struct AudioState {
|
||||||
pub sink: AudioDeviceInfo,
|
pub sink: AudioDeviceInfo,
|
||||||
@@ -44,6 +62,7 @@ pub struct AudioState {
|
|||||||
pub available_sources: Vec<String>,
|
pub available_sources: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Metadata for one PulseAudio sink or source.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct AudioDeviceInfo {
|
pub struct AudioDeviceInfo {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
@@ -53,6 +72,7 @@ pub struct AudioDeviceInfo {
|
|||||||
pub channels: u8,
|
pub channels: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A single BlueZ device, optionally annotated by a plugin (buds, maestro…).
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct BtDeviceInfo {
|
pub struct BtDeviceInfo {
|
||||||
pub device_alias: String,
|
pub device_alias: String,
|
||||||
@@ -61,6 +81,7 @@ pub struct BtDeviceInfo {
|
|||||||
pub plugin_data: Vec<(String, String)>,
|
pub plugin_data: Vec<(String, String)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Snapshot of the Bluetooth adapter plus every tracked device.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct BtState {
|
pub struct BtState {
|
||||||
pub adapter_powered: bool,
|
pub adapter_powered: bool,
|
||||||
@@ -68,6 +89,10 @@ pub struct BtState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl BtState {
|
impl BtState {
|
||||||
|
/// Return the device the client is currently cycled to, if any.
|
||||||
|
///
|
||||||
|
/// The `index` is taken modulo `devices.len()` so cycling past the end
|
||||||
|
/// wraps around naturally.
|
||||||
pub fn active_device(&self, index: usize) -> Option<&BtDeviceInfo> {
|
pub fn active_device(&self, index: usize) -> Option<&BtDeviceInfo> {
|
||||||
if self.devices.is_empty() {
|
if self.devices.is_empty() {
|
||||||
None
|
None
|
||||||
@@ -77,6 +102,7 @@ impl BtState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Per-mountpoint disk usage.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct DiskInfo {
|
pub struct DiskInfo {
|
||||||
pub mount_point: String,
|
pub mount_point: String,
|
||||||
@@ -85,6 +111,7 @@ pub struct DiskInfo {
|
|||||||
pub available_bytes: u64,
|
pub available_bytes: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Throughput and identity of the active network interface.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct NetworkState {
|
pub struct NetworkState {
|
||||||
pub rx_mbps: f64,
|
pub rx_mbps: f64,
|
||||||
@@ -93,6 +120,7 @@ pub struct NetworkState {
|
|||||||
pub ip: String,
|
pub ip: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// CPU utilisation and temperature.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct CpuState {
|
pub struct CpuState {
|
||||||
pub usage: f64,
|
pub usage: f64,
|
||||||
@@ -110,12 +138,14 @@ impl Default for CpuState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// RAM usage in gigabytes.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct MemoryState {
|
pub struct MemoryState {
|
||||||
pub used_gb: f64,
|
pub used_gb: f64,
|
||||||
pub total_gb: f64,
|
pub total_gb: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Load averages, uptime, and process count.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct SysState {
|
pub struct SysState {
|
||||||
pub load_1: f64,
|
pub load_1: f64,
|
||||||
@@ -125,6 +155,9 @@ pub struct SysState {
|
|||||||
pub process_count: usize,
|
pub process_count: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// GPU snapshot (vendor-agnostic).
|
||||||
|
///
|
||||||
|
/// `active` is `false` until detection finds a supported GPU.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct GpuState {
|
pub struct GpuState {
|
||||||
pub active: bool,
|
pub active: bool,
|
||||||
@@ -150,27 +183,32 @@ impl Default for GpuState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Do-Not-Disturb toggle state.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct DndState {
|
pub struct DndState {
|
||||||
pub is_dnd: bool,
|
pub is_dnd: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Currently active keyboard layout.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct KeyboardState {
|
pub struct KeyboardState {
|
||||||
pub layout: String,
|
pub layout: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Display backlight brightness as a 0-100 percentage.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct BacklightState {
|
pub struct BacklightState {
|
||||||
pub percentage: u8,
|
pub percentage: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Marquee scroll position for the MPRIS module.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct MprisScrollState {
|
pub struct MprisScrollState {
|
||||||
pub offset: usize,
|
pub offset: usize,
|
||||||
pub full_text: String,
|
pub full_text: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Currently playing media metadata from an MPRIS player.
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct MprisState {
|
pub struct MprisState {
|
||||||
pub is_playing: bool,
|
pub is_playing: bool,
|
||||||
@@ -181,6 +219,10 @@ pub struct MprisState {
|
|||||||
pub album: String,
|
pub album: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Test harness holding a synthetic [`AppReceivers`] plus its senders.
|
||||||
|
///
|
||||||
|
/// The senders are kept alive via `_*_tx` fields so test code can drive the
|
||||||
|
/// watch channels without them being dropped.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub struct MockState {
|
pub struct MockState {
|
||||||
pub receivers: AppReceivers,
|
pub receivers: AppReceivers,
|
||||||
@@ -210,6 +252,7 @@ pub struct MockState {
|
|||||||
_dnd_tx: watch::Sender<DndState>,
|
_dnd_tx: watch::Sender<DndState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Plain-data counterpart of [`AppReceivers`] used to seed a [`MockState`].
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
@@ -240,6 +283,7 @@ pub struct AppState {
|
|||||||
pub health: HashMap<String, ModuleHealth>,
|
pub health: HashMap<String, ModuleHealth>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Build a [`MockState`] from a plain [`AppState`] snapshot for unit tests.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub fn mock_state(state: AppState) -> MockState {
|
pub fn mock_state(state: AppState) -> MockState {
|
||||||
#[cfg(feature = "mod-network")]
|
#[cfg(feature = "mod-network")]
|
||||||
|
|||||||
+24
-6
@@ -1,23 +1,31 @@
|
|||||||
|
//! Shared helpers: menu spawning, Hyprland socket lookup, and template formatting.
|
||||||
|
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::process::{Command, Stdio};
|
use std::process::{Command, Stdio};
|
||||||
|
|
||||||
|
/// Pipe `items` into an external menu program (rofi/dmenu/wofi) and return
|
||||||
|
/// the user's selection.
|
||||||
|
///
|
||||||
|
/// The prompt is exposed to the command as `$FLUXO_PROMPT` (preferred) and
|
||||||
|
/// as a legacy `{prompt}` placeholder that is substituted in the shell string.
|
||||||
pub fn show_menu(prompt: &str, items: &[String], menu_cmd: &str) -> Result<String> {
|
pub fn show_menu(prompt: &str, items: &[String], menu_cmd: &str) -> Result<String> {
|
||||||
// Backward compatibility for {prompt}, but environment variable is safer
|
|
||||||
let cmd_str = menu_cmd.replace("{prompt}", prompt);
|
let cmd_str = menu_cmd.replace("{prompt}", prompt);
|
||||||
let mut child = Command::new("sh")
|
let mut child = Command::new("sh")
|
||||||
.arg("-c")
|
.arg("-c")
|
||||||
.arg(&cmd_str)
|
.arg(&cmd_str)
|
||||||
.env("FLUXO_PROMPT", prompt) // Safer shell injection
|
.env("FLUXO_PROMPT", prompt)
|
||||||
.stdin(Stdio::piped())
|
.stdin(Stdio::piped())
|
||||||
.stdout(Stdio::piped())
|
.stdout(Stdio::piped())
|
||||||
.stderr(Stdio::null()) // Suppress GTK/Wayland warnings from tools like wofi
|
// Suppress GTK/Wayland noise from tools like wofi.
|
||||||
|
.stderr(Stdio::null())
|
||||||
.spawn()
|
.spawn()
|
||||||
.context("Failed to spawn menu command")?;
|
.context("Failed to spawn menu command")?;
|
||||||
|
|
||||||
if let Some(mut stdin) = child.stdin.take() {
|
if let Some(mut stdin) = child.stdin.take() {
|
||||||
let mut input = items.join("\n");
|
let mut input = items.join("\n");
|
||||||
input.push('\n'); // Ensure trailing newline for wofi/rofi
|
// Trailing newline is required by wofi/rofi.
|
||||||
|
input.push('\n');
|
||||||
stdin
|
stdin
|
||||||
.write_all(input.as_bytes())
|
.write_all(input.as_bytes())
|
||||||
.context("Failed to write to menu stdin")?;
|
.context("Failed to write to menu stdin")?;
|
||||||
@@ -37,11 +45,14 @@ pub fn show_menu(prompt: &str, items: &[String], menu_cmd: &str) -> Result<Strin
|
|||||||
Ok(selected)
|
Ok(selected)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resolve the path to a Hyprland IPC socket for the current session.
|
||||||
|
///
|
||||||
|
/// Looks under `$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/` first,
|
||||||
|
/// then falls back to `/tmp/hypr/...` for older Hyprland builds.
|
||||||
pub fn get_hyprland_socket(socket_name: &str) -> Result<std::path::PathBuf> {
|
pub fn get_hyprland_socket(socket_name: &str) -> Result<std::path::PathBuf> {
|
||||||
let signature = std::env::var("HYPRLAND_INSTANCE_SIGNATURE")
|
let signature = std::env::var("HYPRLAND_INSTANCE_SIGNATURE")
|
||||||
.context("HYPRLAND_INSTANCE_SIGNATURE not set")?;
|
.context("HYPRLAND_INSTANCE_SIGNATURE not set")?;
|
||||||
|
|
||||||
// Try XDG_RUNTIME_DIR first (usually /run/user/1000)
|
|
||||||
if let Ok(runtime_dir) = std::env::var("XDG_RUNTIME_DIR") {
|
if let Ok(runtime_dir) = std::env::var("XDG_RUNTIME_DIR") {
|
||||||
let path = std::path::PathBuf::from(runtime_dir)
|
let path = std::path::PathBuf::from(runtime_dir)
|
||||||
.join("hypr")
|
.join("hypr")
|
||||||
@@ -52,7 +63,6 @@ pub fn get_hyprland_socket(socket_name: &str) -> Result<std::path::PathBuf> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback to /tmp
|
|
||||||
let path = std::path::PathBuf::from("/tmp/hypr")
|
let path = std::path::PathBuf::from("/tmp/hypr")
|
||||||
.join(&signature)
|
.join(&signature)
|
||||||
.join(socket_name);
|
.join(socket_name);
|
||||||
@@ -70,6 +80,7 @@ pub fn get_hyprland_socket(socket_name: &str) -> Result<std::path::PathBuf> {
|
|||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use std::sync::LazyLock;
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
|
/// Bucket `value` into `"normal"`, `"high"`, or `"max"` for CSS class output.
|
||||||
pub fn classify_usage(value: f64, high: f64, max: f64) -> &'static str {
|
pub fn classify_usage(value: f64, high: f64, max: f64) -> &'static str {
|
||||||
if value > max {
|
if value > max {
|
||||||
"max"
|
"max"
|
||||||
@@ -80,15 +91,22 @@ pub fn classify_usage(value: f64, high: f64, max: f64) -> &'static str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A typed value supplied to [`format_template`] — chosen at call site so
|
||||||
|
/// formatting handles precision and alignment correctly per type.
|
||||||
pub enum TokenValue {
|
pub enum TokenValue {
|
||||||
Float(f64),
|
Float(f64),
|
||||||
Int(i64),
|
Int(i64),
|
||||||
String(String),
|
String(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Token grammar: `{name}`, `{name:>5}`, `{name:<8.2}`, `{name:^6}`, etc.
|
||||||
pub static TOKEN_RE: LazyLock<Regex> =
|
pub static TOKEN_RE: LazyLock<Regex> =
|
||||||
LazyLock::new(|| Regex::new(r"\{([a-zA-Z0-9_]+)(?::([<>\^])?(\d+)?(?:\.(\d+))?)?\}").unwrap());
|
LazyLock::new(|| Regex::new(r"\{([a-zA-Z0-9_]+)(?::([<>\^])?(\d+)?(?:\.(\d+))?)?\}").unwrap());
|
||||||
|
|
||||||
|
/// Substitute `{name[:align[width[.precision]]]}` tokens in a template string.
|
||||||
|
///
|
||||||
|
/// Unknown tokens are left verbatim. Width/alignment/precision follow Rust's
|
||||||
|
/// `std::fmt` semantics (`<` left, `^` center, `>` right).
|
||||||
pub fn format_template<K>(template: &str, values: &[(K, TokenValue)]) -> String
|
pub fn format_template<K>(template: &str, values: &[(K, TokenValue)]) -> String
|
||||||
where
|
where
|
||||||
K: AsRef<str>,
|
K: AsRef<str>,
|
||||||
|
|||||||
Reference in New Issue
Block a user