Lock: add session lock from power button and chandra-ctl lock
CI / test (push) Waiting to run

- Lock the session from the power button or `chandra-ctl lock`
- Unlock with a face or the password; the password always works
- Add compositor lock module with tests, and a polkit unlock policy (org.chandra.unlock)
- Document the lock flow in docs/lock.md and link it from the README
- Add generated interface bindings for the compositor and widget components
This commit is contained in:
nandi committed 2026-11-29 03:24:46 -08:00
1 parent 7501fc3ad9
commit c790f96e58
131 files changed
+4693 -274

No files matched your search

+16 -3
View File
@@ -184,6 +184,10 @@ fn ChandraCompositor::auth_drop_link(self : ChandraCompositor, l : AuthLink) ->
Some(ui) if physical_equal(ui.link, l) => self.close_auth(false)
_ => ()
}
match self.auth_agent {
Some(a) if physical_equal(a, l) => self.unlock_pending = false
_ => ()
}
l.conn.close()
}
@@ -207,6 +211,7 @@ fn ChandraCompositor::auth_tick(self : ChandraCompositor) -> Unit {
Some(l) =>
if !self.auth_serve(l) {
self.auth_agent = None
self.unlock_pending = false
let why = if l.error != "" {
l.error
} else {
@@ -264,6 +269,9 @@ fn ChandraCompositor::auth_serve(self : ChandraCompositor, l : AuthLink) -> Bool
if !l.demo {
@sys.log("chandra: chandra-polkit-agent registered with polkit")
self.auth_slow_said = false
if self.locked && !self.manual_screen_off && !self.screen_off {
self.request_unlock()
}
}
}
"error" => {
@@ -271,6 +279,9 @@ fn ChandraCompositor::auth_serve(self : ChandraCompositor, l : AuthLink) -> Bool
@sys.log("chandra: chandra-polkit-agent: " + l.error)
}
"request" => l.view = Some(@polkit.AuthView::from_request(f))
// Session unlock (lock.mbt): the agent's org.chandra.unlock authorization resolved.
"unlocked" => if !l.demo { self.unlocked() }
"unlock-failed" => if !l.demo { self.unlock_failed() }
"close" => {
match self.auth {
Some(ui) if physical_equal(ui.link, l) && ui.view.id == f.get(1).unwrap_or("") => self.close_auth(false)
@@ -327,9 +338,11 @@ fn ChandraCompositor::close_auth(self : ChandraCompositor, dismiss : Bool) -> Un
ui.view.wipe()
self.auth = None
ui.link.view = None
match ui.prev_kbd {
Some(w) => if self.windows.contains(w) { self.set_kbd_focus(Some(w)) }
None => ()
if !self.locked {
match ui.prev_kbd {
Some(w) => if self.windows.contains(w) { self.set_kbd_focus(Some(w)) }
None => ()
}
}
self.osk_sync()
self.damage.mark_full()
+82 -2
View File
@@ -29,7 +29,8 @@ fn auth_bus(tag : String) -> String? {
}
///| The mock polkitd: owns org.freedesktop.PolicyKit1, records the agent that registers, and
/// collects answers to the BeginAuthentication calls it makes.
/// collects answers to the BeginAuthentication calls it makes. Also handles CheckAuthorization /
/// CancelCheckAuthorization for org.chandra.unlock using `unix-process`.
struct MockAuthority {
bus : @network.DBus
mut agent : String
@@ -37,6 +38,14 @@ struct MockAuthority {
mut refuse : String
/// Answers to BeginAuthentication: "ok" or the error name.
answers : Array[String]
/// Subjects passed to CheckAuthorization.
check_subjects : Array[@network.DValue]
/// Cancel ids passed to CancelCheckAuthorization.
cancelled_ids : Array[String]
/// Monotonic cookie counter for CheckAuthorization -> BeginAuthentication.
mut check_seq : Int
/// In-flight CheckAuthorization calls: (cookie, cancel_id, call_msg).
pending_checks : Array[(String, String, @network.DMessage)]
}
///|
@@ -50,7 +59,16 @@ fn MockAuthority::new(path : String) -> MockAuthority {
1000,
)
guard r is Some({ body: [U32(1U)], .. }) else { abort("could not own org.freedesktop.PolicyKit1") }
let a = { bus, agent: "", refuse: "", answers: [] }
let a = {
bus,
agent: "",
refuse: "",
answers: [],
check_subjects: [],
cancelled_ids: [],
check_seq: 0,
pending_checks: [],
}
bus.set_on_call(fn(m) {
match m.meth {
"RegisterAuthenticationAgent" =>
@@ -66,6 +84,68 @@ fn MockAuthority::new(path : String) -> MockAuthority {
}
}
"UnregisterAuthenticationAgent" => bus.reply(m, [])
"CheckAuthorization" =>
match m.body {
[Struct([Str("unix-process"), Arr(_, _)]) as subj, Str(action_id), _, U32(_), Str(cancel_id)] => {
a.check_subjects.push(subj)
a.check_seq = a.check_seq + 1
let cookie = "unlock-cookie-" + a.check_seq.to_string()
a.pending_checks.push((cookie, cancel_id, m))
let ids : Array[@network.DValue] = [
Struct([
Str("unix-user"),
@network.dict("v", [("uid", Variant(U32(@polkit.own_uid().reinterpret_as_uint())))]),
]),
]
ignore(
bus.call(
@network.DMessage::call(a.agent, @polkit.agent_path, @polkit.agent_iface, "BeginAuthentication", [
Str(action_id),
Str("Authentication is required to unlock the screen"),
Str(""),
@network.DValue::Arr("{ss}", []),
Str(cookie),
Arr("(sa{sv})", ids),
]),
on_reply=fn(rm) {
let ok = rm.mtype == @network.method_return
a.answers.push(if ok { "ok" } else { rm.error_name })
match a.pending_checks.search_by(c => c.0 == cookie) {
Some(idx) => {
let (_, _, req_msg) = a.pending_checks.remove(idx)
bus.reply(req_msg, [Struct([Bool(ok), Bool(false), @network.dict("s", [])])])
}
None => ()
}
},
),
)
}
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad CheckAuthorization args")
}
"CancelCheckAuthorization" =>
match m.body {
[Str(cancel_id)] => {
a.cancelled_ids.push(cancel_id)
match a.pending_checks.search_by(c => c.1 == cancel_id) {
Some(idx) => {
let (cookie, _, req_msg) = a.pending_checks.remove(idx)
ignore(
bus.call(
@network.DMessage::call(a.agent, @polkit.agent_path, @polkit.agent_iface, "CancelAuthentication", [
Str(cookie),
]),
on_reply=fn(_) { () },
),
)
bus.reply(req_msg, [Struct([Bool(false), Bool(false), @network.dict("s", [])])])
}
None => ()
}
bus.reply(m, [])
}
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad CancelCheckAuthorization args")
}
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.UnknownMethod", m.meth)
}
})
+67 -23
View File
@@ -153,6 +153,14 @@ pub(all) struct ChandraCompositor {
mut screen_off : Bool
mut manual_screen_off : Bool
mut idle_suspended : Bool
/// The session is locked (lock.mbt): the desktop is hidden and input only reaches the unlock
/// dialog until a face or password unlocks it.
mut locked : Bool
/// Whether turning the screen off (power button) also locks the session. `chandra-ctl lock`
/// locks regardless. Off by default; CHANDRA_LOCK=1 or the setting turns it on.
mut lock_on_blank : Bool
/// An unlock request is out to the agent and we are waiting (don't ask again every wake).
mut unlock_pending : Bool
mut output_w : Int
mut output_h : Int
mut work_area : @wm.Rect
@@ -367,6 +375,8 @@ pub fn ChandraCompositor::new(
)
let work_area = work_area_for(output_w, output_h, theme)
let shell = @shell.DesktopShell::new(socket_path)
let init_rot = initial_rotation_from_env()
shell.rotation = init_rot
shell.set_output(theme, output_w, output_h)
let comp : ChandraCompositor = {
server,
@@ -400,6 +410,9 @@ pub fn ChandraCompositor::new(
screen_off: false,
manual_screen_off: false,
idle_suspended: false,
locked: false,
lock_on_blank: @sys.getenv("CHANDRA_LOCK") == "1",
unlock_pending: false,
output_w,
output_h,
work_area,
@@ -493,7 +506,7 @@ pub fn ChandraCompositor::new(
osk_pressed: None,
osk_hover: None,
osk_pointer_grab: false,
rotation: initial_rotation_from_env(),
rotation: init_rot,
pending_rotation: None,
vol_run: None,
vol_queue: [],
@@ -568,6 +581,7 @@ fn initial_rotation_from_env() -> Int {
pub fn ChandraCompositor::request_rotation(self : ChandraCompositor, rot : Int) -> Unit {
let r = (rot % 4 + 4) % 4
self.pending_rotation = Some(r)
self.shell.rotation = r
self.damage.mark_full()
}
@@ -1235,8 +1249,9 @@ fn ChandraCompositor::build_scene(
self.overview_sync()
let scene = @scene.SceneGraph::new(self.output_w, self.output_h)
let order = self.wm.stacking_order()
// The overview draws the windows itself, as previews.
let shown = if self.overview is Some(_) { [] } else { order }
// The overview draws the windows itself, as previews. A locked session hides every window
// behind the unlock dialog (lock.mbt).
let shown = if self.overview is Some(_) || self.locked { [] } else { order }
for wid in shown {
self.push_window_node(scene, wid)
@@ -1266,17 +1281,19 @@ fn ChandraCompositor::build_scene(
}
}
// Client menus would draw above the auth dialog: none while it is up.
for p in (if self.auth is Some(_) { [] } else { self.popups }) {
// Client menus would draw above the auth dialog: none while it is up or the session is locked.
for p in (if self.auth is Some(_) || self.locked { [] } else { self.popups }) {
match p.surface {
Some(snap) => if self.overview is None { scene.popups.push((self.popup_rect(p), snap)) }
None => ()
}
}
// The drag icon, over every window and menu.
match self.dnd_icon_node() {
Some(n) => scene.popups.push(n)
None => ()
if !self.locked {
match self.dnd_icon_node() {
Some(n) => scene.popups.push(n)
None => ()
}
}
self.shell.layout_sel = match self.layout_mode {
@@ -1287,6 +1304,8 @@ fn ChandraCompositor::build_scene(
self.sync_shell_windows()
self.shell.screenshot_state = (if self.rec is Some(_) { 1 } else { 0 }) |
(if self.rec_pointer { 2 } else { 0 })
self.shell.osk_visible = self.osk_visible
self.shell.rotation = self.pending_rotation.unwrap_or(self.rotation)
// A window over the whole desktop (maximized, fullscreen, monocle) pauses a desktop module's
// animation: nobody can see it.
self.shell.set_desktop_covered(self.desktop_covered())
@@ -1294,24 +1313,34 @@ fn ChandraCompositor::build_scene(
let (bg_ops, shell_ops) = self.shell.render(self.output_w, self.output_h, self.theme)
// The overview goes under the panel and the launcher.
self.overview_sync()
let panel_ops = self.overview_ops()
panel_ops.append(shell_ops)
if self.switcher_on {
panel_ops.append(self.switcher_ops())
let panel_ops = if self.locked {
let ops = self.lock_ops()
ops.append(self.auth_ops())
ops.append(self.auth_notice_ops())
ops.append(self.osk_ops())
ops.append(self.volume_ops())
ops
} else {
let ops = self.overview_ops()
ops.append(shell_ops)
if self.switcher_on {
ops.append(self.switcher_ops())
}
ops.append(self.screenshot_ops())
ops.append(self.emoji_ops())
ops.append(self.face_window_ops())
ops.append(self.auth_ops())
ops.append(self.auth_notice_ops())
ops.append(self.osk_ops())
ops.append(self.volume_ops())
ops
}
panel_ops.append(self.screenshot_ops())
panel_ops.append(self.emoji_ops())
panel_ops.append(self.face_window_ops())
panel_ops.append(self.auth_ops())
panel_ops.append(self.auth_notice_ops())
panel_ops.append(self.osk_ops())
panel_ops.append(self.volume_ops())
self.frames_built = self.frames_built + 1
self.run_shell_actions()
// The wallpaper (the first ops) is cached by the renderer; the desktop card after it changes.
let n_wall = if self.shell.wallpaper_len <= bg_ops.length() { self.shell.wallpaper_len } else { 0 }
scene.wallpaper_ops = Array::makei(n_wall, i => bg_ops[i])
scene.background_ops = Array::makei(bg_ops.length() - n_wall, i => bg_ops[n_wall + i])
scene.background_ops = if self.locked { [] } else { Array::makei(bg_ops.length() - n_wall, i => bg_ops[n_wall + i]) }
scene.panel_ops = panel_ops
let damaged = self.damage.take_damage(self.output_w, self.output_h).length() > 0
let sig : FrameSig = {
@@ -1964,6 +1993,8 @@ fn ChandraCompositor::run_shell_actions(self : ChandraCompositor) -> Unit {
self.frame_changed = true
self.damage.mark_full()
}
@shell.ShellAction::SetOskVisible(v) => self.osk_set_manual_visible(v)
@shell.ShellAction::SetRotation(r) => self.request_rotation(r)
@shell.ShellAction::SetLayout(m) =>
match m {
0 => self.set_layout_mode(@wm.LayoutMode::Tiling)
@@ -2231,11 +2262,10 @@ fn ChandraCompositor::handle_input_inner(
Key(116U, pressed) => {
if pressed {
if self.screen_off || self.manual_screen_off {
self.manual_screen_off = false
self.note_activity(@sys.monotonic_ms())
self.set_manual_screen_off(false)
} else {
self.manual_screen_off = true
self.stop_volume_repeat()
self.set_manual_screen_off(true)
}
}
return
@@ -2256,6 +2286,20 @@ fn ChandraCompositor::handle_input_inner(
}
if self.screen_off {
self.note_activity(@sys.monotonic_ms())
if self.locked {
self.request_unlock()
}
return
}
// Locked: input only reaches the unlock dialog (dispatch_input_inner -> grab_input -> auth).
// Before the dialog is up, swallow everything so nothing leaks to the desktop or apps, and
// take the chance to (re-)raise the prompt only on a key or button press (not hover or release).
if self.locked && self.auth is None {
self.note_activity(@sys.monotonic_ms())
match ev {
Key(_, true) | PointerButton(_, true) => self.request_unlock()
_ => ()
}
return
}
self.note_activity(@sys.monotonic_ms())
+39
View File
@@ -301,6 +301,7 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
"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",
"lock [lock|status|on-blank [on|off|status]] lock the session or configure lock-on-blank",
"brightness [PCT|status] read or set display backlight percent (5..100)",
"volume [up|down|mute|unmute|toggle|PCT|status] read or adjust audio volume",
"osk [on|off|toggle|status] enable, disable, or query the on-screen keyboard",
@@ -491,6 +492,44 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
_ => (["error usage: rotate [cw|ccw|flip|0|90|180|270|status]"], false)
}
}
"lock" => {
let arg = if words.length() >= 2 { words[1] } else { "lock" }
let usage = "error usage: lock [lock|status|on-blank [on|off|status]]"
match arg {
"status" =>
if words.length() > 2 {
([usage], false)
} else {
(["ok " + (if self.locked { "locked" } else { "unlocked" })], true)
}
"lock" =>
if words.length() > 2 {
([usage], false)
} else {
self.lock_now()
(["ok locked"], true)
}
"on-blank" => {
if words.length() > 3 {
return ([usage], false)
}
let sub = if words.length() >= 3 { words[2] } else { "status" }
match sub {
"status" => (["ok " + (if self.lock_on_blank { "on" } else { "off" })], true)
"on" => {
self.lock_on_blank = true
(["ok on"], true)
}
"off" => {
self.lock_on_blank = false
(["ok off"], true)
}
_ => ([usage], false)
}
}
_ => ([usage], false)
}
}
"screen" => {
let arg = if words.length() >= 2 { words[1] } else { "status" }
if words.length() > 2 {
+121
View File
@@ -0,0 +1,121 @@
///| Session lock (docs/lock.md): the compositor hides the desktop and only lets a face or
/// password bring it back. Locking is driven from the power button (when CHANDRA_LOCK=1 /
/// Settings turns on lock-on-blank) or `chandra-ctl lock`; unlocking reuses the password dialog.
///
/// The unlock check runs in chandra-polkit-agent as a real polkit authorization of the
/// `org.chandra.unlock` action (compositor/polkit/agent_loop.mbt): the agent asks polkit, polkit
/// drives the agent's own dialog, and because the `polkit-1` PAM stack carries
/// `pam_chandra_face.so` (docs/face-unlock.md) the camera is tried first, with the password as
/// the fallback. The compositor only sends `unlock` and waits for `unlocked`.
///
/// lock_now ──► request_unlock ──"unlock"──► agent ──► polkit ──► dialog (face, then password)
/// ▲ │
/// │ success: "unlocked" ───┘──► unlocked
/// └── power off / chandra-ctl lock cancel: "unlock-failed" ──► stay locked
///| Whether the session is locked right now.
pub fn ChandraCompositor::is_locked(self : ChandraCompositor) -> Bool {
self.locked
}
///| Lock the session: hide the desktop and demand a face or password to return. Safe to call
/// when already locked. If the screen is on, the unlock prompt comes up at once; if it is off
/// (locked at blank), it comes up when the power button wakes the screen.
pub fn ChandraCompositor::lock_now(self : ChandraCompositor) -> Unit {
if self.locked {
return
}
// Dismiss any unrelated auth prompt before locking the session.
if self.auth is Some(_) {
self.close_auth(true)
}
self.locked = true
self.unlock_pending = false
// Nothing on the desktop keeps the keyboard or the pointer while locked.
self.set_kbd_focus(None)
self.leave_pointer()
self.osk_manual_show = false
self.osk_sync()
self.damage.mark_full()
self.frame_changed = true
if !self.manual_screen_off && !self.screen_off {
self.request_unlock()
}
}
///| Ask the agent to run an unlock check. No-op if not locked, already asked, or no agent runs
/// (then the session simply stays locked until an agent is available and input re-raises it).
pub fn ChandraCompositor::request_unlock(self : ChandraCompositor) -> Unit {
if !self.locked || self.unlock_pending {
return
}
match self.auth_agent {
Some(l) => {
ignore(l.conn.send(["unlock"]))
self.unlock_pending = true
self.damage.mark_full()
self.frame_changed = true
}
None => ()
}
}
///| Cancel any active or pending unlock dialog (used when turning the screen off while locked).
pub fn ChandraCompositor::cancel_unlock(self : ChandraCompositor) -> Unit {
if self.auth is Some(_) {
self.close_auth(true)
}
if self.unlock_pending {
match self.auth_agent {
Some(l) => ignore(l.conn.send(["cancel-unlock"]))
None => ()
}
self.unlock_pending = false
self.damage.mark_full()
self.frame_changed = true
}
}
///| The agent said the unlock succeeded: return to the desktop.
pub fn ChandraCompositor::unlocked(self : ChandraCompositor) -> Unit {
if !self.locked {
return
}
self.locked = false
self.unlock_pending = false
self.note_activity(@sys.monotonic_ms())
self.damage.mark_full()
self.frame_changed = true
}
///| The unlock attempt ended without success (the user cancelled, or it failed): stay locked.
/// The prompt is raised again by the next key/button press or wake, not in a tight loop here.
pub fn ChandraCompositor::unlock_failed(self : ChandraCompositor) -> Unit {
self.unlock_pending = false
self.damage.mark_full()
self.frame_changed = true
}
///| Draw the locked-screen backdrop and idle prompt when no auth card is open.
fn ChandraCompositor::lock_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] {
let ops : Array[@scene.DrawOp] = []
if !self.locked {
return ops
}
let sw = self.output_w
let sh = self.output_h
let bg = @scene.Rgba::new(10, 12, 18, 225)
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, sh), bg, 0))
if self.auth is None {
let p = self.theme.palette
let fs = self.theme.font_size
let s = 44
let cx = sw / 2
let cy = sh / 2 - 20
lock_glyph(cx - s / 2, cy - s - 12, s, p.accent, bg, ops)
ops.push(@scene.DrawOp::Text(cx, cy + 8, "Screen locked", fs + 4, p.foreground, @scene.TextAlign::Center, true))
let sub = if self.unlock_pending { "Starting unlock…" } else { "Tap or press any key to unlock" }
ops.push(@scene.DrawOp::Text(cx, cy + 36, sub, fs - 1, p.foreground_muted, @scene.TextAlign::Center, false))
}
ops
}
+327
View File
@@ -0,0 +1,327 @@
///| Session lock (lock.mbt): the compositor state machine, the `lock` control command, power
/// button / `screen` blanking, lock-screen hiding/backdrop, input gating, and end-to-end
/// polkit `unix-process` unlock + cancel/power-off/agent-restart flows.
///| Whether any draw op renders `text`.
fn lock_has_text(ops : Array[@scene.DrawOp], text : String) -> Bool {
ops.iter().any(op => match op {
Text(_, _, t, _, _, _, _) | MonoText(_, _, t, _, _, _, _) => t == text
_ => false
})
}
///| Drain all lines currently queued on a test link.
fn lock_drain_lines(conn : @polkit.LineConn) -> Array[Array[String]] {
let out : Array[Array[String]] = []
for line in conn.read_lines() {
out.push(@polkit.decode_line(line))
}
out
}
///| 1. Control commands: `lock`, `lock status`, `lock on-blank [on|off|status]`, invalid args.
test "lock: chandra-ctl lock, status, and on-blank toggles" {
let comp = new_comp("lock-cmd")
assert_false(comp.is_locked())
assert_eq(comp.control_command("lock status").0, ["ok unlocked"])
assert_eq(comp.control_command("lock on-blank status").0, ["ok off"])
assert_eq(comp.control_command("lock on-blank").0, ["ok off"])
assert_eq(comp.control_command("lock on-blank on").0, ["ok on"])
assert_true(comp.lock_on_blank)
assert_eq(comp.control_command("lock on-blank status").0, ["ok on"])
assert_eq(comp.control_command("lock on-blank off").0, ["ok off"])
assert_false(comp.lock_on_blank)
let (out, ok) = comp.control_command("lock")
assert_true(ok)
assert_eq(out, ["ok locked"])
assert_true(comp.is_locked())
assert_eq(comp.control_command("lock status").0, ["ok locked"])
// Locking again while already locked is a harmless no-op.
assert_true(comp.control_command("lock lock").1)
assert_true(comp.is_locked())
comp.unlocked()
assert_false(comp.is_locked())
// Bad arguments are rejected.
assert_false(comp.control_command("lock bogus").1)
assert_false(comp.control_command("lock status extra").1)
assert_false(comp.control_command("lock on-blank maybe").1)
assert_false(comp.control_command("lock on-blank on extra").1)
comp.close()
}
///| 2. Power button and `screen off/on` consistency.
test "lock: power button and screen off/on respect lock_on_blank and wake locked" {
let comp = new_comp("lock-power")
// Off by default: blanking does not lock.
assert_false(comp.lock_on_blank)
comp.handle_input(@nested.InputEvent::Key(116U, true), 10U)
assert_true(comp.manual_screen_off)
assert_false(comp.is_locked())
comp.handle_input(@nested.InputEvent::Key(116U, true), 20U)
assert_false(comp.manual_screen_off)
assert_false(comp.is_locked())
// Enabled via on-blank: both power button and `screen off` lock, and waking requests unlock.
assert_eq(comp.control_command("lock on-blank on").0, ["ok on"])
comp.handle_input(@nested.InputEvent::Key(116U, true), 30U)
assert_true(comp.manual_screen_off)
assert_true(comp.is_locked())
comp.handle_input(@nested.InputEvent::Key(116U, true), 40U)
assert_false(comp.manual_screen_off)
assert_true(comp.is_locked())
comp.unlocked()
assert_false(comp.is_locked())
assert_eq(comp.control_command("screen off").0, ["ok off"])
assert_true(comp.manual_screen_off)
assert_true(comp.is_locked())
assert_eq(comp.control_command("screen on").0, ["ok on"])
assert_false(comp.manual_screen_off)
assert_true(comp.is_locked())
comp.close()
}
///| 3. Locked scene hides windows, popups, desktop widgets, and panel while drawing lock backdrop.
test "lock: locked scene hides desktop, windows, popups and panel behind lock backdrop" {
let sock = "/tmp/wayland-moon-lock-scene-" + @sys.getpid().to_string() + ".sock"
let theme = @scene.ThemeTokens::moon_night()
let comp = @host.ChandraCompositor::new(sock, theme, 1280, 720).unwrap()
let (c, shm, surf, xdg, _tl, _deco) = open_and_configure_client(comp, sock, "Secret Notes", "notes")
commit_shm_frame(comp, c, shm, surf, xdg, 1UL)
match comp.compose_scene() {
Some(unlocked_scene) => {
assert_true(unlocked_scene.windows.length() >= 1)
assert_true(unlocked_scene.panel_ops.length() > 0)
}
None => fail("expected initial unlocked scene")
}
comp.lock_now()
assert_true(comp.is_locked())
assert_true(comp.kbd_win is None)
match comp.compose_scene() {
Some(locked_scene) => {
assert_eq(locked_scene.windows.length(), 0)
assert_eq(locked_scene.popups.length(), 0)
assert_eq(locked_scene.background_ops.length(), 0)
assert_true(lock_has_text(locked_scene.panel_ops, "Screen locked"))
assert_true(lock_has_text(locked_scene.panel_ops, "Tap or press any key to unlock"))
}
None => fail("expected locked scene")
}
comp.close()
}
///| 4. Input gating when locked with no dialog open: only presses re-trigger unlock.
test "lock: pointer move and key release do not re-trigger unlock; key/button press does" {
let comp = new_comp("lock-input")
let (mine, theirs) = sock_pair("lock-input")
let peer = @polkit.LineConn::new(theirs)
comp.auth_agent = Some({
conn: @polkit.LineConn::new(mine),
demo: false,
ready: true,
error: "",
started: 0UL,
view: None,
})
comp.lock_now()
assert_true(comp.unlock_pending)
assert_eq(lock_drain_lines(peer), [["unlock"]])
// Simulate previous unlock attempt failed -> dialog dismissed, prompt hidden.
comp.unlock_failed()
assert_false(comp.unlock_pending)
// Pointer motion and releases must be swallowed WITHOUT sending `unlock`.
comp.handle_input(@nested.InputEvent::PointerMove(50.0, 60.0), 10U)
comp.handle_input(@nested.InputEvent::Key(28U, false), 11U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 12U)
assert_false(comp.unlock_pending)
assert_eq(lock_drain_lines(peer), [])
// Key press triggers unlock once.
comp.handle_input(@nested.InputEvent::Key(28U, true), 13U)
assert_true(comp.unlock_pending)
assert_eq(lock_drain_lines(peer), [["unlock"]])
// Simulate another failed attempt, then button press triggers unlock.
comp.unlock_failed()
assert_false(comp.unlock_pending)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 14U)
assert_true(comp.unlock_pending)
assert_eq(lock_drain_lines(peer), [["unlock"]])
peer.close()
comp.close()
}
///| 5. Demo agent cannot unlock a locked session.
test "lock: demo link unlocked message is ignored" {
let comp = new_comp("lock-demo-ignore")
let (mine, theirs) = sock_pair("lock-demo-ignore")
let peer = @polkit.LineConn::new(theirs)
comp.auth_demos.push({
conn: @polkit.LineConn::new(mine),
demo: true,
ready: true,
error: "",
started: 0UL,
view: None,
})
comp.lock_now()
assert_true(comp.is_locked())
ignore(peer.send(["unlocked"]))
comp.step()
assert_true(comp.is_locked())
peer.close()
comp.close()
}
///| 6. End-to-end lock -> unix-process CheckAuthorization -> password & face unlock -> desktop restored.
test "lock: e2e unlock through mock polkitd (unix-process) succeeds and restores desktop" {
let bus = match auth_bus("lock-e2e") {
Some(b) => b
None => return
}
let (hpath, listen) = helper_socket("lock-e2e")
let r = rig("lock-e2e", Some(bus), hpath)
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let a = r.authority()
r.comp.lock_now()
assert_true(r.comp.is_locked())
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.phase == Asking || v.phase == Starting).unwrap_or(false) }))
assert_eq(a.check_subjects.length(), 1)
match a.check_subjects[0] {
Struct([Str(kind), _]) => assert_eq(kind, "unix-process")
_ => fail("expected unix-process subject")
}
assert_eq(r.view().title, "Screen locked")
let (h, _) = r.helper_accept(listen)
helper_say(h, "PAM_TEXT_INFO Face unlock: looking for nandi…")
helper_say(h, "PAM_TEXT_INFO Face unlock: recognized nandi")
helper_say(h, "SUCCESS")
assert_true(r.settle(fn() { !r.comp.is_locked() && r.comp.auth_view() is None }))
assert_false(r.comp.unlock_pending)
@sys.close_fd(h)
@sys.close_fd(listen)
@sys.unlink(hpath)
r.comp.close()
}
///| 7. Cancel unlock stays locked, ignores pointer release, then tap re-prompts and succeeds.
test "lock: cancelling unlock keeps session locked until next tap raises it again" {
let bus = match auth_bus("lock-cancel") {
Some(b) => b
None => return
}
let (hpath, listen) = helper_socket("lock-cancel")
let r = rig("lock-cancel", Some(bus), hpath)
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let a = r.authority()
r.comp.lock_now()
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let (h1, _) = r.helper_accept(listen)
helper_say(h1, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.phase == Asking).unwrap_or(false) }))
// Dismiss via Cancel button -> agent says unlock-failed -> session stays locked.
auth_click(r.comp, Cancel)
assert_true(r.settle(fn() { r.comp.auth_view() is None && !r.comp.unlock_pending && a.answers.length() == 1 }))
assert_true(r.comp.is_locked())
@sys.close_fd(h1)
// Moving pointer / releasing does not immediately re-open the dialog.
r.comp.handle_input(@nested.InputEvent::PointerMove(20.0, 20.0), 10U)
r.comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 11U)
r.pass()
assert_false(r.comp.unlock_pending)
assert_true(r.comp.auth_view() is None)
// Tapping wakes a new unlock attempt and succeeds.
r.comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 12U)
r.comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 13U)
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let (h2, _) = r.helper_accept(listen)
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.phase == Asking).unwrap_or(false) }))
auth_type(r.comp, "Right1")
auth_press(r.comp, 28U)
assert_true(r.settle(fn() { r.comp.auth_view().map(v => v.phase == Checking).unwrap_or(false) }))
assert_eq(helper_lines(h2, 1), "Right1")
helper_say(h2, "SUCCESS")
assert_true(r.settle(fn() { !r.comp.is_locked() && r.comp.auth_view() is None }))
@sys.close_fd(h2)
@sys.close_fd(listen)
@sys.unlink(hpath)
r.comp.close()
}
///| 8. Power off while unlock is in-flight cancels CheckAuthorization and re-prompts cleanly on wake.
test "lock: power off cancels in-flight unlock via CancelCheckAuthorization" {
let bus = match auth_bus("lock-pwrcancel") {
Some(b) => b
None => return
}
let (hpath, listen) = helper_socket("lock-pwrcancel")
let r = rig("lock-pwrcancel", Some(bus), hpath)
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
let a = r.authority()
r.comp.lock_now()
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let (h1, _) = r.helper_accept(listen)
// Power button blanks screen -> cancels unlock & calls CancelCheckAuthorization.
r.comp.handle_input(@nested.InputEvent::Key(116U, true), 20U)
assert_true(r.comp.manual_screen_off)
assert_true(r.comp.is_locked())
assert_false(r.comp.unlock_pending)
assert_true(r.settle(fn() { a.cancelled_ids.length() == 1 && r.comp.auth_view() is None }))
@sys.close_fd(h1)
// Wake screen -> starts fresh unlock request cleanly.
r.comp.handle_input(@nested.InputEvent::Key(116U, true), 30U)
assert_false(r.comp.manual_screen_off)
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let (h2, _) = r.helper_accept(listen)
helper_say(h2, "SUCCESS")
assert_true(r.settle(fn() { !r.comp.is_locked() && r.comp.auth_view() is None }))
@sys.close_fd(h2)
@sys.close_fd(listen)
@sys.unlink(hpath)
r.comp.close()
}
///| 9. Agent disconnect/restart while locked clears unlock_pending and re-requests on ready.
test "lock: agent drop clears unlock_pending and restarted agent resumes unlock on ready" {
let bus = match auth_bus("lock-restart") {
Some(b) => b
None => return
}
let (hpath, listen) = helper_socket("lock-restart")
let r = rig("lock-restart", Some(bus), hpath)
r.comp.start_auth_agent()
assert_true(r.settle(fn() { r.ready() }))
r.comp.lock_now()
assert_true(r.settle(fn() { r.comp.auth_view() is Some(_) }))
let (h1, _) = r.helper_accept(listen)
// Drop the first agent while locked -> auth_tick clears unlock_pending and restarts a new agent.
r.agents[0].shutdown()
assert_true(r.settle(fn() { r.agents.length() >= 2 && r.comp.auth_view() is Some(_) }))
@sys.close_fd(h1)
let (h2, _) = r.helper_accept(listen)
helper_say(h2, "SUCCESS")
assert_true(r.settle(fn() { !r.comp.is_locked() && r.comp.auth_view() is None }))
@sys.close_fd(h2)
@sys.close_fd(listen)
@sys.unlink(hpath)
r.comp.close()
}
+42 -136
View File
@@ -95,9 +95,9 @@ pub fn ChandraCompositor::osk_key_center(self : ChandraCompositor, label : Strin
None
}
///| Room kept below the keyboard for the panel (none in a strict kiosk, which has no panel).
///| Room kept below the keyboard for the panel (none in a strict kiosk or locked session, which have no panel).
fn ChandraCompositor::osk_panel_room(self : ChandraCompositor) -> Int {
if self.kiosk_strict() { 0 } else { self.theme.panel_height }
if self.kiosk_strict() || self.locked { 0 } else { self.theme.panel_height }
}
///| Height of the on-screen keyboard when shown.
@@ -121,26 +121,10 @@ pub fn ChandraCompositor::osk_rect(self : ChandraCompositor) -> @scene.Rect {
@scene.Rect::new(0, self.output_h - self.osk_panel_room() - h, self.output_w, h)
}
///| Compact "KB" pill above the bottom-right corner of the panel when the OSK is enabled but
/// currently hidden, letting users summon the keyboard anywhere manually.
pub fn ChandraCompositor::osk_toggle_rect(self : ChandraCompositor) -> @scene.Rect {
let w = 44
let h = 28
let x = (self.output_w - w - 6).max(4)
let y = (self.output_h - self.theme.panel_height - h - 6).max(4)
@scene.Rect::new(x, y, w, h)
}
///| Compact "Rot" pill beside the "KB" pill: tap rotates 90 deg CW, long-press/right-click flips 180 deg.
pub fn ChandraCompositor::osk_rotate_rect(self : ChandraCompositor) -> @scene.Rect {
let kb = self.osk_toggle_rect()
let w = 44
@scene.Rect::new((kb.x - w - 6).max(4), kb.y, w, kb.h)
}
///| Show or hide the OSK, resizing `work_area` and lifting panel popups so focused content stays
/// above the keyboard.
fn ChandraCompositor::osk_set_visible(self : ChandraCompositor, want : Bool) -> Unit {
self.shell.osk_visible = want
if self.osk_visible == want {
return
}
@@ -160,17 +144,32 @@ fn ChandraCompositor::osk_set_visible(self : ChandraCompositor, want : Bool) ->
}
}
///| Manually show or hide the OSK (called by the Keyboard panel module).
pub fn ChandraCompositor::osk_set_manual_visible(self : ChandraCompositor, want : Bool) -> Unit {
if want {
self.osk_manual_hide = false
self.osk_manual_show = true
self.osk_sync()
} else {
self.osk_manual_hide = true
self.osk_manual_show = false
self.osk_set_visible(false)
}
self.damage.mark_full()
}
///| Synchronize OSK visibility with the active focus target (auth dialog, emoji picker, open
/// shell popup, active text-input-v3 or terminal window).
pub fn ChandraCompositor::osk_sync(self : ChandraCompositor) -> Unit {
if !self.osk_enabled {
if self.osk_visible {
self.osk_set_visible(false)
}
let want = self.osk_manual_show && !self.osk_manual_hide && !(self.locked && self.auth is None)
self.osk_set_visible(want)
return
}
let (target, auto_want) : (String, Bool) = if self.auth is Some(_) {
("auth", true)
} else if self.locked {
("locked", false)
} else if self.emoji_ui is Some(_) {
("emoji", true)
} else if self.shell.popup_open() {
@@ -223,7 +222,10 @@ fn ChandraCompositor::osk_on_shell_click(self : ChandraCompositor, xi : Int, yi
}
let mid = self.shell.open_popup_module_id()
if mid == "launcher" {
self.osk_manual_hide = false
match self.shell.open_popup_rect() {
Some(r) if r.contains(xi, yi) => self.osk_manual_hide = false
_ => ()
}
} else if mid == "network" {
match self.shell.open_popup_rect() {
Some(r) if r.contains(xi, yi) => {
@@ -449,17 +451,9 @@ fn ChandraCompositor::osk_key_at(self : ChandraCompositor, x : Int, y : Int) ->
None
}
///| Whether `(x, y)` hits either the open OSK or its compact corner pills ("Rot" / "KB").
///| Whether `(x, y)` hits the open OSK.
fn ChandraCompositor::osk_hit_any(self : ChandraCompositor, x : Int, y : Int) -> Bool {
if !self.osk_enabled {
return false
}
if self.osk_visible {
self.osk_rect().contains(x, y)
} else {
!self.kiosk_strict() &&
(self.osk_toggle_rect().contains(x, y) || self.osk_rotate_rect().contains(x, y))
}
self.osk_visible && self.osk_rect().contains(x, y)
}
///| Route one virtual key press+release to the active target (auth dialog, emoji picker, open
@@ -569,13 +563,13 @@ fn ChandraCompositor::osk_activate_key(
self.damage.mark_full()
}
///| Handle host input when over the OSK or its toggle pill. True if consumed.
///| Handle host input when over the visible OSK. True if consumed.
fn ChandraCompositor::osk_input(
self : ChandraCompositor,
ev : @nested.InputEvent,
time_ms : UInt,
) -> Bool {
if !self.osk_enabled {
if !self.osk_visible {
return false
}
match ev {
@@ -584,46 +578,17 @@ fn ChandraCompositor::osk_input(
self.ptr_y = y
let xi = x.to_int()
let yi = y.to_int()
if self.osk_visible {
if self.osk_pointer_grab || self.osk_rect().contains(xi, yi) {
let h = self.osk_key_at(xi, yi)
if h != self.osk_hover {
self.osk_hover = h
self.damage.mark_full()
}
return true
}
if self.osk_hover is Some(_) {
self.osk_hover = None
if self.osk_pointer_grab || self.osk_rect().contains(xi, yi) {
let h = self.osk_key_at(xi, yi)
if h != self.osk_hover {
self.osk_hover = h
self.damage.mark_full()
}
return false
return true
}
if !self.kiosk_strict() {
let hover = if self.osk_toggle_rect().contains(xi, yi) {
Some(-1)
} else if self.osk_rotate_rect().contains(xi, yi) {
Some(-2)
} else {
None
}
match hover {
Some(id) => {
if self.osk_hover != Some(id) {
self.osk_hover = Some(id)
self.damage.mark_full()
}
return true
}
None =>
if self.osk_hover == Some(-1) || self.osk_hover == Some(-2) {
self.osk_hover = None
self.damage.mark_full()
}
}
if self.osk_pointer_grab {
return true
}
if self.osk_hover is Some(_) {
self.osk_hover = None
self.damage.mark_full()
}
false
}
@@ -636,18 +601,8 @@ fn ChandraCompositor::osk_input(
self.osk_pressed = None
self.damage.mark_full()
match idx_opt {
Some(-1) =>
if !self.osk_visible && !self.kiosk_strict() && self.osk_toggle_rect().contains(xi, yi) {
self.osk_manual_hide = false
self.osk_manual_show = true
self.osk_sync()
}
Some(-2) =>
if !self.osk_visible && !self.kiosk_strict() && self.osk_rotate_rect().contains(xi, yi) {
self.rotate_cw()
}
Some(idx) =>
if self.osk_visible && self.osk_key_at(xi, yi) == Some(idx) {
if self.osk_key_at(xi, yi) == Some(idx) {
self.osk_activate_key(idx, time_ms)
self.osk_sync()
}
@@ -655,7 +610,7 @@ fn ChandraCompositor::osk_input(
}
return true
}
if self.osk_visible && self.osk_rect().contains(xi, yi) {
if self.osk_rect().contains(xi, yi) {
if button == 272U && pressed {
self.osk_pointer_grab = true
self.osk_pressed = self.osk_key_at(xi, yi)
@@ -663,75 +618,26 @@ fn ChandraCompositor::osk_input(
}
return true
}
if !self.osk_visible && !self.kiosk_strict() {
let pill = if self.osk_toggle_rect().contains(xi, yi) {
Some(-1)
} else if self.osk_rotate_rect().contains(xi, yi) {
Some(-2)
} else {
None
}
match pill {
Some(id) => {
if pressed {
if button == 272U {
self.osk_pointer_grab = true
self.osk_pressed = Some(id)
self.damage.mark_full()
} else if button == 273U && id == -2 {
// Long-press / right-click on Rot flips 180 degrees.
self.rotate_flip()
}
}
return true
}
None => ()
}
}
false
}
Scroll(_, _, _) => {
let xi = self.ptr_x.to_int()
let yi = self.ptr_y.to_int()
if (self.osk_visible && self.osk_rect().contains(xi, yi)) || self.osk_pointer_grab {
return true
}
false
self.osk_rect().contains(xi, yi) || self.osk_pointer_grab
}
_ => false
}
}
///| Draw the OSK or its compact summon pill when enabled.
///| Draw the OSK when visible.
fn ChandraCompositor::osk_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] {
let ops : Array[@scene.DrawOp] = []
if !self.osk_enabled {
if !self.osk_visible {
return ops
}
let pal = self.theme.palette
let fs = self.theme.font_size
let rad = self.theme.radius
if !self.osk_visible {
if self.kiosk_strict() {
return ops
}
let pills = [(self.osk_rotate_rect(), -2, "Rot"), (self.osk_toggle_rect(), -1, "KB")]
for pill in pills {
let (tr, id, label) = pill
let bg = if self.osk_pressed == Some(id) {
pal.accent
} else if self.osk_hover == Some(id) {
pal.surface_hover
} else {
@scene.Rgba::new(pal.surface_popup.r.to_int(), pal.surface_popup.g.to_int(), pal.surface_popup.b.to_int(), 230)
}
let fg = if self.osk_pressed == Some(id) { pal.accent_foreground } else { pal.foreground }
ops.push(@scene.DrawOp::FillRect(tr, bg, rad + 4))
ops.push(@scene.DrawOp::StrokeRect(tr, pal.border, 1, rad + 4))
ops.push(@scene.DrawOp::Text(tr.x + tr.w / 2, tr.y + tr.h / 2, label, (fs - 2).max(10), fg, @scene.TextAlign::Center, true))
}
return ops
}
let r = self.osk_rect()
let panel_bg = @scene.Rgba::new(pal.surface_popup.r.to_int(), pal.surface_popup.g.to_int(), pal.surface_popup.b.to_int(), 248)
ops.push(@scene.DrawOp::FillRect(r, panel_bg, 0))
+130 -19
View File
@@ -12,6 +12,20 @@ fn osk_comp(tag : String, enable_osk? : Bool = true) -> @host.ChandraCompositor
comp
}
///| Replace the panel with the compact 9-module handset set (`rotate` and `osk` included).
fn load_handset_modules(comp : @host.ChandraCompositor) -> Unit raise {
for slot in comp.shell.slots() {
ignore(comp.shell.unload_slot(slot))
}
for id in [
"launcher", "dock", "session-settings", "network", "battery", "clock-digital", "screenshot",
"rotate", "osk",
] {
assert_true(comp.shell.load_module(id))
}
ignore(comp.compose_frame())
}
///|
test "OSK stays disabled under CHANDRA_TEST_CONFIG=1 unless explicitly enabled" {
let socket_path = "/tmp/wayland-moon-osk-disabled-" + @sys.getpid().to_string() + ".sock"
@@ -89,10 +103,15 @@ test "OSK delivers evdev keys and one-shot Shift modifier to focused Wayland cli
}
///|
test "OSK Hide button dismisses keyboard and KB pill or client tap reopens it" {
test "OSK Hide button dismisses keyboard and KB panel module or client tap reopens it" {
let socket_path = "/tmp/wayland-moon-osk-hide-" + @sys.getpid().to_string() + ".sock"
let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 540, 1170).unwrap()
comp.set_osk_enabled(true)
ignore(comp.compose_frame())
load_handset_modules(comp)
let kr = rect_of(comp, "osk")
assert_true(kr.w > 0 && kr.y >= comp.output_h - comp.theme.panel_height)
let (a, shm_a, surf_a, xdg_a, _, _) = open_and_configure_client(comp, socket_path, "Notes", "notes")
commit_shm_frame(comp, a, shm_a, surf_a, xdg_a, 1UL)
let (ti, _) = text_input_for(comp, a)
@@ -104,15 +123,24 @@ test "OSK Hide button dismisses keyboard and KB pill or client tap reopens it" {
click_at(comp, hx, hy, 20U)
assert_false(comp.osk_is_visible())
// Tapping the compact "KB" toggle pill reopens it.
let tr = comp.osk_toggle_rect()
click_at(comp, tr.x + tr.w / 2, tr.y + tr.h / 2, 30U)
assert_true(comp.osk_is_visible())
// No floating "KB" or "Rot" pills are drawn above the panel when hidden.
comp.damage.mark_full()
let scene = comp.compose_scene().unwrap()
for op in scene.panel_ops {
match op {
@scene.DrawOp::Text(_, y, text, _, _, _, _) if text == "KB" || text == "Rot" =>
assert_true(y >= comp.output_h - comp.theme.panel_height)
_ => ()
}
}
// Hide again, then tap inside the client window with active text input -> reopens.
let (hx2, hy2) = comp.osk_key_center("Hide").unwrap()
click_at(comp, hx2, hy2, 40U)
// Tapping the "KB" panel module reopens the keyboard, and tapping it again hides it.
click_module(comp, "osk", 30U)
assert_true(comp.osk_is_visible())
click_module(comp, "osk", 35U)
assert_false(comp.osk_is_visible())
// Tap inside the client window with active text input -> reopens.
let g = comp.windows.get(1UL).unwrap().geometry
click_at(comp, g.x + g.w / 2, g.y + g.h / 2, 50U)
assert_true(comp.osk_is_visible())
@@ -160,24 +188,24 @@ test "OSK reaches the bottom edge in a strict kiosk, which has no panel" {
}
///|
test "Rot pill tap rotates CW, right-click flips 180 deg, and rotate control commands update size" {
test "Rotate panel module rotates CW and rotate control commands update size" {
let comp = osk_comp("rotate")
let rr = comp.osk_rotate_rect()
let rx = rr.x + rr.w / 2
let ry = rr.y + rr.h / 2
load_handset_modules(comp)
let rr = rect_of(comp, "rotate")
assert_true(rr.w > 0 && rr.y >= comp.output_h - comp.theme.panel_height)
// Tap Rot pill -> queues 90 deg CW rotation.
click_at(comp, rx, ry, 10U)
// Tap Rotate panel module -> queues 90 deg CW rotation.
click_module(comp, "rotate", 10U)
assert_eq(comp.take_pending_rotation(), Some(1))
assert_eq(comp.current_rotation(), 1)
comp.apply_rotated_size(1170, 540)
assert_eq((comp.output_w, comp.output_h), (1170, 540))
// Right-click / long-press Rot pill -> queues 180 deg flip (1 -> 3 = 270 deg).
let rr2 = comp.osk_rotate_rect()
click_at(comp, rr2.x + rr2.w / 2, rr2.y + rr2.h / 2, 20U, btn=273U)
assert_eq(comp.take_pending_rotation(), Some(3))
assert_eq(comp.current_rotation(), 3)
// Tap Rotate panel module again -> queues 180 deg rotation.
click_module(comp, "rotate", 20U)
assert_eq(comp.take_pending_rotation(), Some(2))
assert_eq(comp.current_rotation(), 2)
comp.apply_rotated_size(540, 1170)
// chandra-ctl rotate 0 / flip / status.
let (out0, ok0) = comp.control_command("rotate 0")
@@ -198,3 +226,86 @@ test "Rot pill tap rotates CW, right-click flips 180 deg, and rotate control com
assert_eq(out_st, ["ok 180 540x1170"])
comp.close()
}
///|
test "handset panel loads all 9 modules including rotate and osk inside 540px width" {
let comp = osk_comp("handset-fit")
load_handset_modules(comp)
let ids = comp.shell.loaded_modules().filter(m => m.0 != "desktop").map(m => m.1)
assert_eq(ids, [
"launcher", "dock", "session-settings", "network", "battery", "clock-digital", "screenshot",
"rotate", "osk",
])
for id in ids {
let r = rect_of(comp, id)
assert_true(r.w > 0 && r.x >= 0 && r.x + r.w <= comp.output_w)
assert_true(r.y >= comp.output_h - comp.theme.panel_height)
}
comp.damage.mark_full()
let scene = comp.compose_scene().unwrap()
for op in scene.panel_ops {
match op {
@scene.DrawOp::Text(_, y, text, _, _, _, _) if text == "KB" || text == "Rot" =>
assert_true(y >= comp.output_h - comp.theme.panel_height)
_ => ()
}
}
comp.close()
}
///|
test "KB panel module toggles OSK manually even when auto-OSK is disabled" {
let socket_path = "/tmp/wayland-moon-osk-manual-" + @sys.getpid().to_string() + ".sock"
let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 540, 1170).unwrap()
ignore(comp.compose_frame())
load_handset_modules(comp)
let (a, shm_a, surf_a, xdg_a, _, _) = open_and_configure_client(comp, socket_path, "Notes", "notes")
commit_shm_frame(comp, a, shm_a, surf_a, xdg_a, 1UL)
let (ti, kbd) = text_input_for(comp, a)
text_input_state(comp, a, ti, true, 50, 50, 16)
// Auto-OSK is off, so text-input-v3 does not pop it open on its own.
assert_false(comp.osk_is_visible())
ignore(drain_args(a))
// Clicking the KB panel module opens the OSK manually and typing reaches the client.
click_module(comp, "osk", 20U)
assert_true(comp.osk_is_visible())
let (ax, ay) = comp.osk_key_center("a").unwrap()
click_at(comp, ax, ay, 30U)
let keys = drain_args(a).filter(m => m.0 == kbd && m.1 == 3U)
assert_eq(keys.length(), 2)
assert_eq((keys[0].2[2], keys[0].2[3]), (30U, 1U))
// Clicking KB again closes the manually opened OSK.
click_module(comp, "osk", 40U)
assert_false(comp.osk_is_visible())
comp.close()
}
///|
test "clicking KB or Rotate panel modules keeps the launcher popup open" {
let comp = osk_comp("launcher-keep")
load_handset_modules(comp)
click_module(comp, "launcher", 10U)
assert_true(comp.shell.popup_open())
assert_true(comp.osk_is_visible())
let (hx, hy) = comp.osk_key_center("Hide").unwrap()
click_at(comp, hx, hy, 20U)
assert_false(comp.osk_is_visible())
assert_true(comp.shell.popup_open())
// Tapping Rotate leaves the Launcher popup open and does not accidentally reopen the OSK.
click_module(comp, "rotate", 30U)
assert_true(comp.shell.popup_open())
assert_false(comp.osk_is_visible())
assert_eq(comp.take_pending_rotation(), Some(1))
// Tapping KB opens the OSK while keeping the Launcher popup open above it.
click_module(comp, "osk", 40U)
assert_true(comp.shell.popup_open())
assert_true(comp.osk_is_visible())
let pr = comp.shell.open_popup_rect().unwrap()
assert_true(pr.y + pr.h <= comp.osk_rect().y)
comp.close()
}
+10 -1
View File
@@ -27,8 +27,17 @@ pub fn ChandraCompositor::set_manual_screen_off(
off : Bool,
) -> Unit {
self.manual_screen_off = off
if !off {
if off {
if self.locked {
self.cancel_unlock()
} else if self.lock_on_blank {
self.lock_now()
}
} else {
self.note_activity(@sys.monotonic_ms())
if self.locked {
self.request_unlock()
}
}
}
+109
View File
@@ -277,6 +277,115 @@ pub fn PolkitAgent::registered(self : PolkitAgent) -> Bool {
self.registered
}
///| Parse an unsigned 64-bit decimal integer (returns None if empty, >20 chars, or non-digit).
fn parse_u64(s : String) -> UInt64? {
if s.length() == 0 || s.length() > 20 {
return None
}
let mut v = 0UL
for c in s {
if c < '0' || c > '9' {
return None
}
v = v * 10UL + (c.to_int() - '0'.to_int()).to_uint64()
}
Some(v)
}
///| Build a polkit `unix-process` subject from `/proc/<pid>/stat` and `/proc/<pid>/status` text.
pub fn process_subject_for(pid : Int, stat : String, status : String) -> @network.DValue {
let start_time = match stat.rev_find(")") {
Some(i) => {
let parts = stat[i + 1:].to_string().trim(chars=" \t\n").to_string().split(" ").map(v => v.to_string()).filter(v => v != "").to_array()
if parts.length() > 19 {
parse_u64(parts[19]).unwrap_or(0UL)
} else {
0UL
}
}
None => 0UL
}
let uid = uid_from_status(status)
Struct([
Str("unix-process"),
@network.dict("v", [
("pid", Variant(U32(pid.reinterpret_as_uint()))),
("start-time", Variant(U64(start_time))),
("uid", Variant(I32(uid))),
]),
])
}
///| The polkit subject representing the current agent process (`unix-process`).
fn process_subject() -> @network.DValue {
let pid = @sys.getpid()
let stat = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/stat"))
let status = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/status"))
process_subject_for(pid, stat, status)
}
///| Ask polkit to authorize `action_id` for the agent process, allowing user interaction: polkit
/// then drives this same agent's dialog (face via PAM, then password), and the reply says whether
/// it succeeded. Used for session unlock (org.chandra.unlock). False before registration or without a bus.
pub fn PolkitAgent::check_unlock(
self : PolkitAgent,
action_id : String,
cancel_id : String,
on_result : (Bool) -> Unit,
) -> Bool {
if !self.registered {
return false
}
match self.bus {
Some(bus) => {
let serial = bus.call(
@network.DMessage::call(authority_name, authority_path, authority_iface, "CheckAuthorization", [
process_subject(),
Str(action_id),
@network.dict("s", []),
U32(1U), // AllowUserInteraction
Str(cancel_id),
]),
on_reply=fn(m) {
let ok = match m {
{ mtype: 2, body: [Struct([Bool(a), ..]), ..], .. } => a
{ mtype: 2, .. } => {
alog("unlock: unexpected CheckAuthorization reply")
false
}
_ => {
alog("unlock: CheckAuthorization error: " + m.error_text())
false
}
}
on_result(ok)
},
)
serial != 0
}
None => false
}
}
///| Cancel an in-flight CheckAuthorization call identified by `cancel_id`.
pub fn PolkitAgent::cancel_unlock(self : PolkitAgent, cancel_id : String) -> Unit {
if cancel_id == "" {
return
}
match self.bus {
Some(bus) =>
ignore(
bus.call(
@network.DMessage::call(authority_name, authority_path, authority_iface, "CancelCheckAuthorization", [
Str(cancel_id),
]),
on_reply=fn(_) { () },
),
)
None => ()
}
}
///| Why the last start failed ("" when it didn't).
pub fn PolkitAgent::error(self : PolkitAgent) -> String {
self.error
+80
View File
@@ -28,6 +28,12 @@ pub struct AgentLoop {
mut id : String
mut next_id : Int
mut was_registered : Bool
/// An unlock authorization (org.chandra.unlock) is out to polkit; ignore further `unlock`s.
mut unlocking : Bool
/// Cancellation id passed to polkit's CheckAuthorization / CancelCheckAuthorization.
mut unlock_cancel_id : String
/// Monotonic counter so stale CheckAuthorization replies after cancel are ignored.
mut unlock_seq : Int
/// Done: the main loop exits.
mut finished : Bool
}
@@ -56,6 +62,9 @@ pub fn AgentLoop::new(
id: "",
next_id: 1,
was_registered: false,
unlocking: false,
unlock_cancel_id: "",
unlock_seq: 0,
finished: false,
}
}
@@ -73,6 +82,9 @@ pub fn AgentLoop::new_demo(link_fd : Int, mode : String) -> AgentLoop {
id: "",
next_id: 1,
was_registered: false,
unlocking: false,
unlock_cancel_id: "",
unlock_seq: 0,
finished: false,
}
}
@@ -160,10 +172,78 @@ fn AgentLoop::close_request(self : AgentLoop, result : Result[Unit, String]?) ->
}
}
///| Unlock the session: ask polkit to authorize org.chandra.unlock. polkit drives this agent's
/// dialog (face via the polkit-1 PAM stack, then password); the reply tells the compositor
/// `unlocked` or `unlock-failed`. Without polkit (demo) there is nothing to check.
fn AgentLoop::begin_unlock(self : AgentLoop) -> Unit {
match self.polkit {
Some(p) => {
if self.unlocking {
return
}
self.unlock_seq = self.unlock_seq + 1
let seq = self.unlock_seq
let cid = "chandra-unlock-" + seq.to_string()
self.unlocking = true
self.unlock_cancel_id = cid
let started = p.check_unlock("org.chandra.unlock", cid, fn(ok) {
if self.unlock_seq != seq {
return
}
self.unlocking = false
self.unlock_cancel_id = ""
ignore(self.link.send([if ok { "unlocked" } else { "unlock-failed" }]))
})
if !started {
self.unlocking = false
self.unlock_cancel_id = ""
alog("unlock: polkit is not ready")
ignore(self.link.send(["unlock-failed"]))
}
}
None => ignore(self.link.send(["unlock-failed"]))
}
}
///| Cancel an in-flight unlock authorization (e.g., screen blanked again before completion).
fn AgentLoop::cancel_unlock(self : AgentLoop) -> Unit {
if !self.unlocking {
return
}
let cid = self.unlock_cancel_id
self.unlock_seq = self.unlock_seq + 1
self.unlocking = false
self.unlock_cancel_id = ""
match self.machine {
Some(m) if m.req.action_id == "org.chandra.unlock" =>
self.close_request(Some(Err("The unlock request was cancelled")))
_ => ()
}
match self.polkit {
Some(p) => p.cancel_unlock(cid)
None => ()
}
}
///| A message from the compositor.
fn AgentLoop::on_link(self : AgentLoop, line : FixedArray[Byte]) -> Unit {
let f = split_fields(line)
zero(line)
// Session unlock (lock.mbt) is a one-field message, independent of any request/dialog id.
if f.length() >= 1 && field_text(f[0]) == "unlock" {
for b in f {
zero(b)
}
self.begin_unlock()
return
}
if f.length() >= 1 && field_text(f[0]) == "cancel-unlock" {
for b in f {
zero(b)
}
self.cancel_unlock()
return
}
if f.length() < 2 {
return
}
+11
View File
@@ -234,6 +234,17 @@ pub fn describe(req : AuthRequest, cmdline? : (Int) -> Array[String] = proc_cmdl
details,
}
}
// Session unlock: clear lock-screen wording instead of the generic system-action fallback.
if req.action_id == "org.chandra.unlock" {
add("Action", req.action_id)
return {
title: "Screen locked",
subtitle: "Look at the camera or enter your password to unlock.",
command: "",
program: "",
details,
}
}
// Anything else: polkit's message is the best we have.
add("Requested by", who(if subject > 0 { subject } else { caller }))
add("Unit", req.detail("unit"))
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<!--
Session unlock for Chandra (docs/lock.md). The compositor locks the session (power button,
or `chandra-ctl lock`) and asks its polkit agent to authorize this action to unlock. Because
it is auth_self (never _keep), polkit prompts every time, and the polkit-1 PAM stack runs the
camera first (pam_chandra_face.so) with the password as the fallback.
-->
<policyconfig>
<vendor>Chandra</vendor>
<action id="org.chandra.unlock">
<description>Unlock the session</description>
<message>Authenticate to unlock the screen</message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>auth_self</allow_active>
</defaults>
</action>
</policyconfig>
+35
View File
@@ -594,3 +594,38 @@ test "face unlock: Chandra's and Howdy's PAM messages" {
assert_eq(@polkit.face_message("Place your finger on the fingerprint reader", false), None)
assert_eq(@polkit.face_message("The account is locked due to 3 failed logins.", true), None)
}
///|
test "process_subject_for parses /proc/<pid>/stat with spaces/parens and /proc/<pid>/status Uid" {
let stat = "4210 (chandra (polkit) agent) S 1 4210 4210 0 -1 4194304 100 0 0 0 1 0 0 0 20 0 1 0 987654321 12345 100"
let status = "Name:\tchandra-polkit\nState:\tS (sleeping)\nUid:\t1000\t1000\t1000\t1000\nGid:\t1000\t1000\t1000\t1000\n"
let subj = @polkit.process_subject_for(4210, stat, status)
assert_eq(
subj,
@network.DValue::Struct([
Str("unix-process"),
@network.dict("v", [
("pid", Variant(U32(4210U))),
("start-time", Variant(U64(987654321UL))),
("uid", Variant(I32(1000))),
]),
]),
)
}
///|
test "describe: org.chandra.unlock uses clear lock-screen wording" {
let req : @polkit.AuthRequest = {
action_id: "org.chandra.unlock",
message: "Authenticate to unlock the screen",
icon_name: "",
details: {},
cookie: "c-unlock",
users: [{ uid: 1000, name: "nandi", real_name: "Nandi" }],
}
let desc = @polkit.describe(req, cmdline=_ => [], who=_ => "")
assert_eq(desc.title, "Screen locked")
assert_eq(desc.subtitle, "Look at the camera or enter your password to unlock.")
assert_eq(desc.command, "")
assert_eq(desc.details, [("Action", "org.chandra.unlock")])
}
+10 -5
View File
@@ -172,21 +172,26 @@ pub fn string_dict(v : @network.DValue) -> Map[String, String] {
out
}
///| Our uid, from /proc/self/status ("Uid:\treal\teffective..."); -1 when unknown.
pub fn own_uid() -> Int {
let text = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/self/status"))
///| Parse real UID from `/proc/<pid>/status` ("Uid:\treal\teffective..."); -1 when unknown.
pub fn uid_from_status(text : String) -> Int {
for line in text.split("\n") {
let l = line.to_string()
if l.has_prefix("Uid:") {
let parts = l[4:].to_string().trim(chars=" \t").to_string().split("\t").to_array()
let rest = l[4:].to_string().replace_all(old="\t", new=" ")
let parts = rest.split(" ").map(v => v.to_string()).filter(v => v != "").to_array()
if parts.length() > 0 {
return parse_uint(parts[0].to_string().trim(chars=" ").to_string()).unwrap_or(-1)
return parse_uint(parts[0]).unwrap_or(-1)
}
}
}
-1
}
///| Our uid, from /proc/self/status ("Uid:\treal\teffective..."); -1 when unknown.
pub fn own_uid() -> Int {
uid_from_status(@utf8.decode_lossy(@sys.read_proc_bytes("/proc/self/status")))
}
///| The request BeginAuthentication's arguments describe (s s s a{ss} s a(sa{sv})); None when
/// they don't match. Users come from /etc/passwd and /etc/group.
pub fn AuthRequest::from_args(args : Array[@network.DValue]) -> AuthRequest? {
+12 -2
View File
@@ -168,6 +168,10 @@ pub(all) enum ShellAction {
Window(UInt64, WindowCommand)
/// The launcher's Reload reloaded the panel modules: the whole frame needs drawing again.
ModulesReloaded
/// The Keyboard panel module asked to show (true) or hide (false) the built-in OSK.
SetOskVisible(Bool)
/// The Rotate panel module asked to set display rotation (0..3).
SetRotation(Int)
} derive(Eq, Debug)
///| One wasm module loaded into the panel.
@@ -281,6 +285,10 @@ pub(all) struct DesktopShell {
/// What the screenshot module is told (the compositor sets it every frame): bit 0 a
/// recording is running, bit 1 recordings show the pointer.
mut screenshot_state : Int
/// Whether the built-in on-screen keyboard is currently visible (published to `osk`).
mut osk_visible : Bool
/// Current display rotation 0..3 (published to `rotation`).
mut rotation : Int
/// The network service (network.mbt), while a module imports `network`.
mut net : @network.NetService?
mut remember_windows : Bool
@@ -458,6 +466,8 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
bg_key: None,
restore_session: true,
screenshot_state: 2,
osk_visible: false,
rotation: 0,
net: None,
remember_windows: true,
native_auth_agent: true,
@@ -906,8 +916,8 @@ pub fn DesktopShell::pointer_down(self : DesktopShell, x : Int, y : Int) -> Bool
match self.widget_at(x, y) {
Some(w) => {
// A click (delivered on release) or the start of a drag that reorders the panel.
// The Interface Explorer toggle leaves open popups alone.
if !w.has_cap("inspector") {
// The Interface Explorer, Keyboard, and Rotate buttons leave open popups alone.
if !w.has_cap("inspector") && !w.has_cap("osk") && !w.has_cap("rotation") {
self.dismiss_popups(w.slot)
}
self.drag_slot = w.slot
+59 -6
View File
@@ -35,9 +35,10 @@ fn fresh_panel(has_battery : Bool) -> Array[String] {
}
///| Compact default panel for handsets (omits desktop-only inspector, tiling toggle, and moon
/// disc so the dock, launcher, settings, Wi-Fi, battery, clock, and screenshot have room).
/// disc so the dock, launcher, settings, Wi-Fi, battery, clock, screenshot, rotate, and osk have room).
let handset_panel : Array[String] = [
"launcher", "dock", "session-settings", "network", "battery", "clock-digital", "screenshot",
"rotate", "osk",
]
///| Whether a fresh session runs on a handset chassis (tests keep the desktop layout).
@@ -55,6 +56,24 @@ test "a fresh panel gets the battery module only on a machine with a battery" {
assert_eq(p.search("battery").unwrap() + 1, p.search("clock-digital").unwrap())
}
///|
test "handset panel includes rotate and osk and v2 handset migration appends them once" {
assert_eq(handset_panel[handset_panel.length() - 2], "rotate")
assert_eq(handset_panel[handset_panel.length() - 1], "osk")
assert_eq(
migrate_handset_panel(["launcher", "dock", "clock-digital"]),
["launcher", "dock", "clock-digital", "rotate", "osk"],
)
assert_eq(
migrate_handset_panel(["launcher", "osk", "dock"]),
["launcher", "osk", "dock", "rotate"],
)
assert_eq(
migrate_handset_panel(["launcher", "rotate", "osk"]),
["launcher", "rotate", "osk"],
)
}
///| Modules folded into another one: old id -> the module that took over. The old id still
/// works everywhere a module is named (saved panels, load_module), it is just never listed:
/// a stale build/components/clock-digital12.wasm or an old installed copy stays out of the picker.
@@ -217,7 +236,9 @@ fn DesktopShell::panel_slots(self : DesktopShell) -> Array[@panel.SlotIn] {
(w.module_id == "launcher" ||
w.module_id == "session-settings" ||
w.module_id == "network" ||
w.module_id == "screenshot") {
w.module_id == "screenshot" ||
w.module_id == "rotate" ||
w.module_id == "osk") {
36
} else {
base_w
@@ -357,6 +378,19 @@ test "a saved panel's Log out button folds into the launcher" {
assert_false(default_panel.contains("logout"))
}
///| Append the Rotate and Keyboard panel modules when migrating a handset panel saved before
/// panel.edn version 3 (when those controls moved from floating pills into the panel).
fn migrate_handset_panel(entries : Array[String]) -> Array[String] {
let out = entries.copy()
if !out.contains("rotate") {
out.push("rotate")
}
if !out.contains("osk") {
out.push("osk")
}
out
}
///| Load the panel on first use: the saved layout if there is one, else the default modules.
fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit {
if self.booted {
@@ -365,8 +399,16 @@ fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit {
self.booted = true
self.scan_catalog()
let saved = self.load_panel_config()
let saved_ver = if saved is Some(_) { saved_panel_version() } else { panel_version }
let entries = match saved {
Some(e) => migrate_panel(e)
Some(e) => {
let migrated = migrate_panel(e)
if saved_ver < 3 && is_handset_panel() {
migrate_handset_panel(migrated)
} else {
migrated
}
}
None =>
if is_handset_panel() {
handset_panel
@@ -375,10 +417,12 @@ fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit {
}
}
match saved {
Some(old) if saved_panel_version() < panel_version => {
Some(old) if saved_ver < panel_version => {
// Once, before the modules load so they pick up the moved settings; then the file is
// rewritten with the new names and version (also keeping modules that fail to load).
self.migrate_module_cfg(old)
if saved_ver < 2 {
self.migrate_module_cfg(old)
}
write_panel_file(entries)
}
// A renamed or folded module (the Log out button, now in the launcher): rewrite the file so
@@ -803,6 +847,12 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
if self.any_cap("screenshot") {
@wasm.publish_screenshot(self.screenshot_state)
}
if self.any_cap("osk") {
@wasm.publish_osk(self.osk_visible)
}
if self.any_cap("rotation") {
@wasm.publish_rotation(self.rotation)
}
if self.any_cap("battery") {
let b = self.battery.refresh()
@wasm.publish_battery(b.percent, b.state, b.secs_left)
@@ -979,6 +1029,8 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit {
Some(DefaultApp(code)) => self.default_app_request(code)
Some(FaceUnlock(code)) => self.face.request(code)
Some(GameLibrary(code, game, mode)) => self.gamelib.request(code, game, mode)
Some(SetOskVisible(v)) => self.actions.push(SetOskVisible(v))
Some(SetRotation(r)) => self.actions.push(SetRotation(r))
Some(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) }
Some(Network(code, ssid, password)) => self.network_request(code, ssid, password)
Some(SetInspector(on)) => self.set_inspecting(on)
@@ -1447,7 +1499,8 @@ pub fn DesktopShell::save_panel_config(self : DesktopShell) -> Unit {
///| panel.edn's format version (`:version`; files without one are 1). 2: written after the
/// 12-hour clock (clock-digital12) became part of the Digital Clock, whose default went from
/// 24-hour to 12-hour; an older file gets its clock settings moved over once (migrate_module_cfg).
let panel_version : Int = 2
/// 3: handset panels move Rotate (`rotate`) and Keyboard (`osk`) into the panel.
let panel_version : Int = 3
///|
fn write_panel_file(names : Array[String]) -> Unit {
+16
View File
@@ -417,6 +417,16 @@ pub fn publish_screenshot(state : Int) -> Unit {
@hostpl.publish_screenshot(state.reinterpret_as_uint())
}
///| Publish whether the built-in on-screen keyboard is currently visible.
pub fn publish_osk(visible : Bool) -> Unit {
@hostpl.publish_osk(visible)
}
///| Publish the current display rotation (0=0, 1=90 CW, 2=180, 3=270 CW).
pub fn publish_rotation(rot : Int) -> Unit {
@hostpl.publish_rotation(rot.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())
@@ -473,6 +483,10 @@ pub(all) enum HostRequest {
FaceUnlock(Int)
/// The game-library capability: 0 launch (game, mode), 1 stop, 2 focus (game), 3 refresh.
GameLibrary(Int, String, String)
/// The osk capability: show (true) or hide (false) the on-screen keyboard.
SetOskVisible(Bool)
/// The rotation capability: set display orientation (0..3).
SetRotation(Int)
} derive(Eq, Debug)
///|
@@ -502,6 +516,8 @@ pub fn next_request() -> HostRequest? {
Some(SetDesktop(i)) => Some(SetDesktop(i))
Some(FaceUnlock(i)) => Some(FaceUnlock(i))
Some(GameLibrary(r)) => Some(GameLibrary(r.action, r.game, r.mode))
Some(SetOskVisible(v)) => Some(SetOskVisible(v))
Some(SetRotation(r)) => Some(SetRotation(r))
}
}
+16
View File
@@ -831,6 +831,16 @@ pub fn publish_screenshot(state : Int) -> Unit {
c_host_set_int(4, state)
}
///| Publish whether the built-in on-screen keyboard is currently visible.
pub fn publish_osk(visible : Bool) -> Unit {
c_host_set_int(11, if visible { 1 } else { 0 })
}
///| Publish the current display rotation (0=0, 1=90 CW, 2=180, 3=270 CW).
pub fn publish_rotation(rot : Int) -> Unit {
c_host_set_int(12, rot)
}
///| 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)
@@ -891,6 +901,10 @@ pub(all) enum HostRequest {
FaceUnlock(Int)
/// The game-library capability: 0 launch (game, mode), 1 stop, 2 focus (game), 3 refresh.
GameLibrary(Int, String, String)
/// The osk capability: show (true) or hide (false) the on-screen keyboard.
SetOskVisible(Bool)
/// The rotation capability: set display orientation (0..3).
SetRotation(Int)
} derive(Eq, Debug)
///|
@@ -933,6 +947,8 @@ 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()))
21 => Some(SetOskVisible(c_host_req_int() != 0))
22 => Some(SetRotation(c_host_req_int()))
40 => Some(SetDesktop(c_host_req_int()))
44 => Some(FaceUnlock(c_host_req_int()))
45 => {
+16 -2
View File
@@ -68,7 +68,8 @@ enum {
K_DA_CATS, K_DA_APPS, K_DA_SET, K_DA_REFRESH,
K_DESKTOPS, K_DESKTOP_CUR, K_SET_DESKTOP,
K_FU_STATUS, K_FU_FACES, K_FU_ENROLL, K_FU_REMOVE, K_FU_SET_IN_USE, K_FU_REFRESH,
K_GL_STATUS, K_GL_GAMES, K_GL_MODES, K_GL_LAUNCH, K_GL_STOP, K_GL_FOCUS, K_GL_REFRESH
K_GL_STATUS, K_GL_GAMES, K_GL_MODES, K_GL_LAUNCH, K_GL_STOP, K_GL_FOCUS, K_GL_REFRESH,
K_OSK_IS_VISIBLE, K_OSK_SET_VISIBLE, K_ROT_CURRENT, K_ROT_SET
};
typedef struct Env { Inst *inst; int kind; } Env;
@@ -85,7 +86,8 @@ static int32_t host_ints[24] = {[7] = -1, [10] = -1}; /* 0 layout mode, 1 inspec
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,
10 backlight brightness percent (-1: none) */
10 backlight brightness percent (-1: none), 11 osk visible (0/1),
12 display rotation (0..3) */
/* ---- 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;
@@ -493,6 +495,14 @@ 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((host_ints[4] >> 1) & 1);
break;
case K_INSPECT_SET: push_req(4, a0, NULL); break;
case K_OSK_IS_VISIBLE:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[11] != 0);
break;
case K_OSK_SET_VISIBLE: push_req(21, a0 != 0, NULL); break;
case K_ROT_CURRENT:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[12]);
break;
case K_ROT_SET: push_req(22, a0, NULL); break;
case K_MOD_BROWSE: push_req(7, 0, NULL); break;
case K_MOD_LOAD: { char *s = guest_str(in, a0, a1); push_req(5, 0, s); free(s); break; }
case K_MOD_UNLOAD: { char *s = guest_str(in, a0, a1); push_req(6, 0, s); free(s); break; }
@@ -702,6 +712,10 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
if (!strcmp(iface, "layout-control") && !strcmp(fn, "set-layout")) return K_SET_LAYOUT;
if (!strcmp(iface, "inspector") && !strcmp(fn, "is-on")) return K_INSPECT_IS_ON;
if (!strcmp(iface, "inspector") && !strcmp(fn, "set-on")) return K_INSPECT_SET;
if (!strcmp(iface, "osk") && !strcmp(fn, "is-visible")) return K_OSK_IS_VISIBLE;
if (!strcmp(iface, "osk") && !strcmp(fn, "set-visible")) return K_OSK_SET_VISIBLE;
if (!strcmp(iface, "rotation") && !strcmp(fn, "current")) return K_ROT_CURRENT;
if (!strcmp(iface, "rotation") && !strcmp(fn, "set-rotation")) return K_ROT_SET;
if (!strcmp(iface, "modules") && !strcmp(fn, "available")) return K_MOD_AVAILABLE;
if (!strcmp(iface, "modules") && !strcmp(fn, "loaded")) return K_MOD_LOADED;
if (!strcmp(iface, "modules") && !strcmp(fn, "load-module")) return K_MOD_LOAD;
+30
View File
@@ -278,3 +278,33 @@ test "moon and digital clock modules render from the clock capability" {
assert_true(ts[0].has_suffix("AM") || ts[0].has_suffix("PM")) // 12-hour by default
c.unload()
}
///|
test "osk module toggles through the osk capability" {
let p = load_module("osk")
assert_true(p.imports().contains("osk"))
publish_osk(false)
assert_true(texts_of(p.render(44, 34, test_tokens())).contains("KB"))
assert_true(p.popup() is None)
assert_true(p.on_event(false, PointerDown(5, 5)))
assert_eq(drain(), [SetOskVisible(true)])
publish_osk(true)
assert_true(p.on_event(false, PointerDown(5, 5)))
assert_eq(drain(), [SetOskVisible(false)])
p.unload()
}
///|
test "rotate module cycles orientation through the rotation capability" {
let p = load_module("rotate")
assert_true(p.imports().contains("rotation"))
publish_rotation(0)
assert_true(texts_of(p.render(44, 34, test_tokens())).contains("Rot"))
assert_true(p.popup() is None)
assert_true(p.on_event(false, PointerDown(5, 5)))
assert_eq(drain(), [SetRotation(1)])
publish_rotation(3)
assert_true(p.on_event(false, PointerDown(5, 5)))
assert_eq(drain(), [SetRotation(0)])
p.unload()
}