forge
Explore
Log in

Don't you dare go Hollow

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 commit

5da5470cabcceac35748eb92d6b12da59f90174eAhmet Kaan GümüşParent: 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
Show full message
✨ 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
crates/client/Cargo.tomlmodified+1 -0
@@ -47,6 +47,7 @@ ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "sc
4747 [target.'cfg(target_os = "windows")'.dependencies]
4848 wasapi = "0.27.0"
4949 windows-capture = "2.0.1"
50+tray-icon = { version = "0.27.0", default-features = false }
5051
5152 [target.'cfg(target_os = "macos")'.dependencies]
5253 coreaudio-rs = "0.14.2"
crates/client/src/gui.rsmodified+1 -0
@@ -1279,6 +1279,7 @@ pub(super) fn new_input(
12791279
12801280 impl Render for Yumush {
12811281 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1282+ crate::usage::tick(crate::usage::Group::Gui);
12821283 let fullscreen = self
12831284 .chat
12841285 .viewer
crates/client/src/gui/chat.rsmodified+7 -1
@@ -536,7 +536,13 @@ impl Chat {
536536 followed: None,
537537 share_loss: HashMap::new(),
538538 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+ },
540546 ringing: HashSet::new(),
541547 ring_task: None,
542548 typing: HashMap::new(),
crates/client/src/gui/voice_stats.rsmodified+16 -1
@@ -277,6 +277,20 @@ fn machine(usage: &Usage, t: Tokens) -> Div {
277277 false,
278278 t,
279279 ))
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+ }))
280294 .children(usage.gpu.as_ref().map(|gpu| {
281295 let machine = gpu.machine;
282296 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 {
462476 fn gb(mb: u32) -> String {
463477 match mb {
464478 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.)),
466481 }
467482 }
468483
crates/client/src/lib.rsmodified+5 -2
@@ -18,11 +18,14 @@ pub mod voice;
1818
1919 pub const NAME: &str = "Yumush";
2020
21-fn config_file(name: &str) -> Option<PathBuf> {
21+pub fn config_dir() -> Option<PathBuf> {
2222 std::env::var_os("YUMUSH_CONFIG_DIR")
2323 .map(PathBuf::from)
2424 .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))
2629 }
2730
2831 pub fn read_config(name: &str) -> Option<String> {
crates/client/src/main.rsmodified+1 -1
@@ -42,7 +42,6 @@ fn main() {
4242
4343 let settings = settings::load();
4444 let (network_handle, network_event_receiver) = net::start(ClientConfig::default());
45- let (mut tray_receiver, tray_handle) = tray::start();
4645
4746 application()
4847 .with_assets(AllAssets)
@@ -61,6 +60,7 @@ fn main() {
6160 return;
6261 };
6362
63+ let (mut tray_receiver, tray_handle) = tray::start();
6464 let mut tray_state = TrayState::default();
6565 cx.observe(&view, move |view, cx| {
6666 let state = view.read(cx).tray_state();
crates/client/src/media/decode.rsmodified+2 -0
@@ -217,6 +217,7 @@ impl VideoDecoder {
217217 }
218218
219219 pub fn decode(&mut self, data: &[u8], timestamp_ms: u32) -> Vec<Picture> {
220+ crate::usage::tick(crate::usage::Group::Decode);
220221 let mut packet = Packet::new(0, TimeBase::MILLIS, data);
221222 packet.pts = Some(i64::from(timestamp_ms));
222223 self.send(&packet)
@@ -646,6 +647,7 @@ impl Worker {
646647 }
647648
648649 fn decode_backlog(&mut self) -> bool {
650+ crate::usage::tick(crate::usage::Group::Decode);
649651 let Some((_, video)) = self.video.as_mut() else {
650652 return false;
651653 };
crates/client/src/net/link.rsmodified+5 -3
@@ -252,9 +252,11 @@ pub(super) async fn call<C: Call>(
252252 connection: &quinn::Connection,
253253 call: C,
254254 ) -> Result<C::Reply, Fail> {
255- Ok(exchange(connection, &Open::Call(call.into_request()))
256- .await?
257- .0)
255+ Ok(
256+ exchange(connection, &Open::Call(Box::new(call.into_request())))
257+ .await?
258+ .0,
259+ )
258260 }
259261
260262 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(
227227 let mut failures = 0;
228228 let mut due = 0u32;
229229 while !stop.load(Ordering::Relaxed) {
230+ crate::usage::tick(crate::usage::Group::Camera);
230231 let buffer = match camera.frame() {
231232 Ok(buffer) => buffer,
232233 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
484484 }
485485
486486 fn on_process(stream: &pw::stream::Stream, state: &mut State) {
487+ crate::usage::tick(crate::usage::Group::Camera);
487488 let (width, height) = state.size;
488489 if width == 0 || height == 0 {
489490 return;
crates/client/src/share/capture_windows.rsmodified+1 -0
@@ -107,6 +107,7 @@ impl GraphicsCaptureApiHandler for Handler {
107107 frame: &mut CaptureFrame,
108108 _: InternalCaptureControl,
109109 ) -> Result<(), Self::Error> {
110+ crate::usage::tick(crate::usage::Group::Camera);
110111 let (width, height) = (frame.width(), frame.height());
111112 let mut buffer = frame.buffer().map_err(text)?;
112113 let pitch = buffer.row_pitch() as usize;
crates/client/src/share/encode.rsmodified+1 -0
@@ -377,6 +377,7 @@ fn run(
377377 let interval = 1000 / settings.fps;
378378 let mut due = 0u32;
379379 for frame in input {
380+ crate::usage::tick(crate::usage::Group::Encode);
380381 if frame.timestamp_ms + SLACK_MS < due {
381382 continue;
382383 }
crates/client/src/share/fake.rsmodified+1 -0
@@ -45,6 +45,7 @@ pub fn start(spec: &str) -> (u32, u32, u32, Receiver<Frame>, Generator) {
4545 let noisy = std::env::var_os("YUMUSH_TEST_NOISE").is_some();
4646 let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;
4747 while !stop.load(Ordering::Relaxed) {
48+ crate::usage::tick(crate::usage::Group::Camera);
4849 let bar = (number as usize * 8) % width as usize;
4950 let mut bgra = vec![40u8; (width * height) as usize * BYTES_PER_PIXEL];
5051 if noisy {
crates/client/src/tray.rsmodified+161 -75
@@ -1,6 +1,4 @@
1-use tokio::sync::mpsc;
2-
3-pub const AVAILABLE: bool = cfg!(target_os = "linux");
1+pub const AVAILABLE: bool = cfg!(any(target_os = "linux", target_os = "windows"));
42
53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
64 pub enum TrayAction {
@@ -14,50 +12,107 @@ pub struct TrayState {
1412 pub mentions: u32,
1513 }
1614
17-#[derive(Clone)]
18-pub struct TrayHandle(mpsc::UnboundedSender<TrayState>);
15+pub struct TrayHandle(Box<dyn Fn(TrayState)>);
1916
2017 impl TrayHandle {
2118 pub fn set(&self, state: TrayState) {
22- let _ = self.0.send(state);
19+ (self.0)(state);
2320 }
2421 }
2522
2623 #[cfg(target_os = "linux")]
2724 pub use linux::start;
25+#[cfg(target_os = "windows")]
26+pub use windows::start;
2827
29-#[cfg(not(target_os = "linux"))]
30-pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) {
28+#[cfg(not(any(target_os = "linux", target_os = "windows")))]
29+pub fn start() -> (tokio::sync::mpsc::UnboundedReceiver<TrayAction>, TrayHandle) {
3130 (
32- mpsc::unbounded_channel().1,
33- TrayHandle(mpsc::unbounded_channel().0),
31+ tokio::sync::mpsc::unbounded_channel().1,
32+ TrayHandle(Box::new(|_| {})),
3433 )
3534 }
3635
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+
37109 #[cfg(target_os = "linux")]
38110 mod linux {
39111 use ksni::TrayMethods;
40112 use tokio::sync::mpsc;
41113 use tracing::warn;
42114
43- use super::{TrayAction, TrayHandle, TrayState};
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- }
115+ use super::{Badge, ICON_SIZE, TrayAction, TrayHandle, TrayState, pixels};
61116
62117 pub fn start() -> (mpsc::UnboundedReceiver<TrayAction>, TrayHandle) {
63118 let (sender, receiver) = mpsc::unbounded_channel();
@@ -93,7 +148,12 @@ mod linux {
93148 });
94149 });
95150
96- (receiver, TrayHandle(state_sender))
151+ (
152+ receiver,
153+ TrayHandle(Box::new(move |state| {
154+ let _ = state_sender.send(state);
155+ })),
156+ )
97157 }
98158
99159 struct Tray {
@@ -122,16 +182,8 @@ mod linux {
122182 }
123183
124184 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- };
132185 ksni::ToolTip {
133- title: crate::NAME.to_string(),
134- description,
186+ title: self.state.tip(),
135187 ..Default::default()
136188 }
137189 }
@@ -164,47 +216,81 @@ mod linux {
164216 }
165217 }
166218
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-
179219 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-
204220 ksni::Icon {
205221 width: ICON_SIZE,
206222 height: ICON_SIZE,
207- data,
223+ data: pixels(badge)
224+ .flat_map(|([red, green, blue], alpha)| [alpha, red, green, blue])
225+ .collect(),
208226 }
209227 }
210228 }
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};
44
55 #[derive(Debug, Clone, Encode, Decode)]
66 pub enum Open {
7- Call(Request),
7+ Call(Box<Request>),
88 Upload(Upload),
99 Fetch(Blob),
1010 }
crates/common/src/stats.rsmodified+7 -0
@@ -38,9 +38,16 @@ pub struct Usage {
3838 pub total: f32,
3939 pub threads: Option<Threads>,
4040 pub memory: Memory,
41+ pub storage: Option<Storage>,
4142 pub gpu: Option<Gpu>,
4243 }
4344
45+#[derive(Debug, Clone, Copy, Default, Encode, Decode)]
46+pub struct Storage {
47+ pub used_mb: u32,
48+ pub total_mb: u32,
49+}
50+
4451 #[derive(Debug, Clone, Copy, Default, Encode, Decode)]
4552 pub struct Threads {
4653 pub gui: f32,
crates/server/src/network.rsmodified+2 -1
@@ -77,6 +77,7 @@ pub async fn serve(
7777 directory,
7878 backups,
7979 };
80+ shared.services.machine.watch(shared.directory.clone());
8081
8182 tokio::spawn(retention::collect(shared.clone()));
8283
@@ -309,7 +310,7 @@ async fn route(
309310 let send_stream = Sending::new(send_stream);
310311 let open: Open = frame::read(&mut receive_stream, UP_MAX).await?;
311312 match open {
312- Open::Call(request) => answer(client, request, send_stream, shared).await,
313+ Open::Call(request) => answer(client, *request, send_stream, shared).await,
313314 Open::Upload(upload) => {
314315 let user = signed_user(&client, &shared).await?;
315316 files::upload(
crates/server/src/stats.rsmodified+6 -0
@@ -1,3 +1,4 @@
1+use std::path::PathBuf;
12 use std::{
23 collections::{HashMap, VecDeque},
34 sync::{Arc, Mutex},
@@ -83,6 +84,11 @@ pub struct Machine {
8384 }
8485
8586 impl Machine {
87+ pub fn watch(&self, directory: PathBuf) {
88+ self.monitor.watch_disk(directory);
89+ self.monitor.stay_awake();
90+ }
91+
8692 pub fn sample(&self, (sent, received): (u64, u64)) -> Stats {
8793 let now = Instant::now();
8894 let mut rates = self.rates.lock().unwrap();
crates/usage/Cargo.tomlmodified+2 -1
@@ -5,7 +5,8 @@ edition = "2024"
55
66 [dependencies]
77 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"] }
910
1011 [target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies]
1112 nvml-wrapper = "0.13.0"
crates/usage/src/lib.rsmodified+56 -13
@@ -1,4 +1,5 @@
11 use std::{
2+ path::{Path, PathBuf},
23 sync::{Arc, Mutex},
34 thread,
45 time::{Duration, Instant},
@@ -11,9 +12,10 @@ use sysinfo::{
1112
1213 #[cfg(target_os = "linux")]
1314 mod drm;
15+#[cfg(target_os = "macos")]
16+mod mac;
1417 #[cfg(any(target_os = "linux", target_os = "windows"))]
1518 mod nvidia;
16-#[cfg(target_os = "linux")]
1719 mod threads;
1820 #[cfg(target_os = "windows")]
1921 mod windows;
@@ -21,11 +23,14 @@ mod windows;
2123 const INTERVAL: Duration = Duration::from_secs(1);
2224 const IDLE_AFTER: Duration = Duration::from_secs(3);
2325
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};
2528
2629 struct Shared {
2730 latest: Option<Usage>,
2831 requested: Instant,
32+ awake: bool,
33+ disk: Option<PathBuf>,
2934 }
3035
3136 pub struct Monitor {
@@ -37,6 +42,8 @@ impl Default for Monitor {
3742 let shared = Arc::new(Mutex::new(Shared {
3843 latest: None,
3944 requested: Instant::now(),
45+ awake: false,
46+ disk: None,
4047 }));
4148 let worker = Arc::downgrade(&shared);
4249 let _ = thread::Builder::new()
@@ -47,6 +54,18 @@ impl Default for Monitor {
4754 }
4855
4956 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+
5069 pub fn latest(&self) -> Option<Usage> {
5170 let mut shared = self.shared.lock().ok()?;
5271 shared.requested = Instant::now();
@@ -61,14 +80,21 @@ fn run(shared: std::sync::Weak<Mutex<Shared>>) {
6180 let Some(shared) = shared.upgrade() else {
6281 return;
6382 };
64- let wanted = shared
65- .lock()
66- .is_ok_and(|shared| shared.requested.elapsed() < IDLE_AFTER);
83+ let Some((wanted, disk)) = shared.lock().ok().map(|shared| {
84+ (
85+ shared.awake || shared.requested.elapsed() < IDLE_AFTER,
86+ shared.disk.clone(),
87+ )
88+ }) else {
89+ return;
90+ };
6791 let usage = if wanted {
6892 if sampler.is_none() {
6993 sampler = Sampler::new();
7094 }
71- sampler.as_mut().and_then(Sampler::sample)
95+ sampler
96+ .as_mut()
97+ .and_then(|sampler| sampler.sample(disk.as_deref()))
7298 } else {
7399 sampler = None;
74100 None
@@ -88,7 +114,6 @@ struct Sampler {
88114 cpu_model: Arc<str>,
89115 primed: bool,
90116 gpu: GpuSampler,
91- #[cfg(target_os = "linux")]
92117 threads: threads::Sampler,
93118 }
94119
@@ -113,12 +138,11 @@ impl Sampler {
113138 cpu_model,
114139 primed: false,
115140 gpu: GpuSampler::default(),
116- #[cfg(target_os = "linux")]
117141 threads: threads::Sampler::default(),
118142 })
119143 }
120144
121- fn sample(&mut self) -> Option<Usage> {
145+ fn sample(&mut self, disk: Option<&Path>) -> Option<Usage> {
122146 self.system.refresh_cpu_usage();
123147 self.system
124148 .refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
@@ -133,10 +157,7 @@ impl Sampler {
133157 let process = self.system.process(self.pid)?;
134158 let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32;
135159 let total = self.system.total_memory();
136- #[cfg(target_os = "linux")]
137160 let threads = self.threads.sample(self.cores);
138- #[cfg(not(target_os = "linux"))]
139- let threads = None;
140161 Some(Usage {
141162 host: self.host.clone(),
142163 os: self.os.clone(),
@@ -149,6 +170,7 @@ impl Sampler {
149170 used_mb: mb(total.saturating_sub(self.system.available_memory())),
150171 total_mb: mb(total),
151172 },
173+ storage: disk.and_then(storage),
152174 gpu: self.gpu.sample(),
153175 })
154176 }
@@ -162,6 +184,8 @@ struct GpuSampler {
162184 native: drm::Sampler,
163185 #[cfg(target_os = "windows")]
164186 native: windows::Sampler,
187+ #[cfg(target_os = "macos")]
188+ native: mac::Sampler,
165189 }
166190
167191 impl GpuSampler {
@@ -170,7 +194,12 @@ impl GpuSampler {
170194 self.nvidia.sample().or_else(|| self.native.sample())
171195 }
172196
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")))]
174203 fn sample(&mut self) -> Option<Gpu> {
175204 None
176205 }
@@ -187,3 +216,17 @@ fn os() -> String {
187216 None => name,
188217 }
189218 }
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;
29
310 use super::Threads;
411
5-#[derive(Clone, Copy, Default)]
6-struct Ticks {
7- gui: u64,
8- camera: u64,
9- encode: u64,
10- decode: u64,
12+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13+pub enum Group {
14+ Gui,
15+ Camera,
16+ Encode,
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)
1141 }
1242
1343 #[derive(Default)]
1444 pub struct Sampler {
15- previous: Option<(Instant, Ticks)>,
45+ previous: Option<(Instant, Spent)>,
1646 }
1747
1848 impl Sampler {
1949 pub fn sample(&mut self, cores: f32) -> Option<Threads> {
20- let now = (Instant::now(), Ticks::read()?);
50+ let now = (Instant::now(), spent()?);
2151 let (at, then) = self.previous.replace(now)?;
2252 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;
24- let now = now.1;
53+ let cpu = |group: Group| {
54+ let index = group as usize;
55+ now.1[index].saturating_sub(then[index]).as_secs_f32() * 100. / seconds
56+ };
2557 Some(Threads {
26- gui: cpu(now.gui, then.gui),
27- camera: cpu(now.camera, then.camera),
28- encode: cpu(now.encode, then.encode),
29- decode: cpu(now.decode, then.decode),
58+ gui: cpu(Group::Gui),
59+ camera: cpu(Group::Camera),
60+ encode: cpu(Group::Encode),
61+ decode: cpu(Group::Decode),
3062 })
3163 }
3264 }
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-}