use mitsuami_core::{Command, NativeAppInfo, NativeIcon, NodeId, Size, WidgetKind};
use objc2::Message;
use objc2::rc::Retained;
use objc2_app_kit::{NSApplication, NSScrollView, NSView};
use objc2_foundation::{NSBundle, NSDate, NSDefaultRunLoopMode, NSProcessInfo, NSRunLoop};
use super::{AppKitHandle, State, Widget};
impl AppKitHandle {
pub(crate) fn app_name(&self) -> String {
let name = self.state.borrow().app_name.clone();
name.unwrap_or_else(|| NSProcessInfo::processInfo().processName().to_string())
}
pub fn command_log(&self) -> Vec<Command> {
self.state.borrow().log.clone()
}
pub fn take_command_log(&self) -> Vec<Command> {
std::mem::take(&mut self.state.borrow_mut().log)
}
pub fn node_count(&self) -> usize {
self.state.borrow().nodes.len()
}
pub fn ns_view(&self, id: NodeId) -> Option<Retained<NSView>> {
let state = self.state.borrow();
let view = state.nodes.get(&id)?.widget.view();
Some(view.retain())
}
}
impl mitsuami_core::TestHooks for AppKitHandle {
fn name(&self) -> &'static str {
"appkit"
}
fn dragged_files(&self, node: NodeId) -> Option<Vec<std::path::PathBuf>> {
let state = self.state.borrow();
let host = state.nodes.get(&node)?;
match &state.nodes.get(&host.parent?)?.widget {
Widget::List(list) => list.dragged_files(host.row?),
_ => None,
}
}
fn resize_window(&self, window: NodeId, size: Size) {
AppKitHandle::resize_window(self, window, size);
}
fn close_window(&self, window: NodeId) {
if let Some(window) = self.ns_window(window) {
window.performClose(None);
}
}
fn take_command_log(&self) -> Vec<Command> {
AppKitHandle::take_command_log(self)
}
fn node_count(&self) -> usize {
AppKitHandle::node_count(self)
}
fn app_info(&self, _window: NodeId) -> NativeAppInfo {
let mtm = self.state.borrow().mtm;
let id = NSBundle::mainBundle().bundleIdentifier().map(|id| id.to_string());
let icon = NSApplication::sharedApplication(mtm).applicationIconImage().map(|image| {
let size = image.size();
NativeIcon::Image { width: size.width.round() as u32, height: size.height.round() as u32 }
});
NativeAppInfo { id, name: self.state.borrow().app_name.clone(), icon }
}
fn settle(&self) {
if self.state.borrow().nodes.values().any(|n| n.kind == WidgetKind::SearchInput) {
NSRunLoop::currentRunLoop().limitDateForMode(unsafe { NSDefaultRunLoopMode });
}
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
while super::images::thumbnails_pending() && std::time::Instant::now() < deadline {
let until = NSDate::dateWithTimeIntervalSinceNow(0.01);
NSRunLoop::currentRunLoop().runMode_beforeDate(unsafe { NSDefaultRunLoopMode }, &until);
}
let state = self.state.borrow();
state.layout_lists();
state.layout_toolbars();
state.extend_under_bars();
}
}
impl State {
pub(super) fn layout_toolbars(&self) {
for node in self.nodes.values() {
layout_toolbar(&node.widget);
}
}
pub(super) fn layout_lists(&self) {
for node in self.nodes.values() {
layout_list(&node.widget);
}
}
pub(super) fn note_touched(&mut self, command: &Command) {
let ids = match command {
Command::Create { id, .. }
| Command::SetProp { id, .. }
| Command::SetFrame { id, .. }
| Command::SetWindowSize { id, .. }
| Command::ScrollTo { id, .. }
| Command::ScrollToRow { id, .. } => [Some(*id), None],
Command::Insert { parent, child, .. } | Command::Remove { parent, child } => [Some(*parent), Some(*child)],
_ => return,
};
for id in ids.into_iter().flatten() {
let Some(node) = self.nodes.get(&id) else { continue };
match &node.widget {
Widget::List(_) => {
self.touched_lists.insert(id);
}
Widget::Window { .. } => {
self.touched_windows.insert(id);
}
Widget::Tabs(_) | Widget::Scroll(_) => self.touched_all_lists = true,
_ => {}
}
let parent = node.parent.and_then(|p| Some((p, &self.nodes.get(&p)?.widget)));
match parent {
Some((list, Widget::List(_))) => {
self.touched_lists.insert(list);
}
Some((window, Widget::Window { .. })) => {
self.touched_windows.insert(window);
}
_ => {}
}
if let Some(window) = self.toolbar_item_above(id).and_then(|item| self.nodes[&item].parent) {
self.touched_windows.insert(window);
}
}
}
pub(super) fn layout_touched(&mut self) {
if std::mem::take(&mut self.touched_all_lists) {
self.touched_lists.clear();
self.layout_lists();
}
for id in std::mem::take(&mut self.touched_lists) {
if let Some(node) = self.nodes.get(&id) {
layout_list(&node.widget);
}
}
for id in std::mem::take(&mut self.touched_windows) {
if let Some(node) = self.nodes.get(&id) {
layout_toolbar(&node.widget);
}
}
self.extend_under_bars();
}
pub(super) fn extend_under_bars(&self) {
for node in self.nodes.values() {
let scroll = match &node.widget {
Widget::Scroll(scroll) => scroll,
Widget::List(list) => &list.scroll,
_ => continue,
};
let mut host = None;
let mut parent = node.parent;
while let Some(node) = parent.and_then(|id| self.nodes.get(&id)) {
match &node.widget {
Widget::Window { host: window, split: Some(_), .. } => host = Some(window),
Widget::Window { host: window, toolbar: Some(_), .. } => host = Some(window),
Widget::Window { .. } | Widget::Scroll(_) | Widget::List(_) => {}
_ => {
parent = node.parent;
continue;
}
}
break;
}
let height = match host {
Some(host) if at_top(scroll, host) => unsafe { host.superview() }.map_or(0.0, |v| v.safeAreaInsets().top),
_ => 0.0,
};
if scroll.set_under_bar(height) {
layout_list(&node.widget);
}
}
}
}
fn at_top(scroll: &NSScrollView, host: &NSView) -> bool {
let Some(superview) = unsafe { scroll.superview() }.filter(|_| scroll.isDescendantOf(host)) else { return false };
let placed = superview.convertRect_toView(scroll.alignmentRectForFrame(scroll.frame()), Some(host));
placed.origin.y.abs() < 0.5 && placed.size.height > 0.0
}
fn layout_toolbar(widget: &Widget) {
if let Widget::Window { window, toolbar, split, .. } = widget
&& (toolbar.is_some() || split.is_some())
{
window.layoutIfNeeded();
}
}
fn layout_list(widget: &Widget) {
if let Widget::List(list) = widget {
list.table.setNeedsLayout(true);
list.scroll.layoutSubtreeIfNeeded();
}
}