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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
16pub struct ViewId(pub u64);
17
18#[derive(Debug)]
19pub enum AttachError {
21 NoHandle,
23 NotAppKit,
25}
26
27define_class!(
28 #[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 pub(crate) visible: Option<Rect>,
58 placed_frame: u64,
60}
61
62pub(crate) struct Host {
63 pub(crate) content: Retained<NSView>,
65 pub(crate) views: HashMap<ViewId, Mounted>,
66 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 HOST.try_with(|host| host.borrow_mut().as_mut().map(f)).ok().flatten()
97}
98
99pub 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 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
116pub fn is_attached() -> bool {
118 HOST.with_borrow(Option::is_some)
119}
120
121pub fn scale() -> f64 {
123 with_host(|h| h.content.window().map(|w| w.backingScaleFactor())).flatten().unwrap_or(1.0)
124}
125
126pub fn content_view() -> Option<Retained<NSView>> {
128 with_host(|h| h.content.clone())
129}
130
131pub fn view(id: ViewId) -> Option<Retained<NSView>> {
133 with_host(|h| h.views.get(&id).map(|m| m.view.clone())).flatten()
134}
135
136pub fn is_mounted(id: ViewId) -> bool {
138 with_host(|h| h.views.contains_key(&id)).unwrap_or(false)
139}
140
141pub 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
154pub 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
164pub 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
173pub 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
186pub fn is_suppressed(id: ViewId) -> bool {
188 with_host(|h| h.suppressed.contains(&id)).unwrap_or(false)
189}
190
191pub fn begin_frame() {
194 crate::events::frame_started();
195 with_host_mut(|host| host.frame += 1);
196}
197
198pub 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
216pub 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
224pub 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
256pub(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}