Face unlock window: live camera preview, Snap, thumbnails, one password on Apply
CI / test (push) Failing after 12m30s

Settings > Session "Add or remove faces…" (and "Remove…" on a face) opens a
compositor-drawn Face unlock window instead of running root steps one by one:

- chandra-face camera runs as the user (no password): it streams a small live
  picture with the face box and a cropped thumbnail per snap; the snaps'
  embeddings stay in that process, nothing is written to disk.
- Click a snap to drop it; mark saved faces Remove/Keep.
- Apply saves the snaps as one face and removes the marked ones in one root
  `chandra-face apply` (JSON on stdin, validated) through run0/pkexec: one
  password prompt.
- New raster host function image-pixels (host-wasm, wasmhost, native) for the
  window's pictures.

Tests: camera session and apply in face/test_face.py; the window end to end
against a fake tool in compositor/host/face_test.mbt. Docs explain why the
change itself still needs root.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
This commit is contained in:
Claude committed 2026-11-26 02:36:29 +00:00
1 parent 0a9787ae36
commit 9f7489cfea
74 files changed
+2617 -89

No files matched your search

@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/compositor/gen"
// Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/compositor/gen/world/compositor"
// Values
pub fn run(Array[String]) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,27 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/icon-desktop/gen/interface/chandra/desktop/desktop-module"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn backdrop() -> WallpaperMode
pub fn on_scroll(@types.Point, Int32, Int32) -> Bool
pub fn tick(UInt32) -> UInt32
// Errors
// Types and methods
pub(all) enum WallpaperMode {
OVER_WALLPAPER
REPLACE_WALLPAPER
}
pub fn WallpaperMode::from(Int32) -> Self
pub fn WallpaperMode::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -0,0 +1,21 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/icon-desktop/gen/interface/chandra/desktop/module-config"
// Values
pub fn config_items() -> Array[ConfigItem]
pub fn set_config(String, String) -> Bool
// Errors
// Types and methods
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
}
// Type aliases
// Traits
@@ -0,0 +1,42 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/icon-desktop/gen/interface/chandra/desktop/plasmoid"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn info() -> PlasmoidInfo
pub fn on_event(Surface, @types.InputEvent) -> Bool
pub fn popup() -> PopupSurface?
pub fn render(@types.Size) -> Array[@types.DrawOp]
// Errors
// Types and methods
pub(all) struct PlasmoidInfo {
id : String
name : String
preferred : @types.Size
min_width : UInt32
stretch : Bool
}
pub(all) struct PopupSurface {
size : @types.Size
ops : Array[@types.DrawOp]
}
pub(all) enum Surface {
WIDGET
POPUP
}
pub fn Surface::from(Int32) -> Self
pub fn Surface::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/icon-desktop/gen"
// Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,42 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/inspector/gen/interface/chandra/desktop/plasmoid"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn info() -> PlasmoidInfo
pub fn on_event(Surface, @types.InputEvent) -> Bool
pub fn popup() -> PopupSurface?
pub fn render(@types.Size) -> Array[@types.DrawOp]
// Errors
// Types and methods
pub(all) struct PlasmoidInfo {
id : String
name : String
preferred : @types.Size
min_width : UInt32
stretch : Bool
}
pub(all) struct PopupSurface {
size : @types.Size
ops : Array[@types.DrawOp]
}
pub(all) enum Surface {
WIDGET
POPUP
}
pub fn Surface::from(Int32) -> Self
pub fn Surface::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/inspector/gen"
// Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,42 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/layout/gen/interface/chandra/desktop/plasmoid"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn info() -> PlasmoidInfo
pub fn on_event(Surface, @types.InputEvent) -> Bool
pub fn popup() -> PopupSurface?
pub fn render(@types.Size) -> Array[@types.DrawOp]
// Errors
// Types and methods
pub(all) struct PlasmoidInfo {
id : String
name : String
preferred : @types.Size
min_width : UInt32
stretch : Bool
}
pub(all) struct PopupSurface {
size : @types.Size
ops : Array[@types.DrawOp]
}
pub(all) enum Surface {
WIDGET
POPUP
}
pub fn Surface::from(Int32) -> Self
pub fn Surface::ordinal(Self) -> Int32
// Type aliases
// Traits
+13
View File
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/layout/gen"
// Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,42 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/network/gen/interface/chandra/desktop/plasmoid"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn info() -> PlasmoidInfo
pub fn on_event(Surface, @types.InputEvent) -> Bool
pub fn popup() -> PopupSurface?
pub fn render(@types.Size) -> Array[@types.DrawOp]
// Errors
// Types and methods
pub(all) struct PlasmoidInfo {
id : String
name : String
preferred : @types.Size
min_width : UInt32
stretch : Bool
}
pub(all) struct PopupSurface {
size : @types.Size
ops : Array[@types.DrawOp]
}
pub(all) enum Surface {
WIDGET
POPUP
}
pub fn Surface::from(Int32) -> Self
pub fn Surface::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -0,0 +1,42 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/screenshot/gen/interface/chandra/desktop/plasmoid"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn info() -> PlasmoidInfo
pub fn on_event(Surface, @types.InputEvent) -> Bool
pub fn popup() -> PopupSurface?
pub fn render(@types.Size) -> Array[@types.DrawOp]
// Errors
// Types and methods
pub(all) struct PlasmoidInfo {
id : String
name : String
preferred : @types.Size
min_width : UInt32
stretch : Bool
}
pub(all) struct PopupSurface {
size : @types.Size
ops : Array[@types.DrawOp]
}
pub(all) enum Surface {
WIDGET
POPUP
}
pub fn Surface::from(Int32) -> Self
pub fn Surface::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/screenshot/gen"
// Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,44 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/session-settings/gen/interface/chandra/desktop/plasmoid"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn info() -> PlasmoidInfo
pub fn on_event(Surface, @types.InputEvent) -> Bool
pub fn popup() -> PopupSurface?
pub fn render(@types.Size) -> Array[@types.DrawOp]
// Errors
// Types and methods
pub(all) struct PlasmoidInfo {
id : String
name : String
preferred : @types.Size
min_width : UInt32
stretch : Bool
}
pub(all) struct PopupSurface {
size : @types.Size
ops : Array[@types.DrawOp]
}
type Row
pub(all) enum Surface {
WIDGET
POPUP
}
pub fn Surface::from(Int32) -> Self
pub fn Surface::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -96,9 +96,9 @@ enum Row {
AppOption(Int, Int, @default_apps.AppChoice) AppOption(Int, Int, @default_apps.AppChoice)
/// Face unlock's switch: the password dialog and sudo try the face first. /// Face unlock's switch: the password dialog and sudo try the face first.
FaceUse FaceUse
/// An enrolled face: its index, label and when it was added (a second click removes it). /// An enrolled face: its index, label and when it was added ("Remove…" opens the window).
FaceRow(Int, String, String) FaceRow(Int, String, String)
/// "Add a face..." /// "Add or remove faces..." (the Face unlock window)
FaceAdd FaceAdd
} }
@@ -305,7 +305,8 @@ fn rows() -> Array[Row] {
} }
///| Face unlock's rows on the Session tab (docs/face-unlock.md): the switch, the enrolled faces, ///| Face unlock's rows on the Session tab (docs/face-unlock.md): the switch, the enrolled faces,
/// "Add a face..." and what the last change said. Changes ask for the password first. /// "Add or remove faces..." and what the last change said. Changes ask for the password first
/// (the window's Apply asks once for everything).
fn face_rows(rs : Array[Row]) -> Unit { fn face_rows(rs : Array[Row]) -> Unit {
let st = @face_unlock.status() let st = @face_unlock.status()
rs.push(Heading("Face unlock")) rs.push(Heading("Face unlock"))
@@ -329,11 +330,6 @@ fn face_rows(rs : Array[Row]) -> Unit {
} }
} }
///| `armed` value for "click again to remove" on face `i`.
fn face_armed(i : Int) -> Int {
100 + i
}
///| Whether row `i` of `rs` can be highlighted and acted on (headings can't). ///| Whether row `i` of `rs` can be highlighted and acted on (headings can't).
fn active(rs : Array[Row], i : Int) -> Bool { fn active(rs : Array[Row], i : Int) -> Bool {
i >= 0 && i < rs.length() && !(rs[i] is (Heading(_) | Info(_) | Category(_) | NothingToAdd)) i >= 0 && i < rs.length() && !(rs[i] is (Heading(_) | Info(_) | Category(_) | NothingToAdd))
@@ -517,12 +513,8 @@ fn act(rs : Array[Row], i : Int, btn~ : Int = -1, x~ : Int = 0) -> Unit {
if !@face_unlock.status().busy { if !@face_unlock.status().busy {
@face_unlock.set_in_use(!@face_unlock.status().in_use) @face_unlock.set_in_use(!@face_unlock.status().in_use)
} }
FaceRow(k, _, _) => // Both open the Face unlock window (nothing changes until its Apply).
if was_armed == face_armed(k) { FaceRow(k, _, _) => if !@face_unlock.status().busy { @face_unlock.remove(k.reinterpret_as_uint()) }
@face_unlock.remove(k.reinterpret_as_uint())
} else {
armed.val = face_armed(k)
}
FaceAdd => if !@face_unlock.status().busy { @face_unlock.enroll() } FaceAdd => if !@face_unlock.status().busy { @face_unlock.enroll() }
Shortcut(k, sc) => Shortcut(k, sc) =>
if sc.capturing { if sc.capturing {
@@ -691,7 +683,8 @@ pub fn popup() -> PopupSurface? {
switch_ops(w, mid, st.in_use, p, ops) switch_ops(w, mid, st.in_use, p, ops)
} }
FaceRow(k, label, added) => { FaceRow(k, label, added) => {
// A face glyph, the label and date; "Remove" at the right (a second click removes). // A face glyph, the label and date; "Remove…" at the right (opens the Face unlock window
// with this face marked).
let gx = margin + 18 let gx = margin + 18
ops.push(@ui.circle(gx, mid, 7, list_fg, filled=false)) ops.push(@ui.circle(gx, mid, 7, list_fg, filled=false))
ops.push(@ui.circle(gx - 3, mid - 2, 1, list_fg)) ops.push(@ui.circle(gx - 3, mid - 2, 1, list_fg))
@@ -700,13 +693,12 @@ pub fn popup() -> PopupSurface? {
ops.push(@ui.text(margin + 32, mid, label, fs - 1, list_fg)) ops.push(@ui.text(margin + 32, mid, label, fs - 1, list_fg))
let lw = @ui.text_width(label, fs - 1) let lw = @ui.text_width(label, fs - 1)
ops.push(@ui.text(margin + 40 + lw, mid, "added " + added, fs - 3, if hot { list_fg } else { p.foreground_muted })) ops.push(@ui.text(margin + 40 + lw, mid, "added " + added, fs - 3, if hot { list_fg } else { p.foreground_muted }))
let armed_here = armed.val == face_armed(k) ignore(k)
let rlabel = if armed_here { "Click again to remove" } else { "Remove" } ops.push(@ui.text(w - margin - 10, mid, "Remove…", fs - 2, if hot { list_fg } else { p.accent }, align=RIGHT))
ops.push(@ui.text(w - margin - 10, mid, rlabel, fs - 2, if hot { list_fg } else { p.accent }, align=RIGHT, bold=armed_here))
} }
FaceAdd => { FaceAdd => {
let busy = @face_unlock.status().busy let busy = @face_unlock.status().busy
ops.push(@ui.text(margin + 10, mid, if busy { "Working…" } else { "Add a face…" }, fs - 1, if busy && !hot { p.foreground_muted } else { list_fg }, bold=true)) ops.push(@ui.text(margin + 10, mid, if busy { "Working…" } else { "Add or remove faces…" }, fs - 1, if busy && !hot { p.foreground_muted } else { list_fg }, bold=true))
} }
DesktopChoice(k, name) => { DesktopChoice(k, name) => {
if k == cur_desk { if k == cur_desk {
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/session-settings/gen"
// Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,27 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/starfield/gen/interface/chandra/desktop/desktop-module"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn backdrop() -> WallpaperMode
pub fn on_scroll(@types.Point, Int32, Int32) -> Bool
pub fn tick(UInt32) -> UInt32
// Errors
// Types and methods
pub(all) enum WallpaperMode {
OVER_WALLPAPER
REPLACE_WALLPAPER
}
pub fn WallpaperMode::from(Int32) -> Self
pub fn WallpaperMode::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -0,0 +1,21 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/starfield/gen/interface/chandra/desktop/module-config"
// Values
pub fn config_items() -> Array[ConfigItem]
pub fn set_config(String, String) -> Bool
// Errors
// Types and methods
pub(all) struct ConfigItem {
key : String
label : String
choices : Array[String]
value : String
}
// Type aliases
// Traits
@@ -0,0 +1,42 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/starfield/gen/interface/chandra/desktop/plasmoid"
import {
"chandra/desktop/interface/chandra/desktop/types",
}
// Values
pub fn info() -> PlasmoidInfo
pub fn on_event(Surface, @types.InputEvent) -> Bool
pub fn popup() -> PopupSurface?
pub fn render(@types.Size) -> Array[@types.DrawOp]
// Errors
// Types and methods
pub(all) struct PlasmoidInfo {
id : String
name : String
preferred : @types.Size
min_width : UInt32
stretch : Bool
}
pub(all) struct PopupSurface {
size : @types.Size
ops : Array[@types.DrawOp]
}
pub(all) enum Surface {
WIDGET
POPUP
}
pub fn Surface::from(Int32) -> Self
pub fn Surface::ordinal(Self) -> Int32
// Type aliases
// Traits
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/components/starfield/gen"
// Values
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
// Errors
// Types and methods
// Type aliases
// Traits
+3
View File
@@ -7,6 +7,9 @@ pub fn run(Array[String]) -> Int32
// Errors // Errors
// Types and methods // Types and methods
type IdleClock
type Pacer
// Type aliases // Type aliases
+15
View File
@@ -193,6 +193,10 @@ pub(all) struct ChandraCompositor {
mut polkit_bus : String mut polkit_bus : String
mut auth : AuthUi? mut auth : AuthUi?
auth_swallow : Array[UInt] auth_swallow : Array[UInt]
/// The Face unlock window (face_window.mbt): where its controls were drawn, and the change of
/// it last drawn.
face_hits : Array[(@scene.Rect, FaceHit)]
mut face_rev : Int
mut auth_routes : Array[@polkit.HelperRoute] mut auth_routes : Array[@polkit.HelperRoute]
mut keymap : (Bytes, @polkit.Keymap)? mut keymap : (Bytes, @polkit.Keymap)?
/// How requests are put into words (tests pass their own process lookups); None: the usual. /// How requests are put into words (tests pass their own process lookups); None: the usual.
@@ -236,6 +240,8 @@ pub fn ChandraCompositor::new(
polkit_bus: "", polkit_bus: "",
auth: None, auth: None,
auth_swallow: [], auth_swallow: [],
face_hits: [],
face_rev: -1,
auth_routes: [], auth_routes: [],
keymap: None, keymap: None,
auth_describe: None, auth_describe: None,
@@ -478,6 +484,7 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
self.kiosk_tick() self.kiosk_tick()
self.portal_tick() self.portal_tick()
self.auth_tick() self.auth_tick()
self.face_window_tick()
self.control_tick() self.control_tick()
let events = self.server.poll_events() let events = self.server.poll_events()
for ev in events { for ev in events {
@@ -906,6 +913,7 @@ fn ChandraCompositor::build_scene(
panel_ops.append(self.switcher_ops()) panel_ops.append(self.switcher_ops())
} }
panel_ops.append(self.screenshot_ops()) panel_ops.append(self.screenshot_ops())
panel_ops.append(self.face_window_ops())
panel_ops.append(self.auth_ops()) panel_ops.append(self.auth_ops())
self.frames_built = self.frames_built + 1 self.frames_built = self.frames_built + 1
self.run_shell_actions() self.run_shell_actions()
@@ -1506,6 +1514,10 @@ pub fn ChandraCompositor::handle_input(
if self.auth_input(ev) { if self.auth_input(ev) {
return return
} }
// So does the Face unlock window (below the password dialog it opens on Apply).
if self.face_window_input(ev) {
return
}
match ev { match ev {
Key(code, pressed) => { Key(code, pressed) => {
self.track_modifier_key(code, pressed) self.track_modifier_key(code, pressed)
@@ -1868,6 +1880,9 @@ pub fn ChandraCompositor::desired_cursor(self : ChandraCompositor) -> UInt {
Some(ui) => return self.auth_cursor(ui) Some(ui) => return self.auth_cursor(ui)
None => () None => ()
} }
if self.shell.face.window is Some(_) {
return if self.face_window_hit() is Some(_) { 4U } else { 1U }
}
match self.shot { match self.shot {
Some(o) => return self.overlay_cursor(o) Some(o) => return self.overlay_cursor(o)
None => () None => ()
+74 -13
View File
@@ -20,6 +20,27 @@ fn fake_face_tool(dir : String) -> String {
#|remove) #|remove)
#| grep -v "^face $2 " "$S/faces" > "$S/faces.new"; mv "$S/faces.new" "$S/faces" #| grep -v "^face $2 " "$S/faces" > "$S/faces.new"; mv "$S/faces.new" "$S/faces"
#| echo "done Removed face $2" ;; #| echo "done Removed face $2" ;;
#|camera)
#| # The Face unlock window's camera: a grey 4x3 picture with a face box, a white 2x2
#| # thumbnail per snap, and an apply that changes the faces file.
#| pic() { printf 'frame 4 3 1 0 2 2 36\n'; head -c 36 /dev/zero | tr '\000' '\200'; }
#| echo "info Look at the camera and press Snap"; pic
#| n=0; kept=0
#| while read -r cmd arg; do
#| case "$cmd" in
#| snap) n=$((n+1)); kept=$((kept+1)); printf 'snap %d 2 2 12\n' $n; head -c 12 /dev/zero | tr '\000' '\377'; pic ;;
#| drop) kept=$((kept-1)); pic ;;
#| apply)
#| echo "info Waiting for the password…"
#| for id in $(echo "$arg" | tr ',' ' '); do
#| grep -v "^face $id " "$S/faces" > "$S/faces.new"; mv "$S/faces.new" "$S/faces"
#| done
#| [ $kept -gt 0 ] && printf 'face 2\tFace 2\t2026-11-26\n' >> "$S/faces"
#| echo "$kept $arg" > "$S/applied"
#| echo "done Added Face 2 and removed 1 face"; echo "applied 0"; exit 0 ;;
#| quit) exit 0 ;;
#| esac
#| done ;;
#|pam) #|pam)
#| if [ "$2" = enable ]; then echo "polkit-1,sudo" > "$S/pam"; else : > "$S/pam"; fi #| if [ "$2" = enable ]; then echo "polkit-1,sudo" > "$S/pam"; else : > "$S/pam"; fi
#| echo "done ok" ;; #| echo "done ok" ;;
@@ -65,7 +86,7 @@ fn face_click(comp : @host.ChandraCompositor, label : String, t : UInt) -> Unit
} }
///| ///|
test "Settings > Session: face unlock lists faces, adds one, turns it on, removes one" { test "Settings > Session: face unlock lists faces and turns it on" {
let dir = "/tmp/chandra-face-test-" + @sys.getpid().to_string() let dir = "/tmp/chandra-face-test-" + @sys.getpid().to_string()
let tool = fake_face_tool(dir) let tool = fake_face_tool(dir)
let comp = new_comp("face") let comp = new_comp("face")
@@ -77,12 +98,8 @@ test "Settings > Session: face unlock lists faces, adds one, turns it on, remove
assert_true(texts.contains("Face unlock")) assert_true(texts.contains("Face unlock"))
assert_true(texts.contains("Use my face for passwords")) assert_true(texts.contains("Use my face for passwords"))
assert_true(texts.contains("added 2026-11-20")) assert_true(texts.contains("added 2026-11-20"))
assert_true(texts.contains("Add a face…")) assert_true(texts.contains("Add or remove faces…"))
assert_false(comp.shell.face.in_use()) assert_false(comp.shell.face.in_use())
// Add a face: the tool's progress shows, then the new face.
face_click(comp, "Add a face…", 10U)
assert_true(face_settle(comp, fn() { face_texts(comp).contains("Face 2") }))
assert_true(face_texts(comp).contains("Added Face 2"))
// The switch: polkit-1 and sudo try the face first. // The switch: polkit-1 and sudo try the face first.
face_click(comp, "Use my face for passwords", 20U) face_click(comp, "Use my face for passwords", 20U)
assert_true(face_settle(comp, fn() { comp.shell.face.in_use() })) assert_true(face_settle(comp, fn() { comp.shell.face.in_use() }))
@@ -90,13 +107,57 @@ test "Settings > Session: face unlock lists faces, adds one, turns it on, remove
if shots != "" { if shots != "" {
ignore(@sys.write_file_bytes(shots + "/16-settings-face.png", @renderer.encode_png_compressed(comp.compose_frame()))) ignore(@sys.write_file_bytes(shots + "/16-settings-face.png", @renderer.encode_png_compressed(comp.compose_frame())))
} }
// Remove takes a second click. comp.close()
face_click(comp, "Remove", 30U) }
assert_true(face_texts(comp).contains("Click again to remove"))
assert_eq(comp.shell.face.faces.length(), 2) ///|
face_click(comp, "Click again to remove", 40U) fn face_key(comp : @host.ChandraCompositor, code : UInt, t : UInt) -> Unit {
assert_true(face_settle(comp, fn() { comp.shell.face.faces.length() == 1 })) comp.handle_input(@nested.InputEvent::Key(code, true), t)
assert_eq(comp.shell.face.faces[0].1, "Face 2") comp.handle_input(@nested.InputEvent::Key(code, false), t + 1U)
ignore(comp.compose_frame())
}
///|
test "the Face unlock window: live picture, snaps, a face marked for removal, one Apply" {
let dir = "/tmp/chandra-face-win-" + @sys.getpid().to_string()
let tool = fake_face_tool(dir)
let comp = new_comp("facewin")
comp.shell.set_face_tool(["/bin/sh", tool])
assert_true(comp.shell.open_settings(Session))
assert_true(face_settle(comp, fn() { face_texts(comp).contains("Desk") }))
// "Remove…" on a face opens the window with that face marked; nothing is removed yet.
face_click(comp, "Remove…", 10U)
assert_true(face_settle(comp, fn() { comp.shell.face.window.map(w => w.picture != 0U).unwrap_or(false) }))
let w = comp.shell.face.window.unwrap()
assert_eq(w.remove, ["1"])
assert_eq((w.pic_w, w.pic_h, w.face_box), (4, 3, Some((1, 0, 2, 2))))
assert_eq(w.message, "Look at the camera and press Snap")
// Space snaps (the window has the keyboard), twice; one snap is dropped again.
face_key(comp, 57U, 20U)
assert_true(face_settle(comp, fn() { w.snaps.length() == 1 }))
face_key(comp, 57U, 30U)
assert_true(face_settle(comp, fn() { w.snaps.length() == 2 }))
assert_eq(w.message, "2 pictures: snap more, or press Apply")
comp.shell.face.drop_snap(0)
assert_eq(w.snaps.map(s => s.id), ["2"])
assert_eq(w.message, "1 picture: turn a little and snap again, or press Apply")
let shots = @sys.getenv("CHANDRA_AUTH_SHOTS")
if shots != "" {
ignore(@sys.write_file_bytes(shots + "/17-face-window.png", @renderer.encode_png_compressed(comp.compose_frame())))
}
assert_eq(comp.shell.face.faces.length(), 1)
// Enter applies: one run for the snap and the removal; the window closes, Settings shows it.
face_key(comp, 28U, 40U)
assert_true(face_settle(comp, fn() { comp.shell.face.window is None }))
assert_true(face_settle(comp, fn() { face_texts(comp).contains("Face 2") }))
assert_eq(comp.shell.face.faces.map(f => f.1), ["Face 2"])
assert_eq(comp.shell.face.message, "Added Face 2 and removed 1 face")
assert_eq(@sys.read_file_bytes(dir + "/applied") |> @utf8.decode_lossy, "1 1\n")
// Esc cancels without changing anything.
face_click(comp, "Add or remove faces…", 50U)
assert_true(face_settle(comp, fn() { comp.shell.face.window is Some(_) }))
face_key(comp, 1U, 60U)
assert_true(comp.shell.face.window is None)
comp.close() comp.close()
} }
+290
View File
@@ -0,0 +1,290 @@
///| The Face unlock window (docs/face-unlock.md): Settings > Session > "Add or remove faces…"
/// opens it. A live camera picture with the face box, Snap to keep the picture in view (its
/// thumbnail shows below; click one to drop it), the saved faces with Remove / Keep, and Apply,
/// which saves the snaps and removes the marked faces in one root step: polkit asks for the
/// password once, in the password dialog drawn above this window.
///
/// The camera runs as the user (`chandra-face camera`, compositor/shell/face.mbt); the pictures
/// only live in memory, and only the face data (embeddings) is saved.
///
/// Like the password dialog it is drawn by the compositor above the windows, on a dimmed
/// screen, and takes the keyboard and the pointer while it is up: Space snaps, Enter applies,
/// Esc cancels.
///| A control of the window.
pub(all) enum FaceHit {
Snap
DropSnap(Int)
ToggleFace(String)
Apply
Cancel
} derive(Eq)
///| Follow the camera process and redraw when the window changed.
fn ChandraCompositor::face_window_tick(self : ChandraCompositor) -> Unit {
let f = self.shell.face
f.poll_window()
if f.window_rev != self.face_rev {
self.face_rev = f.window_rev
self.damage.mark_full()
}
}
///| The control under the pointer.
fn ChandraCompositor::face_window_hit(self : ChandraCompositor) -> FaceHit? {
let x = self.ptr_x.to_int()
let y = self.ptr_y.to_int()
for h in self.face_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
}
///| Do what control `h` does.
fn ChandraCompositor::face_window_activate(self : ChandraCompositor, h : FaceHit) -> Unit {
let f = self.shell.face
match h {
Snap => f.snap()
DropSnap(i) => f.drop_snap(i)
ToggleFace(id) => f.toggle_remove(id)
Apply => f.apply()
Cancel => f.cancel_window()
}
self.damage.mark_full()
}
///| Input while the window is up: all of it goes to the window.
fn ChandraCompositor::face_window_input(self : ChandraCompositor, ev : @nested.InputEvent) -> Bool {
if self.shell.face.window is None {
return false
}
match ev {
Key(code, pressed) => {
if code == key_lsuper || code == key_rsuper {
self.super_solo = false
}
if pressed {
self.auth_swallow.push(code)
if code == key_esc {
self.face_window_activate(Cancel)
} else if code == key_enter || code == key_kp_enter {
self.face_window_activate(Apply)
} else if code == key_space {
self.face_window_activate(Snap)
}
}
true
}
Modifiers(_, _, _, _) => true
PointerMove(x, y) => {
self.ptr_x = x
self.ptr_y = y
self.damage.mark_full()
true
}
PointerButton(button, pressed) => {
if pressed && button == 272U {
match self.face_window_hit() {
Some(h) => self.face_window_activate(h)
None => ()
}
}
true
}
Scroll(_, _, _) => true
}
}
///|
let key_space : UInt = 57
///| The window, when it is open.
fn ChandraCompositor::face_window_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] {
let ops : Array[@scene.DrawOp] = []
let f = self.shell.face
let win = match f.window {
Some(w) => w
None => {
self.face_hits.clear()
return ops
}
}
let p = self.theme.palette
let (err_c, _) = auth_colors(p)
let fs = self.theme.font_size
let rad = self.theme.radius + 2
let sw = self.output_w
let sh = self.output_h
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, sh), @scene.Rgba::new(0, 0, 0, 150), 0))
let w = (sw - 32).min(560)
let pad = 24
let inner = w - pad * 2
let hover = self.face_window_hit()
let body : Array[@scene.DrawOp] = []
let hits : Array[(@scene.Rect, FaceHit)] = []
let mut y = pad
body.push(@scene.DrawOp::Text(pad, y + 7, "FACE UNLOCK", fs - 3, p.accent, @scene.TextAlign::Left, true))
y = y + 18
body.push(@scene.DrawOp::Text(pad, y + (fs + 8) / 2, "Add or remove faces", fs + 3, p.foreground, @scene.TextAlign::Left, true))
y = y + fs + 10
let intro = "Snap a few pictures: straight on, turned a little, with and without glasses. " +
"Pictures stay in memory; Apply saves only the face data, after one password."
for l in wrap_text(intro, fs - 1, false, false, inner) {
body.push(@scene.DrawOp::Text(pad, y + (fs + 4) / 2, l, fs - 1, p.foreground_muted, @scene.TextAlign::Left, false))
y = y + fs + 4
}
y = y + 12
// The live picture, as big as fits (4:3 until the first one says otherwise).
let (aw, ah) = if win.pic_w > 0 && win.pic_h > 0 { (win.pic_w, win.pic_h) } else { (4, 3) }
let max_h = (sh * 2 / 5).max(120)
let mut pw = inner
let mut ph = pw * ah / aw
if ph > max_h {
ph = max_h
pw = ph * aw / ah
}
let pr = @scene.Rect::new(pad + (inner - pw) / 2, y, pw, ph)
body.push(@scene.DrawOp::FillRect(pr, @scene.Rgba::new(16, 16, 18, 255), rad))
if win.picture != 0U && !win.ended {
body.push(@scene.DrawOp::Image(pr, win.picture))
match win.face_box {
Some((bx, by, bw, bh)) => {
let r = @scene.Rect::new(pr.x + bx * pw / win.pic_w, pr.y + by * ph / win.pic_h, bw * pw / win.pic_w, bh * ph / win.pic_h)
body.push(@scene.DrawOp::StrokeRect(r, p.accent, 2, 6))
}
None => ()
}
} else {
face_glyph(pr.x + pw / 2, pr.y + ph / 2 - 12, 22, @scene.Rgba::new(120, 120, 128, 255), body)
let t = if win.ended { "No camera picture" } else { "Starting the camera…" }
body.push(@scene.DrawOp::Text(pr.x + pw / 2, pr.y + ph / 2 + 30, t, fs - 1, @scene.Rgba::new(200, 200, 205, 255), @scene.TextAlign::Center, false))
}
y = y + ph + 12
// What the camera said, and Snap.
let bh = 34
let snap_w = @renderer.text_width("Snap", fs, true, false) + 40
let sr = @scene.Rect::new(pad + inner - snap_w, y, snap_w, bh)
let can_snap = !win.applying && !win.ended && win.picture != 0U
auth_button(sr, "Snap", true, false, hover == Some(Snap), can_snap, p, fs, rad, body)
if can_snap {
hits.push((sr, Snap))
}
let msg_lines = wrap_text(win.message, fs - 1, false, false, inner - snap_w - 12)
let mut my = y + bh / 2 - (msg_lines.length() - 1) * (fs + 3) / 2
for l in msg_lines {
body.push(@scene.DrawOp::Text(pad, my, l, fs - 1, if win.error { err_c } else { p.foreground }, @scene.TextAlign::Left, false))
my = my + fs + 3
}
y = y + bh.max(msg_lines.length() * (fs + 3)) + 14
// The snaps: click one to drop it.
if win.snaps.length() > 0 {
body.push(@scene.DrawOp::Text(pad, y + 8, "New pictures (click one to drop it)", fs - 2, p.foreground_muted, @scene.TextAlign::Left, true))
y = y + 20
let ts = 64
let gap = 8
let per_row = ((inner + gap) / (ts + gap)).max(1)
for i, s in win.snaps {
let r = @scene.Rect::new(pad + i % per_row * (ts + gap), y + i / per_row * (ts + gap), ts, ts)
body.push(@scene.DrawOp::Image(r, s.image))
let hov = hover == Some(DropSnap(i))
body.push(@scene.DrawOp::StrokeRect(r, if hov { err_c } else { p.border }, if hov { 2 } else { 1 }, 4))
if hov {
// A cross over it: this one goes.
body.push(@scene.DrawOp::Circle(r.x + ts - 10, r.y + 10, 8, err_c, true))
body.push(@scene.DrawOp::Line(r.x + ts - 13, r.y + 7, r.x + ts - 7, r.y + 13, p.surface_popup, 2))
body.push(@scene.DrawOp::Line(r.x + ts - 7, r.y + 7, r.x + ts - 13, r.y + 13, p.surface_popup, 2))
}
if !win.applying {
hits.push((r, DropSnap(i)))
}
}
y = y + (win.snaps.length() + per_row - 1) / per_row * (ts + gap) + 8
}
// The saved faces, each with Remove / Keep.
if f.faces.length() > 0 {
body.push(@scene.DrawOp::Text(pad, y + 8, "Saved faces", fs - 2, p.foreground_muted, @scene.TextAlign::Left, true))
y = y + 20
let rh = 34
for face in f.faces {
let (id, label, added) = face
let marked = win.remove.contains(id)
let btn = if marked { "Keep" } else { "Remove" }
let bw = @renderer.text_width("Remove", fs - 1, false, false) + 28
let br = @scene.Rect::new(pad + inner - bw, y + 3, bw, rh - 6)
face_glyph(pad + 12, y + rh / 2, 9, if marked { p.foreground_muted } else { p.foreground }, body)
body.push(@scene.DrawOp::Text(pad + 32, y + rh / 2, label, fs, if marked { p.foreground_muted } else { p.foreground }, @scene.TextAlign::Left, !marked))
let lw = @renderer.text_width(label, fs, !marked, false)
let note = if marked { "will be removed" } else { "added " + added }
body.push(@scene.DrawOp::Text(pad + 32 + lw + 10, y + rh / 2, note, fs - 2, if marked { err_c } else { p.foreground_muted }, @scene.TextAlign::Left, false))
if marked {
body.push(@scene.DrawOp::Line(pad + 30, y + rh / 2, pad + 34 + lw, y + rh / 2, p.foreground_muted, 1))
}
auth_button(br, btn, false, false, hover == Some(ToggleFace(id)), !win.applying, p, fs - 1, rad, body)
if !win.applying {
hits.push((br, ToggleFace(id)))
}
y = y + rh
}
y = y + 8
}
// Footer: what Apply will do, Cancel, Apply.
y = y + 6
body.push(@scene.DrawOp::Line(pad, y, pad + inner, y, p.border, 1))
y = y + 14
let adds = win.snaps.length()
let rems = win.remove.length()
let summary = if win.applying {
"Saving…"
} else if adds == 0 && rems == 0 {
"Nothing to save yet"
} else {
let parts : Array[String] = []
if adds > 0 {
parts.push("adds a face from " + adds.to_string() + (if adds == 1 { " picture" } else { " pictures" }))
}
if rems > 0 {
parts.push("removes " + rems.to_string() + (if rems == 1 { " face" } else { " faces" }))
}
let s = parts.join(", ")
"Apply " + s
}
let apply_w = @renderer.text_width("Apply", fs, true, false) + 40
let cancel_w = @renderer.text_width("Cancel", fs, false, false) + 32
let ar = @scene.Rect::new(pad + inner - apply_w, y, apply_w, bh)
let cr = @scene.Rect::new(ar.x - 10 - cancel_w, y, cancel_w, bh)
let sl = wrap_text(summary, fs - 2, false, false, cr.x - pad - 12)
let sl = if sl.length() > 2 { sl[:2].to_array() } else { sl }
let lh = fs + 2
for i, l in sl {
body.push(@scene.DrawOp::Text(pad, y + bh / 2 - (sl.length() - 1) * lh / 2 + i * lh, l, fs - 2, p.foreground_muted, @scene.TextAlign::Left, false))
}
auth_button(cr, "Cancel", false, false, hover == Some(Cancel), !win.applying, p, fs, rad, body)
auth_button(ar, "Apply", true, false, hover == Some(Apply), win.can_apply(), p, fs, rad, body)
if !win.applying {
hits.push((cr, Cancel))
}
if win.can_apply() {
hits.push((ar, Apply))
}
y = y + bh + pad
// Centre the card, with the password dialog's shadow.
let h = y
let cx = (sw - w) / 2
let cyy = ((sh - h) / 2).max(8)
for k = 1; k <= 4; k = k + 1 {
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(cx - k * 2, cyy - k * 2 + 6, w + k * 4, h + k * 4), @scene.Rgba::new(0, 0, 0, 22), rad + 6 + k * 2))
}
let opaque = @scene.Rgba::new(p.surface_popup.r.to_int(), p.surface_popup.g.to_int(), p.surface_popup.b.to_int(), 255)
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(cx, cyy, w, h), opaque, rad + 6))
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(cx, cyy, w, h), p.border, 1, rad + 6))
ops.append(offset_ops_all(body, cx, cyy))
self.face_hits.clear()
for hit in hits {
let r = hit.0
self.face_hits.push((@scene.Rect::new(r.x + cx, r.y + cyy, r.w, r.h), hit.1))
}
ops
}
+13
View File
@@ -41,6 +41,19 @@ pub fn snapshot_pixels(_r : @scene.Rect, _w : Int, _h : Int) -> @renderer.Pixmap
abort("the host rasteriser is only available to the wasm compositor") abort("the host rasteriser is only available to the wasm compositor")
} }
///| `w` x `h` RGBA pixels as an image (`reuse`: an earlier handle of this kind to overwrite, or 0).
pub fn image_pixels(w : Int, h : Int, rgba : Bytes, reuse : UInt) -> UInt {
if w <= 0 || h <= 0 || w > 1024 || h > 1024 || rgba.length() < w * h * 4 {
return 0U
}
let p : @renderer.Pixmap = { width: w, height: h, data: rgba.to_fixedarray() }
if reuse == 0U {
@renderer.add_image(p)
} else {
@renderer.set_image(reuse, p)
}
}
///| Images already loaded, by path (0: it failed, don't try again). ///| Images already loaded, by path (0: it failed, don't try again).
let loaded_images : Map[String, UInt] = {} let loaded_images : Map[String, UInt] = {}
+5
View File
@@ -128,6 +128,11 @@ pub fn snapshot_pixels(r : @scene.Rect, w : Int, h : Int) -> @renderer.Pixmap {
{ width: w, height: h, data: @hostraster.snapshot_pixels(r.x, r.y, r.w, r.h, w, h) } { width: w, height: h, data: @hostraster.snapshot_pixels(r.x, r.y, r.w, r.h, w, h) }
} }
///| `w` x `h` RGBA pixels as an image (`reuse`: an earlier handle of this kind to overwrite, or 0).
pub fn image_pixels(w : Int, h : Int, rgba : Bytes, reuse : UInt) -> UInt {
@hostraster.image_pixels(w, h, rgba.to_fixedarray(), reuse)
}
///| Images already loaded, by path (0: it failed, don't ask the host again). ///| Images already loaded, by path (0: it failed, don't ask the host again).
let loaded_images : Map[String, UInt] = {} let loaded_images : Map[String, UInt] = {}
+2 -2
View File
@@ -24,10 +24,10 @@ pub fn render_scene(@scene.SceneGraph) -> Pixmap
pub fn scale_pixmap(Pixmap, Int32, Int32) -> Pixmap pub fn scale_pixmap(Pixmap, Int32, Int32) -> Pixmap
pub fn set_image(UInt32, Pixmap) -> UInt32
pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit
pub fn set_image(UInt32, Pixmap) -> UInt32
pub fn shm_thumbnail(@scene.ShmBufferSnapshot, Int32, Int32) -> Pixmap? pub fn shm_thumbnail(@scene.ShmBufferSnapshot, Int32, Int32) -> Pixmap?
pub fn text_width(String, Int32, Bool, Bool) -> Int32 pub fn text_width(String, Int32, Bool, Bool) -> Int32
+2
View File
@@ -92,6 +92,7 @@ pub(all) enum TextAlign {
Right Right
} }
#derive(Eq)
pub(all) struct ThemePalette { pub(all) struct ThemePalette {
desktop_top : Rgba desktop_top : Rgba
desktop_bottom : Rgba desktop_bottom : Rgba
@@ -105,6 +106,7 @@ pub(all) struct ThemePalette {
border : Rgba border : Rgba
} }
#derive(Eq)
pub(all) struct ThemeTokens { pub(all) struct ThemeTokens {
name : String name : String
palette : ThemePalette palette : ThemePalette
+384 -11
View File
@@ -3,8 +3,14 @@
/// gets all of it from `chandra-face` (face/chandra-face), run on a socket so the compositor /// gets all of it from `chandra-face` (face/chandra-face), run on a socket so the compositor
/// never waits on it: `status` as the user (labels only, no face data), and enroll / remove / /// never waits on it: `status` as the user (labels only, no face data), and enroll / remove /
/// `pam enable|disable` the same way, which re-run themselves through run0 or pkexec, so polkit /// `pam enable|disable` the same way, which re-run themselves through run0 or pkexec, so polkit
/// asks for an administrator's password (in Chandra's own dialog) before anything changes. The /// asks for an administrator's password (in Chandra's own dialog) before anything changes.
/// camera pictures stay inside that root process. ///
/// Adding and removing faces happens in the Face unlock window (FaceWindow, drawn by the host in
/// compositor/host/face_window.mbt): `chandra-face camera` runs as the user, with no password,
/// and streams a small live picture with the face box; Snap keeps a picture (its embedding stays
/// in that process, its thumbnail comes here); saved faces can be marked for removal; Apply hands
/// all of it to one root `chandra-face apply`, so the password is asked once. The pictures only
/// live in memory: that process's and the images here, which are dropped when the window closes.
///| What the shell knows about face unlock, and the chandra-face run in progress. ///| What the shell knows about face unlock, and the chandra-face run in progress.
pub(all) struct FaceUnlock { pub(all) struct FaceUnlock {
@@ -32,6 +38,43 @@ pub(all) struct FaceUnlock {
/// The status was read at least once. /// The status was read at least once.
mut loaded : Bool mut loaded : Bool
mut dirty : Bool mut dirty : Bool
/// The Face unlock window, while it is open, and a count of its changes (the host redraws).
mut window : FaceWindow?
mut window_rev : Int
/// Image handles to reuse for the live picture (two, in turn, so a new picture is a changed
/// draw op) and for snap thumbnails.
pics : Array[UInt]
spare_thumbs : Array[UInt]
}
///| A snap kept in the Face unlock window: its id in the camera process, and its thumbnail.
pub(all) struct FaceSnap {
id : String
image : UInt
}
///| The Face unlock window: the camera process (`chandra-face camera`) and what it showed.
pub(all) struct FaceWindow {
mut fd : Int
inbuf : Array[Byte]
/// A binary message's header words while its bytes are still coming, and how many.
mut header : Array[String]
mut need : Int
/// The live picture (0 until the first one), its size, and the face box in it.
mut picture : UInt
mut pic_w : Int
mut pic_h : Int
mut face_box : (Int, Int, Int, Int)?
mut pictures : Int
snaps : Array[FaceSnap]
/// Ids of saved faces marked for removal.
remove : Array[String]
mut message : String
mut error : Bool
/// Apply was pressed: the root step runs (or polkit is asking).
mut applying : Bool
/// When the camera process ended without a picture: the window shows why.
mut ended : Bool
} }
///| ///|
@@ -60,6 +103,10 @@ pub fn FaceUnlock::new() -> FaceUnlock {
queue: [], queue: [],
loaded: false, loaded: false,
dirty: true, dirty: true,
window: None,
window_rev: 0,
pics: [],
spare_thumbs: [],
} }
} }
@@ -255,10 +302,7 @@ pub fn FaceUnlock::request(self : FaceUnlock, code : Int) -> Unit {
return // one change at a time return // one change at a time
} }
match code { match code {
-2 => { -2 => self.open_window(None)
self.message = "Waiting for the password…"
self.run(["enroll"], true)
}
-3 => { -3 => {
self.message = "Waiting for the password…" self.message = "Waiting for the password…"
self.run(["pam", "disable"], true) self.run(["pam", "disable"], true)
@@ -267,10 +311,7 @@ pub fn FaceUnlock::request(self : FaceUnlock, code : Int) -> Unit {
self.message = "Waiting for the password…" self.message = "Waiting for the password…"
self.run(["pam", "enable"], true) self.run(["pam", "enable"], true)
} }
i if i >= 0 && i < self.faces.length() => { i if i >= 0 && i < self.faces.length() => self.open_window(Some(self.faces[i].0))
self.message = "Waiting for the password…"
self.run(["remove", self.faces[i].0], true)
}
_ => return _ => return
} }
self.dirty = true self.dirty = true
@@ -283,6 +324,337 @@ pub fn FaceUnlock::close(self : FaceUnlock) -> Unit {
self.fd = -1 self.fd = -1
} }
self.queue.clear() self.queue.clear()
self.close_window()
}
// ---- the Face unlock window ----
///| Open the Face unlock window (with saved face `mark` already marked for removal), starting
/// the camera as the user. When it is open already, only the mark is added.
pub fn FaceUnlock::open_window(self : FaceUnlock, mark : String?) -> Unit {
match self.window {
Some(w) => {
match mark {
Some(id) => if !w.remove.contains(id) { w.remove.push(id) }
None => ()
}
self.touch()
return
}
None => ()
}
let argv = self.tool.copy()
argv.append(["camera", "--machine"])
let fd = @sys.spawn_socket(argv)
let w : FaceWindow = {
fd,
inbuf: [],
header: [],
need: 0,
picture: 0U,
pic_w: 0,
pic_h: 0,
face_box: None,
pictures: 0,
snaps: [],
remove: match mark {
Some(id) => [id]
None => []
},
message: "Starting the camera…",
error: false,
applying: false,
ended: fd < 0,
}
if fd < 0 {
w.message = "Couldn't run chandra-face"
w.error = true
}
self.window = Some(w)
self.touch()
}
///| Something in the window changed: Settings and the host redraw.
fn FaceUnlock::touch(self : FaceUnlock) -> Unit {
self.dirty = true
self.window_rev = self.window_rev + 1
}
///| Send a command line to the camera process.
fn FaceWindow::send(self : FaceWindow, line : String) -> Unit {
if self.fd >= 0 {
@sys.write_nonblock(self.fd, @utf8.encode(line + "\n")) |> ignore
}
}
///| Keep the picture in view now.
pub fn FaceUnlock::snap(self : FaceUnlock) -> Unit {
match self.window {
Some(w) if !w.applying && !w.ended => w.send("snap")
_ => ()
}
}
///| Forget snap `i`.
pub fn FaceUnlock::drop_snap(self : FaceUnlock, i : Int) -> Unit {
match self.window {
Some(w) if !w.applying && i >= 0 && i < w.snaps.length() => {
let s = w.snaps.remove(i)
self.spare_thumbs.push(s.image)
w.send("drop " + s.id)
w.message = snapped_text(w.snaps.length())
w.error = false
self.touch()
}
_ => ()
}
}
///| Mark saved face `id` for removal, or unmark it.
pub fn FaceUnlock::toggle_remove(self : FaceUnlock, id : String) -> Unit {
match self.window {
Some(w) if !w.applying => {
if w.remove.contains(id) {
w.remove.retain(r => r != id)
} else {
w.remove.push(id)
}
self.touch()
}
_ => ()
}
}
///| Whether Apply has anything to do.
pub fn FaceWindow::can_apply(self : FaceWindow) -> Bool {
!self.applying && self.fd >= 0 && (self.snaps.length() > 0 || self.remove.length() > 0)
}
///| Save the snaps and remove the marked faces, in one root step (one password).
pub fn FaceUnlock::apply(self : FaceUnlock) -> Unit {
match self.window {
Some(w) if w.can_apply() => {
w.applying = true
w.message = "Waiting for the password…"
w.error = false
w.send("apply " + w.remove.join(","))
self.touch()
}
_ => ()
}
}
///| Close the window without changing anything (the camera stops). Not while Apply runs: the
/// root step can't be taken back half way.
pub fn FaceUnlock::cancel_window(self : FaceUnlock) -> Unit {
match self.window {
Some(w) if !w.applying || w.fd < 0 => self.close_window()
_ => ()
}
}
///| Close the window and drop its pictures.
fn FaceUnlock::close_window(self : FaceUnlock) -> Unit {
match self.window {
Some(w) => {
if w.fd >= 0 {
w.send("quit")
@sys.close_fd(w.fd)
w.fd = -1
}
for s in w.snaps {
self.spare_thumbs.push(s.image)
}
self.window = None
self.touch()
}
None => ()
}
}
///| Read what the camera process sent (non-blocking).
pub fn FaceUnlock::poll_window(self : FaceUnlock) -> Unit {
let w = match self.window {
Some(w) if w.fd >= 0 => w
_ => return
}
let buf : FixedArray[Byte] = FixedArray::make(65536, b'\x00')
let mut eof = false
let mut rounds = 0
// At most ~1 MB a call: a live picture is ~300 KB.
while rounds < 16 && @sys.poll_read(w.fd, 0) > 0 {
rounds = rounds + 1
let (n, extra) = @sys.recvmsg_fd(w.fd, buf, buf.length())
if extra >= 0 {
@sys.close_fd(extra)
}
if n == -1 {
break
}
if n <= 0 {
eof = true
break
}
for i = 0; i < n; i = i + 1 {
w.inbuf.push(buf[i])
}
}
let mut at = 0
while true {
if w.need > 0 {
if w.inbuf.length() - at < w.need {
break
}
let data = Bytes::from_array(w.inbuf[at:at + w.need].to_array())
at = at + w.need
w.need = 0
self.window_blob(w, w.header, data)
continue
}
let mut nl = -1
for i = at; i < w.inbuf.length(); i = i + 1 {
if w.inbuf[i] == b'\n' {
nl = i
break
}
}
if nl < 0 {
break
}
let line = @utf8.decode_lossy(Bytes::from_array(w.inbuf[at:nl].to_array()))
at = nl + 1
let words = line.split(" ").map(s => s.to_string()).to_array()
if (words[0] == "frame" || words[0] == "snap") && words.length() >= 2 {
let n = parse_int(words[words.length() - 1])
if n > 0 && n <= 4 * 1024 * 1024 {
w.header = words
w.need = n
}
continue
}
self.window_line(w, words[0], if line.length() > words[0].length() { line[words[0].length() + 1:].to_string() } else { "" })
}
if at > 0 {
let rest = w.inbuf[at:].to_array()
w.inbuf.clear()
w.inbuf.append(rest)
}
if eof && self.window is Some(_) {
@sys.close_fd(w.fd)
w.fd = -1
if w.applying {
// Apply ended (chandra-face said "applied" or went away): close and show the outcome.
self.message = if w.error || w.message == "Waiting for the password…" {
if w.message == "Waiting for the password…" { "Nothing changed" } else { w.message }
} else {
w.message
}
self.close_window()
self.refresh()
} else {
w.ended = true
if !w.error {
w.message = "The camera stopped"
w.error = true
}
self.touch()
}
}
}
///| A text line from the camera process.
fn FaceUnlock::window_line(self : FaceUnlock, w : FaceWindow, kind : String, text : String) -> Unit {
match kind {
"info" | "done" => {
w.message = text
w.error = false
}
"error" => {
w.message = text
w.error = true
}
"applied" => if text != "0" && !w.error { w.message = "Nothing changed" }
_ => ()
}
self.touch()
}
///| A picture from the camera process: the live one, or a snap's thumbnail.
fn FaceUnlock::window_blob(self : FaceUnlock, w : FaceWindow, header : Array[String], rgb : Bytes) -> Unit {
let num = (i : Int) => if i < header.length() { parse_int(header[i]) } else { -1 }
if header[0] == "frame" && header.length() >= 8 {
let pw = num(1)
let ph = num(2)
let rgba = rgb_to_rgba(rgb, pw, ph)
if rgba.length() == 0 {
return
}
// Two handles in turn: a new picture is a different image op, so the host redraws it.
while self.pics.length() < 2 {
self.pics.push(0U)
}
let k = w.pictures % 2
let h = @raster.image_pixels(pw, ph, rgba, self.pics[k])
self.pics[k] = h
w.picture = h
w.pic_w = pw
w.pic_h = ph
w.pictures = w.pictures + 1
w.face_box = if num(5) > 0 { Some((num(3), num(4), num(5), num(6))) } else { None }
if w.pictures == 1 && w.message == "Starting the camera…" {
w.message = "Look at the camera and press Snap"
}
} else if header[0] == "snap" && header.length() >= 5 {
let rgba = rgb_to_rgba(rgb, num(2), num(3))
if rgba.length() == 0 {
return
}
let reuse = self.spare_thumbs.pop().unwrap_or(0U)
let h = @raster.image_pixels(num(2), num(3), rgba, reuse)
w.snaps.push({ id: header[1], image: h })
w.message = snapped_text(w.snaps.length())
w.error = false
}
self.touch()
}
///| What the window says after a snap or a drop.
fn snapped_text(n : Int) -> String {
match n {
0 => "Look at the camera and press Snap"
1 => "1 picture: turn a little and snap again, or press Apply"
_ => n.to_string() + " pictures: snap more, or press Apply"
}
}
///| RGB bytes of a `w` x `h` picture as RGBA (empty when the sizes don't add up).
fn rgb_to_rgba(rgb : Bytes, w : Int, h : Int) -> Bytes {
if w <= 0 || h <= 0 || w > 1024 || h > 1024 || rgb.length() < w * h * 3 {
return b""
}
let out = FixedArray::make(w * h * 4, b'\xff')
for i = 0; i < w * h; i = i + 1 {
out[i * 4] = rgb[i * 3]
out[i * 4 + 1] = rgb[i * 3 + 1]
out[i * 4 + 2] = rgb[i * 3 + 2]
}
Bytes::from_fixedarray(out)
}
///| A non-negative decimal number, or -1.
fn parse_int(s : String) -> Int {
if s.length() == 0 || s.length() > 9 {
return -1
}
let mut n = 0
for ch in s {
let d = ch.to_int() - 48
if d < 0 || d > 9 {
return -1
}
n = n * 10 + d
}
n
} }
///| Publish the face unlock tables (24: status, 25: faces) while a module imports `face-unlock`. ///| Publish the face unlock tables (24: status, 25: faces) while a module imports `face-unlock`.
@@ -293,6 +665,7 @@ fn DesktopShell::publish_face_unlock(self : DesktopShell) -> Unit {
} }
let f = self.face let f = self.face
f.poll() f.poll()
f.poll_window()
if !f.dirty { if !f.dirty {
return return
} }
@@ -318,5 +691,5 @@ fn DesktopShell::publish_face_unlock(self : DesktopShell) -> Unit {
///| Whether a chandra-face run is in progress: the main loop keeps its frame pace meanwhile, so ///| Whether a chandra-face run is in progress: the main loop keeps its frame pace meanwhile, so
/// what it says shows up (it runs seconds, while the camera looks). /// what it says shows up (it runs seconds, while the camera looks).
pub fn DesktopShell::face_busy(self : DesktopShell) -> Bool { pub fn DesktopShell::face_busy(self : DesktopShell) -> Bool {
self.face.fd >= 0 self.face.fd >= 0 || self.face.window is Some(_)
} }
+50 -17
View File
@@ -31,18 +31,34 @@ The Settings rows are part of the session: after `just install`, log in again so
compositor, its host and the Settings module are the new ones. (`just reload` alone isn't enough: an older host doesn't serve compositor, its host and the Settings module are the new ones. (`just reload` alone isn't enough: an older host doesn't serve
the `face-unlock` capability.) Then in **Settings > Session > Face unlock**: the `face-unlock` capability.) Then in **Settings > Session > Face unlock**:
- **Add a face…** asks for your password (in the password dialog), then looks through the - **Add or remove faces…** opens the Face unlock window (below). **Remove…** on a face opens it
camera for about ten seconds and keeps five views of your face. Add another face for glasses, with that face marked.
a different light, or a second camera position.
- **Use my face for passwords** puts the face first in the PAM services `polkit-1` (the password - **Use my face for passwords** puts the face first in the PAM services `polkit-1` (the password
dialog) and `sudo`, after the password. Turning it off takes it out again. dialog) and `sudo`, after the password. Turning it off takes it out again (one password).
- **Remove** (click twice) forgets one face.
Everything Settings does runs `chandra-face` through run0 (or pkexec), so each change asks for ### The Face unlock window
an administrator's password first. From a terminal:
![The Face unlock window: live picture, two snaps, a saved face](screenshots/face-window.png)
- The camera starts at once, with no password: a live picture with a box round the face it sees.
- **Snap** (or Space) keeps the picture in view and shows it below; snap a few: straight on,
turned a little, with and without glasses. Click a snap to drop it. A snap that can't be used
says why ("No face in view", "More than one face in view", "Come closer to the camera").
- **Remove** / **Keep** on a saved face marks it for removal, or not.
- **Apply** (or Enter) saves the snaps as one new face and removes the marked ones, in one step:
the password dialog asks once, above the window. **Cancel** (Esc) changes nothing.
Why root at all: the face data is root's (`/var/lib/chandra-face`, 0600) and PAM trusts it to let
you into sudo and polkit without a password. If you could write it as yourself, so could any
program running as you, and it could quietly add a face (or a photo) of its choosing and then use
sudo. So only the change needs root, and only once: the camera and the pictures stay on your side,
and only the face data of the snaps you kept crosses to the root step. (Removing a face only
takes access away, so it could be allowed without a password; it isn't yet, to keep one rule.)
From a terminal (each root command asks for the password itself):
```sh ```sh
chandra-face enroll --label "Desk" # add a face chandra-face enroll --label "Desk" # add a face (looks for ten seconds, keeps five views)
chandra-face list chandra-face list
chandra-face test # look now and print the similarity scores chandra-face test # look now and print the similarity scores
chandra-face remove 2 chandra-face remove 2
@@ -130,18 +146,31 @@ models = /usr/local/share/chandra/face
the session-settings module reaches it through the `face-unlock` capability the session-settings module reaches it through the `face-unlock` capability
(`wit/capabilities.wit`). The password dialog (`compositor/polkit/dialog.mbt`, `face_message`) (`wit/capabilities.wit`). The password dialog (`compositor/polkit/dialog.mbt`, `face_message`)
turns the module's messages into the face row. turns the module's messages into the face row.
- The Face unlock window (`compositor/host/face_window.mbt`, drawn by the compositor like the
password dialog) talks to `chandra-face camera`, run as you on a socket: it sends
`frame W H BX BY BW BH LEN` + RGB bytes (320 px wide, about 12 a second) and `snap ID 96 96 LEN`
+ RGB (the face, cropped), and reads `snap`, `drop ID`, `apply REMOVE-IDS`, `quit`. The snaps'
embeddings stay in that process; on `apply` it closes the camera and runs
`chandra-face apply` through run0/pkexec with `{"add": [{"label", "vectors"}], "remove": [ids]}`
on its stdin, which checks the data (sizes, finite numbers, the same length as the faces
already saved) and writes the store once. The window's pictures are host images
(`raster.image-pixels`), reused and dropped when it closes.
## Privacy and security ## Privacy and security
- **Nothing leaves the machine.** Camera frames are only held in memory by the root helper for the - **Nothing leaves the machine.** Camera frames are only held in memory, by the root helper for the
few seconds it looks; they are never written to disk or sent anywhere. The only network access few seconds it looks, and by the Face unlock window (its camera process and its images) while
is the one-time model download. it is open; they are never written to disk or sent anywhere. The only network access is the
one-time model download.
- **What is stored**: per user, `/var/lib/chandra-face/USER/faces.json` (root, mode 0600) holds the - **What is stored**: per user, `/var/lib/chandra-face/USER/faces.json` (root, mode 0600) holds the
embeddings (feature vectors, not pictures) and `faces.list` (0644) only the labels and dates embeddings (feature vectors, not pictures) and `faces.list` (0644) only the labels and dates
that Settings shows. The helper refuses a store, config or model that is a symlink, not root's, that Settings shows. The helper refuses a store, config or model that is a symlink, not root's,
or writable by group or others. or writable by group or others.
- **Changing faces needs an administrator**: enrolling runs as root after polkit's password - **Changing faces needs an administrator**: saving runs as root after polkit's password check,
check, so a program running as you can't quietly add someone else's face to your account. so a program running as you can't quietly add someone else's face to your account. The face
data the window hands over comes from your own camera process: the password is the check, as
it is for anything else that root runs for you. With face unlock already on for polkit-1, the
face itself can answer that password dialog (the window closes the camera first so it can).
- **2D face recognition can be fooled.** A good photo or video of you held up to a normal (RGB) - **2D face recognition can be fooled.** A good photo or video of you held up to a normal (RGB)
webcam may be accepted: there is no liveness or depth check. An infrared camera (most "Windows webcam may be accepted: there is no liveness or depth check. An infrared camera (most "Windows
Hello" laptops have one) is much harder to fool with a photo or a screen; set `device` to it Hello" laptops have one) is much harder to fool with a photo or a screen; set `device` to it
@@ -156,7 +185,8 @@ models = /usr/local/share/chandra/face
`just test-face` runs `face/test_face.py` with a fake camera (a folder of PGM frames) and a `just test-face` runs `face/test_face.py` with a fake camera (a folder of PGM frames) and a
fake recognizer, so it needs no camera, OpenCV or models: enrollment, recognition, the reasons fake recognizer, so it needs no camera, OpenCV or models: enrollment, recognition, the reasons
for failing, permission checks on the store, PAM file editing (including Debian's for failing, permission checks on the store, PAM file editing (including Debian's
`@include common-auth`). `just test-face --pam` (as root, with `pamtester`) also builds the PAM `@include common-auth`), and the window's camera session (live pictures, snaps, drops, one apply
that adds and removes, bad apply data refused). `just test-face --pam` (as root, with `pamtester`) also builds the PAM
module and runs it through a throwaway PAM service: a match succeeds, a stranger falls through, module and runs it through a throwaway PAM service: a match succeeds, a stranger falls through,
remote and unenrolled users are skipped quietly, a hanging helper is killed, a writable helper is remote and unenrolled users are skipped quietly, a hanging helper is killed, a writable helper is
not run. With `CHANDRA_FACE_MODELS=DIR` the OpenCV backend is checked on frames without a face. not run. With `CHANDRA_FACE_MODELS=DIR` the OpenCV backend is checked on frames without a face.
@@ -164,8 +194,11 @@ not run. With `CHANDRA_FACE_MODELS=DIR` the OpenCV backend is checked on frames
On the compositor side, `compositor/polkit/polkit_test.mbt` covers the message parsing and the On the compositor side, `compositor/polkit/polkit_test.mbt` covers the message parsing and the
dialog's face states, `compositor/host/auth_test.mbt` drives the dialog through a mock helper dialog's face states, `compositor/host/auth_test.mbt` drives the dialog through a mock helper
(`CHANDRA_AUTH_SHOTS=dir` saves `14-face-scanning.png` and `15-face-failed.png`), and (`CHANDRA_AUTH_SHOTS=dir` saves `14-face-scanning.png` and `15-face-failed.png`), and
`compositor/host/face_test.mbt` drives Settings > Session against a fake chandra-face. `compositor/host/face_test.mbt` drives Settings > Session and the Face unlock window (Remove…
opens it with the face marked, Space snaps, Enter applies once, Esc cancels) against a fake
chandra-face (`CHANDRA_AUTH_SHOTS=dir` saves `17-face-window.png`).
Not verified here: a real camera (frames came from image files; with OpenCV's real models, a Not verified here: a real camera (frames came from image files; with OpenCV's real models, a
rotated and rescaled photo of the enrolled face scored 0.92 and a different person -0.18), and rotated and rescaled photo of the enrolled face scored 0.92 and a different person -0.18; the
run0/pkexec elevation from Settings on a real systemd session. window's screenshot is the real pipeline on a photo), and run0/pkexec elevation (with the apply
data on stdin) on a real systemd session.
Binary file not shown.

After

Width:  |  Height:  |  Size: 318 KiB

+283 -14
View File
@@ -12,6 +12,12 @@
chandra-face pam [status|enable|disable] [SERVICE...] put pam_chandra_face.so into chandra-face pam [status|enable|disable] [SERVICE...] put pam_chandra_face.so into
/etc/pam.d/SERVICE (root; default polkit-1 sudo) /etc/pam.d/SERVICE (root; default polkit-1 sudo)
chandra-face fetch-models download the face models (root) chandra-face fetch-models download the face models (root)
chandra-face camera [--label L] the "Add a face" window's camera, run as you: streams
a small live picture with the face box, keeps snaps
(their embeddings) in memory, and on "apply" saves
the snaps and removals in one root step (one password)
chandra-face apply [--user U] add and remove faces in one go, from JSON on stdin:
{"add": [{"label", "vectors"}], "remove": [ids]} (root)
Root commands started by another user re-run themselves through run0 or pkexec, so polkit asks Root commands started by another user re-run themselves through run0 or pkexec, so polkit asks
for an administrator's password first (in Chandra's own dialog). for an administrator's password first (in Chandra's own dialog).
@@ -35,6 +41,8 @@ import re
import shutil import shutil
import stat import stat
import sys import sys
import select
import subprocess
import tempfile import tempfile
import time import time
@@ -253,6 +261,10 @@ class OpenCVRecognizer:
import numpy as np import numpy as np
self.cv2, self.np = cv2, np self.cv2, self.np = cv2, np
try:
cv2.utils.logging.setLogLevel(cv2.utils.logging.LOG_LEVEL_ERROR)
except AttributeError:
pass
if not hasattr(cv2, "FaceDetectorYN"): if not hasattr(cv2, "FaceDetectorYN"):
raise Fail("OpenCV %s is too old (4.5.4+ needed)" % cv2.__version__, 2) raise Fail("OpenCV %s is too old (4.5.4+ needed)" % cv2.__version__, 2)
det = os.path.join(cfg.models, "face_detection_yunet_2023mar.onnx") det = os.path.join(cfg.models, "face_detection_yunet_2023mar.onnx")
@@ -362,13 +374,16 @@ def read_pnm(path):
class ImageCamera: class ImageCamera:
"""`images:DIR`: the image files in DIR, in name order, as camera frames (for tests).""" """`images:DIR`: the image files in DIR, in name order, as camera frames (for tests)."""
def __init__(self, spec, cfg): def __init__(self, spec, cfg, loop=False):
d = spec[len("images:"):] d = spec[len("images:"):]
self.files = sorted(os.path.join(d, f) for f in os.listdir(d) if not f.startswith(".")) self.files = sorted(os.path.join(d, f) for f in os.listdir(d) if not f.startswith("."))
self.i = 0 self.i = 0
self.cfg = cfg self.cfg = cfg
self.loop = loop
def read(self): def read(self):
if self.loop and self.files:
self.i %= len(self.files)
if self.i >= len(self.files): if self.i >= len(self.files):
return None return None
f = self.files[self.i] f = self.files[self.i]
@@ -405,9 +420,9 @@ class V4L2Camera:
self.cap.release() self.cap.release()
def open_camera(cfg): def open_camera(cfg, loop=False):
if cfg.device.startswith("images:"): if cfg.device.startswith("images:"):
return ImageCamera(cfg.device, cfg) return ImageCamera(cfg.device, cfg, loop)
if not cfg.device.isdigit() and not os.path.exists(cfg.device): if not cfg.device.isdigit() and not os.path.exists(cfg.device):
raise Fail("no camera at %s" % cfg.device, 2) raise Fail("no camera at %s" % cfg.device, 2)
return V4L2Camera(cfg.device) return V4L2Camera(cfg.device)
@@ -521,7 +536,7 @@ def cmd_enroll(cfg, user, label, out):
raise Fail("couldn't see a face clearly: look at the camera in good light and try again") raise Fail("couldn't see a face clearly: look at the camera in good light and try again")
faces = load_faces(cfg, user) faces = load_faces(cfg, user)
nid = max([f["id"] for f in faces] + [0]) + 1 nid = max([f["id"] for f in faces] + [0]) + 1
label = (label or "Face %d" % nid).replace("\t", " ").replace("\n", " ")[:60] label = clean_label(label, nid)
faces.append({"id": nid, "label": label, "created": time.strftime("%Y-%m-%d"), faces.append({"id": nid, "label": label, "created": time.strftime("%Y-%m-%d"),
"vectors": [[round(x, 6) for x in v] for v in vecs]}) "vectors": [[round(x, 6) for x in v] for v in vecs]})
save_faces(cfg, user, faces) save_faces(cfg, user, faces)
@@ -529,6 +544,260 @@ def cmd_enroll(cfg, user, label, out):
return 0 return 0
def clean_label(label, nid):
return (label or "Face %d" % nid).replace("\t", " ").replace("\n", " ").strip()[:60] or "Face %d" % nid
MAX_APPLY = 1 << 20
def cmd_apply(cfg, user, out, data=None):
"""Add and remove faces in one step (what the "Add a face" window's Apply runs as root).
The embeddings come from the user's own camera process: anyone who can type the admin
password could enroll any face anyway, so the password is the check, as for enroll."""
check_user(user)
if data is None:
data = sys.stdin.buffer.read(MAX_APPLY + 1)
if len(data) > MAX_APPLY:
raise Fail("too much data")
try:
req = json.loads(data.decode("utf-8") or "{}")
except ValueError:
raise Fail("bad request")
if not isinstance(req, dict):
raise Fail("bad request")
adds = req.get("add") or []
removes = [str(r) for r in (req.get("remove") or [])]
if not isinstance(adds, list) or len(adds) > 8:
raise Fail("bad request")
faces = load_faces(cfg, user)
dims = {len(v) for f in faces for v in f.get("vectors", [])}
new = []
for a in adds:
vecs = a.get("vectors") if isinstance(a, dict) else None
if not isinstance(vecs, list) or not 1 <= len(vecs) <= 32:
raise Fail("bad face data")
for v in vecs:
if not isinstance(v, list) or not 4 <= len(v) <= 1024 or \
not all(isinstance(x, (int, float)) and math.isfinite(x) for x in v):
raise Fail("bad face data")
dims.add(len(v))
if len(dims) > 1:
raise Fail("face data from another recognizer")
label = a.get("label") if isinstance(a.get("label"), str) else ""
new.append((label, vecs))
known = {str(f["id"]) for f in faces}
missing = [r for r in removes if r not in known]
if missing:
raise Fail("no face %s for %s" % (", ".join(missing), user))
nid = max([f["id"] for f in faces] + [0]) # ids aren't reused
faces = [f for f in faces if str(f["id"]) not in removes]
for label, vecs in new:
nid += 1
faces.append({"id": nid, "label": clean_label(label, nid), "created": time.strftime("%Y-%m-%d"),
"vectors": [[round(float(x), 6) for x in v] for v in vecs]})
save_faces(cfg, user, faces)
parts = []
if new:
parts.append("added %s" % ", ".join(f["label"] for f in faces[-len(new):]))
if removes:
parts.append("removed %d face%s" % (len(removes), "" if len(removes) == 1 else "s"))
msg = " and ".join(parts) or "nothing to change"
out.emit("done", msg[:1].upper() + msg[1:])
return 0
PREVIEW_W = 320
THUMB = 96
def resize_rows(rows, w, h):
"""Nearest-pixel resize of rows of gray values (the fake camera's frames)."""
sh, sw = len(rows), len(rows[0])
return [[rows[y * sh // h][x * sw // w] for x in range(w)] for y in range(h)]
def rgb_bytes(frame, rec, box=None, size=None):
"""`frame` (or its `box` = (x, y, w, h)) as RGB bytes at `size` = (w, h)."""
if isinstance(frame, list):
if box:
x, y, w, h = box
frame = [r[x:x + w] for r in frame[y:y + h]]
g = resize_rows(frame, *size)
return bytes(v for r in g for v in r for _ in range(3))
cv2 = rec.cv2 if hasattr(rec, "cv2") else __import__("cv2")
if box:
x, y, w, h = box
frame = frame[y:y + h, x:x + w]
if frame.ndim == 2:
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB).tobytes()
def frame_size(frame):
if isinstance(frame, list):
return len(frame[0]), len(frame)
return frame.shape[1], frame.shape[0]
def send_blob(header, data):
"""A binary message: `header LEN` on a line, then LEN bytes."""
sys.stdout.flush()
sys.stdout.buffer.write(("%s %d\n" % (header, len(data))).encode())
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
def elevated(args):
"""argv running chandra-face `args` as root through run0 or pkexec (polkit asks first)."""
me = os.path.realpath(sys.argv[0])
run0 = shutil.which("run0")
if run0 and os.path.isdir("/run/systemd/system"):
return [run0, "--background=", "--", sys.executable, "-I", me] + args
pk = shutil.which("pkexec")
if pk:
return [pk, sys.executable, "-I", me] + args
raise Fail("needs root, and neither run0 nor pkexec is installed")
def cmd_camera(cfg, user, label, out, cfg_path, no_elevate):
"""The "Add a face" window's camera, run as the session user (no root, no password).
Out ("--machine" lines): `frame W H BX BY BW BH LEN` + LEN bytes of RGB (the live picture,
about 12 a second; the box is -1s without one face), `snap ID W H LEN` + RGB (a kept snap,
cropped to the face), `info` / `error` / `done` lines, `applied CODE` at the end of an apply.
In (stdin lines): `snap`, `drop ID`, `apply REMOVE-IDS` (comma-separated, may be empty), `quit`.
The pictures stay in this process's memory: nothing is written to disk; only the embeddings
of the snaps kept go to the root `apply`, through a pipe."""
check_user(user)
rec = make_recognizer(cfg)
cam = open_camera(cfg, loop=True)
snaps = {} # id -> embedding
next_id = 1
last = None
last_sent = 0.0
pending = b""
out.info("Look at the camera and press Snap")
try:
while True:
frame = cam.read()
if frame is None:
out.error("The camera gave no picture")
return 2
if isinstance(cam, ImageCamera):
time.sleep(max(cfg.frame_delay, 0.03))
last = frame
now = time.monotonic()
if now - last_sent >= 0.08:
last_sent = now
w, h = frame_size(frame)
pw = min(PREVIEW_W, w)
ph = max(1, h * pw // w)
dets = rec.detect(frame) if rec.brightness(frame) >= cfg.dark else []
bx = (-1, -1, -1, -1)
if len(dets) == 1:
d = dets[0]
bx = (d.x * pw // w, d.y * ph // h, d.w * pw // w, d.h * ph // h)
send_blob("frame %d %d %d %d %d %d" % ((pw, ph) + bx), rgb_bytes(frame, rec, size=(pw, ph)))
r, _, _ = select.select([0], [], [], 0)
if not r:
continue
got = os.read(0, 4096)
if not got:
return 0
pending += got
while b"\n" in pending:
line, pending = pending.split(b"\n", 1)
words = line.decode("utf-8", "replace").strip().split(" ", 1)
cmd, arg = words[0], (words[1] if len(words) > 1 else "")
if cmd == "quit":
return 0
if cmd == "drop":
snaps.pop(arg, None)
elif cmd == "snap":
v, why, box = snap_face(cfg, rec, last)
if v is None:
out.error(why)
continue
sid = str(next_id)
next_id += 1
snaps[sid] = v
send_blob("snap %s %d %d" % (sid, THUMB, THUMB), rgb_bytes(last, rec, box, (THUMB, THUMB)))
elif cmd == "apply":
cam.close()
cam = None
removes = [r for r in arg.split(",") if r.strip()]
req = {"add": [{"label": label or "", "vectors": list(snaps.values())}] if snaps else [],
"remove": removes}
code = run_apply(cfg, user, out, req, cfg_path, no_elevate)
out.emit("applied", str(code))
return code
finally:
if cam is not None:
cam.close()
def snap_face(cfg, rec, frame):
"""(embedding, "", square face box) for the one face in `frame`, or (None, why, None)."""
if frame is None:
return None, "No picture yet", None
if rec.brightness(frame) < cfg.dark:
return None, "The picture is too dark", None
dets = rec.detect(frame)
if not dets:
return None, "No face in view", None
if len(dets) > 1:
return None, "More than one face in view", None
d = dets[0]
if d.w < cfg.min_face and d.h < cfg.min_face and cfg.backend != "fake":
return None, "Come closer to the camera", None
if cfg.require_ir and not rec.gray(frame):
return None, "Needs an infrared camera (require_ir)", None
v = [round(x, 6) for x in rec.embed(frame, d)]
w, h = frame_size(frame)
side = min(int(max(d.w, d.h) * 1.4), w, h)
x = min(max(0, d.x + d.w // 2 - side // 2), w - side)
y = min(max(0, d.y + d.h // 2 - side // 2), h - side)
return v, "", (x, y, side, side)
def run_apply(cfg, user, out, req, cfg_path, no_elevate):
"""Run `apply` as root with `req` on its stdin, passing on what it says."""
data = json.dumps(req).encode()
if os.geteuid() == 0 or no_elevate:
try:
return cmd_apply(cfg, user, out, data)
except Fail as e:
out.error(str(e))
return e.code
args = ["apply", "--machine", "--user", user]
if cfg_path != DEFAULT_CONFIG:
args += ["--config", cfg_path]
out.info("Waiting for the password…")
p = subprocess.Popen(elevated(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
try:
p.stdin.write(data)
p.stdin.close()
except BrokenPipeError:
pass
said = False
for raw in p.stdout:
line = raw.decode("utf-8", "replace").rstrip("\n")
kind = line.split(" ", 1)[0]
if kind in ("info", "error", "done"):
said = said or kind != "info"
sys.stdout.write(line + "\n")
sys.stdout.flush()
code = p.wait()
if not said:
out.error("Nothing changed")
return code or 1
return code
def cmd_remove(cfg, user, ident, out): def cmd_remove(cfg, user, ident, out):
check_user(user) check_user(user)
faces = load_faces(cfg, user) faces = load_faces(cfg, user)
@@ -670,22 +939,16 @@ def cmd_fetch_models(cfg, out):
# ---------------------------------------------------------------- main # ---------------------------------------------------------------- main
ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models") ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models", "apply")
def elevate(argv, user): def elevate(argv, user):
"""Run this command again as root through run0 (systemd) or pkexec: polkit asks first.""" """Run this command again as root through run0 (systemd) or pkexec: polkit asks first."""
me = os.path.realpath(sys.argv[0]) args = list(argv)
args = [me] + argv
if "--user" not in argv: if "--user" not in argv:
args += ["--user", user] args += ["--user", user]
run0 = shutil.which("run0") cmd = elevated(args)
if run0 and os.path.isdir("/run/systemd/system"): os.execv(cmd[0], cmd)
os.execv(run0, [run0, "--background=", "--"] + [sys.executable, "-I"] + args)
pk = shutil.which("pkexec")
if pk:
os.execv(pk, [pk, sys.executable, "-I"] + args)
raise Fail("needs root, and neither run0 nor pkexec is installed")
def main(argv): def main(argv):
@@ -745,6 +1008,10 @@ def main(argv):
return cmd_compare(cfg, user, out, verbose=True) return cmd_compare(cfg, user, out, verbose=True)
if cmd == "enroll": if cmd == "enroll":
return cmd_enroll(cfg, user, label, out) return cmd_enroll(cfg, user, label, out)
if cmd == "apply":
return cmd_apply(cfg, user, out)
if cmd == "camera":
return cmd_camera(cfg, user, label, out, cfg_path, no_elevate)
if cmd == "remove": if cmd == "remove":
if not params: if not params:
raise Fail("remove ID") raise Fail("remove ID")
@@ -768,6 +1035,8 @@ def main(argv):
return e.code return e.code
except KeyboardInterrupt: except KeyboardInterrupt:
return 1 return 1
except BrokenPipeError:
return 0 # the window that read us went away
if __name__ == "__main__": if __name__ == "__main__":
+108
View File
@@ -240,6 +240,114 @@ class FaceTests(unittest.TestCase):
self.assertIn("problem no camera at /dev/no-such-camera", self.env.run("status")[1]) self.assertIn("problem no camera at /dev/no-such-camera", self.env.run("status")[1])
class Session:
"""`chandra-face camera` as the "Add a face" window runs it: commands in, lines and pictures out."""
def __init__(self, env):
self.p = subprocess.Popen(
[sys.executable, "-I", TOOL, "camera", "--config", env.conf, "--machine", "--no-elevate",
"--user", ME], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def send(self, line):
self.p.stdin.write(line.encode() + b"\n")
self.p.stdin.flush()
def next(self, kind):
"""Messages until one of `kind`: (header words, picture bytes or None)."""
while True:
line = self.p.stdout.readline()
if not line:
raise AssertionError("ended before %s" % kind)
words = line.decode().rstrip("\n").split(" ")
data = None
if words[0] in ("frame", "snap"):
data = self.p.stdout.read(int(words[-1]))
if words[0] == kind:
return words, data
def finish(self):
self.p.stdin.close()
rc = self.p.wait(10)
self.p.stdout.close()
return rc
class CameraWindowTests(unittest.TestCase):
def setUp(self):
self.env = Env()
def tearDown(self):
self.env.close()
def vectors(self):
f = os.path.join(self.env.store, ME, "faces.json")
return json.loads(slurp(f))["faces"] if os.path.exists(f) else []
def test_live_picture_snaps_and_one_apply(self):
self.env.camera(["alice"], frame_delay="0.01")
s = Session(self.env)
words, px = s.next("frame")
w, h = int(words[1]), int(words[2])
self.assertEqual((w, h), (32, 32))
self.assertEqual(len(px), w * h * 3)
self.assertEqual(words[3:7], ["0", "0", "32", "32"]) # the face box
s.send("snap")
words, px = s.next("snap")
self.assertEqual(words[1:4], ["1", "96", "96"])
self.assertEqual(len(px), 96 * 96 * 3)
s.send("snap")
s.next("snap")
s.send("drop 1")
self.assertEqual(self.vectors(), [], "nothing is saved before Apply")
s.send("apply ")
words, _ = s.next("applied")
self.assertEqual(words[1], "0")
self.assertEqual(s.finish(), 0)
faces = self.vectors()
self.assertEqual(len(faces), 1)
self.assertEqual(len(faces[0]["vectors"]), 1, "the dropped snap is not saved")
# The saved face is recognized.
self.env.camera(["alice", "alice"])
rc, out = self.env.run("compare")
self.assertEqual(rc, 0, out)
def test_a_snap_without_a_face_says_why(self):
self.env.camera(["flat"], frame_delay="0.01")
s = Session(self.env)
words, _ = s.next("frame")
self.assertEqual(words[3:7], ["-1"] * 4)
s.send("snap")
words, _ = s.next("error")
self.assertEqual(" ".join(words[1:]), "No face in view")
s.send("quit")
self.assertEqual(s.finish(), 0)
self.assertEqual(self.vectors(), [])
def test_apply_adds_and_removes_in_one_go(self):
self.env.camera(["alice", "alice", "alice"])
self.env.run("enroll", "--label", "Old")
self.env.camera(["bob"], frame_delay="0.01")
s = Session(self.env)
s.send("snap")
s.next("snap")
s.send("apply 1")
words, _ = s.next("done")
self.assertEqual(" ".join(words[1:]), "Added Face 2 and removed 1 face")
self.assertEqual(s.next("applied")[0][1], "0")
s.finish()
self.assertEqual([f["label"] for f in self.vectors()], ["Face 2"])
def test_apply_refuses_bad_data(self):
for bad in (b"[]", b"{\"add\": [{\"vectors\": [[1, 2]]}]}",
b"{\"add\": [{\"vectors\": [[1e999, 0, 0, 0]]}]}", b"{\"remove\": [7]}", b"nonsense"):
buf = io.StringIO()
with redirect_stdout(buf):
cfg = cf.Config(self.env.conf)
with self.assertRaises(cf.Fail, msg=bad):
cf.cmd_apply(cfg, ME, cf.Out(True), bad)
self.assertEqual(self.vectors(), [])
@unittest.skipUnless(os.environ.get("CHANDRA_FACE_MODELS"), "CHANDRA_FACE_MODELS not set") @unittest.skipUnless(os.environ.get("CHANDRA_FACE_MODELS"), "CHANDRA_FACE_MODELS not set")
class OpenCVTests(unittest.TestCase): class OpenCVTests(unittest.TestCase):
def test_no_face_in_noise_or_flat_frames(self): def test_no_face_in_noise_or_flat_frames(self):
+4
View File
@@ -436,6 +436,10 @@ impl chandra::host::raster::Host for State {
self.raster.thumbnail(surface, w, h, reuse) self.raster.thumbnail(surface, w, h, reuse)
} }
fn image_pixels(&mut self, w: i32, h: i32, rgba: Vec<u8>, reuse: u32) -> u32 {
self.raster.image_pixels(w, h, rgba, reuse)
}
fn submit(&mut self, f: chandra::host::raster::Frame) { fn submit(&mut self, f: chandra::host::raster::Frame) {
self.raster.submit_frame(f, &mut self.fonts); self.raster.submit_frame(f, &mut self.fonts);
} }
+10
View File
@@ -912,6 +912,16 @@ impl Raster {
handle handle
} }
/// `w` x `h` RGBA pixels as an image (see `Images::put_pixels` for `reuse`); 0 for a silly
/// size or too few pixels.
pub fn image_pixels(&mut self, w: i32, h: i32, mut rgba: Vec<u8>, reuse: u32) -> u32 {
if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE || rgba.len() < (w * h * 4) as usize {
return 0;
}
rgba.truncate((w * h * 4) as usize);
self.images.put_pixels(reuse, w, h, rgba)
}
pub fn surface_count(&self) -> usize { pub fn surface_count(&self) -> usize {
self.surfaces.len() self.surfaces.len()
} }
@@ -0,0 +1,32 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/default-apps"
// Values
pub fn apps() -> Array[AppChoice]
pub fn categories() -> Array[AppCategory]
pub fn refresh() -> Unit
pub fn set_default(UInt32, UInt32) -> Unit
// Errors
// Types and methods
pub(all) struct AppCategory {
name : String
current : String
missing : String
}
pub(all) struct AppChoice {
category : UInt32
id : String
name : String
icon : UInt32
current : Bool
}
// Type aliases
// Traits
@@ -1,4 +1,5 @@
Face unlock (docs/face-unlock.md): the session user's enrolled faces and whether the password Face unlock (docs/face-unlock.md): the session user's enrolled faces and whether the password
dialog and sudo try the face first. Every change runs chandra-face through run0 or pkexec, so dialog and sudo try the face first. Faces are added and removed in the compositor's Face unlock
polkit asks for an administrator's password before anything happens; the module never sees a window, whose Apply runs chandra-face through run0 or pkexec once, so polkit asks for an
camera picture or any face data, only labels. administrator's password before anything changes; the module never sees a camera picture or
any face data, only labels.
@@ -47,14 +47,14 @@ pub fn faces() -> Array[Face] {
} }
///| ///|
/// Add a face: after the password, the camera looks for about ten seconds. /// Open the Face unlock window (live camera picture, Snap, saved faces, one Apply).
pub fn enroll() -> Unit { pub fn enroll() -> Unit {
wasmImportEnroll(); wasmImportEnroll();
} }
///| ///|
/// Forget face `index` of `faces`. /// Open the Face unlock window with face `index` of `faces` marked for removal.
pub fn remove(index : UInt) -> Unit { pub fn remove(index : UInt) -> Unit {
wasmImportRemove((index).reinterpret_as_int()); wasmImportRemove((index).reinterpret_as_int());
@@ -0,0 +1,13 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/icons"
// Values
pub fn app_icon(String) -> UInt32
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,15 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/inspector"
// Values
pub fn is_on() -> Bool
pub fn set_on(Bool) -> Unit
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,17 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/layout-control"
// Values
pub fn current_layout() -> UInt32
pub fn layout_modes() -> Array[String]
pub fn set_layout(UInt32) -> Unit
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,35 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/modules"
// Values
pub fn available() -> Array[ModuleInfo]
pub fn browse() -> Unit
pub fn load_module(String) -> Unit
pub fn loaded() -> Array[InstanceInfo]
pub fn move_instance(String, Int32) -> Unit
pub fn unload_instance(String) -> Unit
// Errors
// Types and methods
pub(all) struct InstanceInfo {
slot : String
module_ : String
name : String
}
pub(all) struct ModuleInfo {
id : String
name : String
path : String
loaded : UInt32
}
// Type aliases
// Traits
@@ -0,0 +1,45 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/network"
// Values
pub fn connect(String, String) -> Unit
pub fn disconnect() -> Unit
pub fn forget(String) -> Unit
pub fn scan() -> Unit
pub fn set_airplane_mode(Bool) -> Unit
pub fn set_wifi_enabled(Bool) -> Unit
pub fn status() -> NetStatus
pub fn wifi_networks() -> Array[WifiNetwork]
// Errors
// Types and methods
pub(all) struct NetStatus {
state : UInt32
signal : UInt32
name : String
message : String
wifi_enabled : Bool
airplane : Bool
can_manage : Bool
has_wifi : Bool
}
pub(all) struct WifiNetwork {
ssid : String
signal : UInt32
secured : Bool
active : Bool
saved : Bool
}
// Type aliases
// Traits
@@ -0,0 +1,25 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/power"
// Values
pub fn power_off() -> Unit
pub fn reboot() -> Unit
pub fn screen_off_minutes() -> UInt32
pub fn set_screen_off_minutes(UInt32) -> Unit
pub fn set_suspend_minutes(UInt32) -> Unit
pub fn suspend() -> Unit
pub fn suspend_minutes() -> UInt32
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,23 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/screenshot"
// Values
pub fn is_recording() -> Bool
pub fn records_pointer() -> Bool
pub fn set_records_pointer(Bool) -> Unit
pub fn start_recording(UInt32) -> Unit
pub fn stop_recording() -> Unit
pub fn take(UInt32) -> Unit
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,17 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/session-settings"
// Values
pub fn is_on(UInt32) -> Bool
pub fn set_setting(UInt32, Bool) -> Unit
pub fn settings() -> Array[String]
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,15 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/session"
// Values
pub fn logout() -> Unit
pub fn reload() -> Unit
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,28 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/shortcuts"
// Values
pub fn cancel_capture() -> Unit
pub fn capture(UInt32) -> Unit
pub fn reset(UInt32) -> Unit
pub fn reset_all() -> Unit
pub fn shortcuts() -> Array[Shortcut]
// Errors
// Types and methods
pub(all) struct Shortcut {
name : String
binding : String
default_binding : String
conflict : String
capturing : Bool
}
// Type aliases
// Traits
@@ -0,0 +1,24 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/system"
// Values
pub fn read() -> Snapshot
// Errors
// Types and methods
pub(all) struct Snapshot {
cpu_permille : UInt32
mem_used_kib : UInt64
mem_total_kib : UInt64
battery_percent : Int32
charging : Bool
uptime_secs : UInt64
net_rx_bytes_per_sec : UInt64
net_tx_bytes_per_sec : UInt64
load_centi : UInt32
}
// Type aliases
// Traits
@@ -0,0 +1,23 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/wallpaper"
// Values
pub fn current_desktop() -> UInt32
pub fn current_wallpaper() -> UInt32
pub fn desktops() -> Array[String]
pub fn set_desktop(UInt32) -> Unit
pub fn set_wallpaper(UInt32) -> Unit
pub fn wallpapers() -> Array[String]
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,32 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/desktop/windows"
// Values
pub fn all() -> Array[WindowDetail]
pub fn focus(UInt64) -> Unit
pub fn focus_window(UInt32) -> Unit
pub fn list_windows() -> Array[WindowInfo]
// Errors
// Types and methods
pub(all) struct WindowDetail {
id : UInt64
title : String
app_id : String
focused : Bool
}
pub(all) struct WindowInfo {
id : UInt32
title : String
focused : UInt32
minimized : UInt32
}
// Type aliases
// Traits
@@ -0,0 +1,23 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/host/font"
// Values
pub fn load(UInt32, String) -> Bool
pub fn rasterise(UInt32, UInt32, UInt32) -> Glyph
// Errors
// Types and methods
pub(all) struct Glyph {
width : Int32
height : Int32
xoff : Int32
yoff : Int32
advance : Int32
coverage : FixedArray[Byte]
}
// Type aliases
// Traits
+8
View File
@@ -12,6 +12,9 @@ fn wasmImportLoadImage(p0 : Int, p1 : Int) -> Int = "chandra:host/raster@0.1.0"
///| ///|
fn wasmImportThumbnail(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/raster@0.1.0" "thumbnail" fn wasmImportThumbnail(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/raster@0.1.0" "thumbnail"
///|
fn wasmImportImagePixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int = "chandra:host/raster@0.1.0" "image-pixels"
///| ///|
fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) = "chandra:host/raster@0.1.0" "submit" fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) = "chandra:host/raster@0.1.0" "submit"
@@ -56,6 +59,11 @@ extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
#|(func (param i32) (result i32) local.get 0 i32.load) #|(func (param i32) (result i32) local.get 0 i32.load)
///|
#owned(bytes)
extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int =
#|(func (param i32) (result i32) local.get 0)
///| ///|
extern "wasm" fn mbt_ffi_free(position : Int) = extern "wasm" fn mbt_ffi_free(position : Int) =
#|(func (param i32) local.get 0 call $moonbit.decref) #|(func (param i32) local.get 0 call $moonbit.decref)
@@ -20,6 +20,16 @@ fn wasmImportThumbnail(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
abort("wasm-only host import") abort("wasm-only host import")
} }
///|
fn wasmImportImagePixels(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int) -> Int {
abort("wasm-only host import")
}
///|
fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int {
abort("wasm-only")
}
///| ///|
fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) -> Unit { fn wasmImportSubmit(p0 : Int, p1 : Int, p2 : Int, p3 : Int, p4 : Int, p5 : Int, p6 : Int, p7 : Int, p8 : Int, p9 : Int, p10 : Int, p11 : Int, p12 : Int) -> Unit {
abort("wasm-only host import") abort("wasm-only host import")
@@ -0,0 +1,135 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/interface/chandra/host/raster"
// Values
pub fn capture(Int32, Int32, Int32, Int32, Int32, Int32) -> UInt32
pub fn export_memfd() -> Int32
pub fn grab_recording_frame(Int32, Int32, Int32, Int32, Bool, Int32, Int32) -> Bool
pub fn image_pixels(Int32, Int32, FixedArray[Byte], UInt32) -> UInt32
pub fn load_image(String) -> UInt32
pub fn read_frame() -> FixedArray[Byte]
pub fn release(UInt32) -> Unit
pub fn send_recording_frame(Int32) -> Int32
pub fn snapshot_frame() -> Bool
pub fn snapshot_pixels(Int32, Int32, Int32, Int32, Int32, Int32) -> FixedArray[Byte]
pub fn snapshot_png(Int32, Int32, Int32, Int32) -> FixedArray[Byte]
pub fn submit(Frame) -> Unit
pub fn thumbnail(UInt32, Int32, Int32, UInt32) -> UInt32
pub fn write_frame_png(String) -> Bool
// Errors
// Types and methods
pub(all) struct Color {
r : Byte
g : Byte
b : Byte
a : Byte
}
pub(all) struct Disc {
cx : Int32
cy : Int32
radius : Int32
color : Color
filled : Bool
}
pub(all) struct Fill {
area : Rect
color : Color
radius : Int32
}
pub(all) struct Frame {
width : Int32
height : Int32
wallpaper : Array[Op]?
background : Array[Op]
windows : Array[Window]
panel : Array[Op]
popups : Array[Popup]
}
pub(all) struct Label {
x : Int32
y : Int32
text : String
size : Int32
color : Color
align : Byte
bold : Bool
mono : Bool
}
pub(all) enum Op {
FillRect(Fill)
StrokeRect(Stroke)
DrawLine(Segment)
DrawCircle(Disc)
DrawText(Label)
PushClip(Rect)
PopClip
DrawImage(Picture)
}
pub(all) struct Picture {
area : Rect
image : UInt32
}
pub(all) struct Popup {
area : Rect
surface : UInt32
}
pub(all) struct Rect {
x : Int32
y : Int32
w : Int32
h : Int32
}
pub(all) struct Segment {
x0 : Int32
y0 : Int32
x1 : Int32
y1 : Int32
color : Color
width : Int32
}
pub(all) struct Stroke {
area : Rect
color : Color
width : Int32
radius : Int32
}
pub(all) struct Window {
geometry : Rect
inset_top : Int32
inset_right : Int32
inset_bottom : Int32
inset_left : Int32
deco : Array[Op]
fullscreen : Bool
surface : UInt32
}
// Type aliases
// Traits
+14
View File
@@ -95,6 +95,20 @@ pub fn thumbnail(surface : UInt, w : Int, h : Int, reuse : UInt) -> UInt {
let ret = (result).reinterpret_as_uint() let ret = (result).reinterpret_as_uint()
return ret return ret
}
///|
/// `w` x `h` RGBA8888 pixels as an image for `draw-image` (the face unlock window's camera
/// picture). `reuse`: an earlier handle from this function or `thumbnail` to overwrite in place,
/// 0 for a new one. 0 when the size is silly or `rgba` is too short.
pub fn image_pixels(w : Int, h : Int, rgba : FixedArray[Byte], reuse : UInt) -> UInt {
let ptr = mbt_ffi_bytes2ptr(rgba)
let result : Int = wasmImportImagePixels(w, h, ptr, rgba.length(), (reuse).reinterpret_as_int());
mbt_ffi_free(ptr)
let ret = (result).reinterpret_as_uint()
return ret
} }
///| ///|
/// Draw a frame into the host framebuffer. /// Draw a frame into the host framebuffer.
@@ -42,7 +42,7 @@ pub fn sleep_ms(Int32) -> Unit
pub fn spawn(String, String) -> Bool pub fn spawn(String, String) -> Bool
pub fn spawn_socket(String) -> Int pub fn spawn_socket(String) -> Int32
pub fn take_fd(Int32) -> Int32 pub fn take_fd(Int32) -> Int32
+46
View File
@@ -12,22 +12,60 @@ pub let binary_config : ClockConfig
pub fn binary_info() -> (String, String, Int32, Int32, Int32) pub fn binary_info() -> (String, String, Int32, Int32, Int32)
pub fn days_in_month(Int32, Int32) -> Int32
pub let digital_config : ClockConfig pub let digital_config : ClockConfig
pub fn digital_info() -> (String, String, Int32, Int32, Int32) pub fn digital_info() -> (String, String, Int32, Int32, Int32)
pub fn is_leap(Int32) -> Bool
pub fn iso_week(Int32, Int32, Int32) -> Int32
pub fn long_date(@types.Datetime) -> String
pub fn month_grid(Int32, Int32, Bool) -> Array[DayCell]
pub fn render_binary(@types.Size, @theme.Tokens, @types.Datetime, seconds? : Bool) -> Array[@types.DrawOp] pub fn render_binary(@types.Size, @theme.Tokens, @types.Datetime, seconds? : Bool) -> Array[@types.DrawOp]
pub fn render_digital(@types.Size, @theme.Tokens, @types.Datetime, hour12? : Bool, show_date? : Bool, ampm? : Bool) -> Array[@types.DrawOp] pub fn render_digital(@types.Size, @theme.Tokens, @types.Datetime, hour12? : Bool, show_date? : Bool, ampm? : Bool) -> Array[@types.DrawOp]
pub fn weekday_of(Int32, Int32, Int32) -> Int32
// Errors // Errors
// Types and methods // Types and methods
pub(all) struct Calendar {
mut open : Bool
mut year : Int32
mut month : Int32
mut monday_first : Bool
mut week_numbers : Bool
mut hover : CalendarHit
}
pub fn Calendar::go_today(Self, @types.Datetime) -> Unit
pub fn Calendar::handle(Self, Bool, @types.InputEvent, @types.Datetime) -> Bool
pub fn Calendar::hit(Self, Int32, Int32) -> CalendarHit
pub fn Calendar::new() -> Self
pub fn Calendar::render(Self, @theme.Tokens, @types.Datetime, hour12? : Bool, ampm? : Bool) -> Array[@types.DrawOp]
pub fn Calendar::shift(Self, Int32) -> Unit
pub fn Calendar::size(Self) -> (Int32, Int32)
pub fn Calendar::toggle(Self, @types.Datetime) -> Unit
#derive(Eq, @debug.Debug)
pub(all) enum CalendarHit {
Prev
Next
Today
Nothing
}
pub(all) struct ClockConfig { pub(all) struct ClockConfig {
mut hour12 : Bool mut hour12 : Bool
mut show_date : Bool mut show_date : Bool
mut seconds : Bool mut seconds : Bool
mut ampm : Bool mut ampm : Bool
cal : Calendar
} }
pub fn ClockConfig::binary_items(Self) -> Array[ConfigEntry] pub fn ClockConfig::binary_items(Self) -> Array[ConfigEntry]
pub fn ClockConfig::digital_items(Self) -> Array[ConfigEntry] pub fn ClockConfig::digital_items(Self) -> Array[ConfigEntry]
@@ -42,6 +80,14 @@ pub(all) struct ConfigEntry {
value : String value : String
} }
#derive(Eq, @debug.Debug)
pub(all) struct DayCell {
year : Int32
month : Int32
day : Int32
in_month : Bool
}
// Type aliases // Type aliases
// Traits // Traits
+2
View File
@@ -58,6 +58,8 @@ pub let size_choices : Array[String]
pub fn tile_color(String) -> @types.Color pub fn tile_color(String) -> @types.Color
pub fn titled_at(Array[DockItem], DockConfig, Int32, Int32, Int32) -> Bool
pub fn toggle_pin(Array[String], String) -> Array[String] pub fn toggle_pin(Array[String], String) -> Array[String]
// Errors // Errors
+68
View File
@@ -0,0 +1,68 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/lib/icondesk"
import {
"chandra/desktop/interface/chandra/desktop/theme",
"chandra/desktop/interface/chandra/desktop/types",
"moonbitlang/core/debug",
}
// Values
pub let count_choices : Array[String]
pub let size_choices : Array[String]
pub let state : Desk
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) enum Action {
NoAction
Launch(String)
}
#derive(Eq, @debug.Debug)
pub(all) struct ConfigEntry {
key : String
label : String
choices : Array[String]
value : String
}
pub(all) struct Desk {
mut count : String
mut size : String
places : Map[String, (Int32, Int32)]
mut w : Int32
mut h : Int32
mut bottom : Int32
mut hover : String
mut selected : String
mut focused : Bool
mut press_id : String
mut press_x : Int32
mut press_y : Int32
mut dragging : Bool
mut ptr_x : Int32
mut ptr_y : Int32
}
pub fn Desk::app_at(Self, Array[@types.AppEntry], Int32, Int32) -> String
pub fn Desk::cell(Self) -> (Int32, Int32, Int32)
pub fn Desk::cell_at(Self, Int32, Int32) -> (Int32, Int32)
pub fn Desk::cell_origin(Self, Int32, Int32) -> (Int32, Int32)
pub fn Desk::config_items(Self) -> Array[ConfigEntry]
pub fn Desk::decode_places(Self, String) -> Unit
pub fn Desk::encode_places(Self) -> String
pub fn Desk::grid(Self) -> (Int32, Int32)
pub fn Desk::handle(Self, Array[@types.AppEntry], @types.InputEvent) -> (Bool, Action)
pub fn Desk::layout(Self, Array[@types.AppEntry]) -> Array[(Int32, Int32)]
pub fn Desk::new() -> Self
pub fn Desk::render(Self, Array[@types.AppEntry], @types.Size, @theme.Tokens, (String) -> UInt32) -> Array[@types.DrawOp]
pub fn Desk::set_config(Self, String, String) -> Bool
pub fn Desk::shown(Self, Array[@types.AppEntry]) -> Array[@types.AppEntry]
// Type aliases
// Traits
+20 -2
View File
@@ -7,11 +7,25 @@ import {
} }
// Values // Values
pub fn action_at(Array[@types.AppEntry], State, @types.Point) -> Int32
pub let action_logout : Int32
pub let action_power_off : Int32
pub let action_reload : Int32
pub let action_restart : Int32
pub let action_suspend : Int32
pub fn close(State) -> Unit pub fn close(State) -> Unit
pub fn filter(Array[@types.AppEntry], String) -> Array[@types.AppEntry] pub fn filter(Array[@types.AppEntry], String) -> Array[@types.AppEntry]
pub fn handle_event(Array[@types.AppEntry], State, Target, @types.InputEvent, (String) -> Result[Unit, String]) -> Bool pub fn handle_event(Array[@types.AppEntry], State, Target, @types.InputEvent, (String) -> Result[Unit, String], session? : (Int32) -> Unit) -> Bool
pub fn needs_confirm(Int32) -> Bool
pub fn popup_size(Array[@types.AppEntry], State) -> @types.Size pub fn popup_size(Array[@types.AppEntry], State) -> @types.Size
@@ -19,10 +33,12 @@ pub let popup_w : Int32
pub fn render_button(@types.Size, @theme.Tokens, State) -> Array[@types.DrawOp] pub fn render_button(@types.Size, @theme.Tokens, State) -> Array[@types.DrawOp]
pub fn render_popup(Array[@types.AppEntry], @theme.Tokens, State, icon? : (String) -> UInt) -> Array[@types.DrawOp] pub fn render_popup(Array[@types.AppEntry], @theme.Tokens, State, icon? : (String) -> UInt32) -> Array[@types.DrawOp]
pub fn row_at(Array[@types.AppEntry], State, @types.Point) -> Int32 pub fn row_at(Array[@types.AppEntry], State, @types.Point) -> Int32
pub let session_actions : Array[String]
pub fn shown_rows(Array[@types.AppEntry], State) -> Array[@types.AppEntry] pub fn shown_rows(Array[@types.AppEntry], State) -> Array[@types.AppEntry]
// Errors // Errors
@@ -33,6 +49,8 @@ pub struct State {
mut query : String mut query : String
mut hover : Int32 mut hover : Int32
mut error : String mut error : String
mut hover_action : Int32
mut armed : Int32
} }
pub fn State::new() -> Self pub fn State::new() -> Self
+63
View File
@@ -0,0 +1,63 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/lib/starfield"
import {
"chandra/desktop/interface/chandra/desktop/theme",
"chandra/desktop/interface/chandra/desktop/types",
"moonbitlang/core/debug",
}
// Values
pub let density_choices : Array[String]
pub let frame_ms : UInt32
pub let motion_choices : Array[String]
pub let speed_choices : Array[String]
pub let state : Field
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) struct ConfigEntry {
key : String
label : String
choices : Array[String]
value : String
}
pub(all) struct Field {
stars : Array[Star]
mut seed : UInt32
mut speed : String
mut density : String
mut motion : String
mut boost : Double
mut pulse : Double
mut cx : Double
mut cy : Double
mut tx : Double
mut ty : Double
mut w : Int32
mut h : Int32
mut last : Int32
mut frames : Int32
}
pub fn Field::animating(Self) -> Bool
pub fn Field::config_items(Self) -> Array[ConfigEntry]
pub fn Field::handle(Self, @types.InputEvent) -> Bool
pub fn Field::new() -> Self
pub fn Field::render(Self, @types.Size, @theme.Tokens) -> Array[@types.DrawOp]
pub fn Field::scroll(Self, Int32) -> Bool
pub fn Field::set_config(Self, String, String) -> Bool
pub fn Field::step(Self, Double) -> Unit
pub fn Field::tick(Self, UInt32) -> UInt32
type Star
// Type aliases
// Traits
+9
View File
@@ -886,6 +886,15 @@ fn raster_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
}, },
), ),
("load-image", a => [U32(load_image(a[0].to_string()).reinterpret_as_uint())]), ("load-image", a => [U32(load_image(a[0].to_string()).reinterpret_as_uint())]),
(
"image-pixels",
a => {
let reuse = a[3].to_int()
let reuse = if is_path_image(reuse) { 0 } else { reuse }
let px = a[2].to_bytes().to_fixedarray()
[U32(rs_image_put(reuse, a[0].to_int(), a[1].to_int(), px).reinterpret_as_uint())]
},
),
( (
"thumbnail", "thumbnail",
a => { a => {
+6 -5
View File
@@ -336,9 +336,10 @@ interface network {
} }
/// Face unlock (docs/face-unlock.md): the session user's enrolled faces and whether the password /// Face unlock (docs/face-unlock.md): the session user's enrolled faces and whether the password
/// dialog and sudo try the face first. Every change runs chandra-face through run0 or pkexec, so /// dialog and sudo try the face first. Faces are added and removed in the compositor's Face unlock
/// polkit asks for an administrator's password before anything happens; the module never sees a /// window, whose Apply runs chandra-face through run0 or pkexec once, so polkit asks for an
/// camera picture or any face data, only labels. /// administrator's password before anything changes; the module never sees a camera picture or
/// any face data, only labels.
interface face-unlock { interface face-unlock {
record face-status { record face-status {
/// Why face unlock can't work yet ("python3-opencv is not installed"), or empty. /// Why face unlock can't work yet ("python3-opencv is not installed"), or empty.
@@ -363,9 +364,9 @@ interface face-unlock {
status: func() -> face-status; status: func() -> face-status;
/// The enrolled faces, oldest first. /// The enrolled faces, oldest first.
faces: func() -> list<face>; faces: func() -> list<face>;
/// Add a face: after the password, the camera looks for about ten seconds. /// Open the Face unlock window (live camera picture, Snap, saved faces, one Apply).
enroll: func(); enroll: func();
/// Forget face `index` of `faces`. /// Open the Face unlock window with face `index` of `faces` marked for removal.
remove: func(index: u32); remove: func(index: u32);
/// Try the face first in the password dialog and sudo, or stop. /// Try the face first in the password dialog and sudo, or stop.
set-in-use: func(on: bool); set-in-use: func(on: bool);
+4
View File
@@ -62,6 +62,10 @@ interface raster {
/// (the Alt+Tab switcher's window previews). `reuse`: an earlier thumbnail handle to overwrite /// (the Alt+Tab switcher's window previews). `reuse`: an earlier thumbnail handle to overwrite
/// in place, 0 for a new one. 0 when the surface is unknown or the size is silly. /// in place, 0 for a new one. 0 when the surface is unknown or the size is silly.
thumbnail: func(surface: u32, w: s32, h: s32, reuse: u32) -> u32; thumbnail: func(surface: u32, w: s32, h: s32, reuse: u32) -> u32;
/// `w` x `h` RGBA8888 pixels as an image for `draw-image` (the face unlock window's camera
/// picture). `reuse`: an earlier handle from this function or `thumbnail` to overwrite in place,
/// 0 for a new one. 0 when the size is silly or `rgba` is too short.
image-pixels: func(w: s32, h: s32, rgba: list<u8>, reuse: u32) -> u32;
/// Draw a frame into the host framebuffer. /// Draw a frame into the host framebuffer.
submit: func(f: frame); submit: func(f: frame);
/// The framebuffer as RGBA8888 (for screenshots and tests; the display path never needs it). /// The framebuffer as RGBA8888 (for screenshots and tests; the display path never needs it).
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/world/compositor"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/world/icon-desktop-widget"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/world/inspector-widget"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/world/layout-widget"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/world/network-widget"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/world/screenshot-widget"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/world/session-settings-widget"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/world/starfield-widget"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "chandra/desktop/world/taskbar-widget"
// Values
// Errors
// Types and methods
// Type aliases
// Traits