From 7995eac6acdd8bd795494ba5caf193eb867c91b6 Mon Sep 17 00:00:00 2001 From: Muse Date: Sat, 5 Dec 2026 22:23:27 +0000 Subject: [PATCH] Monitor widgets: dynamic graph margins, scaled fonts, tach + audit proportions - Graphs (History/Net/Temp): dynamic left margin from the widest Y label (5 labels, top hangs below / bottom sits above gridline), legend on top with wrap/split so totals never clip; Net Y labels humanised (KB/s, MB/s) and scaled from the series max so no series rides the top edge; Temp keeps the PY layout (now bold top-right, threshold label above the line, min/max/avg bottom line). - XTachometer: numerals ~7.5% of dial diameter, bold, placed by per-label radial extent so wide labels never cross the dial rim; RPM bold centred in-dial below the top numerals; readout inside below the hub; redline numerals red; redline is a rim arc, not a filled sector (red-on-red made the redline numerals invisible). - Audit proportions in all 14 widgets: scaled fonts from widget dimensions (titles 16 bold, body 14-16, hero 20-32 bold), CoreGrid waste-minimising layout (8 cores -> 4x2), UsageBar labels outside the bar with the value name (CPU) and absolute gradient stops, StackBar title+total header (absolute GiB, total 30.3) with a centred block, VerticalBar value inside the bar + peak label above the line, ArcGauge redesigned to arc-line no-needle (C/PY style), DonutGauge centre label = value name with 8-10% ring, ProcessList 13px rows / 23px pitch with colour-coded CPU bars and a 68px PID column (7-digit live PIDs no longer bleed into the name), LoadBadge PY two-line layout with 1/5/15-min sub-labels + core count, MonitorButton/Grid name+status+detail cells with ceil(sqrt(n)) grid geometry, SysBox hero top-left + max + bar % label. - Scaled-font plumbing: DrawTarget::set_scaled_font (default no-op), draw_text_scaled / text_width_scaled / clamp_font_px in xframe-core; X11 binds scalable misc-fixed XLFDs (cached per px/bold) with bitmap fallbacks. - Demo runner only sets text=kind when the widget did not seed its own text, so seeded value names (CPU, Disk) survive. --- crates/xframe-common/src/target.rs | 13 + crates/xframe-common/src/x11.rs | 80 ++- crates/xframe-core/src/draw.rs | 47 ++ crates/xframe-demo/src/lib.rs | 11 +- crates/xframe-widgets/src/monitor.rs | 830 +++++++++++++++++++-------- 5 files changed, 740 insertions(+), 241 deletions(-) diff --git a/crates/xframe-common/src/target.rs b/crates/xframe-common/src/target.rs index 9c19307..2d5b585 100644 --- a/crates/xframe-common/src/target.rs +++ b/crates/xframe-common/src/target.rs @@ -64,6 +64,19 @@ impl DrawTarget for CtxTarget<'_> { fn set_font(&mut self, metrics: FontMetrics) { self.font_metrics = Some(metrics); + // Rebind the regular font: a scaled draw may have left a + // different font in the GC. + self.ctx.bind_font(); + } + + fn set_scaled_font(&mut self, px: i32, bold: bool) -> bool { + match self.ctx.bind_scaled_font(px, bold) { + Some(metrics) => { + self.font_metrics = Some(metrics); + true + } + None => false, + } } fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32) { diff --git a/crates/xframe-common/src/x11.rs b/crates/xframe-common/src/x11.rs index c23ebd3..e5bfb8f 100644 --- a/crates/xframe-common/src/x11.rs +++ b/crates/xframe-common/src/x11.rs @@ -8,6 +8,7 @@ use x11rb::connection::Connection; use x11rb::protocol::xproto::*; use x11rb::rust_connection::RustConnection; use x11rb::COPY_FROM_PARENT; +use xframe_core::font::FontMetrics; pub type Conn = RustConnection; @@ -555,6 +556,13 @@ pub struct DrawCtx<'a> { pub gc: Gcontext, pub font: Font, colors: RefCell>, + /// Scaled fonts opened by `bind_scaled_font`, keyed by + /// (pixel size, bold). Process-lifetime, like the C++ cache. + scaled_fonts: RefCell>, + /// The font currently bound into the GC (starts as `font`). + /// `text_width` measures with this font, so it stays correct + /// after a scaled draw. + current_font: RefCell, } impl<'a> DrawCtx<'a> { @@ -565,6 +573,8 @@ impl<'a> DrawCtx<'a> { gc, font, colors: RefCell::new(HashMap::new()), + scaled_fonts: RefCell::new(HashMap::new()), + current_font: RefCell::new(font), } } @@ -731,7 +741,7 @@ impl<'a> DrawCtx<'a> { } pub fn text_width(&self, text: &str) -> i32 { - self.x.text_width(self.font, text) + self.x.text_width(*self.current_font.borrow(), text) } /// Draw text with the GC font; the GC font must be set by the caller @@ -771,6 +781,74 @@ impl<'a> DrawCtx<'a> { .x .conn .change_gc(self.gc, &ChangeGCAux::new().font(self.font)); + *self.current_font.borrow_mut() = self.font; + } + + /// Bind a scaled font (`px` pixels, bold when `bold`) into the GC + /// and return its metrics. The misc-fixed XLFD is scalable, so the + /// requested size loads exactly; bitmap fallbacks (the only sizes + /// the server has: bold 13/14/15/18/20, medium 13/18/20) and + /// `fixed` cover a server without the scalable face. Results are + /// cached per (px, bold). `None` when nothing loads, in which case + /// the previously bound font stays active. + pub fn bind_scaled_font(&self, px: i32, bold: bool) -> Option { + if let Some(&(font, metrics)) = + self.scaled_fonts.borrow().get(&(px, bold)) + { + let _ = self + .x + .conn + .change_gc(self.gc, &ChangeGCAux::new().font(font)); + *self.current_font.borrow_mut() = font; + return Some(metrics); + } + let weight = if bold { "bold" } else { "medium" }; + let mut candidates: Vec = vec![format!( + "-misc-fixed-{weight}-r-normal--{px}-*-75-75-c-*-iso8859-1" + )]; + let bitmaps: &[i32] = if bold { + &[18, 20, 15, 14, 13] + } else { + &[20, 18, 13] + }; + for size in bitmaps { + candidates.push(format!( + "-misc-fixed-{weight}-r-normal--{size}-120-100-100-c-60-iso8859-1" + )); + } + candidates.push("fixed".to_string()); + for name in &candidates { + let Ok(fid) = self.x.conn.generate_id() else { + continue; + }; + let Ok(cookie) = self.x.conn.open_font(fid, name.as_bytes()) else { + continue; + }; + if cookie.check().is_err() { + continue; + } + let Ok(reply) = self.x.conn.query_font(fid) else { + continue; + }; + let Ok(reply) = reply.reply() else { + continue; + }; + let metrics = FontMetrics { + ascent: reply.font_ascent as i32, + descent: reply.font_descent as i32, + char_width: reply.max_bounds.character_width as i32, + }; + let _ = self + .x + .conn + .change_gc(self.gc, &ChangeGCAux::new().font(fid)); + self.scaled_fonts + .borrow_mut() + .insert((px, bold), (fid, metrics)); + *self.current_font.borrow_mut() = fid; + return Some(metrics); + } + None } pub fn put_rgba(&self, dst_x: i16, dst_y: i16, rgba: &[u8], w: u16, h: u16) { diff --git a/crates/xframe-core/src/draw.rs b/crates/xframe-core/src/draw.rs index db8f2fb..77e7dab 100644 --- a/crates/xframe-core/src/draw.rs +++ b/crates/xframe-core/src/draw.rs @@ -21,6 +21,16 @@ pub trait DrawTarget { fn set_line_width(&mut self, width: u32); /// Install a font for subsequent `draw_string` calls. fn set_font(&mut self, metrics: FontMetrics); + /// Install a scaled font (pixel size `px`, bold when `bold`) for + /// subsequent `draw_string` calls. Returns true when a font at + /// (approximately) that size was bound. Default: no-op returning + /// false — the caller then draws with the current font (the + /// Canvas / test targets have no X server to open fonts on). + /// Live targets (CtxTarget) bind a scalable misc-fixed XLFD, + /// falling back to the nearest bitmap size. + fn set_scaled_font(&mut self, _px: i32, _bold: bool) -> bool { + false + } /// Fill a rectangle (top-left `x, y`, size `w` x `h`). fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32); /// Draw a rectangle outline. @@ -63,6 +73,43 @@ pub fn set_line_width(target: &mut (impl DrawTarget + ?Sized), line_width: i32) target.set_line_width(line_width.max(1) as u32); } +/// Clamp a font size derived from a widget dimension to `[lo, hi]` +/// (sane minimum 11 px so text never shrinks to unreadable). +/// Mirrors `xframe::clamp_font_px` in C++ and `_fpx` in Python. +pub fn clamp_font_px(value: i32, lo: i32, hi: i32) -> i32 { + value.max(lo).min(hi) +} + +/// Draw `text` at baseline `(x, y)` in a scaled font (`px`, `bold`), +/// falling back to the current font on targets without scaled fonts. +/// The caller sets the foreground colour first. +pub fn draw_text_scaled( + target: &mut (impl DrawTarget + ?Sized), + px: i32, + bold: bool, + x: i32, + y: i32, + text: &str, +) { + if text.is_empty() { + return; + } + let _ = target.set_scaled_font(px, bold); + target.draw_string(x, y, text); +} + +/// Width of `text` in a scaled font (`px`, `bold`), or in the current +/// font on targets without scaled fonts. +pub fn text_width_scaled( + target: &mut (impl DrawTarget + ?Sized), + px: i32, + bold: bool, + text: &str, +) -> i32 { + let _ = target.set_scaled_font(px, bold); + target.text_width(text) +} + /// C++ `xf::fill_rounded_rect`: the Part 4 rounded body — Rectangle A + /// Rectangle B + 4 fill arcs. Degenerate radii fall back to a plain fill. pub fn fill_rounded_rect( diff --git a/crates/xframe-demo/src/lib.rs b/crates/xframe-demo/src/lib.rs index 9e1c7db..d3a1568 100644 --- a/crates/xframe-demo/src/lib.rs +++ b/crates/xframe-demo/src/lib.rs @@ -108,9 +108,14 @@ pub fn run_widget_with_csv( }; widget.set_bounds(gx as i32, gy as i32, gw as i32, gh as i32); // Label text: the registry `kind` approximates the C++ constructor's - // default text (see the module docs of the binary). - let kind = widget.kind().to_string(); - widget.set_text(&kind); + // default text (see the module docs of the binary) -- but only when + // the widget did not seed its own text (e.g. the monitor demos seed + // a value name such as "CPU" / "Disk"; overwriting it with the kind + // would show the class name instead of the value name). + if widget.state().text.is_empty() { + let kind = widget.kind().to_string(); + widget.set_text(&kind); + } if let Some(text) = &csv { if let Err(e) = widget.load_csv_data(text) { eprintln!("xframe-demo: --csv: {}", e); diff --git a/crates/xframe-widgets/src/monitor.rs b/crates/xframe-widgets/src/monitor.rs index 90d5230..0c20b88 100644 --- a/crates/xframe-widgets/src/monitor.rs +++ b/crates/xframe-widgets/src/monitor.rs @@ -26,7 +26,9 @@ use std::collections::VecDeque; use std::time::{Duration, Instant}; -use xframe_core::draw::{draw_polished, draw_text_at, draw_text_centered, draw_text_left, text_width}; +use xframe_core::draw::{ + clamp_font_px, draw_polished, draw_text_centered, draw_text_scaled, text_width_scaled, +}; use xframe_core::{DrawTarget, Srgb, Style, StyleManager}; use crate::state::{Key, Rect, WidgetState}; @@ -80,7 +82,6 @@ pub const MAX_SERIES_SAMPLES: usize = 240; // --------------------------------------------------------------------------- const GREEN: Srgb = Srgb::new(34, 197, 94); -const GREEN_DIM: Srgb = Srgb::new(134, 239, 172); const AMBER: Srgb = Srgb::new(245, 158, 11); const RED: Srgb = Srgb::new(239, 68, 68); const BLUE: Srgb = Srgb::new(59, 130, 246); @@ -517,13 +518,17 @@ impl MonitorWidget { self.state.max = 100.0; self.state.value = 62.5; self.peak = 62.5; + // The label is the value name ("CPU"), not the class name. + self.state.text = "CPU".to_string(); } "StackBar" => { + // Absolute GiB values (C/PY demos); total 30.3. + self.unit = "GiB".to_string(); self.segments = vec![ - Segment { label: "used", value: 45.0, color: GREEN }, - Segment { label: "cached", value: 20.0, color: BLUE }, - Segment { label: "buffers", value: 10.0, color: CYAN }, - Segment { label: "free", value: 25.0, color: GREY_DIM }, + Segment { label: "used", value: 11.7, color: GREEN }, + Segment { label: "cached", value: 15.5, color: BLUE }, + Segment { label: "buffers", value: 1.2, color: CYAN }, + Segment { label: "free", value: 1.9, color: GREY_DIM }, ]; } "VerticalBar" => { @@ -551,6 +556,8 @@ impl MonitorWidget { self.state.max = 100.0; self.state.value = 42.0; self.peak = 42.0; + // The centre label is the value name ("Disk"). + self.state.text = "Disk".to_string(); } "ProcessList" => { // Live rows when /proc is there, seeded rows otherwise. @@ -583,7 +590,7 @@ impl MonitorWidget { self.buttons = vec![ MonitorButtonState::new("sshd proc", MonitorTarget::Process("sshd".to_string())), MonitorButtonState::new("sshd unit", MonitorTarget::Unit("sshd".to_string())), - MonitorButtonState::new("SSH :22", MonitorTarget::TcpPort(22)), + MonitorButtonState::new("sshd :22", MonitorTarget::TcpPort(22)), ]; self.poll_all(); } @@ -810,19 +817,115 @@ fn arc64(start_deg: f64, extent_deg: f64) -> (i32, i32) { ((s * 64.0) as i32, (extent_deg * 64.0) as i32) } -/// Text in an explicit colour (the `draw_text_*` helpers always use -/// `style.text_color`). -fn draw_text_colored( +/// Text in a scaled font (`px`, bold) and an explicit colour, at +/// baseline `(x, baseline_y)`. Falls back to the 13 px font on +/// targets without scaled fonts (Canvas / tests). +fn draw_scaled_at( target: &mut dyn DrawTarget, - style: &Style, + px: i32, + bold: bool, x: i32, baseline_y: i32, text: &str, color: Srgb, ) { - let mut st = style.clone(); - st.text_color = color.to_pixel(); - draw_text_at(target, &st, x, baseline_y, text); + target.set_foreground(color.to_pixel()); + draw_text_scaled(target, px, bold, x, baseline_y, text); +} + +/// Scaled text centred horizontally in `[x1, x2]` at `baseline_y`. +fn draw_scaled_centered( + target: &mut dyn DrawTarget, + px: i32, + bold: bool, + x1: i32, + baseline_y: i32, + x2: i32, + text: &str, + color: Srgb, +) { + let tw = text_width_scaled(target, px, bold, text); + draw_scaled_at(target, px, bold, x1 + (x2 - x1 - tw) / 2, baseline_y, text, color); +} + +/// Scaled text right-aligned ending at `x` (baseline `baseline_y`). +fn draw_scaled_right( + target: &mut dyn DrawTarget, + px: i32, + bold: bool, + x: i32, + baseline_y: i32, + text: &str, + color: Srgb, +) { + let tw = text_width_scaled(target, px, bold, text); + draw_scaled_at(target, px, bold, x - tw, baseline_y, text, color); +} + +/// Humanised rate for the net graph's KB/s series: `420.0 KB/s`, +/// `1.24 MB/s` above 1024 KB/s. +pub fn fmt_rate_kbs(v: f64) -> String { + if v.abs() < 1024.0 { + format!("{:.1} KB/s", v) + } else { + format!("{:.2} MB/s", v / 1024.0) + } +} + +/// Plain integer Y label. +fn fmt_num(v: f64) -> String { + format!("{:.0}", v) +} + +/// Temperature Y label. +fn fmt_temp(v: f64) -> String { + format!("{:.0}°C", v) +} + +/// Left margin for a plot: the widest of the 5 Y labels at `px` + 10. +/// Measuring through the target binds the scaled font, so the width +/// is exact for the font actually drawn. +fn y_axis_width( + target: &mut dyn DrawTarget, + ymin: f64, + ymax: f64, + px: i32, + fmt: &dyn Fn(f64) -> String, +) -> i32 { + let mut widest = 0; + for i in 0..=4 { + let v = ymin + (i as f64 / 4.0) * (ymax - ymin); + widest = widest.max(text_width_scaled(target, px, false, &fmt(v))); + } + widest + 10 +} + +/// The 5 Y labels for `plot` (0/25/50/75/100% of the range), +/// right-aligned ending 4 px left of the plot edge. The top label +/// hangs below its gridline (clear of the title), the bottom label +/// sits above its gridline (clear of the strip below the plot); +/// middle labels are centred on their lines. +fn draw_y_labels( + target: &mut dyn DrawTarget, + plot: Rect, + ymin: f64, + ymax: f64, + px: i32, + fmt: &dyn Fn(f64) -> String, +) { + for i in 0..=4 { + let f = i as f64 / 4.0; + let v = ymin + f * (ymax - ymin); + let gy = plot.y + plot.h - (f * plot.h as f64) as i32; + let ybase = if i == 4 { + gy + px * 3 / 4 + } else if i == 0 { + gy - 2 + } else { + gy + px * 7 / 20 + }; + draw_scaled_right(target, px, false, plot.x - 4, ybase, &fmt(v), GREY); + } } /// Human byte count: `1.24 GB`, `380 MB`, `420 KB`. @@ -851,9 +954,10 @@ impl MonitorWidget { /// Title line inside the frame; returns the y just below the title. fn header(&self, target: &mut dyn DrawTarget, style: &Style, title: &str) -> i32 { + let _ = style; let b = self.state.bounds; - draw_text_left(target, style, b.x + 6, b.y + 2, b.y + 18, title); - b.y + 20 + draw_scaled_at(target, 16, true, b.x + 6, b.y + 17, title, INK); + b.y + 24 } /// Y pixel for a value in the plot rect (top = ymax). @@ -870,10 +974,10 @@ impl MonitorWidget { fn draw_series_lines(&self, target: &mut dyn DrawTarget, plot: Rect, ymin: f64, ymax: f64) { target.set_foreground(PLOT_BG.to_pixel()); target.fill_rect(plot.x, plot.y, plot.w, plot.h); - // Horizontal gridlines + y labels. + // Horizontal gridlines + y labels (5 ticks: 0/25/50/75/100%). target.set_foreground(GRID.to_pixel()); - for i in 0..=2 { - let y = plot.y + plot.h * i / 2; + for i in 0..=4 { + let y = plot.y + plot.h * i / 4; target.draw_line(plot.x, y, plot.x + plot.w, y); } target.set_foreground(GREY.to_pixel()); @@ -909,15 +1013,17 @@ impl MonitorWidget { y: i32, s: &Series, ) { + let _ = style; let b = self.state.bounds; + let px = clamp_font_px((0.032 * b.h as f64) as i32, 11, 16); target.set_foreground(s.color.to_pixel()); - target.fill_rect(b.x + 6, y + 3, 8, 8); + target.fill_rect(b.x + 6, y + 3, 10, 10); let stats = series_stats(s) .map(|(mn, mx, av, last)| { format!("{} cur {:.0} min {:.0} max {:.0} avg {:.0}", s.label, last, mn, mx, av) }) .unwrap_or_else(|| format!("{} (no data)", s.label)); - draw_text_at(target, style, b.x + 18, y + 11, &stats); + draw_scaled_at(target, px, false, b.x + 20, y + px * 3 / 4 + 2, &stats, INK); } fn draw_history_graph(&self, target: &mut dyn DrawTarget, style: &Style) { @@ -925,8 +1031,8 @@ impl MonitorWidget { } /// History graph with `extra_bottom` pixels reserved below the - /// legend (used by `XNetGraph` for its totals line). Returns the y - /// just below the legend. + /// plot (used by `XNetGraph` for its totals line — now 0, the + /// legend lives on top). Returns the y just below the plot. fn draw_history_graph_extra( &self, target: &mut dyn DrawTarget, @@ -935,13 +1041,7 @@ impl MonitorWidget { ) -> i32 { let b = self.state.bounds; let y = self.header(target, style, &self.state.name); - let legend_h = (self.series.len() as i32) * 14; - let plot = Rect::new( - b.x + 6, - y, - b.w - 12, - (b.h - (y - b.y) - legend_h - 8 - extra_bottom).max(10), - ); + let body_px = clamp_font_px((0.032 * b.h as f64) as i32, 11, 16); let (mut ymin, mut ymax) = (self.state.min, self.state.max); if ymax <= ymin { // Auto-range from the data. @@ -961,26 +1061,61 @@ impl MonitorWidget { ymin -= pad; ymax += pad; } - self.draw_series_lines(target, plot, ymin, ymax); - // Y labels. - draw_text_colored(target, style, b.x + 8, plot.y + 10, &format!("{:.0}", ymax), GREY); - draw_text_colored(target, style, b.x + 8, plot.y + plot.h - 2, &format!("{:.0}", ymin), GREY); - let mut ly = plot.y + plot.h + 4; + // Legend on top, one 18 px row per series. + let legend_h = (self.series.len() as i32) * 18; + let mut ly = y + 2; for s in &self.series { self.draw_legend_row(target, style, ly, s); - ly += 14; + ly += 18; } - ly + // Dynamic left margin: the plot starts after the widest Y label. + let axis_w = y_axis_width(target, ymin, ymax, body_px, &fmt_num); + let plot_y = y + legend_h + 4; + let plot = Rect::new( + b.x + axis_w, + plot_y, + (b.w - axis_w - 8).max(10), + (b.h - (plot_y - b.y) - 22 - extra_bottom).max(10), + ); + self.draw_series_lines(target, plot, ymin, ymax); + draw_y_labels(target, plot, ymin, ymax, body_px, &fmt_num); + // Time axis: "-60s" left, "now" right. + let time_px = clamp_font_px((0.028 * b.h as f64) as i32, 11, 14); + draw_scaled_at(target, time_px, false, plot.x, b.y + b.h - 5, "-60s", GREY); + draw_scaled_right(target, time_px, false, plot.x + plot.w, b.y + b.h - 5, "now", GREY); + plot.y + plot.h } fn draw_core_grid(&self, target: &mut dyn DrawTarget, style: &Style) { let b = self.state.bounds; let y = self.header(target, style, &self.state.name); let n = self.series.len().max(1); - let cols = (n as f64).sqrt().ceil() as i32; - let rows = (n as i32 + cols - 1) / cols; + // Grid geometry: pick cols/rows with no empty cell when + // possible (8 cores -> 4x2, not 3x3 with a hole). Minimise + // waste among near-square layouts, keeping rows >= 2 and + // cols <= 2*rows (C's layout). + let mut cols = (n as f64).sqrt().ceil() as i32; + let mut rows = (n as i32 + cols - 1) / cols; + let mut best_waste = cols * rows - n as i32; + let mut cc = cols + 1; + while cc <= n as i32 { + let rr = (n as i32 + cc - 1) / cc; + if rr >= 2 && cc <= 2 * rr { + let waste = cc * rr - n as i32; + if waste < best_waste { + cols = cc; + rows = rr; + best_waste = waste; + if waste == 0 { + break; + } + } + } + cc += 1; + } let cw = (b.w - 12) / cols; let ch = (b.h - (y - b.y) - 8) / rows.max(1); + let cell_px = clamp_font_px((0.10 * ch as f64) as i32, 11, 16); for (i, s) in self.series.iter().enumerate() { let cx = b.x + 6 + (i as i32 % cols) * cw; let cy = y + (i as i32 / cols) * ch; @@ -1002,44 +1137,100 @@ impl MonitorWidget { for k in 0..vals.len() - 1 { let x1 = cell.x + 2 + (k as i32 * (cell.w - 4)) / (vals.len() as i32 - 1); let x2 = cell.x + 2 + ((k + 1) as i32 * (cell.w - 4)) / (vals.len() as i32 - 1); - let y1 = cell.y + cell.h - 4 - (((vals[k] - mn) / span) * (cell.h - 16) as f64) as i32; - let y2 = cell.y + cell.h - 4 - (((vals[k + 1] - mn) / span) * (cell.h - 16) as f64) as i32; + let y1 = cell.y + cell.h - 4 - (((vals[k] - mn) / span) * (cell.h - cell_px - 8) as f64) as i32; + let y2 = cell.y + cell.h - 4 - (((vals[k + 1] - mn) / span) * (cell.h - cell_px - 8) as f64) as i32; target.draw_line(x1, y1, x2, y2); } } let label = format!("{} {:.0}%", s.label, s.last()); - draw_text_at(target, style, cell.x + 3, cell.y + 11, &label); + draw_scaled_at(target, cell_px, true, cell.x + 3, cell.y + cell_px + 2, &label, INK); } } fn draw_net_graph(&self, target: &mut dyn DrawTarget, style: &Style) { - let below = self.draw_history_graph_extra(target, style, 28); let b = self.state.bounds; + let y = self.header(target, style, &self.state.name); + let body_px = clamp_font_px((0.032 * b.h as f64) as i32, 11, 16); let down = self.series.first().map(|s| s.last()).unwrap_or(0.0); let up = self.series.get(1).map(|s| s.last()).unwrap_or(0.0); - // Two short lines: the one-line form overflows a 320px widget. - let down_line = format!( - "Down {:.0} {}/s total {}", - down, - self.unit, - fmt_bytes(self.totals.0) + // Scale from the series' max over the visible window, not the + // last values: otherwise a series that peaked earlier rides + // the top edge of the plot. + let peak = self + .series + .iter() + .flat_map(|s| s.values.iter()) + .copied() + .fold(0.0f64, f64::max); + let hi = (peak * 1.15).max(1.0); + // Legend on top: one line per direction, split into rate / + // total lines when the full line would clip at the right edge. + let mut legend: Vec<(Srgb, Vec)> = Vec::new(); + for (color, name, rate, total) in [ + (GREEN, "Down", down, self.totals.0), + (CYAN, "Up", up, self.totals.1), + ] { + let full = format!( + "{} {} total {}", + name, + fmt_rate_kbs(rate), + fmt_bytes(total) + ); + if text_width_scaled(target, body_px, false, &full) <= b.w - 30 { + legend.push((color, vec![full])); + } else { + legend.push((color, vec![ + format!("{} {}", name, fmt_rate_kbs(rate)), + format!("total {}", fmt_bytes(total)), + ])); + } + } + let legend_h = legend.iter().map(|(_, lines)| lines.len() as i32).sum::() * 18; + let mut ly = y + 2; + for (color, lines) in &legend { + for line in lines { + target.set_foreground(color.to_pixel()); + target.fill_rect(b.x + 6, ly + 3, 10, 10); + draw_scaled_at(target, body_px, false, b.x + 20, ly + body_px * 3 / 4 + 2, line, INK); + ly += 18; + } + } + // Dynamic left margin from the widest humanised Y label. + let axis_w = y_axis_width(target, 0.0, hi, body_px, &fmt_rate_kbs); + let plot_y = y + legend_h + 4; + let plot = Rect::new( + b.x + axis_w, + plot_y, + (b.w - axis_w - 8).max(10), + (b.h - (plot_y - b.y) - 6).max(10), ); - let up_line = format!( - "Up {:.0} {}/s total {}", - up, - self.unit, - fmt_bytes(self.totals.1) - ); - draw_text_at(target, style, b.x + 6, below + 11, &down_line); - draw_text_at(target, style, b.x + 6, below + 24, &up_line); + self.draw_series_lines(target, plot, 0.0, hi); + draw_y_labels(target, plot, 0.0, hi, body_px, &fmt_rate_kbs); + let _ = style; } fn draw_temp_history(&self, target: &mut dyn DrawTarget, style: &Style) { let b = self.state.bounds; let y = self.header(target, style, &self.state.name); - let plot = Rect::new(b.x + 6, y, b.w - 12, (b.h - (y - b.y) - 36).max(10)); + let body_px = clamp_font_px((0.032 * b.h as f64) as i32, 11, 16); + // Current value, bold top-right, red when over the threshold. + let cur = self.series.first().map(|s| s.last()).unwrap_or(0.0); + let col = if cur > self.threshold { RED } else { INK }; + draw_scaled_right( + target, body_px, true, b.x + b.w - 8, b.y + 17, + &format!("now {:.1}°C", cur), col, + ); + // Dynamic left margin from the widest °C Y label. + let axis_w = y_axis_width(target, self.state.min, self.state.max, body_px, &fmt_temp); + let plot = Rect::new( + b.x + axis_w, + y + 2, + (b.w - axis_w - 8).max(10), + (b.h - (y + 2 - b.y) - 22).max(10), + ); self.draw_series_lines(target, plot, self.state.min, self.state.max); - // Threshold line (dashed red). + draw_y_labels(target, plot, self.state.min, self.state.max, body_px, &fmt_temp); + // Threshold line (dashed red) + label above the line. let ty = Self::plot_y(plot, self.threshold, self.state.min, self.state.max); target.set_foreground(RED.to_pixel()); let mut x = plot.x; @@ -1047,53 +1238,62 @@ impl MonitorWidget { target.draw_line(x, ty, (x + 6).min(plot.x + plot.w), ty); x += 10; } - // Left-aligned at the start of the line: right-aligning - // under-measures the ° glyph and the label clips at the border. let tlabel = format!("{:.0}°C limit", self.threshold); - draw_text_colored(target, style, plot.x + 4, ty - 2, &tlabel, RED); - // Current value, red when over the threshold. - let cur = self.series.first().map(|s| s.last()).unwrap_or(0.0); - let col = if cur > self.threshold { RED } else { INK }; - let line = format!("now {:.1}°C threshold {:.0}°C", cur, self.threshold); - draw_text_colored(target, style, b.x + 6, b.y + b.h - 8, &line, col); + draw_scaled_right(target, 14, false, plot.x + plot.w - 2, ty - 6, &tlabel, RED); + // Min / max / avg along the bottom. + let vals: Vec = self.series.first().map(|s| s.values.iter().copied().collect()).unwrap_or_default(); + if !vals.is_empty() { + let mn = vals.iter().copied().fold(f64::INFINITY, f64::min); + let mx = vals.iter().copied().fold(f64::NEG_INFINITY, f64::max); + let av = vals.iter().sum::() / vals.len() as f64; + let line = format!("min {:.1} max {:.1} avg {:.1}", mn, mx, av); + draw_scaled_at(target, 13, false, b.x + 8, b.y + b.h - 5, &line, GREY); + } } fn draw_usage_bar(&self, target: &mut dyn DrawTarget, style: &Style) { + let _ = style; let b = self.state.bounds; + // The label is the value name ("CPU"), never the class name. let label = if self.state.text.is_empty() { self.state.name.clone() } else { self.state.text.clone() }; - draw_text_left(target, style, b.x + 6, b.y, b.y + b.h, &label); - let lw = text_width(style, &label); - let pct = format!("{:.1}%", self.state.value); - let pw = text_width(style, &pct); - let bx = b.x + 10 + lw; - let bw = (b.x + b.w - 10 - pw - bx).max(10); - let by = b.y + b.h / 4; - let bh = b.h / 2; + // Labels OUTSIDE the bar, vertically centred. The 0.45x rule + // is capped at 40 px: the literal rule gives a 209 px label + // in a 464 px-tall bar. + let bar_h = b.h - 16; + let label_px = clamp_font_px((0.45 * bar_h as f64) as i32, 11, 40); + let lw = text_width_scaled(target, label_px, true, &label); + let pct = format!("{:.0}%", self.state.value); + let pw = text_width_scaled(target, label_px, true, &pct); + let bx = b.x + 8 + lw + 12; + let bw = (b.x + b.w - 8 - pw - 12 - bx).max(10); + let by = b.y + 8; target.set_foreground(GREY_DIM.to_pixel()); - target.fill_rect(bx, by, bw, bh); - // Gradient fill: green -> amber -> red across the filled width. + target.fill_rect(bx, by, bw, bar_h); + // Gradient fill: green -> yellow -> red across the FULL bar + // width (absolute stops, C/PY style), not across the filled + // width — the colour at a position must not depend on the value. let filled = ((bw as f64 * self.frac()) as i32).max(0); let slices = 32; for i in 0..slices { if filled <= 0 { break; } - let f0 = i as f64 / slices as f64; - let x0 = bx + (filled as f64 * f0) as i32; + let x0 = bx + (filled as f64 * i as f64 / slices as f64) as i32; let x1 = bx + (filled as f64 * (i as f64 + 1.0) / slices as f64) as i32; - let (r, g, bl) = if f0 < 0.5 { - let t = f0 * 2.0; + let f_abs = ((x0 + x1) as f64 / 2.0 - bx as f64) / bw.max(1) as f64; + let (r, g, bl) = if f_abs < 0.6 { + let t = f_abs / 0.6; ( (34.0 + (245.0 - 34.0) * t) as u8, (197.0 + (158.0 - 197.0) * t) as u8, (94.0 + (11.0 - 94.0) * t) as u8, ) } else { - let t = (f0 - 0.5) * 2.0; + let t = (f_abs - 0.6) / 0.4; ( (245.0 + (239.0 - 245.0) * t) as u8, (158.0 + (68.0 - 158.0) * t) as u8, @@ -1101,80 +1301,116 @@ impl MonitorWidget { ) }; target.set_foreground(Srgb::new(r as i32, g as i32, bl as i32).to_pixel()); - target.fill_rect(x0, by, (x1 - x0).max(1), bh); + target.fill_rect(x0, by, (x1 - x0).max(1), bar_h); } target.set_foreground(GREY.to_pixel()); - target.draw_rect(bx, by, bw, bh); - draw_text_left(target, style, b.x + b.w - 6 - pw, b.y, b.y + b.h, &pct); + target.draw_rect(bx, by, bw, bar_h); + let mid = b.y + b.h / 2 + label_px / 4; + draw_scaled_at(target, label_px, true, b.x + 8, mid, &label, INK); + draw_scaled_right(target, label_px, true, b.x + b.w - 8, mid, &pct, INK); } fn draw_stack_bar(&self, target: &mut dyn DrawTarget, style: &Style) { let b = self.state.bounds; - let y = self.header(target, style, &self.state.name); + let legend_px = clamp_font_px((0.032 * b.h as f64) as i32, 11, 16); + let head_px = clamp_font_px((0.033 * b.h as f64) as i32, 11, 16); let total = self.segments_total().max(1.0); + let row_h = (1.6 * legend_px as f64) as i32; + // Legend rows (flow left to right, wrap when the width runs out). + let mut rows: Vec> = Vec::new(); + let mut row: Vec<(usize, String, i32)> = Vec::new(); + let mut lx = 6; + for (i, seg) in self.segments.iter().enumerate() { + let text = format!("{} {:.0}%", seg.label, seg.value / total * 100.0); + let tw = text_width_scaled(target, legend_px, false, &text) + 16; + if lx + tw > b.w - 4 && !row.is_empty() { + rows.push(std::mem::take(&mut row)); + lx = 6; + } + row.push((i, text, tw)); + lx += tw; + } + if !row.is_empty() { + rows.push(row); + } + let bar_h = clamp_font_px((1.5 * legend_px as f64) as i32, 8, (0.30 * b.h as f64) as i32); + let block_h = bar_h + 8 + row_h * rows.len() as i32; + // Title + total header (C style) when the widget is tall + // enough to hold it; at palette-default height the header + // would push the legend out of the widget. + let show_title = b.h - 24 >= block_h; + let y = if show_title { + let y = self.header(target, style, &self.state.name); + let unit = if self.unit.is_empty() { String::new() } else { format!(" {}", self.unit) }; + draw_scaled_right( + target, head_px, false, b.x + b.w - 8, b.y + 17, + &format!("total {:.1}{}", total, unit), INK, + ); + y + } else { + b.y + 6 + }; + let avail = b.y + b.h - y; + let by = y + ((avail - block_h) / 2).max(0); let bx = b.x + 6; let bw = b.w - 12; - let by = y + 4; - let bh = 22; let mut x = bx; for seg in &self.segments { let w = ((bw as f64 * seg.value / total) as i32).max(0); if w > 0 { target.set_foreground(seg.color.to_pixel()); - target.fill_rect(x, by, w, bh); + target.fill_rect(x, by, w, bar_h); } x += w; } target.set_foreground(GREY.to_pixel()); - target.draw_rect(bx, by, bw, bh); + target.draw_rect(bx, by, bw, bar_h); // Legend: colour chip + "label 45%". - let mut lx = bx; - let ly = by + bh + 6; - for seg in &self.segments { - target.set_foreground(seg.color.to_pixel()); - target.fill_rect(lx, ly + 2, 8, 8); - let text = format!("{} {:.0}%", seg.label, seg.value / total * 100.0); - let tw = text_width(style, &text); - draw_text_at(target, style, lx + 11, ly + 11, &text); - lx += 11 + tw + 12; - if lx > b.x + b.w - 40 { - break; + let mut ly = by + bar_h + 8 + legend_px; + for row in &rows { + let mut lx = bx; + for (i, text, tw) in row { + let seg = &self.segments[*i]; + target.set_foreground(seg.color.to_pixel()); + target.fill_rect(lx, ly - legend_px * 7 / 10, legend_px * 7 / 10, legend_px * 7 / 10); + draw_scaled_at(target, legend_px, false, lx + legend_px, ly, text, INK); + lx += tw; } + ly += row_h; } } fn draw_vertical_bar(&self, target: &mut dyn DrawTarget, style: &Style) { + let _ = style; let b = self.state.bounds; let y = self.header(target, style, &self.state.name); - let bx = b.x + 44; - let bw = (b.w - 60).max(10); - let by = y + 4; - let bh = (b.y + b.h - 8 - by).max(10); - // Scale ticks + labels. - for i in 0..=4 { - let f = i as f64 / 4.0; - let ty = by + bh - (f * bh as f64) as i32; - target.set_foreground(GREY.to_pixel()); - target.draw_line(bx - 6, ty, bx - 1, ty); - let lab = format!("{:.0}", self.state.min + f * (self.state.max - self.state.min)); - let tw = text_width(style, &lab); - draw_text_at(target, style, bx - 10 - tw, ty + 4, &lab); - } + let body_px = clamp_font_px((0.032 * b.h as f64) as i32, 11, 16); + // Dynamic scale width from the widest Y label. + let scale_w = y_axis_width(target, self.state.min, self.state.max, body_px, &fmt_num); + let bx = b.x + scale_w; + let bw = (b.x + b.w - 12 - bx).max(20); + let by = y + 2; + let bh = (b.y + b.h - 4 - by).max(10); + let val = self.state.value; + let filled = ((bh as f64 * self.frac()) as i32).max(0); target.set_foreground(GREY_DIM.to_pixel()); target.fill_rect(bx, by, bw, bh); - let filled = ((bh as f64 * self.frac()) as i32).max(0); - let col = if self.frac() < 0.7 { - GREEN - } else if self.frac() < 0.9 { + let col = if self.frac() >= 0.8 { + RED + } else if self.frac() >= 0.5 { AMBER } else { - RED + GREEN }; target.set_foreground(col.to_pixel()); target.fill_rect(bx, by + bh - filled, bw, filled); target.set_foreground(GREY.to_pixel()); target.draw_rect(bx, by, bw, bh); - // Peak-hold marker (label only when it fits inside the frame). + // Y labels at the bar's left edge: top hangs below the top + // edge, bottom sits above the bottom edge, middle centred. + draw_y_labels(target, Rect::new(bx, by, bw, bh), self.state.min, self.state.max, body_px, &fmt_num); + // Peak-hold marker + label above the line (below it when the + // peak is near the top), shrink-to-fit so it never clips. if self.state.max > self.state.min && self.peak.is_finite() { let pf = ((self.peak - self.state.min) / (self.state.max - self.state.min)).clamp(0.0, 1.0); let py = by + bh - (pf * bh as f64) as i32; @@ -1183,11 +1419,21 @@ impl MonitorWidget { target.draw_line(bx - 2, py, bx + bw + 2, py); target.set_line_width(1); let peak_txt = format!("peak {:.0}", self.peak); - if bx + bw + 4 + text_width(style, &peak_txt) < b.right() { - draw_text_colored(target, style, bx + bw + 4, py + 4, &peak_txt, RED); + let mut peak_px = 14; + while peak_px > 11 + && text_width_scaled(target, peak_px, true, &peak_txt) > bw + 6 + { + peak_px -= 1; } + let px2 = (bx + bw + 3 - text_width_scaled(target, peak_px, true, &peak_txt)).max(bx); + let label_y = if py - 6 >= by + peak_px { py - 6 } else { py + peak_px + 4 }; + draw_scaled_at(target, peak_px, true, px2, label_y, &peak_txt, INK); } - draw_text_at(target, style, bx, b.y + b.h - 8, &format!("{:.0}", self.state.value)); + // Value INSIDE the bar bottom-centre (never over a tick label). + let val_text = format!("{:.0}%", val); + let fill_dark = filled >= 16 + 8; + let col = if fill_dark { Srgb::new(255, 255, 255) } else { INK }; + draw_scaled_centered(target, 16, true, bx, by + bh - 4, bx + bw, &val_text, col); } /// Dial face + ticks + needle for the round gauges. `start_deg` is @@ -1203,21 +1449,28 @@ impl MonitorWidget { sweep_deg: f64, redline_from: f64, ) { + let _ = style; // Face. target.set_foreground(0xffffff); target.fill_arc(cx - r, cy - r, 2 * r, 2 * r, 0, 360 * 64); target.set_foreground(INK.to_pixel()); target.draw_arc(cx - r, cy - r, 2 * r, 2 * r, 0, 360 * 64); - // Redline sector (X arc: start at the redline angle, extent to - // the end of the sweep, going CCW from the sweep end). + // Redline arc along the rim (a stroked arc, not a filled + // sector: a filled sector paints red under the redline + // numerals, and red text on red is invisible). if redline_from < 1.0 { let end_deg = start_deg - sweep_deg; let red_start = start_deg - sweep_deg * redline_from; let (a1, a2) = arc64(end_deg, red_start - end_deg); target.set_foreground(RED.to_pixel()); - target.fill_arc(cx - r + 2, cy - r + 2, 2 * (r - 2), 2 * (r - 2), a1, a2); + target.set_line_width(10); + target.draw_arc(cx - r + 6, cy - r + 6, 2 * (r - 6), 2 * (r - 6), a1, a2); + target.set_line_width(1); } - // Ticks + labels. + // Ticks + labels. Numerals are ~7.5% of the dial diameter, + // bold, just inside the major tick ring; numerals in/after + // the redline are red. + let numeral_px = clamp_font_px((0.075 * 2.0 * r as f64) as i32, 13, 28); let frac = self.frac(); for i in 0..=10 { let f = i as f64 / 10.0; @@ -1234,14 +1487,23 @@ impl MonitorWidget { ); if i % 2 == 0 { let lab = format!("{:.0}", self.state.min + f * (self.state.max - self.state.min)); - let tw = text_width(style, &lab); - let lr = (r - 22) as f64; - draw_text_at( + let tw = text_width_scaled(target, numeral_px, true, &lab); + // Numeral centre radius: the glyph box's farthest + // corner in the radial direction must stay inside the + // tick ring (inner end r-10) with 4 px clearance, so a + // wide 4-digit label never crosses the dial rim. + let extent = (tw as f64 / 2.0) * ca.abs() + + (numeral_px as f64 / 2.0) * sa.abs(); + let lr = (r as f64 - 10.0 - extent - 4.0).max(8.0); + let col = if f >= redline_from { RED } else { INK }; + draw_scaled_at( target, - style, + numeral_px, + true, cx + (lr * ca) as i32 - tw / 2, - cy - (lr * sa) as i32 + 4, + cy - (lr * sa) as i32 + numeral_px * 7 / 20, &lab, + col, ); } } @@ -1258,70 +1520,85 @@ impl MonitorWidget { } fn draw_tachometer(&self, target: &mut dyn DrawTarget, style: &Style) { + let _ = style; let b = self.state.bounds; - let y = self.header(target, style, &self.state.name); - let area_h = b.y + b.h - y - 34; - let r = (b.w.min(area_h) / 2 - 6).max(8); + // No header: the dial fills the widget; the title ("RPM") + // lives inside the dial below the top numerals. + let r = (b.w.min(b.h) / 2 - 6).max(8); let cx = b.x + b.w / 2; - let cy = y + area_h / 2 + 4; + let cy = b.y + b.h / 2; self.draw_dial(target, style, cx, cy, r, 225.0, 270.0, self.redline_frac); - let readout = format!("{:.0} {}", self.state.value, self.unit); - draw_text_centered(target, style, b.x, cy + r + 2, b.x + b.w, cy + r + 18, &readout); - let peak = format!("peak {:.0} {}", self.peak, self.unit); - draw_text_colored( - target, - style, - b.x + b.w / 2 - text_width(style, &peak) / 2, - cy + r + 32, - &peak, - RED, + let numeral_px = clamp_font_px((0.075 * 2.0 * r as f64) as i32, 13, 28); + // Title below the top numeral's bottom edge. + let title_px = clamp_font_px(numeral_px - 4, 13, 24); + let title = if self.unit.is_empty() { + self.state.name.clone() + } else { + self.unit.clone() + }; + let title_y = cy - (r - 22) + numeral_px * 3 / 4 + title_px * 3 / 4 + 4; + draw_scaled_centered(target, title_px, true, b.x, title_y, b.x + b.w, &title, INK); + // Current value + peak readout inside the dial below the hub. + let readout_px = clamp_font_px((0.05 * 2.0 * r as f64) as i32, 13, 20); + let readout = format!("{:.0} (peak {:.0})", self.state.value, self.peak); + draw_scaled_centered( + target, readout_px, true, b.x, cy + (r as f64 * 0.45) as i32, + b.x + b.w, &readout, INK, ); } + /// Arc-line gauge, no needle (C/PY design): a grey track, a + /// zone-coloured value arc (green <60%, amber <80%, red above), + /// a big centre value + sub-label, endpoints under the arc ends. fn draw_arc_gauge(&self, target: &mut dyn DrawTarget, style: &Style) { let b = self.state.bounds; let y = self.header(target, style, &self.state.name); - let area_h = b.y + b.h - y - 8; - let r = (b.w / 2 - 8).min(area_h - 30).max(8); + let r = ((b.w / 2 - 20).min(b.h - 64)).max(8); let cx = b.x + b.w / 2; - let cy = y + r + 4; - // Face + coloured zone sectors (top semicircle: 180 -> 0). - // The face is the top half-disc only; a full-circle fill would - // paint a white half-disc over the widget background below the - // diameter line (and past the bottom border at small sizes). - target.set_foreground(0xffffff); - target.fill_arc(cx - r, cy - r, 2 * r, 2 * r, 0, 180 * 64); - for (start, extent, col) in [ - (72.0, 108.0, GREEN_DIM), - (27.0, 45.0, AMBER), - (0.0, 27.0, RED), - ] { - let (a1, a2) = arc64(start, extent); - target.set_foreground(col.to_pixel()); - target.fill_arc(cx - r + 3, cy - r + 3, 2 * (r - 3), 2 * (r - 3), a1, a2); - } - target.set_foreground(INK.to_pixel()); - target.draw_arc(cx - r, cy - r, 2 * r, 2 * r, 0, 180 * 64); - // Needle. + let cy = y + r + 8; let frac = self.frac(); - let nang = (180.0 - 180.0 * frac).to_radians(); - let nl = r - 8; - target.set_line_width(2); - target.draw_line(cx, cy, cx + (nl as f64 * nang.cos()) as i32, cy - (nl as f64 * nang.sin()) as i32); + let centre_px = clamp_font_px((0.10 * 2.0 * r as f64) as i32, 16, 48); + let end_px = clamp_font_px((0.04 * 2.0 * r as f64) as i32, 11, 18); + let sub_px = clamp_font_px((0.04 * 2.0 * r as f64) as i32, 11, 18); + // Track (full semicircle) + zone-coloured value arc. + target.set_line_width(14); + target.set_foreground(GREY_DIM.to_pixel()); + let (a1, a2) = arc64(0.0, 180.0); + target.draw_arc(cx - r, cy - r, 2 * r, 2 * r, a1, a2); + for (f0, f1, col) in [(0.0, 0.6, GREEN), (0.6, 0.8, AMBER), (0.8, 1.0, RED)] { + if frac > f0 { + let (a1, a2) = arc64(180.0 - 180.0 * frac.min(f1), 180.0 * (frac.min(f1) - f0)); + target.set_foreground(col.to_pixel()); + target.draw_arc(cx - r, cy - r, 2 * r, 2 * r, a1, a2); + } + } target.set_line_width(1); - target.fill_arc(cx - 4, cy - 4, 8, 8, 0, 360 * 64); - // Big % below the diameter line. + // Endpoints under the arc ends. + draw_scaled_at(target, end_px, false, cx - r - 4, cy + 16, "0", GREY); + draw_scaled_right(target, end_px, false, cx + r + 4, cy + 16, "100", GREY); + // Centre value (coloured by threshold) + sub-label. + let col = if frac >= 0.8 { RED } else if frac >= 0.6 { AMBER } else { GREEN }; let pct = format!("{:.0}%", self.state.value); - draw_text_centered(target, style, cx - r, cy + 6, cx + r, cy + 22, &pct); + let value_base = cy - (r as f64 * 0.35) as i32; + draw_scaled_centered(target, centre_px, true, cx - r, value_base, cx + r, &pct, col); + let sub = if self.unit.is_empty() { "load".to_string() } else { self.unit.clone() }; + draw_scaled_centered( + target, sub_px, false, cx - r, value_base + sub_px * 3 / 4 + 10, cx + r, &sub, GREY, + ); } fn draw_donut_gauge(&self, target: &mut dyn DrawTarget, style: &Style) { + // No top-left title: the centre label carries the value name + // (the title would duplicate it). + let _ = style; let b = self.state.bounds; - let y = self.header(target, style, &self.state.name); - let area_h = b.y + b.h - y - 8; - let r = (b.w.min(area_h) / 2 - 6).max(8); + let r0 = (b.w.min(b.h) / 2 - 12).max(8); + // Ring thickness 8-10% of the diameter; the stroke extends + // thick/2 past r, so shrink r to keep the ring inside. + let thick = clamp_font_px((0.09 * 2.0 * r0 as f64) as i32, 8, 48); + let r = (r0 - thick / 2).max(8); let cx = b.x + b.w / 2; - let cy = y + area_h / 2; + let cy = b.y + b.h / 2; let frac = self.frac(); // Track ring. target.set_foreground(GREY_DIM.to_pixel()); @@ -1335,10 +1612,22 @@ impl MonitorWidget { } // Punch the hole: inner disc in the frame colour. target.set_foreground(0xffffff); - let ir = r * 2 / 3; + let ir = r - thick; target.fill_arc(cx - ir, cy - ir, 2 * ir, 2 * ir, 0, 360 * 64); + // Centre value + value-name label. + let centre_px = clamp_font_px((0.10 * 2.0 * r as f64) as i32, 16, 44); + let label_px = clamp_font_px((0.04 * 2.0 * r as f64) as i32, 11, 18); let pct = format!("{:.0}%", self.state.value); - draw_text_centered(target, style, cx - r, cy - 8, cx + r, cy + 8, &pct); + let value_base = cy - 2; + draw_scaled_centered(target, centre_px, true, cx - r, value_base, cx + r, &pct, INK); + let label = if self.state.text.is_empty() { + self.state.name.clone() + } else { + self.state.text.clone() + }; + draw_scaled_centered( + target, label_px, false, cx - r, value_base + label_px + 6, cx + r, &label, GREY, + ); } } @@ -1346,23 +1635,30 @@ impl MonitorWidget { fn draw_process_list(&self, target: &mut dyn DrawTarget, style: &Style) { let b = self.state.bounds; let y = self.header(target, style, &self.state.name); - // Columns: PID 52 | NAME flex | CPU 96 (bar) | MEM 64. + // "N procs" top-right, 13 px. + let nprocs = format!("{} procs", self.rows.len()); + draw_scaled_right(target, 13, false, b.x + b.w - 8, b.y + 17, &nprocs, GREY); + // Columns: PID 68 (a 7-digit live PID is ~56 px at 13 px, + // the old 52 px column let it bleed into the name) | NAME + // flex | CPU 96 (bar) | MEM 64. let x_pid = b.x + 6; - let x_name = x_pid + 52; + let x_name = x_pid + 68; let x_cpu = b.x + b.w - 170; let x_mem = b.x + b.w - 66; + let head_px = 13; let headers = [(x_pid, "PID", 0usize), (x_name, "NAME", 1), (x_cpu, "CPU%", 2), (x_mem, "MEM", 3)]; for (x, label, col) in headers { let mut text = label.to_string(); if self.sort_col == col { - text.push_str(if self.sort_desc { " ▼" } else { " ▲" }); + // Sort indicator, padded >=4 px from the label. + text.push_str(if self.sort_desc { " ▼" } else { " ▲" }); } - draw_text_at(target, style, x, y + 11, &text); + draw_scaled_at(target, head_px, true, x, y + head_px + 2, &text, INK); } target.set_foreground(GREY.to_pixel()); - target.draw_line(b.x + 6, y + 15, b.x + b.w - 6, y + 15); - let row_h = 16; - let mut ry = y + 17; + target.draw_line(b.x + 6, y + head_px + 6, b.x + b.w - 6, y + head_px + 6); + let row_h = 23; + let mut ry = y + head_px + 10; for (i, row) in self.rows.iter().enumerate() { if ry + row_h > b.y + b.h - 4 { break; @@ -1371,40 +1667,61 @@ impl MonitorWidget { target.set_foreground(0xdbeafe); target.fill_rect(b.x + 4, ry, b.w - 8, row_h); } - // In-cell CPU% bar. + // In-cell CPU% bar (colour-coded: red >=80, amber >=50). let cpu_w = 56; let cpu_frac = (row.cpu / 100.0).clamp(0.0, 1.0); target.set_foreground(GREY_DIM.to_pixel()); - target.fill_rect(x_cpu, ry + 3, cpu_w, 10); - target.set_foreground(if row.cpu > 80.0 { RED } else if row.cpu > 40.0 { AMBER } else { GREEN }.to_pixel()); - target.fill_rect(x_cpu, ry + 3, (cpu_w as f64 * cpu_frac) as i32, 10); + target.fill_rect(x_cpu, ry + 5, cpu_w, 12); + target.set_foreground(if row.cpu >= 80.0 { RED } else if row.cpu >= 50.0 { AMBER } else { GREEN }.to_pixel()); + target.fill_rect(x_cpu, ry + 5, (cpu_w as f64 * cpu_frac) as i32, 12); let cpu_txt = format!("{:.1}%", row.cpu); - draw_text_at(target, style, x_cpu + cpu_w + 4, ry + 11, &cpu_txt); - draw_text_at(target, style, x_pid, ry + 11, &row.pid.to_string()); - draw_text_at(target, style, x_name, ry + 11, &row.name); - draw_text_at(target, style, x_mem, ry + 11, &format!("{:.0}M", row.mem_mb)); + draw_scaled_at(target, 13, false, x_cpu + cpu_w + 4, ry + 16, &cpu_txt, INK); + draw_scaled_at(target, 13, false, x_pid, ry + 16, &row.pid.to_string(), INK); + draw_scaled_at(target, 13, false, x_name, ry + 16, &row.name, INK); + draw_scaled_at(target, 13, false, x_mem, ry + 16, &format!("{:.0}M", row.mem_mb), INK); ry += row_h; } } + /// PY two-line layout: title + values on line 1, sub-labels + /// ("1 min" / "5 min" / "15 min") under each value, uptime + + /// core count on line 2; the value block is vertically centred. fn draw_load_badge(&self, target: &mut dyn DrawTarget, style: &Style) { + let _ = style; let b = self.state.bounds; let cores = std::thread::available_parallelism() .map(|n| n.get() as f64) .unwrap_or(1.0); - draw_text_left(target, style, b.x + 8, b.y, b.y + b.h, "LOAD"); - let mut x = b.x + 8 + text_width(style, "LOAD") + 10; - for l in self.loads { - let col = Self::load_color(l, cores); + let title_px = clamp_font_px((0.033 * b.h as f64) as i32, 11, 16); + let value_px = clamp_font_px((0.055 * b.h as f64) as i32, 13, 28); + let sub_px = 14; + // "N cores" top-right. + draw_scaled_right(target, title_px, false, b.x + b.w - 8, b.y + 17, &format!("{} cores", cores as i32), GREY); + draw_scaled_at(target, title_px, true, b.x + 8, b.y + 17, "LOAD", INK); + // The three values, evenly spaced; sub-labels underneath. + let block_top = b.y + 24; + let block_h = b.h - 24 - 22; + let value_h = value_px + 4 + sub_px; + let vy = block_top + ((block_h - value_h) / 2).max(0); + let mut x = b.x + 8; + let gap = 28; + for (i, l) in self.loads.iter().enumerate() { + let col = Self::load_color(*l, cores); let text = format!("{:.2}", l); - draw_text_colored(target, style, x, b.y + b.h / 2 + 5, &text, col); - x += text_width(style, &text) + 10; + draw_scaled_at(target, value_px, true, x, vy + value_px, &text, col); + let sub = ["1 min", "5 min", "15 min"][i.min(2)]; + draw_scaled_at(target, sub_px, false, x, vy + value_px + 4 + sub_px, sub, GREY); + x += text_width_scaled(target, value_px, true, &text) + gap; } + // Uptime bottom-left. let up = format!("up {}", fmt_uptime(self.uptime_secs)); - draw_text_at(target, style, b.x + b.w - 6 - text_width(style, &up), b.y + b.h / 2 + 5, &up); + draw_scaled_at(target, 14, false, b.x + 8, b.y + b.h - 6, &up, GREY); } - /// One monitor button cell inside `rect`. + /// One monitor button cell inside `rect`: status lamp, bold + /// service label, status on the label line (right-aligned), + /// detail on its own line below. `dot_d` / `label_px` / + /// `status_px` / `detail_px` scale with the cell height. fn draw_monitor_cell( &self, target: &mut dyn DrawTarget, @@ -1418,13 +1735,20 @@ impl MonitorWidget { std::mem::swap(&mut st.fill_color, &mut st.outline_color); } draw_polished(target, &st, rect.x, rect.y, rect.right(), rect.bottom()); - // Status lamp. - let cx = rect.x + 14; - let cy = rect.y + rect.h / 2; + let dot_d = clamp_font_px((0.11 * rect.h as f64) as i32, 10, 30); + let label_px = clamp_font_px((0.10 * rect.h as f64) as i32, 13, 24); + let status_px = clamp_font_px((0.09 * rect.h as f64) as i32, 12, 20); + let detail_px = clamp_font_px((0.06 * rect.h as f64) as i32, 11, 14); + // Content block, vertically centred. + let block_h = label_px + 4 + detail_px; + let top = rect.y + ((rect.h - block_h) / 2).max(0); + // Status lamp, centred on the block. + let cx = rect.x + 12 + dot_d / 2; + let cy = top + block_h / 2; target.set_foreground(btn.status.color().to_pixel()); - target.fill_arc(cx - 7, cy - 7, 14, 14, 0, 360 * 64); + target.fill_arc(cx - dot_d / 2, cy - dot_d / 2, dot_d, dot_d, 0, 360 * 64); target.set_foreground(INK.to_pixel()); - target.draw_arc(cx - 7, cy - 7, 14, 14, 0, 360 * 64); + target.draw_arc(cx - dot_d / 2, cy - dot_d / 2, dot_d, dot_d, 0, 360 * 64); // Glow outline: green when up, red when down, dim when unknown. if btn.status != MonitorStatus::Unknown { target.set_line_width(2); @@ -1432,17 +1756,26 @@ impl MonitorWidget { target.draw_rect(rect.x + 2, rect.y + 2, rect.w - 4, rect.h - 4); target.set_line_width(1); } - draw_text_left(target, style, rect.x + 26, rect.y, rect.y + rect.h, &btn.label); - let status = format!("{} {}", btn.status.label(), btn.detail); - let tw = text_width(style, &status); - draw_text_colored( - target, - style, - rect.x + rect.w - 6 - tw, - rect.y + rect.h / 2 + 5, - &status, - btn.status.color(), + let lx = rect.x + 12 + dot_d + 10; + let label_base = top + label_px; + draw_scaled_at(target, label_px, true, lx, label_base, &btn.label, INK); + // Status on the label line, right-aligned ("UP"/"DOWN" only). + draw_scaled_right( + target, status_px, true, rect.x + rect.w - 8, label_base, + btn.status.label(), btn.status.color(), ); + // Detail on its own line below the label (never truncated + // into the status: it has the full cell width). + if !btn.detail.is_empty() { + let detail = btn.detail.clone(); + let dw = text_width_scaled(target, detail_px, false, &detail); + let dx = if lx + dw > rect.x + rect.w - 8 { + rect.x + rect.w - 8 - dw + } else { + lx + }; + draw_scaled_at(target, detail_px, false, dx.max(lx), label_base + 4 + detail_px, &detail, GREY); + } } fn draw_monitor_button(&self, target: &mut dyn DrawTarget, style: &Style) { @@ -1458,8 +1791,12 @@ impl MonitorWidget { fn draw_monitor_grid(&self, target: &mut dyn DrawTarget, style: &Style) { let b = self.state.bounds; let y = self.header(target, style, &self.state.name); + // Summary "N/M up", bold, top-right on the title line. + let up = self.buttons.iter().filter(|b| b.status == MonitorStatus::Up).count(); + let summary = format!("{}/{} up", up, self.buttons.len()); + draw_scaled_right(target, 14, true, b.x + b.w - 8, b.y + 17, &summary, INK); let n = self.buttons.len().max(1); - let cols = 2; + let cols = (n as f64).sqrt().ceil() as i32; let rows = (n as i32 + cols - 1) / cols; let cw = (b.w - 12) / cols; let ch = (b.h - (y - b.y) - 8) / rows.max(1); @@ -1472,40 +1809,59 @@ impl MonitorWidget { } } + /// C/PY layout: hero value top-left, "max" top-right, sparkline + /// below the hero, usage bar strip at the bottom with a % label. fn draw_sys_box(&self, target: &mut dyn DrawTarget, style: &Style) { + let _ = style; let b = self.state.bounds; let title = if self.title.is_empty() { self.state.name.clone() } else { self.title.clone() }; - let y = self.header(target, style, &title); - // Big number. + let title_px = clamp_font_px((0.033 * b.h as f64) as i32, 11, 16); + let hero_px = clamp_font_px((0.10 * b.h as f64) as i32, 20, 32); + let bar_h = clamp_font_px((0.055 * b.h as f64) as i32, 20, 28); + // Title top-left, "max" top-right. + draw_scaled_at(target, title_px, true, b.x + 8, b.y + 17, &title, INK); + draw_scaled_right( + target, 13, false, b.x + b.w - 8, b.y + 17, + &format!("max {:.0}{}", self.state.max, self.unit), GREY, + ); + // Hero value top-left under the title. let big = format!("{:.0}{}", self.state.value, self.unit); - draw_text_centered(target, style, b.x, y, b.x + b.w, y + 18, &big); - // History graph. - let plot = Rect::new(b.x + 6, y + 20, b.w - 12, (b.h - (y + 20 - b.y) - 26).max(10)); + let hero_base = b.y + 17 + 6 + hero_px; + draw_scaled_at(target, hero_px, true, b.x + 8, hero_base, &big, INK); + // History graph below the hero. + let plot = Rect::new( + b.x + 6, + hero_base + 8, + b.w - 12, + (b.y + b.h - bar_h - 8 - (hero_base + 8)).max(10), + ); self.draw_series_lines(target, plot, self.state.min, self.state.max); - // Usage bar strip. + // Usage bar strip with a % label. let bx = b.x + 6; let bw = b.w - 12; - let by = b.y + b.h - 14; + let by = b.y + b.h - bar_h - 4; target.set_foreground(GREY_DIM.to_pixel()); - target.fill_rect(bx, by, bw, 8); + target.fill_rect(bx, by, bw, bar_h); target.set_foreground(GREEN.to_pixel()); - target.fill_rect(bx, by, ((bw as f64 * self.frac()) as i32).max(0), 8); + target.fill_rect(bx, by, ((bw as f64 * self.frac()) as i32).max(0), bar_h); target.set_foreground(GREY.to_pixel()); - target.draw_rect(bx, by, bw, 8); + target.draw_rect(bx, by, bw, bar_h); + let pct = format!("{:.0}%", self.frac() * 100.0); + draw_scaled_centered(target, 14, true, bx, by + bar_h / 2 + 5, bx + bw, &pct, INK); } /// Cell index of a point inside the monitor grid, if any. fn grid_cell_at(&self, x: i32, y: i32) -> Option { let b = self.state.bounds; - let top = b.y + 20; + let top = b.y + 24; if y < top || x < b.x + 6 { return None; } - let cols = 2; + let cols = (self.buttons.len().max(1) as f64).sqrt().ceil() as i32; let rows = ((self.buttons.len() as i32 + cols - 1) / cols).max(1); let cw = (b.w - 12) / cols; let ch = (b.h - (top - b.y) - 8) / rows; @@ -1576,10 +1932,10 @@ monitor_impl!( self.state.focused = true; // Header click sorts; body click selects a row. let b = self.state.bounds; - let hy = b.y + 20; - if y < hy + 17 { + let hy = b.y + 24; + if y < hy + 23 { let x_pid = b.x + 6; - let x_name = x_pid + 52; + let x_name = x_pid + 68; let x_cpu = b.x + b.w - 170; let x_mem = b.x + b.w - 66; let col = if x < x_name { @@ -1593,7 +1949,7 @@ monitor_impl!( }; self.sort_by(col); } else { - let row = ((y - (hy + 17)) / 16) as usize; + let row = ((y - (hy + 23)) / 23) as usize; if row < self.rows.len() { self.selected = Some(row); } @@ -1729,7 +2085,7 @@ mod tests { #[test] fn stack_segments_sum() { let m = MonitorWidget::new("StackBar", "StackBar", 0, 0, 360, 80); - assert!((m.segments_total() - 100.0).abs() < 1e-9); + assert!((m.segments_total() - 30.3).abs() < 1e-9); assert_eq!(m.segments.len(), 4); }