Files
chandra/compositor/host/auth.mbt
T
nandi 851c39d827
CI / test (push) Failing after 52s
Auth dialog: OSK auto-open, hex keysyms, and remote text input
- Show the on-screen keyboard when the password dialog opens or reopens, and hide it on submit. Tapping the password field reopens it after a manual Hide.
- Route Chandra Remote text commits (including Enter, Tab, and Backspace) into the password dialog while it is up.
- Keymap: read hex keysyms (`0x31`, `0x20ac`, `0xffb7`) from libxkbcommon text-v1 keymaps, and accept `0x01000000`-range Unicode keysyms.
- Keymap: keypad keys produce digits when NumLock (Mod2) is active.
- Tests cover hex keysym parsing, NumLock keypad mapping, and the OSK/remote-text flow.
2026-11-28 18:51:15 -08:00

521 lines
17 KiB
MoonBit

///| Chandra's password dialog: the compositor's half.
///
/// polkit's side (registering as the session's agent, polkit's helper, the PAM conversation and
/// the request's one state machine) runs in chandra-polkit-agent, a separate program the
/// compositor starts on a socket pair (compositor/polkit/agent_loop.mbt). The compositor only
/// draws what the agent says (auth_draw.mbt), owns the keyboard and the pointer while the dialog
/// is up, and sends back what was typed or picked (compositor/polkit/wire.mbt). The typed text
/// stays here as characters, is wiped once sent, and is never logged.
///
/// Nothing happens quietly. If the agent can't be started, polkit refuses it, or it stops, a
/// notice says so and why (auth_notice); another polkit agent runs only when the Settings switch
/// "Chandra password dialog" is off, which is the user's choice. See docs/auth-dialog.md.
///| A link to a running agent (the session's, or a demo's).
pub(all) struct AuthLink {
conn : @polkit.LineConn
/// `chandra-ctl auth-demo`: one pretend request, then it exits.
demo : Bool
/// The agent said `ready` (registered with polkit).
mut ready : Bool
/// What the agent said in its `error` message ("" when nothing).
mut error : String
/// When it was started (monotonic ms), for the "no answer from polkit" notice.
started : UInt64
/// The request it is describing or showing.
mut view : @polkit.AuthView?
}
///| The dialog while it is up.
pub(all) struct AuthUi {
link : AuthLink
view : @polkit.AuthView
/// The window that had the keyboard before, given it back on close.
prev_kbd : UInt64?
/// The app icon (0: the lock drawn instead).
icon : UInt
/// Where each control was last drawn, for clicks and the cursor.
hits : Array[(@scene.Rect, @polkit.Focus)]
/// When it opened (the spinner's clock).
opened : UInt64
}
///| A notice about the password dialog itself (it couldn't start, it stopped): shown at the top
/// of the screen until clicked.
pub(all) struct AuthNotice {
text : String
mut rect : @scene.Rect
}
///| The dialog's view, while it is up.
pub fn ChandraCompositor::auth_view(self : ChandraCompositor) -> @polkit.AuthView? {
self.auth.map(a => a.view)
}
///| The notice's text, if one is up.
pub fn ChandraCompositor::auth_notice_text(self : ChandraCompositor) -> String? {
self.auth_notice.map(n => n.text)
}
///| Where chandra-polkit-agent is: $CHANDRA_POLKIT_AGENT_BIN, the installed one, else a build in
/// the checkout (the compositor's working directory when run from it). "" when none is found.
pub fn auth_agent_bin() -> String {
let env = @sys.getenv("CHANDRA_POLKIT_AGENT_BIN")
if env != "" {
return env
}
for p in [
"/usr/local/lib/chandra/chandra-polkit-agent", "_build/native/release/build/compositor/authagent/authagent.exe",
"_build/native/debug/build/compositor/authagent/authagent.exe",
] {
if @sys.has_exe(p) {
return p
}
}
""
}
///| Start an agent with `args`: its link, or why not.
fn ChandraCompositor::auth_spawn(self : ChandraCompositor, args : Array[String], demo : Bool) -> Result[AuthLink, String] {
let fd = match self.auth_spawner {
Some(f) => f(args)
None => {
let bin = auth_agent_bin()
if bin == "" {
return Err(
"chandra-polkit-agent is not installed (/usr/local/lib/chandra/chandra-polkit-agent); run `just install`",
)
}
let fd = @sys.spawn_socket([bin, ..args])
if fd < 0 {
return Err("could not run " + bin)
}
fd
}
}
if fd < 0 {
return Err("could not run chandra-polkit-agent")
}
Ok({ conn: @polkit.LineConn::new(fd), demo, ready: false, error: "", started: @sys.monotonic_ms(), view: None })
}
///| Show a notice about the dialog (and log it).
fn ChandraCompositor::auth_say(self : ChandraCompositor, text : String) -> Unit {
@sys.log("chandra: password dialog: " + text)
self.auth_notice = Some({ text, rect: @scene.Rect::new(0, 0, 0, 0) })
self.damage.mark_full()
}
///| Start the password dialog's agent, or the other agent when the Settings switch says so.
/// CHANDRA_POLKIT_AGENT=none starts nothing; =PATH starts that agent instead. Login session only.
pub fn ChandraCompositor::start_auth_agent(self : ChandraCompositor) -> Unit {
let env = @sys.getenv("CHANDRA_POLKIT_AGENT")
if env == "none" {
@sys.log("chandra: CHANDRA_POLKIT_AGENT=none: no polkit agent")
return
}
if env != "" && env != "chandra" {
self.spawn_other_agent(env)
return
}
if !self.shell.native_auth_agent {
// Settings > Session > "Chandra password dialog" is off: the user picked the other agent.
self.spawn_other_agent(@sys.getenv("CHANDRA_POLKIT_FALLBACK"))
return
}
if self.auth_agent is Some(_) {
return
}
match self.auth_spawn([], false) {
Ok(l) => {
self.auth_agent = Some(l)
@sys.log("chandra: started chandra-polkit-agent")
}
Err(why) => self.auth_say("Chandra's password dialog couldn't start: " + why + ".")
}
}
///| Start the other polkit agent (once): the user turned Chandra's dialog off.
fn ChandraCompositor::spawn_other_agent(self : ChandraCompositor, path : String) -> Unit {
if self.fallback_agent_started {
return
}
if path == "" {
self.auth_say("Chandra's password dialog is off in Settings, and no other polkit agent is installed.")
return
}
if @sys.spawn(path, self.shell.display) {
self.fallback_agent_started = true
@sys.log("chandra: started polkit agent " + path + " (Chandra's password dialog is off in Settings)")
} else {
self.auth_say("Chandra's password dialog is off in Settings, and " + path + " could not be started.")
}
}
///| The Settings switch changed. Off: our agent stops (polkit forgets it) and the other one
/// starts. On: ours starts, unless the other already runs (polkit allows one per session), and
/// then the notice says it takes over at the next login.
pub fn ChandraCompositor::auth_agent_setting_changed(self : ChandraCompositor) -> Unit {
if !self.login_session {
return
}
if self.shell.native_auth_agent {
if self.fallback_agent_started {
self.auth_say("Chandra's password dialog takes over at your next login: the other polkit agent runs until then.")
} else {
self.start_auth_agent()
}
} else {
match self.auth_agent {
Some(l) => {
self.auth_agent = None
self.auth_drop_link(l)
@sys.log("chandra: stopped chandra-polkit-agent (turned off in Settings)")
}
None => ()
}
self.start_auth_agent()
}
}
///| Close a link (the agent exits when it sees that); its dialog goes too.
fn ChandraCompositor::auth_drop_link(self : ChandraCompositor, l : AuthLink) -> Unit {
match self.auth {
Some(ui) if physical_equal(ui.link, l) => self.close_auth(false)
_ => ()
}
l.conn.close()
}
///| `chandra-ctl auth-demo [MODE]`: show the dialog with a pretend password check.
pub fn ChandraCompositor::start_auth_demo(self : ChandraCompositor, mode : String) -> Result[Unit, String] {
if mode != "" && !@polkit.demo_modes.contains(mode) {
return Err("no demo mode '" + mode + "' (" + @polkit.demo_modes.join(", ") + ")")
}
match self.auth_spawn(["--demo", if mode == "" { "password" } else { mode }], true) {
Ok(l) => {
self.auth_demos.push(l)
Ok(())
}
Err(why) => Err(why)
}
}
///| Read what each agent said; open, update and close the dialog. Each main-loop pass.
fn ChandraCompositor::auth_tick(self : ChandraCompositor) -> Unit {
match self.auth_agent {
Some(l) =>
if !self.auth_serve(l) {
self.auth_agent = None
let why = if l.error != "" {
l.error
} else {
"chandra-polkit-agent stopped unexpectedly (see ~/.local/state/chandra/session.log)"
}
if l.ready && self.auth_restarts < 3 {
// It ran, then died: start it again (the session needs a password dialog), and say so.
self.auth_restarts = self.auth_restarts + 1
self.auth_say("Chandra's password dialog stopped and was restarted: " + why + ".")
self.start_auth_agent()
} else {
self.auth_say("Chandra's password dialog couldn't start: " + why + ".")
}
} else if !l.ready && !self.auth_slow_said && @sys.monotonic_ms() - l.started > 10000UL {
self.auth_slow_said = true
self.auth_say("Chandra's password dialog is still waiting for polkit to answer (10 s). Password prompts may not appear.")
}
None => ()
}
let demos = self.auth_demos.copy()
for l in demos {
if !self.auth_serve(l) {
self.auth_demos.retain(x => !physical_equal(x, l))
if l.error != "" {
self.auth_say("The password dialog demo couldn't run: " + l.error + ".")
}
}
}
// Nothing up: show the first request that is ready.
if self.auth is None {
let links = match self.auth_agent {
Some(l) => [l, ..self.auth_demos]
None => self.auth_demos.copy()
}
for l in links {
match l.view {
Some(v) if v.shown => {
self.open_auth(l, v)
break
}
_ => ()
}
}
}
}
///| Serve one link. False once it is gone (the agent exited or failed).
fn ChandraCompositor::auth_serve(self : ChandraCompositor, l : AuthLink) -> Bool {
let now = @sys.monotonic_ms()
for line in l.conn.read_lines() {
let f = @polkit.decode_line(line)
match f.get(0).unwrap_or("") {
"ready" => {
l.ready = true
if !l.demo {
@sys.log("chandra: chandra-polkit-agent registered with polkit")
self.auth_slow_said = false
}
}
"error" => {
l.error = f.get(1).unwrap_or("")
@sys.log("chandra: chandra-polkit-agent: " + l.error)
}
"request" => l.view = Some(@polkit.AuthView::from_request(f))
"close" => {
match self.auth {
Some(ui) if physical_equal(ui.link, l) && ui.view.id == f.get(1).unwrap_or("") => self.close_auth(false)
_ => ()
}
l.view = None
}
_ =>
match l.view {
Some(v) if v.id == f.get(1).unwrap_or("") => {
v.apply(f, now)
self.damage.mark_full()
}
_ => ()
}
}
}
if l.conn.eof || l.conn.fd() < 0 {
match self.auth {
Some(ui) if physical_equal(ui.link, l) => self.close_auth(false)
_ => ()
}
l.conn.close()
return false
}
true
}
///| Show the dialog for `v` and take the keyboard and the pointer.
fn ChandraCompositor::open_auth(self : ChandraCompositor, l : AuthLink, v : @polkit.AuthView) -> Unit {
let icon = if v.program != "" {
self.shell.window_icon(v.program)
} else if v.icon_name != "" {
self.shell.theme_icon(v.icon_name)
} else {
0U
}
v.caps = (self.mods_locked & @polkit.mask_lock) != 0U
self.auth = Some({ link: l, view: v, prev_kbd: self.kbd_win, icon, hits: [], opened: @sys.monotonic_ms() })
// Nothing else gets the keyboard or the pointer while it is up.
self.set_kbd_focus(None)
self.leave_pointer()
self.osk_sync()
self.damage.mark_full()
}
///| Close the dialog (`dismiss`: the user did, tell the agent) and give the keyboard back.
fn ChandraCompositor::close_auth(self : ChandraCompositor, dismiss : Bool) -> Unit {
match self.auth {
Some(ui) => {
if dismiss {
ignore(ui.link.conn.send(["cancel", ui.view.id]))
}
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 => ()
}
self.osk_sync()
self.damage.mark_full()
}
None => ()
}
}
///| Stop every agent (the session is ending).
fn ChandraCompositor::auth_shutdown(self : ChandraCompositor) -> Unit {
self.close_auth(true)
match self.auth_agent {
Some(l) => l.conn.close()
None => ()
}
self.auth_agent = None
for l in self.auth_demos {
l.conn.close()
}
self.auth_demos.clear()
}
///| Do what a key or click on the dialog asked.
fn ChandraCompositor::auth_act(self : ChandraCompositor, ui : AuthUi, a : @polkit.ViewAction) -> Unit {
let id = ui.view.id
match a {
Nothing => ()
Submit => {
let line = @polkit.encode_secret_line(["answer", id], ui.view.take_answer())
ignore(ui.link.conn.send_secret(line))
}
Retry => ignore(ui.link.conn.send(["retry", id]))
PickUser(i) => ignore(ui.link.conn.send(["user", id, i.to_string()]))
Dismiss => self.close_auth(true)
}
self.damage.mark_full()
}
///| The keymap typing goes through: the one clients have, else US.
fn ChandraCompositor::auth_keymap(self : ChandraCompositor) -> @polkit.Keymap {
match self.keymap {
Some((src, k)) if physical_equal(src, self.server.keymap) => k
_ => {
let k = @polkit.Keymap::from_text(@utf8.decode_lossy(self.server.keymap))
self.keymap = Some((self.server.keymap, k))
k
}
}
}
///| The one owner of input above the desktop: the password dialog when it is up, else the Face
/// unlock window (which steps aside while its Apply waits for the password). True when it took
/// the event. Releases of keys either took never reach the client that gets the keyboard back.
fn ChandraCompositor::grab_input(self : ChandraCompositor, ev : @nested.InputEvent) -> Bool {
match ev {
Key(code, false) =>
if self.auth_swallow.contains(code) {
self.auth_swallow.retain(c => c != code)
return true
}
_ => ()
}
if self.auth_notice_input(ev) {
return true
}
match self.auth {
Some(ui) => self.auth_input(ui, ev)
None => self.face_window_input(ev)
}
}
///| A click on the notice dismisses it.
fn ChandraCompositor::auth_notice_input(self : ChandraCompositor, ev : @nested.InputEvent) -> Bool {
match (self.auth_notice, ev) {
(Some(n), PointerButton(272U, true)) => {
let x = self.ptr_x.to_int()
let y = self.ptr_y.to_int()
let r = n.rect
if x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h {
self.auth_notice = None
self.auth_notice_press = true
self.damage.mark_full()
return true
}
false
}
(_, PointerButton(272U, false)) if self.auth_notice_press => {
self.auth_notice_press = false
true
}
_ => false
}
}
///| Input while the dialog is up: all of it is the dialog's.
fn ChandraCompositor::auth_input(self : ChandraCompositor, ui : AuthUi, ev : @nested.InputEvent) -> Bool {
match ev {
Key(code, pressed) => {
if code == key_lsuper || code == key_rsuper {
self.super_solo = false
}
if pressed {
self.auth_swallow.push(code)
let mods = self.mods | self.mods_latched | self.mods_locked
let ch = self.auth_keymap().char_for(code, mods, self.mods_group)
self.auth_act(ui, ui.view.key(code, self.mods | self.mods_latched, ch))
}
}
Modifiers(_, _, lock, _) => {
ui.view.caps = (lock & @polkit.mask_lock) != 0U
self.damage.mark_full()
}
PointerMove(x, y) => {
self.ptr_x = x
self.ptr_y = y
self.damage.mark_full()
}
PointerButton(button, pressed) =>
if pressed && button == 272U {
match self.auth_hit(ui) {
Some(f) => {
if f == Field && self.osk_enabled {
self.osk_manual_hide = false
self.osk_sync()
}
self.auth_act(ui, ui.view.activate(f))
}
None => ()
}
}
Scroll(_, _, _) => ()
}
true
}
///| The control under the pointer.
fn ChandraCompositor::auth_hit(self : ChandraCompositor, ui : AuthUi) -> @polkit.Focus? {
let x = self.ptr_x.to_int()
let y = self.ptr_y.to_int()
for h in ui.hits {
let r = h.0
if x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h {
return Some(h.1)
}
}
None
}
///| Cursor over the dialog: a text beam over the field, a hand over buttons, else the arrow.
fn ChandraCompositor::auth_cursor(self : ChandraCompositor, ui : AuthUi) -> UInt {
match self.auth_hit(ui) {
Some(Field) => 9U // text
Some(_) => 4U // pointer
None => 1U // default
}
}
///| Whether the dialog animates (the shake, the spinner while checking, the face scan) or
/// waits on a timer (the "no answer from polkit" notice).
fn ChandraCompositor::auth_animating(self : ChandraCompositor) -> Bool {
let waiting = match self.auth_agent {
Some(l) => !l.ready && !self.auth_slow_said
None => false
}
waiting ||
(match self.auth {
Some(ui) => {
let v = ui.view
v.shaking(@sys.monotonic_ms()) || v.phase == Checking || v.phase == Starting || v.face == Scanning
}
None => false
})
}
///| The fds to wake on: each agent's link.
pub fn ChandraCompositor::auth_fds(self : ChandraCompositor) -> Array[Int] {
let out : Array[Int] = []
match self.auth_agent {
Some(l) => if l.conn.fd() >= 0 { out.push(l.conn.fd()) }
None => ()
}
for l in self.auth_demos {
if l.conn.fd() >= 0 {
out.push(l.conn.fd())
}
}
out
}