diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 527c51e..1b78ab5 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -47,6 +47,7 @@ ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "sc [target.'cfg(target_os = "windows")'.dependencies] wasapi = "0.27.0" windows-capture = "2.0.1" +tray-icon = { version = "0.27.0", default-features = false } [target.'cfg(target_os = "macos")'.dependencies] coreaudio-rs = "0.14.2" diff --git a/crates/client/src/gui.rs b/crates/client/src/gui.rs index 75d1718..079c311 100644 --- a/crates/client/src/gui.rs +++ b/crates/client/src/gui.rs @@ -1279,6 +1279,7 @@ pub(super) fn new_input( impl Render for Yumush { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + crate::usage::tick(crate::usage::Group::Gui); let fullscreen = self .chat .viewer diff --git a/crates/client/src/gui/chat.rs b/crates/client/src/gui/chat.rs index f34310c..0cf4492 100644 --- a/crates/client/src/gui/chat.rs +++ b/crates/client/src/gui/chat.rs @@ -536,7 +536,13 @@ impl Chat { followed: None, share_loss: HashMap::new(), stats_at: None, - usage_monitor: crate::usage::Monitor::default(), + usage_monitor: { + let monitor = crate::usage::Monitor::default(); + if let Some(dir) = crate::config_dir() { + monitor.watch_disk(dir); + } + monitor + }, ringing: HashSet::new(), ring_task: None, typing: HashMap::new(), diff --git a/crates/client/src/gui/voice_stats.rs b/crates/client/src/gui/voice_stats.rs index 0bbb99a..cb858e6 100644 --- a/crates/client/src/gui/voice_stats.rs +++ b/crates/client/src/gui/voice_stats.rs @@ -277,6 +277,20 @@ fn machine(usage: &Usage, t: Tokens) -> Div { false, t, )) + .children(usage.storage.map(|storage| { + line_row( + label("storage", t), + track( + Fill::Part(storage.used_mb as f32 / storage.total_mb.max(1) as f32), + false, + t, + ) + .into_any_element(), + format!("{} / {}", gb(storage.used_mb), gb(storage.total_mb)), + false, + t, + ) + })) .children(usage.gpu.as_ref().map(|gpu| { let machine = gpu.machine; let vram_total = machine.vram_total_mb.max(machine.vram_used_mb).max(1) as f32; @@ -462,7 +476,8 @@ pub(super) fn kind_word(kind: Kind) -> &'static str { fn gb(mb: u32) -> String { match mb { 0..1000 => format!("{mb} MB"), - _ => format!("{:.1} GB", mb as f32 / 1024.), + 1000..1_000_000 => format!("{:.1} GB", mb as f32 / 1024.), + _ => format!("{:.1} TB", mb as f32 / (1024. * 1024.)), } } diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 9a7de53..0fc1f41 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -18,11 +18,14 @@ pub mod voice; pub const NAME: &str = "Yumush"; -fn config_file(name: &str) -> Option { +pub fn config_dir() -> Option { std::env::var_os("YUMUSH_CONFIG_DIR") .map(PathBuf::from) .or_else(|| dirs::config_dir().map(|dir| dir.join("yumush"))) - .map(|dir| dir.join(name)) +} + +fn config_file(name: &str) -> Option { + config_dir().map(|dir| dir.join(name)) } pub fn read_config(name: &str) -> Option { diff --git a/crates/client/src/main.rs b/crates/client/src/main.rs index 1532deb..33a98b6 100644 --- a/crates/client/src/main.rs +++ b/crates/client/src/main.rs @@ -42,7 +42,6 @@ fn main() { let settings = settings::load(); let (network_handle, network_event_receiver) = net::start(ClientConfig::default()); - let (mut tray_receiver, tray_handle) = tray::start(); application() .with_assets(AllAssets) @@ -61,6 +60,7 @@ fn main() { return; }; + let (mut tray_receiver, tray_handle) = tray::start(); let mut tray_state = TrayState::default(); cx.observe(&view, move |view, cx| { let state = view.read(cx).tray_state(); diff --git a/crates/client/src/media/decode.rs b/crates/client/src/media/decode.rs index 584336b..5fe41fb 100644 --- a/crates/client/src/media/decode.rs +++ b/crates/client/src/media/decode.rs @@ -217,6 +217,7 @@ impl VideoDecoder { } pub fn decode(&mut self, data: &[u8], timestamp_ms: u32) -> Vec { + crate::usage::tick(crate::usage::Group::Decode); let mut packet = Packet::new(0, TimeBase::MILLIS, data); packet.pts = Some(i64::from(timestamp_ms)); self.send(&packet) @@ -646,6 +647,7 @@ impl Worker { } fn decode_backlog(&mut self) -> bool { + crate::usage::tick(crate::usage::Group::Decode); let Some((_, video)) = self.video.as_mut() else { return false; }; diff --git a/crates/client/src/net/link.rs b/crates/client/src/net/link.rs index a7eee8d..a42d497 100644 --- a/crates/client/src/net/link.rs +++ b/crates/client/src/net/link.rs @@ -252,9 +252,11 @@ pub(super) async fn call( connection: &quinn::Connection, call: C, ) -> Result { - Ok(exchange(connection, &Open::Call(call.into_request())) - .await? - .0) + Ok( + exchange(connection, &Open::Call(Box::new(call.into_request()))) + .await? + .0, + ) } async fn hello(connection: &quinn::Connection, token: Option) -> Result { diff --git a/crates/client/src/share/camera.rs b/crates/client/src/share/camera.rs index a6e8135..4a1c734 100644 --- a/crates/client/src/share/camera.rs +++ b/crates/client/src/share/camera.rs @@ -227,6 +227,7 @@ fn run( let mut failures = 0; let mut due = 0u32; while !stop.load(Ordering::Relaxed) { + crate::usage::tick(crate::usage::Group::Camera); let buffer = match camera.frame() { Ok(buffer) => buffer, Err(error) => { diff --git a/crates/client/src/share/capture.rs b/crates/client/src/share/capture.rs index 69e1c9a..80ced68 100644 --- a/crates/client/src/share/capture.rs +++ b/crates/client/src/share/capture.rs @@ -484,6 +484,7 @@ fn on_param(stream: &pw::stream::Stream, state: &mut State, id: u32, param: Opti } fn on_process(stream: &pw::stream::Stream, state: &mut State) { + crate::usage::tick(crate::usage::Group::Camera); let (width, height) = state.size; if width == 0 || height == 0 { return; diff --git a/crates/client/src/share/capture_windows.rs b/crates/client/src/share/capture_windows.rs index 688c150..cf1a7fc 100644 --- a/crates/client/src/share/capture_windows.rs +++ b/crates/client/src/share/capture_windows.rs @@ -107,6 +107,7 @@ impl GraphicsCaptureApiHandler for Handler { frame: &mut CaptureFrame, _: InternalCaptureControl, ) -> Result<(), Self::Error> { + crate::usage::tick(crate::usage::Group::Camera); let (width, height) = (frame.width(), frame.height()); let mut buffer = frame.buffer().map_err(text)?; let pitch = buffer.row_pitch() as usize; diff --git a/crates/client/src/share/encode.rs b/crates/client/src/share/encode.rs index cada943..73df80b 100644 --- a/crates/client/src/share/encode.rs +++ b/crates/client/src/share/encode.rs @@ -377,6 +377,7 @@ fn run( let interval = 1000 / settings.fps; let mut due = 0u32; for frame in input { + crate::usage::tick(crate::usage::Group::Encode); if frame.timestamp_ms + SLACK_MS < due { continue; } diff --git a/crates/client/src/share/fake.rs b/crates/client/src/share/fake.rs index 280e3d1..9a6a703 100644 --- a/crates/client/src/share/fake.rs +++ b/crates/client/src/share/fake.rs @@ -45,6 +45,7 @@ pub fn start(spec: &str) -> (u32, u32, u32, Receiver, Generator) { let noisy = std::env::var_os("YUMUSH_TEST_NOISE").is_some(); let mut seed: u64 = 0x9e37_79b9_7f4a_7c15; while !stop.load(Ordering::Relaxed) { + crate::usage::tick(crate::usage::Group::Camera); let bar = (number as usize * 8) % width as usize; let mut bgra = vec![40u8; (width * height) as usize * BYTES_PER_PIXEL]; if noisy { diff --git a/crates/client/src/tray.rs b/crates/client/src/tray.rs index 9d88580..f070e0e 100644 --- a/crates/client/src/tray.rs +++ b/crates/client/src/tray.rs @@ -1,6 +1,4 @@ -use tokio::sync::mpsc; - -pub const AVAILABLE: bool = cfg!(target_os = "linux"); +pub const AVAILABLE: bool = cfg!(any(target_os = "linux", target_os = "windows")); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TrayAction { @@ -14,50 +12,107 @@ pub struct TrayState { pub mentions: u32, } -#[derive(Clone)] -pub struct TrayHandle(mpsc::UnboundedSender); +pub struct TrayHandle(Box); impl TrayHandle { pub fn set(&self, state: TrayState) { - let _ = self.0.send(state); + (self.0)(state); } } #[cfg(target_os = "linux")] pub use linux::start; +#[cfg(target_os = "windows")] +pub use windows::start; -#[cfg(not(target_os = "linux"))] -pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { +#[cfg(not(any(target_os = "linux", target_os = "windows")))] +pub fn start() -> (tokio::sync::mpsc::UnboundedReceiver, TrayHandle) { ( - mpsc::unbounded_channel().1, - TrayHandle(mpsc::unbounded_channel().0), + tokio::sync::mpsc::unbounded_channel().1, + TrayHandle(Box::new(|_| {})), ) } +#[cfg(any(target_os = "linux", target_os = "windows"))] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Badge { + None, + Unread, + Mention, +} + +#[cfg(any(target_os = "linux", target_os = "windows"))] +impl TrayState { + fn badge(self) -> Badge { + match (self.messages, self.mentions) { + (_, 1..) => Badge::Mention, + (1.., _) => Badge::Unread, + _ => Badge::None, + } + } + + fn tip(self) -> String { + match self.badge() { + Badge::None => crate::NAME.to_string(), + _ => format!( + "{} · {} unread · {} mentions", + crate::NAME, + self.messages, + self.mentions + ), + } + } +} + +#[cfg(any(target_os = "linux", target_os = "windows"))] +const ICON_SIZE: i32 = 32; +#[cfg(any(target_os = "linux", target_os = "windows"))] +const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2]; +#[cfg(any(target_os = "linux", target_os = "windows"))] +const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)]; +#[cfg(any(target_os = "linux", target_os = "windows"))] +const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); +#[cfg(any(target_os = "linux", target_os = "windows"))] +const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; +#[cfg(any(target_os = "linux", target_os = "windows"))] +const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; + +#[cfg(any(target_os = "linux", target_os = "windows"))] +fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { + let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); + (radius - distance + 0.5).clamp(0.0, 1.0) +} + +#[cfg(any(target_os = "linux", target_os = "windows"))] +fn pixels(badge: Badge) -> impl Iterator { + let dot = match badge { + Badge::None => None, + Badge::Unread => Some(UNREAD_COLOR), + Badge::Mention => Some(MENTION_COLOR), + }; + (0..ICON_SIZE * ICON_SIZE).map(move |index| { + let x = (index % ICON_SIZE) as f32 + 0.5; + let y = (index / ICON_SIZE) as f32 + 0.5; + let base = ICON_DROPS + .iter() + .map(|drop| coverage(x, y, *drop)) + .fold(0.0, f32::max); + let (color, alpha) = match dot { + Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)), + Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => (ICON_COLOR, 0.0), + _ => (ICON_COLOR, base), + }; + (color, (alpha * 255.0) as u8) + }) +} + #[cfg(target_os = "linux")] mod linux { use ksni::TrayMethods; use tokio::sync::mpsc; use tracing::warn; - use super::{TrayAction, TrayHandle, TrayState}; - - #[derive(Debug, Clone, Copy, PartialEq, Eq)] - enum Badge { - None, - Unread, - Mention, - } - - impl TrayState { - fn badge(self) -> Badge { - match (self.messages, self.mentions) { - (_, 1..) => Badge::Mention, - (1.., _) => Badge::Unread, - _ => Badge::None, - } - } - } + use super::{Badge, ICON_SIZE, TrayAction, TrayHandle, TrayState, pixels}; pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { let (sender, receiver) = mpsc::unbounded_channel(); @@ -93,7 +148,12 @@ mod linux { }); }); - (receiver, TrayHandle(state_sender)) + ( + receiver, + TrayHandle(Box::new(move |state| { + let _ = state_sender.send(state); + })), + ) } struct Tray { @@ -122,16 +182,8 @@ mod linux { } fn tool_tip(&self) -> ksni::ToolTip { - let description = match self.state.badge() { - Badge::None => String::new(), - _ => format!( - "{} unread · {} mentions", - self.state.messages, self.state.mentions - ), - }; ksni::ToolTip { - title: crate::NAME.to_string(), - description, + title: self.state.tip(), ..Default::default() } } @@ -164,47 +216,81 @@ mod linux { } } - const ICON_SIZE: i32 = 32; - const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2]; - const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)]; - const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); - const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; - const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; - - fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { - let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); - (radius - distance + 0.5).clamp(0.0, 1.0) - } - fn icon(badge: Badge) -> ksni::Icon { - let dot = match badge { - Badge::None => None, - Badge::Unread => Some(UNREAD_COLOR), - Badge::Mention => Some(MENTION_COLOR), - }; - let data = (0..ICON_SIZE * ICON_SIZE) - .flat_map(|index| { - let x = (index % ICON_SIZE) as f32 + 0.5; - let y = (index / ICON_SIZE) as f32 + 0.5; - let base = ICON_DROPS - .iter() - .map(|drop| coverage(x, y, *drop)) - .fold(0.0, f32::max); - let ([red, green, blue], alpha) = match dot { - Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)), - Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => { - (ICON_COLOR, 0.0) - } - _ => (ICON_COLOR, base), - }; - [(alpha * 255.0) as u8, red, green, blue] - }) - .collect(); - ksni::Icon { width: ICON_SIZE, height: ICON_SIZE, - data, + data: pixels(badge) + .flat_map(|([red, green, blue], alpha)| [alpha, red, green, blue]) + .collect(), } } } + +#[cfg(target_os = "windows")] +mod windows { + use tokio::sync::mpsc; + use tracing::warn; + use tray_icon::{ + Icon, MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent, + menu::{Menu, MenuEvent, MenuItem}, + }; + + use super::{Badge, ICON_SIZE, TrayAction, TrayHandle, TrayState, pixels}; + + fn icon(badge: Badge) -> Option { + let rgba = pixels(badge) + .flat_map(|([red, green, blue], alpha)| [red, green, blue, alpha]) + .collect(); + Icon::from_rgba(rgba, ICON_SIZE as u32, ICON_SIZE as u32).ok() + } + + pub fn start() -> (mpsc::UnboundedReceiver, TrayHandle) { + let (sender, receiver) = mpsc::unbounded_channel(); + let show = MenuItem::new("Show", true, None); + let quit = MenuItem::new("Quit", true, None); + let menu = Menu::new(); + if let Err(error) = menu.append_items(&[&show, &quit]) { + warn!("tray menu: {error}"); + } + let (show_id, quit_id) = (show.id().clone(), quit.id().clone()); + let menu_sender = sender.clone(); + MenuEvent::set_event_handler(Some(std::sync::Arc::new(move |event: MenuEvent| { + let action = if event.id == show_id { + TrayAction::Show + } else if event.id == quit_id { + TrayAction::Quit + } else { + return; + }; + let _ = menu_sender.send(action); + }))); + TrayIconEvent::set_event_handler(Some(move |event: TrayIconEvent| { + if let TrayIconEvent::Click { + button: MouseButton::Left, + button_state: MouseButtonState::Up, + .. + } = event + { + let _ = sender.send(TrayAction::Show); + } + })); + let mut builder = TrayIconBuilder::new() + .with_menu(Box::new(menu)) + .with_tooltip(crate::NAME); + if let Some(icon) = icon(Badge::None) { + builder = builder.with_icon(icon); + } + let handle = match builder.build() { + Ok(tray) => TrayHandle(Box::new(move |state: TrayState| { + let _ = tray.set_icon(icon(state.badge())); + let _ = tray.set_tooltip(Some(state.tip())); + })), + Err(error) => { + warn!("tray: {error}"); + TrayHandle(Box::new(|_| {})) + } + }; + (receiver, handle) + } +} diff --git a/crates/common/src/open.rs b/crates/common/src/open.rs index bb8a22e..0ae9957 100644 --- a/crates/common/src/open.rs +++ b/crates/common/src/open.rs @@ -4,7 +4,7 @@ use crate::{call::Request, model::Id}; #[derive(Debug, Clone, Encode, Decode)] pub enum Open { - Call(Request), + Call(Box), Upload(Upload), Fetch(Blob), } diff --git a/crates/common/src/stats.rs b/crates/common/src/stats.rs index 7437f20..8f76fa1 100644 --- a/crates/common/src/stats.rs +++ b/crates/common/src/stats.rs @@ -38,9 +38,16 @@ pub struct Usage { pub total: f32, pub threads: Option, pub memory: Memory, + pub storage: Option, pub gpu: Option, } +#[derive(Debug, Clone, Copy, Default, Encode, Decode)] +pub struct Storage { + pub used_mb: u32, + pub total_mb: u32, +} + #[derive(Debug, Clone, Copy, Default, Encode, Decode)] pub struct Threads { pub gui: f32, diff --git a/crates/server/src/network.rs b/crates/server/src/network.rs index 808449b..f97db17 100644 --- a/crates/server/src/network.rs +++ b/crates/server/src/network.rs @@ -77,6 +77,7 @@ pub async fn serve( directory, backups, }; + shared.services.machine.watch(shared.directory.clone()); tokio::spawn(retention::collect(shared.clone())); @@ -309,7 +310,7 @@ async fn route( let send_stream = Sending::new(send_stream); let open: Open = frame::read(&mut receive_stream, UP_MAX).await?; match open { - Open::Call(request) => answer(client, request, send_stream, shared).await, + Open::Call(request) => answer(client, *request, send_stream, shared).await, Open::Upload(upload) => { let user = signed_user(&client, &shared).await?; files::upload( diff --git a/crates/server/src/stats.rs b/crates/server/src/stats.rs index 9d60c16..6a51d7e 100644 --- a/crates/server/src/stats.rs +++ b/crates/server/src/stats.rs @@ -1,3 +1,4 @@ +use std::path::PathBuf; use std::{ collections::{HashMap, VecDeque}, sync::{Arc, Mutex}, @@ -83,6 +84,11 @@ pub struct Machine { } impl Machine { + pub fn watch(&self, directory: PathBuf) { + self.monitor.watch_disk(directory); + self.monitor.stay_awake(); + } + pub fn sample(&self, (sent, received): (u64, u64)) -> Stats { let now = Instant::now(); let mut rates = self.rates.lock().unwrap(); diff --git a/crates/usage/Cargo.toml b/crates/usage/Cargo.toml index d83ff6f..4e7f6a7 100644 --- a/crates/usage/Cargo.toml +++ b/crates/usage/Cargo.toml @@ -5,7 +5,8 @@ edition = "2024" [dependencies] common.workspace = true -sysinfo = { version = "0.40.4", default-features = false, features = ["system"] } +cpu-time = "1.0.0" +sysinfo = { version = "0.40.4", default-features = false, features = ["system", "disk"] } [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] nvml-wrapper = "0.13.0" diff --git a/crates/usage/src/lib.rs b/crates/usage/src/lib.rs index b021cc7..d772410 100644 --- a/crates/usage/src/lib.rs +++ b/crates/usage/src/lib.rs @@ -1,4 +1,5 @@ use std::{ + path::{Path, PathBuf}, sync::{Arc, Mutex}, thread, time::{Duration, Instant}, @@ -11,9 +12,10 @@ use sysinfo::{ #[cfg(target_os = "linux")] mod drm; +#[cfg(target_os = "macos")] +mod mac; #[cfg(any(target_os = "linux", target_os = "windows"))] mod nvidia; -#[cfg(target_os = "linux")] mod threads; #[cfg(target_os = "windows")] mod windows; @@ -21,11 +23,14 @@ mod windows; const INTERVAL: Duration = Duration::from_secs(1); const IDLE_AFTER: Duration = Duration::from_secs(3); -pub use common::stats::{Gpu, GpuMachine, Memory, Threads, Usage}; +pub use common::stats::{Gpu, GpuMachine, Memory, Storage, Threads, Usage}; +pub use threads::{Group, tick}; struct Shared { latest: Option, requested: Instant, + awake: bool, + disk: Option, } pub struct Monitor { @@ -37,6 +42,8 @@ impl Default for Monitor { let shared = Arc::new(Mutex::new(Shared { latest: None, requested: Instant::now(), + awake: false, + disk: None, })); let worker = Arc::downgrade(&shared); let _ = thread::Builder::new() @@ -47,6 +54,18 @@ impl Default for Monitor { } impl Monitor { + pub fn watch_disk(&self, path: PathBuf) { + if let Ok(mut shared) = self.shared.lock() { + shared.disk = Some(path); + } + } + + pub fn stay_awake(&self) { + if let Ok(mut shared) = self.shared.lock() { + shared.awake = true; + } + } + pub fn latest(&self) -> Option { let mut shared = self.shared.lock().ok()?; shared.requested = Instant::now(); @@ -61,14 +80,21 @@ fn run(shared: std::sync::Weak>) { let Some(shared) = shared.upgrade() else { return; }; - let wanted = shared - .lock() - .is_ok_and(|shared| shared.requested.elapsed() < IDLE_AFTER); + let Some((wanted, disk)) = shared.lock().ok().map(|shared| { + ( + shared.awake || shared.requested.elapsed() < IDLE_AFTER, + shared.disk.clone(), + ) + }) else { + return; + }; let usage = if wanted { if sampler.is_none() { sampler = Sampler::new(); } - sampler.as_mut().and_then(Sampler::sample) + sampler + .as_mut() + .and_then(|sampler| sampler.sample(disk.as_deref())) } else { sampler = None; None @@ -88,7 +114,6 @@ struct Sampler { cpu_model: Arc, primed: bool, gpu: GpuSampler, - #[cfg(target_os = "linux")] threads: threads::Sampler, } @@ -113,12 +138,11 @@ impl Sampler { cpu_model, primed: false, gpu: GpuSampler::default(), - #[cfg(target_os = "linux")] threads: threads::Sampler::default(), }) } - fn sample(&mut self) -> Option { + fn sample(&mut self, disk: Option<&Path>) -> Option { self.system.refresh_cpu_usage(); self.system .refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram()); @@ -133,10 +157,7 @@ impl Sampler { let process = self.system.process(self.pid)?; let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; let total = self.system.total_memory(); - #[cfg(target_os = "linux")] let threads = self.threads.sample(self.cores); - #[cfg(not(target_os = "linux"))] - let threads = None; Some(Usage { host: self.host.clone(), os: self.os.clone(), @@ -149,6 +170,7 @@ impl Sampler { used_mb: mb(total.saturating_sub(self.system.available_memory())), total_mb: mb(total), }, + storage: disk.and_then(storage), gpu: self.gpu.sample(), }) } @@ -162,6 +184,8 @@ struct GpuSampler { native: drm::Sampler, #[cfg(target_os = "windows")] native: windows::Sampler, + #[cfg(target_os = "macos")] + native: mac::Sampler, } impl GpuSampler { @@ -170,7 +194,12 @@ impl GpuSampler { self.nvidia.sample().or_else(|| self.native.sample()) } - #[cfg(not(any(target_os = "linux", target_os = "windows")))] + #[cfg(target_os = "macos")] + fn sample(&mut self) -> Option { + self.native.sample() + } + + #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] fn sample(&mut self) -> Option { None } @@ -187,3 +216,17 @@ fn os() -> String { None => name, } } + +fn storage(path: &Path) -> Option { + let path = path.ancestors().find_map(|path| path.canonicalize().ok())?; + let disks = sysinfo::Disks::new_with_refreshed_list().ok()?; + let disk = disks + .iter() + .filter(|disk| path.starts_with(disk.mount_point())) + .max_by_key(|disk| disk.mount_point().as_os_str().len())?; + let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; + Some(Storage { + used_mb: mb(disk.total_space().saturating_sub(disk.available_space())), + total_mb: mb(disk.total_space()), + }) +} diff --git a/crates/usage/src/mac.rs b/crates/usage/src/mac.rs new file mode 100644 index 0000000..974f0f0 --- /dev/null +++ b/crates/usage/src/mac.rs @@ -0,0 +1,41 @@ +use std::process::Command; + +use super::{Gpu, GpuMachine}; + +#[derive(Default)] +pub struct Sampler; + +impl Sampler { + pub fn sample(&mut self) -> Option { + let output = Command::new("ioreg") + .args(["-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"]) + .output() + .ok()?; + let text = String::from_utf8_lossy(&output.stdout); + let number = |key: &str| -> Option { + let at = text.find(&format!("\"{key}\"="))? + key.len() + 3; + let digits: String = text[at..] + .chars() + .take_while(char::is_ascii_digit) + .collect(); + digits.parse().ok() + }; + let model = text + .find("\"model\" = \"") + .map(|at| at + 11) + .and_then(|at| text[at..].split('"').next()) + .unwrap_or_default() + .to_string(); + let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; + Some(Gpu { + model, + machine: GpuMachine { + gfx: number("Device Utilization %")? as f32, + video: 0., + vram_used_mb: number("In use system memory").map_or(0, mb), + vram_total_mb: number("Alloc system memory").map_or(0, mb), + }, + ..Gpu::default() + }) + } +} diff --git a/crates/usage/src/threads.rs b/crates/usage/src/threads.rs index edacee9..a02828d 100644 --- a/crates/usage/src/threads.rs +++ b/crates/usage/src/threads.rs @@ -1,70 +1,64 @@ -use std::{fs, time::Instant}; +use std::{ + collections::HashMap, + sync::{LazyLock, Mutex}, + thread::{self, ThreadId}, + time::{Duration, Instant}, +}; + +use cpu_time::ThreadTime; use super::Threads; -#[derive(Clone, Copy, Default)] -struct Ticks { - gui: u64, - camera: u64, - encode: u64, - decode: u64, +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Group { + Gui, + Camera, + Encode, + Decode, +} + +type Spent = [Duration; 4]; + +static SPENT: LazyLock>> = + LazyLock::new(Default::default); + +pub fn tick(group: Group) { + let Ok(time) = ThreadTime::try_now() else { + return; + }; + if let Ok(mut spent) = SPENT.lock() { + spent.insert(thread::current().id(), (group, time.as_duration())); + } +} + +fn spent() -> Option { + let spent = SPENT.lock().ok()?; + let mut total = Spent::default(); + for (group, time) in spent.values() { + total[*group as usize] += *time; + } + Some(total) } #[derive(Default)] pub struct Sampler { - previous: Option<(Instant, Ticks)>, + previous: Option<(Instant, Spent)>, } impl Sampler { pub fn sample(&mut self, cores: f32) -> Option { - let now = (Instant::now(), Ticks::read()?); + let now = (Instant::now(), spent()?); let (at, then) = self.previous.replace(now)?; let seconds = now.0.duration_since(at).as_secs_f32().max(f32::EPSILON) * cores; - let cpu = |now: u64, before: u64| now.saturating_sub(before) as f32 / seconds; - let now = now.1; + let cpu = |group: Group| { + let index = group as usize; + now.1[index].saturating_sub(then[index]).as_secs_f32() * 100. / seconds + }; Some(Threads { - gui: cpu(now.gui, then.gui), - camera: cpu(now.camera, then.camera), - encode: cpu(now.encode, then.encode), - decode: cpu(now.decode, then.decode), + gui: cpu(Group::Gui), + camera: cpu(Group::Camera), + encode: cpu(Group::Encode), + decode: cpu(Group::Decode), }) } } - -impl Ticks { - fn read() -> Option { - let pid = std::process::id().to_string(); - let mut ticks = Self::default(); - for entry in fs::read_dir("/proc/self/task").ok()?.flatten() { - let path = entry.path(); - let Ok(name) = fs::read_to_string(path.join("comm")) else { - continue; - }; - let Some(used) = fs::read_to_string(path.join("stat")) - .ok() - .and_then(|stat| stat_ticks(&stat)) - else { - continue; - }; - let name = name.trim(); - if entry.file_name().to_str() == Some(pid.as_str()) { - ticks.gui += used; - } else if name.starts_with("camera") || name.starts_with("share-capture") { - ticks.camera += used; - } else if name == "share-encode" { - ticks.encode += used; - } else if name == "media-decode" || name.contains("video") { - ticks.decode += used; - } - } - Some(ticks) - } -} - -fn stat_ticks(stat: &str) -> Option { - let rest = stat.get(stat.rfind(')')? + 1..)?; - let fields: Vec<&str> = rest.split_whitespace().collect(); - let utime: u64 = fields.get(11)?.parse().ok()?; - let stime: u64 = fields.get(12)?.parse().ok()?; - Some(utime + stime) -}