From 2636373a4fbe9880c39770dc4e814e3649ebbfa8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:37:21 +0000 Subject: [PATCH] Power settings: screen off and suspend when idle, battery, suspend / restart / power off - Settings gets a Power tab (fourth; key 4 or SettingsTab::Power): the battery when there is one (the system capability), "Turn screen off after" (Never, 1 min ... 1 hour; default 10 min) and "Suspend after" (Never, 5 min ... 2 hours; default never), a click stepping through the choices, and Suspend / Restart / Power off now. Restart and Power off need a second click. - New `power` capability (screen-off-minutes, suspend-minutes and setters, suspend, power-off, reboot), served by the wasmer stub (host ints 5/6, requests 13-15) and host-wasm (publish-power, set-screen-off / set-suspend-after / power-action). - The timeouts are kept in state.edn as :power {:screen-off N :suspend N} when not the defaults. - Login session only (compositor/host/power.mbt): input restarts the idle time; power_tick, run every pass of the main loop (an idle loop still wakes about once a second), turns the screen off through DPMS and back on at the next input, and suspends once per idle spell. Monotonic time stops in suspend, so a resumed machine waits for input and a new idle spell. Suspend, restart and power off run `systemctl || loginctl ` (logind, so its inhibitors and polkit rules apply); a nested window only shows a notice. - Display: chandra:host/display set-power and Kms::set_power; the shared C shim sets the connector's legacy DPMS property, shows no frames while off (frame_ready false, so the idle loop still sleeps), redoes the modeset when turned on, and keeps the screen off across a VT switch. - components/screenshot bindings regenerated (they were stale: the module didn't build). - Tests: idle timer sequence, the Power tab driving the shell (timeouts, two-click power off), the state.edn round trip, a host-wasm test of the tab, and logind commands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DPL5hgxf6exeYrDGcy4WW3 --- .../chandra/desktop/plasmoid/ffi.mbt | 40 ++++++-- .../chandra/desktop/plasmoid/moon.pkg | 2 + .../chandra/desktop/plasmoid/stub.mbt | 94 ++++++++++++++++++- compositor/app/app.mbt | 15 ++- compositor/host/compositor.mbt | 13 +++ compositor/host/input_test.mbt | 75 ++++++++++++++- compositor/host/power.mbt | 84 +++++++++++++++++ compositor/kms/kms_native.mbt | 9 ++ compositor/kms/kms_stub.c | 38 +++++++- compositor/kms/kms_wasm.mbt | 6 ++ compositor/shell/shell.mbt | 8 ++ compositor/shell/state.mbt | 33 ++++++- compositor/shell/widgets.mbt | 29 +++++- compositor/wasm/wasm_host.mbt | 13 +++ compositor/wasm/wasm_native.mbt | 14 +++ compositor/wasm/wasm_stub.c | 24 ++++- host-wasm/src/kms.rs | 6 ++ host-wasm/src/main.rs | 15 +++ host-wasm/src/plasmoid.rs | 64 ++++++++++++- interface/chandra/desktop/power/README.md | 3 + interface/chandra/desktop/power/ffi.mbt | 23 +++++ interface/chandra/desktop/power/moon.pkg | 1 + interface/chandra/desktop/power/top.mbt | 51 ++++++++++ interface/chandra/desktop/system/README.md | 3 + interface/chandra/desktop/system/ffi.mbt | 28 ++++++ interface/chandra/desktop/system/moon.pkg | 1 + interface/chandra/desktop/system/top.mbt | 16 ++++ interface/chandra/host/display/ffi.mbt | 49 +++++----- .../chandra/host/display/native_stub.mbt | 5 + .../chandra/host/display/pkg.generated.mbti | 2 + interface/chandra/host/display/top.mbt | 8 ++ interface/chandra/host/plasmoids/ffi.mbt | 51 +++++----- .../chandra/host/plasmoids/native_stub.mbt | 5 + .../chandra/host/plasmoids/pkg.generated.mbti | 5 + interface/chandra/host/plasmoids/top.mbt | 22 +++++ wit/capabilities.wit | 16 ++++ wit/host/display.wit | 3 + wit/host/plasmoids.wit | 7 ++ wit/worlds.wit | 8 +- world/session-settings-widget/README.md | 5 +- 40 files changed, 817 insertions(+), 77 deletions(-) create mode 100644 compositor/host/power.mbt create mode 100644 interface/chandra/desktop/power/README.md create mode 100644 interface/chandra/desktop/power/ffi.mbt create mode 100644 interface/chandra/desktop/power/moon.pkg create mode 100644 interface/chandra/desktop/power/top.mbt create mode 100644 interface/chandra/desktop/system/README.md create mode 100644 interface/chandra/desktop/system/ffi.mbt create mode 100644 interface/chandra/desktop/system/moon.pkg create mode 100644 interface/chandra/desktop/system/top.mbt diff --git a/components/screenshot/gen/interface/chandra/desktop/plasmoid/ffi.mbt b/components/screenshot/gen/interface/chandra/desktop/plasmoid/ffi.mbt index 1fa7d88..c897e9b 100644 --- a/components/screenshot/gen/interface/chandra/desktop/plasmoid/ffi.mbt +++ b/components/screenshot/gen/interface/chandra/desktop/plasmoid/ffi.mbt @@ -130,6 +130,16 @@ pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int { PopClip => { mbt_ffi_store8((iter_base) + 0, (6)) + () + } + Image(payload6) => { + mbt_ffi_store8((iter_base) + 0, (7)) + mbt_ffi_store32((iter_base) + 4, ((payload6).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload6).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload6).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload6).rect).h).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 20, ((payload6).image).reinterpret_as_int()) + () } } @@ -160,6 +170,7 @@ pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit { } 5 => () 6 => () + 7 => () _ => panic() } @@ -278,6 +289,16 @@ pub fn wasmExportPopup() -> Int { PopClip => { mbt_ffi_store8((iter_base) + 0, (6)) + () + } + Image(payload8) => { + mbt_ffi_store8((iter_base) + 0, (7)) + mbt_ffi_store32((iter_base) + 4, ((payload8).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload8).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload8).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload8).rect).h).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 20, ((payload8).image).reinterpret_as_int()) + () } } @@ -316,6 +337,7 @@ pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit { } 5 => () 6 => () + 7 => () _ => panic() } @@ -368,6 +390,11 @@ pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { } +///| +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) + ///| extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = #|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) @@ -379,10 +406,6 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = #| local.tee 1 i32.const 0 call $moonbit.init_array8 #| local.get 1) -///| -extern "wasm" fn mbt_ffi_free(position : Int) = -#|(func (param i32) local.get 0 call $moonbit.decref) - ///| extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = #|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) @@ -398,12 +421,11 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #| local.get 1 call $moonbit.init_array16 #| local.get 0) -///| -#owned(str) -extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = -#|(func (param i32) (result i32) local.get 0) - ///| extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = #|(func (param i32) (result i32) local.get 0 i32.load8_u) +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + diff --git a/components/session-settings/gen/interface/chandra/desktop/plasmoid/moon.pkg b/components/session-settings/gen/interface/chandra/desktop/plasmoid/moon.pkg index e82142b..7cbecfd 100644 --- a/components/session-settings/gen/interface/chandra/desktop/plasmoid/moon.pkg +++ b/components/session-settings/gen/interface/chandra/desktop/plasmoid/moon.pkg @@ -4,6 +4,8 @@ import { "chandra/desktop/interface/chandra/desktop/session-settings" @settings, "chandra/desktop/interface/chandra/desktop/wallpaper" @wallpaper, "chandra/desktop/interface/chandra/desktop/modules" @modules, + "chandra/desktop/interface/chandra/desktop/power" @power, + "chandra/desktop/interface/chandra/desktop/system" @system, "chandra/desktop/lib/ui" @ui, } diff --git a/components/session-settings/gen/interface/chandra/desktop/plasmoid/stub.mbt b/components/session-settings/gen/interface/chandra/desktop/plasmoid/stub.mbt index 2127863..bbde113 100644 --- a/components/session-settings/gen/interface/chandra/desktop/plasmoid/stub.mbt +++ b/components/session-settings/gen/interface/chandra/desktop/plasmoid/stub.mbt @@ -8,10 +8,13 @@ /// get their own section here; /// - Panel: the modules in the panel (click to remove), every module found on the search path /// (click to add another instance) and "Browse..." (`modules`). The panel menu's "Modules..." -/// opens this tab. +/// opens this tab; +/// - Power: the battery (`system`, when there is one), how long without input before the screen +/// turns off and before the computer suspends (a click steps through the choices), and Suspend, +/// Restart and Power off now (`power`); Restart and Power off ask for a second click. /// /// Clicking a row acts at once and the popup stays open. Up/Down move the highlight, Left/Right -/// (or 1, 2, 3) switch tabs, Enter or Space acts on the highlighted row, Escape or a click +/// (or 1-4) switch tabs, Enter or Space acts on the highlighted row, Escape or a click /// elsewhere closes. The shell remembers settings and wallpaper in state.edn, the panel in /// panel.edn. @@ -37,7 +40,7 @@ let switch_w : Int = 34 let switch_h : Int = 18 ///| -let tab_names : Array[String] = ["Session", "Desktop", "Panel"] +let tab_names : Array[String] = ["Session", "Desktop", "Panel", "Power"] ///| A popup row. enum Row { @@ -49,6 +52,43 @@ enum Row { /// A module on the search path: path, name and how many instances are loaded. Available(String, String, UInt) Browse + /// A line of text (the battery). + Info(String) + /// A timeout that steps through `choices`: 0 screen off, 1 suspend. + Timeout(Int, String) + /// Suspend (0), power off (1) or restart (2) now. + PowerNow(Int, String) +} + +///| The timeout choices, in minutes (0: never). +let screen_off_choices : Array[Int] = [0, 1, 2, 5, 10, 15, 30, 60] + +///| +let suspend_choices : Array[Int] = [0, 5, 10, 15, 30, 60, 120] + +///| The power action waiting for its confirming second click (-1: none). +let armed : Ref[Int] = { val: -1 } + +///| "Never", "5 min", "1 hour", "2 hours". +fn minutes_label(m : Int) -> String { + if m <= 0 { + "Never" + } else if m % 60 == 0 { + let h = m / 60 + h.to_string() + (if h == 1 { " hour" } else { " hours" }) + } else { + m.to_string() + " min" + } +} + +///| The choice after `cur` in `choices` (wrapping round to the first). +fn next_choice(choices : Array[Int], cur : Int) -> Int { + for c in choices { + if c > cur { + return c + } + } + choices[0] } ///| Whether the popup is open, its tab, and which row is highlighted (-1: none). @@ -77,6 +117,21 @@ fn rows() -> Array[Row] { rs.push(Wallpaper(i, names[i])) } } + 3 => { + let snap = @system.read() + if snap.battery_percent >= 0 { + rs.push(Heading("Battery")) + let state = if snap.charging { " (charging)" } else { "" } + rs.push(Info(snap.battery_percent.to_string() + "%" + state)) + } + rs.push(Heading("When idle")) + rs.push(Timeout(0, "Turn screen off after")) + rs.push(Timeout(1, "Suspend after")) + rs.push(Heading("Now")) + rs.push(PowerNow(0, "Suspend")) + rs.push(PowerNow(2, "Restart")) + rs.push(PowerNow(1, "Power off")) + } _ => { rs.push(Heading("In the panel (click to remove)")) for inst in @modules.loaded() { @@ -94,7 +149,7 @@ fn rows() -> Array[Row] { ///| Whether row `i` of `rs` can be highlighted and acted on (headings can't). fn active(rs : Array[Row], i : Int) -> Bool { - i >= 0 && i < rs.length() && !(rs[i] is Heading(_)) + i >= 0 && i < rs.length() && !(rs[i] is (Heading(_) | Info(_))) } ///| First active row of `rs`, or -1. @@ -138,12 +193,14 @@ fn popup_h(n : Int) -> Int { ///| fn set_tab(i : Int) -> Unit { tab.val = i + armed.val = -1 hover.val = first_active(rows()) } ///| fn close() -> Unit { open_.val = false + armed.val = -1 hover.val = -1 } @@ -152,7 +209,24 @@ fn act(rs : Array[Row], i : Int) -> Unit { if !active(rs, i) { return } + let was_armed = armed.val + armed.val = -1 match rs[i] { + Timeout(0, _) => @power.set_screen_off_minutes(next_choice(screen_off_choices, @power.screen_off_minutes().reinterpret_as_int()).reinterpret_as_uint()) + Timeout(_, _) => @power.set_suspend_minutes(next_choice(suspend_choices, @power.suspend_minutes().reinterpret_as_int()).reinterpret_as_uint()) + PowerNow(0, _) => @power.suspend() + PowerNow(a, _) => + // Restart and power off take a second click on the same row. + if was_armed == a { + if a == 1 { + @power.power_off() + } else { + @power.reboot() + } + } else { + armed.val = a + } + Info(_) => () Setting(k, _) => { let idx = k.reinterpret_as_uint() @settings.set_setting(idx, !@settings.is_on(idx)) @@ -294,6 +368,16 @@ pub fn popup() -> PopupSurface? { } } Browse => ops.push(@ui.text(margin + 10, mid, "Browse...", fs - 1, list_fg, bold=true)) + Info(text) => ops.push(@ui.text(margin + 10, mid, text, fs - 1, p.foreground)) + Timeout(k, label) => { + let m = if k == 0 { @power.screen_off_minutes() } else { @power.suspend_minutes() } + ops.push(@ui.text(margin + 10, mid, label, fs - 1, list_fg)) + ops.push(@ui.text(w - margin - 10, mid, minutes_label(m.reinterpret_as_int()), fs - 1, list_fg, align=RIGHT, bold=true)) + } + PowerNow(a, label) => { + let text = if armed.val == a { "Click again to " + label.to_lower() } else { label } + ops.push(@ui.text(margin + 10, mid, text, fs - 1, list_fg, bold=armed.val == a)) + } } } Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops }) @@ -371,7 +455,7 @@ pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool { } else if k == "ArrowLeft" || k == "Left" { set_tab((tab.val + tab_names.length() - 1) % tab_names.length()) true - } else if k == "1" || k == "2" || k == "3" { + } else if k == "1" || k == "2" || k == "3" || k == "4" { set_tab(k[0].to_int() - '1'.to_int()) true } else { diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index 5ab8edc..428c4ae 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -139,6 +139,7 @@ pub fn run(args : Array[String]) -> Int { Some(comp) => { comp.shell.persist = true // remember which modules are loaded in the panel comp.sync_system_theme = drm // the login session sets apps' dark/light preference + comp.login_session = drm // and power actions (suspend, power off) act on the machine comp.restore_state() // and the layout mode and recent apps from the last session comp.shell.screen_w = width // Screenshots and recordings read the host's framebuffer (it draws the desktop). @@ -203,6 +204,16 @@ pub fn run(args : Array[String]) -> Int { for ev in input { comp.handle_input(ev, now_ms) } + // Idle timeouts (power.mbt): screen off / on, suspend. + match comp.power_tick(@sys.monotonic_ms()) { + ScreenOff => k.set_power(false) + ScreenOn => { + k.set_power(true) + need_present = true + } + Suspend => comp.system_power(0) + NoChange => () + } comp.step() let f1 = @sys.monotonic_ms() k.set_cursor_shape(comp.desired_cursor()) @@ -237,7 +248,9 @@ pub fn run(args : Array[String]) -> Int { comp.prof_raster_ms = 0UL } } - if input.length() == 0 && !changed && !need_present && !comp.has_timed_work() { + // With the screen off nothing can be shown, so a waiting frame doesn't keep the loop busy. + let waiting = need_present && !comp.screen_off + if input.length() == 0 && !changed && !waiting && !comp.has_timed_work() { // Idle: sleep until a client, the seat or the clock has something. let fds = comp.server.wait_fds() fds.append(k.wait_fds()) diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 9908aaa..768d822 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -44,6 +44,13 @@ pub(all) struct ChandraCompositor { /// Also set the system-wide dark/light preference for apps (system_theme.mbt). The login /// session turns it on; nested windows and tests leave it off. mut sync_system_theme : Bool + /// Running as the login session (--drm): power actions act on the machine (power.mbt). + mut login_session : Bool + /// Power (power.mbt): when input last came (monotonic ms), whether the screen is off for being + /// idle, and whether this idle spell already suspended. + mut last_input_ms : UInt64 + mut screen_off : Bool + mut idle_suspended : Bool mut output_w : Int mut output_h : Int mut work_area : @wm.Rect @@ -149,6 +156,10 @@ pub fn ChandraCompositor::new( theme, dark_theme: theme, sync_system_theme: false, + login_session: false, + last_input_ms: @sys.monotonic_ms(), + screen_off: false, + idle_suspended: false, output_w, output_h, work_area, @@ -1122,6 +1133,7 @@ fn ChandraCompositor::run_shell_actions(self : ChandraCompositor) -> Unit { @shell.ShellAction::Logout => self.quit_requested = true @shell.ShellAction::ThemeChanged => self.apply_theme() @shell.ShellAction::Screenshot(code) => self.screenshot_request(code) + @shell.ShellAction::SystemPower(a) => self.system_power(a) @shell.ShellAction::SetLayout(m) => match m { 0 => self.set_layout_mode(@wm.LayoutMode::Tiling) @@ -1204,6 +1216,7 @@ pub fn ChandraCompositor::handle_input( ev : @nested.InputEvent, time_ms : UInt, ) -> Unit { + self.note_activity(@sys.monotonic_ms()) if self.screenshot_input(ev, time_ms) { return } diff --git a/compositor/host/input_test.mbt b/compositor/host/input_test.mbt index cd1d27b..2b1d2d5 100644 --- a/compositor/host/input_test.mbt +++ b/compositor/host/input_test.mbt @@ -1221,10 +1221,10 @@ test "the settings module lists the wallpapers and switches the desktop to the o assert_eq(comp.shell.slot_of("wallpaper"), "") // the standalone chooser is gone assert_eq(comp.shell.wallpaper_sel, 0) // A click opens the popup on its Session tab; the Desktop tab (the second of three 96 px - // tabs) lists the wallpapers below a heading. Nothing changes yet. + // tabs; four 72 px tabs) lists the wallpapers below a heading. Nothing changes yet. click_module(comp, "session-settings", 1U) let p0 = comp.shell.slot_popup_rect(slot) - click_at(comp, p0.x + 6 + 96 + 48, p0.y + 6 + 14, 3U) + click_at(comp, p0.x + 6 + 72 + 36, p0.y + 6 + 14, 3U) let pr = comp.shell.slot_popup_rect(slot) assert_true(pr.h >= 40 + 6 * 28) // heading and one row per wallpaper below the tab bar assert_eq(comp.shell.wallpaper_sel, 0) @@ -1443,3 +1443,74 @@ test "open_settings opens the settings module on the tab asked for" { ignore(comp.compose_frame()) assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 3 * 28 + 6) // the three settings } + +///| +test "idle timeouts turn the screen off, suspend once per idle spell, and input wakes the screen" { + let comp = new_comp("powertick") + comp.shell.screen_off_min = 1 + comp.shell.suspend_min = 2 + comp.note_activity(0UL) + assert_eq(comp.power_tick(30000UL), NoChange) + assert_eq(comp.power_tick(60000UL), ScreenOff) + assert_eq(comp.power_tick(61000UL), NoChange) + assert_eq(comp.power_tick(120000UL), Suspend) + assert_eq(comp.power_tick(200000UL), NoChange) // not again in the same idle spell + comp.note_activity(210000UL) + assert_eq(comp.power_tick(210500UL), ScreenOn) + assert_eq(comp.power_tick(250000UL), NoChange) + // A new idle spell suspends again; 0 means never. + assert_eq(comp.power_tick(270000UL), ScreenOff) + assert_eq(comp.power_tick(330000UL), Suspend) + comp.shell.screen_off_min = 0 + comp.shell.suspend_min = 0 + comp.note_activity(400000UL) + assert_eq(comp.power_tick(400100UL), ScreenOn) + assert_eq(comp.power_tick(99999999UL), NoChange) +} + +///| +test "the settings module's Power tab steps the timeouts and confirms power off" { + let comp = new_comp("powertab") + let slot = comp.shell.slot_of("session-settings") + assert_true(comp.shell.open_settings(Power)) + ignore(comp.compose_frame()) + let pr = comp.shell.slot_popup_rect(slot) + // 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) + 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) + click_at(comp, pr.x + 40, row_y(1), 5U) // screen off: 10 -> 15 min + assert_eq(comp.shell.screen_off_min, 15) + click_at(comp, pr.x + 40, row_y(2), 10U) // suspend: never -> 5 min + assert_eq(comp.shell.suspend_min, 5) + // Power off asks for a second click; outside the login session it only says so. + comp.shell.notice = "" + click_at(comp, pr.x + 40, row_y(6), 15U) + assert_eq(comp.shell.notice, "") + click_at(comp, pr.x + 40, row_y(6), 20U) + assert_true(comp.shell.notice.contains("login session")) +} + +///| +test "power timeouts are saved to state.edn and restored" { + if @sys.getenv("CHANDRA_TEST_CONFIG") == "1" { + write_state_edn("{:note \"keep\"}\n") + let a = new_comp("pow-a") + a.shell.persist = true + a.restore_state() + assert_eq((a.shell.screen_off_min, a.shell.suspend_min), (10, 0)) // the defaults + a.shell.set_power_timeouts(5, 30) + let text = read_state_edn() + assert_true(text.contains(":power {:screen-off 5 :suspend 30}")) + assert_true(text.contains(":note \"keep\"")) + let b = new_comp("pow-b") + b.shell.persist = true + b.restore_state() + assert_eq((b.shell.screen_off_min, b.shell.suspend_min), (5, 30)) + b.shell.set_power_timeouts(10, 0) + assert_false(read_state_edn().contains(":power")) + } +} diff --git a/compositor/host/power.mbt b/compositor/host/power.mbt new file mode 100644 index 0000000..b27e8b4 --- /dev/null +++ b/compositor/host/power.mbt @@ -0,0 +1,84 @@ +///| Power in the login session: the screen goes off and the computer suspends after the minutes +/// without input the settings module's Power tab set (shell.screen_off_min / suspend_min), and the +/// tab's Suspend / Restart / Power off buttons. Suspend, power off and restart go through logind +/// (`systemctl`, else `loginctl`), so its inhibitors and polkit rules apply. +/// +/// The main loop calls `power_tick` every pass. An idle loop still wakes about once a second +/// (IdleClock in compositor/app), so the timeouts fire within a second. CLOCK_MONOTONIC stops +/// while the machine is suspended, so after a resume the idle time hasn't grown past the suspend +/// timeout and the machine doesn't suspend again until there has been input and a new idle spell. + +///| What `power_tick` wants the display / system to do now. +pub(all) enum PowerChange { + NoChange + ScreenOff + ScreenOn + Suspend +} derive(Eq, Debug) + +///| Note input: it restarts the idle time (and wakes a screen that is off at the next tick). +pub fn ChandraCompositor::note_activity(self : ChandraCompositor, now_ms : UInt64) -> Unit { + self.last_input_ms = now_ms +} + +///| Check the idle timeouts at monotonic time `now_ms`. +pub fn ChandraCompositor::power_tick(self : ChandraCompositor, now_ms : UInt64) -> PowerChange { + 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 + let susp = self.shell.suspend_min + if susp > 0 && idle >= minutes(susp) { + if !self.idle_suspended { + self.idle_suspended = true + return Suspend + } + } else { + self.idle_suspended = false + } + if off > 0 && idle >= minutes(off) { + if !self.screen_off { + self.screen_off = true + return ScreenOff + } + } else if self.screen_off { + self.screen_off = false + self.damage.mark_full() + return ScreenOn + } + NoChange +} + +///| The command for a power action: 0 suspend, 1 power off, 2 restart. +pub fn power_command(action : Int) -> String? { + let verb = match action { + 0 => "suspend" + 1 => "poweroff" + 2 => "reboot" + _ => return None + } + Some("systemctl " + verb + " || loginctl " + verb) +} + +///| Suspend, power off or restart now. Only the login session does it: in a nested window (or a +/// test) a notice says so instead, since it would act on the machine the outer desktop runs on. +pub fn ChandraCompositor::system_power(self : ChandraCompositor, action : Int) -> Unit { + match power_command(action) { + None => () + Some(cmd) => + if self.login_session { + if !@sys.spawn(cmd, self.shell.display) { + self.shell.say("Could not run " + cmd) + } + } else { + self.shell.say("Suspend, restart and power off work in the login session only") + } + } +} + +///| +test "power commands go through logind" { + assert_eq(power_command(0), Some("systemctl suspend || loginctl suspend")) + assert_eq(power_command(1), Some("systemctl poweroff || loginctl poweroff")) + assert_eq(power_command(2), Some("systemctl reboot || loginctl reboot")) + assert_eq(power_command(3), None) +} diff --git a/compositor/kms/kms_native.mbt b/compositor/kms/kms_native.mbt index 1de472e..1a434d2 100644 --- a/compositor/kms/kms_native.mbt +++ b/compositor/kms/kms_native.mbt @@ -46,6 +46,15 @@ extern "C" fn c_close() = "mp_kms_close" ///| extern "C" fn c_fd(i : Int) -> Int = "mp_kms_fd" +///| +extern "C" fn c_set_power(on : Int) = "mp_kms_set_power" + +///| Turn the screen on or off (DPMS). While it is off no frame is shown (`frame_ready` is +/// false); on shows the last frame again. +pub fn Kms::set_power(_self : Kms, on : Bool) -> Unit { + c_set_power(if on { 1 } else { 0 }) +} + ///| pub(all) struct Kms { width : Int diff --git a/compositor/kms/kms_stub.c b/compositor/kms/kms_stub.c index 23849a6..e2f8a64 100644 --- a/compositor/kms/kms_stub.c +++ b/compositor/kms/kms_stub.c @@ -123,6 +123,7 @@ static int g_front; /* index currently scanned out */ static int g_flip_pending; static int g_need_modeset; static int g_width, g_height; +static int g_blank; /* screen turned off (DPMS) by mp_kms_set_power */ static int fb_create(struct fbuf *b, int w, int h) { struct drm_mode_create_dumb c = { .width = (uint32_t)w, .height = (uint32_t)h, .bpp = 32 }; @@ -339,8 +340,40 @@ static void do_modeset(void) { cursor_apply(); } +/* Legacy DPMS on the output's connector (the modeset path here is legacy too). */ +static void set_dpms(int on) { + drmModeObjectProperties *props = drmModeObjectGetProperties(g_drm, g_conn, DRM_MODE_OBJECT_CONNECTOR); + if (!props) return; + for (uint32_t i = 0; i < props->count_props; i++) { + drmModePropertyRes *p = drmModeGetProperty(g_drm, props->props[i]); + if (!p) continue; + if (!strcmp(p->name, "DPMS")) { + if (drmModeConnectorSetProperty(g_drm, g_conn, p->prop_id, on ? DRM_MODE_DPMS_ON : DRM_MODE_DPMS_OFF) < 0) + fprintf(stderr, "kms: DPMS %s failed: %s\n", on ? "on" : "off", strerror(errno)); + } + drmModeFreeProperty(p); + } + drmModeFreeObjectProperties(props); +} + /* ---- exported API -------------------------------------------------------- */ +/* Turn the screen off (0) or on (1). While off, no frame is presented; on redoes the modeset so + * the last frame shows again. */ +MOONBIT_FFI_EXPORT +void mp_kms_set_power(int32_t on) { + if (!g_seat || (on ? !g_blank : g_blank)) return; + g_blank = !on; + if (!g_seat_enabled || g_suspended) return; /* applied when the VT comes back */ + if (on) { + set_dpms(1); + do_modeset(); + } else { + set_dpms(0); + } +} + + /* Open seat, DRM output and input. Returns 0 on success, negative step code on failure. */ MOONBIT_FFI_EXPORT int32_t mp_kms_open(void) { @@ -429,6 +462,7 @@ int32_t mp_kms_poll(void) { drmSetMaster(g_drm); if (g_li) libinput_resume(g_li); do_modeset(); + if (g_blank) set_dpms(0); } if (g_li) dispatch_input(); return g_seat_enabled; @@ -450,13 +484,13 @@ int32_t mp_kms_fd(int32_t i) { /* True when a new frame may be presented (seat active, no flip in flight). */ MOONBIT_FFI_EXPORT int32_t mp_kms_frame_ready(void) { - return g_seat_enabled && !g_flip_pending; + return g_seat_enabled && !g_flip_pending && !g_blank; } /* Present an RGBA8888 frame of w x h (must match the mode). */ MOONBIT_FFI_EXPORT int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h) { - if (!g_seat_enabled || g_flip_pending) return 0; + if (!g_seat_enabled || g_flip_pending || g_blank) return 0; int back = 1 - g_front; struct fbuf *b = &g_fb[back]; int cw = w < g_width ? w : g_width; diff --git a/compositor/kms/kms_wasm.mbt b/compositor/kms/kms_wasm.mbt index 42b5978..47b8b03 100644 --- a/compositor/kms/kms_wasm.mbt +++ b/compositor/kms/kms_wasm.mbt @@ -47,6 +47,12 @@ pub fn Kms::present_frame(_self : Kms) -> Unit { @hostdisplay.present_frame() } +///| Turn the screen on or off (DPMS). While it is off no frame is shown (`frame_ready` is +/// false); on shows the last frame again. +pub fn Kms::set_power(_self : Kms, on : Bool) -> Unit { + @hostdisplay.set_power(on) +} + ///| Show the cursor for a wp_cursor_shape_v1 value. pub fn Kms::set_cursor_shape(_self : Kms, shape : UInt) -> Unit { @hostdisplay.set_cursor_shape(shape) diff --git a/compositor/shell/shell.mbt b/compositor/shell/shell.mbt index 9c274c1..c499be7 100644 --- a/compositor/shell/shell.mbt +++ b/compositor/shell/shell.mbt @@ -145,6 +145,8 @@ pub(all) enum ShellAction { /// The screenshot module asked for a screenshot or recording (code: see the compositor's /// screenshot_request). Screenshot(Int) + /// The settings module's Power tab asked to suspend (0), power off (1) or restart (2) now. + SystemPower(Int) } derive(Eq, Debug) ///| One wasm module loaded into the panel. @@ -236,6 +238,10 @@ pub(all) struct DesktopShell { mut remember_windows : Bool /// Dark mode (the configured theme) or light (Moon Day); saved as `:theme :light` when off. mut dark_mode : Bool + /// Power: minutes without input before the login session turns the screen off / suspends + /// (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 desk_set : Bool mut desk_x : Int mut desk_y : Int @@ -336,6 +342,8 @@ pub fn DesktopShell::new(display : String) -> DesktopShell { screenshot_state: 2, remember_windows: true, dark_mode: true, + screen_off_min: default_screen_off_min, + suspend_min: default_suspend_min, desk_set: false, desk_x: 0, desk_y: 0, diff --git a/compositor/shell/state.mbt b/compositor/shell/state.mbt index 4f5d2bb..3e9de6b 100644 --- a/compositor/shell/state.mbt +++ b/compositor/shell/state.mbt @@ -7,6 +7,8 @@ /// :desktop-card {:x 900 :y 24} ; where the desktop card was dragged to (absent: default spot) /// :wallpaper :aurora ; the settings module's wallpaper (absent: :plasma-glow) /// :theme :light ; the settings module's Dark mode switch is off (absent: dark) +/// :power {:screen-off 5 :suspend 30} ; minutes without input before the screen goes off / +/// ; the computer suspends, 0 never (absent: 10 and 0) /// :session [{:app "foot"} {:app "org.gnome.Nautilus" :minimized true}] /// ; the windows open when the last session ended, reopened at /// ; the next start (see session.mbt in compositor/host) @@ -34,6 +36,8 @@ pub(all) struct SavedState { remember_windows : Bool? /// From `:theme`: true for :dark, false for :light. dark_mode : Bool? + /// From `:power`: (screen-off, suspend) minutes; a missing one keeps its default. + power : (Int?, Int?) } ///| @@ -47,7 +51,7 @@ let layout_names : Array[String] = ["tiling", "monocle", "floating"] ///| The keys this build owns; everything else in the file is kept as it is. let owned_keys : Array[String] = [ "layout", "recent", "desktop-card", "windows", "wallpaper", "restore-session", "remember-windows", - "theme", + "theme", "power", ] ///| How state.edn names each wallpaper, in `@libshell.wallpaper_names` order. @@ -92,6 +96,7 @@ pub fn DesktopShell::load_state(self : DesktopShell) -> SavedState { restore_session: None, remember_windows: None, dark_mode: None, + power: (None, None), } } let entries = read_state_file() @@ -191,6 +196,18 @@ pub fn DesktopShell::load_state(self : DesktopShell) -> SavedState { wallpaper, restore_session: flag("restore-session"), remember_windows: flag("remember-windows"), + power: match lookup_key(entries, "power") { + Some(Mapping(m)) => { + let f = fn(k : String) -> Int? { + match lookup_key(m, k) { + Some(Integer(v)) => parse_int_str(v) + _ => None + } + } + (f("screen-off"), f("suspend")) + } + _ => (None, None) + }, dark_mode: match lookup_key(entries, "theme") { Some(Keyword("light")) => Some(false) Some(Keyword("dark")) => Some(true) @@ -220,6 +237,14 @@ pub fn DesktopShell::apply_state(self : DesktopShell, st : SavedState) -> Unit { Some(b) => self.dark_mode = b None => () } + match st.power.0 { + Some(m) if m >= 0 => self.screen_off_min = m + _ => () + } + match st.power.1 { + Some(m) if m >= 0 => self.suspend_min = m + _ => () + } match st.desk { Some((x, y)) => { self.desk_set = true @@ -292,6 +317,12 @@ pub fn DesktopShell::save_state(self : DesktopShell) -> Unit { entries.insert(2, (@edn.Value::Keyword("wallpaper"), @edn.Value::Keyword(wallpaper_keys[self.wallpaper_sel]))) } // Session settings are written only when off: absent means on, as for a hand-written file. + if self.screen_off_min != default_screen_off_min || self.suspend_min != default_suspend_min { + entries.insert(2, (@edn.Value::Keyword("power"), @edn.Value::Mapping([ + (@edn.Value::Keyword("screen-off"), @edn.Value::Integer(self.screen_off_min.to_string())), + (@edn.Value::Keyword("suspend"), @edn.Value::Integer(self.suspend_min.to_string())), + ]))) + } if !self.dark_mode { entries.insert(2, (@edn.Value::Keyword("theme"), @edn.Value::Keyword("light"))) } diff --git a/compositor/shell/widgets.mbt b/compositor/shell/widgets.mbt index fd70d2d..fb28fcf 100644 --- a/compositor/shell/widgets.mbt +++ b/compositor/shell/widgets.mbt @@ -163,7 +163,7 @@ fn DesktopShell::panel_fits(self : DesktopShell) -> Bool { } ///| Show a short message above the panel for a few seconds. -fn DesktopShell::say(self : DesktopShell, msg : String) -> Unit { +pub fn DesktopShell::say(self : DesktopShell, msg : String) -> Unit { self.notice = msg self.notice_frames = 1 self.notice_start = wall_secs() @@ -430,6 +430,9 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit { @wasm.publish(SessionSettings, st) @wasm.publish_session_settings(self.session_settings_bits()) } + if self.widgets.iter().any(w => w.has_cap("power")) { + @wasm.publish_power(self.screen_off_min, self.suspend_min) + } if self.widgets.iter().any(w => w.has_cap("screenshot")) { @wasm.publish_screenshot(self.screenshot_state) } @@ -505,6 +508,22 @@ pub fn DesktopShell::set_session_setting(self : DesktopShell, i : Int, on : Bool self.save_state() } +///| Default power timeouts, in minutes (0: never): the screen goes off after 10 minutes without +/// input; the computer doesn't suspend on its own. +let default_screen_off_min : Int = 10 + +///| +let default_suspend_min : Int = 0 + +///| Set the power timeouts (minutes, 0: never; clamped to a day) and remember them. +pub fn DesktopShell::set_power_timeouts(self : DesktopShell, screen_off : Int, suspend : Int) -> Unit { + let clamp = fn(m : Int) { if m < 0 { 0 } else if m > 1440 { 1440 } else { m } } + self.screen_off_min = clamp(screen_off) + self.suspend_min = clamp(suspend) + @wasm.publish_power(self.screen_off_min, self.suspend_min) + self.save_state() +} + ///| Carry out what modules asked of the host during their last calls. fn DesktopShell::process_requests(self : DesktopShell) -> Unit { while true { @@ -528,6 +547,9 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit { Some(SetWallpaper(i)) => self.set_wallpaper(i) Some(SetSessionSetting(i, on)) => self.set_session_setting(i, on) 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(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) } Some(SetInspector(on)) => self.set_inspecting(on) Some(LoadModule(path)) => { match self.load_path(path) { @@ -604,6 +626,8 @@ pub(all) enum SettingsTab { Desktop /// The panel's modules: remove, add, browse. Panel + /// Battery, idle timeouts, suspend / restart / power off. + Power } derive(Eq, Debug) ///| Open the settings module ("System settings") on `tab`, loading it into the panel first if it @@ -632,11 +656,12 @@ pub fn DesktopShell::open_settings(self : DesktopShell, tab : SettingsTab) -> Bo if w.popup_rect.w == 0 { ignore(self.deliver(w, false, PointerDown(0, 0))) } - // The module's keys 1, 2, 3 pick its tabs. + // The module's keys 1-4 pick its tabs. let key = match tab { Session => "1" Desktop => "2" Panel => "3" + Power => "4" } ignore(self.deliver(w, true, KeyDown(key))) self.save_panel_config() diff --git a/compositor/wasm/wasm_host.mbt b/compositor/wasm/wasm_host.mbt index 0e9e55e..7d4d8b3 100644 --- a/compositor/wasm/wasm_host.mbt +++ b/compositor/wasm/wasm_host.mbt @@ -318,6 +318,11 @@ pub fn publish_screenshot(state : Int) -> Unit { @hostpl.publish_screenshot(state.reinterpret_as_uint()) } +///| The power timeouts, in minutes (0: never). +pub fn publish_power(screen_off : Int, suspend : Int) -> Unit { + @hostpl.publish_power(screen_off.reinterpret_as_uint(), suspend.reinterpret_as_uint()) +} + ///| Something a module asked the host to do during a call. pub(all) enum HostRequest { Launch(String) @@ -333,6 +338,11 @@ pub(all) enum HostRequest { SetSessionSetting(Int, Bool) /// The screenshot capability: 0-3 take, 10-12 record, 20 stop, 30/31 pointer off/on. Screenshot(Int) + /// Power: screen-off / suspend timeouts in minutes (0: never), an action now (0 suspend, + /// 1 power off, 2 restart). + SetScreenOff(Int) + SetSuspendAfter(Int) + PowerAction(Int) } derive(Eq, Debug) ///| @@ -350,6 +360,9 @@ pub fn next_request() -> HostRequest? { Some(SetWallpaper(i)) => Some(SetWallpaper(i)) Some(SetSessionSetting(c)) => Some(SetSessionSetting(c.index, c.on)) Some(Screenshot(code)) => Some(Screenshot(code)) + Some(SetScreenOff(m)) => Some(SetScreenOff(m)) + Some(SetSuspendAfter(m)) => Some(SetSuspendAfter(m)) + Some(PowerAction(a)) => Some(PowerAction(a)) } } diff --git a/compositor/wasm/wasm_native.mbt b/compositor/wasm/wasm_native.mbt index 3795ca7..88f9d78 100644 --- a/compositor/wasm/wasm_native.mbt +++ b/compositor/wasm/wasm_native.mbt @@ -735,6 +735,12 @@ pub fn publish_screenshot(state : Int) -> Unit { c_host_set_int(4, state) } +///| Publish the power timeouts, in minutes (0: never). +pub fn publish_power(screen_off : Int, suspend : Int) -> Unit { + c_host_set_int(5, screen_off) + c_host_set_int(6, suspend) +} + ///| Something a module asked the host to do during a call. pub(all) enum HostRequest { Launch(String) @@ -750,6 +756,11 @@ pub(all) enum HostRequest { SetSessionSetting(Int, Bool) /// The screenshot capability: 0-3 take, 10-12 record, 20 stop, 30/31 pointer off/on. Screenshot(Int) + /// Power: screen-off / suspend timeouts in minutes (0: never), an action now (0 suspend, + /// 1 power off, 2 restart). + SetScreenOff(Int) + SetSuspendAfter(Int) + PowerAction(Int) } derive(Eq, Debug) ///| @@ -774,6 +785,9 @@ pub fn next_request() -> HostRequest? { 10 => Some(SetSessionSetting(c_host_req_int(), false)) 11 => Some(SetSessionSetting(c_host_req_int(), true)) 12 => Some(Screenshot(c_host_req_int())) + 13 => Some(SetScreenOff(c_host_req_int())) + 14 => Some(SetSuspendAfter(c_host_req_int())) + 15 => Some(PowerAction(c_host_req_int())) _ => None } } diff --git a/compositor/wasm/wasm_stub.c b/compositor/wasm/wasm_stub.c index e349812..5d30ee2 100644 --- a/compositor/wasm/wasm_stub.c +++ b/compositor/wasm/wasm_stub.c @@ -55,7 +55,8 @@ enum { K_SYSTEM_READ, K_WIN_ALL, K_WIN_FOCUS_ID, K_LOGOUT, K_WALLPAPERS, K_WALLPAPER_CUR, K_SET_WALLPAPER, 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_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 }; typedef struct Env { Inst *inst; int kind; } Env; @@ -65,7 +66,8 @@ enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SES 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), - 4 screenshot state (bit 0 recording, bit 1 pointer in recordings) */ + 4 screenshot state (bit 0 recording, bit 1 pointer in recordings), + 5 screen-off minutes, 6 suspend minutes (0: never) */ /* ---- 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; @@ -319,6 +321,17 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_ case K_SHOT_RECORD: if (a0 >= 0 && a0 <= 2) push_req(12, 10 + a0, NULL); break; case K_SHOT_STOP: push_req(12, 20, NULL); break; case K_SHOT_SET_PTR: push_req(12, a0 ? 31 : 30, NULL); break; + case K_PW_SCREEN: + if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[5]); + break; + case K_PW_SUSP: + if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[6]); + 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_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; case K_SHOT_IS_REC: if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[4] & 1); break; @@ -474,6 +487,13 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) { if (!strcmp(iface, "screenshot") && !strcmp(fn, "is-recording")) return K_SHOT_IS_REC; if (!strcmp(iface, "screenshot") && !strcmp(fn, "records-pointer")) return K_SHOT_PTR; if (!strcmp(iface, "screenshot") && !strcmp(fn, "set-records-pointer")) return K_SHOT_SET_PTR; + if (!strcmp(iface, "power") && !strcmp(fn, "screen-off-minutes")) return K_PW_SCREEN; + 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, "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; if (!strcmp(iface, "layout-control") && !strcmp(fn, "layout-modes")) return K_LAYOUTS; if (!strcmp(iface, "layout-control") && !strcmp(fn, "current-layout")) return K_LAYOUT_CUR; if (!strcmp(iface, "layout-control") && !strcmp(fn, "set-layout")) return K_SET_LAYOUT; diff --git a/host-wasm/src/kms.rs b/host-wasm/src/kms.rs index ba45bef..76ac209 100644 --- a/host-wasm/src/kms.rs +++ b/host-wasm/src/kms.rs @@ -16,6 +16,7 @@ extern "C" { fn mp_kms_keymap_len() -> i32; fn mp_kms_close(); fn mp_kms_fd(i: i32) -> i32; + fn mp_kms_set_power(on: i32); fn hw_kms_present(pixels: *mut u8, w: i32, h: i32) -> i32; fn hw_kms_keymap_copy(out: *mut u8, cap: i32) -> i32; } @@ -62,6 +63,11 @@ pub fn present(pixels: &[u8], width: u32, height: u32) { unsafe { hw_kms_present(pixels.as_ptr() as *mut u8, width as i32, height as i32) }; } +/// Turn the screen on or off (DPMS). +pub fn set_power(on: bool) { + unsafe { mp_kms_set_power(on as i32) }; +} + pub fn set_cursor_shape(shape: u32) { unsafe { mp_kms_set_cursor_shape(shape as i32) }; } diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs index 444277c..765fcb6 100644 --- a/host-wasm/src/main.rs +++ b/host-wasm/src/main.rs @@ -205,6 +205,12 @@ impl chandra::host::plasmoids::Host for State { self.pl().shared.borrow_mut().screenshot = state; } + fn publish_power(&mut self, screen_off: u32, suspend: u32) { + let mut sh = self.pl().shared.borrow_mut(); + sh.screen_off_min = screen_off; + sh.suspend_min = suspend; + } + fn publish_system(&mut self, s: chandra::host::plasmoids::SystemSnapshot) { use plasmoid::ph::chandra::desktop::system::Snapshot; self.pl().shared.borrow_mut().system = Some(Snapshot { @@ -243,6 +249,9 @@ impl chandra::host::plasmoids::Host for State { R::SetSessionSetting(chandra::host::plasmoids::SettingChange { index, on }) } Req::Screenshot(code) => R::Screenshot(code), + Req::SetScreenOff(m) => R::SetScreenOff(m), + Req::SetSuspendAfter(m) => R::SetSuspendAfter(m), + Req::PowerAction(a) => R::PowerAction(a), }) } @@ -309,6 +318,12 @@ impl chandra::host::display::Host for State { #[cfg(not(feature = "drm"))] let _ = (pixels, width, height); } + fn set_power(&mut self, on: bool) { + #[cfg(feature = "drm")] + kms::set_power(on); + #[cfg(not(feature = "drm"))] + let _ = on; + } fn set_cursor_shape(&mut self, shape: u32) { #[cfg(feature = "drm")] kms::set_cursor_shape(shape); diff --git a/host-wasm/src/plasmoid.rs b/host-wasm/src/plasmoid.rs index 6d34ac1..902cc5f 100644 --- a/host-wasm/src/plasmoid.rs +++ b/host-wasm/src/plasmoid.rs @@ -48,6 +48,10 @@ pub enum Req { SetSessionSetting(i32, bool), /// The screenshot capability: 0-3 take, 10-12 record, 20 stop, 30/31 pointer off/on. Screenshot(i32), + SetScreenOff(i32), + SetSuspendAfter(i32), + /// 0 suspend, 1 power off, 2 restart. + PowerAction(i32), } pub const T_APPS: usize = 0; @@ -70,6 +74,9 @@ pub struct Shared { pub session_settings: u32, /// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer. pub screenshot: u32, + /// Power timeouts in minutes (0: never). + pub screen_off_min: u32, + pub suspend_min: u32, pub inspector_on: bool, pub system: Option, /// (id, title, app id, focused) @@ -307,6 +314,30 @@ impl d::wallpaper::Host for PState { } } +impl d::power::Host for PState { + fn screen_off_minutes(&mut self) -> u32 { + self.shared.borrow().screen_off_min + } + fn set_screen_off_minutes(&mut self, minutes: u32) { + self.shared.borrow_mut().requests.push_back(Req::SetScreenOff(minutes as i32)); + } + fn suspend_minutes(&mut self) -> u32 { + self.shared.borrow().suspend_min + } + fn set_suspend_minutes(&mut self, minutes: u32) { + self.shared.borrow_mut().requests.push_back(Req::SetSuspendAfter(minutes as i32)); + } + fn suspend(&mut self) { + self.shared.borrow_mut().requests.push_back(Req::PowerAction(0)); + } + fn power_off(&mut self) { + self.shared.borrow_mut().requests.push_back(Req::PowerAction(1)); + } + fn reboot(&mut self) { + self.shared.borrow_mut().requests.push_back(Req::PowerAction(2)); + } +} + impl d::screenshot::Host for PState { fn take(&mut self, mode: u32) { if mode <= 3 { @@ -722,9 +753,9 @@ mod tests { assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSessionSetting(1, true)))); assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 2 * 28 + 13 }))); assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSessionSetting(2, false)))); - // The Desktop tab (second of three 96 px tabs): row 0 is the "Wallpaper" heading + // The Desktop tab (second of four 72 px tabs): row 0 is the "Wallpaper" heading // (nothing), rows 1.. the wallpapers: Starfield. - assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 6 + 96 + 48, y: 6 + 14 }))); + assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 6 + 72 + 36, y: 6 + 14 }))); assert!(texts(&rt.popup(h).unwrap().ops).contains(&"Starfield".to_string())); assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 13 }))); assert!(rt.shared.borrow().requests.is_empty()); @@ -800,4 +831,33 @@ mod tests { rt.unload(h); } + #[test] + fn settings_power_tab_steps_timeouts_and_confirms_power_off() { + let mut rt = runtime(); + let l = rt.load(&module("session-settings")).expect("session-settings loads"); + assert!(l.imports.contains(&"power".to_string())); + let h = l.handle; + rt.shared.borrow_mut().screen_off_min = 10; + rt.shared.borrow_mut().suspend_min = 0; + assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); + assert!(rt.on_event(h, true, InputEvent::KeyDown("4".to_string()))); // the Power tab + let ts = texts(&rt.popup(h).expect("popup open").ops); + for want in ["Turn screen off after", "10 min", "Suspend after", "Never", "Power off"] { + assert!(ts.contains(&want.to_string()), "{want} shown"); + } + // No battery: rows of 28 below the tab bar (40) are When idle, screen off, suspend, Now, + // Suspend, Restart, Power off. + let row = |i: i32| Point { x: 20, y: 40 + i * 28 + 13 }; + assert!(rt.on_event(h, true, InputEvent::PointerDown(row(1)))); + assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetScreenOff(15)))); + assert!(rt.on_event(h, true, InputEvent::PointerDown(row(2)))); + assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSuspendAfter(5)))); + // Power off takes two clicks. + assert!(rt.on_event(h, true, InputEvent::PointerDown(row(6)))); + assert!(rt.shared.borrow().requests.is_empty()); + assert!(texts(&rt.popup(h).unwrap().ops).contains(&"Click again to power off".to_string())); + assert!(rt.on_event(h, true, InputEvent::PointerDown(row(6)))); + assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::PowerAction(1)))); + rt.unload(h); + } } diff --git a/interface/chandra/desktop/power/README.md b/interface/chandra/desktop/power/README.md new file mode 100644 index 0000000..4fe352d --- /dev/null +++ b/interface/chandra/desktop/power/README.md @@ -0,0 +1,3 @@ +Power: when the login session turns the screen off and suspends after no input, and suspend, +restart or power off now (through logind). A module with this capability is the settings +module's Power tab. The shell keeps the timeouts in state.edn. \ No newline at end of file diff --git a/interface/chandra/desktop/power/ffi.mbt b/interface/chandra/desktop/power/ffi.mbt new file mode 100644 index 0000000..99525d3 --- /dev/null +++ b/interface/chandra/desktop/power/ffi.mbt @@ -0,0 +1,23 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +fn wasmImportScreenOffMinutes() -> Int = "chandra:desktop/power@0.1.0" "screen-off-minutes" + +///| +fn wasmImportSetScreenOffMinutes(p0 : Int) = "chandra:desktop/power@0.1.0" "set-screen-off-minutes" + +///| +fn wasmImportSuspendMinutes() -> Int = "chandra:desktop/power@0.1.0" "suspend-minutes" + +///| +fn wasmImportSetSuspendMinutes(p0 : Int) = "chandra:desktop/power@0.1.0" "set-suspend-minutes" + +///| +fn wasmImportSuspend() = "chandra:desktop/power@0.1.0" "suspend" + +///| +fn wasmImportPowerOff() = "chandra:desktop/power@0.1.0" "power-off" + +///| +fn wasmImportReboot() = "chandra:desktop/power@0.1.0" "reboot" + diff --git a/interface/chandra/desktop/power/moon.pkg b/interface/chandra/desktop/power/moon.pkg new file mode 100644 index 0000000..e2a6033 --- /dev/null +++ b/interface/chandra/desktop/power/moon.pkg @@ -0,0 +1 @@ +warnings = "-44" diff --git a/interface/chandra/desktop/power/top.mbt b/interface/chandra/desktop/power/top.mbt new file mode 100644 index 0000000..0a31dc7 --- /dev/null +++ b/interface/chandra/desktop/power/top.mbt @@ -0,0 +1,51 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +/// Minutes without input before the screen turns off; 0: never. +pub fn screen_off_minutes() -> UInt { + + let result : Int = wasmImportScreenOffMinutes(); + let ret = (result).reinterpret_as_uint() + return ret + +} +///| +pub fn set_screen_off_minutes(minutes : UInt) -> Unit { + + wasmImportSetScreenOffMinutes((minutes).reinterpret_as_int()); + +} +///| +/// Minutes without input before the computer suspends; 0: never. +pub fn suspend_minutes() -> UInt { + + let result : Int = wasmImportSuspendMinutes(); + let ret = (result).reinterpret_as_uint() + return ret + +} +///| +pub fn set_suspend_minutes(minutes : UInt) -> Unit { + + wasmImportSetSuspendMinutes((minutes).reinterpret_as_int()); + +} +///| +/// Suspend, power off or restart now. +pub fn suspend() -> Unit { + + wasmImportSuspend(); + +} +///| +pub fn power_off() -> Unit { + + wasmImportPowerOff(); + +} +///| +pub fn reboot() -> Unit { + + wasmImportReboot(); + +} + diff --git a/interface/chandra/desktop/system/README.md b/interface/chandra/desktop/system/README.md new file mode 100644 index 0000000..2a02de4 --- /dev/null +++ b/interface/chandra/desktop/system/README.md @@ -0,0 +1,3 @@ +Live machine state, sampled by the host about once a second. The widget never +opens /proc or /sys itself: it can only see what this interface hands it, and +the host can serve it from anything (Linux /proc, a mock, a remote machine). \ No newline at end of file diff --git a/interface/chandra/desktop/system/ffi.mbt b/interface/chandra/desktop/system/ffi.mbt new file mode 100644 index 0000000..07051a1 --- /dev/null +++ b/interface/chandra/desktop/system/ffi.mbt @@ -0,0 +1,28 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +fn wasmImportRead(p0 : Int) = "chandra:desktop/system@0.1.0" "read" + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load) + +///| +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) + +///| +extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = +#|(func (param i32) (result i64) local.get 0 i64.load) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + diff --git a/interface/chandra/desktop/system/moon.pkg b/interface/chandra/desktop/system/moon.pkg new file mode 100644 index 0000000..e2a6033 --- /dev/null +++ b/interface/chandra/desktop/system/moon.pkg @@ -0,0 +1 @@ +warnings = "-44" diff --git a/interface/chandra/desktop/system/top.mbt b/interface/chandra/desktop/system/top.mbt new file mode 100644 index 0000000..2f1f83d --- /dev/null +++ b/interface/chandra/desktop/system/top.mbt @@ -0,0 +1,16 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +pub(all) struct Snapshot { + cpu_permille : UInt; mem_used_kib : UInt64; mem_total_kib : UInt64; battery_percent : Int; charging : Bool; uptime_secs : UInt64; net_rx_bytes_per_sec : UInt64; net_tx_bytes_per_sec : UInt64; load_centi : UInt +} +///| +pub fn read() -> Snapshot { + + let return_area = mbt_ffi_malloc(64) + wasmImportRead(return_area); + let ret = Snapshot::{cpu_permille : (mbt_ffi_load32((return_area) + 0)).reinterpret_as_uint(), mem_used_kib : (mbt_ffi_load64((return_area) + 8)).reinterpret_as_uint64(), mem_total_kib : (mbt_ffi_load64((return_area) + 16)).reinterpret_as_uint64(), battery_percent : mbt_ffi_load32((return_area) + 24), charging : (mbt_ffi_load8_u((return_area) + 28) != 0), uptime_secs : (mbt_ffi_load64((return_area) + 32)).reinterpret_as_uint64(), net_rx_bytes_per_sec : (mbt_ffi_load64((return_area) + 40)).reinterpret_as_uint64(), net_tx_bytes_per_sec : (mbt_ffi_load64((return_area) + 48)).reinterpret_as_uint64(), load_centi : (mbt_ffi_load32((return_area) + 56)).reinterpret_as_uint()} + mbt_ffi_free(return_area) + return ret + +} + diff --git a/interface/chandra/host/display/ffi.mbt b/interface/chandra/host/display/ffi.mbt index cbd87ef..8946480 100644 --- a/interface/chandra/host/display/ffi.mbt +++ b/interface/chandra/host/display/ffi.mbt @@ -18,39 +18,19 @@ fn wasmImportPresentFrame() = "chandra:host/display@0.1.0" "present-frame" ///| fn wasmImportSetCursorShape(p0 : Int) = "chandra:host/display@0.1.0" "set-cursor-shape" +///| +fn wasmImportSetPower(p0 : Int) = "chandra:host/display@0.1.0" "set-power" + ///| fn wasmImportTakeInput(p0 : Int) = "chandra:host/display@0.1.0" "take-input" ///| fn wasmImportClose() = "chandra:host/display@0.1.0" "close" -///| -extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = -#|(func (param i32) (param i32) (result i32) -#| local.get 0 -#| local.get 1 call $moonbit.init_array8 -#| local.get 0) - ///| extern "wasm" fn mbt_ffi_loadf64(offset : Int) -> Double = #|(func (param i32) (result f64) local.get 0 f64.load) -///| -#owned(bytes) -extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = -#|(func (param i32) (result i32) local.get 0) - -///| -extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = -#|(func (param i32) (result i32) (local i32) -#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc -#| local.tee 1 i32.const 0 call $moonbit.init_array8 -#| local.get 1) - -///| -extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = -#|(func (param i32) (result i32) local.get 0 i32.load8_u) - ///| extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = #|(func (param i32) (result i32) local.get 0 i32.load) @@ -59,3 +39,26 @@ extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = extern "wasm" fn mbt_ffi_free(position : Int) = #|(func (param i32) local.get 0 call $moonbit.decref) +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array8 +#| local.get 0) + +///| +#owned(bytes) +extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = +#|(func (param i32) (result i32) local.get 0) + +///| +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) + diff --git a/interface/chandra/host/display/native_stub.mbt b/interface/chandra/host/display/native_stub.mbt index e551218..2533714 100644 --- a/interface/chandra/host/display/native_stub.mbt +++ b/interface/chandra/host/display/native_stub.mbt @@ -30,6 +30,11 @@ fn wasmImportSetCursorShape(p0 : Int) -> Unit { abort("wasm-only host import") } +///| +fn wasmImportSetPower(p0 : Int) -> Unit { + abort("wasm-only host import") +} + ///| fn wasmImportTakeInput(p0 : Int) -> Unit { abort("wasm-only host import") diff --git a/interface/chandra/host/display/pkg.generated.mbti b/interface/chandra/host/display/pkg.generated.mbti index 7613d6b..dd20dd9 100644 --- a/interface/chandra/host/display/pkg.generated.mbti +++ b/interface/chandra/host/display/pkg.generated.mbti @@ -16,6 +16,8 @@ pub fn present_frame() -> Unit pub fn set_cursor_shape(UInt32) -> Unit +pub fn set_power(Bool) -> Unit + pub fn take_input() -> Array[SeatEvent] // Errors diff --git a/interface/chandra/host/display/top.mbt b/interface/chandra/host/display/top.mbt index 1531aec..4c3b7c4 100644 --- a/interface/chandra/host/display/top.mbt +++ b/interface/chandra/host/display/top.mbt @@ -95,6 +95,14 @@ pub fn set_cursor_shape(shape : UInt) -> Unit { wasmImportSetCursorShape((shape).reinterpret_as_int()); +} +///| +/// Turn the screen on or off (DPMS). While it is off no frame is shown (`frame-ready` is false); +/// turning it on shows the last frame again. +pub fn set_power(on : Bool) -> Unit { + + wasmImportSetPower((if on { 1 } else { 0 })); + } ///| /// Input queued since the last call. diff --git a/interface/chandra/host/plasmoids/ffi.mbt b/interface/chandra/host/plasmoids/ffi.mbt index adbbe72..fb3cdff 100644 --- a/interface/chandra/host/plasmoids/ffi.mbt +++ b/interface/chandra/host/plasmoids/ffi.mbt @@ -36,6 +36,9 @@ fn wasmImportPublishWallpaper(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publi ///| fn wasmImportPublishSessionSettings(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publish-session-settings" +///| +fn wasmImportPublishPower(p0 : Int, p1 : Int) = "chandra:host/plasmoids@0.1.0" "publish-power" + ///| fn wasmImportPublishScreenshot(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publish-screenshot" @@ -60,38 +63,22 @@ fn wasmImportPickerStart() -> Int = "chandra:host/plasmoids@0.1.0" "picker-start ///| fn wasmImportPickerPoll(p0 : Int) = "chandra:host/plasmoids@0.1.0" "picker-poll" -///| -extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = -#|(func (param i32) (result i32) (local i32) -#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc -#| local.tee 1 i32.const 0 call $moonbit.init_array8 -#| local.get 1) - ///| extern "wasm" fn mbt_ffi_store64(offset : Int, value : Int64) = #|(func (param i32) (param i64) local.get 0 local.get 1 i64.store) -///| -extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = -#|(func (param i32) (result i64) local.get 0 i64.load) - -///| -extern "wasm" fn mbt_ffi_free(position : Int) = -#|(func (param i32) local.get 0 call $moonbit.decref) - ///| #owned(str) extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = #|(func (param i32) (result i32) local.get 0) ///| -extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = -#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) +extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) ///| -#owned(bytes) -extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = -#|(func (param i32) (result i32) local.get 0) +extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) ///| extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = @@ -101,14 +88,30 @@ extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = #| local.get 0) ///| -extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = -#|(func (param i32) (result i32) local.get 0 i32.load8_u) +#owned(bytes) +extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = +#|(func (param i32) (result i32) local.get 0) ///| -extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = -#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) ///| extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = #|(func (param i32) (result i32) local.get 0 i32.load) +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = +#|(func (param i32) (result i64) local.get 0 i64.load) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + diff --git a/interface/chandra/host/plasmoids/native_stub.mbt b/interface/chandra/host/plasmoids/native_stub.mbt index 068efc2..735eaac 100644 --- a/interface/chandra/host/plasmoids/native_stub.mbt +++ b/interface/chandra/host/plasmoids/native_stub.mbt @@ -60,6 +60,11 @@ fn wasmImportPublishSessionSettings(p0 : Int) -> Unit { abort("wasm-only host import") } +///| +fn wasmImportPublishPower(p0 : Int, p1 : Int) -> Unit { + abort("wasm-only host import") +} + ///| fn wasmImportPublishScreenshot(p0 : Int) -> Unit { abort("wasm-only host import") diff --git a/interface/chandra/host/plasmoids/pkg.generated.mbti b/interface/chandra/host/plasmoids/pkg.generated.mbti index efd6b74..ca132d4 100644 --- a/interface/chandra/host/plasmoids/pkg.generated.mbti +++ b/interface/chandra/host/plasmoids/pkg.generated.mbti @@ -23,6 +23,8 @@ pub fn picker_start() -> Bool pub fn popup(UInt32) -> PopupSurface? +pub fn publish_power(UInt32, UInt32) -> Unit + pub fn publish_screenshot(UInt32) -> Unit pub fn publish_session_settings(UInt32) -> Unit @@ -90,6 +92,9 @@ pub(all) enum Request { SetWallpaper(Int32) SetSessionSetting(SettingChange) Screenshot(Int32) + SetScreenOff(Int32) + SetSuspendAfter(Int32) + PowerAction(Int32) } pub(all) struct SettingChange { diff --git a/interface/chandra/host/plasmoids/top.mbt b/interface/chandra/host/plasmoids/top.mbt index 26910e7..a695a08 100644 --- a/interface/chandra/host/plasmoids/top.mbt +++ b/interface/chandra/host/plasmoids/top.mbt @@ -42,6 +42,9 @@ pub(all) enum Request { SetWallpaper(Int) SetSessionSetting(SettingChange) Screenshot(Int) + SetScreenOff(Int) + SetSuspendAfter(Int) + PowerAction(Int) } ///| /// A native file-chooser dialog (zenity on the host session) for "Add widget". @@ -401,6 +404,13 @@ pub fn publish_session_settings(on : UInt) -> Unit { wasmImportPublishSessionSettings((on).reinterpret_as_int()); +} +///| +/// The power timeouts, in minutes (0: never). +pub fn publish_power(screen_off : UInt, suspend : UInt) -> Unit { + + wasmImportPublishPower((screen_off).reinterpret_as_int(), (suspend).reinterpret_as_int()); + } ///| /// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer. @@ -505,6 +515,18 @@ pub fn next_request() -> Request? { Request::Screenshot(mbt_ffi_load32((return_area) + 8)) } + 11 => { + + Request::SetScreenOff(mbt_ffi_load32((return_area) + 8)) + } + 12 => { + + Request::SetSuspendAfter(mbt_ffi_load32((return_area) + 8)) + } + 13 => { + + Request::PowerAction(mbt_ffi_load32((return_area) + 8)) + } _ => panic() } diff --git a/wit/capabilities.wit b/wit/capabilities.wit index 35fc6cb..d4acb52 100644 --- a/wit/capabilities.wit +++ b/wit/capabilities.wit @@ -167,3 +167,19 @@ interface screenshot { records-pointer: func() -> bool; set-records-pointer: func(on: bool); } + +/// Power: when the login session turns the screen off and suspends after no input, and suspend, +/// restart or power off now (through logind). A module with this capability is the settings +/// module's Power tab. The shell keeps the timeouts in state.edn. +interface power { + /// Minutes without input before the screen turns off; 0: never. + screen-off-minutes: func() -> u32; + set-screen-off-minutes: func(minutes: u32); + /// Minutes without input before the computer suspends; 0: never. + suspend-minutes: func() -> u32; + set-suspend-minutes: func(minutes: u32); + /// Suspend, power off or restart now. + suspend: func(); + power-off: func(); + reboot: func(); +} diff --git a/wit/host/display.wit b/wit/host/display.wit index eeb6a73..b40ed75 100644 --- a/wit/host/display.wit +++ b/wit/host/display.wit @@ -25,6 +25,9 @@ interface display { present-frame: func(); /// Show the cursor for a wp_cursor_shape_v1 value. set-cursor-shape: func(shape: u32); + /// Turn the screen on or off (DPMS). While it is off no frame is shown (`frame-ready` is false); + /// turning it on shows the last frame again. + set-power: func(on: bool); record pointer-pos { x: f64, y: f64 } /// A button or key as an evdev code, pressed or released. diff --git a/wit/host/plasmoids.wit b/wit/host/plasmoids.wit index 1362de4..8fef26b 100644 --- a/wit/host/plasmoids.wit +++ b/wit/host/plasmoids.wit @@ -62,6 +62,8 @@ interface plasmoids { publish-wallpaper: func(current: s32); /// Which session settings are on: bit i for row i of the session settings table. publish-session-settings: func(on: u32); + /// The power timeouts, in minutes (0: never). + publish-power: func(screen-off: u32, suspend: u32); /// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer. publish-screenshot: func(state: u32); @@ -108,6 +110,11 @@ interface plasmoids { /// The screenshot capability: 0-3 take(mode), 10-12 start-recording(mode), 20 stop recording, /// 30/31 hide/show the pointer in recordings. screenshot(s32), + /// Power: new screen-off / suspend timeouts in minutes; an action now (0 suspend, 1 power + /// off, 2 restart). + set-screen-off(s32), + set-suspend-after(s32), + power-action(s32), } /// The next pending request, oldest first. next-request: func() -> option; diff --git a/wit/worlds.wit b/wit/worlds.wit index 78f93e6..74d85a3 100644 --- a/wit/worlds.wit +++ b/wit/worlds.wit @@ -80,6 +80,7 @@ world plasmoid-host { import session-settings; import icons; import screenshot; + import power; export plasmoid; } @@ -89,13 +90,16 @@ world logout-widget { import session; } -/// The settings module: session switches (restore, window places, dark mode), the wallpaper, and -/// the panel's modules (load, unload, browse); the panel menu's "Modules..." opens that tab. +/// The settings module: session switches (restore, window places, dark mode), the wallpaper, the +/// panel's modules (load, unload, browse; the panel menu's "Modules..." opens that tab), and power +/// (idle timeouts, battery, suspend / restart / power off). world session-settings-widget { include widget; import session-settings; import wallpaper; import modules; + import power; + import system; } /// Screenshot and screen recording launcher. diff --git a/world/session-settings-widget/README.md b/world/session-settings-widget/README.md index aca952e..07d541d 100644 --- a/world/session-settings-widget/README.md +++ b/world/session-settings-widget/README.md @@ -1,2 +1,3 @@ -The settings module: session switches (restore, window places, dark mode), the wallpaper, and -the panel's modules (load, unload, browse); the panel menu's "Modules..." opens that tab. \ No newline at end of file +The settings module: session switches (restore, window places, dark mode), the wallpaper, the +panel's modules (load, unload, browse; the panel menu's "Modules..." opens that tab), and power +(idle timeouts, battery, suspend / restart / power off). \ No newline at end of file