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 if !state.options.show_windows {
137 for node in state.nodes.values() {
138 if let Widget::Window { window, _delegate, .. } = &node.widget {
139 _delegate.report_frame(window);
140 }
141 }
142 }
143 }
144}
145
146impl State {
147 pub(super) fn layout_toolbars(&self) {
151 for node in self.nodes.values() {
152 layout_toolbar(&node.widget);
153 }
154 }
155
156 pub(super) fn layout_lists(&self) {
161 for node in self.nodes.values() {
162 layout_list(&node.widget);
163 }
164 }
165
166 pub(super) fn note_touched(&mut self, command: &Command) {
172 let ids = match command {
173 Command::Create { id, .. }
174 | Command::SetProp { id, .. }
175 | Command::SetFrame { id, .. }
176 | Command::SetWindowSize { id, .. }
177 | Command::ScrollTo { id, .. }
178 | Command::ScrollToRow { id, .. } => [Some(*id), None],
179 Command::Insert { parent, child, .. } | Command::Remove { parent, child } => [Some(*parent), Some(*child)],
180 _ => return,
181 };
182 for id in ids.into_iter().flatten() {
183 let Some(node) = self.nodes.get(&id) else { continue };
184 match &node.widget {
185 Widget::List(_) => {
186 self.touched_lists.insert(id);
187 }
188 Widget::Window { .. } => {
189 self.touched_windows.insert(id);
190 }
191 Widget::Tabs(_) | Widget::Scroll(_) => self.touched_all_lists = true,
192 _ => {}
193 }
194 let parent = node.parent.and_then(|p| Some((p, &self.nodes.get(&p)?.widget)));
195 match parent {
196 Some((list, Widget::List(_))) => {
198 self.touched_lists.insert(list);
199 }
200 Some((window, Widget::Window { .. })) => {
202 self.touched_windows.insert(window);
203 }
204 _ => {}
205 }
206 if let Some(window) = self.toolbar_item_above(id).and_then(|item| self.nodes[&item].parent) {
208 self.touched_windows.insert(window);
209 }
210 }
211 }
212
213 pub(super) fn layout_touched(&mut self) {
217 if std::mem::take(&mut self.touched_all_lists) {
218 self.touched_lists.clear();
219 self.layout_lists();
220 }
221 for id in std::mem::take(&mut self.touched_lists) {
222 if let Some(node) = self.nodes.get(&id) {
223 layout_list(&node.widget);
224 }
225 }
226 for id in std::mem::take(&mut self.touched_windows) {
227 if let Some(node) = self.nodes.get(&id) {
228 layout_toolbar(&node.widget);
229 }
230 }
231 self.place_headers();
232 self.extend_under_bars();
233 }
234
235 fn place_headers(&mut self) {
240 let headers: Vec<NodeId> = self.nodes.iter().filter(|(_, n)| n.header.is_some()).map(|(id, _)| *id).collect();
241 for id in headers {
242 let want = self.header_window(id);
243 let node = &self.nodes[&id];
244 let (header, placeholder) = (node.header.as_ref().unwrap(), node.widget.view());
245 let height = placeholder.frame().size.height;
246 let had = header.window.get();
247 if had != want {
248 let host_of = |w: Option<NodeId>| match w.and_then(|w| self.nodes.get(&w)).map(|n| &n.widget) {
249 Some(Widget::Window { host, .. }) => Some(host.clone()),
250 _ => None,
251 };
252 header.detach(placeholder, host_of(had).as_deref().map(|h| &**h));
253 if let Some(w) = want
254 && let Some(Widget::Window { window, host, _delegate, .. }) = self.nodes.get(&w).map(|n| &n.widget)
255 {
256 let size = host.frame().size;
259 crate::sidebar::content_under_bar(self.mtm, window, host);
260 _delegate.set_detail(Some(host));
261 header.attach(w, window, host, height);
262 window.setContentSize(
263 _delegate.at_least_min(window, Size::new(size.width as f32, size.height as f32)),
264 );
265 }
266 } else if let Some(w) = want
267 && let Some(Widget::Window { host, .. }) = self.nodes.get(&w).map(|n| &n.widget)
268 {
269 header.set_height(host, height);
270 }
271 }
272 }
273
274 fn header_window(&self, id: NodeId) -> Option<NodeId> {
277 let node = self.nodes.get(&id)?;
278 if !node.header.as_ref()?.on.get() {
279 return None;
280 }
281 let mut parent = node.parent;
282 while let Some(p) = parent {
283 let above = self.nodes.get(&p)?;
284 match &above.widget {
285 Widget::Window { host, split: None, .. } => return at_top(node.widget.view(), host, 0.0).then_some(p),
286 Widget::Window { .. } | Widget::Scroll(_) | Widget::List(_) | Widget::Tabs(_) | Widget::Sidebar(_) => {
287 return None;
288 }
289 _ if above.kind == WidgetKind::ToolbarItem => return None,
290 _ => parent = above.parent,
291 }
292 }
293 None
294 }
295
296 pub(super) fn extend_under_bars(&self) {
306 let headers: std::collections::HashMap<NodeId, f64> = self
308 .nodes
309 .values()
310 .filter_map(|n| Some((n.header.as_ref()?.window.get()?, n.widget.view().frame().size.height)))
311 .collect();
312 let mut splits: std::collections::HashMap<NodeId, f64> = std::collections::HashMap::new();
314 for node in self.nodes.values() {
315 let scroll = match &node.widget {
316 Widget::Scroll(scroll) => scroll,
317 Widget::List(list) => &list.scroll,
318 _ => continue,
319 };
320 let mut host = None;
321 let mut around = Vec::new();
322 let mut parent = node.parent;
323 while let Some((id, node)) = parent.and_then(|id| Some((id, self.nodes.get(&id)?))) {
324 match &node.widget {
325 Widget::SplitView(_) => {
326 around.push(id);
327 parent = node.parent;
328 continue;
329 }
330 Widget::Window { host: window, split: Some(_), .. } => host = Some((window, 0.0)),
331 Widget::Window { host: window, toolbar: Some(_), .. } => {
332 host = Some((window, headers.get(&id).copied().unwrap_or(0.0)))
333 }
334 Widget::Window { host: window, .. } => host = headers.get(&id).map(|h| (window, *h)),
335 Widget::Scroll(_) | Widget::List(_) => {}
336 _ => {
337 parent = node.parent;
338 continue;
339 }
340 }
341 break;
342 }
343 let height = match host {
346 Some((host, header)) if at_top(scroll, host, header) => {
347 unsafe { host.superview() }.map_or(0.0, |v| v.safeAreaInsets().top)
348 }
349 _ => 0.0,
350 };
351 if height > 0.0 {
352 for split in around {
353 splits.insert(split, height);
354 }
355 }
356 if scroll.set_under_bar(height) {
357 layout_list(&node.widget);
358 }
359 }
360 for (id, node) in &self.nodes {
361 if let Widget::SplitView(split) = &node.widget {
362 split.set_under_bar(splits.get(id).copied().unwrap_or(0.0));
363 }
364 }
365 }
366}
367
368fn at_top(view: &NSView, host: &NSView, top: f64) -> bool {
371 let Some(superview) = unsafe { view.superview() }.filter(|_| view.isDescendantOf(host)) else { return false };
372 let placed = superview.convertRect_toView(view.alignmentRectForFrame(view.frame()), Some(host));
373 (placed.origin.y - top).abs() < 0.5 && placed.size.height > 0.0
374}
375
376fn layout_toolbar(widget: &Widget) {
377 if let Widget::Window { window, toolbar, split, .. } = widget
378 && (toolbar.is_some() || split.is_some())
379 {
380 window.layoutIfNeeded();
381 }
382}
383
384fn layout_list(widget: &Widget) {
385 if let Widget::List(list) = widget {
386 list.table.setNeedsLayout(true);
389 list.scroll.layoutSubtreeIfNeeded();
390 list.remeasure();
391 }
392}