Battery panel module: charge, charging state, time left, low-battery warning
CI / test (push) Failing after 18s

- 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
This commit is contained in:
Claude committed 2026-11-25 19:53:42 +00:00
1 parent 05fe70a2f6
commit 88915842c2
48 files changed
+2143 -17

No files matched your search

+181
View File
@@ -0,0 +1,181 @@
///| Linux provider for the `battery` capability (and the battery fields of `system`): reads
/// /sys/class/power_supply. Every battery the machine has counts together (a laptop with two
/// packs shows one charge). Modules never see these paths.
///| Where power supplies are read from; tests point it at a fake tree.
let power_supply_root : Ref[String] = { val: "/sys/class/power_supply" }
///| Read batteries from `dir` instead of /sys/class/power_supply (tests: a fake power supply).
pub fn set_power_supply_root(dir : String) -> Unit {
power_supply_root.val = dir
}
///| Names Linux gives batteries (ACPI, Apple, Chromebooks, many ARM boards). The tree is not listed:
/// a lookup of each name keeps this to plain file reads, which every host serves.
let battery_names : Array[String] = ["BAT0", "BAT1", "BAT2", "BATT", "BATC", "CMB0", "CMB1", "battery"]
///| The `battery.status` record: state is the `charge-state` index (0 none, 1 discharging,
/// 2 charging, 3 full, 4 not charging).
#derive(Eq, Debug)
pub(all) struct BatteryInfo {
percent : Int
state : Int
secs_left : Int
}
///|
let no_battery : BatteryInfo = { percent: -1, state: 0, secs_left: 0 }
///| One battery's numbers, in µWh/µW (energy_*, power_now) or µAh/µA (charge_*, current_now).
priv struct Pack {
capacity : Int
status : String
now : Int64
full : Int64
rate : Int64
}
///|
fn sysfs_text(path : String) -> String {
@utf8.decode_lossy(@sys.read_proc_bytes(path)).trim(chars=" \n").to_string()
}
///| A sysfs number ("-1234" allowed), or -1 when the file is missing or empty.
fn sysfs_num(path : String) -> Int64 {
let s = sysfs_text(path)
if s.length() == 0 {
return -1L
}
if s.has_prefix("-") {
-parse_i64(s[1:].to_string())
} else {
parse_i64(s)
}
}
///|
fn read_pack(base : String) -> Pack? {
let cap = sysfs_text(base + "/capacity")
if cap.length() == 0 {
return None
}
let ty = sysfs_text(base + "/type")
// A mouse or headset battery (scope Device) is not the machine's.
if (ty.length() > 0 && ty != "Battery") || sysfs_text(base + "/scope") == "Device" {
return None
}
let energy = sysfs_num(base + "/energy_now") >= 0L
let (n, f, r) = if energy {
("energy_now", "energy_full", "power_now")
} else {
("charge_now", "charge_full", "current_now")
}
let rate = sysfs_num(base + "/" + r)
Some({
capacity: parse_i64(cap).to_int(),
status: sysfs_text(base + "/status"),
now: sysfs_num(base + "/" + n),
full: sysfs_num(base + "/" + f),
// Some firmware reports discharge as a negative rate.
rate: if rate < 0L { -rate } else { rate },
})
}
///| The machine's batteries under `root`, summed: percent from the energy left over the energy
/// when full (each pack's capacity if they don't say), state, and the seconds left at the current
/// rate (0 when the firmware doesn't report one). Without a battery: percent -1, state 0.
pub fn read_battery(root? : String = power_supply_root.val) -> BatteryInfo {
let packs : Array[Pack] = []
for name in battery_names {
match read_pack(root + "/" + name) {
Some(p) => packs.push(p)
None => ()
}
}
if packs.length() == 0 {
return no_battery
}
let mut now = 0L
let mut full = 0L
let mut rate = 0L
let mut cap_sum = 0
let mut sized = true
let mut discharging = false
let mut charging = false
let mut all_full = true
for p in packs {
cap_sum = cap_sum + p.capacity
if p.now < 0L || p.full <= 0L {
sized = false
} else {
now = now + p.now
full = full + p.full
}
if p.rate > 0L {
rate = rate + p.rate
}
match p.status {
"Discharging" => discharging = true
"Charging" => charging = true
_ => ()
}
if p.status != "Full" && p.capacity < 100 {
all_full = false
}
}
let percent = if sized {
((now * 100L + full / 2L) / full).to_int()
} else {
cap_sum / packs.length()
}
let percent = if percent < 0 { 0 } else if percent > 100 { 100 } else { percent }
let state = if discharging { 1 } else if charging { 2 } else if all_full { 3 } else { 4 }
let secs = if !sized || rate <= 0L {
0
} else if state == 1 {
(now * 3600L / rate).to_int()
} else if state == 2 {
let left = full - now
if left > 0L { (left * 3600L / rate).to_int() } else { 0 }
} else {
0
}
{ percent, state, secs_left: secs }
}
///| Samples the battery about once a second for the `battery` capability. The discharge rate
/// jumps with load, so time left follows a running average of it rather than each sample.
pub(all) struct BatteryMeter {
mut last_secs : Int
mut last_state : Int
/// Average seconds left, scaled by the latest reading's energy (0: none yet).
mut avg_secs : Int
mut cur : BatteryInfo
}
///|
pub fn BatteryMeter::new() -> BatteryMeter {
{ last_secs: -1, last_state: -1, avg_secs: 0, cur: no_battery }
}
///| Feed one reading: the time left is averaged (a quarter of each new sample) while the state
/// holds, and starts over when it changes (plugged in, unplugged).
pub fn BatteryMeter::feed(self : BatteryMeter, b : BatteryInfo) -> Unit {
if b.state != self.last_state || b.secs_left <= 0 || self.avg_secs <= 0 {
self.avg_secs = b.secs_left
} else {
self.avg_secs = (self.avg_secs * 3 + b.secs_left) / 4
}
self.last_state = b.state
self.cur = { ..b, secs_left: self.avg_secs }
}
///| Re-read if a wall-clock second passed since the last call; cheap otherwise.
pub fn BatteryMeter::refresh(self : BatteryMeter) -> BatteryInfo {
let now = wall_secs()
if now != self.last_secs {
self.last_secs = now
self.feed(read_battery())
}
self.cur
}
+3
View File
@@ -261,6 +261,8 @@ pub(all) struct DesktopShell {
mut picker : @wasm.Picker?
/// Machine-state provider behind the `system` interface, and the window list behind `windows`.
sampler : SysSampler
/// The battery for modules with the `battery` capability (battery.mbt).
battery : BatteryMeter
mut win_list : Array[@wasm.WindowEntry]
mut notice : String
mut notice_frames : Int
@@ -358,6 +360,7 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
actions: [],
apps_dirty: true,
sampler: SysSampler::new(),
battery: BatteryMeter::new(),
win_list: [],
picker: None,
notice: "",
+3 -10
View File
@@ -146,17 +146,10 @@ fn mem_kib() -> (Int64, Int64) {
(total, avail)
}
///| (percent, plugged-in) for the first battery, or (-1, true) without one.
///| (percent, plugged-in) for the machine's batteries (battery.mbt), or (-1, true) without one.
fn battery() -> (Int, Bool) {
for name in ["BAT0", "BAT1", "BATT"] {
let base = "/sys/class/power_supply/" + name
let cap = proc_text(base + "/capacity")
if cap.length() > 0 {
let status = proc_text(base + "/status").trim(chars=" \n").to_string()
return (parse_i64(cap).to_int(), status != "Discharging")
}
}
(-1, true)
let b = read_battery()
(b.percent, b.state != 1)
}
///| Re-sample if a wall-clock second passed since the last call; cheap otherwise.
+28 -1
View File
@@ -17,6 +17,29 @@ let default_panel : Array[String] = [
"logout",
]
///| A fresh panel's modules: the defaults, plus the battery before the clock on a machine that
/// has one (a desktop gets no battery module; it can be added from the settings module).
fn fresh_panel(has_battery : Bool) -> Array[String] {
if !has_battery {
return default_panel
}
let out : Array[String] = []
for m in default_panel {
if m == "clock-digital12" {
out.push("battery")
}
out.push(m)
}
out
}
///|
test "a fresh panel gets the battery module only on a machine with a battery" {
assert_false(fresh_panel(false).contains("battery"))
let p = fresh_panel(true)
assert_eq(p.search("battery").unwrap() + 1, p.search("clock-digital12").unwrap())
}
///| The module whose popup holds the wasm picker (its Modules tab).
let manager_module : String = "session-settings"
@@ -209,7 +232,7 @@ fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit {
self.scan_catalog()
let entries = match self.load_panel_config() {
Some(e) => migrate_panel(e)
None => default_panel
None => fresh_panel(read_battery().state != 0)
}
for e in entries {
let path = if e.has_prefix("/") {
@@ -436,6 +459,10 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
if self.widgets.iter().any(w => w.has_cap("screenshot")) {
@wasm.publish_screenshot(self.screenshot_state)
}
if self.widgets.iter().any(w => w.has_cap("battery")) {
let b = self.battery.refresh()
@wasm.publish_battery(b.percent, b.state, b.secs_left)
}
let it = @wasm.Table::new()
for w in self.widgets {
it.str(w.slot)