ferrokit_core/events.rs
1//! Callbacks from AppKit, handed to the host framework through one sink.
2
3use crate::kept::{UiCell, UiLocal};
4
5use crate::ViewId;
6
7#[derive(Debug, Clone, PartialEq)]
8/// A callback from AppKit for the host framework (see [`set_event_sink`]).
9pub enum Event {
10 /// Tab (`forward`) or Shift-Tab was pressed and belongs to the host's
11 /// focus order (which spans host widgets and native views).
12 FocusStep {
13 /// Tab (true) or Shift-Tab (false).
14 forward: bool,
15 },
16 /// Keyboard focus moved into a mounted native view (`Some`) or out of all
17 /// of them (`None`), e.g. after a click.
18 FocusChanged(Option<ViewId>),
19 /// The system appearance or accent colour changed.
20 AppearanceChanged,
21 /// A native control registered with [`crate::set_action`] fired.
22 Action(ViewId),
23 /// The host should draw another frame (see [`crate::request_redraw`]).
24 Redraw,
25}
26
27type Sink = Box<dyn Fn(Event)>;
28
29thread_local! {
30 static SINK: UiCell<Option<Sink>> = const { UiCell::new(None) };
31}
32
33/// Where events go. Called on the main thread, from AppKit callbacks.
34pub fn set_event_sink(sink: impl Fn(Event) + 'static) {
35 SINK.with_borrow_mut(|s| *s = Some(Box::new(sink)));
36}
37
38/// Sends `event` to the sink; false if there's none yet.
39pub(crate) fn emit(event: Event) -> bool {
40 SINK.with_borrow(|s| match s {
41 Some(sink) => {
42 sink(event);
43 true
44 }
45 None => false,
46 })
47}
48
49thread_local! {
50 static REDRAW_QUEUED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
51}
52
53/// Asks the host for another frame: emits [`Event::Redraw`] once per frame
54/// (the flag clears at [`crate::begin_frame`]). Used while a snapshot swap is
55/// in progress and no input event would otherwise cause a redraw.
56pub fn request_redraw() {
57 // A request before there's a sink (a model filled before the app runs)
58 // reaches nobody: it mustn't leave the flag set, or no later request
59 // would be sent and queued events would wait forever.
60 if !REDRAW_QUEUED.with(|q| q.replace(true)) && !emit(Event::Redraw) {
61 REDRAW_QUEUED.with(|q| q.set(false));
62 }
63}
64
65pub(crate) fn frame_started() {
66 REDRAW_QUEUED.with(|q| q.set(false));
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72 use std::rc::Rc;
73
74 /// A redraw asked for before the sink exists (a table filled before the
75 /// app runs) doesn't block the ones after it.
76 #[test]
77 fn an_early_redraw_request_doesnt_block_later_ones() {
78 request_redraw();
79 let redraws = Rc::new(std::cell::Cell::new(0));
80 let r = redraws.clone();
81 set_event_sink(move |e| {
82 if e == Event::Redraw {
83 r.set(r.get() + 1);
84 }
85 });
86 request_redraw();
87 request_redraw();
88 assert_eq!(redraws.get(), 1, "one per frame");
89 frame_started();
90 request_redraw();
91 assert_eq!(redraws.get(), 2);
92 }
93}