Skip to main content

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
38pub(crate) fn emit(event: Event) {
39    SINK.with_borrow(|s| {
40        if let Some(sink) = s {
41            sink(event);
42        }
43    });
44}
45
46thread_local! {
47    static REDRAW_QUEUED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
48}
49
50/// Asks the host for another frame: emits [`Event::Redraw`] once per frame
51/// (the flag clears at [`crate::begin_frame`]). Used while a snapshot swap is
52/// in progress and no input event would otherwise cause a redraw.
53pub fn request_redraw() {
54    if !REDRAW_QUEUED.with(|q| q.replace(true)) {
55        emit(Event::Redraw);
56    }
57}
58
59pub(crate) fn frame_started() {
60    REDRAW_QUEUED.with(|q| q.set(false));
61}