1use mitsuami_core::{ActionError, Command, NativeAppInfo, NativeIcon, NodeId, Point, Size, WidgetKind};
4use objc2::Message;
5use objc2::rc::Retained;
6use objc2_app_kit::{NSApplication, NSView};
7use objc2_foundation::{NSBundle, NSDate, NSDefaultRunLoopMode, NSPoint, NSProcessInfo, NSRunLoop};
8
9use super::{AppKitHandle, State, Widget};
10
11impl AppKitHandle {
12 pub(crate) fn app_id(&self) -> Option<String> {
14 let id = self.state.borrow().app_id.clone();
15 id.or_else(|| objc2_foundation::NSBundle::mainBundle().bundleIdentifier().map(|id| id.to_string()))
16 }
17
18 pub(crate) fn app_name(&self) -> String {
21 let name = self.state.borrow().app_name.clone();
22 name.unwrap_or_else(|| NSProcessInfo::processInfo().processName().to_string())
23 }
24
25 pub fn command_log(&self) -> Vec<Command> {
26 self.state.borrow().log.clone()
27 }
28
29 pub fn take_command_log(&self) -> Vec<Command> {
30 std::mem::take(&mut self.state.borrow_mut().log)
31 }
32
33 pub fn node_count(&self) -> usize {
35 self.state.borrow().nodes.len()
36 }
37
38 pub fn ns_view(&self, id: NodeId) -> Option<Retained<NSView>> {
40 let state = self.state.borrow();
41 let view = state.nodes.get(&id)?.widget.view();
42 Some(view.retain())
43 }
44}
45
46impl mitsuami_core::TestHooks for AppKitHandle {
47 fn name(&self) -> &'static str {
48 "appkit"
49 }
50
51 fn dragged_files(&self, node: NodeId) -> Option<Vec<std::path::PathBuf>> {
52 let state = self.state.borrow();
53 let host = state.nodes.get(&node)?;
54 match &state.nodes.get(&host.parent?)?.widget {
55 Widget::List(list) => list.dragged_files(host.row?),
56 _ => None,
57 }
58 }
59
60 fn hit(&self, window: NodeId, at: Point) -> Result<Option<NodeId>, ActionError> {
63 let state = self.state.borrow();
64 let content = state.nodes.get(&window).ok_or(ActionError::UnknownNode)?.widget.view().retain();
65 let height = content.bounds().size.height;
66 let local = NSPoint::new(at.x as f64, if content.isFlipped() { at.y as f64 } else { height - at.y as f64 });
67 let point = match unsafe { content.superview() } {
69 Some(parent) => content.convertPoint_toView(local, Some(&parent)),
70 None => local,
71 };
72 let mut view = content.hitTest(point);
73 while let Some(v) = view {
74 if let Some((id, _)) = state.nodes.iter().find(|(_, n)| *n.widget.view() == *v) {
75 return Ok(Some(*id));
76 }
77 view = unsafe { v.superview() };
78 }
79 Ok(None)
80 }
81
82 fn resize_window(&self, window: NodeId, size: Size) {
83 AppKitHandle::resize_window(self, window, size);
84 }
85
86 fn close_window(&self, window: NodeId) {
88 if let Some(window) = self.ns_window(window) {
89 window.performClose(None);
90 }
91 }
92
93 fn take_command_log(&self) -> Vec<Command> {
94 AppKitHandle::take_command_log(self)
95 }
96
97 fn node_count(&self) -> usize {
98 AppKitHandle::node_count(self)
99 }
100
101 fn app_info(&self, _window: NodeId) -> NativeAppInfo {
104 let mtm = self.state.borrow().mtm;
105 let id = NSBundle::mainBundle().bundleIdentifier().map(|id| id.to_string());
106 let icon = NSApplication::sharedApplication(mtm).applicationIconImage().map(|image| {
108 let size = image.size();
109 NativeIcon::Image { width: size.width.round() as u32, height: size.height.round() as u32 }
110 });
111 NativeAppInfo { id, name: self.state.borrow().app_name.clone(), icon }
112 }
113
114 fn settle(&self) {
120 if self.state.borrow().nodes.values().any(|n| n.kind == WidgetKind::SearchInput) {
121 NSRunLoop::currentRunLoop().limitDateForMode(unsafe { NSDefaultRunLoopMode });
122 }
123 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
126 while super::images::thumbnails_pending() && std::time::Instant::now() < deadline {
127 let until = NSDate::dateWithTimeIntervalSinceNow(0.01);
128 NSRunLoop::currentRunLoop().runMode_beforeDate(unsafe { NSDefaultRunLoopMode }, &until);
129 }
130 let state = self.state.borrow();
131 state.layout_lists();
132 state.layout_toolbars();
133 state.extend_under_bars();
134 }
135}
136
137impl State {
138 pub(super) fn layout_toolbars(&self) {
142 for node in self.nodes.values() {
143 layout_toolbar(&node.widget);
144 }
145 }
146
147 pub(super) fn layout_lists(&self) {
152 for node in self.nodes.values() {
153 layout_list(&node.widget);
154 }
155 }
156
157 pub(super) fn note_touched(&mut self, command: &Command) {
163 let ids = match command {
164 Command::Create { id, .. }
165 | Command::SetProp { id, .. }
166 | Command::SetFrame { id, .. }
167 | Command::SetWindowSize { id, .. }
168 | Command::ScrollTo { id, .. }
169 | Command::ScrollToRow { id, .. } => [Some(*id), None],
170 Command::Insert { parent, child, .. } | Command::Remove { parent, child } => [Some(*parent), Some(*child)],
171 _ => return,
172 };
173 for id in ids.into_iter().flatten() {
174 let Some(node) = self.nodes.get(&id) else { continue };
175 match &node.widget {
176 Widget::List(_) => {
177 self.touched_lists.insert(id);
178 }
179 Widget::Window { .. } => {
180 self.touched_windows.insert(id);
181 }
182 Widget::Tabs(_) | Widget::Scroll(_) => self.touched_all_lists = true,
183 _ => {}
184 }
185 let parent = node.parent.and_then(|p| Some((p, &self.nodes.get(&p)?.widget)));
186 match parent {
187 Some((list, Widget::List(_))) => {
189 self.touched_lists.insert(list);
190 }
191 Some((window, Widget::Window { .. })) => {
193 self.touched_windows.insert(window);
194 }
195 _ => {}
196 }
197 if let Some(window) = self.toolbar_item_above(id).and_then(|item| self.nodes[&item].parent) {
199 self.touched_windows.insert(window);
200 }
201 }
202 }
203
204 pub(super) fn layout_touched(&mut self) {
208 if std::mem::take(&mut self.touched_all_lists) {
209 self.touched_lists.clear();
210 self.layout_lists();
211 }
212 for id in std::mem::take(&mut self.touched_lists) {
213 if let Some(node) = self.nodes.get(&id) {
214 layout_list(&node.widget);
215 }
216 }
217 for id in std::mem::take(&mut self.touched_windows) {
218 if let Some(node) = self.nodes.get(&id) {
219 layout_toolbar(&node.widget);
220 }
221 }
222 self.place_headers();
223 self.extend_under_bars();
224 }
225
226 fn place_headers(&mut self) {
231 let headers: Vec<NodeId> = self.nodes.iter().filter(|(_, n)| n.header.is_some()).map(|(id, _)| *id).collect();
232 for id in headers {
233 let want = self.header_window(id);
234 let node = &self.nodes[&id];
235 let (header, placeholder) = (node.header.as_ref().unwrap(), node.widget.view());
236 let height = placeholder.frame().size.height;
237 let had = header.window.get();
238 if had != want {
239 let host_of = |w: Option<NodeId>| match w.and_then(|w| self.nodes.get(&w)).map(|n| &n.widget) {
240 Some(Widget::Window { host, .. }) => Some(host.clone()),
241 _ => None,
242 };
243 header.detach(placeholder, host_of(had).as_deref().map(|h| &**h));
244 if let Some(w) = want
245 && let Some(Widget::Window { window, host, _delegate, .. }) = self.nodes.get(&w).map(|n| &n.widget)
246 {
247 let size = host.frame().size;
250 crate::sidebar::content_under_bar(self.mtm, window, host);
251 _delegate.set_detail(Some(host));
252 header.attach(w, window, host, height);
253 window.setContentSize(
254 _delegate.at_least_min(window, Size::new(size.width as f32, size.height as f32)),
255 );
256 }
257 } else if let Some(w) = want
258 && let Some(Widget::Window { host, .. }) = self.nodes.get(&w).map(|n| &n.widget)
259 {
260 header.set_height(host, height);
261 }
262 }
263 }
264
265 fn header_window(&self, id: NodeId) -> Option<NodeId> {
268 let node = self.nodes.get(&id)?;
269 if !node.header.as_ref()?.on.get() {
270 return None;
271 }
272 let mut parent = node.parent;
273 while let Some(p) = parent {
274 let above = self.nodes.get(&p)?;
275 match &above.widget {
276 Widget::Window { host, split: None, .. } => return at_top(node.widget.view(), host, 0.0).then_some(p),
277 Widget::Window { .. } | Widget::Scroll(_) | Widget::List(_) | Widget::Tabs(_) | Widget::Sidebar(_) => {
278 return None;
279 }
280 _ if above.kind == WidgetKind::ToolbarItem => return None,
281 _ => parent = above.parent,
282 }
283 }
284 None
285 }
286
287 pub(super) fn extend_under_bars(&self) {
297 let headers: std::collections::HashMap<NodeId, f64> = self
299 .nodes
300 .values()
301 .filter_map(|n| Some((n.header.as_ref()?.window.get()?, n.widget.view().frame().size.height)))
302 .collect();
303 let mut splits: std::collections::HashMap<NodeId, f64> = std::collections::HashMap::new();
305 for node in self.nodes.values() {
306 let scroll = match &node.widget {
307 Widget::Scroll(scroll) => scroll,
308 Widget::List(list) => &list.scroll,
309 _ => continue,
310 };
311 let mut host = None;
312 let mut around = Vec::new();
313 let mut parent = node.parent;
314 while let Some((id, node)) = parent.and_then(|id| Some((id, self.nodes.get(&id)?))) {
315 match &node.widget {
316 Widget::SplitView(_) => {
317 around.push(id);
318 parent = node.parent;
319 continue;
320 }
321 Widget::Window { host: window, split: Some(_), .. } => host = Some((window, 0.0)),
322 Widget::Window { host: window, toolbar: Some(_), .. } => {
323 host = Some((window, headers.get(&id).copied().unwrap_or(0.0)))
324 }
325 Widget::Window { host: window, .. } => host = headers.get(&id).map(|h| (window, *h)),
326 Widget::Scroll(_) | Widget::List(_) => {}
327 _ => {
328 parent = node.parent;
329 continue;
330 }
331 }
332 break;
333 }
334 let height = match host {
337 Some((host, header)) if at_top(scroll, host, header) => {
338 unsafe { host.superview() }.map_or(0.0, |v| v.safeAreaInsets().top)
339 }
340 _ => 0.0,
341 };
342 if height > 0.0 {
343 for split in around {
344 splits.insert(split, height);
345 }
346 }
347 if scroll.set_under_bar(height) {
348 layout_list(&node.widget);
349 }
350 }
351 for (id, node) in &self.nodes {
352 if let Widget::SplitView(split) = &node.widget {
353 split.set_under_bar(splits.get(id).copied().unwrap_or(0.0));
354 }
355 }
356 }
357}
358
359fn at_top(view: &NSView, host: &NSView, top: f64) -> bool {
362 let Some(superview) = unsafe { view.superview() }.filter(|_| view.isDescendantOf(host)) else { return false };
363 let placed = superview.convertRect_toView(view.alignmentRectForFrame(view.frame()), Some(host));
364 (placed.origin.y - top).abs() < 0.5 && placed.size.height > 0.0
365}
366
367fn layout_toolbar(widget: &Widget) {
368 if let Widget::Window { window, toolbar, split, .. } = widget
369 && (toolbar.is_some() || split.is_some())
370 {
371 window.layoutIfNeeded();
372 }
373}
374
375fn layout_list(widget: &Widget) {
376 if let Widget::List(list) = widget {
377 list.table.setNeedsLayout(true);
380 list.scroll.layoutSubtreeIfNeeded();
381 list.remeasure();
382 }
383}