From 2b3dec53730390ce5760ee89ac84529cf5460073 Mon Sep 17 00:00:00 2001 From: rajhansgithub Date: Thu, 3 Dec 2026 00:38:54 +0530 Subject: [PATCH 1/2] 2.35.0: every metric in hover popup, scrolls --- .github/workflows/build.yml | 19 + Cargo.lock | 2 +- Cargo.toml | 2 +- res/resmon.manifest | 2 +- setup.iss | 2 +- src/app.rs | 29 +- src/main.rs | 1 + src/monitor.rs | 171 ++++-- src/monitor/addonpage.rs | 35 +- src/monitor/btpage.rs | 26 +- src/monitor/devpage.rs | 278 +++++++--- src/monitor/hover.rs | 1014 +++++++++++++++++++++++++++++++++++ src/popup.rs | 419 +++++++++++++-- src/scroll.rs | 190 +++++++ src/sensors/deep/live.rs | 228 ++++---- src/sensors/deep/mod.rs | 80 ++- src/sensors/detail.rs | 2 + src/sensors/mod.rs | 11 +- src/sensors/net.rs | 2 + src/settings.rs | 103 +++- src/settings_ui.rs | 107 ++-- src/vsync.rs | 26 +- 22 files changed, 2394 insertions(+), 355 deletions(-) create mode 100644 src/monitor/hover.rs create mode 100644 src/scroll.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 25f009c..00bd3ef 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -390,6 +390,7 @@ jobs: } "@ Add-Type -AssemblyName System.Windows.Forms, System.Drawing + $env:RESMON_PERF = "1" $p = Start-Process target/release/ResourceMonitor.exe -PassThru Start-Sleep -Seconds 12 # A second launch asks the running app to show the panel, pinned. @@ -423,8 +424,26 @@ jobs: Start-Sleep -Seconds 6 Grab "target/popup-shots/popup-light.png" if ($ov -ne [IntPtr]::Zero) { Grab "target/popup-shots/widget-both.png" $ov } + # More picked than the screen is tall: the panel stops at the work area and scrolls. + $more = "counts", "sec|cpu", "sec|memory", "sec|disks", "sec|network", "sec|pc", "chart|cpu", "part|memory", "card|cpu|cores", "card|cpu|power", "card|memory|commit", "fact|cpu|power|DPC", + "fact|memory|commit|HARD FAULTS", "drive|drive:C", "chart|drive:C", "card|drive:C|drive-facts", "card|net|adapters-list", "card|net|connection", "addon|usb", "bt|{not-here}" + Add-Content "$dir/settings.ini" "`ntheme = dark`naddon_usb = 1`nhover_more = $($more -join ', ')`n" + Start-Sleep -Seconds 8 + Grab "target/popup-shots/popup-more.png" + [void][W4]::GetWindowRect($h, [ref]$r) + $wa = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea + Write-Host "panel $($r.L),$($r.T) - $($r.Rt),$($r.B); work area $($wa.Left),$($wa.Top) - $($wa.Right),$($wa.Bottom)" + if ($r.T -lt $wa.Top -or $r.B -gt $wa.Bottom) { Write-Error "panel leaves the work area"; exit 1 } + if (($r.B - $r.T) -lt ($wa.Height - 60)) { Write-Error "panel did not fill the work area"; exit 1 } + [void][W4]::SetCursorPos($r.L + 200, $r.T + 300); Start-Sleep -Milliseconds 300 + for ($i = 0; $i -lt 60; $i++) { [W4]::mouse_event(0x0800, 0, 0, [uint32]4294967176, [UIntPtr]::Zero); Start-Sleep -Milliseconds 80 } + Start-Sleep -Seconds 2 + Grab "target/popup-shots/popup-more-end.png" + $a = (Get-FileHash target/popup-shots/popup-more.png).Hash; $b = (Get-FileHash target/popup-shots/popup-more-end.png).Hash + if ($a -eq $b) { Write-Error "the panel did not scroll"; exit 1 } } $log = "$dir/diagnostics.log" + if (Test-Path $log) { Select-String -Path $log -Pattern "perf popup" | Select-Object -Last 8 | ForEach-Object { $_.Line } } if (Test-Path $log) { Get-Content $log -Tail 30 } if ($p.HasExited) { Write-Error "app exited early (code $($p.ExitCode))"; exit 1 } Stop-Process -Id $p.Id diff --git a/Cargo.lock b/Cargo.lock index 0d9a2aa..a91f90d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -92,7 +92,7 @@ dependencies = [ [[package]] name = "resmon" -version = "2.34.0" +version = "2.35.0" dependencies = [ "embed-resource", "windows", diff --git a/Cargo.toml b/Cargo.toml index 7e406f8..076f9bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "resmon" -version = "2.34.0" +version = "2.35.0" edition = "2021" authors = ["Emulsion Labs"] description = "Ultra-light taskbar resource monitor for Windows 10/11" diff --git a/res/resmon.manifest b/res/resmon.manifest index 632d0b0..265b385 100644 --- a/res/resmon.manifest +++ b/res/resmon.manifest @@ -1,6 +1,6 @@ - + diff --git a/setup.iss b/setup.iss index c26d907..eaf4504 100644 --- a/setup.iss +++ b/setup.iss @@ -1,6 +1,6 @@ ; Inno Setup script. Build the exe first: cargo build --release #define MyAppName "Resource Monitor" -#define MyAppVersion "2.34.0" +#define MyAppVersion "2.35.0" #define MyAppPublisher "Emulsion Labs" #define MyAppURL "https://github.com/rajhansgithub/Windows_Resource_Monitoring_Tool" #define MyAppExeName "ResourceMonitor.exe" diff --git a/src/app.rs b/src/app.rs index 033d219..122536a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -415,6 +415,15 @@ pub struct App { pub popup_dark: bool, /// A WM_MOUSELEAVE for the details panel is pending. pub popup_tracking: bool, + /// Items picked on the Monitor pages, as the popup draws them (None = none picked). + pub popup_board: Option>, + pub popup_scroll: crate::scroll::Scroll, + /// The popup's scroll animates (its frame clock runs). + pub popup_scrolling: bool, + /// Scroll offset of the popup's last painted frame. + pub popup_drawn: i32, + /// Dragging the popup's scroll bar: where the thumb was grabbed. + pub popup_drag: Option, } impl Deref for App { @@ -552,6 +561,11 @@ pub fn create(hinst: HINSTANCE, after_update: bool) -> Option<()> { popup_acrylic: false, popup_dark: true, popup_tracking: false, + popup_board: None, + popup_scroll: Default::default(), + popup_scrolling: false, + popup_drawn: 0, + popup_drag: None, icons: None, alerts: AlertState::default(), ach: crate::achievements::observer::Observer::new(), @@ -790,6 +804,9 @@ impl App { fn opts(&self) -> SampleOpts { let sh = |m| self.m.s.shown(m); + // Items picked for the hover window are read while it is open (or about to open). + let page = crate::settings_ui::monitor_warm(); + let hover = if self.detail_warm() { crate::monitor::hover::needs(&self.m.s.hover_more, self.popup_board.as_ref().and_then(|b| b.screen)) } else { Default::default() }; SampleOpts { adapter: (!self.m.s.adapter.is_empty()).then(|| self.m.s.adapter.clone()), // GPU engine counters are the only costly source: query them only when needed. @@ -802,7 +819,9 @@ impl App { procs: sh(Metric::TopProc) || self.detail_warm() || self.ins.wants_procs(), // The Monitor page is on screen, or was within the last minute: it stays warm so // coming back shows live numbers and unbroken charts at once (no extra timer). - detail: crate::settings_ui::monitor_warm(), + detail: page || hover.detail, + hover_only: !page, + hover, dev: crate::settings_ui::monitor_dev(), bt: self.m.s.mod_bluetooth, addons: self.m.s.addons_on(), @@ -819,8 +838,11 @@ impl App { self.detail_until = Some(Instant::now() + std::time::Duration::from_secs(30)); if cold { // Take a baseline now so rates/percentages exist on the next tick. + // Picked items need numbers as it opens: a real sample (new counters prime + // themselves on the sensor thread). let opts = self.opts(); - self.sensors.request(opts, true); + let real = opts.hover.detail; + self.sensors.request(opts, !real); } } @@ -911,6 +933,9 @@ impl App { } m.snap = snap; m.samples += 1; + if opts.detail && self.detail_warm() && !self.m.s.hover_more.is_empty() { + popup::update(self, true); + } if self.last_save.elapsed().as_secs() >= 60 { self.m.usage.save(); diff --git a/src/main.rs b/src/main.rs index 56a5c38..b2d98c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -26,6 +26,7 @@ mod perf; mod popup; mod render; mod report; +mod scroll; mod sensors; mod settings; mod settings_ui; diff --git a/src/monitor.rs b/src/monitor.rs index c72fb3e..a2ff718 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -26,6 +26,7 @@ mod addonpage; pub(crate) use addonpage::mic_glyph; mod btpage; mod devpage; +pub mod hover; mod speedpage; pub use crate::sensors::deep::Dev; @@ -110,6 +111,10 @@ pub enum Hit { IconPick(u8), /// "Show in hover" button: puts item `settings::HOVER_*` in the tray hover window or takes it out. HoverPin(u8), + /// "Show in hover" button of any other item (`hover::name` is its id). + HoverItem(u32), + /// The same on one fact of a card. + HoverFact(u32), /// Add-ons page: open / close this add-on's tile (`addons::Addon::idx`). AddonOpen(u8), /// Add-ons page: this add-on's on / off switch. @@ -391,12 +396,33 @@ pub struct Monitor { pub icons: bool, /// What the tray hover window shows (`Settings::hover_items`, from the settings each tick). pub hover: u8, + /// Everything else it shows (`Settings::hover_more`, as `hover::intern` numbers). + pub hover_more: HashSet, + /// Facts with a "show in hover" button: where they are, and their id. + fact_tiles: Vec<(Rect, u32)>, + /// This one draws the hover window's items: no buttons, no "click for" hints. + in_hover: bool, /// Icon picks from the settings: memory, GPU, disk, Ethernet style, Wi-Fi style. pub icon_picks: [u8; 6], /// Moving parts of the icons, stepped by the host each frame. pub ianim: liticon::Anim, } +/// 14 days of data usage (received, sent), oldest first, and this month's total. +fn usage_days(a: &App) -> (Vec<(u64, u64)>, u64) { + let mut k = usage::today(); + let (yy, mm, _) = usage::ymd(k); + let month = a.m.usage.month(yy, mm).total(); + let mut days = Vec::with_capacity(14); + for _ in 0..14 { + let u = a.m.usage.get(k); + days.push((u.recv, u.sent)); + k = usage::prev_day(k); + } + days.reverse(); + (days, month) +} + impl Monitor { pub fn new() -> Monitor { Monitor { @@ -462,6 +488,9 @@ impl Monitor { speed: false, icons: false, hover: crate::settings::HOVER_ALL, + hover_more: HashSet::new(), + fact_tiles: Vec::new(), + in_hover: false, icon_picks: [0; 6], ianim: liticon::Anim::default(), } @@ -545,6 +574,7 @@ impl Monitor { self.icons = a.m.s.tile_icons || *FORCE.get_or_init(|| std::env::var("RESMON_TILES").is_ok_and(|v| v == "icons")); self.icon_picks = [a.m.s.icon_mem, a.m.s.icon_gpu, a.m.s.icon_disk, a.m.s.icon_eth, a.m.s.icon_wifi, a.m.s.icon_net]; self.hover = a.m.s.hover_items; + self.set_hover_more(&a.m.s.hover_more); if !self.bt_on && self.view == Some(Dev::Bluetooth) { self.close_dev(); } @@ -567,18 +597,7 @@ impl Monitor { push_detail(&mut self.cores, &mut self.kern, &mut self.engines, &mut self.disks, &mut self.nets, &self.det); } - // 14 days of data usage, oldest first. - let mut k = usage::today(); - let (yy, mm, _) = usage::ymd(k); - self.month = a.m.usage.month(yy, mm).total(); - let mut days = Vec::with_capacity(14); - for _ in 0..14 { - let u = a.m.usage.get(k); - days.push((u.recv, u.sent)); - k = usage::prev_day(k); - } - days.reverse(); - self.days = days; + (self.days, self.month) = usage_days(a); if !self.grouped_init { self.grouped_init = true; @@ -835,6 +854,20 @@ impl Monitor { v } + /// Tiles of a key/value grid (see `Draw::kv_grid`). + fn kv_rects(&self, l: i32, t: i32, w: i32, cols: i32, n: usize) -> Vec { + let g = self.sc(8); + let tw = (w - g * (cols - 1)) / cols; + let th = self.sc(48); + (0..n as i32) + .map(|i| { + let (cx, cy) = (i % cols, i / cols); + let x = l + cx * (tw + g); + Rect { l: x, t: t + cy * (th + g), r: if cx == cols - 1 { l + w } else { x + tw }, b: t + cy * (th + g) + th } + }) + .collect() + } + fn sys_cols(&self, w: i32) -> i32 { (w / self.sc(200)).clamp(1, 4) } @@ -960,6 +993,7 @@ impl Monitor { self.vits.clear(); self.boxes.clear(); self.hits.clear(); + self.fact_tiles.clear(); if self.speed { self.anim = None; return self.speed_layout(l, r, y0); @@ -990,6 +1024,9 @@ impl Monitor { self.hits.push((seg, Hit::TileStyle(on))); x += tw; } + // "Show in hover" for the chips (up time, processes, threads, handles). + let pr = range_l - self.sc(12) - tw * 2 - self.sc(10); + self.pin(hover::Item::Counts, pr, y + self.sc(2)); y += sh + gap; // Vitals. @@ -1242,7 +1279,7 @@ impl Monitor { match v { Vit::Cpu => HOVER_CPU, Vit::Mem => HOVER_MEM, - Vit::Gpu | Vit::Vram => HOVER_GPU, + Vit::Gpu | Vit::Vram => HOVER_GPU, // the VRAM tile has an item of its own (`push_pin`) Vit::Disk => HOVER_DISK, Vit::Net => HOVER_NET, Vit::Bat => HOVER_BAT, @@ -1253,6 +1290,9 @@ impl Monitor { fn push_pin(&mut self, tile: Rect, right: i32, v: Vit) { let b = self.sc(24); let t = tile.t + self.sc(6); + if v == Vit::Vram { + return self.pin(hover::Item::Vram, right, t); + } self.hits.push((Rect { l: right - b, t, r: right, b: t + b }, Hit::HoverPin(Self::vit_hover(v)))); } @@ -1384,6 +1424,10 @@ impl Monitor { fn section_hits(&mut self, sec: Sec, r: Rect) { let head = self.sc(14 + 20 + 12); + // "Show in hover" first: it wins over what is under it. + if sec != Sec::Procs { + self.pin_card(hover::Item::Sec(sec), r); + } match sec { Sec::Cpu => self.hits.push((r, Hit::Open(Dev::Cpu))), Sec::Mem => self.hits.push((r, Hit::Open(Dev::Mem))), @@ -1392,6 +1436,9 @@ impl Monitor { // "Show in hover" for data usage, right of the 14-day bars (see `nets`). let on = self.det.adapters.iter().filter(|a| a.connected).count(); let off = if on < self.det.adapters.len() { self.sc(26) } else { 0 }; + for i in 0..on { + self.pin(hover::Item::Net(i), r.r - self.sc(12), r.t + head + i as i32 * self.sc(84)); + } let t = r.t + head + on.max(1) as i32 * self.sc(84) + off + self.sc(24); let b = self.sc(24); self.hits.push((Rect { l: r.r - self.sc(12) - b, t, r: r.r - self.sc(12), b: t + b }, Hit::HoverPin(crate::settings::HOVER_USAGE))); @@ -1405,6 +1452,7 @@ impl Monitor { for n in rows { let rh = self.sc(84); if n != u32::MAX { + self.pin(hover::Item::Drive(n), r.r - self.sc(12), y); self.hits.push((Rect { l: r.l + self.sc(8), t: y, r: r.r - self.sc(8), b: y + rh }, Hit::Open(Dev::Disk(n)))); } y += rh; @@ -1422,6 +1470,7 @@ impl Monitor { let (dl, dt) = if iw >= self.sc(640) { ((l + rr) / 2 + self.sc(14), top) } else { (l, top + self.dimm_h(self.sys_mem_w(iw)) + self.sc(16)) }; let mut y = dt + self.sc(20); for i in 0..screens { + self.pin(hover::Item::Screen(i as u32), r.r - self.sc(12), y + self.sc(6)); self.hits.push((Rect { l: dl, t: y, r: r.r - self.sc(16), b: y + self.sc(44) }, Hit::Open(Dev::Display(i as u32)))); y += self.sc(44); } @@ -1503,6 +1552,7 @@ impl Monitor { let sy = self.y0 + dy; if sy + s(28) >= vt && sy <= vb { d.strip(cv, sy); + d.pins(cv, Rect { l: self.l, t: sy, r: self.r, b: sy + s(28) }); } for (v, r) in &self.vits { let r = self.cur(Key::Vit(*v), *r); @@ -1658,13 +1708,24 @@ impl Draw<'_> { /// Filled with the accent when the item is in the hover window, an outline when not. fn pins(&self, cv: &mut Canvas, area: Rect) { for (i, (hr, h)) in self.m.hits.iter().enumerate() { - let Hit::HoverPin(item) = *h else { continue }; + let on = match *h { + Hit::HoverPin(item) => self.m.hover & (1 << item) != 0, + Hit::HoverItem(id) | Hit::HoverFact(id) => self.m.hover_more.contains(&id), + _ => continue, + }; let b = self.sh(*hr); if !area.contains(b.l, b.t) { continue; } - let on = self.m.hover & (1 << item) != 0; let hot = self.hot == Some(i); + if let Hit::HoverFact(_) = h { + // A fact's button: there while the pointer is on the fact, or once picked. + let over = self.m.dp.hover.is_some_and(|(x, y)| self.m.fact_tiles.iter().any(|(t, _)| t.contains(hr.l, hr.t) && t.contains(x, y))); + if !(on || hot || over) { + continue; + } + cv.fill_round(b, self.sf(6.0), crate::look::over(self.sub, crate::look::over(self.col.card, crate::look::tokens(self.dark()).panel))); + } if hot { cv.fill_round(b, b.h() as f32 / 2.0, self.col.fg.with_a(if self.dark() { 30 } else { 22 })); } @@ -1703,6 +1764,15 @@ impl Draw<'_> { } } + /// Room the "show in hover" button takes at a card's top right. + fn pin_w(&self) -> i32 { + if self.m.in_hover { + 0 + } else { + self.s(28) + } + } + /// Small uppercase label. fn cap(&self, cv: &mut Canvas, s: &str, x: i32, y: i32) { cv.text(self.f.tiny, s, x, y, self.col.dim); @@ -1711,6 +1781,7 @@ impl Draw<'_> { /// Section title + dim subtitle; returns the y below the header. fn header(&self, cv: &mut Canvas, r: Rect, title: &str, sub: &str, right_w: i32) -> i32 { let (x, y) = (r.l + self.s(16), r.t + self.s(14)); + let right_w = right_w + self.pin_w(); let title = cv.ellipsize(self.f.semi, title, r.r - self.s(16) - right_w - x); let tw = cv.text(self.f.semi, &title, x, y, self.col.fg); let tw = tw.max(cv.measure(self.f.semi, &title).0); @@ -1739,7 +1810,8 @@ impl Draw<'_> { let (tw, th) = cv.measure(self.f.small, text); let h = self.s(20); let w = tw + self.s(if dot { 26 } else { 16 }); - let pr = Rect { l: r.r - self.s(16) - w, t: r.t + self.s(14), r: r.r - self.s(16), b: r.t + self.s(14) + h }; + let right = r.r - self.s(16) - self.pin_w(); + let pr = Rect { l: right - w, t: r.t + self.s(14), r: right, b: r.t + self.s(14) + h }; let mut tint = c.with_a(if self.dark() { 40 } else { 32 }); if self.look_chip(cv, pr, false, false).is_some() { // The look's own chip ground: the tone stays in the dot and the (legible) text. @@ -1814,7 +1886,10 @@ impl Draw<'_> { /// Key/value tile. fn kv(&self, cv: &mut Canvas, r: Rect, k: &str, v: &str) { cv.fill_round(r, self.sf(6.0), self.sub); - let room = r.w() - self.s(20); + let full = r.w() - self.s(20); + // A picked fact's button sits at the right of its label. + let picked = self.m.fact_tiles.iter().any(|(t, id)| t.l == r.l && t.t + self.dy == r.t && self.m.hover_more.contains(id)); + let room = if picked { full - self.s(18) } else { full }; // A key too wide for the tile closes up ("CORES / THREADS" -> "CORES/THREADS"), then takes its short // form ("CORES/THR", "PERF"), before it loses letters (the wide faces of HUD and Bento at some scales). let closed = k.replace(" / ", "/"); @@ -1828,20 +1903,14 @@ impl Draw<'_> { let k = cv.ellipsize(self.f.tiny, draw, room); self.cap(cv, &k, r.l + self.s(10), r.t + self.s(6)); // A long value steps down a size before it loses characters. - let (f, v) = cv.fit_text(&[self.f.semi, self.f.small, self.f.tiny], v, room); + let (f, v) = cv.fit_text(&[self.f.semi, self.f.small, self.f.tiny], v, full); let dy = (cv.measure(self.f.semi, "0").1 - cv.measure(f, "0").1) / 2; cv.text(f, &v, r.l + self.s(10), r.t + self.s(22) + dy, self.col.fg); } /// Grid of key/value tiles in `cols` columns starting at (l, t) across width `w`. fn kv_grid(&self, cv: &mut Canvas, l: i32, t: i32, w: i32, cols: i32, items: &[(&str, String)]) { - let g = self.s(8); - let tw = (w - g * (cols - 1)) / cols; - let th = self.s(48); - for (i, (k, v)) in items.iter().enumerate() { - let (cx, cy) = (i as i32 % cols, i as i32 / cols); - let x = l + cx * (tw + g); - let r = Rect { l: x, t: t + cy * (th + g), r: if cx == cols - 1 { l + w } else { x + tw }, b: t + cy * (th + g) + th }; + for (r, (k, v)) in self.m.kv_rects(l, t, w, cols, items.len()).into_iter().zip(items) { self.kv(cv, r, k, v); } } @@ -1916,7 +1985,7 @@ impl Draw<'_> { let (vw, th) = cv.measure(self.f.cap, v); let lw = cv.measure(self.f.small, label).0; let w = vw + lw + self.s(26); - let stop = self.hit_rect(Hit::TileStyle(false)).map_or(m.r - self.s(140), |h| h.l - self.s(8)); + let stop = self.hit_rect(Hit::TileStyle(false)).map_or(m.r - self.s(140), |h| h.l - self.s(8 + 30)); if x + w > stop { break; } @@ -2671,7 +2740,8 @@ impl Draw<'_> { } let st = cv.ellipsize(self.f.tiny, sub, vw); cv.text(self.f.tiny, &st, vx, y + self.s(56), self.col.dim); - let cr = Rect { l: vx + vw + self.s(12), t: y + self.s(4), r: rr, b: y + self.s(68) }; + // The button at the row's right end keeps clear of the chart. + let cr = Rect { l: vx + vw + self.s(12), t: y + self.s(4), r: rr - self.pin_w(), b: y + self.s(68) }; if cr.w() > self.s(40) { self.mirror(cv, cr, a, b, vals[0].2, vals[1].2); if !note.is_empty() && cr.w() > self.s(160) { @@ -2810,7 +2880,7 @@ impl Draw<'_> { cv.fill_rect(Rect { l: cx - self.s(1), t: scr.b, r: cx + self.s(1), b: scr.b + self.s(4) }, acc.with_a(110)); cv.fill_rect(Rect { l: cx - self.s(6), t: scr.b + self.s(4), r: cx + self.s(6), b: scr.b + self.s(5) }, acc.with_a(110)); let tx = l + self.s(74); - let nm = cv.ellipsize(self.f.cap, &d.name, r - tx); + let nm = cv.ellipsize(self.f.cap, &d.name, r - self.pin_w() - tx); cv.text(self.f.cap, &nm, tx, t + self.s(2), self.col.fg); let mut sub: Vec = Vec::new(); if d.w > 0 { @@ -2825,7 +2895,7 @@ impl Draw<'_> { if d.primary && ds.len() > 1 { sub.push("Main".into()); } - let st = cv.ellipsize(self.f.small, &sub.join(" \u{00B7} "), r - tx); + let st = cv.ellipsize(self.f.small, &sub.join(" \u{00B7} "), r - self.pin_w() - tx); cv.text(self.f.small, &st, tx, t + self.s(20), self.col.dim); t += self.s(44); } @@ -2842,25 +2912,11 @@ impl Draw<'_> { let (l, rr) = (r.l + self.s(16), r.r - self.s(16)); let (dn, up) = (self.acc(Metric::Down), self.acc(Metric::Up)); // Connected adapters come first; the rest collapse to one line. - for (i, x) in d.adapters.iter().enumerate().filter(|(_, x)| x.connected) { + for (i, _) in d.adapters.iter().enumerate().filter(|(_, x)| x.connected) { if i > 0 { cv.fill_rect(Rect { l, t: y - self.s(6), r: rr, b: y - self.s(5) }, self.col.card_border); } - let h = m.nets.get(i); - let a: Vec = h.map_or(Vec::new(), |s| s.a.iter().copied().collect()); - let b: Vec = h.map_or(Vec::new(), |s| s.b.iter().copied().collect()); - let mut sub = Vec::new(); - if !x.description.is_empty() { - sub.push(x.description.clone()); - } - if x.link_bps > 0 { - sub.push(link(x.link_bps)); - } - if !x.ipv4.is_empty() { - sub.push(x.ipv4.clone()); - } - let cap = if x.wifi { "WI-FI" } else { "" }; - self.device_row(cv, l, rr, y, 0.0, dn, "", cap, &x.alias, [("\u{25BC}", x.down, dn), ("\u{25B2}", x.up, up)], &sub.join(" \u{00B7} "), "", &a, &b, true); + self.adapter_row(cv, i, l, rr, y); y += self.s(84); } let off: Vec<&str> = d.adapters.iter().filter(|a| !a.connected).map(|a| a.alias.as_str()).collect(); @@ -2908,6 +2964,31 @@ impl Draw<'_> { } } + /// One network adapter: dial, down and up, its chart. + fn adapter_row(&self, cv: &mut Canvas, i: usize, l: i32, rr: i32, y: i32) { + let m = self.m; + let Some(x) = m.det.adapters.get(i) else { return }; + let (dn, up) = (self.acc(Metric::Down), self.acc(Metric::Up)); + let h = m.nets.get(i); + let a: Vec = h.map_or(Vec::new(), |s| s.a.iter().copied().collect()); + let b: Vec = h.map_or(Vec::new(), |s| s.b.iter().copied().collect()); + let mut sub = Vec::new(); + if !x.connected { + sub.push("Not connected".to_string()); + } + if !x.description.is_empty() { + sub.push(x.description.clone()); + } + if x.link_bps > 0 { + sub.push(link(x.link_bps)); + } + if !x.ipv4.is_empty() { + sub.push(x.ipv4.clone()); + } + let cap = if x.wifi { "WI-FI" } else { "" }; + self.device_row(cv, l, rr, y, 0.0, dn, "", cap, &x.alias, [("\u{25BC}", x.down, dn), ("\u{25B2}", x.up, up)], &sub.join(" \u{00B7} "), "", &a, &b, true); + } + // ---- processes fn procs(&self, cv: &mut Canvas, r: Rect) { diff --git a/src/monitor/addonpage.rs b/src/monitor/addonpage.rs index e1e4365..1aa71bc 100644 --- a/src/monitor/addonpage.rs +++ b/src/monitor/addonpage.rs @@ -12,10 +12,10 @@ use crate::sensors::deep::speed::{UsbDev, UsbKind}; /// Narrowest shelf tile and its height, unscaled. const TILE_MIN_W: i32 = 290; -const TILE_H: i32 = 132; +pub(super) const TILE_H: i32 = 132; /// Narrowest device card inside an open tile and its height, unscaled. const CARD_MIN_W: i32 = 330; -const CARD_H: i32 = 164; +pub(super) const CARD_H: i32 = 164; /// Rows of the "Recent apps" list (mic and camera). const RECENT_ROWS: usize = 6; /// History kept of the hottest zone (seconds; one sample per Monitor tick). @@ -332,7 +332,7 @@ pub(super) fn units(a: Addon, x: &Addons) -> Vec { } /// Rows of the recent apps list: (app, what, when). -fn recent_rows(x: &Addons) -> Vec<(String, &'static str, String)> { +pub(super) fn recent_rows(x: &Addons) -> Vec<(String, &'static str, String)> { let now = now_unix(); let mut v: Vec<(u64, bool, String, &'static str)> = Vec::new(); for (list, what) in [(&x.mic, "Microphone"), (&x.cam, "Camera")] { @@ -410,6 +410,8 @@ impl Monitor { let rc = Rect { l: x0, t: *t, r: x1, b: *t + th }; m.hits.push((switch(m, rc), Hit::AddonSwitch(a.idx() as u8))); if m.addons_on.has(a) { + // "Show in hover", left of the switch. + m.pin(hover::Item::Addon(a), rc.r - m.sc(16 + 40 + 8), rc.t + m.sc(11)); m.hits.push((rc, Hit::AddonOpen(a.idx() as u8))); } lay.tiles.push((a, rc)); @@ -430,6 +432,7 @@ impl Monitor { let pad = self.sc(16); let head = Rect { l, t, r, b: t + th }; self.hits.push((switch(self, head), Hit::AddonSwitch(a.idx() as u8))); + self.pin(hover::Item::Addon(a), head.r - self.sc(16 + 40 + 8), head.t + self.sc(11)); self.hits.push((head, Hit::AddonOpen(a.idx() as u8))); let mut b = head.b; let n = units(a, self.addons()).len(); @@ -446,13 +449,16 @@ impl Monitor { let x0 = l + pad + (c as f32 * (cw + gap as f32)).round() as i32; let x1 = if c == in_row - 1 { r - pad } else { l + pad + ((c + 1) as f32 * (cw + gap as f32) - gap as f32).round() as i32 }; let ct = b + row_i * (ch + gap); - lay.cards.push((i as usize, Rect { l: x0, t: ct, r: x1, b: ct + ch })); + let rc = Rect { l: x0, t: ct, r: x1, b: ct + ch }; + self.pin(hover::Item::Unit(a, i as usize), rc.r - self.sc(8), rc.t + self.sc(8)); + lay.cards.push((i as usize, rc)); } b += rows * (ch + gap); } if a == Addon::Privacy { let rows = recent_rows(self.addons()).len().max(1) as i32; let rc = Rect { l: l + pad, t: b, r: r - pad, b: b + self.sc(46) + rows * self.sc(30) }; + self.pin_card(hover::Item::Recent, rc); lay.recent = Some(rc); b = rc.b + gap; } @@ -507,9 +513,14 @@ impl Draw<'_> { self.recent_card(cv, x, sh(r)); } } + for (_, r) in &m.dp.addons.tiles { + if vis(*r) { + self.pins(cv, sh(*r)); + } + } } - fn addon_tile(&self, cv: &mut Canvas, a: Addon, x: &Addons, r: Rect) { + pub(super) fn addon_tile(&self, cv: &mut Canvas, a: Addon, x: &Addons, r: Rect) { let m = self.m; let on = m.addons_on.has(a); let open = on && m.addon_open == Some(a); @@ -533,9 +544,11 @@ impl Draw<'_> { let p = self.s(16); // Title, then the switch on the right. let sw = Rect { l: r.r - p - self.s(40), t: r.t + self.s(12), r: r.r - p, b: r.t + self.s(34) }; - let title = cv.ellipsize(self.f.semi, a.name(), sw.l - self.s(10) - (r.l + p)); + let title = cv.ellipsize(self.f.semi, a.name(), sw.l - self.s(10) - self.pin_w() - (r.l + p)); cv.text(self.f.semi, &title, r.l + p, r.t + self.s(14), if on { self.col.fg } else { self.col.dim }); - self.switch(cv, sw, on, self.is_hot(Hit::AddonSwitch(a.idx() as u8))); + if !m.in_hover { + self.switch(cv, sw, on, self.is_hot(Hit::AddonSwitch(a.idx() as u8))); + } // Body: the live picture on the left, the number and its line on the right. let by = r.t + self.s(46); let bh = self.s(TILE_H - 46 - 16); @@ -561,7 +574,7 @@ impl Draw<'_> { } let sub = cv.ellipsize(self.f.small, &h.sub, r.r - p - tx); cv.text(self.f.small, &sub, tx, ny + nh + self.s(4), self.col.dim); - if !open { + if !open && !m.in_hover { let hint = match a { Addon::Usb => format!("CLICK FOR {} DEVICE{}", x.usb.len(), if x.usb.len() == 1 { "" } else { "S" }), Addon::Thermal => format!("CLICK FOR {} ZONE{}", x.zones.len(), if x.zones.len() == 1 { "" } else { "S" }), @@ -701,7 +714,7 @@ impl Draw<'_> { } /// A device card inside an open tile: gauge, name, the big number, a line, three facts. - fn unit_card(&self, cv: &mut Canvas, a: Addon, u: &Unit, r: Rect) { + pub(super) fn unit_card(&self, cv: &mut Canvas, a: Addon, u: &Unit, r: Rect) { let m = self.m; cv.fill_round(r, self.sf(crate::look::current_card_radius() as f32), self.sub); let p = self.s(16); @@ -720,7 +733,7 @@ impl Draw<'_> { } let tx = r.l + p + gs + self.s(16); let tw = r.r - p - tx; - let nm = cv.ellipsize(self.f.semi, &u.name, tw); + let nm = cv.ellipsize(self.f.semi, &u.name, tw - self.pin_w()); cv.text(self.f.semi, &nm, tx, r.t + p - self.s(2), self.col.fg); let font = m.num_font; let (nw, nh) = cv.measure(font, &u.big); @@ -741,7 +754,7 @@ impl Draw<'_> { } /// Mic and camera: the apps that used them last. - fn recent_card(&self, cv: &mut Canvas, x: &Addons, r: Rect) { + pub(super) fn recent_card(&self, cv: &mut Canvas, x: &Addons, r: Rect) { cv.fill_round(r, self.sf(crate::look::current_card_radius() as f32), self.sub); let rows = recent_rows(x); let y = self.header(cv, r, "Recent apps", "as Windows recorded them", 0); diff --git a/src/monitor/btpage.rs b/src/monitor/btpage.rs index cdc3866..679045c 100644 --- a/src/monitor/btpage.rs +++ b/src/monitor/btpage.rs @@ -22,7 +22,7 @@ const LOW_PCT: u8 = 20; /// Rows on the overview card. const CARD_ROWS: usize = 4; /// Height of a device card (Rack) and of the small cards under the hero, unscaled. -const TILE_H: i32 = 190; +pub(super) const TILE_H: i32 = 190; /// Padding on every side of a device card, unscaled: icon, numbers and name all keep it. const BOXPAD: i32 = 18; @@ -47,7 +47,7 @@ pub(super) fn level(d: &BtDevice) -> Option { } /// Reports left, right and case separately (the helper module fills these). -fn per_bud(d: &BtDevice) -> bool { +pub(super) fn per_bud(d: &BtDevice) -> bool { d.left.is_some() || d.right.is_some() } @@ -461,6 +461,16 @@ impl Monitor { t } }; + // "Show in hover" on every device, in every layout. + if let Some(rc) = lay.list { + for k in 0..n { + self.pin(hover::Item::Bt(k), rc.r - self.sc(16), rc.t + self.sc(46) + k as i32 * self.sc(58) + self.sc(17)); + } + } + let tiles: Vec<(usize, Rect)> = lay.hero.into_iter().chain(lay.tiles.iter().copied()).collect(); + for (i, rc) in tiles { + self.pin(hover::Item::Bt(i), rc.r - self.sc(8), rc.t + self.sc(8)); + } self.dp.bt = lay; bottom } @@ -548,16 +558,23 @@ impl Draw<'_> { } if let Some(r) = lay.list.filter(|r| vis(*r)) { self.bt_list(cv, sh(r)); + self.pins(cv, sh(r)); } if let Some((i, r)) = lay.hero.filter(|x| vis(x.1)) { if let Some(d) = m.bt().get(i) { self.bt_hero(cv, d, sh(r)); + // The tile is filled with the text colour: the button sits on a card-coloured disc. + let c = self.s(12); + let rr = sh(r); + cv.fill_disc((rr.r - self.s(8) - c) as f32, (rr.t + self.s(8) + c) as f32, self.sf(13.0), self.col.bubble); + self.pins(cv, rr); } } for (i, r) in &lay.tiles { let (Some(d), true) = (m.bt().get(*i), vis(*r)) else { continue }; let r = sh(*r); self.bt_icon_tile(cv, d, r); + self.pins(cv, r); } } @@ -568,7 +585,8 @@ impl Draw<'_> { self.card(cv, r); let on = m.bt().iter().filter(|d| d.connected).count(); let y = self.header(cv, r, "Paired devices", &format!("{on} connected"), 0); - let (l, rr) = (r.l + self.s(16), r.r - self.s(16)); + // Each row ends with its "show in hover" button. + let (l, rr) = (r.l + self.s(16), r.r - self.s(16) - self.pin_w()); let rh = self.s(58); let name_w = ((rr - l) as f32 * 0.34).clamp(self.sf(150.0), self.sf(300.0)) as i32; let pct_w = self.s(64); @@ -678,7 +696,7 @@ impl Draw<'_> { /// the numbers on one row at the same height in every card, below the drawing; the /// name at the foot. Tall shapes (speaker, mouse) stand full height on the left with /// their number on the right. One padding on every side. - fn bt_icon_tile(&self, cv: &mut Canvas, d: &BtDevice, r: Rect) { + pub(super) fn bt_icon_tile(&self, cv: &mut Canvas, d: &BtDevice, r: Rect) { let m = self.m; self.card(cv, r); let tk = crate::look::tokens(self.dark()); diff --git a/src/monitor/devpage.rs b/src/monitor/devpage.rs index 9fd06db..037e849 100644 --- a/src/monitor/devpage.rs +++ b/src/monitor/devpage.rs @@ -80,6 +80,8 @@ pub(super) enum Card { Outages, AdapterFacts, Wifi, + /// Every adapter, connected ones first. + NetList, Conns, /// Bytes per app (ETW; admin only, else an unlock button). AppTraffic, @@ -95,7 +97,7 @@ pub(super) struct DevPage { /// Pointer over the page, content coordinates. pub hover: Option<(i32, i32)>, /// Extra history of the open device, newest last. - hist: HashMap>, + pub(super) hist: HashMap>, tops: VecDeque, tabs: Vec<(Dev, Rect)>, /// Bluetooth page pieces. @@ -105,7 +107,7 @@ pub(super) struct DevPage { verdict: Rect, /// The part itself (icon, number, name, key facts), left of the chart. pub(super) part: Rect, - chart: Rect, + pub(super) chart: Rect, cards: Vec<(Card, Rect)>, /// Drives / Displays page: one card per drive or screen. pub(super) units: Vec<(Dev, Rect)>, @@ -326,7 +328,7 @@ impl Monitor { } /// Drive letters on PhysicalDrive `n` (b'C'), in order. - fn disk_letters(&self, n: u32) -> Vec { + pub(super) fn disk_letters(&self, n: u32) -> Vec { let mut v: Vec = match self.det.disks.iter().find(|x| x.num == Some(n)) { Some(x) => x.letters.split_whitespace().filter(|t| crate::sensors::detail::is_letter(t)).map(|t| t.as_bytes()[0].to_ascii_uppercase()).collect(), None => self.det.hw.vols.iter().filter(|v| v.disk == Some(n) && crate::sensors::detail::is_letter(&v.letter)).map(|v| v.letter.as_bytes()[0].to_ascii_uppercase()).collect(), @@ -407,10 +409,13 @@ impl Monitor { if self.view.is_none() { return false; } + let fact = |p: Option<(i32, i32)>| p.and_then(|(x, y)| self.fact_tiles.iter().position(|t| t.0.contains(x, y))); + let was_fact = fact(self.dp.hover); let was = self.dp.hover.filter(|(x, y)| self.dp.chart.contains(*x, *y)); + let now_fact = fact(p); self.dp.hover = p; let now = p.filter(|(x, y)| self.dp.chart.contains(*x, *y)); - was.is_some() || now.is_some() + was.is_some() || now.is_some() || was_fact != now_fact } /// Record the open device's history (called from `feed`). @@ -445,7 +450,13 @@ impl Monitor { self.open_dev(Dev::Disk(first)); } } - let Some(dev) = self.view else { return }; + if let Some(dev) = self.view { + self.push_dev(dev); + } + } + + /// One more sample of `dev`'s own history. + pub(super) fn push_dev(&mut self, dev: Dev) { let lv = self.det.deep.clone(); match dev { Dev::Cpu => { @@ -515,7 +526,7 @@ impl Monitor { v } - fn cards_for(&self, d: Dev) -> Vec { + pub(super) fn cards_for(&self, d: Dev) -> Vec { match d { Dev::Cpu => vec![Card::CoreMap, Card::Power, Card::Apps(0), Card::Clock, Card::Chip], Dev::Mem => vec![Card::MemMap, Card::Apps(1), Card::Commit, Card::Sticks], @@ -536,20 +547,21 @@ impl Monitor { v } Dev::Display(_) => vec![Card::Signal, Card::Link, Card::Hdr, Card::Panel], - Dev::Net => vec![Card::Path, Card::Outages, Card::AdapterFacts, Card::Wifi, Card::AppTraffic, Card::Conns, Card::Traffic], + Dev::Net => vec![Card::Path, Card::Outages, Card::AdapterFacts, Card::Wifi, Card::AppTraffic, Card::Conns, Card::Traffic, Card::NetList], Dev::Battery => vec![Card::Capacity, Card::BatLive], Dev::Bluetooth | Dev::Addons => Vec::new(), } } /// Height a card needs at width `w`. - fn card_h(&self, c: Card, w: i32) -> i32 { + pub(super) fn card_h(&self, c: Card, w: i32) -> i32 { let s = |v: i32| self.sc(v); let head = s(46); let foot = s(16); let kv_rows = |n: usize, w: i32| { let cols = ((w - s(32)) / s(150)).clamp(1, 3) as usize; - n.div_ceil(cols) as i32 * s(56) + // One row at least: "Not reported on this PC". + n.max(1).div_ceil(cols) as i32 * s(56) }; let body = match c { Card::CoreMap => { @@ -583,6 +595,7 @@ impl Monitor { Card::Conns => APP_ROWS as i32 * s(30), Card::AppTraffic => APP_ROWS as i32 * s(30), Card::Traffic => s(130), + Card::NetList => self.det.adapters.len().max(1) as i32 * s(84) - s(8), Card::Capacity => s(40 + 28) + kv_rows(self.bat_facts().len(), w), Card::BatLive => kv_rows(self.bat_live().len(), w), Card::Admin => s(96), @@ -608,7 +621,7 @@ impl Monitor { let nseg = if bt { btpage::BT_LAYOUTS.len() } else if ad { 0 } else { RANGES.len() } as i32; let rx = r - segw * nseg - self.sc(4); let mut x = rx; - let segs: Vec = if bt { (0..nseg as u8).map(Hit::BtLayout).collect() } else { RANGES.iter().map(|x| Hit::Range(x.1)).collect() }; + let segs: Vec = if bt { (0..nseg as u8).map(Hit::BtLayout).collect() } else if ad { Vec::new() } else { RANGES.iter().map(|x| Hit::Range(x.1)).collect() }; for h in segs { self.hits.push((Rect { l: x, t: y + self.sc(3), r: x + segw, b: y + th - self.sc(3) }, h)); x += segw; @@ -712,7 +725,12 @@ impl Monitor { y += ph + gap; } } + if !self.dp.part.is_empty() { + let part = self.dp.part; + self.pin_card(hover::Item::Part(dev), part); + } self.dp.chart = Rect { l: chart_l, t: y, r, b: y + ch }; + self.pin_card(hover::Item::Chart(dev), self.dp.chart); self.hits.push((self.dp.chart, Hit::Spike)); y += ch + gap; let cards = self.cards_for(dev); @@ -741,6 +759,11 @@ impl Monitor { let x1 = if i as i32 == k - 1 { r } else { x0 + cw }; let rc = Rect { l: x0, t: y, r: x1, b: y + h }; self.dp.units.push((d, rc)); + match d { + Dev::Disk(n) => self.pin_card(hover::Item::Drive(n), rc), + Dev::Display(i) => self.pin_card(hover::Item::Screen(i), rc), + _ => {} + } self.hits.push((rc, Hit::Open(d))); } y += h + gap; @@ -758,6 +781,9 @@ impl Monitor { /// The open drive's chart and cards, from `y`; returns the bottom. fn layout_drive_detail(&mut self, l: i32, r: i32, y: i32, ch: i32) -> i32 { self.dp.chart = Rect { l, t: y, r, b: y + ch }; + if let Some(d) = self.view { + self.pin_card(hover::Item::Chart(d), self.dp.chart); + } self.hits.push((self.dp.chart, Hit::Spike)); let cards = self.view.map_or(Vec::new(), |d| self.cards_for(d)); self.masonry(l, r, y + ch + self.sc(12), cards) @@ -765,7 +791,7 @@ impl Monitor { /// Height of every drive card: room for the most drive letters any drive has (2 at least), /// so the cards of a row line up. - fn drive_card_h(&self) -> i32 { + pub(super) fn drive_card_h(&self) -> i32 { self.sc(16 + DRIVE_ICON + 14) + self.drive_vrows() * self.sc(22) + self.sc(14 + 48 + 30 + 48 + 12 + 14 + 16) } @@ -847,7 +873,16 @@ impl Monitor { fn card_hits(&mut self, c: Card, r: Rect) { let dpi = self.dpi as i32; let s = move |v: i32| (v * dpi + 48) / 96; + if let Some(d) = self.view { + self.pin_card(hover::Item::Card(d, c), r); + self.pin_facts(d, c, r); + } match c { + Card::NetList => { + for i in 0..self.det.adapters.len() { + self.pin(hover::Item::Net(i), r.r - s(12), r.t + s(46) + i as i32 * s(84)); + } + } Card::Apps(k) => { let rows = self.app_rows(k); for (i, row) in rows.iter().enumerate() { @@ -869,7 +904,7 @@ impl Monitor { } Card::Outages => { let cw = self.fit_w(120, "Copy for my ISP", s(12)); - let b = Rect { l: r.r - s(16) - cw, t: r.t + s(12), r: r.r - s(16), b: r.t + s(36) }; + let b = Rect { l: r.r - s(16 + 28) - cw, t: r.t + s(12), r: r.r - s(16 + 28), b: r.t + s(36) }; self.hits.push((b, Hit::CopyOutages)); } Card::Admin => { @@ -920,6 +955,121 @@ impl Monitor { } } + /// The facts a card lists, in order. + pub(super) fn card_facts(&self, c: Card) -> Vec<(&'static str, String)> { + match c { + Card::Chip => self.chip_facts(), + Card::Power => self.power_facts(), + Card::Commit => self.commit_facts(), + Card::GpuHealth => self.gpu_facts(), + Card::DriveFacts => self.drive_facts(), + Card::Health => self.health_facts(), + Card::Link => self.link_facts(), + Card::Hdr => self.hdr_facts(), + Card::Panel => self.panel_facts(), + Card::AdapterFacts => self.net_facts(), + Card::Wifi => self.wifi_facts(), + Card::Capacity => self.bat_facts(), + Card::BatLive => self.bat_live(), + _ => Vec::new(), + } + } + + /// Where a card's fact tiles are, with their labels (as `dev_card` draws them). + pub(super) fn fact_rects(&self, c: Card, r: Rect) -> Vec<(Rect, &'static str)> { + let facts = self.card_facts(c); + if facts.is_empty() { + return Vec::new(); + } + let (l, rr) = (r.l + self.sc(16), r.r - self.sc(16)); + let y = r.t + self.sc(46); + let (l, y, w, cols, n) = match c { + Card::Health => { + let (l, cols) = self.health_grid(r); + (l, y, rr - l, cols, facts.len().min(cols as usize * 2)) + } + Card::Hdr => { + let w = rr - l - self.hdr_tri(rr - l); + (l, y, w, (w / self.sc(120)).clamp(1, 2), facts.len()) + } + _ => { + let y = match c { + Card::Wifi if self.live().wifi.as_ref().is_none_or(|w| w.location_blocked) => y + self.sc(24), + Card::Capacity => y + self.sc(40), + _ => y, + }; + (l, y, rr - l, ((rr - l) / self.sc(150)).clamp(1, 3), facts.len()) + } + }; + self.kv_rects(l, y, w, cols, n).into_iter().zip(facts).map(|(r, f)| (r, f.0)).collect() + } + + /// Whose fact it is, for the hover window's label ("CPU", "C:", "LG ULTRAGEAR"). + pub(super) fn fact_owner(&self, d: Dev) -> String { + match d { + Dev::Disk(n) => self.disk_letters(n).first().map_or_else(|| self.drive_name(n), |c| format!("{}:", *c as char)), + Dev::Display(i) => self.screen_info(i).name, + d => dev_label(self, d).to_uppercase(), + } + } + + /// Health facts of the open drive. + fn health_facts(&self) -> Vec<(&'static str, String)> { + let Some(h) = self.view_disk().and_then(|n| self.st().disk(n)).and_then(|x| x.health.as_ref()) else { return Vec::new() }; + let days = (h.power_on_hours as f64 / 24.0).max(1.0); + let daily = h.written_bytes as f64 / days; + let mut items: Vec<(&'static str, String)> = Vec::new(); + if let Some(t) = h.temp_c { + items.push(("TEMPERATURE", format!("{t} \u{00B0}C"))); + } + items.push(("WRITTEN", fmt::bytes(h.written_bytes.min(u128::from(u64::MAX)) as u64))); + items.push(("PER DAY", fmt::bytes(daily as u64))); + items.push(("POWERED ON", format!("{} h", group(h.power_on_hours)))); + items.push(("SPARE", format!("{}%", h.spare))); + items.push(("ERRORS", h.media_errors.to_string())); + if let Some(y2) = crate::sensors::deep::disk::forecast(h, daily) { + items.push(("YEARS LEFT", format!("about {:.0}", y2.min(99.0)))); + } + items.push(("UNSAFE OFFS", h.unsafe_shutdowns.to_string())); + items + } + + /// Left edge and columns of the health card's facts (right of its ring). + fn health_grid(&self, r: Rect) -> (i32, i32) { + let kx = r.l + self.sc(16) + self.sc(124); + (kx, ((r.r - self.sc(16) - kx) / self.sc(130)).clamp(1, 3)) + } + + /// Brightness and colour of the open screen. + fn hdr_facts(&self) -> Vec<(&'static str, String)> { + let Some(s) = self.screen() else { return Vec::new() }; + let mut items: Vec<(&'static str, String)> = Vec::new(); + if let Some(n) = s.max_nits.filter(|n| *n > 0.0) { + items.push(("PEAK", format!("{:.0} nits", n))); + } + if let Some(n) = s.max_full_frame_nits.filter(|n| *n > 0.0) { + items.push(("FULL SCREEN", format!("{:.0} nits", n))); + } + if let Some(n) = s.min_nits.filter(|n| *n > 0.0) { + items.push(("BLACK", format!("{:.3} nits", n))); + } + if let Some(p) = s.primaries { + let (srgb, p3) = display::gamut_cover(&p); + items.push(("SRGB", format!("{:.0}%", srgb))); + items.push(("DCI-P3", format!("{:.0}%", p3))); + } + items + } + + /// Width the colour triangle takes of `w` px (0 = none). + fn hdr_tri(&self, w: i32) -> i32 { + if self.screen().is_some_and(|s| s.primaries.is_some()) && w > self.sc(320) { + self.sc(110) + self.sc(16) + } else { + 0 + } + } + // ------------------------------------------------------------------ data helpers /// Top apps by sort key (0 CPU, 1 memory, 2 disk, 3 GPU): (pid, title, value text, fraction). @@ -1566,9 +1716,8 @@ impl Monitor { /// What a screen card shows of screen `i` (Windows' screen list, else the basic one). fn screen_info(&self, i: u32) -> ScreenInfo { - let open = self.view == Some(Dev::Display(i)); let mh = self.live().measured_hz; - let measured = (open && mh > 0.0).then_some(mh); + let measured = (self.live().measured == Some(i) && mh > 0.0).then_some(mh); let hw = self.det.hw.displays.get(i as usize); match self.st().screens.get(i as usize) { Some(sc) => { @@ -1618,12 +1767,12 @@ impl Monitor { } /// Height of every screen card. - fn screen_card_h(&self) -> i32 { + pub(super) fn screen_card_h(&self) -> i32 { self.sc(16 + DRIVE_ICON + 14) + 2 * self.sc(22) + self.sc(14 + 48 + 30 + 48 + 12 + 14 + 16) } /// Model of disk `n` ("Disk 1" when unknown). - fn drive_name(&self, n: u32) -> String { + pub(super) fn drive_name(&self, n: u32) -> String { self.det.hw.drive(n).map(|d| d.model.trim().to_string()).filter(|m| !m.is_empty()).unwrap_or_else(|| format!("Disk {n}")) } @@ -1795,6 +1944,7 @@ impl Monitor { } if vis(self.dp.part) && !self.dp.part.is_empty() { d.part_card(cv, sh(self.dp.part)); + d.pins(cv, sh(self.dp.part)); } for (u, r) in &self.dp.units { if vis(*r) { @@ -1803,16 +1953,19 @@ impl Monitor { Dev::Display(i) => d.screen_card(cv, i, sh(*r), *r), _ => {} } + d.pins(cv, sh(*r)); } } if vis(self.dp.chart) { d.hero_chart(cv, sh(self.dp.chart)); + d.pins(cv, sh(self.dp.chart)); } for (c, r) in &self.dp.cards { if vis(*r) { let r = sh(*r); d.card(cv, r); d.dev_card(cv, *c, r); + d.pins(cv, r); } } } @@ -1912,7 +2065,7 @@ impl Draw<'_> { } } - fn hero_chart(&self, cv: &mut Canvas, r: Rect) { + pub(super) fn hero_chart(&self, cv: &mut Canvas, r: Rect) { let m = self.m; self.card(cv, r); let (sers, max, axis, title) = m.chart_series(self.dark()); @@ -1922,7 +2075,8 @@ impl Draw<'_> { let mut lx = r.l + self.s(16) + cv.measure(self.f.semi, title).0 + self.s(20); let ly = r.t + self.s(17); let key = "min \u{00B7} avg \u{00B7} max"; - let key_l = r.r - self.s(16) - cv.measure(self.f.tiny, key).0; + let key_r = r.r - self.s(16) - self.pin_w(); + let key_l = key_r - cv.measure(self.f.tiny, key).0; // Whole entries only, each ending before the key on the right. let mut shown = 0; for s in &sers { @@ -1934,7 +2088,17 @@ impl Draw<'_> { shown += 1; } if shown > 0 { - cv.text_right(self.f.tiny, key, r.r - self.s(16), ly + self.s(1), self.col.dim); + cv.text_right(self.f.tiny, key, key_r, ly + self.s(1), self.col.dim); + } else if m.in_hover { + // Too narrow for the legend: each trace's value now. + let mut x = key_r; + for s in sers.iter().rev() { + let Some(v) = s.data.last().filter(|v| v.is_finite()) else { continue }; + let t = axis_text(axis, *v); + let w = cv.measure(self.f.cap, &t).0; + cv.text(self.f.cap, &t, x - w, ly, self.col.legible(s.c, self.col.card)); + x -= w + self.s(10); + } } let p = m.chart_plot(); let p = Rect { t: p.t - m.dp.chart.t + r.t, b: p.b - m.dp.chart.t + r.t, ..p }; @@ -2058,9 +2222,21 @@ impl Draw<'_> { self.kv_grid(cv, l, y, rr - l, cols, items); } - fn dev_card(&self, cv: &mut Canvas, c: Card, r: Rect) { + pub(super) fn dev_card(&self, cv: &mut Canvas, c: Card, r: Rect) { let m = self.m; match c { + Card::NetList => { + let up = m.det.adapters.iter().filter(|a| a.connected).count(); + let mut y = self.card_head(cv, r, "Adapters", &format!("{up} connected")); + let (l, rr) = (r.l + self.s(16), r.r - self.s(16)); + for i in 0..m.det.adapters.len() { + if i > 0 { + cv.fill_rect(Rect { l, t: y - self.s(6), r: rr, b: y - self.s(5) }, self.col.card_border); + } + self.adapter_row(cv, i, l, rr, y); + y += self.s(84); + } + } Card::CoreMap => self.core_map(cv, r), Card::Chip => { let y = self.card_head(cv, r, "Chip", &m.det.cpu_name); @@ -2193,7 +2369,7 @@ impl Draw<'_> { fn apps_card(&self, cv: &mut Canvas, r: Rect, k: u8) { let title = ["Busiest apps", "Biggest apps", "Busiest apps, all disks", "Busiest apps"][k as usize % 4]; - let y = self.card_head(cv, r, title, "click for its menu"); + let y = self.card_head(cv, r, title, if self.m.in_hover { "" } else { "click for its menu" }); let rows = self.m.app_rows(k); let c = [self.acc(Metric::Cpu), self.acc(Metric::Ram), self.acc(Metric::DiskRead), self.acc(Metric::Gpu)][k as usize % 4]; self.bar_rows(cv, r, y, rows.iter().map(|x| (x.0, x.1.clone(), x.2.clone(), x.3, c)).collect()); @@ -2203,7 +2379,7 @@ impl Draw<'_> { let m = self.m; let st = m.live().vol_apps_state; let (title, sub) = match (st, m.view) { - (AppNet::On, Some(Dev::Disk(n))) => (format!("Busiest apps on {}", m.letters_text(n)).trim_end().to_string(), "click for its menu"), + (AppNet::On, Some(Dev::Disk(n))) => (format!("Busiest apps on {}", m.letters_text(n)).trim_end().to_string(), if m.in_hover { "" } else { "click for its menu" }), (AppNet::NeedsAdmin, _) => ("Busiest apps, all disks".to_string(), "per drive needs admin"), (AppNet::Failed, _) => ("Busiest apps, all disks".to_string(), "per-drive counter unavailable"), _ => ("Busiest apps, all disks".to_string(), "starting per-drive counter\u{2026}"), @@ -2423,23 +2599,8 @@ impl Draw<'_> { self.ring(cv, cx, cy, self.sf(50.0), self.sf(10.0), life, c); self.text_c(cv, self.f.head, &format!("{}%", h.life_left), cx as i32, cy as i32 - self.s(6), self.col.fg); self.text_c(cv, self.f.tiny, "life left", cx as i32, cy as i32 + self.s(14), self.col.dim); - let days = (h.power_on_hours as f64 / 24.0).max(1.0); - let daily = h.written_bytes as f64 / days; - let mut items: Vec<(&str, String)> = Vec::new(); - if let Some(t) = h.temp_c { - items.push(("TEMPERATURE", format!("{t} \u{00B0}C"))); - } - items.push(("WRITTEN", fmt::bytes(h.written_bytes.min(u128::from(u64::MAX)) as u64))); - items.push(("PER DAY", fmt::bytes(daily as u64))); - items.push(("POWERED ON", format!("{} h", group(h.power_on_hours)))); - items.push(("SPARE", format!("{}%", h.spare))); - items.push(("ERRORS", h.media_errors.to_string())); - if let Some(y2) = crate::sensors::deep::disk::forecast(h, daily) { - items.push(("YEARS LEFT", format!("about {:.0}", y2.min(99.0)))); - } - items.push(("UNSAFE OFFS", h.unsafe_shutdowns.to_string())); - let kx = l + self.s(124); - let cols = ((r.r - self.s(16) - kx) / self.s(130)).clamp(1, 3); + let items = m.health_facts(); + let (kx, cols) = m.health_grid(r); let shown = (cols * 2) as usize; self.kv_grid(cv, kx, y, r.r - self.s(16) - kx, cols, &items[..items.len().min(shown)]); } @@ -2476,23 +2637,11 @@ impl Draw<'_> { let y = self.card_head(cv, r, "Brightness and colour", ""); let (l, rr) = (r.l + self.s(16), r.r - self.s(16)); let Some(s) = m.screen() else { return }; - let mut items: Vec<(&str, String)> = Vec::new(); - if let Some(n) = s.max_nits.filter(|n| *n > 0.0) { - items.push(("PEAK", format!("{:.0} nits", n))); - } - if let Some(n) = s.max_full_frame_nits.filter(|n| *n > 0.0) { - items.push(("FULL SCREEN", format!("{:.0} nits", n))); - } - if let Some(n) = s.min_nits.filter(|n| *n > 0.0) { - items.push(("BLACK", format!("{:.3} nits", n))); - } + let items = m.hdr_facts(); // Gamut triangle against sRGB, if the panel reports its primaries. let tri = self.s(110); - let tw = if s.primaries.is_some() && rr - l > self.s(320) { tri + self.s(16) } else { 0 }; + let tw = m.hdr_tri(rr - l); if let Some(p) = s.primaries { - let (srgb, p3) = display::gamut_cover(&p); - items.push(("SRGB", format!("{:.0}%", srgb))); - items.push(("DCI-P3", format!("{:.0}%", p3))); if tw > 0 { let b = Rect { l: rr - tri, t: y, r: rr, b: y + tri - self.s(10) }; let map = |(x, yy): (f32, f32)| (b.l as f32 + x / 0.8 * b.w() as f32, b.b as f32 - yy / 0.9 * b.h() as f32); @@ -2722,7 +2871,7 @@ impl Draw<'_> { fn traffic_card(&self, cv: &mut Canvas, r: Rect) { let m = self.m; let st = m.live().app_net_state; - let y = self.card_head(cv, r, "Traffic by app", if st == AppNet::On { "click for its menu" } else { "" }); + let y = self.card_head(cv, r, "Traffic by app", if st == AppNet::On && !m.in_hover { "click for its menu" } else { "" }); let l = r.l + self.s(16); let note = |cv: &mut Canvas, t: &str| { let (f, t) = cv.fit_text(&[self.f.small, self.f.tiny], t, r.r - l - self.s(16)); @@ -3035,14 +3184,15 @@ impl Monitor { impl Draw<'_> { /// One screen on the Displays page: its shape as the icon, refresh as the big number, set /// against what the panel can do, frame pacing (the open screen), signal / HDR / link. - fn screen_card(&self, cv: &mut Canvas, i: u32, r: Rect, rc: Rect) { + pub(super) fn screen_card(&self, cv: &mut Canvas, i: u32, r: Rect, rc: Rect) { let m = self.m; let x = m.screen_info(i); let open = m.view == Some(Dev::Display(i)); + let ringed = open && !m.in_hover; let rad = self.sf(crate::look::current_card_radius() as f32); self.card(cv, r); let ring = self.acc(Metric::Cpu); - if open { + if ringed { cv.stroke_round(r, rad, ring); cv.stroke_round(Rect { l: r.l + 1, t: r.t + 1, r: r.r - 1, b: r.b - 1 }, (rad - 1.0).max(0.0), ring); } else if self.hot_open(Dev::Display(i), rc) { @@ -3060,7 +3210,7 @@ impl Draw<'_> { let tw = rr - tx; let slow = x.below_max(); if tw > self.s(40) { - let name = cv.ellipsize(self.f.semi, &x.name, tw); + let name = cv.ellipsize(self.f.semi, &x.name, tw - self.pin_w()); cv.text(self.f.semi, &name, tx, y + self.s(2), self.col.fg); let mut ty = y + self.s(26); let num = if now >= 100.0 || x.measured.is_none() { format!("{:.0}", now) } else { format!("{:.1}", now) }; @@ -3133,7 +3283,7 @@ impl Draw<'_> { cv.fill_round(Rect { l, t: my, r: rr, b: my + 1 }, 0.0, self.track); cv.spark(Rect { l, t: y, r: rr, b: y + half }, &norm, self.acc(Metric::Cpu)); } else { - self.note_line(cv, "Measured when you open it", l, y + half / 2, rr); + self.note_line(cv, if m.in_hover { "Open Displays to measure it" } else { "Measured when you open it" }, l, y + half / 2, rr); } y += half + self.s(4); let line = if open { format!("Frame pacing, last minute \u{00B7} line = {:.0} Hz", max) } else { format!("{:.0} Hz set in Windows", x.set) }; @@ -3141,6 +3291,9 @@ impl Draw<'_> { cv.text(self.f.small, &line, l, y, self.col.dim); y += self.s(18 + 12); self.kv_grid(cv, l, y, rr - l, 3, &[("SIGNAL", x.signal.clone()), ("HDR", x.hdr.clone()), ("LINK", x.link.clone())]); + if m.in_hover { + return; + } let hint = if open { "Its signal, cable and panel are below" } else { "Click for its signal, cable and panel" }; let cy = r.b - pad - self.s(7); let (f, t) = cv.fit_text(&[self.f.tiny], hint, rr - l); @@ -3150,7 +3303,7 @@ impl Draw<'_> { /// One drive on the Drives page: live icon, free space, a bar per drive letter, read and /// write, health / temperature / link. `r` on screen, `rc` the same in content coordinates. - fn drive_card(&self, cv: &mut Canvas, n: u32, r: Rect, rc: Rect) { + pub(super) fn drive_card(&self, cv: &mut Canvas, n: u32, r: Rect, rc: Rect) { let m = self.m; let open = m.view == Some(Dev::Disk(n)); let rad = self.sf(crate::look::current_card_radius() as f32); @@ -3178,7 +3331,7 @@ impl Draw<'_> { let total: u64 = vols.iter().map(|v| v.total).sum(); let drive = m.det.hw.drive(n); if tw > self.s(40) { - let name = cv.ellipsize(self.f.semi, &m.drive_name(n), tw); + let name = cv.ellipsize(self.f.semi, &m.drive_name(n), tw - self.pin_w()); cv.text(self.f.semi, &name, tx, y + self.s(2), self.col.fg); let mut ty = y + self.s(26); if total > 0 { @@ -3258,6 +3411,9 @@ impl Draw<'_> { }; self.kv_grid(cv, l, y, rr - l, 3, &[("HEALTH", health), ("TEMPERATURE", temp), ("LINK", link)]); // What a click does. + if m.in_hover { + return; + } let hint = if open { "Its apps, health and space are below" } else { "Click for its apps, health and space" }; let cy = r.b - pad - self.s(7); let (f, t) = cv.fit_text(&[self.f.tiny], hint, rr - l); @@ -3266,7 +3422,7 @@ impl Draw<'_> { } /// The part card: the live icon on the left, the number, name, a sub line and the key facts beside it. - fn part_card(&self, cv: &mut Canvas, r: Rect) { + pub(super) fn part_card(&self, cv: &mut Canvas, r: Rect) { let m = self.m; let Some(p) = m.part_info() else { return }; self.card(cv, r); diff --git a/src/monitor/hover.rs b/src/monitor/hover.rs new file mode 100644 index 0000000..7105795 --- /dev/null +++ b/src/monitor/hover.rs @@ -0,0 +1,1014 @@ +//! Anything on the Monitor pages in the tray hover window: every tile, card, chart, device and +//! fact has an id that stays the same across restarts ("bt|{container}", "drive|drive:C", +//! "card|cpu|cores", "fact|cpu|power|DPC"), kept in `Settings::hover_more` in the order picked. +//! +//! The hover window draws the picked items with the Monitor page's own drawing code, from a copy +//! of the numbers the sensor thread already took (`Board`). Nothing is read here. + +use super::addonpage; +use super::btpage; +use super::devpage::Card; +use super::*; +use crate::sensors::deep::addons::{Addon, ALL as ADDONS}; +use crate::sensors::deep::Needs; +use std::sync::Mutex; + +/// Something on a Monitor page that can go in the hover window. +#[derive(Clone, Debug, PartialEq)] +pub(super) enum Item { + /// Up time, processes, threads, handles. + Counts, + /// The VRAM tile. + Vram, + /// A card of the overview. + Sec(Sec), + /// A device page's chart. + Chart(Dev), + /// A device page's part card (icon, number, name, key facts). + Part(Dev), + Card(Dev, Card), + /// One fact of a card, by its label. + Fact(Dev, Card, String), + Drive(u32), + Screen(u32), + /// Index into `Detail::adapters`. + Net(usize), + /// Index into the Bluetooth list. + Bt(usize), + Addon(Addon), + /// One device of an add-on (index into `addonpage::units`). + Unit(Addon, usize), + /// Apps that used the mic or camera last. + Recent, +} + +const CARDS: [(Card, &str); 32] = [ + (Card::CoreMap, "cores"), + (Card::Chip, "chip"), + (Card::Power, "power"), + (Card::Apps(0), "apps-cpu"), + (Card::Apps(1), "apps-memory"), + (Card::Apps(2), "apps-disk"), + (Card::Apps(3), "apps-gpu"), + (Card::Clock, "clock"), + (Card::MemMap, "map"), + (Card::Commit, "commit"), + (Card::Sticks, "sticks"), + (Card::VramApps, "vram"), + (Card::Engines, "engines"), + (Card::GpuHealth, "health"), + (Card::Adapters, "adapters"), + (Card::Health, "drive-health"), + (Card::DriveFacts, "drive-facts"), + (Card::VolApps, "drive-apps"), + (Card::Signal, "signal"), + (Card::Link, "link"), + (Card::Hdr, "hdr"), + (Card::Panel, "panel"), + (Card::Path, "path"), + (Card::Outages, "drops"), + (Card::AdapterFacts, "connection"), + (Card::Wifi, "wifi"), + (Card::Conns, "connections"), + (Card::AppTraffic, "app-traffic"), + (Card::Traffic, "traffic"), + (Card::Capacity, "capacity"), + (Card::BatLive, "now"), + (Card::NetList, "adapters-list"), +]; + +fn card_key(c: Card) -> Option<&'static str> { + CARDS.iter().find(|x| x.0 == c).map(|x| x.1) +} + +fn card_of(k: &str) -> Option { + CARDS.iter().find(|x| x.1 == k).map(|x| x.0) +} + +const SECS: [(Sec, &str); 8] = + [(Sec::Cpu, "cpu"), (Sec::Mem, "memory"), (Sec::Gpu, "gpu"), (Sec::Disk, "disks"), (Sec::Net, "network"), (Sec::Bt, "bluetooth"), (Sec::Addons, "addons"), (Sec::Sys, "pc")]; + +/// A name inside an id: `|` separates its parts. +fn clean(s: &str) -> String { + s.trim().replace('|', "/") +} + +/// Names as keys: the second "LG ULTRAGEAR" is "LG ULTRAGEAR~2". +fn numbered(names: &[String]) -> Vec { + names + .iter() + .enumerate() + .map(|(i, n)| { + let k = names[..i].iter().filter(|x| *x == n).count(); + if k == 0 { + n.clone() + } else { + format!("{n}~{}", k + 1) + } + }) + .collect() +} + +// ---- ids as numbers: a page's clickable regions are `Copy`. + +static IDS: Mutex> = Mutex::new(Vec::new()); + +/// The number that stands for `id` while the app runs. +pub fn intern(id: &str) -> u32 { + let mut v = IDS.lock().unwrap_or_else(|e| e.into_inner()); + match v.iter().position(|x| x == id) { + Some(i) => i as u32, + None => { + v.push(id.to_string()); + v.len() as u32 - 1 + } + } +} + +pub fn name(n: u32) -> String { + IDS.lock().unwrap_or_else(|e| e.into_inner()).get(n as usize).cloned().unwrap_or_default() +} + +/// What the sensor thread must read while the hover window shows these items. +/// `screen` is the picked screen to measure (`Board::screen`). +pub fn needs(ids: &[String], screen: Option) -> Needs { + let mut n = Needs { detail: !ids.is_empty(), ..Needs::default() }; + for id in ids { + let p: Vec<&str> = id.split('|').collect(); + match p.as_slice() { + ["bt", ..] | ["sec", "bluetooth"] => n.bt = true, + ["addon" | "unit" | "recent", ..] | ["sec", "addons"] => n.addons = true, + ["drive", ..] => n.st = true, + ["screen", ..] => { + n.st = true; + n.screen = screen; + } + [kind @ ("chart" | "part" | "card" | "fact"), dev, rest @ ..] => { + n.st = true; + let card = rest.first().copied().unwrap_or(""); + match *dev { + "cpu" => n.cpu = true, + "gpu" => n.gpu = true, + "battery" => n.bat = true, + "net" => { + n.ping |= *kind == "chart" || matches!(card, "path" | "drops"); + n.net |= matches!(card, "wifi" | "connections"); + n.app_net |= card == "app-traffic"; + } + d if d.starts_with("drive:") => n.app_disk |= card == "drive-apps", + d if d.starts_with("screen:") => n.screen = screen, + _ => {} + } + } + _ => {} + } + } + n +} + +impl Monitor { + /// Keys of the drives, one per `drive_nums`: the first letter ("drive:C"), else the model. + fn drive_keys(&self) -> Vec<(u32, String)> { + let nums = self.drive_nums(); + let names: Vec = nums.iter().map(|&n| self.disk_letters(n).first().map_or_else(|| format!("#{}", clean(&self.drive_name(n))), |c| (*c as char).to_string())).collect(); + nums.into_iter().zip(numbered(&names)).map(|(n, k)| (n, format!("drive:{k}"))).collect() + } + + fn screen_keys(&self) -> Vec { + let names: Vec = (0..self.screen_count()) + .map(|i| { + let hw = self.det.hw.displays.get(i).map(|d| clean(&d.name)).filter(|n| !n.is_empty()); + hw.or_else(|| self.det.deep.st.screens.get(i).map(|s| clean(&s.name))).unwrap_or_default() + }) + .collect(); + numbered(&names).into_iter().map(|k| format!("screen:{k}")).collect() + } + + fn dev_key(&self, d: Dev) -> Option { + Some(match d { + Dev::Cpu => "cpu".into(), + Dev::Mem => "memory".into(), + Dev::Gpu => "gpu".into(), + Dev::Net => "net".into(), + Dev::Battery => "battery".into(), + Dev::Bluetooth => "bluetooth".into(), + Dev::Addons => "addons".into(), + Dev::Disk(n) => self.drive_keys().into_iter().find(|x| x.0 == n)?.1, + Dev::Display(i) => self.screen_keys().into_iter().nth(i as usize)?, + }) + } + + fn dev_of(&self, k: &str) -> Option { + Some(match k { + "cpu" => Dev::Cpu, + "memory" => Dev::Mem, + "gpu" if self.has_gpu() => Dev::Gpu, + "net" => Dev::Net, + "battery" if self.snap.battery.is_some() => Dev::Battery, + _ if k.starts_with("drive:") => Dev::Disk(self.drive_keys().into_iter().find(|x| x.1 == k)?.0), + _ if k.starts_with("screen:") => Dev::Display(self.screen_keys().iter().position(|x| x == k)? as u32), + _ => return None, + }) + } + + fn unit_keys(&self, a: Addon) -> Vec { + numbered(&addonpage::units(a, self.addons()).iter().map(|u| clean(&u.name)).collect::>()) + } + + /// The id of an item (None: it has no name that lasts). + pub(super) fn item_id(&self, it: &Item) -> Option { + Some(match it { + Item::Counts => "counts".into(), + Item::Vram => "vram".into(), + Item::Sec(s) => format!("sec|{}", SECS.iter().find(|x| x.0 == *s)?.1), + Item::Chart(d) => format!("chart|{}", self.dev_key(*d)?), + Item::Part(d) => format!("part|{}", self.dev_key(*d)?), + Item::Card(d, c) => format!("card|{}|{}", self.dev_key(*d)?, card_key(*c)?), + Item::Fact(d, c, k) => format!("fact|{}|{}|{}", self.dev_key(*d)?, card_key(*c)?, clean(k)), + Item::Drive(n) => format!("drive|{}", self.dev_key(Dev::Disk(*n))?), + Item::Screen(i) => format!("screen|{}", self.dev_key(Dev::Display(*i))?), + Item::Net(i) => { + let a = self.det.adapters.get(*i)?; + format!("net|{}", if a.guid.is_empty() { clean(&a.alias) } else { a.guid.clone() }) + } + Item::Bt(i) => { + let d = self.bt().get(*i)?; + format!("bt|{}", if d.id.is_empty() { clean(&d.name) } else { clean(&d.id) }) + } + Item::Addon(a) => format!("addon|{}", a.key()), + Item::Unit(a, i) => format!("unit|{}|{}", a.key(), self.unit_keys(*a).get(*i)?), + Item::Recent => "recent".into(), + }) + } + + /// The item an id stands for; None when its device is not there now. + pub(super) fn item_of(&self, id: &str) -> Option { + let p: Vec<&str> = id.split('|').collect(); + let addon = |k: &str| ADDONS.iter().copied().find(|a| a.key() == k).filter(|a| self.addons_on.has(*a)); + Some(match p.as_slice() { + ["counts"] => Item::Counts, + ["vram"] if self.det.vram_total > 0 && self.snap.vram_used.is_some() => Item::Vram, + ["sec", k] => { + let s = SECS.iter().find(|x| x.1 == *k)?.0; + let there = match s { + Sec::Gpu => self.has_gpu(), + Sec::Bt => self.has_bt(), + Sec::Addons => self.has_addons(), + _ => true, + }; + if !there { + return None; + } + Item::Sec(s) + } + ["chart", d] => Item::Chart(self.dev_of(d)?), + ["part", d] => Item::Part(self.dev_of(d)?), + ["card", d, c] => Item::Card(self.dev_of(d)?, card_of(c)?), + ["fact", d, c, k] => Item::Fact(self.dev_of(d)?, card_of(c)?, (*k).to_string()), + ["drive", d] => match self.dev_of(d)? { + Dev::Disk(n) => Item::Drive(n), + _ => return None, + }, + ["screen", d] => match self.dev_of(d)? { + Dev::Display(i) => Item::Screen(i), + _ => return None, + }, + ["net", k] => Item::Net(self.det.adapters.iter().position(|a| a.guid == *k || a.guid.is_empty() && clean(&a.alias) == *k)?), + ["bt", k] if self.bt_on => Item::Bt(self.bt().iter().position(|d| clean(&d.id) == *k || d.id.is_empty() && clean(&d.name) == *k)?), + ["addon", k] => Item::Addon(addon(k)?), + ["unit", a, k] => { + let a = addon(a)?; + Item::Unit(a, self.unit_keys(a).iter().position(|x| x == k)?) + } + ["recent"] => { + addon("privacy")?; + Item::Recent + } + _ => return None, + }) + } + + /// The picked items from the settings. + pub fn set_hover_more(&mut self, ids: &[String]) { + self.hover_more = ids.iter().map(|x| intern(x)).collect(); + } + + /// The "show in hover" button of `it`: 24 px, ending at `right`, its top at `t`. + pub(super) fn pin(&mut self, it: Item, right: i32, t: i32) { + if let Some(id) = self.item_id(&it) { + let b = self.sc(24); + self.hits.push((Rect { l: right - b, t, r: right, b: t + b }, Hit::HoverItem(intern(&id)))); + } + } + + /// The same at a card's top right corner, on its title line. + pub(super) fn pin_card(&mut self, it: Item, r: Rect) { + self.pin(it, r.r - self.sc(12), r.t + self.sc(12)); + } + + /// The buttons on a card's facts (seen when the pointer is on the fact, or when it is picked). + pub(super) fn pin_facts(&mut self, d: Dev, c: Card, r: Rect) { + for (tile, k) in self.fact_rects(c, r) { + let Some(id) = self.item_id(&Item::Fact(d, c, k.to_string())) else { continue }; + let n = intern(&id); + let b = self.sc(24); + self.fact_tiles.push((tile, n)); + self.hits.push((Rect { l: tile.r - b - self.sc(2), t: tile.t + self.sc(1), r: tile.r - self.sc(2), b: tile.t + self.sc(1) + b }, Hit::HoverFact(n))); + } + } +} + +/// One drawn piece of the hover window: an item, two small ones side by side, or a run of facts. +struct Block { + items: Vec, + r: Rect, +} + +/// Space between blocks and card padding of a run of facts (DIP). +const GAP: i32 = 8; +const FACT_PAD: i32 = 10; +/// Chart and part card heights (DIP). +const CHART_H: i32 = 180; +const PART_H: i32 = 170; + +/// The picked items as the hover window draws them. +pub struct Board { + m: Monitor, + fonts: Option<(u32, crate::look::Look, crate::settings_ui::Fonts)>, + blocks: Vec, + /// Extra history of each device shown (the page keeps only the open one's). + hist: HashMap>>, + /// Content height, px (0 = nothing to show). + pub h: i32, + /// The screen whose refresh is measured while the window is open. + pub screen: Option, +} + +impl Default for Board { + fn default() -> Self { + let mut m = Monitor::new(); + m.in_hover = true; + m.view = None; + m.motion = false; + Board { m, fonts: None, blocks: Vec::new(), hist: HashMap::new(), h: 0, screen: None } + } +} + +impl Drop for Board { + fn drop(&mut self) { + if let Some((_, _, f)) = self.fonts.take() { + f.free(); + } + } +} + +fn half(m: &Monitor, it: &Item) -> bool { + match it { + Item::Vram => true, + Item::Bt(i) => m.bt().get(*i).is_some_and(|d| !btpage::per_bud(d)), + _ => false, + } +} + +/// Where a click on the item goes (None = the overview). +fn dev_for(it: &Item) -> Option { + match it { + Item::Counts => None, + Item::Vram => Some(Dev::Gpu), + Item::Sec(s) => match s { + Sec::Cpu => Some(Dev::Cpu), + Sec::Mem => Some(Dev::Mem), + Sec::Gpu => Some(Dev::Gpu), + Sec::Net => Some(Dev::Net), + Sec::Bt => Some(Dev::Bluetooth), + Sec::Addons => Some(Dev::Addons), + _ => None, + }, + Item::Chart(d) | Item::Part(d) | Item::Card(d, _) | Item::Fact(d, ..) => Some(*d), + Item::Drive(n) => Some(Dev::Disk(*n)), + Item::Screen(i) => Some(Dev::Display(*i)), + Item::Net(_) => Some(Dev::Net), + Item::Bt(_) => Some(Dev::Bluetooth), + Item::Addon(_) | Item::Unit(..) | Item::Recent => Some(Dev::Addons), + } +} + +impl Board { + /// Take the sample the app just made (once per sample). + pub fn feed(&mut self, a: &App) { + let m = &mut self.m; + m.ms = a.m.s.interval_ms.max(100) as usize; + m.bt_on = a.m.s.mod_bluetooth; + m.addons_on = a.m.s.addons_on(); + m.icon_picks = [a.m.s.icon_mem, a.m.s.icon_gpu, a.m.s.icon_disk, a.m.s.icon_eth, a.m.s.icon_wifi, a.m.s.icon_net]; + m.warn = a.m.s.warn_pct; + m.crit = a.m.s.crit_pct; + m.range = a.popup_range; + m.snap = a.m.snap.clone(); + m.det = a.detail().clone(); + let copy = |x: Metric| a.m.hist[x.idx()].iter().copied().collect::>(); + m.h_cpu = copy(Metric::Cpu); + m.h_ram = copy(Metric::Ram); + m.h_gpu = copy(Metric::Gpu); + m.h_vram = copy(Metric::Vram); + m.h_dact = copy(Metric::DiskActive); + m.h_down = copy(Metric::Down); + m.h_up = copy(Metric::Up); + (m.days, m.month) = usage_days(a); + if m.fed != a.m.samples { + m.fed = a.m.samples; + push_detail(&mut m.cores, &mut m.kern, &mut m.engines, &mut m.disks, &mut m.nets, &m.det); + self.push_hist(); + } + } + + /// One more sample of each shown device's own history. + fn push_hist(&mut self) { + let mut devs: Vec = self.blocks.iter().flat_map(|b| &b.items).filter_map(dev_for).collect(); + devs.sort_by_key(|d| format!("{d:?}")); + devs.dedup(); + self.hist.retain(|d, _| devs.contains(d)); + for d in devs { + let mut h = self.hist.remove(&d).unwrap_or_default(); + std::mem::swap(&mut self.m.dp.hist, &mut h); + if !matches!(d, Dev::Display(i) if self.m.det.deep.measured != Some(i)) { + self.m.push_dev(d); + } + std::mem::swap(&mut self.m.dp.hist, &mut h); + self.hist.insert(d, h); + } + } + + /// Lay the items out in a column `w` px wide; sets `h`. + pub fn layout(&mut self, ids: &[String], dpi: u32, w: i32) { + let look = crate::look::current(); + if self.fonts.as_ref().is_none_or(|f| f.0 != dpi || f.1 != look) { + if let Some((_, _, f)) = self.fonts.take() { + f.free(); + } + let f = crate::settings_ui::Fonts::for_look(dpi, look); + self.m.tab_font = f.view().small; + self.m.semi_font = f.view().semi; + (self.m.num_font, self.m.num_sm_font) = f.nums(); + self.fonts = Some((dpi, look, f)); + } + self.m.dpi = dpi; + self.blocks.clear(); + let mut items: Vec = ids.iter().filter_map(|id| self.m.item_of(id)).collect(); + items.retain(|it| self.shows(it)); + self.screen = items.iter().find_map(|it| match it { + Item::Screen(i) | Item::Chart(Dev::Display(i)) | Item::Card(Dev::Display(i), _) | Item::Fact(Dev::Display(i), ..) => Some(*i), + _ => None, + }); + let gap = self.m.sc(GAP); + let mut y = 0; + let mut i = 0; + while i < items.len() { + if matches!(items[i], Item::Fact(..)) { + let n = items[i..].iter().take_while(|x| matches!(x, Item::Fact(..))).count(); + let h = self.facts_h(n); + self.blocks.push(Block { items: items[i..i + n].to_vec(), r: Rect { l: 0, t: y, r: w, b: y + h } }); + y += h + gap; + i += n; + continue; + } + // Two small cards in a row share the width; a lone one takes it all. + if half(&self.m, &items[i]) && items.get(i + 1).is_some_and(|n| half(&self.m, n)) { + let cw = (w - gap) / 2; + let h = self.height(&items[i], cw).max(self.height(&items[i + 1], cw)); + self.blocks.push(Block { items: vec![items[i].clone()], r: Rect { l: 0, t: y, r: cw, b: y + h } }); + self.blocks.push(Block { items: vec![items[i + 1].clone()], r: Rect { l: cw + gap, t: y, r: w, b: y + h } }); + y += h + gap; + i += 2; + continue; + } + let h = self.height(&items[i], w); + self.blocks.push(Block { items: vec![items[i].clone()], r: Rect { l: 0, t: y, r: w, b: y + h } }); + y += h + gap; + i += 1; + } + self.h = (y - gap).max(0); + } + + /// The item has something to draw (a fact still reported, a part with a card). + fn shows(&mut self, it: &Item) -> bool { + match it { + Item::Part(d) => { + self.m.view = Some(*d); + let ok = self.m.part_info().is_some(); + self.m.view = None; + ok + } + Item::Fact(d, c, k) => self.fact(*d, *c, k).is_some(), + _ => true, + } + } + + /// A fact's value now. + fn fact(&mut self, d: Dev, c: Card, k: &str) -> Option { + self.m.view = Some(d); + let v = self.m.card_facts(c).into_iter().find(|x| clean(x.0) == k).map(|x| x.1); + self.m.view = None; + v + } + + fn facts_h(&self, n: usize) -> i32 { + let rows = n.div_ceil(2) as i32; + self.m.sc(2 * FACT_PAD) + rows * self.m.sc(48) + (rows - 1) * self.m.sc(8) + } + + fn height(&mut self, it: &Item, w: i32) -> i32 { + let m = &mut self.m; + match it { + Item::Counts => self.facts_h(4), + Item::Vram => m.sc(150), + Item::Sec(s) => m.need_h(*s, w), + Item::Chart(_) => m.sc(CHART_H), + Item::Part(_) => m.sc(PART_H), + Item::Card(d, c) => { + m.view = Some(*d); + let h = m.card_h(*c, w); + m.view = None; + h + } + Item::Fact(..) => self.facts_h(1), + Item::Drive(_) => m.drive_card_h() - m.sc(22), + Item::Screen(_) => m.screen_card_h() - m.sc(22), + Item::Net(_) => m.sc(16 + 72 + 8), + Item::Bt(_) => m.sc(btpage::TILE_H), + Item::Addon(_) => m.sc(addonpage::TILE_H), + Item::Unit(..) => m.sc(addonpage::CARD_H), + Item::Recent => m.sc(46) + addonpage::recent_rows(m.addons()).len().max(1) as i32 * m.sc(30) + m.sc(8), + } + } + + /// Draw the blocks that meet `lim` with the column's top left at (x, y). Returns what each + /// shown block opens when clicked. + pub fn draw(&mut self, cv: &mut Canvas, x: i32, y: i32, lim: Rect, dark: bool, hover: Option<(i32, i32)>) -> Vec<(Rect, Option)> { + let col = crate::settings_ui::view_colors(dark); + let Some(f) = self.fonts.as_ref().map(|f| f.2.view()) else { return Vec::new() }; + let mut out = Vec::new(); + let blocks = std::mem::take(&mut self.blocks); + for b in &blocks { + let r = Rect { l: b.r.l + x, t: b.r.t + y, r: b.r.r + x, b: b.r.b + y }; + if r.b <= lim.t || r.t >= lim.b { + continue; + } + let Some(first) = b.items.first() else { continue }; + let dev = dev_for(first); + out.push((r, dev)); + self.draw_block(cv, &b.items, r, &f, &col); + if hover.is_some_and(|(hx, hy)| r.contains(hx, hy)) { + let rad = self.m.scf(crate::look::current_card_radius() as f32); + cv.stroke_round(r, rad, col.card_border.mix(col.dim, 0.55)); + } + } + self.blocks = blocks; + out + } + + fn draw_block(&mut self, cv: &mut Canvas, items: &[Item], r: Rect, f: &Fonts, col: &Colors) { + let Some(it) = items.first() else { return }; + // What the page's drawing code reads: the device on "its page" and that device's history. + let dev = match it { + Item::Chart(d) | Item::Part(d) | Item::Card(d, _) => Some(*d), + Item::Screen(i) if self.m.det.deep.measured == Some(*i) => Some(Dev::Display(*i)), + Item::Addon(_) => Some(Dev::Addons), + _ => None, + }; + if matches!(it, Item::Fact(..) | Item::Counts) { + let list: Vec<(String, String)> = if *it == Item::Counts { + let (s, d) = (&self.m.snap, &self.m.det); + vec![ + ("UP TIME".into(), fmt::duration(s.uptime_secs)), + ("PROCESSES".into(), if d.processes > 0 { d.processes.to_string() } else { s.proc_count.to_string() }), + ("THREADS".into(), group(d.threads as u64)), + ("HANDLES".into(), group(d.handles as u64)), + ] + } else { + items + .iter() + .filter_map(|x| match x { + Item::Fact(d, c, k) => Some((format!("{} \u{00B7} {k}", self.m.fact_owner(*d)), self.fact(*d, *c, k).unwrap_or_else(|| "--".into()))), + _ => None, + }) + .collect() + }; + let d = draw_for(&self.m, f, col); + d.card(cv, r); + let p = d.s(FACT_PAD); + let list: Vec<(&str, String)> = list.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(); + d.kv_grid(cv, r.l + p, r.t + p, r.w() - 2 * p, if list.len() == 1 { 1 } else { 2 }, &list); + return; + } + if let Some(d) = dev { + self.m.view = Some(d); + std::mem::swap(&mut self.m.dp.hist, self.hist.entry(d).or_default()); + } + if matches!(it, Item::Chart(_)) { + self.m.dp.chart = r; + } + let d = draw_for(&self.m, f, col); + match it { + Item::Vram => d.vital(cv, Vit::Vram, r), + Item::Sec(s) => { + d.card(cv, r); + match s { + Sec::Cpu => d.cpu(cv, r), + Sec::Mem => d.mem(cv, r), + Sec::Gpu => d.gpu(cv, r), + Sec::Disk => d.disks(cv, r), + Sec::Net => d.nets(cv, r), + Sec::Sys => d.system(cv, r), + Sec::Bt => d.bt_card(cv, r), + Sec::Addons => d.addons_card(cv, r), + Sec::Procs => {} + } + } + Item::Chart(_) => d.hero_chart(cv, r), + Item::Part(_) => d.part_card(cv, r), + Item::Card(_, c) => { + d.card(cv, r); + d.dev_card(cv, *c, r); + } + Item::Drive(n) => d.drive_card(cv, *n, r, r), + Item::Screen(i) => d.screen_card(cv, *i, r, r), + Item::Net(i) => { + d.card(cv, r); + d.adapter_row(cv, *i, r.l + d.s(16), r.r - d.s(16), r.t + d.s(14)); + } + Item::Bt(i) => { + if let Some(x) = self.m.bt().get(*i) { + d.bt_icon_tile(cv, x, r); + } + } + Item::Addon(a) => d.addon_tile(cv, *a, self.m.addons(), r), + Item::Unit(a, i) => { + if let Some(u) = addonpage::units(*a, self.m.addons()).get(*i) { + d.card(cv, r); + d.unit_card(cv, *a, u, r); + } + } + Item::Recent => { + d.card(cv, r); + d.recent_card(cv, self.m.addons(), r); + } + Item::Counts | Item::Fact(..) => {} + } + if let Some(d) = dev { + std::mem::swap(&mut self.m.dp.hist, self.hist.entry(d).or_default()); + self.m.view = None; + } + } +} + +fn draw_for<'a>(m: &'a Monitor, f: &'a Fonts, col: &Colors) -> Draw<'a> { + Draw { m, f, col: *col, dx: 0, dy: 0, hot: None, track: col.line, sub: col.fg.with_a(if col.dark { 10 } else { 14 }) } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::look::Look; + use crate::sensors::deep::addons::{Addons, On, Zone}; + use crate::sensors::deep::bluetooth::{BtDevice, Kind}; + use crate::settings::Settings; + use std::sync::Arc; + + /// A PC with a bit of everything: 16 cores, GPU, 2 drives, 2 screens of the same model, 2 + /// adapters, earbuds with per-bud levels, a mouse, every add-on on. + pub(super) fn machine() -> Monitor { + let mut m = Monitor::new(); + m.view = None; + m.det.core_pct = (0..16).map(|i| i as f32 * 6.0).collect(); + m.det.logical = 16; + m.det.cores = 8; + m.det.base_mhz = 4200.0; + m.det.cpu_name = "AMD Ryzen 7 9700X 8-Core Processor".into(); + m.det.engines = vec![("3D".into(), 41.0), ("Copy".into(), 2.0), ("VideoDecode".into(), 0.0)]; + m.det.vram_total = 16 << 30; + m.det.gpu_name = "NVIDIA GeForce RTX 5080".into(); + m.det.commit = 30 << 30; + m.det.commit_limit = 80 << 30; + m.det.procs = (0..300).map(|i| ProcRow { pid: 100 + i, name: format!("process{i}.exe"), cpu: i as f32 / 100.0, mem: u64::from(i) << 20, io: f64::from(i) * 1e3, gpu: 0.0, threads: 8 }).collect(); + m.snap.cpu = 23.0; + m.snap.ram_pct = 44.0; + m.snap.ram_total = 64 << 30; + m.snap.ram_used = 28 << 30; + m.snap.gpu = Some(41.0); + m.snap.vram_used = Some(5 << 30); + m.snap.gpu_temp = Some(61.0); + m.snap.battery = Some(crate::sensors::Battery { percent: 80, charging: false, on_ac: true, secs_left: None }); + m.det.disks = (0..2).map(|i| crate::sensors::detail::DiskStat { name: format!("Disk {i}"), num: Some(i), active: 12.0, read: 4e6, write: 1e6, ..Default::default() }).collect(); + m.det.disks[0].letters = "C: D:".into(); + m.det.adapters = vec![ + crate::sensors::detail::NetStat { guid: "{aa}".into(), alias: "Ethernet".into(), connected: true, down: 2e6, up: 3e5, link_bps: 2_500_000_000, ..Default::default() }, + crate::sensors::detail::NetStat { guid: "{bb}".into(), alias: "Wi-Fi".into(), wifi: true, ..Default::default() }, + ]; + let hw = Arc::make_mut(&mut m.det.hw); + hw.os = "Windows 11 Pro".into(); + hw.host = "MINIPC".into(); + hw.drives = (0..2).map(|i| crate::sensors::hw::Drive { num: i, model: format!("Samsung 990 PRO {i}"), bus: "NVMe".into(), ssd: Some(true), size: 2 << 40, ..Default::default() }).collect(); + hw.vols = ["C:", "D:"].iter().map(|l| crate::sensors::hw::Vol { letter: (*l).into(), label: "Data".into(), total: 900 << 30, free: 300 << 30, disk: Some(0), ..Default::default() }).collect(); + hw.displays = (0..2).map(|i| crate::sensors::hw::Display { name: "LG ULTRAGEAR".into(), w: 2560, h: 1440, hz: 165.0, link: "DisplayPort".into(), primary: i == 0 }).collect(); + let bt = |id: &str, name: &str, kind: Kind| BtDevice { id: id.into(), name: name.into(), kind, connected: true, ..Default::default() }; + m.det.deep.bt = Arc::new(vec![ + BtDevice { left: Some(80), right: Some(75), case: Some(40), ..bt("{buds}", "WF-C510", Kind::Earbuds) }, + BtDevice { battery: Some(75), ..bt("{mx}", "MX Master 4", Kind::Mouse) }, + BtDevice { battery: Some(60), ..bt("{kb}", "MX Keys", Kind::Keyboard) }, + ]); + m.addons_on = On([true; 4]); + m.det.deep.addons = Arc::new(Addons { + on: m.addons_on, + zones: vec![Zone { name: "TZ00".into(), celsius: 48.0, limit_pct: Some(100.0), reasons: Some(0) }], + usb: (0..2) + .map(|_| crate::sensors::deep::speed::UsbDev { name: "USB drive".into(), kind: crate::sensors::deep::speed::UsbKind::Storage, can_ss: true, runs_ss: true, can_ssp: false, runs_ssp: false, uas: true, speed: 3 }) + .collect(), + ..Default::default() + }); + m.h_cpu = (0..600).map(|i| 30.0 + 20.0 * (i as f32 / 20.0).sin()).collect(); + m.h_ram = m.h_cpu.clone(); + m.h_gpu = m.h_cpu.clone(); + m.h_vram = m.h_cpu.iter().map(|v| v * 1e8).collect(); + m.h_down = m.h_cpu.iter().map(|v| v * 1e5).collect(); + m.h_up = m.h_cpu.iter().map(|v| v * 2e4).collect(); + m.days = vec![(3 << 30, 1 << 30); 14]; + m + } + + fn ready(m: &mut Monitor, dpi: u32) -> crate::settings_ui::Fonts { + let fs = crate::settings_ui::Fonts::for_look(dpi, Look::Lime); + m.tab_font = fs.view().small; + m.semi_font = fs.view().semi; + (m.num_font, m.num_sm_font) = fs.nums(); + m.dpi = dpi; + fs + } + + /// Ids of every button on every Monitor page. + fn all_ids(m: &mut Monitor, w: i32) -> Vec<(Option, String)> { + let mut out: Vec<(Option, String)> = Vec::new(); + let mut pages: Vec> = vec![None]; + pages.extend([Dev::Cpu, Dev::Mem, Dev::Gpu, Dev::Disk(0), Dev::Disk(1), Dev::Display(0), Dev::Display(1), Dev::Net, Dev::Battery, Dev::Bluetooth].map(Some)); + pages.extend(std::iter::repeat_n(Some(Dev::Addons), 5)); + let mut open = ADDONS.iter().copied().map(Some).collect::>(); + for p in pages { + m.close_dev(); + if let Some(d) = p { + m.open_dev(d); + } + if p == Some(Dev::Addons) { + m.addon_open = open.pop().flatten(); + } + m.layout(m.dpi, 0, w, 0); + for (_, h) in &m.hits { + if let Hit::HoverItem(n) | Hit::HoverFact(n) = h { + out.push((p, name(*n))); + } + } + } + m.close_dev(); + out + } + + /// Every card, chart, device and fact on every page has a button, its id says which item it + /// is on any later run, and settings keep it. + #[test] + fn every_page_has_buttons_and_ids_last() { + let mut m = machine(); + let fs = ready(&mut m, 96); + let ids = all_ids(&mut m, 1400); + for p in [None, Some(Dev::Cpu), Some(Dev::Mem), Some(Dev::Gpu), Some(Dev::Disk(0)), Some(Dev::Display(1)), Some(Dev::Net), Some(Dev::Battery), Some(Dev::Bluetooth), Some(Dev::Addons)] { + let n = ids.iter().filter(|x| x.0 == p).count(); + println!("{p:?}: {n} buttons"); + assert!(n >= 3, "{p:?} has {n} buttons"); + } + let has = |k: &str| ids.iter().any(|x| x.1 == k); + for k in [ + "bt|{buds}", "bt|{mx}", "bt|{kb}", "drive|drive:C", "drive|drive:#Samsung 990 PRO 1", "screen|screen:LG ULTRAGEAR", "screen|screen:LG ULTRAGEAR~2", "net|{aa}", "net|{bb}", "counts", "vram", + "sec|cpu", "sec|memory", "sec|gpu", "sec|disks", "sec|network", "sec|bluetooth", "sec|addons", "sec|pc", "chart|cpu", "chart|memory", "chart|gpu", "chart|net", "chart|battery", "chart|drive:C", + "chart|screen:LG ULTRAGEAR", "part|cpu", "part|gpu", "card|cpu|cores", "card|cpu|apps-cpu", "card|memory|sticks", "card|gpu|engines", "card|drive:C|drive-health", "card|net|path", "card|battery|now", + "fact|cpu|power|DPC", "fact|cpu|chip|BASE SPEED", "fact|memory|commit|HARD FAULTS", "fact|drive:C|drive-facts|RESPONSE", "addon|usb", "addon|privacy", "addon|thermal", "addon|reboot", "unit|usb|USB drive", + "unit|usb|USB drive~2", "unit|thermal|Zone TZ00", "unit|privacy|Microphone", "unit|privacy|Camera", "recent", + ] { + // DPC needs a counter value to be listed. + if k == "fact|cpu|power|DPC" { + continue; + } + assert!(has(k), "no button for {k}"); + } + // Every card a page shows is covered (all but the folder scan and the admin offer). + for d in [Dev::Cpu, Dev::Mem, Dev::Gpu, Dev::Disk(0), Dev::Display(0), Dev::Net, Dev::Battery] { + m.open_dev(d); + for c in m.cards_for(d) { + let k = m.item_id(&Item::Card(d, c)); + match c { + Card::Space | Card::Admin => assert!(k.is_none()), + _ => assert!(has(&k.unwrap()), "{d:?} {c:?} has no button"), + } + } + } + m.close_dev(); + // Ids survive a save and a load, and mean the same item on the "next run". + let mut s = Settings::default(); + for (_, id) in &ids { + if !s.hover_more.contains(id) { + s.hover_flip(id); + } + } + let again = Settings::from_text(&s.to_text()); + assert_eq!(again.hover_more, s.hover_more); + let next = machine(); + for id in &again.hover_more { + let it = next.item_of(id).unwrap_or_else(|| panic!("{id} not found again")); + assert_eq!(next.item_id(&it).as_deref(), Some(id.as_str())); + } + println!("{} items in all", again.hover_more.len()); + fs.free(); + } + + /// Order of devices does not matter, and one that is gone is skipped without a trace. + #[test] + fn missing_devices_are_skipped() { + let mut m = machine(); + Arc::make_mut(&mut m.det.deep.bt).reverse(); + m.det.adapters.reverse(); + let Some(Item::Bt(i)) = m.item_of("bt|{mx}") else { panic!("mouse not found") }; + assert_eq!(m.bt()[i].name, "MX Master 4"); + assert_eq!(m.item_of("net|{bb}"), Some(Item::Net(0))); + m.det.deep.bt = Arc::default(); + m.det.adapters.clear(); + m.det.disks.clear(); + for id in ["bt|{mx}", "net|{aa}", "drive|drive:C", "card|drive:C|drive-health", "fact|drive:C|drive-facts|MODEL", "nonsense", "card|cpu|nonsense", ""] { + assert_eq!(m.item_of(id), None, "{id}"); + } + m.bt_on = false; + assert_eq!(m.item_of("bt|{mx}"), None); + let mut b = Board::default(); + b.m = m; + b.layout(&["bt|{mx}".into(), "nonsense".into()], 96, 368); + assert_eq!((b.h, b.blocks.len()), (0, 0)); + } + + /// The sensor thread is asked only for what the picked items show. + #[test] + fn only_what_is_picked_is_read() { + let ids = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::>(); + assert_eq!(needs(&[], None), Needs::default()); + assert_eq!(needs(&ids(&["net|{aa}", "counts", "vram"]), None), Needs { detail: true, ..Needs::default() }); + assert_eq!(needs(&ids(&["bt|{mx}"]), None), Needs { detail: true, bt: true, ..Needs::default() }); + let n = needs(&ids(&["card|net|path"]), None); + assert!(n.ping && n.st && !n.app_net && !n.net); + assert!(needs(&ids(&["card|drive:C|drive-apps"]), None).app_disk); + assert!(!needs(&ids(&["card|drive:C|drive-health"]), None).app_disk); + assert_eq!(needs(&ids(&["chart|screen:LG"]), Some(1)).screen, Some(1)); + assert!(needs(&ids(&["unit|usb|x"]), None).addons); + } + + fn board(dpi: u32, ids: &[String]) -> Board { + let mut b = Board::default(); + b.m = machine(); + b.m.in_hover = true; + for _ in 0..60 { + let d = b.m.det.clone(); + push_detail(&mut b.m.cores, &mut b.m.kern, &mut b.m.engines, &mut b.m.disks, &mut b.m.nets, &d); + } + b.layout(ids, dpi, 368 * dpi as i32 / 96); + b + } + + /// Any number of items: one column, in order, nothing overlapping, as tall as it takes. + #[test] + fn no_limit_on_items() { + let mut m = machine(); + let fs = ready(&mut m, 96); + let mut ids: Vec = Vec::new(); + for (_, id) in all_ids(&mut m, 1400) { + if !ids.contains(&id) { + ids.push(id); + } + } + fs.free(); + assert!(ids.len() > 90, "{} items", ids.len()); + for dpi in [96, 144, 192] { + let b = board(dpi, &ids); + let shown: usize = b.blocks.iter().map(|x| x.items.len()).sum(); + assert_eq!(shown, ids.len(), "every item is in the window"); + assert!(b.h > 5000, "{} px", b.h); + assert_eq!(b.blocks.last().unwrap().r.b, b.h); + for p in b.blocks.windows(2) { + let side = p[1].r.t == p[0].r.t && p[1].r.l > p[0].r.r; + assert!(side || p[1].r.t > p[0].r.b, "{:?} then {:?}", p[0].items, p[1].items); + } + } + } + + /// Frame times of the hover window's picked items: 1 full redraw a second, and the strip a + /// scroll frame adds. Printed (run with --nocapture); a scroll frame must fit in 60 Hz. + #[test] + fn frame_times() { + assert!(crate::fonts::ready(), "bundled fonts did not load"); + let mut m = machine(); + let fs = ready(&mut m, 144); + let mut ids: Vec = Vec::new(); + for (_, id) in all_ids(&mut m, 1400) { + if !ids.contains(&id) { + ids.push(id); + } + } + fs.free(); + let mut b = board(144, &ids); + let mut cv = Canvas::new(); + // A 1440 p screen at 150 %: the tallest the window gets there. + let (w, h) = (368 * 144 / 96 + 36, 1360); + cv.resize(w, h); + let full = Rect { l: 0, t: 0, r: w, b: h }; + let time = |f: &mut dyn FnMut(i32), n: i32| { + let mut v: Vec = (0..n) + .map(|i| { + let t = std::time::Instant::now(); + f(i); + t.elapsed().as_secs_f32() * 1000.0 + }) + .collect(); + v.sort_by(f32::total_cmp); + (v.iter().sum::() / n as f32, v[(n as usize * 95 / 100).min(n as usize - 1)], v[n as usize - 1]) + }; + let span = b.h - h; + // Warm the glyph caches as the first paint does. + b.draw(&mut cv, 18, 0, full, true, None); + let a = time(&mut |i| drop(b.draw(&mut cv, 18, -(span * i / 120), full, true, None)), 120); + let mut y = 0; + let s = time( + &mut |_| { + // 40 px a frame: a fast wheel spin. + let d = 40; + y = (y + d) % span; + cv.shift_rows(full, -d); + let strip = Rect { t: h - d, ..full }; + cv.set_limit(Some(strip)); + b.draw(&mut cv, 18, -y, strip, true, None); + cv.set_limit(None); + }, + 400, + ); + let l = time(&mut |_| b.layout(&ids, 144, 368 * 144 / 96), 50); + println!("hover items {}: content {} px; full redraw avg {:.2} p95 {:.2} max {:.2} ms; scroll frame avg {:.2} p95 {:.2} max {:.2} ms; layout avg {:.2} ms", ids.len(), b.h, a.0, a.1, a.2, s.0, s.1, s.2, l.0); + // Debug builds are not what ships. + if !cfg!(debug_assertions) { + assert!(s.1 < 16.6, "scroll frame p95 {:.2} ms", s.1); + } + // RESMON_SHOT_DIR: save what the window shows, to look at. + if let Ok(dir) = std::env::var("RESMON_SHOT_DIR") { + let mut cv = Canvas::new(); + let step = 3000; + let save = |cv: &mut Canvas, file: String| { + let (w, h) = (cv.w, cv.h); + let px: Vec = cv.pixels().iter().flat_map(|p| p.to_le_bytes()).collect(); + let mut o: Vec = b"BM".to_vec(); + o.extend((54 + px.len() as u32).to_le_bytes()); + o.extend([0; 4]); + o.extend(54u32.to_le_bytes()); + o.extend(40u32.to_le_bytes()); + o.extend(w.to_le_bytes()); + o.extend((-h).to_le_bytes()); + o.extend(1u16.to_le_bytes()); + o.extend(32u16.to_le_bytes()); + o.extend([0; 24]); + o.extend(px); + let _ = std::fs::write(format!("{dir}/{file}.bmp"), o); + }; + for k in 0..(b.h + step - 1) / step { + cv.resize(w, step); + cv.clear(crate::look::tokens(true).bg); + b.draw(&mut cv, 18, 8 - k * step, Rect { l: 0, t: 0, r: w, b: step }, true, None); + save(&mut cv, format!("hover-{k}")); + } + // And the pages with their buttons, every other one picked. + let mut m = machine(); + let fs = ready(&mut m, 96); + for (k, id) in ids.iter().enumerate() { + if k % 2 == 0 { + m.hover_more.insert(intern(id)); + } + } + for (file, p, layout) in [ + ("overview", None, 1), ("cpu", Some(Dev::Cpu), 1), ("drives", Some(Dev::Disk(0)), 1), ("displays", Some(Dev::Display(0)), 1), ("net", Some(Dev::Net), 1), ("bt-list", Some(Dev::Bluetooth), 0), + ("bt-rack", Some(Dev::Bluetooth), 1), ("bt-hero", Some(Dev::Bluetooth), 2), ("addons", Some(Dev::Addons), 1), + ] { + m.close_dev(); + m.bt_layout = layout; + m.addon_open = Some(Addon::Usb); + if let Some(d) = p { + m.open_dev(d); + } + let h = m.layout(96, 16, 1184, 16) + 16; + cv.resize(1200, h); + cv.clear(crate::look::tokens(true).bg); + m.draw(&mut cv, &fs.view(), &crate::settings_ui::view_colors(true), 0, 0, h, None); + save(&mut cv, format!("page-{file}")); + } + fs.free(); + } + } +} diff --git a/src/popup.rs b/src/popup.rs index 3570eff..cff24c7 100644 --- a/src/popup.rs +++ b/src/popup.rs @@ -7,6 +7,7 @@ use crate::settings::Metric; use crate::taskbar::Edge; use crate::usage; use crate::util::*; +use std::cell::Cell; use std::collections::VecDeque; use windows_sys::Win32::Foundation::*; use windows_sys::Win32::Graphics::Dwm::*; @@ -17,7 +18,7 @@ use windows_sys::Win32::System::Threading::{ OpenProcess, QueryFullProcessImageNameW, TerminateProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, }; use windows_sys::Win32::UI::Controls::WM_MOUSELEAVE; -use windows_sys::Win32::UI::Input::KeyboardAndMouse::{TrackMouseEvent, TME_LEAVE, TRACKMOUSEEVENT}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, TrackMouseEvent, TME_LEAVE, TRACKMOUSEEVENT}; use windows_sys::Win32::UI::WindowsAndMessaging::*; const CLASS: &str = "ResourceMonitor.Popup"; @@ -259,6 +260,8 @@ pub enum PopupHit { Chart, /// Tiles as ring gauges (false) or lit part icons (true). TileStyle(bool), + /// A picked Monitor item: opens its device page (None = the overview). + Dev(Option), } const RANGES: [(&str, usize); 3] = [("1m", 60), ("5m", 300), ("1h", 3600)]; @@ -297,6 +300,9 @@ const PROCS: f32 = 36.0 + 5.0 * PROC_ROW + 4.0; const DIAL_A0: f32 = std::f32::consts::PI * 0.75; const DIAL_SPAN: f32 = std::f32::consts::PI * 1.5; +/// Between the window and the taskbar strip it opens from: the same px at every DPI. +const TASKBAR_GAP: i32 = 5; + fn has_space(a: &App) -> bool { a.snap.disk_used_pct.is_some() && a.snap.disk_total > 0 } @@ -326,7 +332,8 @@ fn gauge_metrics(a: &App) -> Vec { v } -fn size(a: &App) -> (i32, i32) { +/// Height of everything the window shows, px: it scrolls when that does not fit (`size`). +fn natural_h(a: &App) -> i32 { use crate::settings::*; let mut h = PAD + HEADER + PAD; let mut card = |v: f32| h += GAP + v; @@ -345,11 +352,78 @@ fn size(a: &App) -> (i32, i32) { if a.s.hover(HOVER_TOP) { card(PROCS); } - (sc(a, W), sc(a, h)) + let more = a.popup_board.as_ref().map_or(0, |b| b.h); + sc(a, h) + if more > 0 { sc(a, GAP) + more } else { 0 } +} + +fn size(a: &App) -> (i32, i32) { + let room = max_h(a).unwrap_or(i32::MAX); + (sc(a, W), natural_h(a).min(room)) +} + +/// Top of the part that scrolls (under the header), px at `scale`. +fn body_top(scale: f32) -> i32 { + ((PAD + HEADER + GAP / 2.0) * scale).round() as i32 +} + +/// Tallest the window may be next to the strip it opens from. +fn max_h(a: &App) -> Option { + let (anchor, tb, _) = a.anchor()?; + let center = POINT { x: (anchor.l + anchor.r) / 2, y: (anchor.t + anchor.b) / 2 }; + let work = crate::taskbar::monitor_info(unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONEAREST) }).map_or(tb.work, |m| m.1); + let docked = a.s.mode != crate::settings::Mode::Float; + Some(tallest(work, anchor, docked.then_some(tb.edge), sc(a, 10.0), TASKBAR_GAP, sc(a, 320.0))) +} + +/// Room for the window in the work area: `g` px from the screen's edges, `tg` from the taskbar it +/// is docked to (`edge`; None = a floating widget), never over the strip it opens from. `least` is +/// the height below which a floating widget's window goes beside it instead. +fn tallest(work: Rect, anchor: Rect, edge: Option, g: i32, tg: i32, least: i32) -> i32 { + let whole = work.h() - 2 * g; + let h = match edge { + // The strip can reach past the work area (an auto-hidden taskbar keeps no room). + Some(Edge::Bottom) => work.b.min(anchor.t) - tg - (work.t + g), + Some(Edge::Top) => (work.b - g) - (work.t.max(anchor.b) + tg), + Some(Edge::Left | Edge::Right) => whole, + None => { + let beside = (anchor.t - tg - (work.t + g)).max((work.b - g) - (anchor.b + tg)); + if beside >= least { + beside + } else { + whole + } + } + }; + // Some odd monitor set-up: still a window, inside the screen. + if h < 160 { + whole.max(160) + } else { + h + } +} + +/// Lay the picked items out again (a sample came, something was picked or taken out). +/// `feed`: take the sample the app just made. +pub fn update(a: &mut App, feed: bool) { + if a.m.s.hover_more.is_empty() { + a.popup_board = None; + return; + } + let fresh = a.popup_board.is_none(); + let mut b = a.popup_board.take().unwrap_or_default(); + if feed || fresh { + b.feed(a); + } + let dpi = (scale(a) * 96.0).round() as u32; + b.layout(&a.m.s.hover_more, dpi, sc(a, W) - 2 * sc(a, PAD)); + a.popup_board = Some(b); } pub fn reposition(a: &mut App) { + update(a, false); let (w, h) = size(a); + let max = natural_h(a) - h; + a.popup_scroll.set_max(max); let Some((x, y)) = place(a, w, h) else { return; }; @@ -362,7 +436,7 @@ pub fn reposition(a: &mut App) { /// Where a `w`×`h` box goes next to the taskbar strip: the hover popup's spot. /// The update window uses it too, so both sit in the same place. pub fn place(a: &App, w: i32, h: i32) -> Option<(i32, i32)> { - place_gap(a, w, h, 5) + place_gap(a, w, h, TASKBAR_GAP) } /// `place` with `tg` px between the box and the taskbar strip it sits next to. The incident flyout @@ -406,6 +480,8 @@ pub fn show(a: &mut App, pinned: bool) { a.popup_pinned = pinned; a.popup_acrylic = style_popup(a.popup, a.dark); a.popup_dark = a.dark; + a.popup_scroll.reset(); + a.popup_drag = None; reposition(a); unsafe { ShowWindow(a.popup, SW_SHOWNOACTIVATE) }; } @@ -414,6 +490,11 @@ pub fn hide(a: &mut App) { a.popup_pinned = false; a.popup_hover = None; a.popup_tracking = false; + if a.popup_drag.take().is_some() { + unsafe { ReleaseCapture() }; + } + crate::vsync::stop(crate::vsync::Clock::Popup); + a.popup_scrolling = false; if !a.popup.is_null() { unsafe { ShowWindow(a.popup, SW_HIDE) }; } @@ -431,6 +512,8 @@ struct Env<'a> { base: Pal, scale: f32, hover: Option<(i32, i32)>, + /// Where the scrolling part starts: what slid under the header is not under the pointer. + body_t: i32, /// Corner factor of small shapes (1 = the old rounding; the 2.32 looks scale it with their card radius). rk: f32, /// Chart window in samples. @@ -442,7 +525,7 @@ impl Env<'_> { (v * self.scale).round() as i32 } fn hot(&self, r: Rect) -> bool { - self.hover.is_some_and(|(x, y)| r.contains(x, y)) + self.hover.is_some_and(|(x, y)| r.contains(x, y) && (y >= self.body_t) == (r.b > self.body_t)) } } @@ -558,8 +641,8 @@ fn chart(c: &mut Canvas, e: &Env, out: &mut Out, r: Rect, kind: Kind, traces: &[ } let hit = Rect { t: r.t - e.sc(4.0), b: r.b + e.sc(4.0), ..r }; out.hits.push((hit, PopupHit::Chart)); - let Some((hx, hy)) = e.hover else { return }; - if !hit.contains(hx, hy) || raws.iter().all(|v| v.iter().all(|x| x.is_nan())) { + let Some((hx, _)) = e.hover else { return }; + if !e.hot(hit) || raws.iter().all(|v| v.iter().all(|x| x.is_nan())) { return; } // Nearest point to the mouse, and the column the chart draws it in. @@ -645,14 +728,37 @@ fn chip(c: &mut Canvas, f: HFONT, text: &str, x: &mut i32, min_x: i32, y: i32, h *x -= w + gap; } +thread_local! { + /// The next paint differs from the last one by the scroll offset alone. + static SCROLL_ONLY: Cell = const { Cell::new(false) }; +} + +/// Scroll bar of the window: track (its hit area) and thumb, when there is more than fits. +fn scrollbar(a: &App, w: i32, h: i32, scale: f32, wide: bool) -> Option<(Rect, Rect)> { + let sc = |v: f32| (v * scale).round() as i32; + if a.popup_scroll.max <= 0 { + return None; + } + let track = Rect { l: w - sc(PAD), t: body_top(scale) + sc(4.0), r: w, b: h - sc(8.0) }; + // The bar shows the scrolling part's share: the header does not scroll. + let view = h - body_top(scale); + let (t, th) = crate::scroll::thumb(track.h(), view, view + a.popup_scroll.max, a.popup_scroll.pos, sc(28.0)); + let bw = sc(if wide { 6.0 } else { 4.0 }); + let l = track.l + (track.w() - bw) / 2; + Some((track, Rect { l, t: track.t + t, r: l + bw, b: track.t + t + th })) +} + fn paint(a: &mut App, hwnd: HWND) { // Size can change (GPU appears, cap set…): keep window in sync. let (w, h) = size(a); + let scroll_only = SCROLL_ONLY.with(|f| f.replace(false)); if let Some(r) = window_rect(hwnd) { if r.w() != w || r.h() != h { reposition(a); } } + let max = natural_h(a) - size(a).1; + a.popup_scroll.set_max(max); // Theme switched while open: restyle the backdrop (acrylic tint, frame). if a.popup_dark != a.dark { a.popup_acrylic = style_popup(hwnd, a.dark); @@ -668,11 +774,41 @@ fn paint(a: &mut App, hwnd: HWND) { // Fonts and canvas are cached across the once-per-second repaints. let mut cache = a.popup_cache.take().filter(|(f, _)| f.scale == scale && f.look == crate::look::current()); let (f, mut c) = cache.take().unwrap_or_else(|| (Fonts::gray(scale), Canvas::new())); + let same = c.w == cw && c.h == ch; c.resize(cw, ch); - let mut out = Out { hits: std::mem::take(&mut a.popup_hits), tip: None }; - out.hits.clear(); - draw(a, &mut c, &f, scale, &mut out); - a.popup_hits = out.hits; + let body = Rect { l: 0, t: body_top(scale), r: cw, b: ch }; + let now = a.popup_scroll.px(); + let d = now - a.popup_drawn; + let mut board = a.popup_board.take(); + if scroll_only && same && d.abs() < body.h() / 2 && crate::looks::scroll_shift(crate::look::current()) { + // Only the scroll moved since the last frame: move the pixels, draw the strip that came in. + let _p = crate::perf::span("popup_scroll"); + if d != 0 { + c.shift_rows(body, -d); + let strip = if d > 0 { Rect { t: body.b - d, ..body } } else { Rect { b: body.t - d, ..body } }; + // The scroll bar sits in the right margin: redraw that column too. + let bar = Rect { l: cw - (PAD * scale).round() as i32, ..body }; + let hover = a.popup_hover.take(); + for lim in [strip, bar] { + c.set_limit(Some(lim)); + let mut out = Out::default(); + draw(a, &mut c, &f, scale, &mut out, board.as_deref_mut(), Some(lim)); + } + c.set_limit(None); + a.popup_hover = hover; + for (r, _) in a.popup_hits.iter_mut().filter(|x| x.0.b > body.t) { + r.t -= d; + r.b -= d; + } + } + } else { + let mut out = Out { hits: std::mem::take(&mut a.popup_hits), tip: None }; + out.hits.clear(); + draw(a, &mut c, &f, scale, &mut out, board.as_deref_mut(), None); + a.popup_hits = out.hits; + } + a.popup_board = board; + a.popup_drawn = now; c.blit(dc, 0, 0); a.popup_cache = Some((f, c)); unsafe { EndPaint(hwnd, &ps) }; @@ -759,21 +895,17 @@ fn value_row(c: &mut Canvas, f: &Fonts, x: i32, y: i32, max_w: i32, mark: &str, const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { +/// Draw the window; with `lim`, only what meets that strip of the scrolling part. +fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out, board: Option<&mut crate::monitor::hover::Board>, lim: Option) { let sc = |v: f32| (v * scale).round() as i32; let base = palette(a.dark); - // Metric colours drawn as text go through `legible` (a custom metric colour can be anything). let tk = crate::look::tokens(a.dark); - let ink = |col: Rgba| tk.legible(col, tk.panel); let pal = if a.popup_acrylic { translucent(palette(a.dark), a.dark) } else { palette(a.dark) }; let ms = a.s.interval_ms.max(1) as usize; let rk = if tk.look.is_new() { crate::looks::popup_style(tk.look).radius.map_or(1.0, |r| r as f32 / 10.0) } else { 1.0 }; - let e = Env { a, f, pal, base, scale, hover: a.popup_hover, rk, n: (a.popup_range * 1000 / ms).clamp(2, HIST) }; + let e = Env { a, f, pal, base, scale, hover: a.popup_hover, body_t: body_top(scale), rk, n: (a.popup_range * 1000 / ms).clamp(2, HIST) }; let pal = &e.pal; - let s = &a.snap; let pad = sc(PAD); - let gap = sc(GAP); - let right = c.w - pad; let rad = if tk.look.is_new() { crate::looks::popup_style(tk.look).radius.map_or(10.0, |r| r as f32) * scale } else { 10.0 * scale }; c.clear(pal.bg); if tk.look.is_new() { @@ -781,7 +913,36 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { crate::looks::decor(c, tk.look, &ctx); } - // ---- header: logo + name, range control, uptime (clock icon), battery + // Under the header everything scrolls. + let chip_h = sc(22.0); + let body = Rect { l: 0, t: e.body_t, r: c.w, b: c.h }; + if lim.is_none() { + header(a, c, f, scale, out, &e, &tk); + } + let head_hits = out.hits.len(); + c.set_clip(Some(body)); + draw_body(a, c, f, scale, out, &e, &tk, rad, chip_h, board, lim.unwrap_or(body)); + c.set_clip(None); + // Regions that slid under the header are not there to click. + for (r, _) in &mut out.hits[head_hits..] { + r.t = r.t.max(body.t); + r.b = r.b.max(r.t); + } + if let Some((_, thumb)) = scrollbar(a, c.w, c.h, scale, a.popup_drag.is_some() || a.popup_hover.is_some_and(|(x, y)| x >= c.w - pad && y >= body.t)) { + c.fill_round(thumb, thumb.w() as f32 / 2.0, pal.dim.with_a(if a.popup_drag.is_some() { 230 } else { 150 })); + } + if let Some(t) = out.tip.take() { + draw_tip(c, &e, &t); + } +} + +/// Logo + name, range control, uptime (clock icon), battery. +fn header(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out, e: &Env, tk: &crate::look::Tokens) { + let sc = |v: f32| (v * scale).round() as i32; + let pal = &e.pal; + let s = &a.snap; + let pad = sc(PAD); + let right = c.w - pad; // Two lines beside the logo: "Resource Monitor" over "by Emulsion Labs". let chip_h = sc(22.0); let logo = sc(HEADER); @@ -796,14 +957,14 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { // A click on the logo and name opens the Monitor page. out.hits.push((Rect { l: pad, t: pad, r: min_x - sc(4.0), b: pad + logo }, PopupHit::Monitor)); // The chips sit on the logo's centre line. - let mut y = pad + (logo - chip_h) / 2; + let y = pad + (logo - chip_h) / 2; let mut x = right; { // Segmented time-range control. let widths: Vec = RANGES.iter().map(|(t, _)| c.measure(f.small, t).0 + sc(16.0)).collect(); let total = widths.iter().sum::() + sc(4.0); let r = Rect { l: x - total, t: y, r: x, b: y + chip_h }; - if look_chip(c, &tk, scale, r, false, false).is_none() { + if look_chip(c, tk, scale, r, false, false).is_none() { c.fill_round(r, chip_h as f32 / 2.0, pal.chip); } let mut sx = r.l + sc(2.0); @@ -812,7 +973,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let on = a.popup_range == *secs; let mut sel_ink = None; if on { - sel_ink = look_chip(c, &tk, scale, seg, true, e.hot(seg)); + sel_ink = look_chip(c, tk, scale, seg, true, e.hot(seg)); if sel_ink.is_none() { c.fill_round(seg, seg.h() as f32 / 2.0, pal.fg.with_a(if a.dark { 46 } else { 34 })); } @@ -830,7 +991,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let segw = chip_h + sc(4.0); let r = Rect { l: x - segw * 2 - sc(4.0), t: y, r: x, b: y + chip_h }; if r.l >= min_x { - if look_chip(c, &tk, scale, r, false, false).is_none() { + if look_chip(c, tk, scale, r, false, false).is_none() { c.fill_round(r, chip_h as f32 / 2.0, pal.chip); } for (i, on) in [false, true].into_iter().enumerate() { @@ -838,7 +999,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let sel = a.s.tile_icons == on; let mut sel_ink = None; if sel { - sel_ink = look_chip(c, &tk, scale, seg, true, e.hot(seg)); + sel_ink = look_chip(c, tk, scale, seg, true, e.hot(seg)); if sel_ink.is_none() { c.fill_round(seg, seg.h() as f32 / 2.0, pal.fg.with_a(if a.dark { 46 } else { 34 })); } @@ -870,7 +1031,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let w = tw + icon + sc(5.0) + chip_h; if x - w >= min_x { let r = Rect { l: x - w, t: y, r: x, b: y + chip_h }; - if look_chip(c, &tk, scale, r, false, false).is_none() { + if look_chip(c, tk, scale, r, false, false).is_none() { c.fill_round(r, chip_h as f32 / 2.0, pal.chip); } let (icx, icy) = ((r.l + chip_h / 2) as f32 + icon as f32 / 2.0, (y + chip_h / 2) as f32); @@ -891,9 +1052,23 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { } else if let (Some(sec), false) = (b.secs_left, b.on_ac) { t.push_str(&format!(" \u{00B7} {}", fmt::duration(sec as u64))); } - chip(c, f.small, &t, &mut x, min_x, y, chip_h, sc(6.0), pal, (&tk, scale)); + chip(c, f.small, &t, &mut x, min_x, y, chip_h, sc(6.0), pal, (tk, scale)); } - y = pad + sc(HEADER) + gap; +} + +/// The cards under the header, scrolled; only those that meet `lim`. +#[allow(clippy::too_many_arguments)] +fn draw_body(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out, e: &Env, tk: &crate::look::Tokens, rad: f32, chip_h: i32, board: Option<&mut crate::monitor::hover::Board>, lim: Rect) { + let sc = |v: f32| (v * scale).round() as i32; + // Metric colours drawn as text go through `legible` (a custom metric colour can be anything). + let ink = |col: Rgba| tk.legible(col, tk.panel); + let pal = &e.pal; + let s = &a.snap; + let pad = sc(PAD); + let gap = sc(GAP); + let right = c.w - pad; + let vis = |t: i32, h: i32| t + h > lim.t && t < lim.b; + let mut y = pad + sc(HEADER) + gap - a.popup_scroll.px(); // ---- ring gauges: ring, label, one short line, sparkline struct Gauge { @@ -951,7 +1126,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let n = (gauges.len() as i32).max(1); let gw = (right - pad - gap * (n - 1)) / n; let gh = if gauges.is_empty() { -gap } else { sc(RINGS) }; - for (i, g) in gauges.iter().enumerate() { + for (i, g) in gauges.iter().enumerate().filter(|_| vis(y, gh)) { let x = pad + i as i32 * (gw + gap); let r = Rect { l: x, t: y, r: x + gw, b: y + gh }; card(c, r, rad, pal, e.hot(r), scale); @@ -971,7 +1146,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { }; let size = (54.0 * scale).min((gw - sc(16.0)) as f32); let lv = crate::liticon::Live { v: g.pct, cores: &a.detail().core_pct, ..live }; - crate::liticon::draw(c, glyph, cx - size / 2.0, (y + sc(6.0)) as f32, size, &lv, &an, &tk); + crate::liticon::draw(c, glyph, cx - size / 2.0, (y + sc(6.0)) as f32, size, &lv, &an, tk); c.numeral_center(f.mid, &v, cx as i32, y + sc(68.0) - vh / 2, a.heat_text(pal.fg, g.pct)); } else { let rr = 34.0 * scale; @@ -984,7 +1159,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let sub = c.ellipsize(f.small, &g.sub, gw - sc(16.0)); c.text_center(f.small, &sub, cx as i32, y + sc(99.0), g.sub_col); let cr = Rect { l: x + sc(12.0), t: y + sc(118.0), r: x + gw - sc(12.0), b: y + gh - sc(9.0) }; - chart(c, &e, out, cr, Kind::Pct, &[Trace { m: g.m, col: acc, tag: "" }], false); + chart(c, e, out, cr, Kind::Pct, &[Trace { m: g.m, col: acc, tag: "" }], false); } y += gh + gap; @@ -1001,6 +1176,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let up_c = accent(Metric::Up, a.dark); if a.s.hover(HOVER_NET) { let nh = sc(DIAL_CARD); + if vis(y, nh) { let r = Rect { l: pad, t: y, r: right, b: y + nh }; card(c, r, rad, pal, e.hot(r), scale); out.hits.push((r, PopupHit::NetSettings)); @@ -1008,7 +1184,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let (cx, cy) = ((pad + sc(10.0)) as f32 + dial_d as f32 / 2.0, (y + nh / 2) as f32); let size = (nh - sc(12.0)) as f32; let lv = crate::liticon::Live { down: log_frac(s.net_down), up: log_frac(s.net_up), ..live }; - crate::liticon::draw(c, pk.net, cx - size / 2.0, cy - size / 2.0, size, &lv, &an, &tk); + crate::liticon::draw(c, pk.net, cx - size / 2.0, cy - size / 2.0, size, &lv, &an, tk); } else { let (cx, cy) = ((pad + sc(10.0)) as f32 + dial_d as f32 / 2.0, (y + nh / 2) as f32); dial(c, cx, cy, 32.0 * scale, 5.5 * scale, log_frac(s.net_down), down_c, pal.track); @@ -1035,7 +1211,8 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { Trace { m: Metric::Down, col: down_c, tag: "\u{25BC}" }, Trace { m: Metric::Up, col: up_c, tag: "\u{25B2}" }, ]; - chart(c, &e, out, cr, Kind::Net, &tr, true); + chart(c, e, out, cr, Kind::Net, &tr, true); + } } y += nh + gap; } @@ -1044,6 +1221,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { // ---- disk: active-time dial, R/W values, mirror chart, drive cells let space = has_space(a); let dh = sc(DIAL_CARD + if space { DISK_SPACE } else { 0.0 }); + if vis(y, dh) { let r = Rect { l: pad, t: y, r: right, b: y + dh }; card(c, r, rad, pal, e.hot(r), scale); out.hits.push((r, PopupHit::ResMon)); @@ -1062,7 +1240,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { if icons { let size = 52.0 * scale; let lv = crate::liticon::Live { v: act, ..live }; - crate::liticon::draw(c, pk.disk, cx - size / 2.0, cy - sc(38.0) as f32, size, &lv, &an, &tk); + crate::liticon::draw(c, pk.disk, cx - size / 2.0, cy - sc(38.0) as f32, size, &lv, &an, tk); c.text_center(f.bold, &v, cx as i32, cy as i32 + sc(20.0) - vh / 2, a.heat_text(pal.fg, act)); } else { dial(c, cx, cy, 30.0 * scale, 6.0 * scale, act / 100.0, act_c, pal.track); @@ -1076,7 +1254,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { { let cr = Rect { l: chart_l, t: y + sc(14.0), r: right - sc(12.0), b: y + nh - sc(14.0) }; let tr = [Trace { m: Metric::DiskRead, col: rd_c, tag: "R" }, Trace { m: Metric::DiskWrite, col: wr_c, tag: "W" }]; - chart(c, &e, out, cr, Kind::Disk, &tr, true); + chart(c, e, out, cr, Kind::Disk, &tr, true); } if space { let drive = std::env::var("SystemDrive").ok().filter(|d| !d.is_empty()).unwrap_or_else(|| "C:".into()); @@ -1103,6 +1281,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { } } } + } y += dh + gap; } @@ -1110,6 +1289,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { // ---- data usage: today + month figures, 14-day stacked bars let cap = a.cycle_usage(); let uh = sc(USAGE) + if cap.is_some() { sc(CAP) } else { 0 }; + if vis(y, uh) { let r = Rect { l: pad, t: y, r: right, b: y + uh }; card(c, r, rad, pal, e.hot(r), scale); out.hits.push((r, PopupHit::UsageReport)); @@ -1209,12 +1389,14 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { c.meter(bar, (pct / 100.0).min(1.0) as f32, col, pal.track); c.text(f.small, &label, right - sc(14.0) - lw, by - sc(4.0), pal.dim); } + } y += uh + gap; } if a.s.hover(HOVER_TOP) { // ---- top processes: one list, CPU / Memory / Disk tabs, bars let ph = sc(PROCS); + if vis(y, ph) { card(c, Rect { l: pad, t: y, r: right, b: y + ph }, rad, pal, false, scale); c.text(f.caps, "TOP", ix, y + sc(14.0), pal.dim); let tabs: [(&str, Rgba); 3] = [ @@ -1228,7 +1410,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let widths: Vec = tabs.iter().map(|(t, _)| c.measure(f.small, t).0 + dot + sc(5.0) + sc(18.0)).collect(); let total = widths.iter().sum::() + sc(4.0); let tr = Rect { l: right - sc(10.0) - total, t: y + sc(8.0), r: right - sc(10.0), b: y + sc(8.0) + chip_h }; - if look_chip(c, &tk, scale, tr, false, false).is_none() { + if look_chip(c, tk, scale, tr, false, false).is_none() { c.fill_round(tr, chip_h as f32 / 2.0, pal.chip); } let mut sx = tr.l + sc(2.0); @@ -1237,7 +1419,7 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { let on = i == sel; let mut sel_ink = None; if on { - sel_ink = look_chip(c, &tk, scale, seg, true, e.hot(seg)); + sel_ink = look_chip(c, tk, scale, seg, true, e.hot(seg)); if sel_ink.is_none() { c.fill_round(seg, seg.h() as f32 / 2.0, pal.fg.with_a(if a.dark { 46 } else { 34 })); } @@ -1297,10 +1479,14 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out) { c.text_right(f.small, text, inner_r, mid - nh / 2, pal.dim); } } - } - if let Some(t) = out.tip.take() { - draw_tip(c, &e, &t); + y += ph + gap; + } + + // ---- everything else picked on the Monitor pages, in the order it was picked + if let Some(b) = board { + let at = e.hover.filter(|p| p.1 >= e.body_t); + out.hits.extend(b.draw(c, pad, y, lim, a.dark, at).into_iter().map(|(r, d)| (r, PopupHit::Dev(d)))); } } @@ -1332,12 +1518,17 @@ fn on_mouse_move(hwnd: HWND, l: LPARAM) { a.popup_tracking = unsafe { TrackMouseEvent(&mut t) } != 0; } let (x, y) = (get_x(l), get_y(l)); + if let Some(off) = a.popup_drag { + drag_to(a, hwnd, y - off); + return; + } // Repaint only when the hovered region (or the position inside a chart) changed. let key = |a: &App, p: Option<(i32, i32)>| { p.map(|(x, y)| { let i = hit_index(a, x, y); let in_chart = i.is_some_and(|i| a.popup_hits[i].1 == PopupHit::Chart); - (i, if in_chart { x } else { 0 }) + let bar = a.popup_scroll.max > 0 && x >= sc(a, W) - sc(a, PAD) && y >= body_top(scale(a)); + (i, if in_chart { x } else { 0 }, bar) }) }; let old = key(a, a.popup_hover); @@ -1370,7 +1561,7 @@ fn on_set_cursor(hwnd: HWND) -> bool { } let hand = matches!( hit_at(a, pt.x, pt.y, true), - Some(PopupHit::Range(_) | PopupHit::TopTab(_) | PopupHit::TaskMgr | PopupHit::ResMon | PopupHit::NetSettings | PopupHit::UsageReport | PopupHit::Monitor) + Some(PopupHit::Range(_) | PopupHit::TopTab(_) | PopupHit::TaskMgr | PopupHit::ResMon | PopupHit::NetSettings | PopupHit::UsageReport | PopupHit::Monitor | PopupHit::Dev(_)) ); unsafe { SetCursor(LoadCursorW(std::ptr::null_mut(), if hand { IDC_HAND } else { IDC_ARROW })) }; true @@ -1381,6 +1572,7 @@ fn on_click(hwnd: HWND, l: LPARAM) { match hit_at(a, get_x(l), get_y(l), true) { Some(PopupHit::Range(secs)) => { a.popup_range = secs; + update(a, true); unsafe { InvalidateRect(hwnd, std::ptr::null(), 0) }; } Some(PopupHit::TopTab(i)) => { @@ -1400,6 +1592,10 @@ fn on_click(hwnd: HWND, l: LPARAM) { hide(a); crate::settings_ui::open(a, crate::nav::Page::Monitor); } + Some(PopupHit::Dev(d)) => { + hide(a); + crate::settings_ui::open_dev(a, d); + } Some(PopupHit::UsageReport) => { hide(a); crate::report::open(a); @@ -1408,15 +1604,91 @@ fn on_click(hwnd: HWND, l: LPARAM) { } } -/// Repaint the panel if it is open (an icon setting changed elsewhere). +/// Repaint the panel if it is open (a setting changed elsewhere: an icon, what it shows). pub fn refresh() { if let Some(a) = crate::app::app() { if a.popup_open() { - unsafe { InvalidateRect(a.popup, std::ptr::null(), 0) }; + reposition(a); } } } +// ================================================================ scrolling + +/// The wheel over the window (it never has the focus: Windows sends the wheel to the window under +/// the pointer). +fn on_wheel(hwnd: HWND, delta: i32) { + let Some(a) = crate::app::app() else { return }; + let view = size(a).1 - body_top(scale(a)); + let step = crate::scroll::wheel_px(sc(a, 34.0), view); + if a.popup_drag.is_some() || !a.popup_scroll.wheel(delta, step, std::time::Instant::now()) { + return; + } + if !crate::settings_ui::animations_on() { + let t = a.popup_scroll.target; + a.popup_scroll.jump(t); + unsafe { InvalidateRect(hwnd, std::ptr::null(), 0) }; + return; + } + if !a.popup_scrolling { + a.popup_scrolling = true; + a.popup_scroll.begin(); + crate::vsync::start(crate::vsync::Clock::Popup, hwnd); + } +} + +/// One frame of the scroll. +fn on_frame(hwnd: HWND) { + if let Some(a) = crate::app::app() { + if a.popup_scrolling { + let was = a.popup_scroll.px(); + let busy = a.popup_scroll.tick(std::time::Instant::now()); + if !busy { + a.popup_scrolling = false; + crate::vsync::stop(crate::vsync::Clock::Popup); + } + // Something else asked for a repaint meanwhile, or it came to rest (hover follows now): + // the whole window. Else just the move. + let pending = unsafe { GetUpdateRect(hwnd, std::ptr::null_mut(), 0) } != 0; + if !busy || pending || was != a.popup_scroll.px() { + SCROLL_ONLY.with(|f| f.set(busy && !pending)); + unsafe { + InvalidateRect(hwnd, std::ptr::null(), 0); + UpdateWindow(hwnd); + } + SCROLL_ONLY.with(|f| f.set(false)); + } + } + } + crate::vsync::ack(crate::vsync::Clock::Popup); +} + +/// Press on the scroll bar: grab the thumb, or page toward the press. +fn on_down(hwnd: HWND, l: LPARAM) { + let Some(a) = crate::app::app() else { return }; + let (x, y) = (get_x(l), get_y(l)); + let (w, h) = size(a); + let Some((track, thumb)) = scrollbar(a, w, h, scale(a), true) else { return }; + if !track.contains(x, y) { + return; + } + let off = if y >= thumb.t && y < thumb.b { y - thumb.t } else { thumb.h() / 2 }; + a.popup_drag = Some(off); + unsafe { SetCapture(hwnd) }; + drag_to(a, hwnd, y - off); +} + +/// The thumb's top was dragged to client `top`. +fn drag_to(a: &mut App, hwnd: HWND, top: i32) { + let (w, h) = size(a); + if let Some((track, thumb)) = scrollbar(a, w, h, scale(a), true) { + let room = (track.h() - thumb.h()).max(1) as f32; + let to = ((top - track.t) as f32 / room).clamp(0.0, 1.0) * a.popup_scroll.max as f32; + a.popup_scroll.jump(to.round() as i32); + unsafe { InvalidateRect(hwnd, std::ptr::null(), 0) }; + } +} + fn on_right_click(l: LPARAM) { let row = crate::app::app().and_then(|a| match hit_at(a, get_x(l), get_y(l), true) { Some(PopupHit::Proc(pid)) => Some(pid), @@ -1614,7 +1886,30 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> DefWindowProcW(hwnd, msg, w, l) } } + WM_MOUSEWHEEL => { + on_wheel(hwnd, (w >> 16) as u16 as i16 as i32); + 0 + } + crate::vsync::WM_APP_FRAME => { + on_frame(hwnd); + 0 + } + WM_LBUTTONDOWN => { + on_down(hwnd, l); + 0 + } + WM_CAPTURECHANGED => { + if let Some(a) = crate::app::app() { + a.popup_drag = None; + } + 0 + } WM_LBUTTONUP => { + if crate::app::app().is_some_and(|a| a.popup_drag.take().is_some()) { + ReleaseCapture(); + InvalidateRect(hwnd, std::ptr::null(), 0); + return 0; + } on_click(hwnd, l); 0 } @@ -1636,6 +1931,44 @@ mod tests { crate::render::measure_text(f, s).0 } + /// Any number of items fits any screen: the window stops at the work area and scrolls. + #[test] + fn height_stops_at_the_work_area() { + // 2560 x 1440 at 150 %, taskbar 72 px at the bottom, strip inside it. + let work = Rect { l: 0, t: 0, r: 2560, b: 1368 }; + let strip = Rect { l: 1800, t: 1374, r: 2100, b: 1434 }; + let (g, tg, least) = (15, 5, 480); + let h = tallest(work, strip, Some(Edge::Bottom), g, tg, least); + assert_eq!(h, 1368 - 5 - 15, "5 px from the taskbar, the margin at the top"); + // Placed at the bottom limit it starts at the top margin and ends above the taskbar. + let top = work.b - tg - h; + assert_eq!(top, work.t + g); + // Taskbar on top, strip inside it. + let work2 = Rect { l: 0, t: 72, r: 2560, b: 1440 }; + let h = tallest(work2, Rect { l: 0, t: 6, r: 300, b: 66 }, Some(Edge::Top), g, tg, least); + assert_eq!(h, 1440 - 15 - 77); + // An auto-hidden taskbar keeps no work area: still clear of the strip. + let full = Rect { l: 0, t: 0, r: 2560, b: 1440 }; + assert_eq!(tallest(full, strip, Some(Edge::Bottom), g, tg, least), 1374 - 5 - 15); + // Taskbar on a side: the whole height. + assert_eq!(tallest(full, Rect { l: 0, t: 1000, r: 60, b: 1400 }, Some(Edge::Left), g, tg, least), 1410); + // A floating widget: the bigger side of it, or beside it when neither has room. + assert_eq!(tallest(full, Rect { l: 500, t: 900, r: 800, b: 940 }, None, g, tg, least), 900 - 5 - 15); + assert_eq!(tallest(full, Rect { l: 500, t: 400, r: 800, b: 1000 }, None, g, tg, least), 1410); + // A second monitor left of and above the first (negative coordinates). + let work3 = Rect { l: -1920, t: -300, r: 0, b: 740 }; + assert_eq!(tallest(work3, Rect { l: -600, t: 745, r: -300, b: 775 }, Some(Edge::Bottom), 10, tg, 320), 740 - 5 + 290); + // Content taller than that scrolls by exactly the rest; shorter content does not scroll. + let mut s = crate::scroll::Scroll::default(); + let content = 9000; + s.set_max(content - content.min(1348)); + assert_eq!(s.max, 9000 - 1348); + s.jump(i32::MAX); + assert_eq!(content - s.px(), 1348, "the last item ends at the window's end"); + s.set_max(700 - 700.min(1348)); + assert_eq!((s.max, s.px()), (0, 0)); + } + #[test] fn popup_text_fits_every_look() { assert!(crate::fonts::ready(), "bundled fonts did not load"); diff --git a/src/scroll.rs b/src/scroll.rs new file mode 100644 index 0000000..122270c --- /dev/null +++ b/src/scroll.rs @@ -0,0 +1,190 @@ +//! Smooth scrolling shared by the main window and the tray hover window: wheel notches ease out +//! and quick ones build speed, touchpads are followed closely, and the thumb shows where you are. +//! Pure maths (no window), so it is tested here. + +use std::time::Instant; +use windows_sys::Win32::UI::WindowsAndMessaging::{SystemParametersInfoW, SPI_GETWHEELSCROLLLINES}; + +/// Scroll smoothing (s): a notch eases out over ~0.2 s; touchpads follow closely. +pub const TAU: f32 = 0.065; +pub const TAU_PRECISE: f32 = 0.028; + +/// One frame of the ease toward `target`: the new position, and whether it is still moving. +/// Exponential: quick start, soft landing, the same at 60 or 144 Hz. +pub fn ease(pos: f32, target: f32, tau: f32, dt: f32) -> (f32, bool) { + let d = target - pos; + if d.abs() < 0.5 { + return (target, false); + } + let p = pos + d * (1.0 - (-dt / tau.max(0.005)).exp()); + if (target - p).abs() < 0.5 { + (target, false) + } else { + (p, true) + } +} + +/// What a wheel message means: how fast to follow it and how much to boost it. +/// `last` remembers the notch before (time, direction, boost). +pub fn wheel(last: &mut Option<(Instant, i32, f32)>, delta: i32, now: Instant) -> (f32, f32) { + // Precision touchpads send small deltas many times a second: follow them closely. A mouse + // wheel sends whole notches (120): ease each one out, and quick notches in a row build speed. + if delta % 120 != 0 { + return (TAU_PRECISE, 1.0); + } + let dir = delta.signum(); + let mut boost = 1.0f32; + if let Some((t, d, b)) = *last { + if d == dir && (now - t).as_secs_f32() < 0.09 { + boost = (b + 0.2).min(2.5); + } + } + *last = Some((now, dir, boost)); + (TAU, boost) +} + +/// Pixels per wheel notch: the user's "lines to scroll" (Mouse settings) times +/// a line, or a page when it is set to one screen at a time. +pub fn wheel_px(line: i32, page: i32) -> i32 { + let mut lines: u32 = 3; + // SAFETY: valid out pointer of the documented size. + unsafe { SystemParametersInfoW(SPI_GETWHEELSCROLLLINES, 0, &mut lines as *mut u32 as *mut core::ffi::c_void, 0) }; + if lines == u32::MAX { + return (page * 7 / 8).max(line); + } + line * lines.clamp(1, 20) as i32 +} + +/// Scroll bar thumb in a track `track` px tall for `view` px of `content`: (top, height). +pub fn thumb(track: i32, view: i32, content: i32, pos: f32, min: i32) -> (i32, i32) { + let h = ((track as i64 * view as i64 / content.max(1) as i64) as i32).max(min).min(track); + let max = (content - view).max(1) as f32; + (((track - h) as f32 * (pos / max).clamp(0.0, 1.0)).round() as i32, h) +} + +/// A scrolling view: where it is, where it is going. +#[derive(Default)] +pub struct Scroll { + /// Shown offset, px. + pub pos: f32, + /// Where it eases to, px. + pub target: i32, + /// Furthest offset (content minus view), px. + pub max: i32, + tau: f32, + last: Option<(Instant, i32, f32)>, + frame: Option, +} + +impl Scroll { + pub fn px(&self) -> i32 { + self.pos.round() as i32 + } + + /// Back to the top (the window opens). + pub fn reset(&mut self) { + *self = Scroll { max: self.max, ..Scroll::default() }; + } + + /// The content or the view changed size: never past the end. + pub fn set_max(&mut self, max: i32) { + self.max = max.max(0); + self.target = self.target.clamp(0, self.max); + self.pos = self.pos.clamp(0.0, self.max as f32); + } + + /// Wheel turned: keep adding to where the scroll is heading, so fast notches add up. + /// Returns whether there is anywhere to go. + pub fn wheel(&mut self, delta: i32, step: i32, now: Instant) -> bool { + let (tau, boost) = wheel(&mut self.last, delta, now); + self.tau = tau; + let px = (delta as f32 * step as f32 / 120.0 * boost).round() as i32; + self.target = (self.target - px).clamp(0, self.max); + self.moving() + } + + pub fn jump(&mut self, to: i32) { + self.target = to.clamp(0, self.max); + self.pos = self.target as f32; + } + + pub fn moving(&self) -> bool { + (self.target as f32 - self.pos).abs() >= 0.5 + } + + /// Motion starts now (the first frame has no frame before it). + pub fn begin(&mut self) { + self.frame = None; + } + + /// One animation frame; returns whether it still moves. + pub fn tick(&mut self, now: Instant) -> bool { + let dt = self.frame.map_or(1.0 / 60.0, |t| (now - t).as_secs_f32()).clamp(0.0, 0.1); + self.frame = Some(now); + let tau = if self.tau > 0.0 { self.tau } else { TAU }; + let (p, busy) = ease(self.pos, self.target as f32, tau, dt); + self.pos = p; + busy + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn ease_lands_exactly_and_never_overshoots() { + let mut p = 0.0f32; + let mut frames = 0; + loop { + let (n, busy) = ease(p, 500.0, TAU, 1.0 / 60.0); + assert!(n >= p && n <= 500.0); + p = n; + frames += 1; + if !busy { + break; + } + } + assert_eq!(p, 500.0); + assert!(frames > 4 && frames < 60, "{frames} frames"); + } + + #[test] + fn wheel_stops_at_both_ends() { + let mut s = Scroll::default(); + s.set_max(3000); + let t = Instant::now(); + assert!(!s.wheel(120, 90, t), "already at the top"); + assert!(s.wheel(-120, 90, t + Duration::from_millis(500))); + assert_eq!(s.target, 90); + for i in 0..100 { + s.wheel(-120, 90, t + Duration::from_millis(1000 + 500 * i)); + } + assert_eq!(s.target, 3000, "never past the end"); + s.jump(99999); + assert_eq!((s.target, s.px()), (3000, 3000)); + // Content got shorter (an item was taken out): pulled back inside. + s.set_max(40); + assert_eq!((s.target, s.px()), (40, 40)); + s.set_max(-5); + assert_eq!((s.target, s.px(), s.max), (0, 0, 0)); + } + + #[test] + fn quick_notches_build_speed_and_touchpads_do_not() { + let mut last = None; + let t = Instant::now(); + assert_eq!(wheel(&mut last, -120, t).1, 1.0); + assert!(wheel(&mut last, -120, t + Duration::from_millis(40)).1 > 1.0); + assert_eq!(wheel(&mut last, 120, t + Duration::from_millis(60)).1, 1.0, "turning back starts over"); + assert_eq!(wheel(&mut last, -13, t + Duration::from_millis(70)), (TAU_PRECISE, 1.0)); + } + + #[test] + fn thumb_covers_its_share() { + assert_eq!(thumb(400, 400, 800, 0.0, 32), (0, 200)); + assert_eq!(thumb(400, 400, 800, 400.0, 32), (200, 200), "at the end it touches the bottom"); + assert_eq!(thumb(400, 400, 400_000, 399_600.0, 32), (368, 32), "never thinner than the minimum"); + } +} diff --git a/src/sensors/deep/live.rs b/src/sensors/deep/live.rs index e422dd0..3a05a9c 100644 --- a/src/sensors/deep/live.rs +++ b/src/sensors/deep/live.rs @@ -6,7 +6,7 @@ //! pinging (two tiny ICMP echoes a second, on its own thread) so the outage log covers the //! whole session, not only the minutes the page was on screen. -use super::{addons, battery, bluetooth, cpu, etw, etw_disk, gpu, net, reader::Reader, refresh::Meter, smooth::Smooth, AppNet, DeepLive, Dev}; +use super::{addons, battery, bluetooth, cpu, etw, etw_disk, gpu, net, reader::Reader, refresh::Meter, smooth::Smooth, AppNet, DeepLive, Dev, Needs}; use std::sync::{Arc, Mutex}; use crate::sensors::pdh::{Counter, Query}; @@ -39,22 +39,6 @@ struct Counters { eng3d: Option, } -/// What a device kind needs attached. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Group { - Cpu, - Gpu, - Other, -} - -fn group(d: Dev) -> Group { - match d { - Dev::Cpu => Group::Cpu, - Dev::Gpu => Group::Gpu, - _ => Group::Other, - } -} - /// The ETW session for per-app bytes. Starting and stopping it can block for a second or /// two, so both happen on a short-lived thread, never on the sensor beat. enum Etw { @@ -124,7 +108,8 @@ impl Etw { #[derive(Default)] pub struct LiveSensors { - dev: Option, + /// Everything to read: the page's facts and the hover window's. + need: Needs, c: Counters, buf: Vec, rows: Vec<(String, f64)>, @@ -139,6 +124,8 @@ pub struct LiveSensors { conns: net::Conns, wlan: Option, net_age: f64, + /// Connections and Wi-Fi as last read (re-read every `NET_SECS`). + net_kept: Option<(Vec, Option)>, bats: Option, bat: Vec, etw: Etw, @@ -148,6 +135,8 @@ pub struct LiveSensors { net_smooth: Smooth, /// Per-(letter, app) disk rates averaged the same way. disk_smooth: Smooth<(u8, u32)>, + /// The Monitor page is not on screen, only the hover window (set before each sample). + pub hover_only: bool, /// The Bluetooth module is on (set before each sample). pub bt_on: bool, bt: std::sync::Arc>, @@ -168,30 +157,46 @@ fn utf16(s: &[u16]) -> String { } impl LiveSensors { - /// Attach the counters the open page needs (None = Monitor hidden or overview). - pub fn sync(&mut self, q: &Query, dev: Option) { - let was = self.dev.map(group); - let now = dev.map(group); - if dev.is_none() { + /// Attach the counters the open page (None = Monitor hidden or overview) and the hover + /// window's items need. + pub fn sync(&mut self, q: &Query, dev: Option, hover: Needs) { + let need = dev.map_or(Needs::default(), Needs::page).or(hover); + let was = self.need; + if !need.st { self.static_age = None; } - if dev != self.dev { - self.leave(self.dev, dev); - if dev == Some(Dev::Bluetooth) { - self.bt_now(); - } - if dev == Some(Dev::Addons) && self.addon_age.is_some() { - self.addon_age = Some(f64::MAX / 2.0); - } + // Stop what nothing needs any more. + if was.screen.is_some() && need.screen.is_none() { + self.meter.set(None); } - self.dev = dev; - if was == now { - return; + if was.bat && !need.bat { + self.bats = None; + self.bat.clear(); + } + if was.net && !need.net { + self.wlan = None; + self.net_kept = None; + } + if was.app_net && !need.app_net { + self.etw.stop(); + self.net_smooth.clear(); + } + if was.app_disk && !need.app_disk { + self.etw_disk.stop(); + self.disk_smooth.clear(); + } + // Just came on screen: read now, not when the slower beat is next due. + if need.bt && !was.bt { + self.bt_now(); + } + if need.addons && !was.addons && self.addon_age.is_some() { + self.addon_age = Some(f64::MAX / 2.0); } - self.c = Counters::default(); + self.need = need; let c = &mut self.c; - match now { - Some(Group::Cpu) => { + if was.cpu != need.cpu { + (c.freq, c.perf, c.intr, c.dpc, c.ctx, c.queue) = (None, None, None, None, None, None); + if need.cpu { c.freq = q.add(r"\Processor Information(*)\Processor Frequency"); c.perf = q.add(r"\Processor Information(*)\% Processor Performance"); c.intr = q.add(r"\Processor Information(_Total)\% Interrupt Time"); @@ -199,33 +204,14 @@ impl LiveSensors { c.ctx = q.add(r"\System\Context Switches/sec"); c.queue = q.add(r"\System\Processor Queue Length"); } - Some(Group::Gpu) => { + } + if was.gpu != need.gpu { + (c.ded, c.shr, c.eng3d) = (None, None, None); + if need.gpu { c.ded = q.add(r"\GPU Process Memory(*)\Dedicated Usage"); c.shr = q.add(r"\GPU Process Memory(*)\Shared Usage"); c.eng3d = q.add(r"\GPU Engine(*engtype_3D)\Utilization Percentage"); } - _ => {} - } - } - - /// Stop what only the page being left needed. - fn leave(&mut self, old: Option, new: Option) { - if matches!(old, Some(Dev::Display(_))) && !matches!(new, Some(Dev::Display(_))) { - self.meter.set(None); - } - if old == Some(Dev::Battery) { - self.bats = None; - self.bat.clear(); - } - if old == Some(Dev::Net) { - self.wlan = None; - self.etw.stop(); - self.net_smooth.clear(); - } - let drive = |d: Option| matches!(d, Some(Dev::Disk(_))); - if drive(old) && !drive(new) { - self.etw_disk.stop(); - self.disk_smooth.clear(); } } @@ -233,70 +219,70 @@ impl LiveSensors { pub fn sample(&mut self, elapsed: f64, disks: &[u32], out: &mut DeepLive) { self.bluetooth(elapsed); self.addons(elapsed); - let Some(dev) = self.dev else { - *out = DeepLive { st: self.reader.latest(), ping: self.pinger.as_ref().map(net::Pinger::snapshot), bt: self.bt.clone(), addons: self.addons.clone(), ..Default::default() }; - return; - }; - + let need = self.need; // Static facts: on open, every minute, and when the drive list changes. - let due = self.static_age.is_none_or(|a| a >= STATIC_SECS) || self.disks != disks; - if due { - self.static_age = Some(0.0); - self.disks = disks.to_vec(); - self.reader.request(disks); - } else if let Some(a) = &mut self.static_age { - *a += elapsed; - } - // Only the open page's fields are filled; the rest clear so a stale page never shows. - let old = std::mem::take(out); - out.dev = Some(dev); - out.st = self.reader.latest(); - out.ping = self.pinger.as_ref().map(net::Pinger::snapshot); - out.bt = self.bt.clone(); - out.addons = self.addons.clone(); - - match dev { - Dev::Cpu => self.cpu(out), - Dev::Gpu => self.gpu(out), - Dev::Display(i) => { - let gdi = out.st.screens.get(i as usize).map(|s| s.gdi.clone()); - self.meter.set(gdi.as_deref()); - out.measured_hz = super::refresh::tidy(self.meter.hz()); + if need.st { + let due = self.static_age.is_none_or(|a| a >= STATIC_SECS) || self.disks != disks; + if due { + self.static_age = Some(0.0); + self.disks = disks.to_vec(); + self.reader.request(disks); + } else if let Some(a) = &mut self.static_age { + *a += elapsed; } - Dev::Net => { - if self.pinger.is_none() { - self.pinger = Some(net::Pinger::start()); + } + if need.ping && self.pinger.is_none() { + self.pinger = Some(net::Pinger::start()); + } + // Only what is needed is filled; the rest clears so a stale page never shows. + *out = DeepLive { st: self.reader.latest(), ping: self.pinger.as_ref().map(net::Pinger::snapshot), bt: self.bt.clone(), addons: self.addons.clone(), ..Default::default() }; + if need.cpu { + self.cpu(out); + } + if need.gpu { + self.gpu(out); + } + if let Some(i) = need.screen { + let gdi = out.st.screens.get(i as usize).map(|s| s.gdi.clone()); + self.meter.set(gdi.as_deref()); + out.measured_hz = super::refresh::tidy(self.meter.hz()); + out.measured = Some(i); + } + if need.net { + self.net_age += elapsed; + match &self.net_kept { + Some((conns, wifi)) if self.net_age < NET_SECS => { + out.conns = conns.clone(); + out.wifi = wifi.clone(); } - self.net_age += elapsed; - if self.net_age >= NET_SECS || old.dev != Some(Dev::Net) { + _ => { self.net_age = 0.0; out.conns = self.conns.read(); out.wifi = self.wlan.get_or_insert_with(net::Wlan::new).read(); - } else { - out.conns = old.conns; - out.wifi = old.wifi; + self.net_kept = Some((out.conns.clone(), out.wifi.clone())); } - self.app_net(elapsed, out); } - Dev::Battery => { - if self.bats.is_none() { - let mut b = battery::Batteries::open(); - self.bat = b.statics(); - self.bats = Some(b); - } else if let Some(b) = &mut self.bats { - b.live(&mut self.bat); - } - out.batteries = self.bat.clone(); - } - Dev::Disk(_) => { - let (st, e) = self.etw_disk.poll(etw_disk::DiskEtw::start); - out.vol_apps_state = st; - out.vol_apps = match e { - Some(e) => smooth_disk(&mut self.disk_smooth, elapsed, e.take(elapsed)), - None => Vec::new(), - }; + } + if need.app_net { + self.app_net(elapsed, out); + } + if need.bat { + if self.bats.is_none() { + let mut b = battery::Batteries::open(); + self.bat = b.statics(); + self.bats = Some(b); + } else if let Some(b) = &mut self.bats { + b.live(&mut self.bat); } - Dev::Mem | Dev::Bluetooth | Dev::Addons => {} + out.batteries = self.bat.clone(); + } + if need.app_disk { + let (st, e) = self.etw_disk.poll(etw_disk::DiskEtw::start); + out.vol_apps_state = st; + out.vol_apps = match e { + Some(e) => smooth_disk(&mut self.disk_smooth, elapsed, e.take(elapsed)), + None => Vec::new(), + }; } } @@ -311,7 +297,11 @@ impl LiveSensors { } return; } - let every = if self.dev == Some(Dev::Addons) { ADDON_PAGE_SECS } else { ADDON_SECS }; + // Only the hover window is open and it shows no add-on: keep what there is. + if self.hover_only && !self.need.addons { + return; + } + let every = if self.need.addons { ADDON_PAGE_SECS } else { ADDON_SECS }; // An add-on was switched on or off: read again now. let changed = self.addons.on != self.addons_on; match &mut self.addon_age { @@ -338,7 +328,11 @@ impl LiveSensors { } return; } - let every = if self.dev == Some(Dev::Bluetooth) { BT_PAGE_SECS } else { BT_SECS }; + // Only the hover window is open and it shows no Bluetooth device: keep what there is. + if self.hover_only && !self.need.bt { + return; + } + let every = if self.need.bt { BT_PAGE_SECS } else { BT_SECS }; match &mut self.bt_age { Some(a) if *a + elapsed < every => *a += elapsed, _ => { diff --git a/src/sensors/deep/mod.rs b/src/sensors/deep/mod.rs index a130ed1..22e43b1 100644 --- a/src/sensors/deep/mod.rs +++ b/src/sensors/deep/mod.rs @@ -38,6 +38,18 @@ mod tests { assert_eq!(Dev::from_key("addons"), Some(Dev::Addons)); assert_eq!(Dev::from_key("drives"), Some(Dev::Disk(0))); } + + /// An open page and the hover window's items are read together; the page's screen wins. + #[test] + fn needs_add_up() { + use super::Needs; + let hover = Needs { detail: true, gpu: true, bt: true, screen: Some(1), ..Needs::default() }; + let both = Needs::page(Dev::Display(0)).or(hover); + assert!(both.gpu && both.bt && both.st && both.detail && !both.cpu && !both.ping); + assert_eq!(both.screen, Some(0)); + assert_eq!(Needs::default().or(hover), hover); + assert!(Needs::page(Dev::Net).ping && Needs::page(Dev::Net).app_net); + } } use std::sync::Arc; @@ -97,6 +109,68 @@ impl Dev { } } +/// Deep facts to read on a sample: the open device page's, plus whatever the items picked for +/// the tray hover window show while it is open. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Needs { + /// Something picked needs the Monitor detail at all. + pub detail: bool, + /// Per-core clocks, interrupts, queue. + pub cpu: bool, + /// GPU memory by app, fan, temperature. + pub gpu: bool, + /// Wi-Fi and connections. + pub net: bool, + /// The router / internet pinger. + pub ping: bool, + pub bat: bool, + /// Bytes per app (ETW, admin only): network, drives. + pub app_net: bool, + pub app_disk: bool, + /// Static facts (topology, drive health, screens, adapters). + pub st: bool, + /// Measure this screen's refresh. + pub screen: Option, + pub bt: bool, + pub addons: bool, +} + +impl Needs { + /// What a device page reads. + pub fn page(d: Dev) -> Needs { + let n = Needs { detail: true, st: true, ..Needs::default() }; + match d { + Dev::Cpu => Needs { cpu: true, ..n }, + Dev::Gpu => Needs { gpu: true, ..n }, + Dev::Net => Needs { net: true, ping: true, app_net: true, ..n }, + Dev::Battery => Needs { bat: true, ..n }, + Dev::Disk(_) => Needs { app_disk: true, ..n }, + Dev::Display(i) => Needs { screen: Some(i), ..n }, + Dev::Bluetooth => Needs { bt: true, ..n }, + Dev::Addons => Needs { addons: true, ..n }, + Dev::Mem => n, + } + } + + /// Both. The open page's screen is the one measured (`self` is the page). + pub fn or(self, o: Needs) -> Needs { + Needs { + detail: self.detail || o.detail, + cpu: self.cpu || o.cpu, + gpu: self.gpu || o.gpu, + net: self.net || o.net, + ping: self.ping || o.ping, + bat: self.bat || o.bat, + app_net: self.app_net || o.app_net, + app_disk: self.app_disk || o.app_disk, + st: self.st || o.st, + screen: self.screen.or(o.screen), + bt: self.bt || o.bt, + addons: self.addons || o.addons, + } + } +} + /// Health and extra facts of one physical drive. #[derive(Clone, Debug, Default)] pub struct DiskDeep { @@ -127,8 +201,6 @@ impl DeepStatic { /// Live values of the open device page, sampled with the detail once a second. #[derive(Clone, Debug, Default)] pub struct DeepLive { - /// The page these values are for. - pub dev: Option, pub st: Arc, // ---- CPU /// Effective clock per logical processor, MHz. @@ -147,8 +219,10 @@ pub struct DeepLive { /// (adapter LUID, sensor data). pub gpu_perf: Vec<(u64, gpu::PerfData)>, // ---- display - /// Measured refresh of the open screen, Hz (0 = not measured yet). + /// Measured refresh of `measured`, Hz (0 = not measured yet). pub measured_hz: f32, + /// The screen being measured. + pub measured: Option, // ---- network pub ping: Option, pub conns: Vec, diff --git a/src/sensors/detail.rs b/src/sensors/detail.rs index fe4bc13..86aad54 100644 --- a/src/sensors/detail.rs +++ b/src/sensors/detail.rs @@ -37,6 +37,8 @@ pub struct DiskStat { #[derive(Clone, Debug, Default)] pub struct NetStat { + /// Interface GUID as "{xxxxxxxx-...}": the same across renames and restarts. + pub guid: String, pub alias: String, pub description: String, pub connected: bool, diff --git a/src/sensors/mod.rs b/src/sensors/mod.rs index c83837a..ab786b6 100644 --- a/src/sensors/mod.rs +++ b/src/sensors/mod.rs @@ -130,6 +130,10 @@ pub struct SampleOpts { pub bt: bool, /// Add-ons that are on: read while the Monitor page is on screen. pub addons: deep::addons::On, + /// What the hover window's items need (with `detail`, while it is open). + pub hover: deep::Needs, + /// `detail` is for the hover window alone. + pub hover_only: bool, } /// Gap between the priming collection and the real one when counters were just attached: @@ -242,7 +246,12 @@ impl Sensors { self.gpu.sync(q, opts.gpu); self.disk.sync(q, opts.disk); self.detail.sync(q, opts.detail); - self.deep.sync(q, if opts.detail { opts.dev } else { None }); + if opts.detail { + self.deep.sync(q, opts.dev, opts.hover); + } else { + self.deep.sync(q, None, deep::Needs::default()); + } + self.deep.hover_only = opts.hover_only; self.deep.bt_on = opts.bt; self.deep.addons_on = opts.addons; // Counters just attached (app start, Monitor or a device page opening) have no diff --git a/src/sensors/net.rs b/src/sensors/net.rs index ebb7e0c..9a47cb1 100644 --- a/src/sensors/net.rs +++ b/src/sensors/net.rs @@ -216,7 +216,9 @@ impl NetDetail { } self.prev.insert(luid, (row.InOctets, row.OutOctets)); let connected = is_up(row); + let g = row.InterfaceGuid; out.push(super::detail::NetStat { + guid: format!("{{{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{}}}", g.data1, g.data2, g.data3, g.data4[0], g.data4[1], g.data4[2..].iter().map(|b| format!("{b:02x}")).collect::()), alias, description: description(row), connected, diff --git a/src/settings.rs b/src/settings.rs index 52b25ec..3d2e651 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -217,6 +217,9 @@ pub struct Settings { pub tile_icons: bool, /// What the tray hover window shows, a bit per `HOVER_ITEMS`. `hover_items = cpu, memory, …`. pub hover_items: u8, + /// Everything else picked for the hover window, in the order it was picked: ids made by + /// `monitor::hover` ("bt|{id}", "drive|C", "card|cpu|cores"). No limit. + pub hover_more: Vec, /// Icon picks, indexes into `liticon::*_CHOICES` (0 = auto where offered). pub icon_mem: u8, pub icon_gpu: u8, @@ -291,6 +294,7 @@ impl Default for Settings { bt_layout_set: false, tile_icons: false, hover_items: HOVER_ALL, + hover_more: Vec::new(), icon_mem: 0, icon_gpu: 0, icon_disk: 0, @@ -320,12 +324,68 @@ impl Settings { pub fn hover(&self, item: u8) -> bool { self.hover_items & (1 << item) != 0 } + + /// Put `id` in the hover window (at the end) or take it out. Returns whether it is in now. + pub fn hover_flip(&mut self, id: &str) -> bool { + match self.hover_more.iter().position(|x| x == id) { + Some(i) => { + self.hover_more.remove(i); + false + } + None => { + self.hover_more.push(id.to_string()); + true + } + } + } } fn hover_parse(v: &str) -> u8 { v.split(',').filter_map(|w| HOVER_ITEMS.iter().position(|k| k.eq_ignore_ascii_case(w.trim()))).fold(0, |m, i| m | 1 << i) } +/// Ids hold device names: anything that could split the list or the line is %XX. +fn id_encode(id: &str) -> String { + let mut o = String::with_capacity(id.len()); + for b in id.bytes() { + match b { + b'%' | b',' | b'=' | b';' | b'#' | b'"' | 0..=0x1F | 0x7F..=0xFF => o.push_str(&format!("%{b:02X}")), + _ => o.push(b as char), + } + } + o +} + +fn id_decode(t: &str) -> String { + let b = t.as_bytes(); + let mut o = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + let hex = if b[i] == b'%' { b.get(i + 1..i + 3) } else { None }; + match hex.and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok()) { + Some(v) => { + o.push(v); + i += 3; + } + None => { + o.push(b[i]); + i += 1; + } + } + } + String::from_utf8_lossy(&o).into_owned() +} + +fn more_parse(v: &str) -> Vec { + let mut out: Vec = Vec::new(); + for id in v.split(',').map(|t| id_decode(t.trim())).filter(|t| !t.is_empty()) { + if !out.contains(&id) { + out.push(id); + } + } + out +} + fn hover_text(m: u8) -> String { let on: Vec<&str> = HOVER_ITEMS.iter().enumerate().filter(|(i, _)| m & (1 << i) != 0).map(|(_, k)| *k).collect(); if on.is_empty() { @@ -445,6 +505,14 @@ impl Settings { Some(s) } + /// Settings from a settings file's text (tests). + #[cfg(test)] + pub fn from_text(txt: &str) -> Settings { + let mut s = Settings::default(); + s.apply(txt); + s + } + fn apply(&mut self, txt: &str) { for line in txt.lines() { let line = line.trim(); @@ -539,6 +607,7 @@ impl Settings { } "tile_style" => self.tile_icons = v.eq_ignore_ascii_case("icons"), "hover_items" => self.hover_items = hover_parse(v), + "hover_more" => self.hover_more = more_parse(v), "icon_memory" => self.icon_mem = choice(&crate::liticon::MEM_CHOICES, v).unwrap_or(self.icon_mem), "icon_gpu" => self.icon_gpu = choice(&crate::liticon::GPU_CHOICES, v).unwrap_or(self.icon_gpu), "icon_disk" => self.icon_disk = choice(&crate::liticon::DISK_CHOICES, v).unwrap_or(self.icon_disk), @@ -641,7 +710,7 @@ impl Settings { } /// The settings file's text (what `save` writes and `apply` reads back). - fn to_text(&self) -> String { + pub(crate) fn to_text(&self) -> String { let mut o = String::with_capacity(1024); o.push_str("# Resource Monitor settings. Edit freely; changes apply within a few seconds.\n"); o.push_str("# Booleans: 1/0. Delete this file to reset everything.\n\n"); @@ -780,6 +849,10 @@ impl Settings { "\n# Tray hover window: cpu, memory, gpu, disk, network, usage, top, battery (or none)\nhover_items = {}\n", hover_text(self.hover_items) )); + if !self.hover_more.is_empty() { + let v: Vec = self.hover_more.iter().map(|id| id_encode(id)).collect(); + o.push_str(&format!("# Anything else picked on the Monitor pages, in order\nhover_more = {}\n", v.join(", "))); + } if self.window.is_some() || !self.window_page.is_empty() { o.push_str("\n# Main window: x,y,width,height,maximized (screen pixels) and the last page\n"); if let Some(w) = &self.window { @@ -903,6 +976,34 @@ mod tests { back.apply(&s.to_text()); assert_eq!(back.hover_items, 0); } + + /// Any number of picked items, with whatever is in a device's name, comes back the same + /// and in the same order after a restart. + #[test] + fn hover_more_round_trip() { + let mut s = Settings::default(); + assert!(s.hover_more.is_empty()); + let names = ["bt|{0a1b-22}", "drive|C", "screen|LG 27\" = \"Ultra\", #1; 50%", "screen|\u{30C6}\u{30EC}\u{30D3}", "net|{GUID}", "fact|cpu|power|DPC", "usb|A, B"]; + for n in names { + assert!(s.hover_flip(n)); + } + for i in 0..500 { + assert!(s.hover_flip(&format!("card|drive-{i}|health"))); + } + let mut back = Settings::default(); + back.apply(&s.to_text()); + assert_eq!(back.hover_more, s.hover_more); + assert_eq!(&back.hover_more[..names.len()], &names[..]); + // Taking one out keeps the others in place; a second write has no trace of it. + assert!(!s.hover_flip("drive|C")); + let mut back = Settings::default(); + back.apply(&s.to_text()); + assert_eq!(back.hover_more.len(), names.len() + 499); + assert!(!back.hover_more.iter().any(|x| x == "drive|C")); + // A line edited by hand: blanks and repeats are dropped. + back.apply("hover_more = drive|C, , drive|C,net|x\n"); + assert_eq!(back.hover_more, ["drive|C", "net|x"]); + } } /// Notify `hwnd` with `msg` whenever a file in the data folder is written. diff --git a/src/settings_ui.rs b/src/settings_ui.rs index 46b8e68..5339be8 100644 --- a/src/settings_ui.rs +++ b/src/settings_ui.rs @@ -124,9 +124,7 @@ const CELL_GAP: i32 = 8; const WHEEL_STEP: i32 = 48; /// One wheel notch per wheel "line" (Windows default: 3 lines = 108 epx). const WHEEL_LINE: i32 = 36; -/// Scroll smoothing (s): a notch eases out over ~0.2 s; touchpads follow closely. -const SCROLL_TAU: f32 = 0.065; -const SCROLL_TAU_PRECISE: f32 = 0.028; +use crate::scroll::TAU as SCROLL_TAU; const BTN_W: i32 = 112; const STEPPER_W: i32 = 132; @@ -456,6 +454,11 @@ pub(crate) fn accent_color(dark: bool) -> Rgba { } } +/// Colours the Monitor cards are drawn with outside this window (the tray hover window). +pub(crate) fn view_colors(dark: bool) -> view::Colors { + Pal::new(dark, false, hx(0)).view() +} + // ------------------------------------------------------------------ dark mode /// Undocumented uxtheme ordinals every dark-mode Win32 app (Explorer, @@ -657,6 +660,11 @@ impl Fonts { } } + /// Big and small light numerals. + pub(crate) fn nums(&self) -> (HFONT, HFONT) { + (self.num, self.num_sm) + } + pub(crate) fn view(&self) -> view::Fonts { view::Fonts { body: self.body, small: self.small, tiny: self.tiny, semi: self.semi, cap: self.cap, head: self.head } } @@ -857,7 +865,7 @@ fn ease(t: f32) -> f32 { /// Windows "Animate controls and elements inside windows" (Settings > /// Accessibility > Visual effects > Animation effects). -fn animations_on() -> bool { +pub(crate) fn animations_on() -> bool { let mut on: BOOL = 1; // SAFETY: valid out pointer of the documented size. unsafe { SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION, 0, &mut on as *mut BOOL as _, 0) }; @@ -2386,8 +2394,8 @@ impl Ui { } let (vt, vb) = self.view(); let track = Rect { l: self.cw - self.sc(16), t: vt + self.sc(4), r: self.cw - self.sc(2), b: vb - self.sc(4) }; - let th = (track.h() * (vb - vt) / self.content_h.max(1)).max(self.sc(32)).min(track.h()); - let ty = track.t + ((track.h() - th) as f32 * (self.scroll / max as f32)).round() as i32; + let (ty, th) = crate::scroll::thumb(track.h(), vb - vt, max + vb - vt, self.scroll, self.sc(32)); + let ty = track.t + ty; let wide = self.sb_hover || matches!(self.drag, Drag::Thumb(_)); let w = if wide { self.sc(6) } else { self.sc(4) }; let r = track.r - self.sc(2); @@ -2401,14 +2409,14 @@ impl Ui { if !self.anim.timer { self.anim.timer = true; self.last_frame = Some(Instant::now()); - crate::vsync::start(self.hwnd); + crate::vsync::start(crate::vsync::Clock::Main, self.hwnd); } } fn stop_timer(&mut self) { self.anim.timer = false; self.last_frame = None; - crate::vsync::stop(); + crate::vsync::stop(crate::vsync::Clock::Main); } /// The Modules page's slow timer (LED blink, download progress) runs only while it is @@ -2460,21 +2468,8 @@ impl Ui { let now = Instant::now(); let dt = self.last_frame.map_or(1.0 / 60.0, |t| (now - t).as_secs_f32()).clamp(0.0, 0.1); self.last_frame = Some(now); - let mut busy = false; - let d = self.target as f32 - self.scroll; - if d.abs() < 0.5 { - self.scroll = self.target as f32; - } else { - // Exponential ease toward the target: quick start, soft landing. - let k = 1.0 - (-dt / self.scroll_tau.max(0.005)).exp(); - self.scroll += d * k; - if (self.target as f32 - self.scroll).abs() < 0.5 { - self.scroll = self.target as f32; - } else { - busy = true; - } - } - let scrolling = busy; + let (pos, scrolling) = crate::scroll::ease(self.scroll, self.target as f32, self.scroll_tau, dt); + self.scroll = pos; // Anything besides the scroll offset moving this frame. let mut other = false; let done = |t: Option, dur: f32| t.is_none_or(|t| t.elapsed().as_secs_f32() >= dur); @@ -3893,6 +3888,8 @@ fn merge(dst: &mut Settings, src: &Settings) { dst.crit_pct = src.crit_pct; dst.data_cap_gb = src.data_cap_gb; dst.cap_reset_day = src.cap_reset_day; + dst.hover_items = src.hover_items; + dst.hover_more = src.hover_more.clone(); dst.alerts = src.alerts; dst.alert_cpu_pct = src.alert_cpu_pct; dst.alert_ram_pct = src.alert_ram_pct; @@ -4387,6 +4384,17 @@ fn activate(hwnd: HWND, id: i32) { crate::popup::refresh(); } } + Some(MonHit::HoverItem(n) | MonHit::HoverFact(n)) => { + // Any other item: in at the end of the hover window, or out. + if let Some(a) = app() { + a.m.s.hover_flip(&crate::monitor::hover::name(n)); + u.draft.hover_more = a.m.s.hover_more.clone(); + u.mon.set_hover_more(&a.m.s.hover_more); + a.save_settings(); + crate::popup::refresh(); + } + invalidate(hwnd); + } Some(MonHit::AddonOpen(i)) => { u.mon.addon_click(i); u.layout(); @@ -4828,41 +4836,15 @@ fn on_wheel(hwnd: HWND, delta: i32, sx: i32, sy: i32) { } } } - let now = Instant::now(); - // Precision touchpads send small deltas many times a second: follow them - // closely. A mouse wheel sends whole notches (120): ease each one out, and - // quick notches in a row build speed (like a browser). - let notch = delta % 120 == 0; - let dir = delta.signum(); - let mut boost = 1.0f32; - if notch { - if let Some((t, d, b)) = u.wheel { - let gap = (now - t).as_secs_f32(); - if d == dir && gap < 0.09 { - boost = (b + 0.2).min(2.5); - } - } - u.wheel = Some((now, dir, boost)); - } - u.scroll_tau = if notch { SCROLL_TAU } else { SCROLL_TAU_PRECISE }; - let step = wheel_px(u.sc(WHEEL_LINE), u.view().1 - u.view().0); + let (tau, boost) = crate::scroll::wheel(&mut u.wheel, delta, Instant::now()); + u.scroll_tau = tau; + let step = crate::scroll::wheel_px(u.sc(WHEEL_LINE), u.view().1 - u.view().0); let px = (delta as f32 * step as f32 / 120.0 * boost).round() as i32; // Keep adding to where the scroll is heading, so fast notches add up. let t = u.target - px; u.scroll_to(t, true); } -/// Pixels per wheel notch: the user's "lines to scroll" (Mouse settings) times -/// a line, or a page when it is set to one screen at a time. -fn wheel_px(line: i32, page: i32) -> i32 { - let mut lines: u32 = 3; - unsafe { SystemParametersInfoW(SPI_GETWHEELSCROLLLINES, 0, &mut lines as *mut u32 as *mut core::ffi::c_void, 0) }; - if lines == u32::MAX { - return (page * 7 / 8).max(line); - } - line * lines.clamp(1, 20) as i32 -} - fn track_mouse(hwnd: HWND, hover: bool) -> bool { let flags = if hover { TME_LEAVE | TME_HOVER } else { TME_LEAVE }; let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::() as u32, dwFlags: flags, hwndTrack: hwnd, dwHoverTime: u32::MAX /* HOVER_DEFAULT */ }; @@ -5372,6 +5354,23 @@ fn mark_monitor_seen() { *MON_SEEN.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now()); } +/// Open the Monitor page on a device (None = its overview). +pub fn open_dev(a: &mut crate::app::App, d: Option) { + open(a, Page::Monitor); + let Some(u) = ui().filter(|u| !u.hwnd.is_null()) else { return }; + match d { + Some(d) => u.mon.open_dev(d), + None => { + u.mon.close_dev(); + } + } + u.layout(); + u.scroll_to(0, false); + u.refresh_hover(); + invalidate(u.hwnd); + a.request_sample(); +} + /// The Monitor page is on screen, or was within the last minute. pub fn monitor_warm() -> bool { monitor_visible() @@ -5641,7 +5640,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> // waiting: input would starve, clicks pile up and replay seconds later, and // the coin could not be dragged. Acked here, the clock posts again at the // next vblank, and input queued meanwhile is handled first. - crate::vsync::ack(); + crate::vsync::ack(crate::vsync::Clock::Main); 0 } WM_TIMER => { @@ -5704,7 +5703,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> WM_DESTROY => { KillTimer(hwnd, T_LIVE); KillTimer(hwnd, T_ANIM); - crate::vsync::stop(); + crate::vsync::stop(crate::vsync::Clock::Main); crate::util::interactive(false); KillTimer(hwnd, T_REPEAT); KillTimer(hwnd, T_BLINK); diff --git a/src/vsync.rs b/src/vsync.rs index cdd3184..974f72a 100644 --- a/src/vsync.rs +++ b/src/vsync.rs @@ -33,9 +33,17 @@ struct Shared { wake: Condvar, } -fn shared() -> &'static Arc { - static S: OnceLock> = OnceLock::new(); - S.get_or_init(|| { +/// Whose frames: the main window and the tray hover window each have a clock of their own, so +/// one animating never takes the other's frames. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Clock { + Main, + Popup, +} + +fn shared(c: Clock) -> &'static Arc { + static S: [OnceLock>; 2] = [const { OnceLock::new() }; 2]; + S[c as usize].get_or_init(|| { let s = Arc::new(Shared { run: AtomicBool::new(false), queued: AtomicBool::new(false), missed: AtomicBool::new(false), hwnd: AtomicIsize::new(0), gate: Mutex::new(()), wake: Condvar::new() }); let t = s.clone(); let _ = std::thread::Builder::new().name("vsync".into()).spawn(move || run(&t)); @@ -44,8 +52,8 @@ fn shared() -> &'static Arc { } /// Start sending frames to `hwnd`. -pub fn start(hwnd: HWND) { - let s = shared(); +pub fn start(c: Clock, hwnd: HWND) { + let s = shared(c); s.hwnd.store(hwnd as isize, Relaxed); if !s.run.swap(true, AcqRel) { s.queued.store(false, Release); @@ -55,8 +63,8 @@ pub fn start(hwnd: HWND) { } /// Stop sending frames (the thread goes back to sleep). -pub fn stop() { - shared().run.store(false, Release); +pub fn stop(c: Clock) { + shared(c).run.store(false, Release); } /// The window finished a frame (call it after drawing, not before): the next one may be @@ -66,8 +74,8 @@ pub fn stop() { /// When that frame ran past a vblank and nothing else waits in this thread's queue (no /// input, paint, timer or posted message), the next frame is posted at once instead, so /// a frame slightly over budget does not halve the frame rate. Call on the UI thread. -pub fn ack() { - let s = shared(); +pub fn ack(c: Clock) { + let s = shared(c); if s.missed.swap(false, AcqRel) && s.run.load(Acquire) { let busy = unsafe { GetQueueStatus(QS_INPUT | QS_PAINT | QS_TIMER | QS_POSTMESSAGE | QS_HOTKEY) } >> 16; if busy == 0 && unsafe { PostMessageW(s.hwnd.load(Relaxed) as HWND, WM_APP_FRAME, 0, 0) } != 0 { From 0c006b61d6397914a5ed70ea9a694a18c8890c31 Mon Sep 17 00:00:00 2001 From: rajhansgithub Date: Thu, 3 Dec 2026 00:43:30 +0530 Subject: [PATCH 2/2] Scroll frames skip the cards behind the scroll bar; no tip dragged along --- src/popup.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/popup.rs b/src/popup.rs index cff24c7..16397d3 100644 --- a/src/popup.rs +++ b/src/popup.rs @@ -731,6 +731,8 @@ fn chip(c: &mut Canvas, f: HFONT, text: &str, x: &mut i32, min_x: i32, y: i32, h thread_local! { /// The next paint differs from the last one by the scroll offset alone. static SCROLL_ONLY: Cell = const { Cell::new(false) }; + /// The frame on screen has a chart's tooltip over it. + static TIP_ON: Cell = const { Cell::new(false) }; } /// Scroll bar of the window: track (its hit area) and thumb, when there is more than fits. @@ -780,7 +782,12 @@ fn paint(a: &mut App, hwnd: HWND) { let now = a.popup_scroll.px(); let d = now - a.popup_drawn; let mut board = a.popup_board.take(); - if scroll_only && same && d.abs() < body.h() / 2 && crate::looks::scroll_shift(crate::look::current()) { + // While it scrolls nothing is under the pointer: a highlight or a tip would be dragged along. + let hover = a.popup_hover; + if a.popup_scrolling { + a.popup_hover = None; + } + if scroll_only && same && !TIP_ON.with(Cell::get) && d.abs() < body.h() / 2 && crate::looks::scroll_shift(crate::look::current()) { // Only the scroll moved since the last frame: move the pixels, draw the strip that came in. let _p = crate::perf::span("popup_scroll"); if d != 0 { @@ -788,14 +795,12 @@ fn paint(a: &mut App, hwnd: HWND) { let strip = if d > 0 { Rect { t: body.b - d, ..body } } else { Rect { b: body.t - d, ..body } }; // The scroll bar sits in the right margin: redraw that column too. let bar = Rect { l: cw - (PAD * scale).round() as i32, ..body }; - let hover = a.popup_hover.take(); for lim in [strip, bar] { c.set_limit(Some(lim)); let mut out = Out::default(); draw(a, &mut c, &f, scale, &mut out, board.as_deref_mut(), Some(lim)); } c.set_limit(None); - a.popup_hover = hover; for (r, _) in a.popup_hits.iter_mut().filter(|x| x.0.b > body.t) { r.t -= d; r.b -= d; @@ -807,6 +812,7 @@ fn paint(a: &mut App, hwnd: HWND) { draw(a, &mut c, &f, scale, &mut out, board.as_deref_mut(), None); a.popup_hits = out.hits; } + a.popup_hover = hover; a.popup_board = board; a.popup_drawn = now; c.blit(dc, 0, 0); @@ -921,7 +927,10 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out, board: Op } let head_hits = out.hits.len(); c.set_clip(Some(body)); - draw_body(a, c, f, scale, out, &e, &tk, rad, chip_h, board, lim.unwrap_or(body)); + // The scroll bar's column (the right margin) has no cards in it. + if lim.is_none_or(|l| l.l < c.w - pad) { + draw_body(a, c, f, scale, out, &e, &tk, rad, chip_h, board, lim.unwrap_or(body)); + } c.set_clip(None); // Regions that slid under the header are not there to click. for (r, _) in &mut out.hits[head_hits..] { @@ -931,7 +940,11 @@ fn draw(a: &App, c: &mut Canvas, f: &Fonts, scale: f32, out: &mut Out, board: Op if let Some((_, thumb)) = scrollbar(a, c.w, c.h, scale, a.popup_drag.is_some() || a.popup_hover.is_some_and(|(x, y)| x >= c.w - pad && y >= body.t)) { c.fill_round(thumb, thumb.w() as f32 / 2.0, pal.dim.with_a(if a.popup_drag.is_some() { 230 } else { 150 })); } - if let Some(t) = out.tip.take() { + let tip = out.tip.take(); + if lim.is_none() { + TIP_ON.with(|f| f.set(tip.is_some())); + } + if let Some(t) = tip { draw_tip(c, &e, &t); } }