RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
System Monitor: expandable CPU and RAM cards
oxydizere8b0f1431a0e
diff --git a/docs/system-monitor.md b/docs/system-monitor.mdindex 860640c..35db4a5 100644--- a/docs/system-monitor.md+++ b/docs/system-monitor.md@@ -9,7 +9,24 @@ client has inhibited compositor shortcuts.CPU and RAM summary cards show large current percentages and shaded 60-secondgraphs. CPU includes its reported frequency and logical CPU count; RAM includesused/total capacity and a usage bar. Graph axes show CPU percentages and memory-capacity. The cards use a compact layout in narrow windows. System RAM usage is+capacity. The cards use a compact layout in narrow windows.++Click a card (or focus it with Tab and press Enter) to expand it to the full+width; the other card slides away. Click the expanded card again, use the+collapse button at its top-right corner, or press Escape outside the search+field to bring both cards back.+Expanded CPU adds a vertical load meter made of horizontal segments for every+online logical CPU. The meters fill from the bottom and are about two digits+wide, with kernel CPU numbers and percentages when there is room. Many-core+machines drop the percentages, then the numbers, and use narrower meters if+needed. The card also shows the 1, 5 and 15 minute load averages and the system's+thread count. Expanded RAM adds a bar of used+memory and reclaimable cache, then used, cached (buffers, page cache and+reclaimable slab, as `free` reports buff/cache), swap, available, free and+shared (tmpfs and shared memory) amounts, and the four processes of any user+holding the most resident memory. Both keep the 60-second graph when the+window is wide enough. FreeBSD reports cached memory as inactive pages and+has no shared figure or thread count. System RAM usage is`MemTotal - MemAvailable`; process memory is resident memory. A processusing one CPU core reads 100%, so multithreaded processes can exceed 100%.New processes and the first sample after resuming show an em dash untildiff --git a/po/rediwm.pot b/po/rediwm.potindex 4e341ac..1100f48 100644--- a/po/rediwm.pot+++ b/po/rediwm.pot@@ -644,6 +644,10 @@ msgstr ""msgid "Automatic updates are off. Applications keep the last applied colors."msgstr ""+#: src/system_monitor/app_summary_ram.zig+msgid "Available"+msgstr ""+#: src/control_center/sections/bluetooth.zigmsgid "Available Devices"msgstr ""@@ -940,6 +944,10 @@ msgstr ""msgid "Cable unplugged"msgstr ""+#: src/system_monitor/app_summary_ram.zig+msgid "Cached"+msgstr ""+#: src/files/app_model.zigmsgid "Calculate size"msgstr ""@@ -1400,6 +1408,10 @@ msgstr ""msgid "Closing ends this shell and its running jobs."msgstr ""+#: src/system_monitor/app.zig+msgid "Collapse"+msgstr ""+#: src/system_monitor/app_footer.zigmsgid "Collecting processes…"msgstr ""@@ -3196,6 +3208,10 @@ msgstr ""msgid "Four keyboard layouts is the most XKB allows."msgstr ""+#: src/system_monitor/app_summary_ram.zig+msgid "Free"+msgstr ""+#: src/control_center/sections/region.zigmsgid "Friday"msgstr ""@@ -3792,6 +3808,10 @@ msgstr ""msgid "List"msgstr ""+#: src/system_monitor/app_summary_cpu.zig+msgid "Load"+msgstr ""+#: src/control_center/sections/printers_tools.zigmsgid "Loaded paper height"msgstr ""@@ -4068,6 +4088,10 @@ msgstr ""msgid "More settings"msgstr ""+#: src/system_monitor/app_summary_ram.zig+msgid "Most memory"+msgstr ""+#: src/control_center/sections/appearance.zigmsgid "Motion & feedback"msgstr ""@@ -4973,6 +4997,10 @@ msgstr ""msgid "Pending"msgstr ""+#: src/system_monitor/app_summary_cpu.zig+msgid "Per-core load is unavailable"+msgstr ""+#: src/control_center/sections/power.zigmsgid "Performance"msgstr ""@@ -5165,7 +5193,7 @@ msgstr ""msgid "Prevent this device from connecting."msgstr ""-#: src/files/app_torrents.zig+#: src/files/app_audio_bar.zigmsgid "Previous"msgstr ""@@ -6435,6 +6463,10 @@ msgstr ""msgid "Speed"msgstr ""+#: src/control_center/sections/shortcuts.zig+msgid "Spread all canvas windows into a grid, including minimized windows."+msgstr ""+#: src/control_center/sections/users.zigmsgid "Standard"msgstr ""@@ -6563,6 +6595,10 @@ msgstr ""msgid "Suspend Auto"msgstr ""+#: src/system_monitor/app_summary_ram.zig+msgid "Swap"+msgstr ""+#: src/control_center/sections/shortcuts.zigmsgid "Swap Down"msgstr ""@@ -7559,6 +7595,10 @@ msgstr ""msgid "Use suggested resolution"msgstr ""+#: src/system_monitor/app_summary_ram.zig+msgid "Used"+msgstr ""+#: src/control_center/sections/default_apps.zigmsgid "Used for desktop folders, app shortcuts and apps that run in a terminal."msgstr ""@@ -7719,6 +7759,10 @@ msgstr ""msgid "Window Management"msgstr ""+#: src/control_center/sections/shortcuts.zig+msgid "Window Overview"+msgstr ""+#: src/control_center/sections/appearance_rows.zigmsgid "Window and panel transitions"msgstr ""@@ -8739,6 +8783,12 @@ msgid_plural "{n} services, {enabled} enabled"msgstr[0] ""msgstr[1] ""+#: src/system_monitor/app_summary_cpu.zig+msgid "{n} thread"+msgid_plural "{n} threads"+msgstr[0] ""+msgstr[1] ""+#: src/files/app_torrents.zigmsgid "{rate} KiB/s"msgstr ""diff --git a/src/system_monitor/AGENTS.md b/src/system_monitor/AGENTS.mdindex aa9e4d2..aea0018 100644--- a/src/system_monitor/AGENTS.md+++ b/src/system_monitor/AGENTS.md@@ -9,7 +9,8 @@(`kern.proc` sysctls; a `Process` holds the `kinfo_proc` taken at open, CPU isin microseconds). Never read`/proc` outside a backend; a new OS needs `Process`, `List`, `cpuTotals`,- `memoryTotals`, `systemStats` and `ticksPerSecond`. Optional footer telemetry+ `cpuCores`, `memoryTotals`, `systemStats` and `ticksPerSecond`. Per-CPU+ loads pair cores by kernel id, not position (CPUs go offline). Optional footer telemetrylives in `proc_linux_system.zig`; rates reset with the worker generation.CPU and GPU temperatures stay separate; GPU hwmon reads only the die/packagechannel. Optional NVIDIA NVML (`proc_gpu.zig`) is owned by the active worker,@@ -28,6 +29,10 @@action opens a pidfd first, checks the proc identity, UIDs and protected exe,verifies the pidfd's fdinfo identity and liveness, then signals that fd.Never fall back to `kill(pid)`. Tests signal only disposable fixtures.+* The CPU/RAM cards and the expanded card's collapse button are shared+ widgets (`App.cards`) that `app_summary.layout` places over hand-painted+ cards; visible cards toggle expansion, and the hidden card has no size to hit.+ Expansion is applied after dispatch (`card_request`) and eases `card_t`.* `App.ensureWidgets` runs after App has a stable address. Widget trees persistacross snapshots so focus, presses and field strings survive. Callbacks setpending actions; modal tree changes happen after dispatch returns.diff --git a/src/system_monitor/app.zig b/src/system_monitor/app.zigindex 4c4066c..3b37b17 100644--- a/src/system_monitor/app.zig+++ b/src/system_monitor/app.zig@@ -45,6 +45,14 @@ pub const App = struct {py: f32 = -1,root: W = .{ .kind = .container },sections: [6]W = undefined,+ /// CPU card, RAM card, collapse button (`app_summary.zig` places them).+ cards: [3]W = undefined,+ /// The card that is expanded, or was last; `card_t` eases 0 → 1 open.+ card: usize = 0,+ card_open: bool = false,+ card_anim: ui.anim.Anim = .{},+ card_t: f32 = 0,+ card_request: ?usize = null,toolbar: [3]W = undefined,headers: [6]W = undefined,header_labels: [6][64]u8 = undefined,@@ -127,9 +135,17 @@ pub const App = struct {self.button(tr("Force quit…"), 3, 124),};self.footer[1].kind.button.destructive = true;+ for (self.cards[0..2], 0..) |*card, i| card.* = .{+ .name = if (i == 0) "monitor_cpu_card" else "monitor_ram_card",+ .kind = .{ .row = .{ .owner = self, .id = 30 + i, .on_click = clicked, .underlay = true } },+ };+ self.cards[2] = self.button(tr("Collapse"), 32, 28);+ self.cards[2].height = .{ .fixed = 28 };+ self.cards[2].kind.button.icon = .minimize;+ self.cards[2].kind.button.variant = .ghost;for (self.footer[1..]) |*control| control.height = .{ .fixed = 38 };self.sections = .{- .{ .kind = .container, .height = .{ .fixed = 150 } },+ .{ .kind = .container, .height = .{ .fixed = 150 }, .children = &self.cards },.{ .kind = .container, .height = .{ .fixed = 50 }, .padding = .{ .left = 16, .right = 16, .top = 4 }, .gap = 8, .children = &self.toolbar },.{ .kind = .container, .height = .{ .fixed = 36 }, .padding = .{ .left = 16, .right = scrollbar.gutter(theme.global.scrollbar_width) + 16 }, .children = &self.headers },.{ .kind = .container, .height = .{ .flex = 1 } },@@ -151,6 +167,7 @@ pub const App = struct {ui.measure.measure(&self.root, @floatFromInt(self.w), @floatFromInt(self.h));ui.arrange.arrange(&self.root, 0, 0, @floatFromInt(self.w), @floatFromInt(self.h));self.layoutFooter();+ summary.layout(self);const box = self.dialogBox();ui.measure.measure(&self.modal, 252, 34);ui.arrange.arrange(&self.modal, box.x + box.w - 276, box.y + box.h - 50, 252, 34);@@ -182,6 +199,7 @@ pub const App = struct {10...15 => self.model.setSort(@fromBackingInt(@intCast(id - 10))),20 => self.pending = .cancel,21 => self.pending = .force,+ 30...32 => self.card_request = id - 30,else => {},}self.dirty = true;@@ -197,7 +215,27 @@ pub const App = struct {const row = self.model.selectedProcess() orelse return false;return row.uids != null and proc.owned(row.uids.?, self.model.uid) and !row.protected and row.state != 'Z' and row.state != 'X';}+ /// Toggles card 0/1 or collapses (2) once dispatch has returned, then+ /// re-targets the pointer: the widget under it just moved or vanished.+ fn applyCardRequest(self: *App) void {+ const request = self.card_request orelse return;+ self.card_request = null;+ if (request < 2) {+ // A card still sliding back can't take over mid-way.+ if ((self.card_open or self.card_t > 0) and request != self.card) return;+ self.card = request;+ self.card_open = !self.card_open;+ } else self.card_open = false;+ const now = ui.key_repeat.nowMs();+ self.card_anim.retargetTo(now, if (self.card_open) 1 else 0, ui.anim.curveFor(.panel_slide));+ self.layout();+ // The card stays focusable while open; only the collapse button vanishes.+ if (!self.card_open and self.dispatcher.focused == &self.cards[2]) self.dispatcher.focus(&self.root, &self.cards[self.card]);+ self.dispatcher.pointerMotion(self.tree(), self.px, self.py);+ self.dirty = true;+ }fn applyPending(self: *App) void {+ self.applyCardRequest();const pending = self.pending;self.pending = .none;if (pending == .none) return;@@ -318,6 +356,11 @@ pub const App = struct {ui.widgets.text_input.selectAll(&self.toolbar[0]);return;}+ if (sym == c.XKB_KEY_Escape and self.card_open and self.dispatcher.focused != &self.toolbar[0]) {+ self.card_request = 2;+ self.applyPending();+ return;+ }if (sym == c.XKB_KEY_Escape) {if (self.toolbar[0].kind.text_input.value.len > 0) {ui.widgets.text_input.selectAll(&self.toolbar[0]);@@ -375,6 +418,7 @@ pub const App = struct {fn activateFocused(self: *App) void {const focused = self.dispatcher.focused orelse return;if (focused.kind == .button) ui.widgets.button.press(focused);+ if (focused.kind == .row) if (focused.kind.row.on_click) |click| click(focused.kind.row.owner, focused.kind.row.id);self.applyPending();}pub fn keyRepeats(self: *App, sym: u32, text: []const u8) bool {@@ -405,6 +449,12 @@ pub const App = struct {return scrollbar.Geometry.compute(.vertical, .{ .x = list.x + list.w - gutter, .y = list.y, .w = gutter, .h = list.h }, list.h, @as(f32, @floatFromInt(self.model.rows.items.len)) * @as(f32, @floatCast(row_h)), @floatCast(self.model.scroll));}pub fn stepAnimations(self: *App, now: i64) void {+ const t = if (self.card_anim.settled(now)) self.card_anim.to else self.card_anim.value(now);+ if (t != self.card_t) {+ self.card_t = t;+ self.layout();+ self.dirty = true;+ }const index = self.processAt();const hovered = if (index) |i| blk: {const identity = self.model.snapshot.?.processes[self.model.rows.items[i]].identity;@@ -444,7 +494,7 @@ pub const App = struct {pub fn animationTimeout(self: *App, now: i64) ?u32 {if (self.suspended) return null;var timeout: ?u32 = if (self.bar.active) 16 else if (self.bar.deadline) |deadline| @intCast(@min(60000, @max(0, deadline - now))) else null;- if (self.row_hover.animating(now)) timeout = 16;+ if (self.row_hover.animating(now) or !self.card_anim.settled(now)) timeout = 16;for (self.selections.items) |selection| if (!selection.fade.animation.settled(now)) {timeout = if (timeout) |existing| @min(existing, 16) else 16;break;diff --git a/src/system_monitor/app_summary.zig b/src/system_monitor/app_summary.zigindex 3c352a8..2080ec9 100644--- a/src/system_monitor/app_summary.zig+++ b/src/system_monitor/app_summary.zig@@ -1,4 +1,8 @@//! CPU and RAM cards: current values beside a bounded, gap-aware history.+//! Clicking a card grows it to the full width (`app_summary_cpu.zig`,+//! `app_summary_ram.zig`) while the other slides away; the expanded card's+//! surface or collapse button brings both back. The cards and that button are shared+//! widgets placed here after the tree is arranged; their pixels are ours.const std = @import("std");const i18n = @import("i18n");const tr = i18n.tr;@@ -9,65 +13,158 @@ const c = @import("../files/c.zig").api;const app = @import("app.zig");const App = app.App;const Rect = cairo.Rect;+const cpu_view = @import("app_summary_cpu.zig");+const ram_view = @import("app_summary_ram.zig");const Position = struct { x: f64, y: f64 };+pub const top: f32 = 14;+pub const card_h: f32 = 122;+const collapse_size: f32 = 28;+/// What an expanded card keeps clear at its right for the collapse button.+pub const collapse_room: f32 = collapse_size + 22;++/// Both cards' boxes at the current expansion; the hidden one may lie+/// outside the summary area while it slides away.+fn boxes(self: *const App) [2]Rect {+ const full = @as(f32, @floatFromInt(self.w)) - 32;+ const half = (full - 16) / 2;+ const t = std.math.clamp(self.card_t, 0, 1);+ const grow = (full - half) * t;+ var out: [2]Rect = undefined;+ if (self.card == 0) {+ out[0] = .{ .x = 16, .y = top, .w = half + grow, .h = card_h };+ out[1] = .{ .x = 32 + half + grow, .y = top, .w = half, .h = card_h };+ } else {+ out[1] = .{ .x = 32 + half - (16 + half) * t, .y = top, .w = half + grow, .h = card_h };+ out[0] = .{ .x = out[1].x - 16 - half, .y = top, .w = half, .h = card_h };+ }+ return out;+}++/// The visible cards toggle expansion; the hidden card cannot take clicks.+pub fn layout(self: *App) void {+ const placed = boxes(self);+ for (self.cards[0..2], placed, 0..) |*card, box, index| place(card, if (self.card_open and index != self.card) null else box);+ const open = placed[self.card];+ place(&self.cards[2], if (self.card_open) .{+ .x = open.x + open.w - collapse_size - 12,+ .y = open.y + 10,+ .w = collapse_size,+ .h = collapse_size,+ } else null);+}++fn place(widget: *ui.layout.Widget, box: ?Rect) void {+ const b = box orelse Rect{ .x = -1, .y = -1, .w = 0, .h = 0 };+ ui.measure.measure(widget, b.w, b.h);+ ui.arrange.arrange(widget, b.x, b.y, b.w, b.h);+}+pub fn paint(self: *App, cr: *c.cairo_t) void {- const width = (@as(f32, @floatFromInt(self.w)) - 48) / 2;- for (0..2) |index| paintCard(self, cr, index, .{- .x = 16 + @as(f32, @floatFromInt(index)) * (width + 16),- .y = 14,- .w = width,- .h = 122,- });+ const full = @as(f32, @floatFromInt(self.w)) - 32;+ c.cairo_save(cr);+ defer c.cairo_restore(cr);+ c.cairo_rectangle(cr, 16, top, full, card_h);+ c.cairo_clip(cr);+ const t = std.math.clamp(self.card_t, 0, 1);+ for (boxes(self), 0..) |box, index| {+ const leaving = t > 0 and index != self.card;+ if (leaving and t >= 1) continue;+ const group = leaving;+ if (group) c.cairo_push_group(cr);+ paintFrame(self, cr, index, box);+ if (index == self.card and t > 0) {+ // Cross-fade through the midpoint: compact content out, expanded in.+ const expanded = t >= 0.5;+ const alpha = if (expanded) 2 * t - 1 else 1 - 2 * t;+ if (alpha > 0) {+ if (alpha < 1) c.cairo_push_group(cr);+ if (!expanded) paintCompact(self, cr, index, box) else if (index == 0) cpu_view.paint(self, cr, box) else ram_view.paint(self, cr, box);+ if (alpha < 1) {+ c.cairo_pop_group_to_source(cr);+ c.cairo_paint_with_alpha(cr, alpha);+ }+ }+ } else paintCompact(self, cr, index, box);+ if (group) {+ c.cairo_pop_group_to_source(cr);+ c.cairo_paint_with_alpha(cr, 1 - t);+ }+ }}-fn paintCard(self: *App, cr: *c.cairo_t, index: usize, box: Rect) void {- const compact = box.w < 420;- const info_width = std.math.clamp(box.w * 0.38, 200, 260);- const accent = theme.shellPalette().accent;- const snap = self.model.snapshot;- const mem = if (snap) |s| s.memory else null;- const percent: ?f64 = if (index == 0)- (if (snap) |s| s.cpu_percent else null)- else if (mem) |m|- (if (m.total > 0) @as(f64, @floatFromInt(m.used())) * 100 / @as(f64, @floatFromInt(m.total)) else null)- else- null;+fn paintFrame(self: *App, cr: *c.cairo_t, index: usize, box: Rect) void {+ const card = &self.cards[index];+ const lit = card.kind.row.state == .hover or card.kind.row.state == .press or self.dispatcher.focused == card;+ var border = theme.global.app_divider;+ if (lit) {+ border = theme.shellPalette().accent;+ border[3] *= 0.7;+ }if (cairo.Layer.begin(cr, box)) |value| {var layer = value;layer.renderer.fillRect(0.5, 0.5, box.w - 1, box.h - 1, .{.color = theme.global.app_bar,.radius = theme.global.radius_md,.border_width = 1,- .border_color = theme.global.app_divider,+ .border_color = border,});- const badge: f32 = if (compact) 28 else 36;+ layer.finish();+ }+}++/// The icon badge at a card's top-left; `compact` is the narrow layout.+pub fn paintBadge(cr: *c.cairo_t, index: usize, box: Rect, compact: bool) void {+ const accent = theme.shellPalette().accent;+ const badge: f32 = if (compact) 28 else 36;+ if (cairo.Layer.begin(cr, .{ .x = box.x + 12, .y = box.y + 12, .w = badge, .h = badge })) |value| {+ var layer = value;var tint = accent;tint[3] *= 0.14;- layer.renderer.fillRect(12, 12, badge, badge, .{ .color = tint, .radius = theme.global.radius });- layer.renderer.drawIcon(17, 17, badge - 10, badge - 10, .{ .id = if (index == 0) .cpu else .ram, .color = accent });+ layer.renderer.fillRect(0, 0, badge, badge, .{ .color = tint, .radius = theme.global.radius });+ layer.renderer.drawIcon(5, 5, badge - 10, badge - 10, .{ .id = if (index == 0) .cpu else .ram, .color = accent });layer.finish();}+}++pub fn cpuPercent(self: *const App) ?f64 {+ return if (self.model.snapshot) |s| s.cpu_percent else null;+}++pub fn memoryPercent(self: *const App) ?f64 {+ const m = (self.model.snapshot orelse return null).memory orelse return null;+ return if (m.total > 0) @as(f64, @floatFromInt(m.used())) * 100 / @as(f64, @floatFromInt(m.total)) else null;+}++/// The card's large current percentage.+pub fn paintPercent(cr: *c.cairo_t, percent: ?f64, box: Rect, scale: f32) void {+ var buf: [32]u8 = undefined;+ const text = if (percent) |p| std.fmt.bufPrint(&buf, "{d:.1}%", .{p}) catch "—" else "—";+ label(cr, text, box, cairo.headingSize() * scale, true);+}++fn paintCompact(self: *App, cr: *c.cairo_t, index: usize, box: Rect) void {+ const compact = box.w < 420;+ const info_width = std.math.clamp(box.w * 0.38, 200, 260);+ const snap = self.model.snapshot;+ const mem = if (snap) |s| s.memory else null;+ const percent = if (index == 0) cpuPercent(self) else memoryPercent(self);+ paintBadge(cr, index, box, compact);const text_x = box.x + (if (compact) @as(f32, 48) else 62);const text_w = if (compact) box.w - 166 else info_width - 76;label(cr, if (index == 0) tr("CPU") else tr("RAM"), .{ .x = text_x, .y = box.y + 10, .w = text_w, .h = 24 }, cairo.headingSize() * 1.25, true);var buf: [128]u8 = undefined;- const percent_text = if (percent) |p| std.fmt.bufPrint(&buf, "{d:.1}%", .{p}) catch "—" else "—";const number_box: Rect = if (compact).{ .x = box.x + box.w - 118, .y = box.y + 8, .w = 106, .h = 36 }else.{ .x = text_x, .y = box.y + (if (index == 0) @as(f32, 36) else 58), .w = text_w, .h = 40 };- label(cr, percent_text, number_box, cairo.headingSize() * (if (compact) @as(f32, 2.2) else 2.6), true);+ paintPercent(cr, percent, number_box, if (compact) 2.2 else 2.6);const details: Rect = if (compact).{ .x = box.x + 12, .y = box.y + 43, .w = box.w - 24, .h = 22 }else.{ .x = text_x, .y = box.y + (if (index == 0) @as(f32, 84) else 34), .w = text_w, .h = 24 };if (index == 0) {- var count_buf: [48]u8 = undefined;- const system = if (snap) |s| s.system else @import("proc.zig").System{};- const count = if (system.logical_cpus) |n| i18n.fmt(&count_buf, i18n.trn("{n} CPU", "{n} CPUs", n), .{ .n = n }) catch "—" else "—";- const text = if (system.frequency_ghz) |ghz| std.fmt.bufPrint(&buf, "{d:.1} GHz · {s}", .{ ghz, count }) catch "—" else count;- label(cr, text, details, cairo.textSize(), false);+ label(cr, cpuLine(self, &buf), details, cairo.textSize(), false);} else {const text = if (mem) |m| app.bytesPair(&buf, m.used(), m.total) else "—";label(cr, text, details, cairo.textSize(), false);@@ -82,27 +179,54 @@ fn paintCard(self: *App, cr: *c.cairo_t, index: usize, box: Rect) void {.{ .x = box.x + 12, .y = box.y + 78, .w = box.w - 32 - axis_w, .h = 32 }else.{ .x = box.x + info_width, .y = box.y + 18, .w = box.w - info_width - axis_w - 20, .h = 84 };- paintGrid(cr, graph, index, if (mem) |m| m.total else null, compact);+ paintGraph(self, cr, index, graph, compact);+}++/// "3.2 GHz · 16 CPUs", or just the count without a frequency.+pub fn cpuLine(self: *const App, buf: []u8) []const u8 {+ var count_buf: [48]u8 = undefined;+ const system = if (self.model.snapshot) |s| s.system else @import("proc.zig").System{};+ const count = if (system.logical_cpus) |n| i18n.fmt(&count_buf, i18n.trn("{n} CPU", "{n} CPUs", n), .{ .n = n }) catch "—" else "—";+ return if (system.frequency_ghz) |ghz| std.fmt.bufPrint(buf, "{d:.1} GHz · {s}", .{ ghz, count }) catch "—" else std.fmt.bufPrint(buf, "{s}", .{count}) catch "—";+}++/// The 60-second history with its grid, axis and caption (not when compact).+pub fn paintGraph(self: *const App, cr: *c.cairo_t, index: usize, graph: Rect, compact: bool) void {+ const total = if (self.model.snapshot) |s| if (s.memory) |m| m.total else null else null;+ paintGrid(cr, graph, index, total, compact);paintHistory(self, cr, index, graph);- if (!compact) label(cr, tr("60 seconds"), .{ .x = graph.x, .y = box.y + 104, .w = graph.w, .h = 16 }, cairo.statusSize(), false);+ if (!compact) label(cr, tr("60 seconds"), .{ .x = graph.x, .y = graph.y + graph.h + 2, .w = graph.w, .h = 16 }, cairo.statusSize(), false);}-fn label(cr: *c.cairo_t, text: []const u8, box: Rect, size: f32, bold: bool) void {+pub fn label(cr: *c.cairo_t, text: []const u8, box: Rect, size: f32, bold: bool) void {app.textBox(cr, text, box, size, bold, theme.global.window_fg);}-fn paintMeter(cr: *c.cairo_t, box: Rect, percent: ?f64) void {+/// Like `label`, ending at the box's right edge.+pub fn labelRight(cr: *c.cairo_t, text: []const u8, box: Rect, size: f32, bold: bool) void {+ const width: f32 = @floatCast(cairo.measureText(cr, text, size, bold));+ const x = @max(box.x, box.x + box.w - width);+ label(cr, text, .{ .x = x, .y = box.y, .w = box.x + box.w - x, .h = box.h }, size, bold);+}++pub fn paintMeter(cr: *c.cairo_t, box: Rect, percent: ?f64) void {+ if (box.w <= 0 or box.h <= 0) return;if (cairo.Layer.begin(cr, box)) |value| {var layer = value;- layer.renderer.fillRect(0, 0, box.w, box.h, .{ .color = theme.global.app_divider, .radius = box.h / 2 });- if (percent) |p| {- const width = box.w * @as(f32, @floatCast(std.math.clamp(p / 100, 0, 1)));- if (width > 0) layer.renderer.fillRect(0, 0, width, box.h, .{ .color = theme.shellPalette().accent, .radius = @min(width, box.h) / 2 });- }+ drawMeter(&layer.renderer, .{ .x = 0, .y = 0, .w = box.w, .h = box.h }, percent);layer.finish();}}+/// A rounded track filled to `percent`, in the renderer's coordinates.+pub fn drawMeter(renderer: *ui.paint.Renderer, box: Rect, percent: ?f64) void {+ if (box.w <= 0 or box.h <= 0) return;+ renderer.fillRect(box.x, box.y, box.w, box.h, .{ .color = theme.global.app_divider, .radius = box.h / 2 });+ const p = percent orelse return;+ const width = box.w * @as(f32, @floatCast(std.math.clamp(p / 100, 0, 1)));+ if (width > 0) renderer.fillRect(box.x, box.y, width, box.h, .{ .color = theme.shellPalette().accent, .radius = @min(width, box.h) / 2 });+}+fn axisLabel(buf: []u8, index: usize, total: ?u64, quarter: usize) []const u8 {if (index == 0) return std.fmt.bufPrint(buf, "{d}%", .{quarter * 25}) catch "—";const bytes = total orelse return "—";@@ -111,7 +235,7 @@ fn axisLabel(buf: []u8, index: usize, total: ?u64, quarter: usize) []const u8 {return app.bytesLabel(buf, bytes / 4 * quarter + bytes % 4 * quarter / 4);}-fn axisWidth(cr: *c.cairo_t, index: usize, total: ?u64) f32 {+pub fn axisWidth(cr: *c.cairo_t, index: usize, total: ?u64) f32 {var width: f32 = 0;var buf: [32]u8 = undefined;for (0..5) |quarter| width = @max(width, @as(f32, @floatCast(cairo.measureText(cr, axisLabel(&buf, index, total, quarter), cairo.statusSize(), false))));@@ -179,15 +303,15 @@ fn paintSegment(cr: *c.cairo_t, points: []const Position, bottom: f64) void {c.cairo_fill(cr);return;}- var top = bottom;+ var top_y = bottom;c.cairo_move_to(cr, points[0].x, bottom);for (points) |point| {c.cairo_line_to(cr, point.x, point.y);- top = @min(top, point.y);+ top_y = @min(top_y, point.y);}c.cairo_line_to(cr, points[points.len - 1].x, bottom);c.cairo_close_path(cr);- const gradient = c.cairo_pattern_create_linear(0, top, 0, @max(top + 1, bottom));+ const gradient = c.cairo_pattern_create_linear(0, top_y, 0, @max(top_y + 1, bottom));defer c.cairo_pattern_destroy(gradient);c.cairo_pattern_add_color_stop_rgba(gradient, 0, accent[0], accent[1], accent[2], accent[3] * 0.28);c.cairo_pattern_add_color_stop_rgba(gradient, 1, accent[0], accent[1], accent[2], accent[3] * 0.025);diff --git a/src/system_monitor/app_summary_cpu.zig b/src/system_monitor/app_summary_cpu.zignew file mode 100644index 0000000..c6c0c1c--- /dev/null+++ b/src/system_monitor/app_summary_cpu.zig@@ -0,0 +1,151 @@+//! The expanded CPU card: totals and load average, one segmented tower per online+//! logical CPU, and the 60-second history when the card is wide enough.+const std = @import("std");+const tr = @import("i18n").tr;+const ui = @import("ui");+const cairo = ui.cairo;+const c = @import("../files/c.zig").api;+const App = @import("app.zig").App;+const Rect = cairo.Rect;+const summary = @import("app_summary.zig");++pub fn paint(self: *App, cr: *c.cairo_t, box: Rect) void {+ const info_w = std.math.clamp(box.w * 0.22, 190, 240);+ const text_x = box.x + 62;+ const text_w = info_w - 76;+ summary.paintBadge(cr, 0, box, false);+ summary.label(cr, tr("CPU"), .{ .x = text_x, .y = box.y + 10, .w = text_w, .h = 24 }, cairo.headingSize() * 1.25, true);+ summary.paintPercent(cr, summary.cpuPercent(self), .{ .x = text_x, .y = box.y + 34, .w = text_w, .h = 40 }, 2.6);+ var buf: [128]u8 = undefined;+ summary.label(cr, summary.cpuLine(self, &buf), .{ .x = box.x + 16, .y = box.y + 76, .w = info_w - 28, .h = 20 }, cairo.textSize(), false);+ var line = loadLine(self, &buf, true);+ if (cairo.measureText(cr, line, cairo.statusSize(), false) > info_w - 28) line = loadLine(self, &buf, false);+ summary.label(cr, line, .{ .x = box.x + 16, .y = box.y + 96, .w = info_w - 28, .h = 18 }, cairo.statusSize(), false);++ var right = box.x + box.w - summary.collapse_room;+ if (box.w >= 820) {+ const axis_w = summary.axisWidth(cr, 0, null);+ const graph_w = std.math.clamp(box.w * 0.24, 180, 300);+ const graph: Rect = .{ .x = right - axis_w - 8 - graph_w, .y = box.y + 18, .w = graph_w, .h = 84 };+ const n = if (self.model.snapshot) |s| s.cores.len else 0;+ // Keep enough room for a row of two-digit-wide meters before giving+ // space to history. Dense machines can use the entire detail area.+ if (graph.x - 28 - box.x - info_w >= @as(f32, @floatFromInt(n)) * (meterWidth(cr) + 8)) {+ summary.paintGraph(self, cr, 0, graph, false);+ right = graph.x - 28;+ }+ }+ paintCores(self, cr, .{ .x = box.x + info_w, .y = box.y + 14, .w = right - box.x - info_w, .h = box.h - 28 });+}++/// "Load 0.52 · 0.58 · 0.59 · 1234 threads", dropping what the OS lacks.+fn loadLine(self: *const App, buf: []u8, with_threads: bool) []const u8 {+ const system = (self.model.snapshot orelse return "").system;+ var used: usize = 0;+ if (system.load) |load| {+ used = (std.fmt.bufPrint(buf, "{s} {d:.2} · {d:.2} · {d:.2}", .{ tr("Load"), load[0], load[1], load[2] }) catch return "").len;+ }+ if (system.threads) |threads| if (with_threads or used == 0) {+ var count: [64]u8 = undefined;+ const text = @import("i18n").fmt(&count, @import("i18n").trn("{n} thread", "{n} threads", threads), .{ .n = threads }) catch return buf[0..used];+ used += (std.fmt.bufPrint(buf[used..], "{s}{s}", .{ if (used > 0) " · " else "", text }) catch return buf[0..used]).len;+ };+ return buf[0..used];+}++const Tier = enum { full, numbered, bars };+const Grid = struct { tier: Tier, cols: usize, cell: f32, pitch: f32 };++fn meterWidth(cr: *c.cairo_t) f32 {+ return @max(16, @as(f32, @floatCast(cairo.measureText(cr, "00", cairo.statusSize(), false))) + 2);+}++/// Prefer IDs above and percentages below each tower, then drop labels as+/// needed. CPU numbers run left to right, wrapping on many-core machines.+fn grid(n: usize, region: Rect, bar_w: f32, id_w: f32, value_w: f32, label_h: f32) Grid {+ const bar_h = @max(28, bar_w * 1.75);+ const tiers = [_]struct { tier: Tier, width: f32, height: f32 }{+ .{ .tier = .full, .width = @max(bar_w, @max(id_w, value_w)) + 6, .height = bar_h + 2 * label_h + 6 },+ .{ .tier = .numbered, .width = @max(bar_w, id_w) + 8, .height = bar_h + label_h + 6 },+ .{ .tier = .bars, .width = bar_w + 8, .height = bar_h + 6 },+ };+ for (tiers) |tier| {+ const cols = @min(n, @max(1, @as(usize, @intFromFloat(@floor(region.w / tier.width)))));+ const rows = std.math.divCeil(usize, n, cols) catch 1;+ const pitch = region.h / @as(f32, @floatFromInt(rows));+ if (pitch >= tier.height and region.w >= tier.width) return .{+ .tier = tier.tier,+ .cols = cols,+ .cell = region.w / @as(f32, @floatFromInt(cols)),+ .pitch = pitch,+ };+ }+ // Keep every CPU visible even when the towers must become narrower.+ const max_rows: usize = @max(1, @as(usize, @intFromFloat(@floor(region.h / (bar_h + 6)))));+ const cols = std.math.divCeil(usize, n, max_rows) catch 1;+ const rows = std.math.divCeil(usize, n, cols) catch 1;+ return .{ .tier = .bars, .cols = cols, .cell = region.w / @as(f32, @floatFromInt(cols)), .pitch = region.h / @as(f32, @floatFromInt(rows)) };+}++fn cellAt(g: Grid, i: usize) Rect {+ return .{ .x = @as(f32, @floatFromInt(i % g.cols)) * g.cell, .y = @as(f32, @floatFromInt(i / g.cols)) * g.pitch, .w = g.cell, .h = g.pitch };+}++fn drawTower(renderer: *ui.paint.Renderer, box: Rect, percent: ?f64) void {+ const count: usize = @intFromFloat(std.math.clamp(@floor((box.h + 2) / 6), 2, 10));+ const pitch = (box.h + 2) / @as(f32, @floatFromInt(count));+ const lit: usize = if (percent) |p| @intFromFloat(@ceil(std.math.clamp(p / 100, 0, 1) * @as(f64, @floatFromInt(count)))) else 0;+ for (0..count) |i| {+ const y = box.y + box.h - @as(f32, @floatFromInt(i + 1)) * pitch + 2;+ renderer.fillRect(box.x, y, box.w, pitch - 2, .{+ .color = if (i < lit) ui.theme.shellPalette().accent else ui.theme.global.app_divider,+ .radius = 1,+ });+ }+}++fn labelCentered(cr: *c.cairo_t, text: []const u8, box: Rect) void {+ const width: f32 = @floatCast(cairo.measureText(cr, text, cairo.statusSize(), false));+ const inset = @max(0, (box.w - width) / 2);+ summary.label(cr, text, .{ .x = box.x + inset, .y = box.y, .w = box.w - inset, .h = box.h }, cairo.statusSize(), false);+}++fn paintCores(self: *const App, cr: *c.cairo_t, region: Rect) void {+ if (region.w <= 0 or region.h <= 0) return;+ const snap = self.model.snapshot orelse return;+ const n = snap.cores.len;+ if (n == 0) {+ summary.label(cr, tr("Per-core load is unavailable"), region, cairo.textSize(), false);+ return;+ }+ c.cairo_save(cr);+ defer c.cairo_restore(cr);+ c.cairo_rectangle(cr, region.x, region.y, region.w, region.h);+ c.cairo_clip(cr);+ const size = cairo.statusSize();+ var buf: [16]u8 = undefined;+ const id_w: f32 = @floatCast(cairo.measureText(cr, std.fmt.bufPrint(&buf, "{d}", .{snap.cores[n - 1].id}) catch "00", size, false));+ const value_w: f32 = @floatCast(cairo.measureText(cr, "100%", size, false));+ const label_h = @max(16, size + 4);+ const g = grid(n, region, meterWidth(cr), id_w, value_w, label_h);+ const bar_w = @min(meterWidth(cr), g.cell * 0.75);+ const label_space = label_h * @as(f32, if (g.tier == .full) 2 else if (g.tier == .numbered) 1 else 0);+ // Every bar in one offscreen layer; the text goes on top afterwards.+ if (cairo.Layer.begin(cr, region)) |value| {+ var layer = value;+ for (snap.core_percent, 0..) |percent, i| {+ const at = cellAt(g, i);+ drawTower(&layer.renderer, .{ .x = at.x + (g.cell - bar_w) / 2, .y = at.y + (if (g.tier == .bars) @as(f32, 0) else label_h) + 3, .w = bar_w, .h = g.pitch - label_space - 6 }, percent);+ }+ layer.finish();+ }+ if (g.tier == .bars) return;+ for (snap.cores, snap.core_percent, 0..) |core, percent, i| {+ const at = cellAt(g, i);+ labelCentered(cr, std.fmt.bufPrint(&buf, "{d}", .{core.id}) catch "", .{ .x = region.x + at.x, .y = region.y + at.y, .w = g.cell, .h = label_h });+ if (g.tier == .full) {+ const text = if (percent) |p| std.fmt.bufPrint(&buf, "{d:.0}%", .{p}) catch "—" else "—";+ labelCentered(cr, text, .{ .x = region.x + at.x, .y = region.y + at.y + g.pitch - label_h, .w = g.cell, .h = label_h });+ }+ }+}diff --git a/src/system_monitor/app_summary_ram.zig b/src/system_monitor/app_summary_ram.zignew file mode 100644index 0000000..ba20337--- /dev/null+++ b/src/system_monitor/app_summary_ram.zig@@ -0,0 +1,142 @@+//! The expanded RAM card: used and cached memory as one composition bar, the+//! kernel's breakdown and swap, the processes holding the most resident+//! memory, and the 60-second history when the card is wide enough.+const std = @import("std");+const tr = @import("i18n").tr;+const ui = @import("ui");+const cairo = ui.cairo;+const theme = ui.theme;+const c = @import("../files/c.zig").api;+const app = @import("app.zig");+const App = app.App;+const Rect = cairo.Rect;+const collector = @import("collector.zig");+const proc = @import("proc.zig");+const summary = @import("app_summary.zig");++const details_w: f32 = 330;+const top_count = 4;++pub fn paint(self: *App, cr: *c.cairo_t, box: Rect) void {+ const snap = self.model.snapshot;+ const mem = if (snap) |s| s.memory else null;+ const info_w = std.math.clamp(box.w * 0.22, 190, 240);+ const text_x = box.x + 62;+ const text_w = info_w - 76;+ summary.paintBadge(cr, 1, box, false);+ summary.label(cr, tr("RAM"), .{ .x = text_x, .y = box.y + 10, .w = text_w, .h = 24 }, cairo.headingSize() * 1.25, true);+ summary.paintPercent(cr, summary.memoryPercent(self), .{ .x = text_x, .y = box.y + 34, .w = text_w, .h = 40 }, 2.6);+ var buf: [128]u8 = undefined;+ summary.label(cr, if (mem) |m| app.bytesPair(&buf, m.used(), m.total) else "—", .{ .x = box.x + 16, .y = box.y + 76, .w = info_w - 28, .h = 20 }, cairo.textSize(), false);+ paintComposition(cr, .{ .x = box.x + 16, .y = box.y + 101, .w = info_w - 28, .h = 8 }, mem);++ const right = box.x + box.w - summary.collapse_room;+ var x = box.x + info_w;+ paintDetails(cr, .{ .x = x, .y = box.y + 14, .w = @min(details_w, right - x), .h = box.h - 28 }, mem);+ x += details_w + 24;+ const room = right - x;+ if (room < 160) return;+ const list_w = @min(room, 210);+ paintLargest(self, cr, .{ .x = x, .y = box.y + 12, .w = list_w, .h = box.h - 24 });+ x += list_w + 28;+ const axis_w = summary.axisWidth(cr, 1, if (mem) |m| m.total else null);+ const graph_w = right - x - axis_w - 8;+ if (graph_w >= 120) summary.paintGraph(self, cr, 1, .{ .x = x, .y = box.y + 18, .w = graph_w, .h = 84 }, false);+}++fn cachedColor() [4]f32 {+ var color = theme.shellPalette().accent;+ color[3] *= 0.4;+ return color;+}++/// Used, then reclaimable cache, over the whole capacity. The cache segment+/// never runs past what is not free, so the bar always sums to the total.+fn paintComposition(cr: *c.cairo_t, box: Rect, mem: ?proc.Memory) void {+ const layer_value = cairo.Layer.begin(cr, box) orelse return;+ var layer = layer_value;+ defer layer.finish();+ layer.renderer.fillRect(0, 0, box.w, box.h, .{ .color = theme.global.app_divider, .radius = box.h / 2 });+ const m = mem orelse return;+ if (m.total == 0) return;+ const total: f32 = @floatFromInt(m.total);+ const used = @as(f32, @floatFromInt(m.used())) / total;+ const room = @as(f32, @floatFromInt(m.total -| m.used() -| (m.free orelse 0))) / total;+ const cached = @min(room, @as(f32, @floatFromInt(m.cached orelse 0)) / total);+ const end = box.w * std.math.clamp(used + cached, 0, 1);+ if (end > 0) layer.renderer.fillRect(0, 0, end, box.h, .{ .color = cachedColor(), .radius = @min(end, box.h) / 2 });+ const used_w = box.w * std.math.clamp(used, 0, 1);+ if (used_w > 0) layer.renderer.fillRect(0, 0, used_w, box.h, .{ .color = theme.shellPalette().accent, .radius = @min(used_w, box.h) / 2 });+}++/// Name over value in three columns; Used and Cached carry the bar's colours.+/// The last column is wider for swap's "used / total".+fn paintDetails(cr: *c.cairo_t, region: Rect, mem: ?proc.Memory) void {+ if (region.w <= 0) return;+ const names = [_][]const u8{ tr("Used"), tr("Cached"), tr("Swap"), tr("Available"), tr("Free"), tr("Shared") };+ const values = [_]usize{ 0, 2, 5, 1, 3, 4 };+ const unit = region.w / details_w;+ const cols = [_]f32{ 0, 100 * unit, 200 * unit, region.w };+ const row_h = region.h / 2;+ const swatch: f32 = 8;+ const pad = (row_h - 36) / 2;+ if (cairo.Layer.begin(cr, region)) |value| {+ var layer = value;+ const y = pad + 8 - swatch / 2;+ layer.renderer.fillRect(cols[0], y, swatch, swatch, .{ .color = theme.shellPalette().accent, .radius = 2 });+ layer.renderer.fillRect(cols[1], y, swatch, swatch, .{ .color = cachedColor(), .radius = 2 });+ layer.finish();+ }+ for (names, values, 0..) |name, slot, i| {+ var buf: [64]u8 = undefined;+ const x = region.x + cols[i % 3] + (if (i < 2) swatch + 6 else 0);+ const w = region.x + cols[i % 3 + 1] - x - 10;+ const y = region.y + @as(f32, @floatFromInt(i / 3)) * row_h + pad;+ summary.label(cr, name, .{ .x = x, .y = y, .w = w, .h = 16 }, cairo.statusSize(), false);+ summary.label(cr, detailValue(&buf, mem, slot), .{ .x = region.x + cols[i % 3], .y = y + 16, .w = region.x + cols[i % 3 + 1] - region.x - cols[i % 3] - 10, .h = 20 }, cairo.textSize(), true);+ }+}++fn detailValue(buf: []u8, mem: ?proc.Memory, index: usize) []const u8 {+ const m = mem orelse return "—";+ const bytes: ?u64 = switch (index) {+ 0 => m.used(),+ 1 => m.available,+ 2 => m.cached,+ 3 => m.free,+ 4 => m.shared,+ else => {+ const total = m.swap_total orelse return "—";+ if (total == 0) return tr("None");+ return app.bytesPair(buf, total -| (m.swap_free orelse total), total);+ },+ };+ return if (bytes) |value| app.bytesLabel(buf, value) else "—";+}++/// Every user's processes, not just the table's filter: what to close first.+fn paintLargest(self: *const App, cr: *c.cairo_t, region: Rect) void {+ summary.label(cr, tr("Most memory"), .{ .x = region.x, .y = region.y, .w = region.w, .h = 16 }, cairo.statusSize(), false);+ const snap = self.model.snapshot orelse return;+ var top: [top_count]*const collector.Process = undefined;+ var count: usize = 0;+ for (snap.processes) |*row| {+ const bytes = row.resident_bytes orelse continue;+ var at = count;+ while (at > 0 and (top[at - 1].resident_bytes orelse 0) < bytes) at -= 1;+ if (at == top_count) continue;+ if (count < top_count) count += 1;+ var move = count - 1;+ while (move > at) : (move -= 1) top[move] = top[move - 1];+ top[at] = row;+ }+ const pitch = (region.h - 20) / @as(f32, top_count);+ for (top[0..count], 0..) |row, i| {+ var buf: [32]u8 = undefined;+ const y = region.y + 20 + @as(f32, @floatFromInt(i)) * pitch;+ const size = app.bytesLabel(&buf, row.resident_bytes.?);+ const size_w: f32 = @floatCast(cairo.measureText(cr, size, cairo.textSize(), false));+ summary.label(cr, row.name, .{ .x = region.x, .y = y, .w = region.w - size_w - 10, .h = pitch }, cairo.textSize(), false);+ summary.labelRight(cr, size, .{ .x = region.x, .y = y, .w = region.w, .h = pitch }, cairo.textSize(), false);+ }+}diff --git a/src/system_monitor/collector.zig b/src/system_monitor/collector.zigindex 69c76d9..79a8425 100644--- a/src/system_monitor/collector.zig+++ b/src/system_monitor/collector.zig@@ -23,6 +23,9 @@ pub const Snapshot = struct {at_ns: u64,cpu: ?proc.Cpu,cpu_percent: ?f64 = null,+ /// Online logical CPUs' counters and, from the second sample, their load.+ cores: []proc.Core = &.{},+ core_percent: []?f64 = &.{},memory: ?proc.Memory,system: proc.System = .{},network_rate: ?proc.NetworkRate = null,@@ -42,6 +45,11 @@ pub fn sample(cancelled: *const std.atomic.Value(u64), generation: u64) !*Snapshconst arena = snapshot.arena.allocator();var buf: [65536]u8 = undefined;snapshot.cpu = proc.cpuTotals(&buf);+ var cores: [proc.max_cores]proc.Core = undefined;+ const core_count = proc.cpuCores(&buf, &cores);+ snapshot.cores = try arena.dupe(proc.Core, cores[0..core_count]);+ snapshot.core_percent = try arena.alloc(?f64, core_count);+ @memset(snapshot.core_percent, null);snapshot.memory = proc.memoryTotals(&buf);snapshot.system = proc.systemStats(&buf);var list = proc.List.open() orelse {@@ -172,6 +180,8 @@ pub const Worker = struct {defer previous.deinit(a);var last_at: u64 = 0;var last_cpu: ?proc.Cpu = null;+ var last_cores: [proc.max_cores]proc.Core = undefined;+ var last_core_count: usize = 0;var last_network: ?proc.Network = null;var observed: u64 = std.math.maxInt(u64);var deadline: u64 = 0;@@ -183,6 +193,7 @@ pub const Worker = struct {previous.clearRetainingCapacity();last_at = 0;last_cpu = null;+ last_core_count = 0;last_network = null;deadline = 0;}@@ -205,6 +216,9 @@ pub const Worker = struct {if (last_cpu) |before| if (snap.cpu) |after| {snap.cpu_percent = proc.cpuPercent(before, after);};+ corePercents(snap, last_cores[0..last_core_count]);+ last_core_count = snap.cores.len;+ @memcpy(last_cores[0..last_core_count], snap.cores);if (last_network) |before| if (snap.system.network) |after| {snap.network_rate = proc.networkRate(before, after, snap.at_ns -| last_at);};@@ -240,6 +254,16 @@ pub const Worker = struct {}};+/// Pairs cores by id: one going offline shifts the rest of the list.+pub fn corePercents(snap: *Snapshot, before: []const proc.Core) void {+ for (snap.cores, snap.core_percent, 0..) |core, *percent, i| {+ const previous = if (i < before.len and before[i].id == core.id) before[i] else for (before) |other| {+ if (other.id == core.id) break other;+ } else continue;+ percent.* = proc.cpuPercent(previous.cpu, core.cpu);+ }+}+pub fn wake(fd: c_int) void {const one: u64 = 1;_ = c.write(fd, &one, @sizeOf(u64));diff --git a/src/system_monitor/proc.zig b/src/system_monitor/proc.zigindex 0746b51..86a97e8 100644--- a/src/system_monitor/proc.zig+++ b/src/system_monitor/proc.zig@@ -7,7 +7,7 @@//! * `Process`: `open(pid)`, `close`, `stat(buf)`, `uids(buf)`, `exePath(buf)`.//! One open `Process` describes one task, so its three reads agree.//! * `List`: `open()`, `next()` (a pid), `close()`.-//! * `cpuTotals(buf)`, `memoryTotals(buf)`, `systemStats(buf)`, `ticksPerSecond()`.+//! * `cpuTotals(buf)`, `cpuCores(buf, out)`, `memoryTotals(buf)`, `systemStats(buf)`, `ticksPerSecond()`.//!//! No compositor, Wayland or UI dependencies.const builtin = @import("builtin");@@ -24,6 +24,8 @@ pub const Identity = common.Identity;pub const Stat = common.Stat;pub const Uids = common.Uids;pub const Cpu = common.Cpu;+pub const Core = common.Core;+pub const max_cores = common.max_cores;pub const Memory = common.Memory;pub const System = common.System;pub const Network = common.Network;@@ -40,6 +42,7 @@ pub const nowNs = common.nowNs;pub const Process = backend.Process;pub const List = backend.List;pub const cpuTotals = backend.cpuTotals;+pub const cpuCores = backend.cpuCores;pub const memoryTotals = backend.memoryTotals;pub const systemStats = backend.systemStats;pub const ticksPerSecond = backend.ticksPerSecond;diff --git a/src/system_monitor/proc_common.zig b/src/system_monitor/proc_common.zigindex 35a2c3f..31e1070 100644--- a/src/system_monitor/proc_common.zig+++ b/src/system_monitor/proc_common.zig@@ -39,6 +39,10 @@ pub fn protectedName(name: []const u8) bool {}pub const Cpu = struct { total: u64, idle: u64 };+/// One online logical CPU's counters; `id` survives offline CPUs in between.+pub const Core = struct { id: u32, cpu: Cpu };+/// The expanded CPU card shows at most this many cores.+pub const max_cores = 1024;pub const System = struct {logical_cpus: ?u32 = null,frequency_ghz: ?f64 = null,@@ -46,6 +50,10 @@ pub const System = struct {temperature_c: ?f64 = null,gpu_temperature_c: ?f64 = null,network: ?Network = null,+ /// 1, 5 and 15 minute load averages.+ load: ?[3]f64 = null,+ /// Every thread on the system (Linux reports it beside the load).+ threads: ?u64 = null,};pub const Network = struct { received: u64 = 0, sent: u64 = 0, interfaces: u64 = 0 };pub const NetworkRate = struct { received: f64, sent: f64 };@@ -78,6 +86,12 @@ pub const Memory = struct {available: u64,swap_total: ?u64,swap_free: ?u64,+ /// Never used, not even as cache.+ free: ?u64 = null,+ /// Buffers and page cache the kernel can reclaim (free(1)'s buff/cache).+ cached: ?u64 = null,+ /// tmpfs and shared memory, counted inside `cached`.+ shared: ?u64 = null,pub fn used(self: Memory) u64 {return self.total -| self.available;}diff --git a/src/system_monitor/proc_freebsd.zig b/src/system_monitor/proc_freebsd.zigindex 8ed8630..090c346 100644--- a/src/system_monitor/proc_freebsd.zig+++ b/src/system_monitor/proc_freebsd.zig@@ -162,6 +162,26 @@ pub fn cpuTotals(_: []u8) ?common.Cpu {return .{ .total = total, .idle = @intCast(@max(times[4], 0)) };}+/// `kern.cp_times`: the same five counters per CPU up to `mp_maxid`; absent+/// CPUs read all zero and are skipped, so `id` keeps the CPU number.+pub fn cpuCores(buf: []u8, out: []common.Core) usize {+ const per_cpu = 5 * @sizeOf(c_long);+ var len: usize = buf.len - buf.len % per_cpu;+ if (std.c.sysctlbyname("kern.cp_times", buf.ptr, &len, null, 0) != 0 or len % per_cpu != 0) return 0;+ var count: usize = 0;+ for (0..len / per_cpu) |cpu| {+ if (count == out.len) break;+ var times: [5]c_long = undefined;+ @memcpy(std.mem.asBytes(×), buf[cpu * per_cpu ..][0..per_cpu]);+ var total: u64 = 0;+ for (times) |ticks| total += @intCast(@max(ticks, 0));+ if (total == 0) continue;+ out[count] = .{ .id = @intCast(cpu), .cpu = .{ .total = total, .idle = @intCast(@max(times[4], 0)) } };+ count += 1;+ }+ return count;+}+/// Available is free plus inactive pages. Swap is not read.pub fn memoryTotals(_: []u8) ?common.Memory {const page = common.pageSize();@@ -174,6 +194,8 @@ pub fn memoryTotals(_: []u8) ?common.Memory {.available = @min(total, (@as(u64, free) + inactive) * page),.swap_total = null,.swap_free = null,+ .free = @min(total, @as(u64, free) * page),+ .cached = @min(total, @as(u64, inactive) * page),};}@@ -189,6 +211,8 @@ pub fn systemStats(_: []u8) common.System {if (sysctlValue(c_int, "dev.cpu.0.freq")) |mhz| if (mhz > 0) {result.frequency_ghz = @as(f64, @floatFromInt(mhz)) / 1000;};+ var load: [3]f64 = undefined;+ if (c.getloadavg(&load, 3) == 3) result.load = load;var uptime: c.struct_timespec = undefined;if (c.clock_gettime(c.CLOCK_UPTIME, &uptime) == 0 and uptime.tv_sec >= 0)result.uptime_seconds = @intCast(uptime.tv_sec);diff --git a/src/system_monitor/proc_linux.zig b/src/system_monitor/proc_linux.zigindex 95055aa..94b0a2b 100644--- a/src/system_monitor/proc_linux.zig+++ b/src/system_monitor/proc_linux.zig@@ -55,6 +55,31 @@ pub fn parseUids(bytes: []const u8) ?Uids {pub fn parseCpu(bytes: []const u8) ?Cpu {var fields = std.mem.tokenizeAny(u8, bytes[0 .. std.mem.indexOfScalar(u8, bytes, '\n') orelse bytes.len], " \t");if (!std.mem.eql(u8, fields.next() orelse return null, "cpu")) return null;+ return cpuFields(&fields);+}++/// The `cpuN` lines in order; offline CPUs have none, so `id` keeps N.+pub fn parseCores(bytes: []const u8, out: []common.Core) usize {+ var count: usize = 0;+ var lines = std.mem.splitScalar(u8, bytes, '\n');+ while (lines.next()) |line| {+ if (count == out.len) break;+ var fields = std.mem.tokenizeAny(u8, line, " \t");+ const name = fields.next() orelse continue;+ if (!std.mem.startsWith(u8, name, "cpu")) {+ // The per-CPU lines follow the total; anything else ends them.+ if (count > 0) break;+ continue;+ }+ if (name.len == 3) continue;+ const id = std.fmt.parseInt(u32, name[3..], 10) catch continue;+ out[count] = .{ .id = id, .cpu = cpuFields(&fields) orelse continue };+ count += 1;+ }+ return count;+}++fn cpuFields(fields: *std.mem.TokenIterator(u8, .any)) ?Cpu {var out: Cpu = .{ .total = 0, .idle = 0 };var count: usize = 0;// guest and guest_nice are already included in user/nice.@@ -72,11 +97,22 @@ pub fn parseMemory(bytes: []const u8) ?Memory {var available: ?u64 = null;var swap_total: ?u64 = null;var swap_free: ?u64 = null;+ // Free, buff/cache (Buffers + Cached + SReclaimable) and Shmem.+ var extra: [5]?u64 = @splat(null);+ const extra_keys = [_][]const u8{ "MemFree:", "Buffers:", "Cached:", "SReclaimable:", "Shmem:" };var lines = std.mem.splitScalar(u8, bytes, '\n');while (lines.next()) |line| {var fields = std.mem.tokenizeAny(u8, line, " \t");const key = fields.next() orelse continue;+ const slot = for (extra_keys, 0..) |name, i| {+ if (std.mem.eql(u8, key, name)) break i;+ } else null;const relevant = std.mem.eql(u8, key, "MemTotal:") or std.mem.eql(u8, key, "MemAvailable:") or std.mem.eql(u8, key, "SwapTotal:") or std.mem.eql(u8, key, "SwapFree:");+ if (slot) |i| {+ const kb = std.fmt.parseInt(u64, fields.next() orelse continue, 10) catch continue;+ extra[i] = std.math.mul(u64, kb, 1024) catch null;+ continue;+ }if (!relevant) continue;const kb = std.fmt.parseInt(u64, fields.next() orelse return null, 10) catch return null;if (!std.mem.eql(u8, fields.next() orelse return null, "kB")) return null;@@ -86,7 +122,19 @@ pub fn parseMemory(bytes: []const u8) ?Memory {if (std.mem.eql(u8, key, "SwapTotal:")) swap_total = value;if (std.mem.eql(u8, key, "SwapFree:")) swap_free = value;}- return .{ .total = total orelse return null, .available = available orelse return null, .swap_total = swap_total, .swap_free = swap_free };+ const cached: ?u64 = if (extra[1] != null and extra[2] != null)+ extra[1].? +| extra[2].? +| (extra[3] orelse 0)+ else+ null;+ return .{+ .total = total orelse return null,+ .available = available orelse return null,+ .swap_total = swap_total,+ .swap_free = swap_free,+ .free = extra[0],+ .cached = cached,+ .shared = extra[4],+ };}pub const Process = struct {@@ -146,6 +194,10 @@ pub fn cpuTotals(buf: []u8) ?Cpu {return parseCpu(readAt(c.AT_FDCWD, "/proc/stat", buf) catch return null);}+pub fn cpuCores(buf: []u8, out: []common.Core) usize {+ return parseCores(readAt(c.AT_FDCWD, "/proc/stat", buf) catch return 0, out);+}+pub fn memoryTotals(buf: []u8) ?Memory {return parseMemory(readAt(c.AT_FDCWD, "/proc/meminfo", buf) catch return null);}diff --git a/src/system_monitor/proc_linux_system.zig b/src/system_monitor/proc_linux_system.zigindex 83807c3..274a72e 100644--- a/src/system_monitor/proc_linux_system.zig+++ b/src/system_monitor/proc_linux_system.zig@@ -18,6 +18,9 @@ pub fn sample(buf: []u8) common.System {result.uptime_seconds = @intFromFloat(seconds);}} else |_| {}+ if (common.readAt(c.AT_FDCWD, "/proc/loadavg", buf)) |bytes| {+ parseLoad(bytes, &result);+ } else |_| {}if (common.readAt(c.AT_FDCWD, "/proc/net/dev", buf)) |bytes| {result.network = parseNetwork(bytes);} else |_| {}@@ -27,6 +30,20 @@ pub fn sample(buf: []u8) common.System {return result;}+/// "0.52 0.58 0.59 2/1234 5678": three averages, then running/total threads.+pub fn parseLoad(bytes: []const u8, result: *common.System) void {+ var fields = std.mem.tokenizeAny(u8, bytes, " \t\n");+ var load: [3]f64 = undefined;+ for (&load) |*value| {+ value.* = std.fmt.parseFloat(f64, fields.next() orelse return) catch return;+ if (!std.math.isFinite(value.*) or value.* < 0) return;+ }+ result.load = load;+ const entities = fields.next() orelse return;+ const slash = std.mem.indexOfScalar(u8, entities, '/') orelse return;+ result.threads = std.fmt.parseInt(u64, entities[slash + 1 ..], 10) catch null;+}+pub fn parseNetwork(bytes: []const u8) ?common.Network {var lines = std.mem.splitScalar(u8, bytes, '\n');if (std.mem.indexOf(u8, lines.next() orelse return null, "Inter-") == null) return null;diff --git a/src/system_monitor/proc_system_tests.zig b/src/system_monitor/proc_system_tests.zigindex 154a765..b637641 100644--- a/src/system_monitor/proc_system_tests.zig+++ b/src/system_monitor/proc_system_tests.zig@@ -25,3 +25,13 @@ test "network totals exclude loopback and compare interface sets independent oftry std.testing.expect(linux.parseNetwork(header ++ "eth0: 1 2 3\n") == null);try std.testing.expect(linux.parseNetwork("unavailable") == null);}++test "load averages and the thread count come from /proc/loadavg" {+ var system: proc.System = .{};+ linux.parseLoad("0.52 0.58 1.50 2/1234 5678\n", &system);+ try std.testing.expectEqual([3]f64{ 0.52, 0.58, 1.50 }, system.load.?);+ try std.testing.expectEqual(@as(u64, 1234), system.threads.?);+ var broken: proc.System = .{};+ linux.parseLoad("0.5 nan", &broken);+ try std.testing.expect(broken.load == null and broken.threads == null);+}diff --git a/src/system_monitor_tests.zig b/src/system_monitor_tests.zigindex b04794a..09ed26b 100644--- a/src/system_monitor_tests.zig+++ b/src/system_monitor_tests.zig@@ -36,6 +36,8 @@ test "monitor backend lists and describes this process and the machine" {const cpu = proc.cpuTotals(&buf).?;try std.testing.expect(cpu.total > 0 and cpu.idle <= cpu.total);+ var cores: [proc.max_cores]proc.Core = undefined;+ try std.testing.expect(proc.cpuCores(&buf, &cores) > 0);const memory = proc.memoryTotals(&buf).?;try std.testing.expect(memory.total > 0 and memory.available <= memory.total);try std.testing.expect(proc.ticksPerSecond() > 0 and proc.pageSize() > 0);@@ -57,6 +59,22 @@ test "monitor CPU excludes guest accounting and rejects reset counters and PID rtry std.testing.expectEqual(@as(u64, 640), before.total);try std.testing.expectApproxEqAbs(@as(f64, 50), proc.cpuPercent(before, after).?, 0.001);try std.testing.expect(proc.cpuPercent(after, before) == null);+ // Per-CPU lines keep their numbers across an offline CPU and stop at intr.+ var cores: [4]proc.Core = undefined;+ const listed = linux.parseCores("cpu 9 9 9 9\ncpu0 10 0 0 30\ncpu2 1 2 3 4 5\nintr 5 6\ncpu3 1 1 1 1\n", &cores);+ try std.testing.expectEqual(@as(usize, 2), listed);+ try std.testing.expectEqual(@as(u32, 2), cores[1].id);+ try std.testing.expectEqual(proc.Cpu{ .total = 40, .idle = 30 }, cores[0].cpu);+ try std.testing.expectEqual(@as(usize, 1), linux.parseCores("cpu0 1 1 1 1\ncpu1 1 1 1 1\n", cores[0..1]));+ var snap: collector.Snapshot = .{ .arena = .init(std.testing.allocator), .processes = &.{}, .at_ns = 0, .cpu = null, .memory = null };+ defer snap.arena.deinit();+ var now = [_]proc.Core{ .{ .id = 0, .cpu = .{ .total = 200, .idle = 50 } }, .{ .id = 3, .cpu = .{ .total = 200, .idle = 200 } } };+ var percent = [_]?f64{ null, null };+ snap.cores = &now;+ snap.core_percent = &percent;+ collector.corePercents(&snap, &.{ .{ .id = 3, .cpu = .{ .total = 100, .idle = 100 } }, .{ .id = 0, .cpu = .{ .total = 100, .idle = 50 } } });+ try std.testing.expectApproxEqAbs(@as(f64, 100), percent[0].?, 0.001);+ try std.testing.expectApproxEqAbs(@as(f64, 0), percent[1].?, 0.001);var first: proc.Stat = .{ .name = "", .state = 'R', .cpu = 100, .start = 10, .rss = 0 };var second = first;second.cpu = 350;@@ -68,6 +86,11 @@ test "monitor memory uses available rather than free and bounds missing values"const mem = linux.parseMemory("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 400 kB\nSwapTotal: 500 kB\nSwapFree: 250 kB\n").?;try std.testing.expectEqual(@as(u64, 600 * 1024), mem.used());try std.testing.expectEqual(@as(u64, 500 * 1024), mem.swap_total.?);+ try std.testing.expectEqual(@as(u64, 100 * 1024), mem.free.?);+ try std.testing.expect(mem.cached == null);+ const detail = linux.parseMemory("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 400 kB\nBuffers: 10 kB\nCached: 200 kB\nShmem: 30 kB\nSReclaimable: 20 kB\n").?;+ try std.testing.expectEqual(@as(u64, 230 * 1024), detail.cached.?);+ try std.testing.expectEqual(@as(u64, 30 * 1024), detail.shared.?);try std.testing.expect(linux.parseMemory("MemTotal: 1000 kB\nMemFree: 100 kB\n") == null);try std.testing.expect(linux.parseMemory("MemTotal: 18446744073709551615 kB\nMemAvailable: 1 kB") == null);}diff --git a/tests/system_monitor.py b/tests/system_monitor.pyindex 47976ca..5ad8736 100644--- a/tests/system_monitor.py+++ b/tests/system_monitor.py@@ -206,6 +206,27 @@ def run(scale, workspace):assert shot("initial").getpixel((4, 4)) == (32, 48, 64)assert "temperature" in gpu_trace.read_text().splitlines(), "GPU telemetry was not sampled"+ # A card expands to the full width over the gap between the two;+ # clicking its body, its collapse button or Escape brings both back.+ def gap_pixel(name):+ image = shot(name)+ factor = image.width / box()["width"]+ return image.getpixel((round(box()["width"] / 2 * factor), round(75 * factor)))+ assert gap_pixel("cards") == (32, 48, 64)+ for name, card_x in (("cpu", 120), ("ram", box()["width"] - 120)):+ for dismiss in ("pane", "button", "escape"):+ click(card_x, 75)+ time.sleep(1)+ assert gap_pixel(f"{name}-expanded-{dismiss}") != (32, 48, 64), f"{name} card did not expand"+ if dismiss == "pane":+ click(box()["width"] / 2, 75)+ elif dismiss == "button":+ click(box()["width"] - 42, 38)+ else:+ chord(1)+ time.sleep(1)+ assert gap_pixel(f"{name}-collapsed-{dismiss}") == (32, 48, 64), f"{name} card did not collapse via {dismiss}"+# Background collection follows visibility, independently of keyboard focus.ipc.open_control_center()before = switches(monitor_pid)