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  refused: Option<Signal<bool>>,
49}
50
51impl SessionLock {
52  /// A lock that never locks, with nothing on its surfaces.
53  pub fn new() -> SessionLock {
54    SessionLock::default()
55  }
56
57  /// Sets whether the session is locked. Turning it false unlocks, as
58  /// after the user's password was checked.
59  pub fn locked(mut self, locked: impl IntoProp<bool>) -> SessionLock {
60    self.locked = Some(locked.into_prop());
61    self
62  }
63
64  /// Writes `refused` true when the compositor refuses the lock, as when
65  /// another program holds it, or ends it while `locked` is still true,
66  /// and when it lacks `ext-session-lock-v1`. It turns false again once
67  /// `locked` turns false, so a config can tell a refusal from "not
68  /// locked yet" and clear its own `locked` flag. Not set, nothing is
69  /// written.
70  pub fn refused(mut self, refused: Signal<bool>) -> SessionLock {
71    self.refused = Some(refused);
72    self
73  }
74
75  /// Sets the style of every output's surface. Its color and font are
76  /// inherited by every [`Text`](crate::Text) on them that doesn't set its
77  /// own.
78  pub fn style(mut self, style: impl IntoProp<Style>) -> SessionLock {
79    self.style = Some(style.into_prop());
80    self
81  }
82
83  /// Sets what each output's surface shows: `build` runs for every output
84  /// while the session locks, and for each output added while it is
85  /// locked, under a context that goes with that surface.
86  pub fn surface<W: Widget>(mut self, build: impl Fn(&Cx, &Output) -> W + 'static) -> SessionLock {
87    self.surface = Some(Rc::new(move |cx: &Cx, output: &Output| {
88      Box::new(build(cx, output)) as Box<dyn Widget>
89    }));
90    self
91  }
92
93  /// Runs `handler` with every key a surface's focused field or button
94  /// didn't use, as [`PanelWindow::on_key`](crate::PanelWindow::on_key)
95  /// does, with that surface's context; it returns `true` when it used
96  /// the key. Escape clearing the password field is the usual one. A
97  /// handler that panics is logged with the surface's path, such as
98  /// `SessionLock[DP-1].on_key`, and that surface's stops running it.
99  pub fn on_key(mut self, handler: impl Fn(&Cx, &KeyEvent) -> bool + 'static) -> SessionLock {
100    self.on_key = Some(Rc::new(handler));
101    self
102  }
103}
104
105/// A [`SessionLock`] as the platform holds it: whether the config wants
106/// the session locked, what the compositor says, and each output's lock
107/// surface. Dropping it disposes its owner, which frees everything it
108/// made.
109pub struct Lock {
110  cx: Cx,
111  /// What `locked` says.
112  wanted: Signal<bool>,
113  /// What the compositor says.
114  locked: Signal<bool>,
115  /// The config's, from `refused`.
116  refused: Option<Signal<bool>>,
117  /// Kept in the reactive runtime, which drops the user's closures when
118  /// the lock's owner goes.
119  parts: Signal<Parts>,
120}
121
122impl Lock {
123  /// Builds `lock` under a new child owner of `cx`. A `locked` binding is
124  /// an effect, so it first runs at the next flush.
125  ///
126  /// # Panics
127  ///
128  /// If `cx`'s owner was disposed, as [`Cx::signal`] does.
129  pub fn new(cx: &Cx, lock: SessionLock) -> Lock {
130    let cx = cx.child().named("SessionLock");
131    let wanted = cx.signal(false);
132    match lock.locked.map(|locked| locked.0) {
133      None => {}
134      Some(PropKind::Value(value)) => wanted.set(value),
135      Some(PropKind::Binding(mut compute)) => {
136        cx.effect(move || wanted.set(compute()))
137          .named("SessionLock.locked");
138      }
139    }
140    Lock {
141      wanted,
142      locked: cx.signal(false),
143      refused: lock.refused,
144      parts: cx.signal((lock.style.map(Prop::shared), lock.surface, lock.on_key)),
145      cx,
146    }
147  }
148
149  /// Whether `locked` says to lock; `None` once the lock's owner is gone.
150  pub fn wanted(&self) -> Option<bool> {
151    untrack(|| self.wanted.try_get())
152  }
153
154  /// `true` while the compositor says the session is locked.
155  pub fn locked(&self) -> ReadSignal<bool> {
156    self.locked.read_only()
157  }
158
159  /// Records what the compositor said; a value it holds already is left
160  /// alone, so nothing reruns.
161  pub fn set_locked(&self, locked: bool) {
162    if untrack(|| self.locked.try_get()) == Some(!locked) {
163      self.locked.set(locked);
164    }
165  }
166
167  /// Records whether the compositor refused or ended the lock, into the
168  /// `refused` signal when one was given and its owner lives; a value it
169  /// holds already is left alone.
170  pub fn set_refused(&self, refused: bool) {
171    if let Some(signal) = self.refused
172      && untrack(|| signal.try_get()) == Some(!refused)
173    {
174      signal.set(refused);
175    }
176  }
177
178  /// Builds `output`'s lock surface under a new child owner, its path
179  /// `SessionLock[DP-1]`. A `surface` builder that panics is logged with
180  /// that path, and the surface shows only the lock's style. `None` once
181  /// the lock's owner is gone.
182  pub fn surface(&self, output: &Output) -> Option<Window> {
183    let (style, build, on_key) = untrack(|| self.parts.try_with(Clone::clone))?;
184    let path: Rc<str> = format!("SessionLock[{}]", output.name()).into();
185    let cx = self
186      .cx
187      .child()
188      .named(path.to_string())
189      .at(Rc::new(Anchor::default()));
190    // Untracked, as a popup's builder: nothing reruns it.
191    let built = panic::catch_unwind(AssertUnwindSafe(|| {
192      untrack(|| build.map(|build| build(&cx, output).into_element()))
193    }));
194    let child = built.unwrap_or_else(|payload| {
195      tracing::error!(
196        "{path} panicked while it was built, so it shows only the lock's style: {}",
197        panic_message(payload.as_ref())
198      );
199      None
200    });
201    let owner = cx.owner();
202    let tree = Rc::new_cyclic(|this| {
203      RefCell::new(Tree::new(
204        this.clone(),
205        "SessionLock",
206        output.clone(),
207        cx,
208        path,
209      ))
210    });
211    let style = style.map(|style| (move || style()).into_prop());
212    let mut mounted = borrow(&tree);
213    // Each surface's own, so a panic disables it on that surface only.
214    mounted.keyboard.handler = on_key.map(|on_key| {
215      Rc::new(Handler::new(move |cx: &Cx, event: &KeyEvent| {
216        on_key(cx, event)
217      })) as KeyHandler
218    });
219    mounted.mount_root(style, child);
220    drop(mounted);
221    Some(Window { tree, owner })
222  }
223}
224
225impl Drop for Lock {
226  fn drop(&mut self) {
227    self.cx.owner().dispose();
228  }
229}