Add backlight control to the shell and regenerate WIT bindings
CI / test (push) Canceled after 0s

- Add compositor/shell/backlight.mbt for backlight control in the shell
- Update wit/capabilities.wit and wit/host/plasmoids.wit, then regenerate the component and interface ffi.mbt bindings (mostly export reordering)
- Add world/launcher-widget/README.md
This commit is contained in:
nandi committed 2026-11-28 02:16:07 -08:00
1 parent 2e00009c79
commit 74235cb0ca
84 files changed
+1525 -864

No files matched your search

+6
View File
@@ -216,6 +216,12 @@ fn main {
for ev in k.take_input() {
comp.handle_input(ev, now_ms)
}
match comp.power_tick(@sys.monotonic_ms()) {
ScreenOff => k.set_power(false)
ScreenOn => k.set_power(true)
Suspend => comp.system_power(0)
NoChange => ()
}
match comp.take_pending_rotation() {
Some(rot) => {
let (nw, nh) = k.set_rotation(rot)
+23
View File
@@ -151,6 +151,7 @@ pub(all) struct ChandraCompositor {
/// idle, and whether this idle spell already suspended.
mut last_input_ms : UInt64
mut screen_off : Bool
mut manual_screen_off : Bool
mut idle_suspended : Bool
mut output_w : Int
mut output_h : Int
@@ -384,6 +385,7 @@ pub fn ChandraCompositor::new(
login_session: false,
last_input_ms: @sys.monotonic_ms(),
screen_off: false,
manual_screen_off: false,
idle_suspended: false,
output_w,
output_h,
@@ -2071,6 +2073,27 @@ fn ChandraCompositor::handle_input_inner(
ev : @nested.InputEvent,
time_ms : UInt,
) -> Unit {
match ev {
Key(116U, pressed) => {
if pressed {
if self.screen_off || self.manual_screen_off {
self.manual_screen_off = false
self.note_activity(@sys.monotonic_ms())
} else {
self.manual_screen_off = true
}
}
return
}
_ => ()
}
if self.manual_screen_off {
return
}
if self.screen_off {
self.note_activity(@sys.monotonic_ms())
return
}
self.note_activity(@sys.monotonic_ms())
match ev {
Modifiers(dep, lat, lock, group) => {
+60
View File
@@ -214,6 +214,8 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
"windows each window: frame, layout, box, shadow, size limits; and what is under the pointer",
"screenshot [PATH] save a full-screen PNG directly (without opening the editor)",
"rotate [cw|ccw|flip|0|90|180|270|status] rotate or flip the display",
"screen [on|off|toggle|status] blank or wake the display",
"brightness [PCT|status] read or set display backlight percent (5..100)",
"auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " +
@polkit.demo_modes.join(", "),
"auth-status the password dialog's agent: running, registered, or why not",
@@ -398,6 +400,64 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
_ => (["error usage: rotate [cw|ccw|flip|0|90|180|270|status]"], false)
}
}
"screen" => {
let arg = if words.length() >= 2 { words[1] } else { "status" }
if words.length() > 2 {
return (["error usage: screen [on|off|toggle|status]"], false)
}
match arg {
"status" => (["ok " + (if self.screen_off || self.manual_screen_off { "off" } else { "on" })], true)
"off" => {
self.set_manual_screen_off(true)
(["ok off"], true)
}
"on" => {
self.set_manual_screen_off(false)
(["ok on"], true)
}
"toggle" => {
let next_off = !(self.screen_off || self.manual_screen_off)
self.set_manual_screen_off(next_off)
(["ok " + (if next_off { "off" } else { "on" })], true)
}
_ => (["error usage: screen [on|off|toggle|status]"], false)
}
}
"brightness" => {
let arg = if words.length() >= 2 { words[1] } else { "status" }
if words.length() > 2 {
return (["error usage: brightness [PCT|status]"], false)
}
if arg == "status" {
let cur = @shell.read_backlight_percent()
if cur < 0 {
(["error no backlight"], false)
} else {
(["ok " + cur.to_string()], true)
}
} else {
let mut val = 0
let mut valid = arg.length() > 0
for ch in arg {
let c = ch.to_int()
if c >= 48 && c <= 57 {
val = val * 10 + (c - 48)
} else {
valid = false
break
}
}
if !valid {
return (["error usage: brightness [PCT|status]"], false)
}
let next = self.shell.set_brightness(val)
if next < 0 {
(["error no backlight"], false)
} else {
(["ok " + next.to_string()], true)
}
}
}
other => (["error unknown command '" + other + "' (try: help)"], false)
}
}
+59 -1
View File
@@ -1739,7 +1739,7 @@ test "the settings module's Power tab steps the timeouts and confirms power off"
// Rows of 28 below the tab bar (40): [Battery heading, battery,] When idle, screen off,
// suspend, Now, Suspend, Restart, Power off.
let n = (pr.h - 40 - 6) / 28
assert_true(n == 7 || n == 9)
assert_true(n == 7 || n == 9 || n == 11)
let first = n - 7
let row_y = fn(i : Int) { pr.y + 40 + (first + i) * 28 + 13 }
assert_eq(comp.shell.screen_off_min, 10)
@@ -1775,3 +1775,61 @@ test "power timeouts are saved to state.edn and restored" {
assert_false(read_state_edn().contains(":power"))
}
}
///|
test "power key toggles manual screen off and wakes without leaking touches" {
let comp = new_comp("powerbtn")
comp.note_activity(1000UL)
assert_eq(comp.power_tick(1000UL), NoChange)
// Pressing KEY_POWER (116) turns screen off; releasing it leaves it off.
comp.handle_input(@nested.InputEvent::Key(116U, true), 10U)
comp.handle_input(@nested.InputEvent::Key(116U, false), 20U)
assert_eq(comp.power_tick(1050UL), ScreenOff)
assert_eq(comp.power_tick(1060UL), NoChange)
// Stray touch/pointer activity while manually blanked does not wake the screen.
comp.handle_input(@nested.InputEvent::PointerMove(50.0, 50.0), 30U)
assert_eq(comp.power_tick(1100UL), NoChange)
// Second KEY_POWER press wakes the screen and keeps it awake after release.
comp.handle_input(@nested.InputEvent::Key(116U, true), 40U)
comp.handle_input(@nested.InputEvent::Key(116U, false), 50U)
assert_eq(comp.power_tick(1200UL), ScreenOn)
assert_eq(comp.power_tick(1300UL), NoChange)
// Control socket screen commands work symmetrically.
let (r1, ok1) = comp.control_command("screen off")
assert_true(ok1 && r1 == ["ok off"])
assert_eq(comp.power_tick(1400UL), ScreenOff)
let (r2, ok2) = comp.control_command("screen on")
assert_true(ok2 && r2 == ["ok on"])
assert_eq(comp.power_tick(1500UL), ScreenOn)
}
///|
test "settings Power tab displays and adjusts backlight brightness" {
let root = "/tmp/chandra-test-backlight"
let dev = root + "/ae94000.dsi.0"
ignore(@sys.mkdir_p(dev))
assert_eq(@sys.write_file_bytes(dev + "/max_brightness", @utf8.encode("1000\n")), 0)
assert_eq(@sys.write_file_bytes(dev + "/brightness", @utf8.encode("500\n")), 0)
@shell.set_backlight_root(root)
let comp = new_comp("brightness")
comp.shell.refresh_brightness()
let slot = comp.shell.slot_of("session-settings")
assert_true(comp.shell.open_settings(Power))
ignore(comp.compose_frame())
let texts = comp.shell.slot_popup_texts(slot).map(t => t.0)
assert_true(texts.contains("Brightness"))
assert_true(texts.contains("50%"))
let pr = comp.shell.slot_popup_rect(slot)
let (_, br) = comp.control_command("brightness 80")
assert_true(br)
ignore(comp.compose_frame())
assert_true(comp.shell.slot_popup_texts(slot).map(t => t.0).contains("80%"))
assert_eq(@shell.read_backlight_percent(), 80)
// Clicking the '-' button (x inside [margin..47]) steps 80 -> 70%.
let n = (pr.h - 40 - 6) / 28
let bright_row = n - 8
assert_true(bright_row >= 1)
click_at(comp, pr.x + 25, pr.y + 40 + bright_row * 28 + 13, 10U)
assert_eq(@shell.read_backlight_percent(), 70)
@shell.set_backlight_root("/sys/class/backlight")
}
+19 -1
View File
@@ -21,8 +21,26 @@ pub fn ChandraCompositor::note_activity(self : ChandraCompositor, now_ms : UInt6
self.last_input_ms = now_ms
}
///| Check the idle timeouts at monotonic time `now_ms`.
///| Turn the screen off or back on from a manual action (power button or `chandra-ctl screen`).
pub fn ChandraCompositor::set_manual_screen_off(
self : ChandraCompositor,
off : Bool,
) -> Unit {
self.manual_screen_off = off
if !off {
self.note_activity(@sys.monotonic_ms())
}
}
///| Check the idle timeouts and manual screen blank state at monotonic time `now_ms`.
pub fn ChandraCompositor::power_tick(self : ChandraCompositor, now_ms : UInt64) -> PowerChange {
if self.manual_screen_off {
if !self.screen_off {
self.screen_off = true
return ScreenOff
}
return NoChange
}
let idle = if now_ms > self.last_input_ms { now_ms - self.last_input_ms } else { 0UL }
let minutes = fn(m : Int) { m.to_uint64() * 60000UL }
let off = self.shell.screen_off_min
+2
View File
@@ -538,6 +538,7 @@ MOONBIT_FFI_EXPORT
void mp_kms_set_power(int32_t on) {
if (!g_seat || (on ? !g_blank : g_blank)) return;
g_blank = !on;
if (!on) touch_cancel();
if (!g_seat_enabled || g_suspended) return; /* applied when the VT comes back */
if (on) {
set_dpms(1);
@@ -545,6 +546,7 @@ void mp_kms_set_power(int32_t on) {
} else {
set_dpms(0);
}
fprintf(stderr, "kms: screen %s\n", on ? "on" : "off");
}
+151
View File
@@ -0,0 +1,151 @@
///| Linux backlight provider for the `power` capability (sysfs read + logind SetBrightness fallback).
let backlight_root : Ref[String] = { val: "/sys/class/backlight" }
let backlight_sample_sec : Ref[Int] = { val: -1 }
let backlight_cached : Ref[Int] = { val: -1 }
///| Override /sys/class/backlight root for unit tests.
pub fn set_backlight_root(dir : String) -> Unit {
backlight_root.val = dir
backlight_sample_sec.val = -1
backlight_cached.val = -1
}
let backlight_names : Array[String] = [
"ae94000.dsi.0",
"intel_backlight",
"amdgpu_bl0",
"amdgpu_bl1",
"acpi_video0",
"acpi_video1",
"nvidia_0",
"nvidia_wmi_ec_backlight",
"apple-panel-bl",
"gmux_backlight",
"backlight",
"panel_backlight",
"pwm-backlight",
"qcom-wled",
"soc:backlight",
"rpi_backlight",
]
priv struct BacklightDev {
name : String
path : String
cur : Int64
max : Int64
}
fn safe_backlight_name(s : String) -> Bool {
if s.length() == 0 {
return false
}
for ch in s {
let ok = (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '.' ||
ch == '_' ||
ch == ':' ||
ch == '-'
if !ok {
return false
}
}
!s.has_prefix(".")
}
fn try_backlight(root : String, name : String) -> BacklightDev? {
if !safe_backlight_name(name) {
return None
}
let path = root + "/" + name
let max = sysfs_num(path + "/max_brightness")
if max <= 0L {
return None
}
let cur = sysfs_num(path + "/brightness")
if cur < 0L {
return None
}
Some({ name, path, cur, max })
}
fn find_backlight(root : String) -> BacklightDev? {
let override_name = @sys.getenv("CHANDRA_BACKLIGHT").trim(chars=" \n\r\t").to_string()
match try_backlight(root, override_name) {
Some(dev) => return Some(dev)
None => ()
}
for name in backlight_names {
match try_backlight(root, name) {
Some(dev) => return Some(dev)
None => ()
}
}
None
}
fn clamp_pct(pct : Int, lo : Int, hi : Int) -> Int {
if pct < lo { lo } else if pct > hi { hi } else { pct }
}
///| Read backlight brightness percentage in 0..100, or -1 if no backlight exists.
pub fn read_backlight_percent(root? : String = backlight_root.val) -> Int {
match find_backlight(root) {
None => -1
Some(dev) => clamp_pct(((dev.cur * 100L + dev.max / 2L) / dev.max).to_int(), 0, 100)
}
}
///| Sample backlight at most once per wall-clock second.
pub fn read_backlight_polled() -> Int {
let now = wall_secs()
if now != backlight_sample_sec.val {
backlight_sample_sec.val = now
backlight_cached.val = read_backlight_percent()
}
backlight_cached.val
}
///| Write display backlight percentage (clamped to 5..100) via sysfs or systemd-logind SetBrightness.
pub fn write_backlight_percent(
pct : Int,
display : String,
root? : String = backlight_root.val,
) -> Int {
match find_backlight(root) {
None => -1
Some(dev) => {
let clamped = clamp_pct(pct, 5, 100)
let raw0 = (clamped.to_int64() * dev.max + 50L) / 100L
let raw = if raw0 < 1L { 1L } else if raw0 > dev.max { dev.max } else { raw0 }
let data = @utf8.encode(raw.to_string() + "\n")
if @sys.write_file_bytes(dev.path + "/brightness", data) < 0 {
let sid = @sys.getenv("XDG_SESSION_ID").trim(chars=" \n\r\t").to_string()
let sess = if sid.length() > 0 && safe_backlight_name(sid) {
"/org/freedesktop/login1/session/" + sid
} else {
"/org/freedesktop/login1/session/auto"
}
ignore(
@sys.spawn(
"busctl call org.freedesktop.login1 " +
sess +
" org.freedesktop.login1.Session SetBrightness ssu backlight " +
dev.name +
" " +
raw.to_string(),
display,
),
)
}
backlight_sample_sec.val = wall_secs()
backlight_cached.val = clamped
clamped
}
}
}
+2
View File
@@ -303,6 +303,7 @@ pub(all) struct DesktopShell {
/// (0: never). Saved in state.edn as :power {:screen-off 10 :suspend 0} when not the defaults.
mut screen_off_min : Int
mut suspend_min : Int
mut brightness_pct : Int
/// Keyboard shortcuts (shortcuts.mbt); saved in state.edn as :shortcuts when not the defaults.
shortcuts : Shortcuts
/// The shortcut waiting for its new combo from the Shortcuts tab (-1: none).
@@ -481,6 +482,7 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
window_style: @scene.WindowStyle::Flat,
screen_off_min: default_screen_off_min,
suspend_min: default_suspend_min,
brightness_pct: -1,
shortcuts: Shortcuts::defaults(),
shortcut_capture: -1,
xdg_dirs: XdgDirs::from_env(),
+17
View File
@@ -782,6 +782,7 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
}
if self.any_cap("power") {
@wasm.publish_power(self.screen_off_min, self.suspend_min)
self.refresh_brightness()
}
if self.any_cap("shortcuts") {
self.publish_shortcuts()
@@ -915,6 +916,21 @@ pub fn DesktopShell::set_power_timeouts(self : DesktopShell, screen_off : Int, s
self.save_state()
}
///| Refresh cached backlight brightness (0..100, or -1 if absent) and publish to modules.
pub fn DesktopShell::refresh_brightness(self : DesktopShell) -> Unit {
let pct = read_backlight_polled()
self.brightness_pct = pct
@wasm.publish_brightness(pct)
}
///| Set display backlight percentage (5..100) and publish the updated value.
pub fn DesktopShell::set_brightness(self : DesktopShell, pct : Int) -> Int {
let res = write_backlight_percent(pct, self.display)
self.brightness_pct = res
@wasm.publish_brightness(res)
res
}
///| Start the catalog app `id` (a desktop file id) and remember it as the latest launch.
fn DesktopShell::launch_catalog_app(self : DesktopShell, id : String) -> Unit {
match self.command_for(id) {
@@ -950,6 +966,7 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit {
Some(Screenshot(code)) => self.actions.push(Screenshot(code))
Some(SetScreenOff(m)) => self.set_power_timeouts(m, self.suspend_min)
Some(SetSuspendAfter(m)) => self.set_power_timeouts(self.screen_off_min, m)
Some(SetBrightness(p)) => ignore(self.set_brightness(p))
Some(Shortcut(code)) => self.shortcut_request(code)
Some(DefaultApp(code)) => self.default_app_request(code)
Some(FaceUnlock(code)) => self.face.request(code)
+7
View File
@@ -422,6 +422,11 @@ pub fn publish_power(screen_off : Int, suspend : Int) -> Unit {
@hostpl.publish_power(screen_off.reinterpret_as_uint(), suspend.reinterpret_as_uint())
}
///| Display backlight brightness percentage (0..100, or -1 if none).
pub fn publish_brightness(percent : Int) -> Unit {
@hostpl.publish_brightness(percent)
}
///| 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())
@@ -448,6 +453,7 @@ pub(all) enum HostRequest {
/// 1 power off, 2 restart).
SetScreenOff(Int)
SetSuspendAfter(Int)
SetBrightness(Int)
PowerAction(Int)
/// A network module's action (0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode
/// off/on, 6 connect, 7 forget), with the network name and password where it needs them.
@@ -487,6 +493,7 @@ pub fn next_request() -> HostRequest? {
Some(Screenshot(code)) => Some(Screenshot(code))
Some(SetScreenOff(m)) => Some(SetScreenOff(m))
Some(SetSuspendAfter(m)) => Some(SetSuspendAfter(m))
Some(SetBrightness(p)) => Some(SetBrightness(p))
Some(PowerAction(a)) => Some(PowerAction(a))
Some(Network(r)) => Some(Network(r.action, r.ssid, r.password))
Some(Shortcut(code)) => Some(Shortcut(code))
+7
View File
@@ -817,6 +817,11 @@ pub fn publish_power(screen_off : Int, suspend : Int) -> Unit {
c_host_set_int(6, suspend)
}
///| Publish current display backlight brightness percentage (0..100, or -1 if none).
pub fn publish_brightness(percent : Int) -> Unit {
c_host_set_int(10, percent)
}
///| 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 {
@@ -846,6 +851,7 @@ pub(all) enum HostRequest {
/// 1 power off, 2 restart).
SetScreenOff(Int)
SetSuspendAfter(Int)
SetBrightness(Int)
PowerAction(Int)
/// A network module's action (0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode
/// off/on, 6 connect, 7 forget), with the network name and password where it needs them.
@@ -906,6 +912,7 @@ pub fn next_request() -> HostRequest? {
}
18 => Some(Shortcut(c_host_req_int()))
19 => Some(DefaultApp(c_host_req_int()))
20 => Some(SetBrightness(c_host_req_int()))
40 => Some(SetDesktop(c_host_req_int()))
44 => Some(FaceUnlock(c_host_req_int()))
45 => {
+10 -3
View File
@@ -60,7 +60,7 @@ 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_BRIGHTNESS, K_PW_SET_BRIGHTNESS, K_PW_SUSPEND, K_PW_OFF, K_PW_REBOOT,
K_BAT_READ,
K_NET_STATUS, K_NET_LIST, K_NET_SCAN, K_NET_CONNECT, K_NET_DISCONNECT, K_NET_FORGET, K_NET_SET_WIFI,
K_NET_SET_AIRPLANE,
@@ -81,10 +81,11 @@ enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SES
T_GL_STATUS = 26, T_GL_GAMES = 27, T_GL_MODES = 28, T_N = 32 };
typedef struct { uint8_t *data; size_t len; } Blob;
static Blob tables[T_N];
static int32_t host_ints[24] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
static int32_t host_ints[24] = {[7] = -1, [10] = -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),
7 battery percent (-1: none), 8 battery charge-state, 9 battery seconds left */
7 battery percent (-1: none), 8 battery charge-state, 9 battery seconds left,
10 backlight brightness percent (-1: none) */
/* ---- 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;
@@ -436,6 +437,10 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_
break;
case K_PW_SET_SCREEN: push_req(13, a0, NULL); break;
case K_PW_SET_SUSP: push_req(14, a0, NULL); break;
case K_PW_BRIGHTNESS:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[10]);
break;
case K_PW_SET_BRIGHTNESS: push_req(20, a0, NULL); break;
case K_PW_SUSPEND: push_req(15, 0, NULL); break; /* 15: power action n (0 suspend, 1 off, 2 restart) */
case K_PW_OFF: push_req(15, 1, NULL); break;
case K_PW_REBOOT: push_req(15, 2, NULL); break;
@@ -665,6 +670,8 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
if (!strcmp(iface, "power") && !strcmp(fn, "set-screen-off-minutes")) return K_PW_SET_SCREEN;
if (!strcmp(iface, "power") && !strcmp(fn, "suspend-minutes")) return K_PW_SUSP;
if (!strcmp(iface, "power") && !strcmp(fn, "set-suspend-minutes")) return K_PW_SET_SUSP;
if (!strcmp(iface, "power") && !strcmp(fn, "brightness")) return K_PW_BRIGHTNESS;
if (!strcmp(iface, "power") && !strcmp(fn, "set-brightness")) return K_PW_SET_BRIGHTNESS;
if (!strcmp(iface, "power") && !strcmp(fn, "suspend")) return K_PW_SUSPEND;
if (!strcmp(iface, "power") && !strcmp(fn, "power-off")) return K_PW_OFF;
if (!strcmp(iface, "power") && !strcmp(fn, "reboot")) return K_PW_REBOOT;