use crate::color::Color;
use crate::core_text::SystemText;
use crate::event::{Button, Cursor, Event, Key, Mods};
use crate::geom::{Point, Rect, Size, pt};
use crate::macos_sys::*;
use crate::platform::{Clipboard, PicturesAndFiles, Window};
use crate::preferences::Preferences;
use crate::screens::Screen;
use crate::surface::Surface;
use crate::theme::ContrastColors;
#[cfg(feature = "touch")]
use crate::touch::Stylus;
use crate::touch::TouchPhase;
use crate::ui::Ui;
use std::cell::{Cell, RefCell};
use std::ffi::{CStr, c_char, c_void};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct Insets {
pub top: f64,
pub left: f64,
pub bottom: f64,
pub right: f64,
}
#[link(name = "UIKit", kind = "framework")]
unsafe extern "C" {
fn UIApplicationMain(argc: i32, argv: *mut *mut c_char, principal: Obj, delegate: Obj) -> i32;
fn UIAccessibilityIsReduceMotionEnabled() -> bool;
fn UIAccessibilityDarkerSystemColorsEnabled() -> bool;
fn UIImagePNGRepresentation(image: Obj) -> Obj;
static UIApplicationDidEnterBackgroundNotification: Obj;
static UIApplicationWillEnterForegroundNotification: Obj;
static UIApplicationDidBecomeActiveNotification: Obj;
static UIApplicationWillResignActiveNotification: Obj;
static UIApplicationWillTerminateNotification: Obj;
static UIContentSizeCategoryDidChangeNotification: Obj;
static UIAccessibilityReduceMotionStatusDidChangeNotification: Obj;
static UIAccessibilityDarkerSystemColorsStatusDidChangeNotification: Obj;
static UIKeyboardWillChangeFrameNotification: Obj;
static UIKeyboardWillHideNotification: Obj;
static UIKeyboardFrameEndUserInfoKey: Obj;
}
unsafe extern "C" {
static _dispatch_main_q: u8;
fn dispatch_async_f(queue: *const c_void, context: *mut c_void, work: extern "C" fn(*mut c_void));
fn dispatch_after_f(when: u64, queue: *const c_void, context: *mut c_void, work: extern "C" fn(*mut c_void));
fn dispatch_time(when: u64, delta: i64) -> u64;
fn exit(code: i32) -> !;
}
#[link(name = "objc")]
unsafe extern "C" {
fn objc_msgSendSuper();
}
const PENCIL: isize = 2;
const POINTER: isize = 3;
const BEGAN: isize = 1;
const CHANGED: isize = 2;
const SHIFT: isize = 1 << 17;
const CONTROL: isize = 1 << 18;
const OPTION: isize = 1 << 19;
const COMMAND: isize = 1 << 20;
const NOTCH: f32 = 48.0;
const REPEAT_AFTER: Duration = Duration::from_millis(500);
const REPEAT_EVERY: Duration = Duration::from_millis(40);
pub(crate) enum Heard {
Event(Event),
Resized,
Looks,
Keyboard(f64),
Background(bool),
Active(bool),
Ending,
Other(Box<dyn FnOnce(&mut Ui) -> bool>),
}
type Starting = (String, Box<dyn FnMut(&mut Ui)>);
#[derive(Default)]
struct Input {
fingers: Vec<(Obj, u32)>,
next_finger: u32,
mouse: Option<Obj>,
pointer_button: Option<Button>,
held: Mods,
keys: Vec<isize>,
passed: Vec<isize>,
repeating: Option<(Key, Mods, Instant)>,
}
thread_local! {
static HEARD: RefCell<Vec<Heard>> = const { RefCell::new(Vec::new()) };
static HOST: RefCell<Option<Host>> = const { RefCell::new(None) };
static STARTING: RefCell<Option<Starting>> = const { RefCell::new(None) };
static INPUT: RefCell<Input> = RefCell::new(Input::default());
static SCENE_WINDOW: Cell<Obj> = const { Cell::new(std::ptr::null_mut()) };
static QUEUED: Cell<bool> = const { Cell::new(false) };
static TIMER: Cell<(Option<Instant>, usize)> = const { Cell::new((None, 0)) };
static PASTED: RefCell<Option<String>> = const { RefCell::new(None) };
static VIEW: Cell<Obj> = const { Cell::new(std::ptr::null_mut()) };
static ORIGIN: Cell<NSPoint> = const { Cell::new(NSPoint { x: 0.0, y: 0.0 }) };
static DARK_PAGE: Cell<bool> = const { Cell::new(false) };
static CURSOR: Cell<Cursor> = const { Cell::new(Cursor::Arrow) };
}
static RUNNING: AtomicBool = AtomicBool::new(false);
static WOKEN: AtomicBool = AtomicBool::new(false);
pub(crate) fn heard(what: Heard) {
HEARD.with_borrow_mut(|heard| heard.push(what));
queue_turn();
}
pub(crate) fn origin() -> NSPoint {
ORIGIN.get()
}
fn main_queue() -> *const c_void {
(&raw const _dispatch_main_q).cast()
}
fn queue_turn() {
if !QUEUED.replace(true) {
unsafe { dispatch_async_f(main_queue(), std::ptr::null_mut(), queued) };
}
}
extern "C" fn queued(_: *mut c_void) {
QUEUED.set(false);
turn();
}
fn wake_at(at: Instant) {
let (due, number) = TIMER.get();
if due.is_some_and(|due| due <= at) {
return;
}
TIMER.set((Some(at), number + 1));
let wait = at.saturating_duration_since(Instant::now()).as_nanos().min(i64::MAX as u128) as i64;
unsafe { dispatch_after_f(dispatch_time(0, wait), main_queue(), (number + 1) as *mut c_void, timed) };
}
extern "C" fn timed(number: *mut c_void) {
let (_, latest) = TIMER.get();
if number as usize == latest {
TIMER.set((None, latest));
turn();
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Waker;
impl Waker {
pub fn wake(&self) {
if RUNNING.load(Ordering::SeqCst) && !WOKEN.swap(true, Ordering::SeqCst) {
unsafe { dispatch_async_f(main_queue(), std::ptr::null_mut(), woken) };
}
}
}
extern "C" fn woken(_: *mut c_void) {
WOKEN.store(false, Ordering::SeqCst);
heard(Heard::Other(Box::new(|_| true)));
}
fn delegate_class() -> Obj {
let notice = "v@:@";
let methods: [(&CStr, *const c_void, &str); 9] = [
(c"application:didFinishLaunchingWithOptions:", launched as *const c_void, "B@:@@"),
(c"application:configurationForConnectingSceneSession:options:", scene_configuration as *const c_void, "@@:@@@"),
(c"enteredBackground:", entered_background as *const c_void, notice),
(c"enteringForeground:", entering_foreground as *const c_void, notice),
(c"becameActive:", became_active as *const c_void, notice),
(c"resigningActive:", resigning_active as *const c_void, notice),
(c"terminating:", terminating as *const c_void, notice),
(c"looksChanged:", looks_changed as *const c_void, notice),
(c"keyboardMoved:", keyboard_moved as *const c_void, notice),
];
made_class(c"TautAppDelegate", c"UIResponder", &methods, &[c"UIApplicationDelegate"])
}
fn scene_class() -> Obj {
let methods: [(&CStr, *const c_void, &str); 3] = [
(c"scene:willConnectToSession:options:", scene_connected as *const c_void, "v@:@@@"),
(c"window", scene_window as *const c_void, "@@:"),
(c"setWindow:", set_scene_window as *const c_void, "v@:@"),
];
made_class(c"TautSceneDelegate", c"UIResponder", &methods, &[c"UIWindowSceneDelegate"])
}
extern "C" fn launched(delegate: Obj, _: Sel, _: Obj, _: Obj) -> Bool {
let _pool = Pool::new();
unsafe {
let centre: Obj = send(class(c"NSNotificationCenter"), c"defaultCenter", ());
let notices = [
(UIApplicationDidEnterBackgroundNotification, c"enteredBackground:"),
(UIApplicationWillEnterForegroundNotification, c"enteringForeground:"),
(UIApplicationDidBecomeActiveNotification, c"becameActive:"),
(UIApplicationWillResignActiveNotification, c"resigningActive:"),
(UIApplicationWillTerminateNotification, c"terminating:"),
(UIContentSizeCategoryDidChangeNotification, c"looksChanged:"),
(UIAccessibilityReduceMotionStatusDidChangeNotification, c"looksChanged:"),
(UIAccessibilityDarkerSystemColorsStatusDidChangeNotification, c"looksChanged:"),
(UIKeyboardWillChangeFrameNotification, c"keyboardMoved:"),
(UIKeyboardWillHideNotification, c"keyboardMoved:"),
];
for (name, action) in notices {
send::<()>(centre, c"addObserver:selector:name:object:", (delegate, sel(action), name, std::ptr::null_mut::<c_void>()));
}
let bundle: Obj = send(class(c"NSBundle"), c"mainBundle", ());
let scenes: Obj = send(bundle, c"objectForInfoDictionaryKey:", (ns_string("UIApplicationSceneManifest"),));
if scenes.is_null() {
let screen: Obj = send(class(c"UIScreen"), c"mainScreen", ());
let window: Obj = send(send::<Obj>(class(c"UIWindow"), c"alloc", ()), c"initWithFrame:", (send_rect(screen, c"bounds", ()),));
open(window);
}
}
1
}
extern "C" fn scene_configuration(_: Obj, _: Sel, _: Obj, session: Obj, _: Obj) -> Obj {
unsafe {
let role: Obj = send(session, c"role", ());
let made: Obj = send(class(c"UISceneConfiguration"), c"alloc", ());
let made: Obj = send(made, c"initWithName:sessionRole:", (std::ptr::null_mut::<c_void>(), role));
send::<()>(made, c"setDelegateClass:", (scene_class(),));
send(made, c"autorelease", ())
}
}
extern "C" fn scene_connected(_: Obj, _: Sel, scene: Obj, _: Obj, _: Obj) {
if !SCENE_WINDOW.get().is_null() {
return;
}
let window: Obj = unsafe { send(send::<Obj>(class(c"UIWindow"), c"alloc", ()), c"initWithWindowScene:", (scene,)) };
SCENE_WINDOW.set(window);
open(window);
}
extern "C" fn scene_window(_: Obj, _: Sel) -> Obj {
SCENE_WINDOW.get()
}
extern "C" fn set_scene_window(_: Obj, _: Sel, window: Obj) {
SCENE_WINDOW.set(window);
}
extern "C" fn entered_background(_: Obj, _: Sel, _: Obj) {
heard(Heard::Background(true));
turn();
}
extern "C" fn entering_foreground(_: Obj, _: Sel, _: Obj) {
heard(Heard::Background(false));
}
extern "C" fn became_active(_: Obj, _: Sel, _: Obj) {
heard(Heard::Active(true));
}
extern "C" fn resigning_active(_: Obj, _: Sel, _: Obj) {
heard(Heard::Active(false));
}
extern "C" fn terminating(_: Obj, _: Sel, _: Obj) {
heard(Heard::Ending);
turn();
}
extern "C" fn looks_changed(_: Obj, _: Sel, _: Obj) {
heard(Heard::Looks);
}
extern "C" fn keyboard_moved(_: Obj, _: Sel, notice: Obj) {
let view = VIEW.get();
let covered = unsafe {
let name: Obj = send(notice, c"name", ());
let hides = send::<Bool>(name, c"isEqualToString:", (UIKeyboardWillHideNotification,)) != 0;
let info: Obj = send(notice, c"userInfo", ());
let value: Obj = send(info, c"objectForKey:", (UIKeyboardFrameEndUserInfoKey,));
if hides || value.is_null() || view.is_null() {
0.0
} else {
let screen: Obj = send(send::<Obj>(class(c"UIScreen"), c"mainScreen", ()), c"coordinateSpace", ());
let frame = send_rect(view, c"convertRect:fromCoordinateSpace:", (send_rect(value, c"CGRectValue", ()), screen));
let bounds = send_rect(view, c"bounds", ());
(bounds.size.height - frame.origin.y).clamp(0.0, bounds.size.height)
}
};
heard(Heard::Keyboard(covered));
}
fn preferences(view: Obj) -> Preferences {
unsafe {
let traits: Obj = send(view, c"traitCollection", ());
let dark = send::<isize>(traits, c"userInterfaceStyle", ()) == 2;
let metrics: Obj = send(class(c"UIFontMetrics"), c"defaultMetrics", ());
let body = 17.0;
let scaled = if metrics.is_null() { body } else { send::<f64>(metrics, c"scaledValueForValue:compatibleWithTraitCollection:", (body, traits)) };
let contrast = UIAccessibilityDarkerSystemColorsEnabled();
let high_contrast = contrast.then_some(if dark { ContrastColors::DARK } else { ContrastColors::LIGHT });
let text_scale = (scaled / body).clamp(0.5, 4.0) as f32;
Preferences { dark, accent: None, high_contrast, reduced_motion: UIAccessibilityIsReduceMotionEnabled(), text_scale }
}
}
fn screens() -> Vec<Screen> {
unsafe {
let screen: Obj = send(class(c"UIScreen"), c"mainScreen", ());
let bounds = send_rect(screen, c"bounds", ());
let rect = Rect { x: 0.0, y: 0.0, w: bounds.size.width as f32, h: bounds.size.height as f32 };
vec![Screen { rect, work_area: rect, scale: send::<f64>(screen, c"scale", ()) as f32 }]
}
}
fn controller_class() -> Obj {
made_class(c"TautViewController", c"UIViewController", &[(c"preferredStatusBarStyle", status_bar_style as *const c_void, "q@:")], &[])
}
extern "C" fn status_bar_style(_: Obj, _: Sel) -> isize {
if DARK_PAGE.get() { 1 } else { 3 }
}
pub(crate) fn view_class() -> Obj {
let (touches, plain, yes) = ("v@:@@".to_string(), "v@:".to_string(), format!("{BOOL}@:"));
let mut methods: Vec<(&CStr, *const c_void, String)> = vec![
(c"touchesBegan:withEvent:", touches_began as *const c_void, touches.clone()),
(c"touchesMoved:withEvent:", touches_moved as *const c_void, touches.clone()),
(c"touchesEnded:withEvent:", touches_ended as *const c_void, touches.clone()),
(c"touchesCancelled:withEvent:", touches_cancelled as *const c_void, touches.clone()),
(c"pressesBegan:withEvent:", presses_began as *const c_void, touches.clone()),
(c"pressesEnded:withEvent:", presses_ended as *const c_void, touches.clone()),
(c"pressesCancelled:withEvent:", presses_ended as *const c_void, touches),
(c"layoutSubviews", laid_out as *const c_void, plain.clone()),
(c"safeAreaInsetsDidChange", insets_changed as *const c_void, plain),
(c"traitCollectionDidChange:", traits_changed as *const c_void, "v@:@".into()),
(c"canBecomeFirstResponder", yes_please as *const c_void, yes),
(c"hovered:", hovered as *const c_void, "v@:@".into()),
(c"scrolled:", scrolled as *const c_void, "v@:@".into()),
(c"pinched:", pinched as *const c_void, "v@:@".into()),
(c"pointerInteraction:regionForRequest:defaultRegion:", pointer_region as *const c_void, "@@:@@@".into()),
(c"pointerInteraction:styleForRegion:", pointer_style as *const c_void, "@@:@@".into()),
];
methods.extend(crate::ui_accessibility::view_methods());
let listed: Vec<(&CStr, *const c_void, &str)> = methods.iter().map(|(name, imp, types)| (*name, *imp, types.as_str())).collect();
made_class(c"TautView", c"UIView", &listed, &[c"UIPointerInteractionDelegate"])
}
extern "C" fn yes_please(_: Obj, _: Sel) -> Bool {
1
}
pub(crate) unsafe fn send_super<R>(to: Obj, of: &CStr, name: &CStr, args: impl Args) -> R {
#[repr(C)]
struct Super {
receiver: Obj,
class: Obj,
}
let asked = Super { receiver: to, class: class(of) };
unsafe { args.send(objc_msgSendSuper, (&raw const asked).cast_mut().cast(), sel(name)) }
}
extern "C" fn laid_out(view: Obj, _: Sel) {
unsafe { send_super::<()>(view, c"UIView", c"layoutSubviews", ()) };
heard(Heard::Resized);
turn();
}
extern "C" fn insets_changed(_: Obj, _: Sel) {
heard(Heard::Resized);
}
extern "C" fn traits_changed(_: Obj, _: Sel, _: Obj) {
heard(Heard::Looks);
heard(Heard::Resized);
}
fn place_of(view: Obj, touch: Obj) -> Point {
let at: NSPoint = unsafe { send(touch, c"locationInView:", (view,)) };
let origin = ORIGIN.get();
pt((at.x - origin.x) as f32, (at.y - origin.y) as f32)
}
fn mods_of(flags: isize) -> Mods {
Mods { ctrl: flags & (CONTROL | COMMAND) != 0, shift: flags & SHIFT != 0, alt: flags & OPTION != 0 }
}
fn touches_in(set: Obj) -> Vec<Obj> {
array_items(unsafe { send(set, c"allObjects", ()) })
}
extern "C" fn touches_began(view: Obj, _: Sel, set: Obj, event: Obj) {
touched(view, set, event, TouchPhase::Down);
}
extern "C" fn touches_moved(view: Obj, _: Sel, set: Obj, event: Obj) {
touched(view, set, event, TouchPhase::Move);
}
extern "C" fn touches_ended(view: Obj, _: Sel, set: Obj, event: Obj) {
touched(view, set, event, TouchPhase::Up);
}
extern "C" fn touches_cancelled(view: Obj, _: Sel, set: Obj, event: Obj) {
touched(view, set, event, TouchPhase::Cancel);
}
fn touched(view: Obj, set: Obj, event: Obj, phase: TouchPhase) {
for touch in touches_in(set) {
match unsafe { send::<isize>(touch, c"type", ()) } {
POINTER => pointed(view, touch, event, phase),
PENCIL => penned(view, touch, phase),
_ => fingered(view, touch, phase),
}
}
}
fn pointer_button(event: Obj) -> Button {
let mask = unsafe { send::<isize>(event, c"buttonMask", ()) };
if mask & 2 != 0 { Button::Right } else { Button::Left }
}
fn pointed(view: Obj, touch: Obj, event: Obj, phase: TouchPhase) {
let place = place_of(view, touch);
heard(Heard::Event(Event::Move(place)));
let held = INPUT.with_borrow(|input| input.held);
let pressed = INPUT.with_borrow_mut(|input| match phase {
TouchPhase::Down => Some(Event::Press(*input.pointer_button.insert(pointer_button(event)), held)),
TouchPhase::Move => None,
TouchPhase::Up | TouchPhase::Cancel => input.pointer_button.take().map(Event::Release),
});
pressed.into_iter().for_each(|event| heard(Heard::Event(event)));
}
#[cfg(feature = "touch")]
fn stylus_of(view: Obj, touch: Obj, touching: bool) -> Stylus {
let (force, most, altitude, azimuth) =
unsafe { (send::<f64>(touch, c"force", ()), send::<f64>(touch, c"maximumPossibleForce", ()), send::<f64>(touch, c"altitudeAngle", ()), send::<f64>(touch, c"azimuthAngleInView:", (view,))) };
let pressure = if !touching {
0.0
} else if most > 0.0 {
(force / most).clamp(0.0, 1.0) as f32
} else {
0.5
};
let lean = altitude.tan().max(1e-6);
let tilt = [(azimuth.cos() / lean).atan().to_degrees() as f32, (azimuth.sin() / lean).atan().to_degrees() as f32];
Stylus { pressure, tilt, twist: 0.0, barrel: false, eraser: false, touching }
}
fn penned(view: Obj, touch: Obj, phase: TouchPhase) {
#[cfg(feature = "touch")]
heard(Heard::Event(Event::Stylus(Some(stylus_of(view, touch, phase == TouchPhase::Down || phase == TouchPhase::Move)))));
as_mouse(place_of(view, touch), phase);
#[cfg(feature = "touch")]
if matches!(phase, TouchPhase::Up | TouchPhase::Cancel) {
heard(Heard::Event(Event::Stylus(None)));
}
}
fn fingered(view: Obj, touch: Obj, phase: TouchPhase) {
let place = place_of(view, touch);
let id = INPUT.with_borrow_mut(|input| finger_id(input, touch, phase));
if cfg!(feature = "touch") {
return heard(Heard::Event(Event::Touch(crate::touch::Touch { id, position: place, phase })));
}
let mouse = INPUT.with_borrow_mut(|input| {
input.mouse = input.mouse.or((phase == TouchPhase::Down).then_some(touch));
let mine = input.mouse == Some(touch);
input.mouse = input.mouse.filter(|_| matches!(phase, TouchPhase::Down | TouchPhase::Move));
mine
});
if mouse {
as_mouse(place, phase);
}
}
fn finger_id(input: &mut Input, touch: Obj, phase: TouchPhase) -> u32 {
let known = input.fingers.iter().position(|(of, _)| *of == touch);
let id = match known {
Some(at) => input.fingers[at].1,
None => {
input.next_finger = input.next_finger.wrapping_add(1);
input.fingers.push((touch, input.next_finger));
input.next_finger
}
};
if matches!(phase, TouchPhase::Up | TouchPhase::Cancel) {
input.fingers.retain(|(of, _)| *of != touch);
}
id
}
fn as_mouse(place: Point, phase: TouchPhase) {
let held = INPUT.with_borrow(|input| input.held);
let events = match phase {
TouchPhase::Down => [Some(Event::Move(place)), Some(Event::Press(Button::Left, held))],
TouchPhase::Move => [Some(Event::Move(place)), None],
TouchPhase::Up | TouchPhase::Cancel => [Some(Event::Release(Button::Left)), Some(Event::Leave)],
};
events.into_iter().flatten().for_each(|event| heard(Heard::Event(event)));
}
fn state_of(gesture: Obj) -> isize {
unsafe { send(gesture, c"state", ()) }
}
extern "C" fn hovered(view: Obj, _: Sel, gesture: Obj) {
let event = if matches!(state_of(gesture), BEGAN | CHANGED) { Event::Move(place_of(view, gesture)) } else { Event::Leave };
heard(Heard::Event(event));
}
extern "C" fn scrolled(view: Obj, _: Sel, gesture: Obj) {
if !matches!(state_of(gesture), BEGAN | CHANGED) {
return;
}
let by: NSPoint = unsafe { send(gesture, c"translationInView:", (view,)) };
unsafe { send::<()>(gesture, c"setTranslation:inView:", (NSPoint::default(), view)) };
heard(Heard::Event(Event::Move(place_of(view, gesture))));
let (right, down) = (-by.x as f32, -by.y as f32);
let zoom = INPUT.with_borrow(|input| input.held.ctrl) && down != 0.0;
heard(Heard::Event(if zoom { Event::Zoom(crate::touch::wheel_zoom(-down / NOTCH)) } else { Event::Wheel(right, down) }));
}
extern "C" fn pinched(view: Obj, _: Sel, gesture: Obj) {
if !matches!(state_of(gesture), BEGAN | CHANGED) {
return;
}
let by = unsafe { send::<f64>(gesture, c"scale", ()) } as f32;
unsafe { send::<()>(gesture, c"setScale:", (1.0f64,)) };
heard(Heard::Event(Event::Move(place_of(view, gesture))));
heard(Heard::Event(Event::Zoom(by.max(0.1))));
}
extern "C" fn pointer_region(_: Obj, _: Sel, _: Obj, _: Obj, region: Obj) -> Obj {
region
}
extern "C" fn pointer_style(_: Obj, _: Sel, _: Obj, _: Obj) -> Obj {
if CURSOR.get() != Cursor::Text {
return std::ptr::null_mut();
}
unsafe {
let shape: Obj = send(class(c"UIPointerShape"), c"beamWithPreferredLength:axis:", (20.0f64, 2usize));
send(class(c"UIPointerStyle"), c"styleWithShape:constrainedAxes:", (shape, 0usize))
}
}
fn key_of(code: isize, letters: Obj) -> Option<Key> {
let named = match code {
0x28 | 0x58 => Key::Enter,
0x29 => Key::Escape,
0x2b => Key::Tab,
0x2a => Key::Backspace,
0x4c => Key::Delete,
0x50 => Key::Left,
0x4f => Key::Right,
0x52 => Key::Up,
0x51 => Key::Down,
0x4a => Key::Home,
0x4d => Key::End,
0x4b => Key::PageUp,
0x4e => Key::PageDown,
0x2c => Key::Space,
0x65 => Key::Menu,
0x3a..=0x45 => Key::F((code - 0x3a + 1) as u8),
_ => return letter_of(letters),
};
Some(named)
}
fn letter_of(letters: Obj) -> Option<Key> {
let letter = rust_string(letters)?.chars().next()?.to_lowercase().next()?;
(!letter.is_control() && !('\u{f700}'..='\u{f8ff}').contains(&letter)).then_some(Key::Char(letter))
}
fn modifier(code: isize) -> Option<fn(&mut Mods) -> &mut bool> {
match code {
0xe0 | 0xe3 | 0xe4 | 0xe7 => Some(|mods| &mut mods.ctrl),
0xe1 | 0xe5 => Some(|mods| &mut mods.shift),
0xe2 | 0xe6 => Some(|mods| &mut mods.alt),
_ => None,
}
}
fn repeats(key: Key) -> bool {
matches!(key, Key::Backspace | Key::Delete | Key::Left | Key::Right | Key::Up | Key::Down | Key::PageUp | Key::PageDown | Key::Enter | Key::Tab)
}
fn press_of(press: Obj) -> Option<(isize, isize, Obj)> {
unsafe {
let key: Obj = send(press, c"key", ());
(!key.is_null()).then(|| (send::<isize>(key, c"keyCode", ()), send::<isize>(key, c"modifierFlags", ()), send::<Obj>(key, c"charactersIgnoringModifiers", ())))
}
}
pub(crate) extern "C" fn presses_began(view: Obj, _: Sel, presses: Obj, event: Obj) {
let mut rest = Vec::new();
for press in touches_in(presses) {
let Some((code, flags, letters)) = press_of(press) else {
rest.push(press);
continue;
};
if pressed(code, flags, letters) {
INPUT.with_borrow_mut(|input| input.passed.push(code));
rest.push(press);
}
}
pass_on(view, c"pressesBegan:withEvent:", &rest, event);
}
fn pressed(code: isize, flags: isize, letters: Obj) -> bool {
if let Some(bit) = modifier(code) {
let held = INPUT.with_borrow_mut(|input| {
*bit(&mut input.held) = true;
input.held
});
heard(Heard::Event(Event::ModifiersChanged(held)));
return false;
}
let held = mods_of(flags);
let Some(key) = key_of(code, letters) else { return true };
INPUT.with_borrow_mut(|input| {
input.keys.push(code);
input.repeating = repeats(key).then(|| (key, held, Instant::now() + REPEAT_AFTER));
});
heard(Heard::Event(Event::Key(key, held)));
if repeats(key) {
wake_at(Instant::now() + REPEAT_AFTER);
}
!repeats(key) && !held.ctrl
}
pub(crate) extern "C" fn presses_ended(view: Obj, name: Sel, presses: Obj, event: Obj) {
let mut rest = Vec::new();
for press in touches_in(presses) {
let Some((code, _, letters)) = press_of(press) else {
rest.push(press);
continue;
};
released(code, letters);
let passed = INPUT.with_borrow_mut(|input| input.passed.iter().position(|of| *of == code).map(|at| input.passed.remove(at)));
if passed.is_some() {
rest.push(press);
}
}
let ended = std::ptr::eq(name, sel(c"pressesEnded:withEvent:"));
pass_on(view, if ended { c"pressesEnded:withEvent:" } else { c"pressesCancelled:withEvent:" }, &rest, event);
}
fn released(code: isize, letters: Obj) {
if let Some(bit) = modifier(code) {
let held = INPUT.with_borrow_mut(|input| {
*bit(&mut input.held) = false;
input.held
});
return heard(Heard::Event(Event::ModifiersChanged(held)));
}
INPUT.with_borrow_mut(|input| {
input.keys.retain(|held| *held != code);
input.repeating = input.repeating.filter(|_| !input.keys.is_empty());
});
if let Some(key) = key_of(code, letters) {
heard(Heard::Event(Event::KeyUp(key)));
}
}
fn pass_on(view: Obj, name: &CStr, presses: &[Obj], event: Obj) {
if presses.is_empty() {
return;
}
unsafe {
let set: Obj = send(class(c"NSSet"), c"setWithArray:", (ns_array(presses),));
send_super::<()>(view, c"UIView", name, (set, event));
}
}
pub(crate) fn key_held(key: Key) -> bool {
INPUT.with_borrow(|input| input.repeating.is_some_and(|(held, ..)| held == key) || input.keys.iter().any(|code| key_of(*code, std::ptr::null_mut()) == Some(key)))
}
fn repeat_keys() {
let due = INPUT.with_borrow_mut(|input| {
let (key, held, at) = input.repeating?;
let now = Instant::now();
if at > now {
return Some((None, at));
}
input.repeating = Some((key, held, now + REPEAT_EVERY));
Some((Some(Event::Key(key, held)), now + REPEAT_EVERY))
});
let Some((event, next)) = due else { return };
if let Some(event) = event {
HEARD.with_borrow_mut(|heard| heard.push(Heard::Event(event)));
}
wake_at(next);
}
struct Host {
app: Box<dyn FnMut(&mut Ui)>,
ui: Ui,
window: Obj,
view: Obj,
controller: Obj,
page: Obj,
area: NSRect,
keyboard: f64,
scale: f32,
surface: Surface,
background: Color,
pointer: Obj,
rerun: bool,
start: Instant,
title: String,
}
fn open(window: Obj) {
let Some((title, app)) = STARTING.with_borrow_mut(Option::take) else { return };
let Some(text) = SystemText::new() else {
return eprintln!("taut: CoreText has no system font.");
};
let (view, controller, page) = unsafe {
let bounds = send_rect(window, c"bounds", ());
let view: Obj = send(send::<Obj>(view_class(), c"alloc", ()), c"initWithFrame:", (bounds,));
send::<()>(view, c"setMultipleTouchEnabled:", (1 as Bool,));
let controller: Obj = send(send::<Obj>(controller_class(), c"alloc", ()), c"init", ());
send::<()>(controller, c"setView:", (view,));
send::<()>(view, c"release", ());
send::<()>(window, c"setRootViewController:", (controller,));
send::<()>(controller, c"release", ());
let page: Obj = send(class(c"CALayer"), c"layer", ());
send::<()>(page, c"setContentsGravity:", (kCAGravityTopLeft,));
send::<()>(page, c"setOpaque:", (1 as Bool,));
send::<()>(send::<Obj>(view, c"layer", ()), c"addSublayer:", (page,));
send::<()>(window, c"makeKeyAndVisible", ());
(view, controller, page)
};
let pointer = listen_to_pointer(view);
crate::ios_text_input::open(view);
unsafe { send::<Bool>(view, c"becomeFirstResponder", ()) };
let mut ui = Ui::new(Box::new(text), Box::new(SystemClipboard));
ui.set_preferences(preferences(view));
ui.set_screens(screens());
#[rustfmt::skip]
let host = Host {
app, ui, window, view, controller, page, area: NSRect::default(), keyboard: 0.0, scale: 1.0, surface: Surface::default(),
background: Color::NONE, pointer, rerun: true, start: Instant::now(), title,
};
VIEW.set(view);
HOST.set(Some(host));
RUNNING.store(true, Ordering::SeqCst);
crate::ui_accessibility::listen_if_running(view);
heard(Heard::Resized);
turn();
}
fn listen_to_pointer(view: Obj) -> Obj {
unsafe {
let made = |name: &CStr, action: &CStr| -> Obj {
let gesture: Obj = send(send::<Obj>(class(name), c"alloc", ()), c"initWithTarget:action:", (view, sel(action)));
send::<()>(gesture, c"setCancelsTouchesInView:", (0 as Bool,));
send::<()>(view, c"addGestureRecognizer:", (gesture,));
send::<()>(gesture, c"release", ());
gesture
};
made(c"UIHoverGestureRecognizer", c"hovered:");
let scrolling = made(c"UIPanGestureRecognizer", c"scrolled:");
send::<()>(scrolling, c"setAllowedScrollTypesMask:", (3isize,));
send::<()>(scrolling, c"setMaximumNumberOfTouches:", (0usize,));
let pinching = made(c"UIPinchGestureRecognizer", c"pinched:");
let pointer_only: Obj = send(class(c"NSNumber"), c"numberWithInteger:", (POINTER,));
send::<()>(pinching, c"setAllowedTouchTypes:", (ns_array(&[pointer_only]),));
if class(c"UIPointerInteraction").is_null() {
return std::ptr::null_mut();
}
let interaction: Obj = send(send::<Obj>(class(c"UIPointerInteraction"), c"alloc", ()), c"initWithDelegate:", (view,));
send::<()>(view, c"addInteraction:", (interaction,));
send::<()>(interaction, c"release", ());
interaction
}
}
impl Host {
fn measure(&mut self) -> bool {
let (bounds, insets, scale) = unsafe {
let traits: Obj = send(self.view, c"traitCollection", ());
(send_rect(self.view, c"bounds", ()), send::<Insets>(self.view, c"safeAreaInsets", ()), send::<f64>(traits, c"displayScale", ()))
};
let bottom = insets.bottom.max(self.keyboard);
let width = (bounds.size.width - insets.left - insets.right).max(1.0);
let area = NSRect::new(insets.left, insets.top, width, (bounds.size.height - insets.top - bottom).max(1.0));
let scale = if scale > 0.0 { scale as f32 } else { self.scale };
let changed = (area, scale) != (self.area, self.scale);
(self.area, self.scale) = (area, scale);
ORIGIN.set(area.origin);
changed
}
fn take(&mut self, what: Heard) {
match what {
Heard::Event(event) => self.rerun |= self.ui.event(event),
Heard::Resized => self.rerun |= self.measure(),
Heard::Looks => self.rerun |= self.ui.set_preferences(preferences(self.view)) | self.ui.set_screens(screens()),
Heard::Keyboard(covered) => {
self.keyboard = covered;
self.rerun |= self.measure();
}
Heard::Background(away) => self.rerun |= self.ui.event(Event::Minimized(away)),
Heard::Active(on) => self.rerun |= self.ui.event(Event::Focused(on)),
Heard::Ending => {
self.ui.request_close();
self.rerun = true;
}
Heard::Other(work) => self.rerun |= work(&mut self.ui),
}
}
fn describe(&mut self) {
self.ui.resize(Size { w: self.area.size.width as f32, h: self.area.size.height as f32 }, self.scale);
self.ui.run(&mut self.app);
self.rerun = false;
if self.ui.take_closing() == Some(Ok(())) || self.ui.quitting() {
unsafe { exit(0) }
}
self.follow();
crate::ios_text_input::follow(self.view, &mut self.ui);
if self.ui.listening {
crate::ui_accessibility::keep(self.view, (self.area.origin.x, self.area.origin.y), &self.ui);
}
}
fn follow(&mut self) {
if let Some(title) = self.ui.take_title() {
unsafe { send::<()>(send::<Obj>(self.window, c"windowScene", ()), c"setTitle:", (ns_string(&title),)) };
self.title = title;
}
let cursor = self.ui.cursor();
if CURSOR.replace(cursor) != cursor && !self.pointer.is_null() {
unsafe { send::<()>(self.pointer, c"invalidate", ()) };
}
let background = self.ui.theme.bg.solid();
if std::mem::replace(&mut self.background, background) != background {
self.paint_background(background);
}
}
fn paint_background(&mut self, background: Color) {
let channel = |shift: u32| f64::from((background.0 >> shift) & 0xff) / 255.0;
let (red, green, blue) = (channel(16), channel(8), channel(0));
DARK_PAGE.set(0.2126 * red + 0.7152 * green + 0.0722 * blue < 0.5);
unsafe {
let color: Obj = send(class(c"UIColor"), c"colorWithRed:green:blue:alpha:", (red, green, blue, 1.0f64));
send::<()>(self.view, c"setBackgroundColor:", (color,));
send::<()>(self.controller, c"setNeedsStatusBarAppearanceUpdate", ());
}
}
fn draw(&mut self) {
let changed = self.surface.update(&mut self.ui);
self.ui.changed();
if !changed.is_empty() {
self.present();
}
}
fn present(&self) {
let (width, height) = (self.surface.width, self.surface.height);
if width == 0 || height == 0 {
return;
}
unsafe {
let bytes = CFDataCreate(std::ptr::null(), self.surface.pixels.as_ptr().cast(), (width * height * 4) as isize);
let provider = CGDataProviderCreateWithCFData(bytes);
let space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
let picture = CGImageCreate(width, height, 8, 32, width * 4, space, SOLID, provider, std::ptr::null(), false, 0);
send::<()>(class(c"CATransaction"), c"begin", ());
send::<()>(class(c"CATransaction"), c"setDisableActions:", (1 as Bool,));
send::<()>(self.page, c"setFrame:", (self.area,));
send::<()>(self.page, c"setContentsScale:", (f64::from(self.scale),));
send::<()>(self.page, c"setContents:", (picture,));
send::<()>(class(c"CATransaction"), c"commit", ());
CGImageRelease(picture);
CGColorSpaceRelease(space);
CGDataProviderRelease(provider);
CFRelease(bytes);
}
}
fn turn(&mut self) {
self.ui.set_time(self.start.elapsed());
self.rerun |= self.ui.wake_in() == Some(Duration::ZERO);
for what in HEARD.with_borrow_mut(std::mem::take) {
self.take(what);
}
self.rerun |= crate::ui_accessibility::listen(&mut self.ui);
if self.rerun {
self.describe();
}
self.draw();
if let Some(wait) = self.ui.wake_in() {
wake_at(Instant::now() + wait);
}
}
}
fn turn() {
repeat_keys();
let _pool = Pool::new();
HOST.with(|host| {
let Ok(mut host) = host.try_borrow_mut() else { return queue_turn() };
if let Some(host) = host.as_mut() {
host.turn();
}
});
}
pub fn run(window: Window, app: impl FnMut(&mut Ui) + 'static) {
let _pool = Pool::new();
if unsafe { send::<Bool>(class(c"NSThread"), c"isMainThread", ()) } == 0 {
return eprintln!("taut: iOS shows windows only from the program's main thread.");
}
STARTING.set(Some((window.title.to_string(), Box::new(app))));
let delegate = delegate_class();
let arguments: Vec<*mut c_char> = std::env::args().filter_map(|argument| std::ffi::CString::new(argument).ok()).map(std::ffi::CString::into_raw).collect();
let arguments = Box::leak(arguments.into_boxed_slice());
unsafe {
let name: Obj = send(delegate, c"description", ());
UIApplicationMain(arguments.len() as i32, arguments.as_mut_ptr(), std::ptr::null_mut(), name);
}
}
pub(crate) fn open_link(link: &str) -> bool {
let link = Box::into_raw(Box::new(link.to_string()));
unsafe { dispatch_async_f(main_queue(), link.cast(), open_now) };
true
}
extern "C" fn open_now(link: *mut c_void) {
let link = unsafe { Box::from_raw(link.cast::<String>()) };
let _pool = Pool::new();
unsafe {
let url: Obj = send(class(c"NSURL"), c"URLWithString:", (ns_string(&link),));
let app: Obj = send(class(c"UIApplication"), c"sharedApplication", ());
if !url.is_null() {
let options: Obj = send(class(c"NSDictionary"), c"dictionary", ());
send::<()>(app, c"openURL:options:completionHandler:", (url, options, std::ptr::null_mut::<c_void>()));
}
}
}
struct SystemClipboard;
fn pasteboard() -> Obj {
unsafe { send(class(c"UIPasteboard"), c"generalPasteboard", ()) }
}
pub(crate) fn paste_now() {
let _pool = Pool::new();
let text = rust_string(unsafe { send(pasteboard(), c"string", ()) });
PASTED.set(text);
}
impl Clipboard for SystemClipboard {
fn get(&mut self) -> Option<String> {
if let Some(text) = PASTED.take() {
return Some(text);
}
let _pool = Pool::new();
rust_string(unsafe { send(pasteboard(), c"string", ()) })
}
fn set(&mut self, text: &str) {
let _pool = Pool::new();
unsafe { send::<()>(pasteboard(), c"setString:", (ns_string(text),)) };
}
fn picture(&mut self) -> Option<(usize, Vec<u32>)> {
(PICTURES.get()?.picture)(self)
}
fn set_picture(&mut self, width: usize, pixels: &[u32]) {
PICTURES.get().map_or((), |its| (its.set_picture)(self, width, pixels))
}
fn files(&mut self) -> Vec<std::path::PathBuf> {
PICTURES.get().map_or(Vec::new(), |its| (its.files)(self))
}
fn set_files(&mut self, files: &[std::path::PathBuf]) {
PICTURES.get().map_or((), |its| (its.set_files)(self, files))
}
}
thread_local! {
static PICTURES: Cell<Option<PicturesAndFiles<SystemClipboard>>> = const { Cell::new(None) };
}
pub(crate) fn hand_pictures_and_files() {
let (picture, set_picture) = (SystemClipboard::picture_on, SystemClipboard::put_picture);
PICTURES.set(Some(PicturesAndFiles { picture, set_picture, files: |_| Vec::new(), set_files: |_, _| {} }));
}
impl SystemClipboard {
fn picture_on(&mut self) -> Option<(usize, Vec<u32>)> {
let _pool = Pool::new();
let png = unsafe { UIImagePNGRepresentation(send(pasteboard(), c"image", ())) };
crate::png::decode(&bytes_of(png))
}
fn put_picture(&mut self, width: usize, pixels: &[u32]) {
let Some(png) = crate::png::encode_rgba(width, pixels) else { return };
let _pool = Pool::new();
unsafe { send::<()>(pasteboard(), c"setData:forPasteboardType:", (ns_data(&png), ns_string("public.png"))) };
}
}