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_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 hit(&self, window: NodeId, at: Point) -> Result<Option<NodeId>, ActionError> {
57 let state = self.state.borrow();
58 let content = state.nodes.get(&window).ok_or(ActionError::UnknownNode)?.widget.view().retain();
59 let height = content.bounds().size.height;
60 let local = NSPoint::new(at.x as f64, if content.isFlipped() { at.y as f64 } else { height - at.y as f64 });
61 let point = match unsafe { content.superview() } {
63 Some(parent) => content.convertPoint_toView(local, Some(&parent)),
64 None => local,
65 };
66 let mut view = content.hitTest(point);
67 while let Some(v) = view {
68 if let Some((id, _)) = state.nodes.iter().find(|(_, n)| *n.widget.view() == *v) {
69 return Ok(Some(*id));
70 }
71 view = unsafe { v.superview() };
72 }
73 Ok(None)
74 }
75
76 fn resize_window(&self, window: NodeId, size: Size) {
77 AppKitHandle::resize_window(self, window, size);
78 }
79
80 fn close_window(&self, window: NodeId) {
82 if let Some(window) = self.ns_window(window) {
83 window.performClose(None);
84 }
85 }
86
87 fn take_command_log(&self) -> Vec<Command> {
88 AppKitHandle::take_command_log(self)
89 }
90
91 fn node_count(&self) -> usize {
92 AppKitHandle::node_count(self)
93 }
94
95 fn app_info(&self, _window: NodeId) -> NativeAppInfo {
98 let mtm = self.state.borrow().mtm;
99 let id = NSBundle::mainBundle().bundleIdentifier().map(|id| id.to_string());
100 let icon = NSApplication::sharedApplication(mtm).applicationIconImage().map(|image| {
102 let size = image.size();
103 NativeIcon::Image { width: size.width.round() as u32, height: size.height.round() as u32 }
104 });
105 NativeAppInfo { id, name: self.state.borrow().app_name.clone(), icon }
106 }
107
108 fn settle(&self) {
114 if self.state.borrow().nodes.values().any(|n| n.kind == WidgetKind::SearchInput) {
115 NSRunLoop::currentRunLoop().limitDateForMode(unsafe { NSDefaultRunLoopMode });
116 }
117 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
120 while super::images::thumbnails_pending() && std::time::Instant::now() < deadline {
121 let until = NSDate::dateWithTimeIntervalSinceNow(0.01);
122 NSRunLoop::currentRunLoop().runMode_beforeDate(unsafe { NSDefaultRunLoopMode }, &until);
123 }
124 let state = self.state.borrow();
125 state.layout_lists();
126 state.layout_toolbars();
127 state.extend_under_bars();
128 }
129}
130
131impl State {
132 pub(super) fn layout_toolbars(&self) {
136 for node in self.nodes.values() {
137 layout_toolbar(&node.widget);
138 }
139 }
140
141 pub(super) fn layout_lists(&self) {
146 for node in self.nodes.values() {
147 layout_list(&node.widget);
148 }
149 }
150
151 pub(super) fn note_touched(&mut self, command: &Command) {
157 let ids = match command {
158 Command::Create { id, .. }
159 | Command::SetProp { id, .. }
160 | Command::SetFrame { id, .. }
161 | Command::SetWindowSize { id, .. }
162 | Command::ScrollTo { id, .. }
163 | Command::ScrollToRow { id, .. } => [Some(*id), None],
164 Command::Insert { parent, child, .. } | Command::Remove { parent, child } => [Some(*parent), Some(*child)],
165 _ => return,
166 };
167 for id in ids.into_iter().flatten() {
168 let Some(node) = self.nodes.get(&id) else { continue };
169 match &node.widget {
170 Widget::List(_) => {
171 self.touched_lists.insert(id);
172 }
173 Widget::Window { .. } => {
174 self.touched_windows.insert(id);
175 }
176 Widget::Tabs(_) | Widget::Scroll(_) => self.touched_all_lists = true,
177 _ => {}
178 }
179 let parent = node.parent.and_then(|p| Some((p, &self.nodes.get(&p)?.widget)));
180 match parent {
181 Some((list, Widget::List(_))) => {
183 self.touched_lists.insert(list);
184 }
185 Some((window, Widget::Window { .. })) => {
187 self.touched_windows.insert(window);
188 }
189 _ => {}
190 }
191 if let Some(window) = self.toolbar_item_above(id).and_then(|item| self.nodes[&item].parent) {
193 self.touched_windows.insert(window);
194 }
195 }
196 }
197
198 pub(super) fn layout_touched(&mut self) {
202 if std::mem::take(&mut self.touched_all_lists) {
203 self.touched_lists.clear();
204 self.layout_lists();
205 }
206 for id in std::mem::take(&mut self.touched_lists) {
207 if let Some(node) = self.nodes.get(&id) {
208 layout_list(&node.widget);
209 }
210 }
211 for id in std::mem::take(&mut self.touched_windows) {
212 if let Some(node) = self.nodes.get(&id) {
213 layout_toolbar(&node.widget);
214 }
215 }
216 self.place_headers();
217 self.extend_under_bars();
218 }
219
220 fn place_headers(&mut self) {
225 let headers: Vec<NodeId> = self.nodes.iter().filter(|(_, n)| n.header.is_some()).map(|(id, _)| *id).collect();
226 for id in headers {
227 let want = self.header_window(id);
228 let node = &self.nodes[&id];
229 let (header, placeholder) = (node.header.as_ref().unwrap(), node.widget.view());
230 let height = placeholder.frame().size.height;
231 let had = header.window.get();
232 if had != want {
233 let host_of = |w: Option<NodeId>| match w.and_then(|w| self.nodes.get(&w)).map(|n| &n.widget) {
234 Some(Widget::Window { host, .. }) => Some(host.clone()),
235 _ => None,
236 };
237 header.detach(placeholder, host_of(had).as_deref().map(|h| &**h));
238 if let Some(w) = want
239 && let Some(Widget::Window { window, host, _delegate, .. }) = self.nodes.get(&w).map(|n| &n.widget)
240 {
241 let size = host.frame().size;
244 crate::sidebar::content_under_bar(self.mtm, window, host);
245 _delegate.set_detail(Some(host));
246 header.attach(w, window, host, height);
247 window.setContentSize(
248 _delegate.at_least_min(window, Size::new(size.width as f32, size.height as f32)),
249 );
250 }
251 } else if let Some(w) = want
252 && let Some(Widget::Window { host, .. }) = self.nodes.get(&w).map(|n| &n.widget)
253 {
254 header.set_height(host, height);
255 }
256 }
257 }
258
259 fn header_window(&self, id: NodeId) -> Option<NodeId> {
262 let node = self.nodes.get(&id)?;
263 if !node.header.as_ref()?.on.get() {
264 return None;
265 }
266 let mut parent = node.parent;
267 while let Some(p) = parent {
268 let above = self.nodes.get(&p)?;
269 match &above.widget {
270 Widget::Window { host, split: None, .. } => return at_top(node.widget.view(), host, 0.0).then_some(p),
271 Widget::Window { .. } | Widget::Scroll(_) | Widget::List(_) | Widget::Tabs(_) | Widget::Sidebar(_) => {
272 return None;
273 }
274 _ if above.kind == WidgetKind::ToolbarItem => return None,
275 _ => parent = above.parent,
276 }
277 }
278 None
279 }
280
281 pub(super) fn extend_under_bars(&self) {
291 let headers: std::collections::HashMap<NodeId, f64> = self
293 .nodes
294 .values()
295 .filter_map(|n| Some((n.header.as_ref()?.window.get()?, n.widget.view().frame().size.height)))
296 .collect();
297 let mut splits: std::collections::HashMap<NodeId, f64> = std::collections::HashMap::new();
299 for node in self.nodes.values() {
300 let scroll = match &node.widget {
301 Widget::Scroll(scroll) => scroll,
302 Widget::List(list) => &list.scroll,
303 _ => continue,
304 };
305 let mut host = None;
306 let mut around = Vec::new();
307 let mut parent = node.parent;
308 while let Some((id, node)) = parent.and_then(|id| Some((id, self.nodes.get(&id)?))) {
309 match &node.widget {
310 Widget::SplitView(_) => {
311 around.push(id);
312 parent = node.parent;
313 continue;
314 }
315 Widget::Window { host: window, split: Some(_), .. } => host = Some((window, 0.0)),
316 Widget::Window { host: window, toolbar: Some(_), .. } => {
317 host = Some((window, headers.get(&id).copied().unwrap_or(0.0)))
318 }
319 Widget::Window { host: window, .. } => host = headers.get(&id).map(|h| (window, *h)),
320 Widget::Scroll(_) | Widget::List(_) => {}
321 _ => {
322 parent = node.parent;
323 continue;
324 }
325 }
326 break;
327 }
328 let height = match host {
331 Some((host, header)) if at_top(scroll, host, header) => {
332 unsafe { host.superview() }.map_or(0.0, |v| v.safeAreaInsets().top)
333 }
334 _ => 0.0,
335 };
336 if height > 0.0 {
337 for split in around {
338 splits.insert(split, height);
339 }
340 }
341 if scroll.set_under_bar(height) {
342 layout_list(&node.widget);
343 }
344 }
345 for (id, node) in &self.nodes {
346 if let Widget::SplitView(split) = &node.widget {
347 split.set_under_bar(splits.get(id).copied().unwrap_or(0.0));
348 }
349 }
350 }
351}
352
353fn at_top(view: &NSView, host: &NSView, top: f64) -> bool {
356 let Some(superview) = unsafe { view.superview() }.filter(|_| view.isDescendantOf(host)) else { return false };
357 let placed = superview.convertRect_toView(view.alignmentRectForFrame(view.frame()), Some(host));
358 (placed.origin.y - top).abs() < 0.5 && placed.size.height > 0.0
359}
360
361fn layout_toolbar(widget: &Widget) {
362 if let Widget::Window { window, toolbar, split, .. } = widget
363 && (toolbar.is_some() || split.is_some())
364 {
365 window.layoutIfNeeded();
366 }
367}
368
369fn layout_list(widget: &Widget) {
370 if let Widget::List(list) = widget {
371 list.table.setNeedsLayout(true);
374 list.scroll.layoutSubtreeIfNeeded();
375 list.remeasure();
376 }
377}