Skip to main content

ferrokit_core/
host.rs

1use crate::kept::{UiCell, UiLocal};
2use std::collections::{HashMap, HashSet};
3
4use objc2::rc::Retained;
5use objc2::runtime::NSObject;
6use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send};
7use objc2_app_kit::{NSResponder, NSScrollView, NSView};
8use objc2_foundation::{NSPoint, NSRect, NSSize};
9use raw_window_handle::{HasWindowHandle, RawWindowHandle};
10
11use crate::geometry::{self, Rect};
12
13/// Identifies a mounted native view. Chosen by the caller; stable for the
14/// view's lifetime (views are created once and updated in place).
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
16pub struct ViewId(pub u64);
17
18impl ViewId {
19    /// A new id, different from every other `next` gives and from the small
20    /// numbers apps chose before 0.13 (`with_id`).
21    pub fn next() -> ViewId {
22        use std::sync::atomic::{AtomicU64, Ordering};
23        static NEXT: AtomicU64 = AtomicU64::new(1 << 40);
24        ViewId(NEXT.fetch_add(1, Ordering::Relaxed))
25    }
26}
27
28#[derive(Debug)]
29/// Why [`attach`] failed.
30pub enum AttachError {
31    /// The window has no handle (yet).
32    NoHandle,
33    /// The window isn't an AppKit window.
34    NotAppKit,
35}
36
37define_class!(
38    // Clipping container around every native view: sized to the visible part
39    // of the slot, flipped so the child's offset uses the host's top-left space.
40    #[unsafe(super(NSView, NSResponder, NSObject))]
41    #[thread_kind = MainThreadOnly]
42    #[name = "FerrokitCoreClipView"]
43    struct ClipView;
44
45    impl ClipView {
46        #[unsafe(method(isFlipped))]
47        fn is_flipped(&self) -> bool {
48            true
49        }
50    }
51);
52
53impl ClipView {
54    fn new(mtm: MainThreadMarker) -> Retained<Self> {
55        let this = Self::alloc(mtm).set_ivars(());
56        let this: Retained<Self> = unsafe { msg_send![super(this), initWithFrame: NSRect::ZERO] };
57        this.setClipsToBounds(true);
58        this.setHidden(true);
59        this
60    }
61}
62
63pub(crate) struct Mounted {
64    clip: Retained<ClipView>,
65    pub(crate) view: Retained<NSView>,
66    /// Visible part in host coordinates, as of the last `place`.
67    pub(crate) visible: Option<Rect>,
68    /// Frame number of the last `place`.
69    placed_frame: u64,
70}
71
72pub(crate) struct Host {
73    /// The host's content view; its layer is the GPU surface.
74    pub(crate) content: Retained<NSView>,
75    pub(crate) views: HashMap<ViewId, Mounted>,
76    /// Views kept hidden regardless of layout (e.g. under an open host overlay).
77    suppressed: HashSet<ViewId>,
78    frame: u64,
79}
80
81thread_local! {
82    static HOST: UiCell<Option<Host>> = const { UiCell::new(None) };
83}
84
85pub(crate) fn mtm() -> MainThreadMarker {
86    MainThreadMarker::new().expect("ferrokit-core must be used on the main thread")
87}
88
89impl Mounted {
90    pub(crate) fn clip_frame(&self) -> NSRect {
91        self.clip.frame()
92    }
93
94    pub(crate) fn shown(&self) -> bool {
95        self.visible.is_some() && !self.clip.isHidden()
96    }
97}
98
99pub(crate) fn with_host<R>(f: impl FnOnce(&Host) -> R) -> Option<R> {
100    HOST.with_borrow(|host| host.as_ref().map(f))
101}
102
103fn with_host_mut<R>(f: impl FnOnce(&mut Host) -> R) -> Option<R> {
104    // `try_with`: views are also unmounted while thread-locals are torn
105    // down at exit.
106    HOST.try_with(|host| host.borrow_mut().as_mut().map(f)).ok().flatten()
107}
108
109/// Takes the window's content view. Call once the host window exists.
110pub fn attach(window: &impl HasWindowHandle) -> Result<(), AttachError> {
111    let _ = mtm();
112    let handle = window.window_handle().map_err(|_| AttachError::NoHandle)?.as_raw();
113    let RawWindowHandle::AppKit(handle) = handle else { return Err(AttachError::NotAppKit) };
114    // SAFETY: an AppKit window handle carries a valid NSView pointer while the
115    // window lives; we retain it.
116    let content: Retained<NSView> =
117        unsafe { Retained::retain(handle.ns_view.as_ptr().cast()) }.ok_or(AttachError::NoHandle)?;
118    HOST.with_borrow_mut(|host| {
119        *host = Some(Host { content, views: HashMap::new(), suppressed: HashSet::new(), frame: 0 })
120    });
121    crate::keys::install();
122    crate::appearance::observe_appearance();
123    Ok(())
124}
125
126/// Whether [`attach`] has succeeded.
127pub fn is_attached() -> bool {
128    HOST.with_borrow(Option::is_some)
129}
130
131/// Device pixels per point for the attached window (1.0 before attaching).
132pub fn scale() -> f64 {
133    with_host(|h| h.content.window().map(|w| w.backingScaleFactor())).flatten().unwrap_or(1.0)
134}
135
136/// The host's content view (whose layer is the GPU surface).
137pub fn content_view() -> Option<Retained<NSView>> {
138    with_host(|h| h.content.clone())
139}
140
141/// The mounted view itself (not its clip container).
142pub fn view(id: ViewId) -> Option<Retained<NSView>> {
143    with_host(|h| h.views.get(&id).map(|m| m.view.clone())).flatten()
144}
145
146/// Whether a view with this id is mounted.
147pub fn is_mounted(id: ViewId) -> bool {
148    with_host(|h| h.views.contains_key(&id)).unwrap_or(false)
149}
150
151/// Adds `view` (hidden until first placed). Replaces any view with this id.
152pub fn mount(id: ViewId, view: Retained<NSView>) {
153    let mtm = mtm();
154    with_host_mut(|host| {
155        let clip = ClipView::new(mtm);
156        clip.addSubview(&view);
157        host.content.addSubview(&clip);
158        if let Some(old) = host.views.insert(id, Mounted { clip, view, visible: None, placed_frame: 0 }) {
159            old.clip.removeFromSuperview();
160        }
161    });
162}
163
164/// Removes a view from the window (the view is released).
165pub fn unmount(id: ViewId) {
166    with_host_mut(|host| {
167        host.suppressed.remove(&id);
168        if let Some(m) = host.views.remove(&id) {
169            m.clip.removeFromSuperview();
170        }
171    });
172}
173
174/// Hides a view until its next [`place`].
175pub fn hide(id: ViewId) {
176    with_host(|host| {
177        if let Some(m) = host.views.get(&id) {
178            m.clip.setHidden(true);
179        }
180    });
181}
182
183/// Records that a view must stay hidden (or may show again). Takes effect at
184/// the view's next `place`, so the change lands in the same frame the host
185/// draws (toggling it immediately showed a one-frame flash in the spike).
186pub fn set_suppressed(id: ViewId, suppressed: bool) {
187    with_host_mut(|host| {
188        if suppressed {
189            host.suppressed.insert(id);
190        } else {
191            host.suppressed.remove(&id);
192        }
193    });
194}
195
196/// Whether [`set_suppressed`] is keeping the view hidden.
197pub fn is_suppressed(id: ViewId) -> bool {
198    with_host(|h| h.suppressed.contains(&id)).unwrap_or(false)
199}
200
201/// Starts a host frame. Views not placed between this and [`end_frame`] are
202/// hidden: they are no longer in the host's layout.
203pub fn begin_frame() {
204    crate::events::frame_started();
205    with_host_mut(|host| host.frame += 1);
206}
207
208/// Ends a host frame: hides every view that wasn't placed during it.
209pub fn end_frame() {
210    with_host(|host| {
211        for m in host.views.values() {
212            if m.placed_frame != host.frame && !m.clip.isHidden() {
213                m.clip.setHidden(true);
214            }
215        }
216    });
217    with_host_mut(|host| {
218        for m in host.views.values_mut() {
219            if m.placed_frame != host.frame {
220                m.visible = None;
221            }
222        }
223    });
224}
225
226/// Mounted views whose visible part (as last placed) intersects `area`.
227pub fn views_in(area: Rect) -> Vec<ViewId> {
228    with_host(|h| {
229        h.views.iter().filter(|(_, m)| m.visible.is_some_and(|v| v.intersection(&area).is_some())).map(|(id, _)| *id).collect()
230    })
231    .unwrap_or_default()
232}
233
234/// Moves a view to the host's layout. Call while the host draws the frame
235/// that shows the slot, so the native change and the GPU frame belong together.
236/// `bounds`: where the whole view would be. `visible`: the part that may show.
237pub fn place(id: ViewId, bounds: Rect, visible: Rect) {
238    crate::sync::note_place();
239    with_host_mut(|host| {
240        let frame = host.frame;
241        let suppressed = host.suppressed.contains(&id);
242        let scale = host.content.window().map_or(1.0, |w| w.backingScaleFactor());
243        let (height, flipped) = (host.content.bounds().size.height, host.content.isFlipped());
244        let Some(m) = host.views.get_mut(&id) else { return };
245        m.placed_frame = frame;
246        m.visible = (!visible.is_empty()).then_some(visible);
247        if suppressed || visible.is_empty() {
248            m.clip.setHidden(true);
249            return;
250        }
251        let f = geometry::frames(bounds, visible, scale, height, flipped);
252        let ns = |r: Rect| NSRect::new(NSPoint::new(r.x, r.y), NSSize::new(r.width, r.height));
253        let (clip, view) = (ns(f.clip), ns(f.view));
254        if m.clip.frame() != clip {
255            m.clip.setFrame(clip);
256        }
257        if m.view.frame() != view {
258            m.view.setFrame(view);
259        }
260        if m.clip.isHidden() {
261            m.clip.setHidden(false);
262        }
263    });
264}
265
266/// The view that takes keyboard focus for a mounted view: a scroll view's
267/// document view, otherwise the view itself.
268pub(crate) fn focus_target(view: &NSView) -> Retained<NSView> {
269    use objc2::Message as _;
270    match view.downcast_ref::<NSScrollView>() {
271        Some(scroll) => scroll.documentView().unwrap_or_else(|| view.retain()),
272        None => view.retain(),
273    }
274}