Windows tray (badge icon, Show/Quit, close to tray), per-thread CPU on every OS (threads report their own time), machine storage row, server stats sampled always, macOS GPU via ioreg
Browse files at this commit5da5470cabcceac35748eb92d6b12da59f90174eParent: 15435f7- feat
- Windows tray (badge icon, Show/Quit, close to tray), per-thread CPU on every OS (threads report their own time), machine storage row, server stats sampled always, macOS GPU via ioreg
- fix
- server machine stats late on first open
22 changed files +366 -152
- crates/client/Cargo.toml +1 -0
- crates/client/src/gui.rs +1 -0
- crates/client/src/gui/chat.rs +7 -1
- crates/client/src/gui/voice_stats.rs +16 -1
- crates/client/src/lib.rs +5 -2
- crates/client/src/main.rs +1 -1
- crates/client/src/media/decode.rs +2 -0
- crates/client/src/net/link.rs +5 -3
- crates/client/src/share/camera.rs +1 -0
- crates/client/src/share/capture.rs +1 -0
- crates/client/src/share/capture_windows.rs +1 -0
- crates/client/src/share/encode.rs +1 -0
- crates/client/src/share/fake.rs +1 -0
- crates/client/src/tray.rs +161 -75
- crates/common/src/open.rs +1 -1
- crates/common/src/stats.rs +7 -0
- crates/server/src/network.rs +2 -1
- crates/server/src/stats.rs +6 -0
- crates/usage/Cargo.toml +2 -1
- crates/usage/src/lib.rs +56 -13
- crates/usage/src/mac.rs +41 -0
- crates/usage/src/threads.rs +47 -53
crates/client/Cargo.tomlmodified+1 -0
| @@ -47,6 +47,7 @@ ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "sc | |||
| 47 | [target.'cfg(target_os = "windows")'.dependencies] | 47 | [target.'cfg(target_os = "windows")'.dependencies] |
| 48 | wasapi = "0.27.0" | 48 | wasapi = "0.27.0" |
| 49 | windows-capture = "2.0.1" | 49 | windows-capture = "2.0.1" |
| 50 | +tray-icon = { version = "0.27.0", default-features = false } | ||
| 50 | 51 | ||
| 51 | [target.'cfg(target_os = "macos")'.dependencies] | 52 | [target.'cfg(target_os = "macos")'.dependencies] |
| 52 | coreaudio-rs = "0.14.2" | 53 | coreaudio-rs = "0.14.2" |
crates/client/src/gui.rsmodified+1 -0
| @@ -1279,6 +1279,7 @@ pub(super) fn new_input( | |||
| 1279 | 1279 | ||
| 1280 | impl Render for Yumush { | 1280 | impl Render for Yumush { |
| 1281 | fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { | 1281 | fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 1282 | + crate::usage::tick(crate::usage::Group::Gui); | ||
| 1282 | let fullscreen = self | 1283 | let fullscreen = self |
| 1283 | .chat | 1284 | .chat |
| 1284 | .viewer | 1285 | .viewer |
crates/client/src/gui/chat.rsmodified+7 -1
| @@ -536,7 +536,13 @@ impl Chat { | |||
| 536 | followed: None, | 536 | followed: None, |
| 537 | share_loss: HashMap::new(), | 537 | share_loss: HashMap::new(), |
| 538 | stats_at: None, | 538 | stats_at: None, |
| 539 | - usage_monitor: crate::usage::Monitor::default(), | 539 | + usage_monitor: { |
| 540 | + let monitor = crate::usage::Monitor::default(); | ||
| 541 | + if let Some(dir) = crate::config_dir() { | ||
| 542 | + monitor.watch_disk(dir); | ||
| 543 | + } | ||
| 544 | + monitor | ||
| 545 | + }, | ||
| 540 | ringing: HashSet::new(), | 546 | ringing: HashSet::new(), |
| 541 | ring_task: None, | 547 | ring_task: None, |
| 542 | typing: HashMap::new(), | 548 | typing: HashMap::new(), |
crates/client/src/gui/voice_stats.rsmodified+16 -1
| @@ -277,6 +277,20 @@ fn machine(usage: &Usage, t: Tokens) -> Div { | |||
| 277 | false, | 277 | false, |
| 278 | t, | 278 | t, |
| 279 | )) | 279 | )) |
| 280 | + .children(usage.storage.map(|storage| { | ||
| 281 | + line_row( | ||
| 282 | + label("storage", t), | ||
| 283 | + track( | ||
| 284 | + Fill::Part(storage.used_mb as f32 / storage.total_mb.max(1) as f32), | ||
| 285 | + false, | ||
| 286 | + t, | ||
| 287 | + ) | ||
| 288 | + .into_any_element(), | ||
| 289 | + format!("{} / {}", gb(storage.used_mb), gb(storage.total_mb)), | ||
| 290 | + false, | ||
| 291 | + t, | ||
| 292 | + ) | ||
| 293 | + })) | ||
| 280 | .children(usage.gpu.as_ref().map(|gpu| { | 294 | .children(usage.gpu.as_ref().map(|gpu| { |
| 281 | let machine = gpu.machine; | 295 | let machine = gpu.machine; |
| 282 | let vram_total = machine.vram_total_mb.max(machine.vram_used_mb).max(1) as f32; | 296 | 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 { | |||
| 462 | fn gb(mb: u32) -> String { | 476 | fn gb(mb: u32) -> String { |
| 463 | match mb { | 477 | match mb { |
| 464 | 0..1000 => format!("{mb} MB"), | 478 | 0..1000 => format!("{mb} MB"), |
| 465 | - _ => format!("{:.1} GB", mb as f32 / 1024.), | 479 | + 1000..1_000_000 => format!("{:.1} GB", mb as f32 / 1024.), |
| 480 | + _ => format!("{:.1} TB", mb as f32 / (1024. * 1024.)), | ||
| 466 | } | 481 | } |
| 467 | } | 482 | } |
| 468 | 483 | ||
crates/client/src/lib.rsmodified+5 -2
| @@ -18,11 +18,14 @@ pub mod voice; | |||
| 18 | 18 | ||
| 19 | pub const NAME: &str = "Yumush"; | 19 | pub const NAME: &str = "Yumush"; |
| 20 | 20 | ||
| 21 | -fn config_file(name: &str) -> Option<PathBuf> { | 21 | +pub fn config_dir() -> Option<PathBuf> { |
| 22 | std::env::var_os("YUMUSH_CONFIG_DIR") | 22 | std::env::var_os("YUMUSH_CONFIG_DIR") |
| 23 | .map(PathBuf::from) | 23 | .map(PathBuf::from) |
| 24 | .or_else(|| dirs::config_dir().map(|dir| dir.join("yumush"))) | 24 | .or_else(|| dirs::config_dir().map(|dir| dir.join("yumush"))) |
| 25 | - .map(|dir| dir.join(name)) | 25 | +} |
| 26 | + | ||
| 27 | +fn config_file(name: &str) -> Option<PathBuf> { | ||
| 28 | + config_dir().map(|dir| dir.join(name)) | ||
| 26 | } | 29 | } |
| 27 | 30 | ||
| 28 | pub fn read_config(name: &str) -> Option<String> { | 31 | pub fn read_config(name: &str) -> Option<String> { |
crates/client/src/main.rsmodified+1 -1
| @@ -42,7 +42,6 @@ fn main() { | |||
| 42 | 42 | ||
| 43 | let settings = settings::load(); | 43 | let settings = settings::load(); |
| 44 | let (network_handle, network_event_receiver) = net::start(ClientConfig::default()); | 44 | let (network_handle, network_event_receiver) = net::start(ClientConfig::default()); |
| 45 | - let (mut tray_receiver, tray_handle) = tray::start(); | ||
| 46 | 45 | ||
| 47 | application() | 46 | application() |
| 48 | .with_assets(AllAssets) | 47 | .with_assets(AllAssets) |
| @@ -61,6 +60,7 @@ fn main() { | |||
| 61 | return; | 60 | return; |
| 62 | }; | 61 | }; |
| 63 | 62 | ||
| 63 | + let (mut tray_receiver, tray_handle) = tray::start(); | ||
| 64 | let mut tray_state = TrayState::default(); | 64 | let mut tray_state = TrayState::default(); |
| 65 | cx.observe(&view, move |view, cx| { | 65 | cx.observe(&view, move |view, cx| { |
| 66 | let state = view.read(cx).tray_state(); | 66 | let state = view.read(cx).tray_state(); |
crates/client/src/media/decode.rsmodified+2 -0
| @@ -217,6 +217,7 @@ impl VideoDecoder { | |||
| 217 | } | 217 | } |
| 218 | 218 | ||
| 219 | pub fn decode(&mut self, data: &[u8], timestamp_ms: u32) -> Vec<Picture> { | 219 | pub fn decode(&mut self, data: &[u8], timestamp_ms: u32) -> Vec<Picture> { |
| 220 | + crate::usage::tick(crate::usage::Group::Decode); | ||
| 220 | let mut packet = Packet::new(0, TimeBase::MILLIS, data); | 221 | let mut packet = Packet::new(0, TimeBase::MILLIS, data); |
| 221 | packet.pts = Some(i64::from(timestamp_ms)); | 222 | packet.pts = Some(i64::from(timestamp_ms)); |
| 222 | self.send(&packet) | 223 | self.send(&packet) |
| @@ -646,6 +647,7 @@ impl Worker { | |||
| 646 | } | 647 | } |
| 647 | 648 | ||
| 648 | fn decode_backlog(&mut self) -> bool { | 649 | fn decode_backlog(&mut self) -> bool { |
| 650 | + crate::usage::tick(crate::usage::Group::Decode); | ||
| 649 | let Some((_, video)) = self.video.as_mut() else { | 651 | let Some((_, video)) = self.video.as_mut() else { |
| 650 | return false; | 652 | return false; |
| 651 | }; | 653 | }; |
crates/client/src/net/link.rsmodified+5 -3
| @@ -252,9 +252,11 @@ pub(super) async fn call<C: Call>( | |||
| 252 | connection: &quinn::Connection, | 252 | connection: &quinn::Connection, |
| 253 | call: C, | 253 | call: C, |
| 254 | ) -> Result<C::Reply, Fail> { | 254 | ) -> Result<C::Reply, Fail> { |
| 255 | - Ok(exchange(connection, &Open::Call(call.into_request())) | 255 | + Ok( |
| 256 | - .await? | 256 | + exchange(connection, &Open::Call(Box::new(call.into_request()))) |
| 257 | - .0) | 257 | + .await? |
| 258 | + .0, | ||
| 259 | + ) | ||
| 258 | } | 260 | } |
| 259 | 261 | ||
| 260 | async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> { | 262 | async fn hello(connection: &quinn::Connection, token: Option<String>) -> Result<Welcome, Fail> { |
crates/client/src/share/camera.rsmodified+1 -0
| @@ -227,6 +227,7 @@ fn run( | |||
| 227 | let mut failures = 0; | 227 | let mut failures = 0; |
| 228 | let mut due = 0u32; | 228 | let mut due = 0u32; |
| 229 | while !stop.load(Ordering::Relaxed) { | 229 | while !stop.load(Ordering::Relaxed) { |
| 230 | + crate::usage::tick(crate::usage::Group::Camera); | ||
| 230 | let buffer = match camera.frame() { | 231 | let buffer = match camera.frame() { |
| 231 | Ok(buffer) => buffer, | 232 | Ok(buffer) => buffer, |
| 232 | Err(error) => { | 233 | Err(error) => { |
crates/client/src/share/capture.rsmodified+1 -0
| @@ -484,6 +484,7 @@ fn on_param(stream: &pw::stream::Stream, state: &mut State, id: u32, param: Opti | |||
| 484 | } | 484 | } |
| 485 | 485 | ||
| 486 | fn on_process(stream: &pw::stream::Stream, state: &mut State) { | 486 | fn on_process(stream: &pw::stream::Stream, state: &mut State) { |
| 487 | + crate::usage::tick(crate::usage::Group::Camera); | ||
| 487 | let (width, height) = state.size; | 488 | let (width, height) = state.size; |
| 488 | if width == 0 || height == 0 { | 489 | if width == 0 || height == 0 { |
| 489 | return; | 490 | return; |
crates/client/src/share/capture_windows.rsmodified+1 -0
| @@ -107,6 +107,7 @@ impl GraphicsCaptureApiHandler for Handler { | |||
| 107 | frame: &mut CaptureFrame, | 107 | frame: &mut CaptureFrame, |
| 108 | _: InternalCaptureControl, | 108 | _: InternalCaptureControl, |
| 109 | ) -> Result<(), Self::Error> { | 109 | ) -> Result<(), Self::Error> { |
| 110 | + crate::usage::tick(crate::usage::Group::Camera); | ||
| 110 | let (width, height) = (frame.width(), frame.height()); | 111 | let (width, height) = (frame.width(), frame.height()); |
| 111 | let mut buffer = frame.buffer().map_err(text)?; | 112 | let mut buffer = frame.buffer().map_err(text)?; |
| 112 | let pitch = buffer.row_pitch() as usize; | 113 | let pitch = buffer.row_pitch() as usize; |
crates/client/src/share/encode.rsmodified+1 -0
| @@ -377,6 +377,7 @@ fn run( | |||
| 377 | let interval = 1000 / settings.fps; | 377 | let interval = 1000 / settings.fps; |
| 378 | let mut due = 0u32; | 378 | let mut due = 0u32; |
| 379 | for frame in input { | 379 | for frame in input { |
| 380 | + crate::usage::tick(crate::usage::Group::Encode); | ||
| 380 | if frame.timestamp_ms + SLACK_MS < due { | 381 | if frame.timestamp_ms + SLACK_MS < due { |
| 381 | continue; | 382 | continue; |
| 382 | } | 383 | } |
crates/client/src/share/fake.rsmodified+1 -0
| @@ -45,6 +45,7 @@ pub fn start(spec: &str) -> (u32, u32, u32, Receiver<Frame>, Generator) { | |||
| 45 | let noisy = std::env::var_os("YUMUSH_TEST_NOISE").is_some(); | 45 | let noisy = std::env::var_os("YUMUSH_TEST_NOISE").is_some(); |
| 46 | let mut seed: u64 = 0x9e37_79b9_7f4a_7c15; | 46 | let mut seed: u64 = 0x9e37_79b9_7f4a_7c15; |
| 47 | while !stop.load(Ordering::Relaxed) { | 47 | while !stop.load(Ordering::Relaxed) { |
| 48 | + crate::usage::tick(crate::usage::Group::Camera); | ||
| 48 | let bar = (number as usize * 8) % width as usize; | 49 | let bar = (number as usize * 8) % width as usize; |
| 49 | let mut bgra = vec![40u8; (width * height) as usize * BYTES_PER_PIXEL]; | 50 | let mut bgra = vec![40u8; (width * height) as usize * BYTES_PER_PIXEL]; |
| 50 | if noisy { | 51 | if noisy { |
crates/client/src/tray.rsmodified+161 -75
| @@ -1,6 +1,4 @@ | |||
| 1 | -use tokio::sync::mpsc; | 1 | +pub const AVAILABLE: bool = cfg!(any(target_os = "linux", target_os = "windows")); |
| 2 | - | ||
| 3 | -pub const AVAILABLE: bool = cfg!(target_os = "linux"); | ||
| 4 | 2 | ||
| 5 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 3 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 6 | pub enum TrayAction { | 4 | pub enum TrayAction { |
| @@ -14,50 +12,107 @@ pub struct TrayState { | |||
| 14 | pub mentions: u32, | 12 | pub mentions: u32, |
| 15 | } | 13 | } |
| 16 | 14 | ||
| 17 | -#[derive(Clone)] | 15 | +pub struct TrayHandle(Box<dyn Fn(TrayState)>); |
| 18 | -pub struct TrayHandle(mpsc::UnboundedSender<TrayState>); | ||
| 19 | 16 | ||
| 20 | impl TrayHandle { | 17 | impl TrayHandle { |
| 21 | pub fn set(&self, state: TrayState) { | 18 | pub fn set(&self, state: TrayState) { |
| 22 | - let _ = self.0.send(state); | 19 | + (self.0)(state); |
| 23 | } | 20 | } |
| 24 | } | 21 | } |
| 25 | 22 | ||
| 26 | #[cfg(target_os = "linux")] | 23 | #[cfg(target_os = "linux")] |
| 27 | pub use linux::start; | 24 | pub use linux::start; |
| 25 | +#[cfg(target_os = "windows")] | ||
| 26 | +pub use windows::start; | ||
| 28 | 27 | ||
| 29 | -#[cfg(not(target_os = "linux"))] | 28 | +#[cfg(not(any(target_os = "linux", target_os = "windows")))] |
| 30 | -pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { | 29 | +pub fn start() -> (tokio::sync::mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { |
| 31 | ( | 30 | ( |
| 32 | - mpsc::unbounded_channel().1, | 31 | + tokio::sync::mpsc::unbounded_channel().1, |
| 33 | - TrayHandle(mpsc::unbounded_channel().0), | 32 | + TrayHandle(Box::new(|_| {})), |
| 34 | ) | 33 | ) |
| 35 | } | 34 | } |
| 36 | 35 | ||
| 36 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 37 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 38 | +enum Badge { | ||
| 39 | + None, | ||
| 40 | + Unread, | ||
| 41 | + Mention, | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 45 | +impl TrayState { | ||
| 46 | + fn badge(self) -> Badge { | ||
| 47 | + match (self.messages, self.mentions) { | ||
| 48 | + (_, 1..) => Badge::Mention, | ||
| 49 | + (1.., _) => Badge::Unread, | ||
| 50 | + _ => Badge::None, | ||
| 51 | + } | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + fn tip(self) -> String { | ||
| 55 | + match self.badge() { | ||
| 56 | + Badge::None => crate::NAME.to_string(), | ||
| 57 | + _ => format!( | ||
| 58 | + "{} · {} unread · {} mentions", | ||
| 59 | + crate::NAME, | ||
| 60 | + self.messages, | ||
| 61 | + self.mentions | ||
| 62 | + ), | ||
| 63 | + } | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 68 | +const ICON_SIZE: i32 = 32; | ||
| 69 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 70 | +const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2]; | ||
| 71 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 72 | +const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)]; | ||
| 73 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 74 | +const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); | ||
| 75 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 76 | +const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; | ||
| 77 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 78 | +const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; | ||
| 79 | + | ||
| 80 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 81 | +fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { | ||
| 82 | + let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); | ||
| 83 | + (radius - distance + 0.5).clamp(0.0, 1.0) | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +#[cfg(any(target_os = "linux", target_os = "windows"))] | ||
| 87 | +fn pixels(badge: Badge) -> impl Iterator<Item = ([u8; 3], u8)> { | ||
| 88 | + let dot = match badge { | ||
| 89 | + Badge::None => None, | ||
| 90 | + Badge::Unread => Some(UNREAD_COLOR), | ||
| 91 | + Badge::Mention => Some(MENTION_COLOR), | ||
| 92 | + }; | ||
| 93 | + (0..ICON_SIZE * ICON_SIZE).map(move |index| { | ||
| 94 | + let x = (index % ICON_SIZE) as f32 + 0.5; | ||
| 95 | + let y = (index / ICON_SIZE) as f32 + 0.5; | ||
| 96 | + let base = ICON_DROPS | ||
| 97 | + .iter() | ||
| 98 | + .map(|drop| coverage(x, y, *drop)) | ||
| 99 | + .fold(0.0, f32::max); | ||
| 100 | + let (color, alpha) = match dot { | ||
| 101 | + Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)), | ||
| 102 | + Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => (ICON_COLOR, 0.0), | ||
| 103 | + _ => (ICON_COLOR, base), | ||
| 104 | + }; | ||
| 105 | + (color, (alpha * 255.0) as u8) | ||
| 106 | + }) | ||
| 107 | +} | ||
| 108 | + | ||
| 37 | #[cfg(target_os = "linux")] | 109 | #[cfg(target_os = "linux")] |
| 38 | mod linux { | 110 | mod linux { |
| 39 | use ksni::TrayMethods; | 111 | use ksni::TrayMethods; |
| 40 | use tokio::sync::mpsc; | 112 | use tokio::sync::mpsc; |
| 41 | use tracing::warn; | 113 | use tracing::warn; |
| 42 | 114 | ||
| 43 | - use super::{TrayAction, TrayHandle, TrayState}; | 115 | + use super::{Badge, ICON_SIZE, TrayAction, TrayHandle, TrayState, pixels}; |
| 44 | - | ||
| 45 | - #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 46 | - enum Badge { | ||
| 47 | - None, | ||
| 48 | - Unread, | ||
| 49 | - Mention, | ||
| 50 | - } | ||
| 51 | - | ||
| 52 | - impl TrayState { | ||
| 53 | - fn badge(self) -> Badge { | ||
| 54 | - match (self.messages, self.mentions) { | ||
| 55 | - (_, 1..) => Badge::Mention, | ||
| 56 | - (1.., _) => Badge::Unread, | ||
| 57 | - _ => Badge::None, | ||
| 58 | - } | ||
| 59 | - } | ||
| 60 | - } | ||
| 61 | 116 | ||
| 62 | pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { | 117 | pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { |
| 63 | let (sender, receiver) = mpsc::unbounded_channel(); | 118 | let (sender, receiver) = mpsc::unbounded_channel(); |
| @@ -93,7 +148,12 @@ mod linux { | |||
| 93 | }); | 148 | }); |
| 94 | }); | 149 | }); |
| 95 | 150 | ||
| 96 | - (receiver, TrayHandle(state_sender)) | 151 | + ( |
| 152 | + receiver, | ||
| 153 | + TrayHandle(Box::new(move |state| { | ||
| 154 | + let _ = state_sender.send(state); | ||
| 155 | + })), | ||
| 156 | + ) | ||
| 97 | } | 157 | } |
| 98 | 158 | ||
| 99 | struct Tray { | 159 | struct Tray { |
| @@ -122,16 +182,8 @@ mod linux { | |||
| 122 | } | 182 | } |
| 123 | 183 | ||
| 124 | fn tool_tip(&self) -> ksni::ToolTip { | 184 | fn tool_tip(&self) -> ksni::ToolTip { |
| 125 | - let description = match self.state.badge() { | ||
| 126 | - Badge::None => String::new(), | ||
| 127 | - _ => format!( | ||
| 128 | - "{} unread · {} mentions", | ||
| 129 | - self.state.messages, self.state.mentions | ||
| 130 | - ), | ||
| 131 | - }; | ||
| 132 | ksni::ToolTip { | 185 | ksni::ToolTip { |
| 133 | - title: crate::NAME.to_string(), | 186 | + title: self.state.tip(), |
| 134 | - description, | ||
| 135 | ..Default::default() | 187 | ..Default::default() |
| 136 | } | 188 | } |
| 137 | } | 189 | } |
| @@ -164,47 +216,81 @@ mod linux { | |||
| 164 | } | 216 | } |
| 165 | } | 217 | } |
| 166 | 218 | ||
| 167 | - const ICON_SIZE: i32 = 32; | ||
| 168 | - const ICON_COLOR: [u8; 3] = [0x7c, 0x6c, 0xf2]; | ||
| 169 | - const ICON_DROPS: [(f32, f32, f32); 2] = [(13.0, 18.0, 11.0), (24.0, 9.0, 6.0)]; | ||
| 170 | - const BADGE: (f32, f32, f32) = (25.0, 25.0, 7.0); | ||
| 171 | - const UNREAD_COLOR: [u8; 3] = [0xe6, 0xe6, 0xe6]; | ||
| 172 | - const MENTION_COLOR: [u8; 3] = [0xef, 0x44, 0x44]; | ||
| 173 | - | ||
| 174 | - fn coverage(x: f32, y: f32, (cx, cy, radius): (f32, f32, f32)) -> f32 { | ||
| 175 | - let distance = ((x - cx).powi(2) + (y - cy).powi(2)).sqrt(); | ||
| 176 | - (radius - distance + 0.5).clamp(0.0, 1.0) | ||
| 177 | - } | ||
| 178 | - | ||
| 179 | fn icon(badge: Badge) -> ksni::Icon { | 219 | fn icon(badge: Badge) -> ksni::Icon { |
| 180 | - let dot = match badge { | ||
| 181 | - Badge::None => None, | ||
| 182 | - Badge::Unread => Some(UNREAD_COLOR), | ||
| 183 | - Badge::Mention => Some(MENTION_COLOR), | ||
| 184 | - }; | ||
| 185 | - let data = (0..ICON_SIZE * ICON_SIZE) | ||
| 186 | - .flat_map(|index| { | ||
| 187 | - let x = (index % ICON_SIZE) as f32 + 0.5; | ||
| 188 | - let y = (index / ICON_SIZE) as f32 + 0.5; | ||
| 189 | - let base = ICON_DROPS | ||
| 190 | - .iter() | ||
| 191 | - .map(|drop| coverage(x, y, *drop)) | ||
| 192 | - .fold(0.0, f32::max); | ||
| 193 | - let ([red, green, blue], alpha) = match dot { | ||
| 194 | - Some(color) if coverage(x, y, BADGE) > 0.0 => (color, coverage(x, y, BADGE)), | ||
| 195 | - Some(_) if coverage(x, y, (BADGE.0, BADGE.1, BADGE.2 + 2.0)) > 0.0 => { | ||
| 196 | - (ICON_COLOR, 0.0) | ||
| 197 | - } | ||
| 198 | - _ => (ICON_COLOR, base), | ||
| 199 | - }; | ||
| 200 | - [(alpha * 255.0) as u8, red, green, blue] | ||
| 201 | - }) | ||
| 202 | - .collect(); | ||
| 203 | - | ||
| 204 | ksni::Icon { | 220 | ksni::Icon { |
| 205 | width: ICON_SIZE, | 221 | width: ICON_SIZE, |
| 206 | height: ICON_SIZE, | 222 | height: ICON_SIZE, |
| 207 | - data, | 223 | + data: pixels(badge) |
| 224 | + .flat_map(|([red, green, blue], alpha)| [alpha, red, green, blue]) | ||
| 225 | + .collect(), | ||
| 208 | } | 226 | } |
| 209 | } | 227 | } |
| 210 | } | 228 | } |
| 229 | + | ||
| 230 | +#[cfg(target_os = "windows")] | ||
| 231 | +mod windows { | ||
| 232 | + use tokio::sync::mpsc; | ||
| 233 | + use tracing::warn; | ||
| 234 | + use tray_icon::{ | ||
| 235 | + Icon, MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent, | ||
| 236 | + menu::{Menu, MenuEvent, MenuItem}, | ||
| 237 | + }; | ||
| 238 | + | ||
| 239 | + use super::{Badge, ICON_SIZE, TrayAction, TrayHandle, TrayState, pixels}; | ||
| 240 | + | ||
| 241 | + fn icon(badge: Badge) -> Option<Icon> { | ||
| 242 | + let rgba = pixels(badge) | ||
| 243 | + .flat_map(|([red, green, blue], alpha)| [red, green, blue, alpha]) | ||
| 244 | + .collect(); | ||
| 245 | + Icon::from_rgba(rgba, ICON_SIZE as u32, ICON_SIZE as u32).ok() | ||
| 246 | + } | ||
| 247 | + | ||
| 248 | + pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) { | ||
| 249 | + let (sender, receiver) = mpsc::unbounded_channel(); | ||
| 250 | + let show = MenuItem::new("Show", true, None); | ||
| 251 | + let quit = MenuItem::new("Quit", true, None); | ||
| 252 | + let menu = Menu::new(); | ||
| 253 | + if let Err(error) = menu.append_items(&[&show, &quit]) { | ||
| 254 | + warn!("tray menu: {error}"); | ||
| 255 | + } | ||
| 256 | + let (show_id, quit_id) = (show.id().clone(), quit.id().clone()); | ||
| 257 | + let menu_sender = sender.clone(); | ||
| 258 | + MenuEvent::set_event_handler(Some(std::sync::Arc::new(move |event: MenuEvent| { | ||
| 259 | + let action = if event.id == show_id { | ||
| 260 | + TrayAction::Show | ||
| 261 | + } else if event.id == quit_id { | ||
| 262 | + TrayAction::Quit | ||
| 263 | + } else { | ||
| 264 | + return; | ||
| 265 | + }; | ||
| 266 | + let _ = menu_sender.send(action); | ||
| 267 | + }))); | ||
| 268 | + TrayIconEvent::set_event_handler(Some(move |event: TrayIconEvent| { | ||
| 269 | + if let TrayIconEvent::Click { | ||
| 270 | + button: MouseButton::Left, | ||
| 271 | + button_state: MouseButtonState::Up, | ||
| 272 | + .. | ||
| 273 | + } = event | ||
| 274 | + { | ||
| 275 | + let _ = sender.send(TrayAction::Show); | ||
| 276 | + } | ||
| 277 | + })); | ||
| 278 | + let mut builder = TrayIconBuilder::new() | ||
| 279 | + .with_menu(Box::new(menu)) | ||
| 280 | + .with_tooltip(crate::NAME); | ||
| 281 | + if let Some(icon) = icon(Badge::None) { | ||
| 282 | + builder = builder.with_icon(icon); | ||
| 283 | + } | ||
| 284 | + let handle = match builder.build() { | ||
| 285 | + Ok(tray) => TrayHandle(Box::new(move |state: TrayState| { | ||
| 286 | + let _ = tray.set_icon(icon(state.badge())); | ||
| 287 | + let _ = tray.set_tooltip(Some(state.tip())); | ||
| 288 | + })), | ||
| 289 | + Err(error) => { | ||
| 290 | + warn!("tray: {error}"); | ||
| 291 | + TrayHandle(Box::new(|_| {})) | ||
| 292 | + } | ||
| 293 | + }; | ||
| 294 | + (receiver, handle) | ||
| 295 | + } | ||
| 296 | +} | ||
crates/common/src/open.rsmodified+1 -1
| @@ -4,7 +4,7 @@ use crate::{call::Request, model::Id}; | |||
| 4 | 4 | ||
| 5 | #[derive(Debug, Clone, Encode, Decode)] | 5 | #[derive(Debug, Clone, Encode, Decode)] |
| 6 | pub enum Open { | 6 | pub enum Open { |
| 7 | - Call(Request), | 7 | + Call(Box<Request>), |
| 8 | Upload(Upload), | 8 | Upload(Upload), |
| 9 | Fetch(Blob), | 9 | Fetch(Blob), |
| 10 | } | 10 | } |
crates/common/src/stats.rsmodified+7 -0
| @@ -38,9 +38,16 @@ pub struct Usage { | |||
| 38 | pub total: f32, | 38 | pub total: f32, |
| 39 | pub threads: Option<Threads>, | 39 | pub threads: Option<Threads>, |
| 40 | pub memory: Memory, | 40 | pub memory: Memory, |
| 41 | + pub storage: Option<Storage>, | ||
| 41 | pub gpu: Option<Gpu>, | 42 | pub gpu: Option<Gpu>, |
| 42 | } | 43 | } |
| 43 | 44 | ||
| 45 | +#[derive(Debug, Clone, Copy, Default, Encode, Decode)] | ||
| 46 | +pub struct Storage { | ||
| 47 | + pub used_mb: u32, | ||
| 48 | + pub total_mb: u32, | ||
| 49 | +} | ||
| 50 | + | ||
| 44 | #[derive(Debug, Clone, Copy, Default, Encode, Decode)] | 51 | #[derive(Debug, Clone, Copy, Default, Encode, Decode)] |
| 45 | pub struct Threads { | 52 | pub struct Threads { |
| 46 | pub gui: f32, | 53 | pub gui: f32, |
crates/server/src/network.rsmodified+2 -1
| @@ -77,6 +77,7 @@ pub async fn serve( | |||
| 77 | directory, | 77 | directory, |
| 78 | backups, | 78 | backups, |
| 79 | }; | 79 | }; |
| 80 | + shared.services.machine.watch(shared.directory.clone()); | ||
| 80 | 81 | ||
| 81 | tokio::spawn(retention::collect(shared.clone())); | 82 | tokio::spawn(retention::collect(shared.clone())); |
| 82 | 83 | ||
| @@ -309,7 +310,7 @@ async fn route( | |||
| 309 | let send_stream = Sending::new(send_stream); | 310 | let send_stream = Sending::new(send_stream); |
| 310 | let open: Open = frame::read(&mut receive_stream, UP_MAX).await?; | 311 | let open: Open = frame::read(&mut receive_stream, UP_MAX).await?; |
| 311 | match open { | 312 | match open { |
| 312 | - Open::Call(request) => answer(client, request, send_stream, shared).await, | 313 | + Open::Call(request) => answer(client, *request, send_stream, shared).await, |
| 313 | Open::Upload(upload) => { | 314 | Open::Upload(upload) => { |
| 314 | let user = signed_user(&client, &shared).await?; | 315 | let user = signed_user(&client, &shared).await?; |
| 315 | files::upload( | 316 | files::upload( |
crates/server/src/stats.rsmodified+6 -0
| @@ -1,3 +1,4 @@ | |||
| 1 | +use std::path::PathBuf; | ||
| 1 | use std::{ | 2 | use std::{ |
| 2 | collections::{HashMap, VecDeque}, | 3 | collections::{HashMap, VecDeque}, |
| 3 | sync::{Arc, Mutex}, | 4 | sync::{Arc, Mutex}, |
| @@ -83,6 +84,11 @@ pub struct Machine { | |||
| 83 | } | 84 | } |
| 84 | 85 | ||
| 85 | impl Machine { | 86 | impl Machine { |
| 87 | + pub fn watch(&self, directory: PathBuf) { | ||
| 88 | + self.monitor.watch_disk(directory); | ||
| 89 | + self.monitor.stay_awake(); | ||
| 90 | + } | ||
| 91 | + | ||
| 86 | pub fn sample(&self, (sent, received): (u64, u64)) -> Stats { | 92 | pub fn sample(&self, (sent, received): (u64, u64)) -> Stats { |
| 87 | let now = Instant::now(); | 93 | let now = Instant::now(); |
| 88 | let mut rates = self.rates.lock().unwrap(); | 94 | let mut rates = self.rates.lock().unwrap(); |
crates/usage/Cargo.tomlmodified+2 -1
| @@ -5,7 +5,8 @@ edition = "2024" | |||
| 5 | 5 | ||
| 6 | [dependencies] | 6 | [dependencies] |
| 7 | common.workspace = true | 7 | common.workspace = true |
| 8 | -sysinfo = { version = "0.40.4", default-features = false, features = ["system"] } | 8 | +cpu-time = "1.0.0" |
| 9 | +sysinfo = { version = "0.40.4", default-features = false, features = ["system", "disk"] } | ||
| 9 | 10 | ||
| 10 | [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] | 11 | [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies] |
| 11 | nvml-wrapper = "0.13.0" | 12 | nvml-wrapper = "0.13.0" |
crates/usage/src/lib.rsmodified+56 -13
| @@ -1,4 +1,5 @@ | |||
| 1 | use std::{ | 1 | use std::{ |
| 2 | + path::{Path, PathBuf}, | ||
| 2 | sync::{Arc, Mutex}, | 3 | sync::{Arc, Mutex}, |
| 3 | thread, | 4 | thread, |
| 4 | time::{Duration, Instant}, | 5 | time::{Duration, Instant}, |
| @@ -11,9 +12,10 @@ use sysinfo::{ | |||
| 11 | 12 | ||
| 12 | #[cfg(target_os = "linux")] | 13 | #[cfg(target_os = "linux")] |
| 13 | mod drm; | 14 | mod drm; |
| 15 | +#[cfg(target_os = "macos")] | ||
| 16 | +mod mac; | ||
| 14 | #[cfg(any(target_os = "linux", target_os = "windows"))] | 17 | #[cfg(any(target_os = "linux", target_os = "windows"))] |
| 15 | mod nvidia; | 18 | mod nvidia; |
| 16 | -#[cfg(target_os = "linux")] | ||
| 17 | mod threads; | 19 | mod threads; |
| 18 | #[cfg(target_os = "windows")] | 20 | #[cfg(target_os = "windows")] |
| 19 | mod windows; | 21 | mod windows; |
| @@ -21,11 +23,14 @@ mod windows; | |||
| 21 | const INTERVAL: Duration = Duration::from_secs(1); | 23 | const INTERVAL: Duration = Duration::from_secs(1); |
| 22 | const IDLE_AFTER: Duration = Duration::from_secs(3); | 24 | const IDLE_AFTER: Duration = Duration::from_secs(3); |
| 23 | 25 | ||
| 24 | -pub use common::stats::{Gpu, GpuMachine, Memory, Threads, Usage}; | 26 | +pub use common::stats::{Gpu, GpuMachine, Memory, Storage, Threads, Usage}; |
| 27 | +pub use threads::{Group, tick}; | ||
| 25 | 28 | ||
| 26 | struct Shared { | 29 | struct Shared { |
| 27 | latest: Option<Usage>, | 30 | latest: Option<Usage>, |
| 28 | requested: Instant, | 31 | requested: Instant, |
| 32 | + awake: bool, | ||
| 33 | + disk: Option<PathBuf>, | ||
| 29 | } | 34 | } |
| 30 | 35 | ||
| 31 | pub struct Monitor { | 36 | pub struct Monitor { |
| @@ -37,6 +42,8 @@ impl Default for Monitor { | |||
| 37 | let shared = Arc::new(Mutex::new(Shared { | 42 | let shared = Arc::new(Mutex::new(Shared { |
| 38 | latest: None, | 43 | latest: None, |
| 39 | requested: Instant::now(), | 44 | requested: Instant::now(), |
| 45 | + awake: false, | ||
| 46 | + disk: None, | ||
| 40 | })); | 47 | })); |
| 41 | let worker = Arc::downgrade(&shared); | 48 | let worker = Arc::downgrade(&shared); |
| 42 | let _ = thread::Builder::new() | 49 | let _ = thread::Builder::new() |
| @@ -47,6 +54,18 @@ impl Default for Monitor { | |||
| 47 | } | 54 | } |
| 48 | 55 | ||
| 49 | impl Monitor { | 56 | impl Monitor { |
| 57 | + pub fn watch_disk(&self, path: PathBuf) { | ||
| 58 | + if let Ok(mut shared) = self.shared.lock() { | ||
| 59 | + shared.disk = Some(path); | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + | ||
| 63 | + pub fn stay_awake(&self) { | ||
| 64 | + if let Ok(mut shared) = self.shared.lock() { | ||
| 65 | + shared.awake = true; | ||
| 66 | + } | ||
| 67 | + } | ||
| 68 | + | ||
| 50 | pub fn latest(&self) -> Option<Usage> { | 69 | pub fn latest(&self) -> Option<Usage> { |
| 51 | let mut shared = self.shared.lock().ok()?; | 70 | let mut shared = self.shared.lock().ok()?; |
| 52 | shared.requested = Instant::now(); | 71 | shared.requested = Instant::now(); |
| @@ -61,14 +80,21 @@ fn run(shared: std::sync::Weak<Mutex<Shared>>) { | |||
| 61 | let Some(shared) = shared.upgrade() else { | 80 | let Some(shared) = shared.upgrade() else { |
| 62 | return; | 81 | return; |
| 63 | }; | 82 | }; |
| 64 | - let wanted = shared | 83 | + let Some((wanted, disk)) = shared.lock().ok().map(|shared| { |
| 65 | - .lock() | 84 | + ( |
| 66 | - .is_ok_and(|shared| shared.requested.elapsed() < IDLE_AFTER); | 85 | + shared.awake || shared.requested.elapsed() < IDLE_AFTER, |
| 86 | + shared.disk.clone(), | ||
| 87 | + ) | ||
| 88 | + }) else { | ||
| 89 | + return; | ||
| 90 | + }; | ||
| 67 | let usage = if wanted { | 91 | let usage = if wanted { |
| 68 | if sampler.is_none() { | 92 | if sampler.is_none() { |
| 69 | sampler = Sampler::new(); | 93 | sampler = Sampler::new(); |
| 70 | } | 94 | } |
| 71 | - sampler.as_mut().and_then(Sampler::sample) | 95 | + sampler |
| 96 | + .as_mut() | ||
| 97 | + .and_then(|sampler| sampler.sample(disk.as_deref())) | ||
| 72 | } else { | 98 | } else { |
| 73 | sampler = None; | 99 | sampler = None; |
| 74 | None | 100 | None |
| @@ -88,7 +114,6 @@ struct Sampler { | |||
| 88 | cpu_model: Arc<str>, | 114 | cpu_model: Arc<str>, |
| 89 | primed: bool, | 115 | primed: bool, |
| 90 | gpu: GpuSampler, | 116 | gpu: GpuSampler, |
| 91 | - #[cfg(target_os = "linux")] | ||
| 92 | threads: threads::Sampler, | 117 | threads: threads::Sampler, |
| 93 | } | 118 | } |
| 94 | 119 | ||
| @@ -113,12 +138,11 @@ impl Sampler { | |||
| 113 | cpu_model, | 138 | cpu_model, |
| 114 | primed: false, | 139 | primed: false, |
| 115 | gpu: GpuSampler::default(), | 140 | gpu: GpuSampler::default(), |
| 116 | - #[cfg(target_os = "linux")] | ||
| 117 | threads: threads::Sampler::default(), | 141 | threads: threads::Sampler::default(), |
| 118 | }) | 142 | }) |
| 119 | } | 143 | } |
| 120 | 144 | ||
| 121 | - fn sample(&mut self) -> Option<Usage> { | 145 | + fn sample(&mut self, disk: Option<&Path>) -> Option<Usage> { |
| 122 | self.system.refresh_cpu_usage(); | 146 | self.system.refresh_cpu_usage(); |
| 123 | self.system | 147 | self.system |
| 124 | .refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram()); | 148 | .refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram()); |
| @@ -133,10 +157,7 @@ impl Sampler { | |||
| 133 | let process = self.system.process(self.pid)?; | 157 | let process = self.system.process(self.pid)?; |
| 134 | let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; | 158 | let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; |
| 135 | let total = self.system.total_memory(); | 159 | let total = self.system.total_memory(); |
| 136 | - #[cfg(target_os = "linux")] | ||
| 137 | let threads = self.threads.sample(self.cores); | 160 | let threads = self.threads.sample(self.cores); |
| 138 | - #[cfg(not(target_os = "linux"))] | ||
| 139 | - let threads = None; | ||
| 140 | Some(Usage { | 161 | Some(Usage { |
| 141 | host: self.host.clone(), | 162 | host: self.host.clone(), |
| 142 | os: self.os.clone(), | 163 | os: self.os.clone(), |
| @@ -149,6 +170,7 @@ impl Sampler { | |||
| 149 | used_mb: mb(total.saturating_sub(self.system.available_memory())), | 170 | used_mb: mb(total.saturating_sub(self.system.available_memory())), |
| 150 | total_mb: mb(total), | 171 | total_mb: mb(total), |
| 151 | }, | 172 | }, |
| 173 | + storage: disk.and_then(storage), | ||
| 152 | gpu: self.gpu.sample(), | 174 | gpu: self.gpu.sample(), |
| 153 | }) | 175 | }) |
| 154 | } | 176 | } |
| @@ -162,6 +184,8 @@ struct GpuSampler { | |||
| 162 | native: drm::Sampler, | 184 | native: drm::Sampler, |
| 163 | #[cfg(target_os = "windows")] | 185 | #[cfg(target_os = "windows")] |
| 164 | native: windows::Sampler, | 186 | native: windows::Sampler, |
| 187 | + #[cfg(target_os = "macos")] | ||
| 188 | + native: mac::Sampler, | ||
| 165 | } | 189 | } |
| 166 | 190 | ||
| 167 | impl GpuSampler { | 191 | impl GpuSampler { |
| @@ -170,7 +194,12 @@ impl GpuSampler { | |||
| 170 | self.nvidia.sample().or_else(|| self.native.sample()) | 194 | self.nvidia.sample().or_else(|| self.native.sample()) |
| 171 | } | 195 | } |
| 172 | 196 | ||
| 173 | - #[cfg(not(any(target_os = "linux", target_os = "windows")))] | 197 | + #[cfg(target_os = "macos")] |
| 198 | + fn sample(&mut self) -> Option<Gpu> { | ||
| 199 | + self.native.sample() | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] | ||
| 174 | fn sample(&mut self) -> Option<Gpu> { | 203 | fn sample(&mut self) -> Option<Gpu> { |
| 175 | None | 204 | None |
| 176 | } | 205 | } |
| @@ -187,3 +216,17 @@ fn os() -> String { | |||
| 187 | None => name, | 216 | None => name, |
| 188 | } | 217 | } |
| 189 | } | 218 | } |
| 219 | + | ||
| 220 | +fn storage(path: &Path) -> Option<Storage> { | ||
| 221 | + let path = path.ancestors().find_map(|path| path.canonicalize().ok())?; | ||
| 222 | + let disks = sysinfo::Disks::new_with_refreshed_list().ok()?; | ||
| 223 | + let disk = disks | ||
| 224 | + .iter() | ||
| 225 | + .filter(|disk| path.starts_with(disk.mount_point())) | ||
| 226 | + .max_by_key(|disk| disk.mount_point().as_os_str().len())?; | ||
| 227 | + let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; | ||
| 228 | + Some(Storage { | ||
| 229 | + used_mb: mb(disk.total_space().saturating_sub(disk.available_space())), | ||
| 230 | + total_mb: mb(disk.total_space()), | ||
| 231 | + }) | ||
| 232 | +} | ||
crates/usage/src/mac.rsadded+41 -0
| @@ -0,0 +1,41 @@ | |||
| 1 | +use std::process::Command; | ||
| 2 | + | ||
| 3 | +use super::{Gpu, GpuMachine}; | ||
| 4 | + | ||
| 5 | +#[derive(Default)] | ||
| 6 | +pub struct Sampler; | ||
| 7 | + | ||
| 8 | +impl Sampler { | ||
| 9 | + pub fn sample(&mut self) -> Option<Gpu> { | ||
| 10 | + let output = Command::new("ioreg") | ||
| 11 | + .args(["-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"]) | ||
| 12 | + .output() | ||
| 13 | + .ok()?; | ||
| 14 | + let text = String::from_utf8_lossy(&output.stdout); | ||
| 15 | + let number = |key: &str| -> Option<u64> { | ||
| 16 | + let at = text.find(&format!("\"{key}\"="))? + key.len() + 3; | ||
| 17 | + let digits: String = text[at..] | ||
| 18 | + .chars() | ||
| 19 | + .take_while(char::is_ascii_digit) | ||
| 20 | + .collect(); | ||
| 21 | + digits.parse().ok() | ||
| 22 | + }; | ||
| 23 | + let model = text | ||
| 24 | + .find("\"model\" = \"") | ||
| 25 | + .map(|at| at + 11) | ||
| 26 | + .and_then(|at| text[at..].split('"').next()) | ||
| 27 | + .unwrap_or_default() | ||
| 28 | + .to_string(); | ||
| 29 | + let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32; | ||
| 30 | + Some(Gpu { | ||
| 31 | + model, | ||
| 32 | + machine: GpuMachine { | ||
| 33 | + gfx: number("Device Utilization %")? as f32, | ||
| 34 | + video: 0., | ||
| 35 | + vram_used_mb: number("In use system memory").map_or(0, mb), | ||
| 36 | + vram_total_mb: number("Alloc system memory").map_or(0, mb), | ||
| 37 | + }, | ||
| 38 | + ..Gpu::default() | ||
| 39 | + }) | ||
| 40 | + } | ||
| 41 | +} | ||
crates/usage/src/threads.rsmodified+47 -53
| @@ -1,70 +1,64 @@ | |||
| 1 | -use std::{fs, time::Instant}; | 1 | +use std::{ |
| 2 | + collections::HashMap, | ||
| 3 | + sync::{LazyLock, Mutex}, | ||
| 4 | + thread::{self, ThreadId}, | ||
| 5 | + time::{Duration, Instant}, | ||
| 6 | +}; | ||
| 7 | + | ||
| 8 | +use cpu_time::ThreadTime; | ||
| 2 | 9 | ||
| 3 | use super::Threads; | 10 | use super::Threads; |
| 4 | 11 | ||
| 5 | -#[derive(Clone, Copy, Default)] | 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 6 | -struct Ticks { | 13 | +pub enum Group { |
| 7 | - gui: u64, | 14 | + Gui, |
| 8 | - camera: u64, | 15 | + Camera, |
| 9 | - encode: u64, | 16 | + Encode, |
| 10 | - decode: u64, | 17 | + Decode, |
| 18 | +} | ||
| 19 | + | ||
| 20 | +type Spent = [Duration; 4]; | ||
| 21 | + | ||
| 22 | +static SPENT: LazyLock<Mutex<HashMap<ThreadId, (Group, Duration)>>> = | ||
| 23 | + LazyLock::new(Default::default); | ||
| 24 | + | ||
| 25 | +pub fn tick(group: Group) { | ||
| 26 | + let Ok(time) = ThreadTime::try_now() else { | ||
| 27 | + return; | ||
| 28 | + }; | ||
| 29 | + if let Ok(mut spent) = SPENT.lock() { | ||
| 30 | + spent.insert(thread::current().id(), (group, time.as_duration())); | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +fn spent() -> Option<Spent> { | ||
| 35 | + let spent = SPENT.lock().ok()?; | ||
| 36 | + let mut total = Spent::default(); | ||
| 37 | + for (group, time) in spent.values() { | ||
| 38 | + total[*group as usize] += *time; | ||
| 39 | + } | ||
| 40 | + Some(total) | ||
| 11 | } | 41 | } |
| 12 | 42 | ||
| 13 | #[derive(Default)] | 43 | #[derive(Default)] |
| 14 | pub struct Sampler { | 44 | pub struct Sampler { |
| 15 | - previous: Option<(Instant, Ticks)>, | 45 | + previous: Option<(Instant, Spent)>, |
| 16 | } | 46 | } |
| 17 | 47 | ||
| 18 | impl Sampler { | 48 | impl Sampler { |
| 19 | pub fn sample(&mut self, cores: f32) -> Option<Threads> { | 49 | pub fn sample(&mut self, cores: f32) -> Option<Threads> { |
| 20 | - let now = (Instant::now(), Ticks::read()?); | 50 | + let now = (Instant::now(), spent()?); |
| 21 | let (at, then) = self.previous.replace(now)?; | 51 | let (at, then) = self.previous.replace(now)?; |
| 22 | let seconds = now.0.duration_since(at).as_secs_f32().max(f32::EPSILON) * cores; | 52 | let seconds = now.0.duration_since(at).as_secs_f32().max(f32::EPSILON) * cores; |
| 23 | - let cpu = |now: u64, before: u64| now.saturating_sub(before) as f32 / seconds; | 53 | + let cpu = |group: Group| { |
| 24 | - let now = now.1; | 54 | + let index = group as usize; |
| 55 | + now.1[index].saturating_sub(then[index]).as_secs_f32() * 100. / seconds | ||
| 56 | + }; | ||
| 25 | Some(Threads { | 57 | Some(Threads { |
| 26 | - gui: cpu(now.gui, then.gui), | 58 | + gui: cpu(Group::Gui), |
| 27 | - camera: cpu(now.camera, then.camera), | 59 | + camera: cpu(Group::Camera), |
| 28 | - encode: cpu(now.encode, then.encode), | 60 | + encode: cpu(Group::Encode), |
| 29 | - decode: cpu(now.decode, then.decode), | 61 | + decode: cpu(Group::Decode), |
| 30 | }) | 62 | }) |
| 31 | } | 63 | } |
| 32 | } | 64 | } |
| 33 | - | ||
| 34 | -impl Ticks { | ||
| 35 | - fn read() -> Option<Self> { | ||
| 36 | - let pid = std::process::id().to_string(); | ||
| 37 | - let mut ticks = Self::default(); | ||
| 38 | - for entry in fs::read_dir("/proc/self/task").ok()?.flatten() { | ||
| 39 | - let path = entry.path(); | ||
| 40 | - let Ok(name) = fs::read_to_string(path.join("comm")) else { | ||
| 41 | - continue; | ||
| 42 | - }; | ||
| 43 | - let Some(used) = fs::read_to_string(path.join("stat")) | ||
| 44 | - .ok() | ||
| 45 | - .and_then(|stat| stat_ticks(&stat)) | ||
| 46 | - else { | ||
| 47 | - continue; | ||
| 48 | - }; | ||
| 49 | - let name = name.trim(); | ||
| 50 | - if entry.file_name().to_str() == Some(pid.as_str()) { | ||
| 51 | - ticks.gui += used; | ||
| 52 | - } else if name.starts_with("camera") || name.starts_with("share-capture") { | ||
| 53 | - ticks.camera += used; | ||
| 54 | - } else if name == "share-encode" { | ||
| 55 | - ticks.encode += used; | ||
| 56 | - } else if name == "media-decode" || name.contains("video") { | ||
| 57 | - ticks.decode += used; | ||
| 58 | - } | ||
| 59 | - } | ||
| 60 | - Some(ticks) | ||
| 61 | - } | ||
| 62 | -} | ||
| 63 | - | ||
| 64 | -fn stat_ticks(stat: &str) -> Option<u64> { | ||
| 65 | - let rest = stat.get(stat.rfind(')')? + 1..)?; | ||
| 66 | - let fields: Vec<&str> = rest.split_whitespace().collect(); | ||
| 67 | - let utime: u64 = fields.get(11)?.parse().ok()?; | ||
| 68 | - let stime: u64 = fields.get(12)?.parse().ok()?; | ||
| 69 | - Some(utime + stime) | ||
| 70 | -} | ||