Files
chandra/compositor/shell/sysinfo.mbt
T
Claude 88915842c2
CI / test (push) Failing after 18s
Battery panel module: charge, charging state, time left, low-battery warning
- New `battery` panel module (components/battery, logic in lib/battery): a battery icon filled to
  the charge with the percentage and time remaining ("73% 2:05"; time to full while charging).
  The fill turns green when charging or full, amber at 20 % and below, and at 10 % the whole
  button turns red and a "Battery low" popup opens by itself, once per discharge spell. A click
  opens the details (charge, state, time left in words). Without a battery it shows a plug.
- Right-click "Module settings": Show percentage, Show time remaining, and Without a battery
  (Show a plug / Show nothing). Saved per module in state.edn like the clocks' settings.
- New `battery` capability (wit/capabilities.wit: read -> status {percent, charge-state,
  secs-left}). Served by the wasmer stub (host ints 7-9), host-wasm and wasmhost (publish-battery).
- Host side (compositor/shell/battery.mbt): reads /sys/class/power_supply, every battery
  together (energy_* / power_now, or charge_* / current_now; capacity when that is all there
  is; device-scope batteries like mice are skipped). The `system` snapshot the Power tab uses
  now reads the battery through the same code. Time left follows a running average of the
  rate, starting over when the state changes.
- A fresh panel gets the battery module before the clock only on a machine with a battery.
- wasm_stub: MAX_INST 512 -> 2048. The host test binary creates ~70 compositors without
  unloading their modules; at 512 the last tests' panels came up half empty.
- Tests: sysfs reading against a fake power supply (energy and charge units, two packs,
  charging, full, capacity only, no battery), the running average, the module in the panel
  (text, settings, click, the critical warning, the plug), the rendering logic, and a
  host-wasm test of the module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hky51dmaUqiYW746Gz
2026-11-25 19:53:42 +00:00

193 lines
4.9 KiB
MoonBit

///| Linux provider for the `system` interface: samples /proc and /sys about once a second
/// and hands widgets a `SystemSnapshot`. Widgets never see these paths; swapping this file
/// for another provider (a VM, a remote host, a mock) changes nothing for them.
///|
pub(all) struct SysSampler {
mut last_secs : Int
mut prev_busy : Int64
mut prev_total : Int64
mut prev_rx : Int64
mut prev_tx : Int64
mut primed : Bool
mut cur : @wasm.SystemSnapshot
}
///|
fn SysSampler::new() -> SysSampler {
{
last_secs: -1,
prev_busy: 0L,
prev_total: 0L,
prev_rx: 0L,
prev_tx: 0L,
primed: false,
cur: {
cpu_permille: 0,
mem_used_kib: 0L,
mem_total_kib: 0L,
battery_percent: -1,
charging: false,
uptime_secs: 0L,
rx_bps: 0L,
tx_bps: 0L,
load_centi: 0,
},
}
}
///|
fn proc_text(path : String) -> String {
@utf8.decode_lossy(@sys.read_proc_bytes(path))
}
///| Leading unsigned integer of `s` (0 if none).
fn parse_i64(s : String) -> Int64 {
let mut v = 0L
for ch in s {
let c = ch.to_int()
if c >= 48 && c <= 57 {
v = v * 10L + (c - 48).to_int64()
} else {
break
}
}
v
}
///| Whitespace-separated fields.
fn fields(s : String) -> Array[String] {
let out : Array[String] = []
let mut cur = ""
for ch in s {
if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' {
if cur.length() > 0 {
out.push(cur)
cur = ""
}
} else {
cur = cur + ch.to_string()
}
}
if cur.length() > 0 {
out.push(cur)
}
out
}
///| "0.52" -> 52 (hundredths).
fn parse_centi(s : String) -> Int {
let parts = s.split(".").collect()
let whole = parse_i64(parts[0].to_string()).to_int()
let frac = if parts.length() > 1 {
let f = parts[1].to_string()
let two = if f.length() >= 2 { f[:2].to_string() } else { f + "0" }
parse_i64(two).to_int()
} else {
0
}
whole * 100 + frac
}
///| (busy, total) jiffies from the aggregate "cpu" line of /proc/stat.
fn cpu_times() -> (Int64, Int64) {
let text = proc_text("/proc/stat")
for line in text.split("\n") {
let f = fields(line.to_string())
if f.length() > 5 && f[0] == "cpu" {
let mut total = 0L
for i = 1; i < f.length() && i <= 8; i = i + 1 {
total = total + parse_i64(f[i])
}
let idle = parse_i64(f[4]) + parse_i64(f[5])
return (total - idle, total)
}
}
(0L, 0L)
}
///| (rx, tx) bytes summed over every interface but loopback.
fn net_bytes() -> (Int64, Int64) {
let mut rx = 0L
let mut tx = 0L
for line in proc_text("/proc/net/dev").split("\n") {
let l = line.to_string()
match l.find(":") {
None => ()
Some(i) => {
let name = l[:i].to_string().trim(chars=" ").to_string()
if name != "lo" {
let f = fields(l[i + 1:].to_string())
if f.length() > 8 {
rx = rx + parse_i64(f[0])
tx = tx + parse_i64(f[8])
}
}
}
}
}
(rx, tx)
}
///| (total, available) KiB from /proc/meminfo.
fn mem_kib() -> (Int64, Int64) {
let mut total = 0L
let mut avail = 0L
for line in proc_text("/proc/meminfo").split("\n") {
let f = fields(line.to_string())
if f.length() >= 2 {
if f[0] == "MemTotal:" {
total = parse_i64(f[1])
} else if f[0] == "MemAvailable:" {
avail = parse_i64(f[1])
}
}
}
(total, avail)
}
///| (percent, plugged-in) for the machine's batteries (battery.mbt), or (-1, true) without one.
fn battery() -> (Int, Bool) {
let b = read_battery()
(b.percent, b.state != 1)
}
///| Re-sample if a wall-clock second passed since the last call; cheap otherwise.
fn SysSampler::refresh(self : SysSampler) -> Unit {
let now = wall_secs()
if now == self.last_secs {
return
}
let dt = if self.last_secs < 0 {
1
} else {
let d = now - self.last_secs
if d <= 0 { d + 86400 } else { d }
}
self.last_secs = now
let (busy, total) = cpu_times()
let (rx, tx) = net_bytes()
let (mt, ma) = mem_kib()
let (pct, plugged) = battery()
let dtotal = total - self.prev_total
let cpu = if self.primed && dtotal > 0L { ((busy - self.prev_busy) * 1000L / dtotal).to_int() } else { 0 }
let load = parse_centi(fields(proc_text("/proc/loadavg")).get(0).unwrap_or("0"))
self.cur = {
cpu_permille: if cpu < 0 { 0 } else if cpu > 1000 { 1000 } else { cpu },
mem_used_kib: mt - ma,
mem_total_kib: mt,
battery_percent: pct,
charging: plugged,
uptime_secs: parse_i64(fields(proc_text("/proc/uptime")).get(0).unwrap_or("0")),
rx_bps: if self.primed && rx >= self.prev_rx { (rx - self.prev_rx) / dt.to_int64() } else { 0L },
tx_bps: if self.primed && tx >= self.prev_tx { (tx - self.prev_tx) / dt.to_int64() } else { 0L },
load_centi: load,
}
self.prev_busy = busy
self.prev_total = total
self.prev_rx = rx
self.prev_tx = tx
self.primed = true
@wasm.set_system(self.cur)
}