Skip to main content

crabshell_ui/
lock.rs

1//! [`SessionLock`], a lock screen over every output, and [`Lock`], the
2//! live one the platform locks the session for and builds each output's
3//! lock surface from.
4
5use std::cell::RefCell;
6use std::panic::{self, AssertUnwindSafe};
7use std::rc::Rc;
8
9use crabshell_reactive::{ReadSignal, Signal, untrack};
10
11use crate::cx::{Anchor, Cx};
12use crate::input::{Handler, panic_message};
13use crate::keyboard::{KeyEvent, KeyHandler};
14use crate::prop::{IntoProp, Prop, PropKind};
15use crate::style::Style;
16use crate::tree::{Tree, borrow};
17use crate::widgets::Widget;
18use crate::window::{Output, Window};
19
20/// A `surface` builder, as stored.
21type Build = Rc<dyn Fn(&Cx, &Output) -> Box<dyn Widget>>;
22
23/// An `on_key` handler, as stored.
24type OnKey = Rc<dyn Fn(&Cx, &KeyEvent) -> bool>;
25
26/// The style, shared by every surface, the builder and `on_key`.
27type Parts = (Option<Rc<dyn Fn() -> Style>>, Option<Build>, Option<OnKey>);
28
29/// A lock screen: while `locked` is true, the compositor shows only its
30/// surfaces, one covering each output, and nothing else gets input. Lock
31/// with `cx.session_lock` from the `crabshell` crate. Every property
32/// takes a value or a closure.
33///
34/// ```
35/// use crabshell_ui::{Color, SessionLock, Style, Text};
36///
37/// let lock = SessionLock::new()
38///     .locked(true)
39///     .style(Style::new().background(Color::rgb(0, 0, 0)))
40///     .surface(|_cx, output| Text::new(format!("locked on {}", output.name())));
41/// ```
42#[derive(Default)]
43pub struct SessionLock {
44  locked: Option<Prop<bool>>,
45  style: Option<Prop<Style>>,
46  surface: Option<Build>,
47  on_key: Option<OnKey>,
48}
49
50impl SessionLock {
51  /// A lock that never locks, with nothing on its surfaces.
52  pub fn new() -> SessionLock {
53    SessionLock::default()
54  }
55
56  /// Sets whether the session is locked. Turning it false unlocks, as
57  /// after the user's password was checked.
58  pub fn locked(mut self, locked: impl IntoProp<bool>) -> SessionLock {
59    self.locked = Some(locked.into_prop());
60    self
61  }
62
63  /// Sets the style of every output's surface. Its color and font are
64  /// inherited by every [`Text`](crate::Text) on them that doesn't set its
65  /// own.
66  pub fn style(mut self, style: impl IntoProp<Style>) -> SessionLock {
67    self.style = Some(style.into_prop());
68    self
69  }
70
71  /// Sets what each output's surface shows: `build` runs for every output
72  /// while the session locks, and for each output added while it is
73  /// locked, under a context that goes with that surface.
74  pub fn surface<W: Widget>(mut self, build: impl Fn(&Cx, &Output) -> W + 'static) -> SessionLock {
75    self.surface = Some(Rc::new(move |cx: &Cx, output: &Output| {
76      Box::new(build(cx, output)) as Box<dyn Widget>
77    }));
78    self
79  }
80
81  /// Runs `handler` with every key a surface's focused field or button
82  /// didn't use, as [`PanelWindow::on_key`](crate::PanelWindow::on_key)
83  /// does, with that surface's context; it returns `true` when it used
84  /// the key. Escape clearing the password field is the usual one. A
85  /// handler that panics is logged with the surface's path, such as
86  /// `SessionLock[DP-1].on_key`, and that surface's stops running it.
87  pub fn on_key(mut self, handler: impl Fn(&Cx, &KeyEvent) -> bool + 'static) -> SessionLock {
88    self.on_key = Some(Rc::new(handler));
89    self
90  }
91}
92
93/// A [`SessionLock`] as the platform holds it: whether the config wants
94/// the session locked, what the compositor says, and each output's lock
95/// surface. Dropping it disposes its owner, which frees everything it
96/// made.
97pub struct Lock {
98  cx: Cx,
99  /// What `locked` says.
100  wanted: Signal<bool>,
101  /// What the compositor says.
102  locked: Signal<bool>,
103  /// Kept in the reactive runtime, which drops the user's closures when
104  /// the lock's owner goes.
105  parts: Signal<Parts>,
106}
107
108impl Lock {
109  /// Builds `lock` under a new child owner of `cx`. A `locked` binding is
110  /// an effect, so it first runs at the next flush.
111  ///
112  /// # Panics
113  ///
114  /// If `cx`'s owner was disposed, as [`Cx::signal`] does.
115  pub fn new(cx: &Cx, lock: SessionLock) -> Lock {
116    let cx = cx.child().named("SessionLock");
117    let wanted = cx.signal(false);
118    match lock.locked.map(|locked| locked.0) {
119      None => {}
120      Some(PropKind::Value(value)) => wanted.set(value),
121      Some(PropKind::Binding(mut compute)) => {
122        cx.effect(move || wanted.set(compute()))
123          .named("SessionLock.locked");
124      }
125    }
126    Lock {
127      wanted,
128      locked: cx.signal(false),
129      parts: cx.signal((lock.style.map(Prop::shared), lock.surface, lock.on_key)),
130      cx,
131    }
132  }
133
134  /// Whether `locked` says to lock; `None` once the lock's owner is gone.
135  pub fn wanted(&self) -> Option<bool> {
136    untrack(|| self.wanted.try_get())
137  }
138
139  /// `true` while the compositor says the session is locked.
140  pub fn locked(&self) -> ReadSignal<bool> {
141    self.locked.read_only()
142  }
143
144  /// Records what the compositor said; a value it holds already is left
145  /// alone, so nothing reruns.
146  pub fn set_locked(&self, locked: bool) {
147    if untrack(|| self.locked.try_get()) == Some(!locked) {
148      self.locked.set(locked);
149    }
150  }
151
152  /// Builds `output`'s lock surface under a new child owner, its path
153  /// `SessionLock[DP-1]`. A `surface` builder that panics is logged with
154  /// that path, and the surface shows only the lock's style. `None` once
155  /// the lock's owner is gone.
156  pub fn surface(&self, output: &Output) -> Option<Window> {
157    let (style, build, on_key) = untrack(|| self.parts.try_with(Clone::clone))?;
158    let path: Rc<str> = format!("SessionLock[{}]", output.name()).into();
159    let cx = self
160      .cx
161      .child()
162      .named(path.to_string())
163      .at(Rc::new(Anchor::default()));
164    // Untracked, as a popup's builder: nothing reruns it.
165    let built = panic::catch_unwind(AssertUnwindSafe(|| {
166      untrack(|| build.map(|build| build(&cx, output).into_element()))
167    }));
168    let child = built.unwrap_or_else(|payload| {
169      tracing::error!(
170        "{path} panicked while it was built, so it shows only the lock's style: {}",
171        panic_message(payload.as_ref())
172      );
173      None
174    });
175    let owner = cx.owner();
176    let tree = Rc::new_cyclic(|this| {
177      RefCell::new(Tree::new(
178        this.clone(),
179        "SessionLock",
180        output.clone(),
181        cx,
182        path,
183      ))
184    });
185    let style = style.map(|style| (move || style()).into_prop());
186    let mut mounted = borrow(&tree);
187    // Each surface's own, so a panic disables it on that surface only.
188    mounted.keyboard.handler = on_key.map(|on_key| {
189      Rc::new(Handler::new(move |cx: &Cx, event: &KeyEvent| {
190        on_key(cx, event)
191      })) as KeyHandler
192    });
193    mounted.mount_root(style, child);
194    drop(mounted);
195    Some(Window { tree, owner })
196  }
197}
198
199impl Drop for Lock {
200  fn drop(&mut self) {
201    self.cx.owner().dispose();
202  }
203}