1use mitsuami_core::{Command, NativeAppInfo, NativeIcon, NodeId, Size, WidgetKind};
4use objc2::Message;
5use objc2::rc::Retained;
6use objc2_app_kit::{NSApplication, NSView};
7use objc2_foundation::{NSBundle, NSDate, NSDefaultRunLoopMode, NSProcessInfo, NSRunLoop};
8
9use super::{AppKitHandle, State, Widget};
10
11impl AppKitHandle {
12 pub(crate) fn app_name(&self) -> String {
15 let name = self.state.borrow().app_name.clone();
16 name.unwrap_or_else(|| NSProcessInfo::processInfo().processName().to_string())
17 }
18
19 pub fn command_log(&self) -> Vec<Command> {
20 self.state.borrow().log.clone()
21 }
22
23 pub fn take_command_log(&self) -> Vec<Command> {
24 std::mem::take(&mut self.state.borrow_mut().log)
25 }
26
27 pub fn node_count(&self) -> usize {
29 self.state.borrow().nodes.len()
30 }
31
32 pub fn ns_view(&self, id: NodeId) -> Option<Retained<NSView>> {
34 let state = self.state.borrow();
35 let view = state.nodes.get(&id)?.widget.view();
36 Some(view.retain())
37 }
38}
39
40impl mitsuami_core::TestHooks for AppKitHandle {
41 fn name(&self) -> &'static str {
42 "appkit"
43 }
44
45 fn dragged_files(&self, node: NodeId) -> Option<Vec<std::path::PathBuf>> {
46 let state = self.state.borrow();
47 let host = state.nodes.get(&node)?;
48 match &state.nodes.get(&host.parent?)?.widget {
49 Widget::List(list) => list.dragged_files(host.row?),
50 _ => None,
51 }
52 }
53
54 fn resize_window(&self, window: NodeId, size: Size) {
55 AppKitHandle::resize_window(self, window, size);
56 }
57
58 fn close_window(&self, window: NodeId) {
60 if let Some(window) = self.ns_window(window) {
61 window.performClose(None);
62 }
63 }
64
65 fn take_command_log(&self) -> Vec<Command> {
66 AppKitHandle::take_command_log(self)
67 }
68
69 fn node_count(&self) -> usize {
70 AppKitHandle::node_count(self)
71 }
72
73 fn app_info(&self, _window: NodeId) -> NativeAppInfo {
76 let mtm = self.state.borrow().mtm;
77 let id = NSBundle::mainBundle().bundleIdentifier().map(|id| id.to_string());
78 let icon = NSApplication::sharedApplication(mtm).applicationIconImage().map(|image| {
80 let size = image.size();
81 NativeIcon::Image { width: size.width.round() as u32, height: size.height.round() as u32 }
82 });
83 NativeAppInfo { id, name: self.state.borrow().app_name.clone(), icon }
84 }
85
86 fn settle(&self) {
92 if self.state.borrow().nodes.values().any(|n| n.kind == WidgetKind::SearchInput) {
93 NSRunLoop::currentRunLoop().limitDateForMode(unsafe { NSDefaultRunLoopMode });
94 }
95 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
98 while super::images::thumbnails_pending() && std::time::Instant::now() < deadline {
99 let until = NSDate::dateWithTimeIntervalSinceNow(0.01);
100 NSRunLoop::currentRunLoop().runMode_beforeDate(unsafe { NSDefaultRunLoopMode }, &until);
101 }
102 let state = self.state.borrow();
103 state.layout_lists();
104 state.layout_toolbars();
105 state.extend_under_bars();
106 }
107}
108
109impl State {
110 pub(super) fn layout_toolbars(&self) {
114 for node in self.nodes.values() {
115 layout_toolbar(&node.widget);
116 }
117 }
118
119 pub(super) fn layout_lists(&self) {
124 for node in self.nodes.values() {
125 layout_list(&node.widget);
126 }
127 }
128
129 pub(super) fn note_touched(&mut self, command: &Command) {
135 let ids = match command {
136 Command::Create { id, .. }
137 | Command::SetProp { id, .. }
138 | Command::SetFrame { id, .. }
139 | Command::SetWindowSize { id, .. }
140 | Command::ScrollTo { id, .. }
141 | Command::ScrollToRow { id, .. } => [Some(*id), None],
142 Command::Insert { parent, child, .. } | Command::Remove { parent, child } => [Some(*parent), Some(*child)],
143 _ => return,
144 };
145 for id in ids.into_iter().flatten() {
146 let Some(node) = self.nodes.get(&id) else { continue };
147 match &node.widget {
148 Widget::List(_) => {
149 self.touched_lists.insert(id);
150 }
151 Widget::Window { .. } => {
152 self.touched_windows.insert(id);
153 }
154 Widget::Tabs(_) | Widget::Scroll(_) => self.touched_all_lists = true,
155 _ => {}
156 }
157 let parent = node.parent.and_then(|p| Some((p, &self.nodes.get(&p)?.widget)));
158 match parent {
159 Some((list, Widget::List(_))) => {
161 self.touched_lists.insert(list);
162 }
163 Some((window, Widget::Window { .. })) => {
165 self.touched_windows.insert(window);
166 }
167 _ => {}
168 }
169 if let Some(window) = self.toolbar_item_above(id).and_then(|item| self.nodes[&item].parent) {
171 self.touched_windows.insert(window);
172 }
173 }
174 }
175
176 pub(super) fn layout_touched(&mut self) {
180 if std::mem::take(&mut self.touched_all_lists) {
181 self.touched_lists.clear();
182 self.layout_lists();
183 }
184 for id in std::mem::take(&mut self.touched_lists) {
185 if let Some(node) = self.nodes.get(&id) {
186 layout_list(&node.widget);
187 }
188 }
189 for id in std::mem::take(&mut self.touched_windows) {
190 if let Some(node) = self.nodes.get(&id) {
191 layout_toolbar(&node.widget);
192 }
193 }
194 self.place_headers();
195 self.extend_under_bars();
196 }
197
198 fn place_headers(&mut self) {
203 let headers: Vec<NodeId> = self.nodes.iter().filter(|(_, n)| n.header.is_some()).map(|(id, _)| *id).collect();
204 for id in headers {
205 let want = self.header_window(id);
206 let node = &self.nodes[&id];
207 let (header, placeholder) = (node.header.as_ref().unwrap(), node.widget.view());
208 let height = placeholder.frame().size.height;
209 let had = header.window.get();
210 if had != want {
211 let host_of = |w: Option<NodeId>| match w.and_then(|w| self.nodes.get(&w)).map(|n| &n.widget) {
212 Some(Widget::Window { host, .. }) => Some(host.clone()),
213 _ => None,
214 };
215 header.detach(placeholder, host_of(had).as_deref().map(|h| &**h));
216 if let Some(w) = want
217 && let Some(Widget::Window { window, host, _delegate, .. }) = self.nodes.get(&w).map(|n| &n.widget)
218 {
219 let size = host.frame().size;
222 crate::sidebar::content_under_bar(self.mtm, window, host);
223 _delegate.set_detail(Some(host));
224 header.attach(w, window, host, height);
225 window.setContentSize(
226 _delegate.at_least_min(window, Size::new(size.width as f32, size.height as f32)),
227 );
228 }
229 } else if let Some(w) = want
230 && let Some(Widget::Window { host, .. }) = self.nodes.get(&w).map(|n| &n.widget)
231 {
232 header.set_height(host, height);
233 }
234 }
235 }
236
237 fn header_window(&self, id: NodeId) -> Option<NodeId> {
240 let node = self.nodes.get(&id)?;
241 if !node.header.as_ref()?.on.get() {
242 return None;
243 }
244 let mut parent = node.parent;
245 while let Some(p) = parent {
246 let above = self.nodes.get(&p)?;
247 match &above.widget {
248 Widget::Window { host, split: None, .. } => return at_top(node.widget.view(), host, 0.0).then_some(p),
249 Widget::Window { .. } | Widget::Scroll(_) | Widget::List(_) | Widget::Tabs(_) | Widget::Sidebar(_) => {
250 return None;
251 }
252 _ if above.kind == WidgetKind::ToolbarItem => return None,
253 _ => parent = above.parent,
254 }
255 }
256 None
257 }
258
259 pub(super) fn extend_under_bars(&self) {
267 let headers: std::collections::HashMap<NodeId, f64> = self
269 .nodes
270 .values()
271 .filter_map(|n| Some((n.header.as_ref()?.window.get()?, n.widget.view().frame().size.height)))
272 .collect();
273 for node in self.nodes.values() {
274 let scroll = match &node.widget {
275 Widget::Scroll(scroll) => scroll,
276 Widget::List(list) => &list.scroll,
277 _ => continue,
278 };
279 let mut host = None;
280 let mut parent = node.parent;
281 while let Some((id, node)) = parent.and_then(|id| Some((id, self.nodes.get(&id)?))) {
282 match &node.widget {
283 Widget::Window { host: window, split: Some(_), .. } => host = Some((window, 0.0)),
284 Widget::Window { host: window, toolbar: Some(_), .. } => {
285 host = Some((window, headers.get(&id).copied().unwrap_or(0.0)))
286 }
287 Widget::Window { host: window, .. } => host = headers.get(&id).map(|h| (window, *h)),
288 Widget::Scroll(_) | Widget::List(_) => {}
289 _ => {
290 parent = node.parent;
291 continue;
292 }
293 }
294 break;
295 }
296 let height = match host {
299 Some((host, header)) if at_top(scroll, host, header) => {
300 unsafe { host.superview() }.map_or(0.0, |v| v.safeAreaInsets().top)
301 }
302 _ => 0.0,
303 };
304 if scroll.set_under_bar(height) {
305 layout_list(&node.widget);
306 }
307 }
308 }
309}
310
311fn at_top(view: &NSView, host: &NSView, top: f64) -> bool {
314 let Some(superview) = unsafe { view.superview() }.filter(|_| view.isDescendantOf(host)) else { return false };
315 let placed = superview.convertRect_toView(view.alignmentRectForFrame(view.frame()), Some(host));
316 (placed.origin.y - top).abs() < 0.5 && placed.size.height > 0.0
317}
318
319fn layout_toolbar(widget: &Widget) {
320 if let Widget::Window { window, toolbar, split, .. } = widget
321 && (toolbar.is_some() || split.is_some())
322 {
323 window.layoutIfNeeded();
324 }
325}
326
327fn layout_list(widget: &Widget) {
328 if let Widget::List(list) = widget {
329 list.table.setNeedsLayout(true);
332 list.scroll.layoutSubtreeIfNeeded();
333 }
334}