Files
chandra/compositor/polkit/keymap.mbt
Claude 0feea23a06
CI / test (push) Failing after 18s
Password dialog: Chandra is its own polkit agent, drawn in the shell layer
run0, pkexec and other polkit prompts used whatever third-party agent was
installed: a plain toolkit window saying "start transient unit
'run-p15802-i1990.service'". The compositor now registers as the session's
polkit authentication agent and asks in its own dialog:

- a centered card over a dimmed screen, above all windows and client menus,
  themed (dark/light follow the Dark mode switch), keyboard-first: Enter,
  Esc, Tab order, Alt+R show/hide, Alt+D details, Ctrl+U clear
- for run0 it shows the command it will run ("gparted /dev/sda", as root)
  from run0's command line (pid from polkit's details or the unit name),
  pkexec's command from its details, polkit's message otherwise; Details
  lists the requester, target user, unit and action id
- account picker when several admins can answer (group members expanded)
- the PAM conversation through polkit-agent-helper-1: polkit 126's socket
  first, else the setuid helper on a socket pair (new sys spawn-socket on the
  native, Rust and MoonBit hosts); password, echo-on prompts, info (fingerprint)
  and errors (faillock) shown as they come; wrong password shakes and retries;
  spinner while PAM checks; Caps Lock warning
- typing through the clients' xkb keymap (groups, Shift, AltGr, Caps Lock),
  US layout when there is none
- no client has keyboard focus or input while it is up; the password is
  wiped after sending and never logged

Settings > Session > "Chandra password dialog" (state.edn :auth-agent
:system when off) switches back to the third-party agent, which
chandra-session now finds and the compositor starts (also when polkit
refuses our agent). Tests: polkit_test (keymaps, helper protocol, run0
parsing, dialog states, the socket-pair route) and auth_test (mock polkit
Authority on a private dbus-daemon, mock helper; CHANDRA_AUTH_SHOTS writes
a PNG per state). Docs: docs/auth-dialog.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgkRPrAzXECBUGmNEE
2026-11-26 00:17:04 +00:00

635 lines
17 KiB
MoonBit

///| Characters for the password field, from the keymap clients are sent.
///
/// The compositor sees keys as evdev codes; the characters they type depend on the keyboard
/// layout, and a password typed on the wrong layout is the wrong password. So the auth dialog reads
/// the xkb keymap (text format v1, what the host hands `WaylandServer::set_keymap`): the keycode
/// names (`<AE01> = 10;`) and each key's symbols per group and level (`key <AE01> { [ 1, exclam ] };`),
/// and maps keysym names to characters (ASCII and Latin-1 names, `Uxxxx`, `0x100xxxxx`). Without a
/// keymap (nested windows, tests) a built-in US layout is used.
///| One key's keysym names: groups, then levels.
struct KeySyms {
groups : Array[Array[String]]
}
///| Characters per keycode (evdev code + 8), parsed from an xkb keymap.
pub struct Keymap {
keys : Map[Int, KeySyms]
}
///|
fn chars_of(s : String) -> Array[Char] {
let out : Array[Char] = []
for c in s {
out.push(c)
}
out
}
///|
fn str_of(cs : Array[Char], from : Int, to : Int) -> String {
let sb = StringBuilder::new()
for i = from; i < to && i < cs.length(); i = i + 1 {
sb.write_char(cs[i])
}
sb.to_string()
}
///|
fn is_space(c : Char) -> Bool {
c == ' ' || c == '\t' || c == '\n' || c == '\r'
}
///| The text of section `name` (say "xkb_symbols"): from its opening brace to the matching close.
fn section(cs : Array[Char], name : String) -> (Int, Int)? {
let n = chars_of(name)
let mut i = 0
while i + n.length() <= cs.length() {
let mut hit = true
for k = 0; k < n.length(); k = k + 1 {
if cs[i + k] != n[k] {
hit = false
break
}
}
if hit {
let mut j = i + n.length()
while j < cs.length() && cs[j] != '{' {
j = j + 1
}
let start = j + 1
let mut depth = 1
j = start
while j < cs.length() && depth > 0 {
if cs[j] == '{' {
depth = depth + 1
} else if cs[j] == '}' {
depth = depth - 1
}
j = j + 1
}
return Some((start, j - 1))
}
i = i + 1
}
None
}
///| Statements of a section body split on top-level ';' (braces nest).
fn statements(cs : Array[Char], from : Int, to : Int) -> Array[String] {
let out : Array[String] = []
let mut depth = 0
let mut start = from
let mut in_str = false
for i = from; i < to; i = i + 1 {
let c = cs[i]
if c == '"' {
in_str = !in_str
} else if !in_str {
if c == '{' {
depth = depth + 1
} else if c == '}' {
depth = depth - 1
} else if c == ';' && depth == 0 {
out.push(str_of(cs, start, i).trim(chars=" \t\r\n").to_string())
start = i + 1
}
}
}
out
}
///| `<NAME> = 10` -> ("NAME", 10); `alias <A> = <B>` handled by the caller.
fn parse_keycode(st : String) -> (String, Int)? {
if !st.has_prefix("<") {
return None
}
let cs = chars_of(st)
let mut close = -1
for i, c in cs {
if c == '>' {
close = i
break
}
}
if close < 0 {
return None
}
let name = str_of(cs, 1, close)
let rest = str_of(cs, close + 1, cs.length()).trim(chars=" \t=").to_string()
let mut v = 0
let mut any = false
for c in rest {
if c >= '0' && c <= '9' {
v = v * 10 + (c.to_int() - '0'.to_int())
any = true
} else {
break
}
}
if any {
Some((name, v))
} else {
None
}
}
///| The keysym lists in a key body: `[ a, A ]` (group 1) or `symbols[1]= [ a, A ], symbols[2]= [...]`.
fn key_groups(body : Array[Char]) -> Array[Array[String]] {
let groups : Array[Array[String]] = []
let mut i = 0
let n = body.length()
// Whether the next '[' opens a keysym list: after '{', ',' or '=' preceded by symbols[..].
let mut prev_word = ""
let word = StringBuilder::new()
let mut last_sig = '{'
while i < n {
let c = body[i]
if c == '"' {
i = i + 1
while i < n && body[i] != '"' {
i = i + 1
}
i = i + 1
last_sig = '"'
continue
}
if c.is_ascii_alphabetic() || c.is_ascii_digit() || c == '_' {
word.write_char(c)
i = i + 1
continue
}
if word.to_string() != "" {
prev_word = word.to_string()
word.reset()
last_sig = 'w'
}
if is_space(c) {
i = i + 1
continue
}
if c == '[' {
if last_sig == 'w' {
// An index like symbols[1] or actions[Group2]: skip it, remember what it indexes.
let kind = prev_word
while i < n && body[i] != ']' {
i = i + 1
}
i = i + 1
last_sig = if kind == "symbols" { 's' } else { 'x' }
continue
}
let take = last_sig == '{' || last_sig == ',' || last_sig == 'S'
let start = i + 1
while i < n && body[i] != ']' {
i = i + 1
}
if take {
let syms : Array[String] = []
for p in str_of(body, start, i).split(",") {
syms.push(p.trim(chars=" \t\r\n").to_string())
}
groups.push(syms)
}
i = i + 1
last_sig = ']'
continue
}
if c == '=' {
last_sig = if last_sig == 's' { 'S' } else { '=' }
} else if c == ',' {
last_sig = if last_sig == ']' { ',' } else { ',' }
} else {
last_sig = c
}
i = i + 1
}
groups
}
///| Parse an xkb text keymap. None when it has no symbols we can use.
pub fn Keymap::parse(text : String) -> Keymap? {
let cs = chars_of(text)
let codes : Map[String, Int] = {}
match section(cs, "xkb_keycodes") {
Some((a, b)) => {
let aliases : Array[(String, String)] = []
for st in statements(cs, a, b) {
if st.has_prefix("alias") {
let parts = st.split("=").to_array()
if parts.length() == 2 {
let al = parts[0].trim(chars=" \taliasAL").to_string()
let tg = parts[1].trim(chars=" \t").to_string()
aliases.push((al.trim(chars="<>").to_string(), tg.trim(chars="<>").to_string()))
}
} else {
match parse_keycode(st) {
Some((name, v)) => codes.set(name, v)
None => ()
}
}
}
for a in aliases {
match codes.get(a.1) {
Some(v) => if !codes.contains(a.0) { codes.set(a.0, v) }
None => ()
}
}
}
None => ()
}
let keys : Map[Int, KeySyms] = {}
match section(cs, "xkb_symbols") {
Some((a, b)) =>
for st in statements(cs, a, b) {
if !st.has_prefix("key ") && !st.has_prefix("key\t") {
continue
}
let sc = chars_of(st)
let mut lt = -1
let mut gt = -1
for i, c in sc {
if c == '<' && lt < 0 {
lt = i
} else if c == '>' && lt >= 0 {
gt = i
break
}
}
if lt < 0 || gt < 0 {
continue
}
let name = str_of(sc, lt + 1, gt)
let mut ob = -1
for i = gt; i < sc.length(); i = i + 1 {
if sc[i] == '{' {
ob = i
break
}
}
if ob < 0 {
continue
}
let body = sc[ob:].to_array()
let groups = key_groups(body)
if groups.length() == 0 {
continue
}
let code = match codes.get(name) {
Some(v) => v
None => match us_codes().get(name) {
Some(v) => v
None => continue
}
}
keys.set(code, { groups, })
}
None => ()
}
if keys.length() == 0 {
None
} else {
Some({ keys, })
}
}
///| Names of keysyms 0x20..0x7e (ASCII), in order.
let ascii_names : Array[String] = [
"space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "apostrophe",
"parenleft", "parenright", "asterisk", "plus", "comma", "minus", "period", "slash", "0", "1",
"2", "3", "4", "5", "6", "7", "8", "9", "colon", "semicolon", "less", "equal", "greater",
"question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash",
"bracketright", "asciicircum", "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"braceleft", "bar", "braceright", "asciitilde",
]
///| Names of keysyms 0xa0..0xff (Latin-1, keysym = code point), in order.
let latin1_names : Array[String] = [
"nobreakspace", "exclamdown", "cent", "sterling", "currency", "yen", "brokenbar", "section",
"diaeresis", "copyright", "ordfeminine", "guillemotleft", "notsign", "hyphen", "registered",
"macron", "degree", "plusminus", "twosuperior", "threesuperior", "acute", "mu", "paragraph",
"periodcentered", "cedilla", "onesuperior", "masculine", "guillemotright", "onequarter",
"onehalf", "threequarters", "questiondown", "Agrave", "Aacute", "Acircumflex", "Atilde",
"Adiaeresis", "Aring", "AE", "Ccedilla", "Egrave", "Eacute", "Ecircumflex", "Ediaeresis",
"Igrave", "Iacute", "Icircumflex", "Idiaeresis", "ETH", "Ntilde", "Ograve", "Oacute",
"Ocircumflex", "Otilde", "Odiaeresis", "multiply", "Oslash", "Ugrave", "Uacute",
"Ucircumflex", "Udiaeresis", "Yacute", "THORN", "ssharp", "agrave", "aacute", "acircumflex",
"atilde", "adiaeresis", "aring", "ae", "ccedilla", "egrave", "eacute", "ecircumflex",
"ediaeresis", "igrave", "iacute", "icircumflex", "idiaeresis", "eth", "ntilde", "ograve",
"oacute", "ocircumflex", "otilde", "odiaeresis", "division", "oslash", "ugrave", "uacute",
"ucircumflex", "udiaeresis", "yacute", "thorn", "ydiaeresis",
]
///| Other names that type a character.
let extra_names : Array[(String, Int)] = [
("EuroSign", 0x20ac),
("guillemetleft", 0xab),
("guillemetright", 0xbb),
("Ooblique", 0xd8),
("ooblique", 0xf8),
("masculine", 0xba),
("ordmasculine", 0xba),
("KP_0", 0x30),
("KP_1", 0x31),
("KP_2", 0x32),
("KP_3", 0x33),
("KP_4", 0x34),
("KP_5", 0x35),
("KP_6", 0x36),
("KP_7", 0x37),
("KP_8", 0x38),
("KP_9", 0x39),
("KP_Decimal", 0x2e),
("KP_Add", 0x2b),
("KP_Subtract", 0x2d),
("KP_Multiply", 0x2a),
("KP_Divide", 0x2f),
("KP_Space", 0x20),
("KP_Separator", 0x2c),
]
///|
let name_table : Ref[Map[String, Int]?] = { val: None }
///|
fn names() -> Map[String, Int] {
match name_table.val {
Some(m) => m
None => {
let m : Map[String, Int] = {}
for i, n in ascii_names {
m.set(n, 0x20 + i)
}
for i, n in latin1_names {
m.set(n, 0xa0 + i)
}
for e in extra_names {
m.set(e.0, e.1)
}
name_table.val = Some(m)
m
}
}
}
///|
fn hex_value(s : String) -> Int? {
let mut v = 0
if s.length() == 0 || s.length() > 8 {
return None
}
for c in s {
let d = if c >= '0' && c <= '9' {
c.to_int() - '0'.to_int()
} else if c >= 'a' && c <= 'f' {
c.to_int() - 'a'.to_int() + 10
} else if c >= 'A' && c <= 'F' {
c.to_int() - 'A'.to_int() + 10
} else {
return None
}
v = v * 16 + d
}
Some(v)
}
///| The character keysym `name` types, if any (dead keys, modifiers and unknown names: None).
pub fn keysym_char(name : String) -> Char? {
match names().get(name) {
Some(cp) => return Some(Int::unsafe_to_char(cp))
None => ()
}
let cp = if name.length() >= 5 && name.has_prefix("U") {
hex_value(name[1:].to_string())
} else if (name.length() == 9 || name.length() == 10) && name.has_prefix("0x100") {
hex_value(name[5:].to_string())
} else {
None
}
match cp {
Some(v) if v >= 0x20 && v < 0x110000 && !(v >= 0xd800 && v < 0xe000) && v != 0x7f =>
Some(Int::unsafe_to_char(v))
_ => None
}
}
///| Modifier bits of an xkb state (wl_keyboard.modifiers): Shift, Lock (Caps), Mod5 (AltGr).
pub let mask_shift : UInt = 1
///|
pub let mask_lock : UInt = 2
///|
pub let mask_ctrl : UInt = 4
///|
pub let mask_alt : UInt = 8
///|
pub let mask_altgr : UInt = 0x80
///| Whether `c` is a letter Caps Lock applies to: ASCII and Latin-1 letters, and anything past
/// Latin-1 (Cyrillic, Greek, ...), as long as its two levels differ (checked by the caller).
fn letter(c : Char) -> Bool {
let v = c.to_int()
c.is_ascii_alphabetic() || (v >= 0xc0 && v <= 0xff && v != 0xd7 && v != 0xf7) || v > 0x24f
}
///| The character evdev key `code` types with modifier `mods` (depressed | latched | locked)
/// in layout group `group`; None for keys that type nothing.
pub fn Keymap::char_for(self : Keymap, code : UInt, mods : UInt, group : UInt) -> Char? {
let ks = match self.keys.get(code.reinterpret_as_int() + 8) {
Some(k) => k
None => return None
}
let g = if group.reinterpret_as_int() < ks.groups.length() {
ks.groups[group.reinterpret_as_int()]
} else {
ks.groups[0]
}
if g.length() == 0 {
return None
}
let shift = (mods & mask_shift) != 0U
let altgr = (mods & mask_altgr) != 0U && g.length() > 2
let base = if altgr { 2 } else { 0 }
let at = fn(l : Int) -> Char? {
if l < g.length() {
keysym_char(g[l])
} else if l > 0 {
keysym_char(g[l - 1])
} else {
None
}
}
let mut level = base + (if shift { 1 } else { 0 })
// Caps Lock flips the case of letters (the ALPHABETIC key type), not digits or punctuation.
if (mods & mask_lock) != 0U {
match (at(base), at(base + 1)) {
(Some(lo), Some(up)) if lo != up && letter(lo) && letter(up) =>
level = base + (if shift { 0 } else { 1 })
_ => ()
}
}
at(level)
}
///| xkb keycode names of the US layout's keys (evdev + 8), for keymaps whose keycodes section
/// is missing.
fn us_codes() -> Map[String, Int] {
let m : Map[String, Int] = {}
let rows = [
("TLDE", 49),
("AE01", 10),
("AE02", 11),
("AE03", 12),
("AE04", 13),
("AE05", 14),
("AE06", 15),
("AE07", 16),
("AE08", 17),
("AE09", 18),
("AE10", 19),
("AE11", 20),
("AE12", 21),
("AD01", 24),
("AD02", 25),
("AD03", 26),
("AD04", 27),
("AD05", 28),
("AD06", 29),
("AD07", 30),
("AD08", 31),
("AD09", 32),
("AD10", 33),
("AD11", 34),
("AD12", 35),
("AC01", 38),
("AC02", 39),
("AC03", 40),
("AC04", 41),
("AC05", 42),
("AC06", 43),
("AC07", 44),
("AC08", 45),
("AC09", 46),
("AC10", 47),
("AC11", 48),
("BKSL", 51),
("AB01", 52),
("AB02", 53),
("AB03", 54),
("AB04", 55),
("AB05", 56),
("AB06", 57),
("AB07", 58),
("AB08", 59),
("AB09", 60),
("AB10", 61),
("SPCE", 65),
("LSGT", 94),
("KP7", 79),
("KP8", 80),
("KP9", 81),
("KPSU", 82),
("KP4", 83),
("KP5", 84),
("KP6", 85),
("KPAD", 86),
("KP1", 87),
("KP2", 88),
("KP3", 89),
("KP0", 90),
("KPDL", 91),
("KPDV", 106),
("KPMU", 63),
]
for r in rows {
m.set(r.0, r.1)
}
m
}
///| The US layout, used when there is no keymap.
let us_symbols : String =
#|xkb_symbols "us" {
#| key <TLDE> { [ grave, asciitilde ] };
#| key <AE01> { [ 1, exclam ] };
#| key <AE02> { [ 2, at ] };
#| key <AE03> { [ 3, numbersign ] };
#| key <AE04> { [ 4, dollar ] };
#| key <AE05> { [ 5, percent ] };
#| key <AE06> { [ 6, asciicircum ] };
#| key <AE07> { [ 7, ampersand ] };
#| key <AE08> { [ 8, asterisk ] };
#| key <AE09> { [ 9, parenleft ] };
#| key <AE10> { [ 0, parenright ] };
#| key <AE11> { [ minus, underscore ] };
#| key <AE12> { [ equal, plus ] };
#| key <AD01> { [ q, Q ] };
#| key <AD02> { [ w, W ] };
#| key <AD03> { [ e, E ] };
#| key <AD04> { [ r, R ] };
#| key <AD05> { [ t, T ] };
#| key <AD06> { [ y, Y ] };
#| key <AD07> { [ u, U ] };
#| key <AD08> { [ i, I ] };
#| key <AD09> { [ o, O ] };
#| key <AD10> { [ p, P ] };
#| key <AD11> { [ bracketleft, braceleft ] };
#| key <AD12> { [ bracketright, braceright ] };
#| key <AC01> { [ a, A ] };
#| key <AC02> { [ s, S ] };
#| key <AC03> { [ d, D ] };
#| key <AC04> { [ f, F ] };
#| key <AC05> { [ g, G ] };
#| key <AC06> { [ h, H ] };
#| key <AC07> { [ j, J ] };
#| key <AC08> { [ k, K ] };
#| key <AC09> { [ l, L ] };
#| key <AC10> { [ semicolon, colon ] };
#| key <AC11> { [ apostrophe, quotedbl ] };
#| key <BKSL> { [ backslash, bar ] };
#| key <AB01> { [ z, Z ] };
#| key <AB02> { [ x, X ] };
#| key <AB03> { [ c, C ] };
#| key <AB04> { [ v, V ] };
#| key <AB05> { [ b, B ] };
#| key <AB06> { [ n, N ] };
#| key <AB07> { [ m, M ] };
#| key <AB08> { [ comma, less ] };
#| key <AB09> { [ period, greater ] };
#| key <AB10> { [ slash, question ] };
#| key <SPCE> { [ space ] };
#| key <KP7> { [ KP_7 ] };
#| key <KP8> { [ KP_8 ] };
#| key <KP9> { [ KP_9 ] };
#| key <KP4> { [ KP_4 ] };
#| key <KP5> { [ KP_5 ] };
#| key <KP6> { [ KP_6 ] };
#| key <KP1> { [ KP_1 ] };
#| key <KP2> { [ KP_2 ] };
#| key <KP3> { [ KP_3 ] };
#| key <KP0> { [ KP_0 ] };
#| key <KPDL> { [ KP_Decimal ] };
#| key <KPAD> { [ KP_Add ] };
#| key <KPSU> { [ KP_Subtract ] };
#| key <KPMU> { [ KP_Multiply ] };
#| key <KPDV> { [ KP_Divide ] };
#|};
///| The keymap `text` describes, or the US layout when it is empty or unusable.
pub fn Keymap::from_text(text : String) -> Keymap {
match Keymap::parse(text) {
Some(k) => k
None => Keymap::us()
}
}
///| The built-in US layout.
pub fn Keymap::us() -> Keymap {
Keymap::parse(us_symbols).unwrap()
}