use crate::event::{Event, Key, Mods};
use crate::geom::Rect;
use crate::ios::{Heard, heard};
use crate::macos_sys::*;
use crate::ui::Ui;
use std::cell::{Cell, RefCell};
use std::ffi::{CStr, c_void};
#[link(name = "objc")]
unsafe extern "C" {
fn class_createInstance(class: Obj, extra: usize) -> Obj;
fn object_getIndexedIvars(object: Obj) -> *mut c_void;
}
#[link(name = "UIKit", kind = "framework")]
unsafe extern "C" {
static NSUnderlineStyleAttributeName: Obj;
static NSBackgroundColorAttributeName: Obj;
}
const LEFT: isize = 3;
const UP: isize = 4;
const BACKWARD: isize = 1;
const SINGLE: isize = 1;
const THICK: isize = 2;
#[derive(Default)]
struct Composing {
marked: Vec<u16>,
picked: NSRange,
editing: bool,
secret: bool,
cursor: Option<Rect>,
delegate: Obj,
tokenizer: Obj,
style: Obj,
label: Obj,
}
thread_local! {
static INPUT: Cell<Obj> = const { Cell::new(std::ptr::null_mut()) };
static COMPOSING: RefCell<Composing> = RefCell::new(Composing::default());
}
const OBJECT: &str = "@@:";
const NUMBER: &str = "q@:";
fn input_class() -> Obj {
let (yes, rect) = (format!("{BOOL}@:"), format!("{RECT}@:@"));
let methods: Vec<(&CStr, *const c_void, String)> = vec![
(c"canBecomeFirstResponder", yes_please as *const c_void, yes.clone()),
(c"hasText", yes_please as *const c_void, yes),
(c"insertText:", inserted as *const c_void, "v@:@".into()),
(c"deleteBackward", deleted as *const c_void, "v@:".into()),
(c"textInRange:", text_in as *const c_void, "@@:@".into()),
(c"replaceRange:withText:", replaced as *const c_void, "v@:@@".into()),
(c"selectedTextRange", selected_range as *const c_void, OBJECT.into()),
(c"setSelectedTextRange:", ignored as *const c_void, "v@:@".into()),
(c"markedTextRange", marked_range as *const c_void, OBJECT.into()),
(c"markedTextStyle", style as *const c_void, OBJECT.into()),
(c"setMarkedTextStyle:", set_style as *const c_void, "v@:@".into()),
(c"setMarkedText:selectedRange:", marked as *const c_void, format!("v@:@{RANGE}")),
(c"unmarkText", unmarked as *const c_void, "v@:".into()),
(c"beginningOfDocument", beginning as *const c_void, OBJECT.into()),
(c"endOfDocument", end as *const c_void, OBJECT.into()),
(c"textRangeFromPosition:toPosition:", range_between as *const c_void, "@@:@@".into()),
(c"positionFromPosition:offset:", moved as *const c_void, "@@:@q".into()),
(c"positionFromPosition:inDirection:offset:", moved_toward as *const c_void, "@@:@qq".into()),
(c"comparePosition:toPosition:", compared as *const c_void, "q@:@@".into()),
(c"offsetFromPosition:toPosition:", offset_between as *const c_void, "q@:@@".into()),
(c"inputDelegate", delegate as *const c_void, OBJECT.into()),
(c"setInputDelegate:", set_delegate as *const c_void, "v@:@".into()),
(c"tokenizer", tokenizer as *const c_void, OBJECT.into()),
(c"positionWithinRange:farthestInDirection:", farthest as *const c_void, "@@:@q".into()),
(c"characterRangeByExtendingPosition:inDirection:", extended as *const c_void, "@@:@q".into()),
(c"baseWritingDirectionForPosition:inDirection:", left_to_right as *const c_void, "q@:@q".into()),
(c"setBaseWritingDirection:forRange:", ignored_direction as *const c_void, "v@:q@".into()),
(c"firstRectForRange:", first_rect as *const c_void, rect.clone()),
(c"caretRectForPosition:", caret_rect as *const c_void, rect),
(c"selectionRectsForRange:", no_rects as *const c_void, "@@:@".into()),
(c"closestPositionToPoint:", closest as *const c_void, format!("@@:{POINT}")),
(c"closestPositionToPoint:withinRange:", closest_within as *const c_void, format!("@@:{POINT}@")),
(c"characterRangeAtPoint:", no_range as *const c_void, format!("@@:{POINT}")),
(c"autocorrectionType", no_trait as *const c_void, NUMBER.into()),
(c"spellCheckingType", no_trait as *const c_void, NUMBER.into()),
(c"smartQuotesType", no_trait as *const c_void, NUMBER.into()),
(c"smartDashesType", no_trait as *const c_void, NUMBER.into()),
(c"smartInsertDeleteType", no_trait as *const c_void, NUMBER.into()),
(c"autocapitalizationType", none_trait as *const c_void, NUMBER.into()),
(c"isSecureTextEntry", secret as *const c_void, format!("{BOOL}@:")),
(c"copy:", copied as *const c_void, "v@:@".into()),
(c"cut:", cut as *const c_void, "v@:@".into()),
(c"paste:", pasted as *const c_void, "v@:@".into()),
(c"selectAll:", all_selected as *const c_void, "v@:@".into()),
(c"canPerformAction:withSender:", can_perform as *const c_void, format!("{BOOL}@::@")),
(c"pressesBegan:withEvent:", crate::ios::presses_began as *const c_void, "v@:@@".into()),
(c"pressesEnded:withEvent:", crate::ios::presses_ended as *const c_void, "v@:@@".into()),
(c"pressesCancelled:withEvent:", crate::ios::presses_ended as *const c_void, "v@:@@".into()),
];
let listed: Vec<(&CStr, *const c_void, &str)> = methods.iter().map(|(name, imp, types)| (*name, *imp, types.as_str())).collect();
made_class(c"TautTextInput", c"UIView", &listed, &[c"UITextInput", c"UIKeyInput", c"UITextInputTraits"])
}
fn position_class() -> Obj {
made_class(c"TautTextPosition", c"UITextPosition", &[], &[])
}
fn range_class() -> Obj {
let methods: [(&CStr, *const c_void, &str); 3] =
[(c"start", range_start as *const c_void, OBJECT), (c"end", range_end as *const c_void, OBJECT), (c"isEmpty", range_empty as *const c_void, "B@:")];
made_class(c"TautTextRange", c"UITextRange", &methods, &[])
}
pub(crate) fn open(view: Obj) {
unsafe {
let input: Obj = send(send::<Obj>(input_class(), c"alloc", ()), c"initWithFrame:", (NSRect::new(0.0, 0.0, 1.0, 1.0),));
send::<()>(input, c"setUserInteractionEnabled:", (0 as Bool,));
send::<()>(input, c"setBackgroundColor:", (send::<Obj>(class(c"UIColor"), c"clearColor", ()),));
send::<()>(view, c"addSubview:", (input,));
let tokenizer: Obj = send(send::<Obj>(class(c"UITextInputStringTokenizer"), c"alloc", ()), c"initWithTextInput:", (input,));
COMPOSING.with_borrow_mut(|composing| composing.tokenizer = tokenizer);
INPUT.set(input);
}
}
pub(crate) fn follow(view: Obj, ui: &mut Ui) {
let input = INPUT.get();
let origin = crate::ios::origin();
let cursor = ui.ime_area().map(|at| Rect { x: at.x + origin.x as f32, y: at.y + origin.y as f32, ..at });
let secret = ui.password_focused();
let (was_editing, was_secret, was_at) = COMPOSING.with_borrow(|composing| (composing.editing, composing.secret, composing.cursor));
let editing = cursor.is_some();
COMPOSING.with_borrow_mut(|composing| (composing.editing, composing.secret, composing.cursor) = (editing, secret, cursor));
if let Some(at) = cursor {
unsafe { send::<()>(input, c"setFrame:", (NSRect::new(f64::from(at.x), f64::from(at.y), 1.0, f64::from(at.h.max(1.0))),)) };
}
if editing == was_editing && secret == was_secret {
if cursor != was_at {
moved_cursor();
}
return show_marked();
}
drop_marked();
unsafe {
if editing {
send::<Bool>(input, c"resignFirstResponder", ());
send::<Bool>(input, c"becomeFirstResponder", ());
} else {
send::<Bool>(view, c"becomeFirstResponder", ());
}
}
}
fn moved_cursor() {
let delegate = COMPOSING.with_borrow(|composing| composing.delegate);
unsafe {
send::<()>(delegate, c"selectionWillChange:", (INPUT.get(),));
send::<()>(delegate, c"selectionDidChange:", (INPUT.get(),));
}
}
fn drop_marked() {
let delegate = COMPOSING.with_borrow_mut(|composing| {
composing.marked.clear();
composing.delegate
});
hide_marked();
unsafe {
send::<()>(delegate, c"textWillChange:", (INPUT.get(),));
send::<()>(delegate, c"textDidChange:", (INPUT.get(),));
}
}
extern "C" fn yes_please(_: Obj, _: Sel) -> Bool {
1
}
extern "C" fn ignored(_: Obj, _: Sel, _: Obj) {}
extern "C" fn ignored_direction(_: Obj, _: Sel, _: isize, _: Obj) {}
fn position(offset: usize) -> Obj {
unsafe {
let made = class_createInstance(position_class(), size_of::<usize>());
object_getIndexedIvars(made).cast::<usize>().write(offset);
send(made, c"autorelease", ())
}
}
fn range(from: usize, to: usize) -> Obj {
unsafe {
let made = class_createInstance(range_class(), 2 * size_of::<usize>());
object_getIndexedIvars(made).cast::<[usize; 2]>().write([from.min(to), from.max(to)]);
send(made, c"autorelease", ())
}
}
fn is_of(object: Obj, made: Obj) -> bool {
unsafe { send::<Bool>(object, c"isKindOfClass:", (made,)) != 0 }
}
fn offset_of(position: Obj) -> usize {
if is_of(position, position_class()) { unsafe { object_getIndexedIvars(position).cast::<usize>().read() } } else { 0 }
}
fn ends_of(range: Obj) -> [usize; 2] {
if is_of(range, range_class()) { unsafe { object_getIndexedIvars(range).cast::<[usize; 2]>().read() } } else { [0, 0] }
}
extern "C" fn range_start(range: Obj, _: Sel) -> Obj {
position(ends_of(range)[0])
}
extern "C" fn range_end(range: Obj, _: Sel) -> Obj {
position(ends_of(range)[1])
}
extern "C" fn range_empty(range: Obj, _: Sel) -> Bool {
let [from, to] = ends_of(range);
Bool::from(from == to)
}
fn length() -> usize {
COMPOSING.with_borrow(|composing| composing.marked.len())
}
extern "C" fn beginning(_: Obj, _: Sel) -> Obj {
position(0)
}
extern "C" fn end(_: Obj, _: Sel) -> Obj {
position(length())
}
extern "C" fn range_between(_: Obj, _: Sel, from: Obj, to: Obj) -> Obj {
range(offset_of(from), offset_of(to))
}
extern "C" fn moved(_: Obj, _: Sel, from: Obj, by: isize) -> Obj {
let to = offset_of(from) as isize + by;
if (0..=length() as isize).contains(&to) { position(to as usize) } else { std::ptr::null_mut() }
}
extern "C" fn moved_toward(input: Obj, name: Sel, from: Obj, direction: isize, by: isize) -> Obj {
let back = matches!(direction, LEFT | UP | BACKWARD);
moved(input, name, from, if back { -by } else { by })
}
extern "C" fn compared(_: Obj, _: Sel, one: Obj, other: Obj) -> isize {
offset_of(one).cmp(&offset_of(other)) as isize
}
extern "C" fn offset_between(_: Obj, _: Sel, from: Obj, to: Obj) -> isize {
offset_of(to) as isize - offset_of(from) as isize
}
extern "C" fn farthest(_: Obj, _: Sel, within: Obj, direction: isize) -> Obj {
let [from, to] = ends_of(within);
position(if matches!(direction, LEFT | UP) { from } else { to })
}
extern "C" fn extended(_: Obj, _: Sel, from: Obj, direction: isize) -> Obj {
let at = offset_of(from);
if matches!(direction, LEFT | UP) { range(at.saturating_sub(1), at) } else { range(at, (at + 1).min(length())) }
}
extern "C" fn left_to_right(_: Obj, _: Sel, _: Obj, _: isize) -> isize {
0
}
fn piece(from: usize, to: usize) -> String {
COMPOSING.with_borrow(|composing| {
let marked = &composing.marked;
String::from_utf16_lossy(&marked[from.min(marked.len())..to.min(marked.len())])
})
}
extern "C" fn text_in(_: Obj, _: Sel, within: Obj) -> Obj {
let [from, to] = ends_of(within);
ns_string(&piece(from, to))
}
fn text_of(string: Obj) -> String {
let attributed = unsafe { send::<Bool>(string, c"isKindOfClass:", (class(c"NSAttributedString"),)) } != 0;
let plain = if attributed { unsafe { send(string, c"string", ()) } } else { string };
rust_string(plain).unwrap_or_default()
}
fn typed(text: String) {
COMPOSING.with_borrow_mut(|composing| composing.marked.clear());
hide_marked();
let key = match text.as_str() {
"\n" | "\r" => Some(Key::Enter),
"\t" => Some(Key::Tab),
_ => None,
};
match key {
Some(key) if crate::ios::key_held(key) => {}
Some(key) => heard(Heard::Event(Event::Key(key, Mods::NONE))),
None if !text.is_empty() => heard(Heard::Event(Event::Text(text))),
None => {}
}
}
extern "C" fn inserted(_: Obj, _: Sel, text: Obj) {
typed(text_of(text));
}
extern "C" fn deleted(_: Obj, _: Sel) {
if length() > 0 {
return drop_marked();
}
if !crate::ios::key_held(Key::Backspace) {
heard(Heard::Event(Event::Key(Key::Backspace, Mods::NONE)));
}
}
extern "C" fn replaced(_: Obj, _: Sel, _: Obj, text: Obj) {
typed(text_of(text));
}
extern "C" fn selected_range(_: Obj, _: Sel) -> Obj {
let (picked, long) = COMPOSING.with_borrow(|composing| (composing.picked, composing.marked.len()));
if long == 0 { range(0, 0) } else { range(picked.location.min(long), (picked.location + picked.length).min(long)) }
}
extern "C" fn marked_range(_: Obj, _: Sel) -> Obj {
let long = length();
if long == 0 { std::ptr::null_mut() } else { range(0, long) }
}
extern "C" fn style(_: Obj, _: Sel) -> Obj {
COMPOSING.with_borrow(|composing| composing.style)
}
extern "C" fn set_style(_: Obj, _: Sel, style: Obj) {
COMPOSING.with_borrow_mut(|composing| composing.style = style);
}
extern "C" fn marked(_: Obj, _: Sel, text: Obj, picked: NSRange) {
let text = text_of(text);
COMPOSING.with_borrow_mut(|composing| (composing.marked, composing.picked) = (text.encode_utf16().collect(), picked));
show_marked();
}
extern "C" fn unmarked(_: Obj, _: Sel) {
let text = piece(0, length());
typed(text);
}
extern "C" fn delegate(_: Obj, _: Sel) -> Obj {
COMPOSING.with_borrow(|composing| composing.delegate)
}
extern "C" fn set_delegate(_: Obj, _: Sel, delegate: Obj) {
COMPOSING.with_borrow_mut(|composing| composing.delegate = delegate);
}
extern "C" fn tokenizer(_: Obj, _: Sel) -> Obj {
COMPOSING.with_borrow(|composing| composing.tokenizer)
}
extern "C" fn first_rect(_: Obj, _: Sel, _: Obj) -> NSRect {
let (height, width) = COMPOSING.with_borrow(|composing| (composing.cursor.map_or(1.0, |at| at.h), composing.label));
let wide = unsafe { send_rect(width, c"frame", ()) }.size.width.max(1.0);
NSRect::new(0.0, 0.0, wide, f64::from(height))
}
extern "C" fn caret_rect(_: Obj, _: Sel, _: Obj) -> NSRect {
let height = COMPOSING.with_borrow(|composing| composing.cursor.map_or(1.0, |at| at.h));
NSRect::new(0.0, 0.0, 2.0, f64::from(height))
}
extern "C" fn no_rects(_: Obj, _: Sel, _: Obj) -> Obj {
ns_array(&[])
}
extern "C" fn closest(_: Obj, _: Sel, _: NSPoint) -> Obj {
position(length())
}
extern "C" fn closest_within(_: Obj, _: Sel, _: NSPoint, within: Obj) -> Obj {
position(ends_of(within)[1])
}
extern "C" fn no_range(_: Obj, _: Sel, _: NSPoint) -> Obj {
std::ptr::null_mut()
}
extern "C" fn no_trait(_: Obj, _: Sel) -> isize {
1
}
extern "C" fn none_trait(_: Obj, _: Sel) -> isize {
0
}
extern "C" fn secret(_: Obj, _: Sel) -> Bool {
Bool::from(COMPOSING.with_borrow(|composing| composing.secret))
}
fn command(letter: char) {
heard(Heard::Event(Event::Key(Key::Char(letter), Mods::CTRL)));
}
extern "C" fn copied(_: Obj, _: Sel, _: Obj) {
command('c');
}
extern "C" fn cut(_: Obj, _: Sel, _: Obj) {
command('x');
}
extern "C" fn pasted(_: Obj, _: Sel, _: Obj) {
crate::ios::paste_now();
command('v');
}
extern "C" fn all_selected(_: Obj, _: Sel, _: Obj) {
command('a');
}
extern "C" fn can_perform(_: Obj, _: Sel, action: Sel, _: Obj) -> Bool {
let offered = [c"copy:", c"cut:", c"paste:", c"selectAll:"];
Bool::from(offered.into_iter().any(|name| std::ptr::eq(sel(name), action)))
}
fn show_marked() {
let (text, picked, cursor) = COMPOSING.with_borrow(|composing| (String::from_utf16_lossy(&composing.marked), composing.picked, composing.cursor));
let Some(at) = cursor.filter(|_| !text.is_empty()) else { return hide_marked() };
let label = label();
unsafe {
send::<()>(label, c"setAttributedText:", (dressed(&text, picked),));
let font: Obj = send(class(c"UIFont"), c"systemFontOfSize:", (f64::from(at.h * 0.8),));
send::<()>(label, c"setFont:", (font,));
send::<()>(label, c"sizeToFit", ());
let size = send_rect(label, c"frame", ()).size;
send::<()>(label, c"setFrame:", (NSRect::new(f64::from(at.x), f64::from(at.y), size.width, f64::from(at.h).max(size.height)),));
send::<()>(label, c"setHidden:", (0 as Bool,));
}
}
fn hide_marked() {
let label = COMPOSING.with_borrow(|composing| composing.label);
unsafe { send::<()>(label, c"setHidden:", (1 as Bool,)) };
}
fn label() -> Obj {
let known = COMPOSING.with_borrow(|composing| composing.label);
if !known.is_null() {
return known;
}
let label = unsafe {
let label: Obj = send(send::<Obj>(class(c"UILabel"), c"alloc", ()), c"initWithFrame:", (NSRect::default(),));
send::<()>(label, c"setUserInteractionEnabled:", (0 as Bool,));
send::<()>(label, c"setBackgroundColor:", (send::<Obj>(class(c"UIColor"), c"systemBackgroundColor", ()),));
send::<()>(label, c"setTextColor:", (send::<Obj>(class(c"UIColor"), c"labelColor", ()),));
let input = INPUT.get();
send::<()>(send::<Obj>(input, c"superview", ()), c"addSubview:", (label,));
send::<()>(label, c"release", ());
label
};
COMPOSING.with_borrow_mut(|composing| composing.label = label);
label
}
fn dressed(text: &str, picked: NSRange) -> Obj {
let number = |style: isize| -> Obj { unsafe { send(class(c"NSNumber"), c"numberWithInteger:", (style,)) } };
let long = text.encode_utf16().count();
unsafe {
let made: Obj = send(send::<Obj>(class(c"NSMutableAttributedString"), c"alloc", ()), c"initWithString:", (ns_string(text),));
send::<()>(made, c"addAttribute:value:range:", (NSUnderlineStyleAttributeName, number(SINGLE), NSRange { location: 0, length: long }));
let from = picked.location.min(long);
let within = NSRange { location: from, length: picked.length.min(long - from) };
if within.length > 0 {
send::<()>(made, c"addAttribute:value:range:", (NSUnderlineStyleAttributeName, number(THICK), within));
let tint: Obj = send(class(c"UIColor"), c"systemFillColor", ());
send::<()>(made, c"addAttribute:value:range:", (NSBackgroundColorAttributeName, tint, within));
}
send(made, c"autorelease", ())
}
}