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