Battery panel module: charge, charging state, time left, low-battery warning
CI / test (push) Failing after 18s
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:
48 files changed
+2143
-17
No files matched your search
@@ -0,0 +1,184 @@
|
||||
///| The battery: reading a fake /sys/class/power_supply, and the battery panel module drawing it.
|
||||
|
||||
///| Write a fake power supply tree: (directory, [(file, contents)]) under a fresh directory.
|
||||
fn fake_supply(tag : String, entries : Array[(String, Array[(String, String)])]) -> String {
|
||||
let root = "/tmp/chandra-power-" + tag + "-" + @sys.getpid().to_string()
|
||||
for e in entries {
|
||||
let (name, files) = e
|
||||
ignore(@sys.mkdir_p(root + "/" + name))
|
||||
for f in files {
|
||||
let (file, text) = f
|
||||
ignore(@sys.write_file_bytes(root + "/" + name + "/" + file, @sys.str_to_utf8_bytes(text + "\n")))
|
||||
}
|
||||
}
|
||||
ignore(@sys.mkdir_p(root))
|
||||
root
|
||||
}
|
||||
|
||||
///|
|
||||
fn bat(status : String, capacity : Int, now : Int, full : Int, rate : Int) -> Array[(String, String)] {
|
||||
[
|
||||
("type", "Battery"),
|
||||
("status", status),
|
||||
("capacity", capacity.to_string()),
|
||||
("energy_now", now.to_string()),
|
||||
("energy_full", full.to_string()),
|
||||
("power_now", rate.to_string()),
|
||||
]
|
||||
}
|
||||
|
||||
///|
|
||||
test "no battery: percent -1, state none" {
|
||||
let root = fake_supply("none", [("AC", [("type", "Mains"), ("online", "1")])])
|
||||
assert_eq(@shell.read_battery(root~), { percent: -1, state: 0, secs_left: 0 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "a discharging battery: percent from energy, time left at the current power" {
|
||||
let root = fake_supply("dis", [("BAT0", bat("Discharging", 59, 30000000, 50000000, 10000000))])
|
||||
// 30 Wh of 50 Wh at 10 W: 60 %, three hours.
|
||||
assert_eq(@shell.read_battery(root~), { percent: 60, state: 1, secs_left: 3 * 3600 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "charging: time until full; full and not charging have no time" {
|
||||
let root = fake_supply("chg", [("BAT0", bat("Charging", 40, 20000000, 50000000, 15000000))])
|
||||
assert_eq(@shell.read_battery(root~), { percent: 40, state: 2, secs_left: 2 * 3600 })
|
||||
let root = fake_supply("full", [("BAT0", bat("Full", 100, 50000000, 50000000, 0))])
|
||||
assert_eq(@shell.read_battery(root~), { percent: 100, state: 3, secs_left: 0 })
|
||||
let root = fake_supply("hold", [("BAT0", bat("Not charging", 80, 40000000, 50000000, 0))])
|
||||
assert_eq(@shell.read_battery(root~), { percent: 80, state: 4, secs_left: 0 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "two packs in charge units count together; a negative current is a discharge" {
|
||||
let root = fake_supply("two", [
|
||||
(
|
||||
"BAT0",
|
||||
[
|
||||
("type", "Battery"),
|
||||
("status", "Discharging"),
|
||||
("capacity", "50"),
|
||||
("charge_now", "2000000"),
|
||||
("charge_full", "4000000"),
|
||||
("current_now", "-1000000"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"BAT1",
|
||||
[
|
||||
("type", "Battery"),
|
||||
("status", "Not charging"),
|
||||
("capacity", "100"),
|
||||
("charge_now", "4000000"),
|
||||
("charge_full", "4000000"),
|
||||
("current_now", "0"),
|
||||
],
|
||||
),
|
||||
])
|
||||
// 6 of 8 Ah, draining at 1 A: six hours.
|
||||
assert_eq(@shell.read_battery(root~), { percent: 75, state: 1, secs_left: 6 * 3600 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "a battery without energy or charge files uses its capacity; time is unknown" {
|
||||
let root = fake_supply("cap", [("BAT1", [("status", "Discharging"), ("capacity", "42")])])
|
||||
assert_eq(@shell.read_battery(root~), { percent: 42, state: 1, secs_left: 0 })
|
||||
}
|
||||
|
||||
///|
|
||||
test "time left is a running average while the state holds" {
|
||||
let m = @shell.BatteryMeter::new()
|
||||
m.feed({ percent: 50, state: 1, secs_left: 4000 })
|
||||
assert_eq(m.cur.secs_left, 4000)
|
||||
m.feed({ percent: 50, state: 1, secs_left: 8000 })
|
||||
assert_eq(m.cur.secs_left, 5000)
|
||||
// Plugging in starts over.
|
||||
m.feed({ percent: 50, state: 2, secs_left: 1200 })
|
||||
assert_eq(m.cur.secs_left, 1200)
|
||||
}
|
||||
|
||||
///|
|
||||
fn module_texts(comp : @host.ChandraCompositor) -> Array[String] {
|
||||
let out : Array[String] = []
|
||||
for op in comp.shell.slot_ops(comp.shell.slot_of("battery")) {
|
||||
if op is Text(t) {
|
||||
out.push(t.text)
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| A compositor whose panel has the battery module. A fresh panel gets it from the (fake) battery;
|
||||
/// a panel.edn another test saved may not have it, so it is added (in place of their extra clock,
|
||||
/// which would not leave room).
|
||||
fn battery_comp(tag : String) -> @host.ChandraCompositor {
|
||||
let comp = new_comp(tag)
|
||||
if comp.shell.slot_of("battery") == "" {
|
||||
let extra = comp.shell.slot_of("clock-binary")
|
||||
if extra != "" {
|
||||
ignore(comp.shell.unload_slot(extra))
|
||||
}
|
||||
ignore(comp.shell.load_module("battery"))
|
||||
ignore(comp.compose_frame())
|
||||
}
|
||||
comp
|
||||
}
|
||||
|
||||
///| Wait for the wall clock's next second, so the shell samples the battery again.
|
||||
fn next_second(comp : @host.ChandraCompositor) -> Unit {
|
||||
let s = @sys.wall_time_field(5)
|
||||
let t0 = @sys.monotonic_ms()
|
||||
while @sys.wall_time_field(5) == s && @sys.monotonic_ms() - t0 < 2000UL {
|
||||
@sys.sleep_ms(20)
|
||||
}
|
||||
ignore(comp.compose_frame())
|
||||
}
|
||||
|
||||
///|
|
||||
test "the battery module shows charge and time left, its settings, and warns when critical" {
|
||||
let root = fake_supply("module", [("BAT0", bat("Discharging", 60, 30000000, 50000000, 10000000))])
|
||||
@shell.set_power_supply_root(root)
|
||||
let comp = battery_comp("battery")
|
||||
let slot = comp.shell.slot_of("battery")
|
||||
assert_true(comp.shell.slot_rect(slot).w > 0)
|
||||
assert_eq(module_texts(comp), ["60% 3:00"])
|
||||
assert_eq(comp.shell.slot_config(slot).map(i => i.key), ["percent", "time", "no-battery"])
|
||||
comp.shell.set_module_setting(slot, "time", "off")
|
||||
assert_eq(module_texts(comp), ["60%"])
|
||||
comp.shell.set_module_setting(slot, "time", "on")
|
||||
// A click opens the details.
|
||||
click_module(comp, "battery", 1U) catch {
|
||||
_ => fail("battery module not placed")
|
||||
}
|
||||
assert_true(comp.shell.slot_popup_rect(slot).w > 0)
|
||||
click_module(comp, "battery", 5U) catch {
|
||||
_ => fail("battery module not placed")
|
||||
}
|
||||
assert_eq(comp.shell.slot_popup_rect(slot).w, 0)
|
||||
// Down to 8 %: the warning opens by itself.
|
||||
ignore(
|
||||
@sys.write_file_bytes(root + "/BAT0/energy_now", @sys.str_to_utf8_bytes("4000000\n")),
|
||||
)
|
||||
next_second(comp)
|
||||
ignore(comp.compose_frame())
|
||||
// (The time left eases toward the new 24 minutes, a quarter per sample.)
|
||||
assert_true(module_texts(comp)[0].has_prefix("8% "))
|
||||
assert_true(comp.shell.slot_popup_rect(slot).w > 0)
|
||||
@shell.set_power_supply_root("/sys/class/power_supply")
|
||||
}
|
||||
|
||||
///|
|
||||
test "without a battery the module shows a plug, or nothing" {
|
||||
let root = fake_supply("module-none", [])
|
||||
@shell.set_power_supply_root(root)
|
||||
let comp = battery_comp("battery-none")
|
||||
let slot = comp.shell.slot_of("battery")
|
||||
let ops = comp.shell.slot_ops(slot)
|
||||
assert_true(ops.length() > 0)
|
||||
assert_eq(module_texts(comp), [])
|
||||
comp.shell.set_module_setting(slot, "no-battery", "Show nothing")
|
||||
assert_eq(comp.shell.slot_ops(slot).length(), 0)
|
||||
@shell.set_power_supply_root("/sys/class/power_supply")
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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: "",
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -323,6 +323,11 @@ pub fn publish_power(screen_off : Int, suspend : Int) -> Unit {
|
||||
@hostpl.publish_power(screen_off.reinterpret_as_uint(), suspend.reinterpret_as_uint())
|
||||
}
|
||||
|
||||
///| The battery (the `battery` capability): percent (-1: none), charge-state index, seconds left.
|
||||
pub fn publish_battery(percent : Int, state : Int, secs_left : Int) -> Unit {
|
||||
@hostpl.publish_battery(percent, state.reinterpret_as_uint(), secs_left.reinterpret_as_uint())
|
||||
}
|
||||
|
||||
///| Something a module asked the host to do during a call.
|
||||
pub(all) enum HostRequest {
|
||||
Launch(String)
|
||||
|
||||
@@ -741,6 +741,14 @@ pub fn publish_power(screen_off : Int, suspend : Int) -> Unit {
|
||||
c_host_set_int(6, suspend)
|
||||
}
|
||||
|
||||
///| Publish the battery (the `battery` capability): percent (-1: none), charge-state index,
|
||||
/// seconds left (0: unknown).
|
||||
pub fn publish_battery(percent : Int, state : Int, secs_left : Int) -> Unit {
|
||||
c_host_set_int(7, percent)
|
||||
c_host_set_int(8, state)
|
||||
c_host_set_int(9, secs_left)
|
||||
}
|
||||
|
||||
///| Something a module asked the host to do during a call.
|
||||
pub(all) enum HostRequest {
|
||||
Launch(String)
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
#include <wasm.h>
|
||||
#include "moonbit.h"
|
||||
|
||||
#define MAX_INST 512
|
||||
#define MAX_INST 2048
|
||||
enum { EX_INFO, EX_RENDER, EX_ONEVENT, EX_POPUP, EX_POST_INFO, EX_POST_RENDER, EX_POST_POPUP, EX_REALLOC,
|
||||
EX_CFG_ITEMS, EX_POST_CFG_ITEMS, EX_SET_CFG, EX_N };
|
||||
static const char *ex_names[EX_N] = {
|
||||
@@ -56,7 +56,8 @@ enum {
|
||||
K_SESSION_SETTINGS, K_SESSION_IS_ON, K_SESSION_SET,
|
||||
K_APP_ICON,
|
||||
K_SHOT_TAKE, K_SHOT_RECORD, K_SHOT_STOP, K_SHOT_IS_REC, K_SHOT_PTR, K_SHOT_SET_PTR,
|
||||
K_PW_SCREEN, K_PW_SET_SCREEN, K_PW_SUSP, K_PW_SET_SUSP, K_PW_SUSPEND, K_PW_OFF, K_PW_REBOOT
|
||||
K_PW_SCREEN, K_PW_SET_SCREEN, K_PW_SUSP, K_PW_SET_SUSP, K_PW_SUSPEND, K_PW_OFF, K_PW_REBOOT,
|
||||
K_BAT_READ
|
||||
};
|
||||
typedef struct Env { Inst *inst; int kind; } Env;
|
||||
|
||||
@@ -65,9 +66,10 @@ typedef struct Env { Inst *inst; int kind; } Env;
|
||||
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS, T_N };
|
||||
typedef struct { uint8_t *data; size_t len; } Blob;
|
||||
static Blob tables[T_N];
|
||||
static int32_t host_ints[8]; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
|
||||
static int32_t host_ints[12] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
|
||||
4 screenshot state (bit 0 recording, bit 1 pointer in recordings),
|
||||
5 screen-off minutes, 6 suspend minutes (0: never) */
|
||||
5 screen-off minutes, 6 suspend minutes (0: never),
|
||||
7 battery percent (-1: none), 8 battery charge-state, 9 battery seconds left */
|
||||
|
||||
/* ---- requests a guest made of the host (launch, focus, ...) ; drained by the shell after each call ---- */
|
||||
typedef struct { int kind; int32_t n; char *s; } Req;
|
||||
@@ -364,6 +366,16 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_
|
||||
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(h);
|
||||
break;
|
||||
}
|
||||
case K_BAT_READ: {
|
||||
/* battery.status: percent s32 @0, charge-state u8 @4, secs-left u32 @8 */
|
||||
uint8_t st[12] = {0};
|
||||
int32_t state = host_ints[8] >= 0 && host_ints[8] <= 4 ? host_ints[8] : 0;
|
||||
memcpy(st, &host_ints[7], 4);
|
||||
st[4] = (uint8_t)state;
|
||||
memcpy(st + 8, &host_ints[9], 4);
|
||||
if (args->size >= 1) mem_write(in, a0, st, 12);
|
||||
break;
|
||||
}
|
||||
case K_SYSTEM_READ:
|
||||
if (args->size >= 1) mem_write(in, a0, g_system, 64);
|
||||
break;
|
||||
@@ -473,6 +485,7 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
|
||||
if (!strcmp(iface, "windows") && !strcmp(fn, "all")) return K_WIN_ALL;
|
||||
if (!strcmp(iface, "windows") && !strcmp(fn, "focus")) return K_WIN_FOCUS_ID;
|
||||
if (!strcmp(iface, "system") && !strcmp(fn, "read")) return K_SYSTEM_READ;
|
||||
if (!strcmp(iface, "battery") && !strcmp(fn, "read")) return K_BAT_READ;
|
||||
if (!strcmp(iface, "icons") && !strcmp(fn, "app-icon")) return K_APP_ICON;
|
||||
if (!strcmp(iface, "session") && !strcmp(fn, "logout")) return K_LOGOUT;
|
||||
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "wallpapers")) return K_WALLPAPERS;
|
||||
@@ -753,7 +766,7 @@ void mp_host_set_table(int32_t which, moonbit_bytes_t data) {
|
||||
|
||||
MOONBIT_FFI_EXPORT
|
||||
void mp_host_set_int(int32_t which, int32_t v) {
|
||||
if (which >= 0 && which < 8) host_ints[which] = v;
|
||||
if (which >= 0 && which < 12) host_ints[which] = v;
|
||||
}
|
||||
|
||||
/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */
|
||||
|
||||
Reference in new issue
Block a user