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
18impl ViewId {
19 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)]
29pub enum AttachError {
31 NoHandle,
33 NotAppKit,
35}
36
37define_class!(
38 #[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 pub(crate) visible: Option<Rect>,
68 placed_frame: u64,
70}
71
72pub(crate) struct Host {
73 pub(crate) content: Retained<NSView>,
75 pub(crate) views: HashMap<ViewId, Mounted>,
76 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 HOST.try_with(|host| host.borrow_mut().as_mut().map(f)).ok().flatten()
107}
108
109pub 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 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
126pub fn is_attached() -> bool {
128 HOST.with_borrow(Option::is_some)
129}
130
131pub fn scale() -> f64 {
133 with_host(|h| h.content.window().map(|w| w.backingScaleFactor())).flatten().unwrap_or(1.0)
134}
135
136pub fn content_view() -> Option<Retained<NSView>> {
138 with_host(|h| h.content.clone())
139}
140
141pub fn view(id: ViewId) -> Option<Retained<NSView>> {
143 with_host(|h| h.views.get(&id).map(|m| m.view.clone())).flatten()
144}
145
146pub fn is_mounted(id: ViewId) -> bool {
148 with_host(|h| h.views.contains_key(&id)).unwrap_or(false)
149}
150
151pub 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
164pub 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
174pub 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
183pub 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
196pub fn is_suppressed(id: ViewId) -> bool {
198 with_host(|h| h.suppressed.contains(&id)).unwrap_or(false)
199}
200
201pub fn begin_frame() {
204 crate::events::frame_started();
205 with_host_mut(|host| host.frame += 1);
206}
207
208pub 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
226pub 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
234pub 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
266pub(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}