From a2b17dbc61f140ed83f609b5b8737d922f45780f Mon Sep 17 00:00:00 2001 From: Arnold Loubriat Date: Mon, 23 Nov 2026 00:47:21 +0100 Subject: [PATCH 1/4] Only post layout changes on iOS when the layout changes --- adapters/ios/src/event.rs | 170 +++++++++++++++++++++++++++++++++++++- 1 file changed, 166 insertions(+), 4 deletions(-) diff --git a/adapters/ios/src/event.rs b/adapters/ios/src/event.rs index 171ef470d..2a39d1c45 100644 --- a/adapters/ios/src/event.rs +++ b/adapters/ios/src/event.rs @@ -3,7 +3,7 @@ // the LICENSE-APACHE file) or the MIT license (found in // the LICENSE-MIT file), at your option. -use accesskit::Live; +use accesskit::{Live, Role}; use accesskit_consumer::{FilterResult, FullNodeId, NodeRef, TreeChangeHandler}; use objc2::runtime::{AnyObject, ProtocolObject}; use objc2_foundation::{ @@ -19,7 +19,7 @@ use std::rc::Rc; use crate::{ context::Context, - filters::filter, + filters::{filter, filter_for_is_accessibility_element}, node::{NodeWrapper, PlatformNode}, util::{announcement_priority_high, announcement_priority_key, announcement_priority_low}, }; @@ -204,6 +204,31 @@ impl EventGenerator { } } +/// Other changes, like a text input's value, don't count: the notification +/// would interrupt VoiceOver while it echoes typing. Children make a node a +/// container, except text runs, which change whenever a line wraps. +fn layout_changed(old_node: &NodeRef, new_node: &NodeRef) -> bool { + fn children(node: &NodeRef) -> impl Iterator { + node.children() + .filter(|child| child.role() != Role::TextRun) + .map(|child| child.id()) + } + fn is_element_changed(old_node: Option, new_node: Option) -> bool { + old_node.map(|node| filter_for_is_accessibility_element(&node)) + != new_node.map(|node| filter_for_is_accessibility_element(&node)) + } + let (old, new) = (old_node.data(), new_node.data()); + is_element_changed(Some(*old_node), Some(*new_node)) + || is_element_changed( + old_node.filtered_parent(&filter), + new_node.filtered_parent(&filter), + ) + || old_node.role() != new_node.role() + || old.bounds() != new.bounds() + || old.transform() != new.transform() + || !children(old_node).eq(children(new_node)) +} + impl TreeChangeHandler for EventGenerator { fn node_added(&mut self, node: &NodeRef) { if filter(node) != FilterResult::Include { @@ -233,11 +258,11 @@ impl TreeChangeHandler for EventGenerator { return; } - if new_included { + let was_filtered_out = old_filter_result != FilterResult::Include; + if new_included && (was_filtered_out || layout_changed(old_node, new_node)) { self.insert_layout_changed_event_if_needed(); } - let was_filtered_out = old_filter_result != FilterResult::Include; if let Some(label) = NodeWrapper(new_node).label() { if new_node.live() != Live::Off && (Some(&label) != NodeWrapper(old_node).label().as_ref() @@ -268,3 +293,140 @@ impl TreeChangeHandler for EventGenerator { self.remove_node(node.id()); } } + +#[cfg(test)] +mod tests { + use super::*; + use accesskit::{Action, Affine, Node, NodeId, Rect, TreeId, TreeInfo, TreeUpdate}; + use accesskit_consumer::Tree; + + const ROOT: NodeId = NodeId(0); + + fn tree(nodes: Vec<(NodeId, Node)>) -> Tree { + Tree::new( + TreeUpdate { + nodes, + tree: Some(TreeInfo::new(ROOT)), + tree_id: TreeId::ROOT, + focus: ROOT, + }, + false, + ) + } + + fn compare( + old: Vec<(NodeId, Node)>, + new: Vec<(NodeId, Node)>, + f: impl FnOnce(&NodeRef, &NodeRef) -> R, + ) -> R { + compare_node(old, new, ROOT, f) + } + + fn compare_node( + old: Vec<(NodeId, Node)>, + new: Vec<(NodeId, Node)>, + id: NodeId, + f: impl FnOnce(&NodeRef, &NodeRef) -> R, + ) -> R { + let (old, new) = (tree(old), tree(new)); + let (old, new) = (old.state(), new.state()); + f( + &old.node_by_tree_local_id(id, TreeId::ROOT).unwrap(), + &new.node_by_tree_local_id(id, TreeId::ROOT).unwrap(), + ) + } + + fn text_input(runs: &[&str]) -> Vec<(NodeId, Node)> { + let run_ids = (1..=runs.len() as u64).map(NodeId); + let mut input = Node::new(Role::TextInput); + input.set_bounds(Rect::new(0.0, 0.0, 100.0, 20.0)); + input.set_children(run_ids.clone().collect::>()); + let mut nodes = vec![(ROOT, input)]; + for (id, text) in run_ids.zip(runs) { + let mut run = Node::new(Role::TextRun); + run.set_value(*text); + run.set_character_lengths(text.chars().map(|c| c.len_utf8() as u8).collect::>()); + nodes.push((id, run)); + } + nodes + } + + fn group(children: &[u64]) -> Vec<(NodeId, Node)> { + let mut group = Node::new(Role::Group); + group.set_children(children.iter().copied().map(NodeId).collect::>()); + let mut nodes = vec![(ROOT, group)]; + nodes.extend( + children + .iter() + .map(|id| (NodeId(*id), Node::new(Role::Button))), + ); + nodes + } + + #[test] + fn typing_does_not_change_the_layout() { + let changed = compare( + text_input(&["hello"]), + text_input(&["hello!"]), + layout_changed, + ); + assert!(!changed); + } + + #[test] + fn wrapping_a_line_does_not_change_the_layout() { + let changed = compare( + text_input(&["hello world"]), + text_input(&["hello ", "world"]), + layout_changed, + ); + assert!(!changed); + } + + #[test] + fn moving_changes_the_layout() { + let mut moved = text_input(&["hello"]); + moved[0].1.set_bounds(Rect::new(0.0, 20.0, 100.0, 40.0)); + assert!(compare(text_input(&["hello"]), moved, layout_changed)); + let mut scaled = text_input(&["hello"]); + scaled[0].1.set_transform(Affine::scale(2.0)); + assert!(compare(text_input(&["hello"]), scaled, layout_changed)); + } + + #[test] + fn changing_the_role_changes_the_layout() { + let mut search = text_input(&["hello"]); + search[0].1.set_role(Role::SearchInput); + assert!(compare(text_input(&["hello"]), search, layout_changed)); + } + + #[test] + fn changing_the_children_changes_the_layout() { + assert!(!compare(group(&[1]), group(&[1]), layout_changed)); + assert!(compare(group(&[1]), group(&[1, 2]), layout_changed)); + assert!(compare(group(&[1, 2]), group(&[2, 1]), layout_changed)); + } + + fn labelled_group() -> Vec<(NodeId, Node)> { + let mut nodes = group(&[1]); + nodes[1].1.set_label("OK"); + nodes + } + + #[test] + fn becoming_an_element_changes_the_layout() { + let mut clickable = labelled_group(); + clickable[0].1.add_action(Action::Click); + assert!(compare(labelled_group(), clickable, layout_changed)); + } + + #[test] + fn making_the_parent_a_container_changes_the_layout() { + assert!(compare_node( + group(&[1]), + labelled_group(), + NodeId(1), + layout_changed + )); + } +} From 8a40d140cda257bbe21ab62021fd4b3b24819256 Mon Sep 17 00:00:00 2001 From: Arnold Loubriat Date: Mon, 23 Nov 2026 00:47:27 +0100 Subject: [PATCH 2/4] Expose text inputs to VoiceOver on iOS --- adapters/ios/Cargo.toml | 7 + adapters/ios/src/adapter.rs | 148 +++- adapters/ios/src/context.rs | 43 +- adapters/ios/src/event.rs | 11 +- adapters/ios/src/lib.rs | 3 + adapters/ios/src/node.rs | 46 +- adapters/ios/src/subclass.rs | 47 +- adapters/ios/src/text.rs | 865 +++++++++++++++++++ adapters/ios/src/text_input.rs | 564 ++++++++++++ adapters/ios/tests/integration/main.rs | 8 +- adapters/ios/tests/integration/text.rs | 40 + adapters/ios/tests/integration/text_input.rs | 555 ++++++++++++ 12 files changed, 2303 insertions(+), 34 deletions(-) create mode 100644 adapters/ios/src/text.rs create mode 100644 adapters/ios/src/text_input.rs create mode 100644 adapters/ios/tests/integration/text.rs create mode 100644 adapters/ios/tests/integration/text_input.rs diff --git a/adapters/ios/Cargo.toml b/adapters/ios/Cargo.toml index 69ef47fa2..02d443a8e 100644 --- a/adapters/ios/Cargo.toml +++ b/adapters/ios/Cargo.toml @@ -25,11 +25,14 @@ objc2-foundation = { version = "0.2.0", features = [ "NSAttributedString", "NSDictionary", "NSNotification", + "NSRange", "NSString", "NSValue", "NSThread", + "NSZone", ] } objc2-ui-kit = { version = "0.2.0", features = [ + "NSText", "UIAccessibility", "UIAccessibilityConstants", "UIAccessibilityContainer", @@ -38,6 +41,8 @@ objc2-ui-kit = { version = "0.2.0", features = [ "UIGeometry", "UIResponder", "UIScreen", + "UITextInput", + "UITextInputTraits", "UIView", "UIViewController", "UIWindow", @@ -50,9 +55,11 @@ objc2-foundation = { version = "0.2.0", features = ["NSObjCRuntime", "NSRunLoop" objc2-ui-kit = { version = "0.2.0", features = [ "UIApplication", "UIColor", + "UIControl", "UIScene", "UISceneOptions", "UISceneSession", + "UITextField", "UIWindowScene", ] } diff --git a/adapters/ios/src/adapter.rs b/adapters/ios/src/adapter.rs index a881775cc..f2fe964f7 100644 --- a/adapters/ios/src/adapter.rs +++ b/adapters/ios/src/adapter.rs @@ -42,10 +42,13 @@ use std::rc::{Rc, Weak}; use std::{ffi::c_void, ptr::null_mut}; use crate::{ - context::{ActionHandlerNoMut, ActionHandlerWrapper, Context}, + context::{ + ActionHandlerNoMut, ActionHandlerWrapper, ActiveTextInput, ActiveTextInputCell, Context, + }, event::{EventGenerator, QueuedEvents, layout_event, screen_changed_event}, filters::{element_at_point, filter}, node::PlatformNode, + text::TextTokenizer, util::from_cg_point, }; @@ -55,6 +58,7 @@ enum State { Inactive { view: WeakId, action_handler: Rc, + active_text_input: ActiveTextInputCell, mtm: MainThreadMarker, }, Placeholder { @@ -70,6 +74,7 @@ impl Debug for State { State::Inactive { view, action_handler: _, + active_text_input: _, mtm, } => f .debug_struct("Inactive") @@ -129,7 +134,7 @@ fn get_or_init_context( state: &RefCell, activation_handler: &ActivationHandlerCell, ) -> Rc { - let (view, action_handler, mtm) = { + let (view, action_handler, active_text_input, mtm) = { let state = state.borrow(); match &*state { State::Active(context) => return Rc::clone(context), @@ -140,8 +145,14 @@ fn get_or_init_context( State::Inactive { view, action_handler, + active_text_input, mtm, - } => (view.clone(), Rc::clone(action_handler), *mtm), + } => ( + view.clone(), + Rc::clone(action_handler), + Rc::clone(active_text_input), + *mtm, + ), } }; @@ -157,7 +168,7 @@ fn get_or_init_context( State::Inactive { .. } => match initial { Some(initial_state) => { let tree = Tree::new(initial_state, true); - let context = Context::new(view, tree, action_handler, mtm); + let context = Context::new(view, tree, action_handler, active_text_input, mtm); let result = Rc::clone(&context); *state = State::Active(context); result @@ -174,6 +185,7 @@ fn get_or_init_context( view, placeholder_tree, Rc::new(ActionHandlerWrapper::new(PlaceholderActionHandler {})), + active_text_input, mtm, ); let result = Rc::clone(&placeholder_context); @@ -208,26 +220,19 @@ fn try_activate( fn try_deactivate(state: &RefCell, deactivation_handler: &DeactivationHandlerCell) { let transitioned = { let mut state = state.borrow_mut(); - let (view, action_handler, mtm) = match &*state { + let (context, action_handler) = match &*state { State::Inactive { .. } => return, State::Placeholder { placeholder_context, action_handler, - } => ( - placeholder_context.view.clone(), - Rc::clone(action_handler), - placeholder_context.mtm, - ), - State::Active(context) => ( - context.view.clone(), - Rc::clone(&context.action_handler), - context.mtm, - ), + } => (placeholder_context, Rc::clone(action_handler)), + State::Active(context) => (context, Rc::clone(&context.action_handler)), }; *state = State::Inactive { - view, + view: context.view.clone(), action_handler, - mtm, + active_text_input: Rc::clone(&context.active_text_input), + mtm: context.mtm, }; true }; @@ -318,6 +323,7 @@ impl StatusObserver { /// All adapter methods must be called on the main thread. pub struct Adapter { state: Rc>, + active_text_input: ActiveTextInputCell, activation_handler: Rc, #[allow(dead_code)] deactivation_handler: Rc, @@ -351,9 +357,11 @@ impl Adapter { let view = WeakId::from_retained(&view); let mtm = MainThreadMarker::new().unwrap(); + let active_text_input = ActiveTextInputCell::default(); let state = Rc::new(RefCell::new(State::Inactive { view, action_handler: Rc::new(ActionHandlerWrapper::new(action_handler)), + active_text_input: Rc::clone(&active_text_input), mtm, })); let activation_handler: Rc = @@ -381,6 +389,7 @@ impl Adapter { Self { state, + active_text_input, activation_handler, deactivation_handler, status_observer, @@ -415,6 +424,7 @@ impl Adapter { placeholder_context.view.clone(), tree, Rc::clone(action_handler), + Rc::clone(&placeholder_context.active_text_input), placeholder_context.mtm, ); let focus_id = context.tree.borrow().state().focus().map(|node| node.id()); @@ -445,6 +455,110 @@ impl Adapter { try_activate(&self.state, &self.activation_handler) } + /// Tell the adapter that `view`, which has just become the first + /// responder, is editing the given text input node, so that assistive + /// technologies follow the text while it's edited. Call + /// [`Adapter::clear_text_input_view`] once editing stops. + /// + /// The view should be a subview of the adapter's view, with a non-zero + /// size, and its `UITextInput` implementation must use [`TextPosition`] + /// and [`TextRange`](crate::TextRange). The adapter only keeps a weak + /// reference to it. + /// + /// While it edits a password, assistive technologies read the view's + /// `accessibilityValue`, which must then mask each UTF-16 code unit of + /// the text. + /// + /// [`TextPosition`]: crate::TextPosition + /// + /// # Safety + /// + /// `view` must be a valid, unreleased pointer to a `UIView` that + /// conforms to `UITextInput`. + pub unsafe fn set_text_input_view(&self, view: *mut c_void, node_id: NodeId, tree_id: TreeId) { + let view = unsafe { Retained::retain(view as *mut UIView) }.unwrap(); + *self.active_text_input.borrow_mut() = Some(ActiveTextInput { + node_id, + tree_id, + view: WeakId::from_retained(&view), + }); + } + + /// Tell the adapter that the view passed to + /// [`Adapter::set_text_input_view`] stopped editing. + pub fn clear_text_input_view(&self) { + *self.active_text_input.borrow_mut() = None; + } + + /// A tokenizer to return from the `tokenizer` property of `view`, the + /// view passed to [`Adapter::set_text_input_view`]. + /// + /// # Safety + /// + /// `view` must be a valid, unreleased pointer to a `UIView` that + /// conforms to `UITextInput`. + pub unsafe fn text_tokenizer(&self, view: *mut c_void) -> Retained { + let view = unsafe { Retained::retain(view as *mut UIView) }.unwrap(); + let state = Rc::downgrade(&self.state); + let weak_view = WeakId::from_retained(&view); + let node = move || { + let state = state.upgrade()?; + let State::Active(context) = &*state.borrow() else { + return None; + }; + let view = weak_view.load()?; + let id = { + let active = context.active_text_input.borrow(); + let active = active.as_ref()?; + if active.view.load()? != view { + return None; + } + let tree = context.tree.borrow(); + let node = tree + .state() + .node_by_tree_local_id(active.node_id, active.tree_id)?; + node.id() + }; + Some((Rc::clone(context), id)) + }; + TextTokenizer::new(&view, Box::new(node)) + } + + /// Move the accessibility focus from the view passed to + /// [`Adapter::set_text_input_view`] to the text input node it is + /// editing. Call this from the view's + /// `accessibilityElementDidBecomeFocused` when its + /// `accessibilityElementIsFocused` returns `YES`. + /// + /// If a [`QueuedEvents`] instance is returned, the caller must call + /// [`QueuedEvents::raise`] on it. + pub fn redirect_accessibility_focus(&self) -> Option { + let (node_id, tree_id) = { + let active = self.active_text_input.borrow(); + let active = active.as_ref()?; + (active.node_id, active.tree_id) + }; + let context = match &*self.state.borrow() { + State::Active(context) => Rc::clone(context), + _ => return None, + }; + let id = context + .tree + .borrow() + .state() + .node_by_tree_local_id(node_id, tree_id)? + .id(); + // Posting the notification anyway would make VoiceOver start over, + // with a sound or a vibration and sometimes no announcement. + if *context.platform_focus.borrow() == Some(id) { + return None; + } + Some(QueuedEvents::new( + context, + vec![screen_changed_event(Some(id))], + )) + } + // UIAccessibilityContainer methods /// Indicates whether the view itself is an accessibility element. diff --git a/adapters/ios/src/context.rs b/adapters/ios/src/context.rs index ed784868b..accc4f430 100644 --- a/adapters/ios/src/context.rs +++ b/adapters/ios/src/context.rs @@ -3,16 +3,16 @@ // the LICENSE-APACHE file) or the MIT license (found in // the LICENSE-MIT file), at your option. -use accesskit::{ActionHandler, ActionRequest}; +use accesskit::{ActionHandler, ActionRequest, NodeId, TreeId}; use accesskit_consumer::{FullNodeId, Tree}; use hashbrown::HashMap; use objc2::rc::{Retained, WeakId}; -use objc2_foundation::MainThreadMarker; +use objc2_foundation::{MainThreadMarker, NSObject, NSObjectProtocol}; use objc2_ui_kit::UIView; use std::fmt::Debug; use std::{cell::RefCell, rc::Rc}; -use crate::node::PlatformNode; +use crate::{node::PlatformNode, text_input::TextInputNode}; pub(crate) trait ActionHandlerNoMut { fn do_action(&self, request: ActionRequest); @@ -32,12 +32,24 @@ impl ActionHandlerNoMut for ActionHandlerWrapper { } } +#[derive(Debug)] +pub(crate) struct ActiveTextInput { + pub(crate) node_id: NodeId, + pub(crate) tree_id: TreeId, + pub(crate) view: WeakId, +} + +/// Shared between the adapter and its contexts, since the application may +/// set it before the tree is initialized. +pub(crate) type ActiveTextInputCell = Rc>>; + pub(crate) struct Context { pub(crate) view: WeakId, pub(crate) tree: RefCell, pub(crate) action_handler: Rc, platform_nodes: RefCell>>, pub(crate) platform_focus: RefCell>, + pub(crate) active_text_input: ActiveTextInputCell, pub(crate) mtm: MainThreadMarker, } @@ -49,6 +61,7 @@ impl Debug for Context { .field("action_handler", &"ActionHandler") .field("platform_nodes", &self.platform_nodes) .field("platform_focus", &self.platform_focus) + .field("active_text_input", &self.active_text_input) .field("mtm", &self.mtm) .finish() } @@ -59,6 +72,7 @@ impl Context { view: WeakId, tree: Tree, action_handler: Rc, + active_text_input: ActiveTextInputCell, mtm: MainThreadMarker, ) -> Rc { Rc::new(Self { @@ -67,20 +81,37 @@ impl Context { action_handler, platform_nodes: RefCell::new(HashMap::new()), platform_focus: RefCell::new(None), + active_text_input, mtm, }) } + /// Replaces the element of a node that started or stopped needing a + /// [`TextInputNode`]. pub(crate) fn get_or_create_platform_node( self: &Rc, id: FullNodeId, ) -> Option> { + let is_text_input = { + let tree = self.tree.borrow(); + TextInputNode::is_needed_for(&tree.state().node_by_id(id)?) + }; if let Some(result) = self.platform_nodes.borrow().get(&id) { - return Some(result.clone()); + let object: &NSObject = PlatformNode::as_ns_object(result); + if object.is_kind_of::() == is_text_input { + return Some(result.clone()); + } } - let result = PlatformNode::new(self, id)?; - self.platform_nodes.borrow_mut().insert(id, result.clone()); + let result = if is_text_input { + Retained::into_super(TextInputNode::new(self, id)?) + } else { + PlatformNode::new(self, id)? + }; + let replaced = self.platform_nodes.borrow_mut().insert(id, result.clone()); + // Its dealloc can call `accessibilityContainer`, which reads the cache. + // See https://github.com/flutter/flutter/issues/87247. + drop(replaced); Some(result) } diff --git a/adapters/ios/src/event.rs b/adapters/ios/src/event.rs index 2a39d1c45..13413f968 100644 --- a/adapters/ios/src/event.rs +++ b/adapters/ios/src/event.rs @@ -21,6 +21,7 @@ use crate::{ context::Context, filters::{filter, filter_for_is_accessibility_element}, node::{NodeWrapper, PlatformNode}, + text_input::TextInputNode, util::{announcement_priority_high, announcement_priority_key, announcement_priority_low}, }; @@ -218,7 +219,8 @@ fn layout_changed(old_node: &NodeRef, new_node: &NodeRef) -> bool { != new_node.map(|node| filter_for_is_accessibility_element(&node)) } let (old, new) = (old_node.data(), new_node.data()); - is_element_changed(Some(*old_node), Some(*new_node)) + TextInputNode::is_needed_for(old_node) != TextInputNode::is_needed_for(new_node) + || is_element_changed(Some(*old_node), Some(*new_node)) || is_element_changed( old_node.filtered_parent(&filter), new_node.filtered_parent(&filter), @@ -400,6 +402,13 @@ mod tests { assert!(compare(text_input(&["hello"]), search, layout_changed)); } + #[test] + fn becoming_read_only_changes_the_layout() { + let mut read_only = text_input(&["hello"]); + read_only[0].1.set_read_only(); + assert!(compare(text_input(&["hello"]), read_only, layout_changed)); + } + #[test] fn changing_the_children_changes_the_layout() { assert!(!compare(group(&[1]), group(&[1]), layout_changed)); diff --git a/adapters/ios/src/lib.rs b/adapters/ios/src/lib.rs index a32aa4ab0..dcccc9510 100644 --- a/adapters/ios/src/lib.rs +++ b/adapters/ios/src/lib.rs @@ -27,6 +27,9 @@ mod context; mod filters; mod node; +mod text; +pub use text::{TextPosition, TextRange, TextSelectionRect, TextTokenizer}; +mod text_input; mod util; mod adapter; diff --git a/adapters/ios/src/node.rs b/adapters/ios/src/node.rs index 9fa7ca684..3a235f811 100644 --- a/adapters/ios/src/node.rs +++ b/adapters/ios/src/node.rs @@ -13,7 +13,7 @@ use accesskit_consumer::{FilterResult, FullNodeId, NodeRef, Tree}; use objc2::{ ClassType, DeclaredClass, declare_class, msg_send_id, mutability::MainThreadOnly, - rc::Retained, + rc::{Allocated, Retained}, runtime::{AnyObject, Bool}, }; use objc2_foundation::{CGRect, NSArray, NSObject, NSObjectProtocol, NSString}; @@ -23,9 +23,12 @@ use objc2_ui_kit::{ UIAccessibilityTraitButton, UIAccessibilityTraitHeader, UIAccessibilityTraitImage, UIAccessibilityTraitLink, UIAccessibilityTraitNone, UIAccessibilityTraitNotEnabled, UIAccessibilityTraitSearchField, UIAccessibilityTraitSelected, UIAccessibilityTraitStaticText, - UIAccessibilityTraitUpdatesFrequently, UIAccessibilityTraits, + UIAccessibilityTraitUpdatesFrequently, UIAccessibilityTraits, UIResponder, +}; +use std::{ + ffi::c_void, + rc::{Rc, Weak}, }; -use std::rc::{Rc, Weak}; use crate::{ context::Context, @@ -238,6 +241,19 @@ declare_class!( #[allow(non_snake_case)] unsafe impl PlatformNode { + // Objective-C can't carry the ivars by value, so they come boxed. + #[method_id(initWithAccessKitIvars:container:)] + fn init_with_ivars( + this: Allocated, + ivars: *mut c_void, + container: &AnyObject, + ) -> Option> { + // SAFETY: `init_args` boxed the ivars and gave up ownership of them. + let ivars = unsafe { Box::from_raw(ivars.cast::()) }; + let this = this.set_ivars(*ivars); + unsafe { msg_send_id![super(this), initWithAccessibilityContainer: container] } + } + #[method_id(accessibilityContainer)] fn container(&self) -> Option> { self.resolve_container() @@ -474,11 +490,27 @@ impl PlatformNode { Retained::into_super(responder) } + pub(crate) fn as_ns_object(&self) -> &NSObject { + let element: &UIAccessibilityElement = self; + let responder: &UIResponder = element; + responder + } + pub(crate) fn into_any_object(this: Retained) -> Retained { Retained::into_super(Self::into_ns_object(this)) } pub(crate) fn new(context: &Rc, node_id: FullNodeId) -> Option> { + let (ivars, container) = Self::init_args(context, node_id)?; + let this = context.mtm.alloc::(); + Some(unsafe { msg_send_id![this, initWithAccessKitIvars: ivars, container: &*container] }) + } + + /// The ivars are leaked unless passed to `initWithAccessKitIvars:container:`. + pub(crate) fn init_args( + context: &Rc, + node_id: FullNodeId, + ) -> Option<(*mut c_void, Retained)> { // UIAccessibilityElement's designated initializer is // `initWithAccessibilityContainer:`; plain `init` raises // NSInvalidArgumentException at runtime. Following Flutter's iOS @@ -487,14 +519,14 @@ impl PlatformNode { // actual parent dynamically via the `accessibilityContainer` override. let view = context.view.load()?; let container = Retained::into_super(Retained::into_super(Retained::into_super(view))); - let this = context.mtm.alloc::().set_ivars(PlatformNodeIvars { + let ivars = Box::new(PlatformNodeIvars { context: Rc::downgrade(context), node_id, }); - Some(unsafe { msg_send_id![super(this), initWithAccessibilityContainer: &*container] }) + Some((Box::into_raw(ivars).cast(), container)) } - fn resolve(&self, f: F) -> Option + pub(crate) fn resolve(&self, f: F) -> Option where F: FnOnce(&NodeRef) -> T, { @@ -505,7 +537,7 @@ impl PlatformNode { Some(f(&node)) } - fn resolve_with_context(&self, f: F) -> Option + pub(crate) fn resolve_with_context(&self, f: F) -> Option where F: FnOnce(&NodeRef, &Tree, &Rc) -> T, { diff --git a/adapters/ios/src/subclass.rs b/adapters/ios/src/subclass.rs index 055990340..bfd4363fd 100644 --- a/adapters/ios/src/subclass.rs +++ b/adapters/ios/src/subclass.rs @@ -3,7 +3,9 @@ // the LICENSE-APACHE file) or the MIT license (found in // the LICENSE-MIT file), at your option. -use accesskit::{ActionHandler, ActivationHandler, DeactivationHandler, TreeUpdate}; +use accesskit::{ + ActionHandler, ActivationHandler, DeactivationHandler, NodeId, TreeId, TreeUpdate, +}; use objc2::{ ClassType, DeclaredClass, declare::ClassBuilder, @@ -22,7 +24,7 @@ use objc2_foundation::{CGPoint, MainThreadMarker, NSArray, NSObject}; use objc2_ui_kit::{UIView, UIWindow}; use std::{ffi::c_void, ptr::null_mut, sync::Mutex}; -use crate::{Adapter, event::QueuedEvents}; +use crate::{Adapter, TextTokenizer, event::QueuedEvents}; static SUBCLASSES: Mutex> = Mutex::new(Vec::new()); @@ -362,6 +364,47 @@ impl SubclassingAdapter { .adapter .update_if_active(update_factory) } + + /// See [`Adapter::set_text_input_view`]. + /// + /// # Safety + /// + /// `view` must be a valid, unreleased pointer to a `UIView` that + /// conforms to `UITextInput`. + pub unsafe fn set_text_input_view(&self, view: *mut c_void, node_id: NodeId, tree_id: TreeId) { + unsafe { + self.associated + .ivars() + .adapter + .set_text_input_view(view, node_id, tree_id) + } + } + + /// See [`Adapter::clear_text_input_view`]. + pub fn clear_text_input_view(&self) { + self.associated.ivars().adapter.clear_text_input_view() + } + + /// See [`Adapter::text_tokenizer`]. + /// + /// # Safety + /// + /// `view` must be a valid, unreleased pointer to a `UIView` that + /// conforms to `UITextInput`. + pub unsafe fn text_tokenizer(&self, view: *mut c_void) -> Retained { + unsafe { self.associated.ivars().adapter.text_tokenizer(view) } + } + + /// See [`Adapter::redirect_accessibility_focus`]. + /// + /// If a [`QueuedEvents`] instance is returned, the caller must call + /// [`QueuedEvents::raise`] on it. + pub fn redirect_accessibility_focus(&self) -> Option { + self.associated + .ivars() + .adapter + .redirect_accessibility_focus() + } } impl Drop for SubclassingAdapter { diff --git a/adapters/ios/src/text.rs b/adapters/ios/src/text.rs new file mode 100644 index 000000000..eecf7c971 --- /dev/null +++ b/adapters/ios/src/text.rs @@ -0,0 +1,865 @@ +// Copyright 2026 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +// Derived from the Flutter engine. +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE.chromium file. + +//! VoiceOver may hand positions and ranges from the application's view to an +//! [`InactiveTextInput`] and back, so both use [`TextPosition`] and +//! [`TextRange`]. + +use accesskit_consumer::{FullNodeId, NodeRef, TextPosition as Position}; +use objc2::{ + ClassType, DeclaredClass, declare_class, msg_send_id, + mutability::MainThreadOnly, + rc::Retained, + runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject}, +}; +use objc2_foundation::{ + CGPoint, CGRect, MainThreadMarker, NSArray, NSAttributedStringKey, NSComparisonResult, + NSCopying, NSDictionary, NSInteger, NSRange, NSString, NSZone, +}; +use objc2_ui_kit::{ + NSWritingDirection, UIKeyInput, UIResponder, UITextDirection, UITextGranularity, UITextInput, + UITextInputDelegate, UITextInputStringTokenizer, UITextInputTokenizer, UITextInputTraits, + UITextLayoutDirection, UITextPosition, UITextRange, UITextSelectionRect, + UITextStorageDirection, UIView, +}; +use std::{ + cell::{Cell, RefCell}, + ops::Range, + rc::{Rc, Weak}, +}; + +use crate::{ + context::Context, + util::{from_cg_point, to_cg_rect}, +}; + +pub struct TextPositionIvars { + index: usize, +} + +declare_class!( + /// A UTF-16 index, for the view passed to + /// [`Adapter::set_text_input_view`](crate::Adapter::set_text_input_view). + #[derive(Debug)] + pub struct TextPosition; + + unsafe impl ClassType for TextPosition { + #[inherits(NSObject)] + type Super = UITextPosition; + type Mutability = MainThreadOnly; + const NAME: &'static str = "AccessKitTextPosition"; + } + + impl DeclaredClass for TextPosition { + type Ivars = TextPositionIvars; + } + + unsafe impl NSObjectProtocol for TextPosition {} +); + +impl TextPosition { + pub fn new(mtm: MainThreadMarker, index: usize) -> Retained { + let this = mtm.alloc::().set_ivars(TextPositionIvars { index }); + unsafe { msg_send_id![super(this), init] } + } + + /// The UTF-16 index of `position`, or `None` if it isn't a + /// [`TextPosition`]. + pub fn index(position: &UITextPosition) -> Option { + // SAFETY: We just checked the class of the position. + position + .is_kind_of::() + .then(|| unsafe { &*(position as *const UITextPosition as *const Self) }) + .map(|position| position.ivars().index) + } +} + +pub struct TextRangeIvars { + range: Range, +} + +declare_class!( + /// A UTF-16 range, for the view passed to + /// [`Adapter::set_text_input_view`](crate::Adapter::set_text_input_view). + #[derive(Debug)] + pub struct TextRange; + + unsafe impl ClassType for TextRange { + #[inherits(NSObject)] + type Super = UITextRange; + type Mutability = MainThreadOnly; + const NAME: &'static str = "AccessKitTextRange"; + } + + impl DeclaredClass for TextRange { + type Ivars = TextRangeIvars; + } + + unsafe impl NSObjectProtocol for TextRange {} + + unsafe impl TextRange { + #[method_id(start)] + fn start(&self) -> Retained { + let start = self.ivars().range.start; + Retained::into_super(TextPosition::new(MainThreadMarker::from(self), start)) + } + + #[method_id(end)] + fn end(&self) -> Retained { + let end = self.ivars().range.end; + Retained::into_super(TextPosition::new(MainThreadMarker::from(self), end)) + } + + #[method(isEmpty)] + fn is_empty(&self) -> bool { + self.ivars().range.is_empty() + } + } + + unsafe impl NSCopying for TextRange { + #[method_id(copyWithZone:)] + fn copy_with_zone(&self, _zone: *mut NSZone) -> Retained { + Self::new(MainThreadMarker::from(self), self.ivars().range.clone()) + } + } +); + +impl TextRange { + pub fn new(mtm: MainThreadMarker, range: Range) -> Retained { + let this = mtm.alloc::().set_ivars(TextRangeIvars { range }); + unsafe { msg_send_id![super(this), init] } + } + + /// The UTF-16 range of `range`, or `None` if it isn't a [`TextRange`]. + pub fn range(range: &UITextRange) -> Option> { + // SAFETY: We just checked the class of the range. + range + .is_kind_of::() + .then(|| unsafe { &*(range as *const UITextRange as *const Self) }) + .map(|range| range.ivars().range.clone()) + } +} + +pub struct TextSelectionRectIvars { + rect: CGRect, + contains_start: bool, + contains_end: bool, +} + +declare_class!( + /// A horizontal, left-to-right selection rectangle, to return from + /// `selectionRectsForRange:`. + #[derive(Debug)] + pub struct TextSelectionRect; + + unsafe impl ClassType for TextSelectionRect { + #[inherits(NSObject)] + type Super = UITextSelectionRect; + type Mutability = MainThreadOnly; + const NAME: &'static str = "AccessKitTextSelectionRect"; + } + + impl DeclaredClass for TextSelectionRect { + type Ivars = TextSelectionRectIvars; + } + + unsafe impl NSObjectProtocol for TextSelectionRect {} + + unsafe impl TextSelectionRect { + #[method(rect)] + fn rect(&self) -> CGRect { + self.ivars().rect + } + + #[method(writingDirection)] + fn writing_direction(&self) -> NSWritingDirection { + NSWritingDirection::LeftToRight + } + + #[method(containsStart)] + fn contains_start(&self) -> bool { + self.ivars().contains_start + } + + #[method(containsEnd)] + fn contains_end(&self) -> bool { + self.ivars().contains_end + } + + #[method(isVertical)] + fn is_vertical(&self) -> bool { + false + } + } +); + +impl TextSelectionRect { + pub fn new( + mtm: MainThreadMarker, + rect: CGRect, + contains_start: bool, + contains_end: bool, + ) -> Retained { + let this = mtm.alloc::().set_ivars(TextSelectionRectIvars { + rect, + contains_start, + contains_end, + }); + unsafe { msg_send_id![super(this), init] } + } + + /// The rectangles of a selection, from its start to its end, as + /// `selectionRectsForRange:` returns them. + pub fn array( + mtm: MainThreadMarker, + rects: &[CGRect], + ) -> Retained> { + let last = rects.len().saturating_sub(1); + let rects = rects + .iter() + .enumerate() + .map(|(index, rect)| { + Retained::into_super(Self::new(mtm, *rect, index == 0, index == last)) + }) + .collect(); + NSArray::from_vec(rects) + } +} + +pub(crate) type NodeLookup = Box Option<(Rc, FullNodeId)>>; + +pub struct TextTokenizerIvars { + node: NodeLookup, +} + +declare_class!( + /// A tokenizer for the view passed to + /// [`Adapter::set_text_input_view`](crate::Adapter::set_text_input_view), + /// made by [`Adapter::text_tokenizer`](crate::Adapter::text_tokenizer). + #[derive(Debug)] + pub struct TextTokenizer; + + unsafe impl ClassType for TextTokenizer { + #[inherits(NSObject)] + type Super = UITextInputStringTokenizer; + type Mutability = MainThreadOnly; + const NAME: &'static str = "AccessKitTextTokenizer"; + } + + impl DeclaredClass for TextTokenizer { + type Ivars = TextTokenizerIvars; + } + + unsafe impl NSObjectProtocol for TextTokenizer {} + + unsafe impl TextTokenizer { + #[method_id(rangeEnclosingPosition:withGranularity:inDirection:)] + fn range_enclosing_position( + &self, + position: Option<&UITextPosition>, + granularity: UITextGranularity, + direction: UITextDirection, + ) -> Option> { + position.and_then(|position| { + if granularity == UITextGranularity::Line { + return self.line_enclosing_position(position, direction); + } + unsafe { + msg_send_id![ + super(self), + rangeEnclosingPosition: position, + withGranularity: granularity, + inDirection: direction, + ] + } + }) + } + } +); + +impl TextTokenizer { + pub(crate) fn new(text_input: &UIResponder, node: NodeLookup) -> Retained { + let mtm = MainThreadMarker::from(text_input); + let this = mtm.alloc::().set_ivars(TextTokenizerIvars { node }); + unsafe { msg_send_id![super(this), initWithTextInput: text_input] } + } + + /// `UITextInputStringTokenizer` guesses where lines wrap, while the text + /// runs say it. + fn line_enclosing_position( + &self, + position: &UITextPosition, + direction: UITextDirection, + ) -> Option> { + let index = TextPosition::index(position)?; + let (context, node_id) = (self.ivars().node)()?; + let tree = context.tree.borrow(); + let state = tree.state(); + let node = state.node_by_id(node_id)?; + let range = line_enclosing(&node, index, is_backward(direction))?; + let range = TextRange::new(MainThreadMarker::from(self), range); + Some(Retained::into_super(range)) + } +} + +fn is_backward(direction: UITextDirection) -> bool { + [ + UITextStorageDirection::Backward.0, + UITextLayoutDirection::Left.0, + UITextLayoutDirection::Up.0, + ] + .contains(&direction) +} + +/// As Apple documents, a position between two lines belongs to the one in +/// `direction`. +fn line_enclosing(node: &NodeRef, index: usize, backward: bool) -> Option> { + if !node.supports_text_ranges() { + return None; + } + let position = node.text_position_from_global_utf16_index(index)?; + let character = if backward { + if position.is_document_start() { + return None; + } + position.backward_to_character_start() + } else { + if position.is_document_end() { + return None; + } + position + }; + Some(line_range(line_start(character))) +} + +fn line_start(position: Position) -> Position { + let position = position.biased_to_start(); + if position.is_line_start() { + position + } else { + position.backward_to_line_start() + } +} + +/// The UTF-16 range of the line starting at `start`, without its line break. +fn line_range(start: Position) -> Range { + let mut range = start.to_degenerate_range(); + range.set_end(start.forward_to_line_end()); + while !range.is_degenerate() && range.text().ends_with(['\n', '\r']) { + range.set_end(range.end().backward_to_character_start()); + } + range.start().to_global_utf16_index()..range.end().to_global_utf16_index() +} + +pub(crate) fn composed_character_range(text: &NSString, index: usize) -> Range { + let range = unsafe { text.rangeOfComposedCharacterSequenceAtIndex(index) }; + range.location..range.location + range.length +} + +pub(crate) fn offset_by_characters(text: &NSString, index: usize, offset: isize) -> Option { + let len = text.length(); + if index > len { + return None; + } + let mut index = index; + for _ in 0..offset.unsigned_abs() { + index = if offset > 0 { + (index < len).then(|| composed_character_range(text, index).end)? + } else { + (index > 0).then(|| composed_character_range(text, index - 1).start)? + }; + } + Some(index) +} + +pub(crate) struct InactiveTextInputIvars { + context: Weak, + node_id: FullNodeId, + text: RefCell>, + selection: RefCell>>, + is_secure: Cell, + tokenizer: RefCell>>, +} + +declare_class!( + /// A view, though never in a hierarchy, because UIKit only describes a + /// view as a text input. + #[derive(Debug)] + pub(crate) struct InactiveTextInput; + + unsafe impl ClassType for InactiveTextInput { + #[inherits(UIResponder, NSObject)] + type Super = UIView; + type Mutability = MainThreadOnly; + const NAME: &'static str = "AccessKitInactiveTextInput"; + } + + impl DeclaredClass for InactiveTextInput { + type Ivars = InactiveTextInputIvars; + } + + unsafe impl NSObjectProtocol for InactiveTextInput {} + + unsafe impl UITextInputTraits for InactiveTextInput { + #[method(isSecureTextEntry)] + fn is_secure_text_entry(&self) -> bool { + self.ivars().is_secure.get() + } + } + + #[allow(non_snake_case)] + unsafe impl UIKeyInput for InactiveTextInput { + #[method(hasText)] + fn hasText(&self) -> bool { + self.len() > 0 + } + + #[method(insertText:)] + fn insertText(&self, _text: &NSString) {} + + #[method(deleteBackward)] + fn deleteBackward(&self) {} + } + + #[allow(non_snake_case)] + unsafe impl UITextInput for InactiveTextInput { + #[method_id(textInRange:)] + fn textInRange(&self, range: Option<&UITextRange>) -> Option> { + range.and_then(|range| self.text_in_range(range)) + } + + #[method(replaceRange:withText:)] + fn replaceRange_withText(&self, _range: Option<&UITextRange>, _text: &NSString) {} + + #[method_id(selectedTextRange)] + fn selectedTextRange(&self) -> Option> { + let selection = self.ivars().selection.borrow().clone(); + selection.map(|selection| self.range(selection)) + } + + #[method(setSelectedTextRange:)] + fn setSelectedTextRange(&self, range: Option<&UITextRange>) { + *self.ivars().selection.borrow_mut() = range.and_then(TextRange::range); + } + + #[method_id(markedTextRange)] + fn markedTextRange(&self) -> Option> { + None + } + + #[method_id(markedTextStyle)] + fn markedTextStyle( + &self, + ) -> Option>> { + None + } + + #[method(setMarkedTextStyle:)] + fn setMarkedTextStyle( + &self, + _style: Option<&NSDictionary>, + ) { + } + + #[method(setMarkedText:selectedRange:)] + fn setMarkedText_selectedRange( + &self, + _marked_text: Option<&NSString>, + _selected_range: NSRange, + ) { + } + + #[method(unmarkText)] + fn unmarkText(&self) {} + + #[method_id(beginningOfDocument)] + fn beginningOfDocument(&self) -> Retained { + self.position(0) + } + + #[method_id(endOfDocument)] + fn endOfDocument(&self) -> Retained { + self.position(self.len()) + } + + #[method_id(textRangeFromPosition:toPosition:)] + fn textRangeFromPosition_toPosition( + &self, + from_position: Option<&UITextPosition>, + to_position: Option<&UITextPosition>, + ) -> Option> { + let from = from_position.and_then(TextPosition::index); + let to = to_position.and_then(TextPosition::index); + from.zip(to) + .map(|(from, to)| self.range(from.min(to)..from.max(to))) + } + + // UIKit's tokenizer finds characters by stepping over code units, even + // in the middle of a character. + #[method_id(positionFromPosition:offset:)] + fn positionFromPosition_offset( + &self, + position: Option<&UITextPosition>, + offset: NSInteger, + ) -> Option> { + let index = position.and_then(TextPosition::index); + let index = index.and_then(|index| index.checked_add_signed(offset)); + index + .filter(|index| *index <= self.len()) + .map(|index| self.position(index)) + } + + #[method_id(positionFromPosition:inDirection:offset:)] + fn positionFromPosition_inDirection_offset( + &self, + position: Option<&UITextPosition>, + direction: UITextLayoutDirection, + offset: NSInteger, + ) -> Option> { + position.and_then(|position| match direction { + UITextLayoutDirection::Up => self.position_on_line(position, -offset), + UITextLayoutDirection::Down => self.position_on_line(position, offset), + UITextLayoutDirection::Left => self.position_by_characters(position, -offset), + _ => self.position_by_characters(position, offset), + }) + } + + #[method(comparePosition:toPosition:)] + fn comparePosition_toPosition( + &self, + position: Option<&UITextPosition>, + other: Option<&UITextPosition>, + ) -> NSComparisonResult { + let index = |position: Option<&UITextPosition>| position.and_then(TextPosition::index); + match (index(position), index(other)) { + (Some(position), Some(other)) => position.cmp(&other).into(), + _ => NSComparisonResult::Same, + } + } + + #[method(offsetFromPosition:toPosition:)] + fn offsetFromPosition_toPosition( + &self, + from: Option<&UITextPosition>, + to_position: Option<&UITextPosition>, + ) -> NSInteger { + let index = |position: Option<&UITextPosition>| position.and_then(TextPosition::index); + match (index(from), index(to_position)) { + (Some(from), Some(to)) => to as NSInteger - from as NSInteger, + _ => 0, + } + } + + // UIKit only assigns an input delegate to the text input it is + // actually editing, which this never is. + #[method_id(inputDelegate)] + fn inputDelegate(&self) -> Option>> { + None + } + + #[method(setInputDelegate:)] + fn setInputDelegate( + &self, + _delegate: Option<&ProtocolObject>, + ) { + } + + #[method_id(tokenizer)] + fn tokenizer(&self) -> Retained> { + let tokenizer = self + .ivars() + .tokenizer + .borrow_mut() + .get_or_insert_with(|| { + let context = self.ivars().context.clone(); + let node_id = self.ivars().node_id; + let node = move || Some((context.upgrade()?, node_id)); + TextTokenizer::new(self, Box::new(node)) + }) + .clone(); + ProtocolObject::from_retained(Retained::into_super(tokenizer)) + } + + #[method_id(positionWithinRange:farthestInDirection:)] + fn positionWithinRange_farthestInDirection( + &self, + range: Option<&UITextRange>, + direction: UITextLayoutDirection, + ) -> Option> { + range.and_then(TextRange::range).map(|range| match direction { + UITextLayoutDirection::Left | UITextLayoutDirection::Up => { + self.position(range.start) + } + _ => self.position(range.end), + }) + } + + #[method_id(characterRangeByExtendingPosition:inDirection:)] + fn characterRangeByExtendingPosition_inDirection( + &self, + position: Option<&UITextPosition>, + direction: UITextLayoutDirection, + ) -> Option> { + let index = position.and_then(TextPosition::index); + index.and_then(|index| self.character_range_by_extending(index, direction)) + } + + #[method(baseWritingDirectionForPosition:inDirection:)] + fn baseWritingDirectionForPosition_inDirection( + &self, + _position: Option<&UITextPosition>, + _direction: UITextStorageDirection, + ) -> NSWritingDirection { + NSWritingDirection::Natural + } + + #[method(setBaseWritingDirection:forRange:)] + fn setBaseWritingDirection_forRange( + &self, + _writing_direction: NSWritingDirection, + _range: Option<&UITextRange>, + ) { + } + + // The stand-in isn't in a window, so like the element's frame, these + // are in screen coordinates. + + #[method(firstRectForRange:)] + fn firstRectForRange(&self, range: Option<&UITextRange>) -> CGRect { + let range = range.and_then(TextRange::range); + let rects = range.map_or_else(Vec::new, |range| self.rects(range)); + rects.first().copied().unwrap_or(CGRect::ZERO) + } + + #[method(caretRectForPosition:)] + fn caretRectForPosition(&self, position: Option<&UITextPosition>) -> CGRect { + let index = position.and_then(TextPosition::index); + let rects = index.map_or_else(Vec::new, |index| self.rects(index..index)); + rects.first().copied().unwrap_or(CGRect::ZERO) + } + + #[method_id(selectionRectsForRange:)] + fn selectionRectsForRange( + &self, + range: Option<&UITextRange>, + ) -> Retained> { + let range = range.and_then(TextRange::range); + let rects = range.map_or_else(Vec::new, |range| self.rects(range)); + TextSelectionRect::array(MainThreadMarker::from(self), &rects) + } + + #[method_id(closestPositionToPoint:)] + fn closestPositionToPoint(&self, point: CGPoint) -> Option> { + self.index_at_point(point).map(|index| self.position(index)) + } + + #[method_id(closestPositionToPoint:withinRange:)] + fn closestPositionToPoint_withinRange( + &self, + point: CGPoint, + range: Option<&UITextRange>, + ) -> Option> { + let range = range.and_then(TextRange::range); + let index = range.zip(self.index_at_point(point)); + index.map(|(range, index)| self.position(index.clamp(range.start, range.end))) + } + + #[method_id(characterRangeAtPoint:)] + fn characterRangeAtPoint(&self, point: CGPoint) -> Option> { + self.character_range_at_point(point) + .map(|range| self.range(range)) + } + } +); + +impl InactiveTextInput { + pub(crate) fn new(context: &Rc, node_id: FullNodeId) -> Retained { + let this = context + .mtm + .alloc::() + .set_ivars(InactiveTextInputIvars { + context: Rc::downgrade(context), + node_id, + text: RefCell::new(NSString::new()), + selection: RefCell::new(None), + is_secure: Cell::new(false), + tokenizer: RefCell::new(None), + }); + unsafe { msg_send_id![super(this), init] } + } + + pub(crate) fn set_contents( + &self, + text: &str, + utf16_selection: Option>, + is_secure: bool, + ) { + *self.ivars().text.borrow_mut() = NSString::from_str(text); + *self.ivars().selection.borrow_mut() = utf16_selection; + self.ivars().is_secure.set(is_secure); + } + + fn len(&self) -> usize { + self.ivars().text.borrow().length() + } + + fn resolve(&self, f: impl FnOnce(&NodeRef, &UIView) -> Option) -> Option { + let context = self.ivars().context.upgrade()?; + let view = context.view.load()?; + let tree = context.tree.borrow(); + let state = tree.state(); + let node = state.node_by_id(self.ivars().node_id)?; + if !node.supports_text_ranges() { + return None; + } + f(&node, &view) + } + + fn rects(&self, range: Range) -> Vec { + self.resolve(|node, view| { + let start = node.text_position_from_global_utf16_index(range.start)?; + let end = node.text_position_from_global_utf16_index(range.end)?; + let mut text_range = start.to_degenerate_range(); + text_range.set_end(end); + let mut lines = Vec::::new(); + for rect in text_range.bounding_boxes() { + match lines.last_mut() { + Some(line) if rect.y0 < line.y1 && line.y0 < rect.y1 => { + *line = line.union(rect); + } + _ => lines.push(rect), + } + } + Some( + lines + .into_iter() + .map(|rect| to_cg_rect(view, rect)) + .collect(), + ) + }) + .unwrap_or_default() + } + + fn index_at_point(&self, point: CGPoint) -> Option { + self.resolve(|node, view| { + let point = from_cg_point(view, node, point)?; + Some(node.text_position_at_point(point).to_global_utf16_index()) + }) + } + + fn character_range_at_point(&self, point: CGPoint) -> Option> { + self.resolve(|node, view| { + let position = node.text_position_at_point(from_cg_point(view, node, point)?); + if position.is_document_end() { + return None; + } + let start = position.to_global_utf16_index(); + Some(start..position.forward_to_character_end().to_global_utf16_index()) + }) + } + + fn position(&self, index: usize) -> Retained { + Retained::into_super(TextPosition::new(MainThreadMarker::from(self), index)) + } + + fn range(&self, range: Range) -> Retained { + Retained::into_super(TextRange::new(MainThreadMarker::from(self), range)) + } + + fn text_in_range(&self, range: &UITextRange) -> Option> { + let range = TextRange::range(range)?; + let text = self.ivars().text.borrow(); + (range.start <= range.end && range.end <= text.length()).then(|| unsafe { + text.substringWithRange(NSRange::new(range.start, range.end - range.start)) + }) + } + + fn character_range_by_extending( + &self, + index: usize, + direction: UITextLayoutDirection, + ) -> Option> { + let lines = match direction { + UITextLayoutDirection::Up => -1, + UITextLayoutDirection::Down => 1, + _ => 0, + }; + if lines != 0 { + let other = self.index_on_line(index, lines)?; + return Some(self.range(index.min(other)..index.max(other))); + } + let text = self.ivars().text.borrow(); + if index > text.length() { + return None; + } + let range = match direction { + UITextLayoutDirection::Left if index > 0 => { + composed_character_range(&text, index - 1).start..index + } + UITextLayoutDirection::Left => index..index, + _ if index < text.length() => index..composed_character_range(&text, index).end, + _ => index..index, + }; + Some(self.range(range)) + } + + fn position_on_line( + &self, + position: &UITextPosition, + lines: NSInteger, + ) -> Option> { + let index = TextPosition::index(position)?; + Some(self.position(self.index_on_line(index, lines)?)) + } + + fn index_on_line(&self, index: usize, lines: NSInteger) -> Option { + self.resolve(|node, view| { + let position = node + .text_position_from_global_utf16_index(index)? + .biased_to_start(); + let mut line = line_start(position); + for _ in 0..lines.unsigned_abs() { + if lines < 0 { + if line.is_document_start() { + return Some(0); + } + line = line.backward_to_line_start(); + } else { + let end = line.forward_to_line_end(); + if end.is_document_end() { + return Some(end.to_global_utf16_index()); + } + line = line.forward_to_line_start(); + } + } + let target = line_range(line); + let caret = to_cg_rect( + view, + *position.to_degenerate_range().bounding_boxes().first()?, + ); + let line_box = *line.to_degenerate_range().bounding_boxes().first()?; + let line_box = to_cg_rect(view, line_box); + let y = line_box.origin.y + line_box.size.height / 2.0; + let point = from_cg_point(view, node, CGPoint::new(caret.origin.x, y))?; + let index = node.text_position_at_point(point).to_global_utf16_index(); + Some(index.clamp(target.start, target.end)) + }) + } + + fn position_by_characters( + &self, + position: &UITextPosition, + offset: NSInteger, + ) -> Option> { + let index = TextPosition::index(position)?; + let index = offset_by_characters(&self.ivars().text.borrow(), index, offset)?; + Some(self.position(index)) + } +} diff --git a/adapters/ios/src/text_input.rs b/adapters/ios/src/text_input.rs new file mode 100644 index 000000000..0f2c37aea --- /dev/null +++ b/adapters/ios/src/text_input.rs @@ -0,0 +1,564 @@ +// Copyright 2026 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +// Derived from the Flutter engine. +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE.chromium file. + +//! UIKit only treats an element as a text input if it conforms to +//! `UITextInput`. [`TextInputNode`] forwards that protocol to the +//! application's view while the node is being edited, and to an +//! [`InactiveTextInput`] otherwise. + +use accesskit::{Action, Role}; +use accesskit_consumer::{FullNodeId, NodeRef}; +use objc2::{ + ClassType, DeclaredClass, declare_class, msg_send, msg_send_id, + mutability::MainThreadOnly, + rc::Retained, + runtime::{AnyObject, Bool, NSObject, NSObjectProtocol, ProtocolObject, Sel}, + sel, +}; +use objc2_foundation::{ + CGPoint, CGRect, NSArray, NSAttributedStringKey, NSComparisonResult, NSDictionary, NSInteger, + NSRange, NSString, +}; +use objc2_ui_kit::{ + NSWritingDirection, UIAccessibilityElement, UIAccessibilityTraits, UIKeyInput, UIResponder, + UITextInput, UITextInputDelegate, UITextInputTokenizer, UITextInputTraits, + UITextLayoutDirection, UITextPosition, UITextRange, UITextSelectionRect, + UITextStorageDirection, UIView, +}; +use std::{ops::Range, rc::Rc}; + +use crate::{context::Context, filters::filter, node::PlatformNode, text::InactiveTextInput}; + +/// A private trait that native text fields don't have. Left unmasked, it makes +/// VoiceOver say "empty line" when the input is tapped and put the caret at +/// the start when editing starts. +const EMPTY_LINE_TRAIT: UIAccessibilityTraits = 0x800000000000; + +pub(crate) struct TextInputNodeIvars { + inactive: Retained, +} + +declare_class!( + #[derive(Debug)] + pub(crate) struct TextInputNode; + + unsafe impl ClassType for TextInputNode { + #[inherits(UIAccessibilityElement, UIResponder, NSObject)] + type Super = PlatformNode; + type Mutability = MainThreadOnly; + const NAME: &'static str = "AccessKitTextInputNode"; + } + + impl DeclaredClass for TextInputNode { + type Ivars = TextInputNodeIvars; + } + + unsafe impl NSObjectProtocol for TextInputNode {} + + unsafe impl TextInputNode { + #[method_id(accessibilityLabel)] + fn label(&self) -> Option> { + let label: Option> = + unsafe { msg_send_id![super(self), accessibilityLabel] }; + label.or_else(|| unsafe { msg_send_id![&*self.surrogate(), accessibilityLabel] }) + } + + #[method_id(accessibilityHint)] + fn hint(&self) -> Option> { + let hint: Option> = + unsafe { msg_send_id![super(self), accessibilityHint] }; + hint.or_else(|| unsafe { msg_send_id![&*self.surrogate(), accessibilityHint] }) + } + + #[method_id(accessibilityValue)] + fn value(&self) -> Option> { + let value: Option> = + unsafe { msg_send_id![super(self), accessibilityValue] }; + value.or_else(|| unsafe { msg_send_id![&*self.surrogate(), accessibilityValue] }) + } + + #[method(accessibilityTraits)] + fn traits(&self) -> UIAccessibilityTraits { + let traits: UIAccessibilityTraits = + unsafe { msg_send![super(self), accessibilityTraits] }; + let surrogate_traits: UIAccessibilityTraits = + unsafe { msg_send![&*self.surrogate(), accessibilityTraits] }; + (traits | surrogate_traits) & !EMPTY_LINE_TRAIT + } + + // An inactive stand-in doesn't handle activation, so click to let the + // application start editing. + #[method(accessibilityActivate)] + fn activate(&self) -> bool { + let handled: Bool = unsafe { msg_send![&*self.surrogate(), accessibilityActivate] }; + handled.as_bool() || unsafe { msg_send![super(self), accessibilityActivate] } + } + + // Recorded first, or the application's view would redirect + // VoiceOver here again. + #[method(accessibilityElementDidBecomeFocused)] + fn element_did_become_focused(&self) { + unsafe { + let _: () = msg_send![super(self), accessibilityElementDidBecomeFocused]; + let _: () = msg_send![&*self.surrogate(), accessibilityElementDidBecomeFocused]; + } + } + + #[method(accessibilityElementDidLoseFocus)] + fn element_did_lose_focus(&self) { + unsafe { + let _: () = msg_send![&*self.surrogate(), accessibilityElementDidLoseFocus]; + let _: () = msg_send![super(self), accessibilityElementDidLoseFocus]; + } + } + + #[method(cut:)] + fn cut(&self, sender: Option<&AnyObject>) { + self.forward_edit_action(sel!(cut:), sender); + } + + #[method(copy:)] + fn copy(&self, sender: Option<&AnyObject>) { + self.forward_edit_action(sel!(copy:), sender); + } + + #[method(paste:)] + fn paste(&self, sender: Option<&AnyObject>) { + self.forward_edit_action(sel!(paste:), sender); + } + + #[method(selectAll:)] + fn select_all(&self, sender: Option<&AnyObject>) { + self.forward_edit_action(sel!(selectAll:), sender); + } + + #[method(delete:)] + fn delete(&self, sender: Option<&AnyObject>) { + self.forward_edit_action(sel!(delete:), sender); + } + + #[method(canPerformAction:withSender:)] + fn can_perform_action(&self, action: Sel, sender: Option<&AnyObject>) -> bool { + unsafe { self.surrogate().canPerformAction_withSender(action, sender) } + } + } + + // The application's view may not say that a password input is secure, + // so the node's role counts too. + unsafe impl UITextInputTraits for TextInputNode { + #[method(isSecureTextEntry)] + fn is_secure_text_entry(&self) -> bool { + self.resolve(|node| node.is_password_input()).unwrap_or(false) || { + let surrogate = self.surrogate(); + surrogate.respondsToSelector(sel!(isSecureTextEntry)) + && unsafe { msg_send![&*surrogate, isSecureTextEntry] } + } + } + } + + #[allow(non_snake_case)] + unsafe impl UIKeyInput for TextInputNode { + #[method(hasText)] + fn hasText(&self) -> bool { + unsafe { self.text_input().hasText() } + } + + #[method(insertText:)] + fn insertText(&self, text: &NSString) { + unsafe { self.text_input().insertText(text) } + } + + #[method(deleteBackward)] + fn deleteBackward(&self) { + unsafe { self.text_input().deleteBackward() } + } + } + + #[allow(non_snake_case)] + unsafe impl UITextInput for TextInputNode { + #[method_id(textInRange:)] + fn textInRange(&self, range: Option<&UITextRange>) -> Option> { + range.and_then(|range| unsafe { self.text_input().textInRange(range) }) + } + + #[method(replaceRange:withText:)] + fn replaceRange_withText(&self, range: Option<&UITextRange>, text: &NSString) { + if let Some(range) = range { + unsafe { self.text_input().replaceRange_withText(range, text) } + } + } + + #[method(shouldChangeTextInRange:replacementText:)] + fn shouldChangeTextInRange_replacementText( + &self, + range: Option<&UITextRange>, + text: &NSString, + ) -> bool { + let surrogate = self.surrogate(); + let selector = sel!(shouldChangeTextInRange:replacementText:); + !surrogate.respondsToSelector(selector) + || unsafe { + msg_send![&*surrogate, shouldChangeTextInRange: range, replacementText: text] + } + } + + #[method_id(selectedTextRange)] + fn selectedTextRange(&self) -> Option> { + unsafe { self.text_input().selectedTextRange() } + } + + #[method(setSelectedTextRange:)] + fn setSelectedTextRange(&self, range: Option<&UITextRange>) { + unsafe { self.text_input().setSelectedTextRange(range) } + } + + #[method_id(markedTextRange)] + fn markedTextRange(&self) -> Option> { + unsafe { self.text_input().markedTextRange() } + } + + #[method_id(markedTextStyle)] + fn markedTextStyle( + &self, + ) -> Option>> { + unsafe { self.text_input().markedTextStyle() } + } + + #[method(setMarkedTextStyle:)] + fn setMarkedTextStyle( + &self, + style: Option<&NSDictionary>, + ) { + unsafe { self.text_input().setMarkedTextStyle(style) } + } + + #[method(setMarkedText:selectedRange:)] + fn setMarkedText_selectedRange( + &self, + marked_text: Option<&NSString>, + selected_range: NSRange, + ) { + unsafe { + self.text_input() + .setMarkedText_selectedRange(marked_text, selected_range) + } + } + + #[method(unmarkText)] + fn unmarkText(&self) { + unsafe { self.text_input().unmarkText() } + } + + #[method_id(beginningOfDocument)] + fn beginningOfDocument(&self) -> Retained { + unsafe { self.text_input().beginningOfDocument() } + } + + #[method_id(endOfDocument)] + fn endOfDocument(&self) -> Retained { + unsafe { self.text_input().endOfDocument() } + } + + #[method_id(textRangeFromPosition:toPosition:)] + fn textRangeFromPosition_toPosition( + &self, + from_position: Option<&UITextPosition>, + to_position: Option<&UITextPosition>, + ) -> Option> { + let positions = from_position.zip(to_position); + positions.and_then(|(from_position, to_position)| unsafe { + self.text_input() + .textRangeFromPosition_toPosition(from_position, to_position) + }) + } + + #[method_id(positionFromPosition:offset:)] + fn positionFromPosition_offset( + &self, + position: Option<&UITextPosition>, + offset: NSInteger, + ) -> Option> { + position.and_then(|position| unsafe { + self.text_input().positionFromPosition_offset(position, offset) + }) + } + + #[method_id(positionFromPosition:inDirection:offset:)] + fn positionFromPosition_inDirection_offset( + &self, + position: Option<&UITextPosition>, + direction: UITextLayoutDirection, + offset: NSInteger, + ) -> Option> { + position.and_then(|position| unsafe { + self.text_input() + .positionFromPosition_inDirection_offset(position, direction, offset) + }) + } + + #[method(comparePosition:toPosition:)] + fn comparePosition_toPosition( + &self, + position: Option<&UITextPosition>, + other: Option<&UITextPosition>, + ) -> NSComparisonResult { + let (Some(position), Some(other)) = (position, other) else { + return NSComparisonResult::Same; + }; + unsafe { self.text_input().comparePosition_toPosition(position, other) } + } + + #[method(offsetFromPosition:toPosition:)] + fn offsetFromPosition_toPosition( + &self, + from: Option<&UITextPosition>, + to_position: Option<&UITextPosition>, + ) -> NSInteger { + let (Some(from), Some(to_position)) = (from, to_position) else { + return 0; + }; + unsafe { self.text_input().offsetFromPosition_toPosition(from, to_position) } + } + + #[method_id(inputDelegate)] + fn inputDelegate(&self) -> Option>> { + unsafe { self.text_input().inputDelegate() } + } + + #[method(setInputDelegate:)] + fn setInputDelegate(&self, delegate: Option<&ProtocolObject>) { + unsafe { self.text_input().setInputDelegate(delegate) } + } + + #[method_id(tokenizer)] + fn tokenizer(&self) -> Retained> { + unsafe { self.text_input().tokenizer() } + } + + #[method_id(positionWithinRange:farthestInDirection:)] + fn positionWithinRange_farthestInDirection( + &self, + range: Option<&UITextRange>, + direction: UITextLayoutDirection, + ) -> Option> { + range.and_then(|range| unsafe { + self.text_input() + .positionWithinRange_farthestInDirection(range, direction) + }) + } + + #[method_id(characterRangeByExtendingPosition:inDirection:)] + fn characterRangeByExtendingPosition_inDirection( + &self, + position: Option<&UITextPosition>, + direction: UITextLayoutDirection, + ) -> Option> { + position.and_then(|position| unsafe { + self.text_input() + .characterRangeByExtendingPosition_inDirection(position, direction) + }) + } + + #[method(baseWritingDirectionForPosition:inDirection:)] + fn baseWritingDirectionForPosition_inDirection( + &self, + position: Option<&UITextPosition>, + direction: UITextStorageDirection, + ) -> NSWritingDirection { + let Some(position) = position else { + return NSWritingDirection::Natural; + }; + unsafe { + self.text_input() + .baseWritingDirectionForPosition_inDirection(position, direction) + } + } + + #[method(setBaseWritingDirection:forRange:)] + fn setBaseWritingDirection_forRange( + &self, + writing_direction: NSWritingDirection, + range: Option<&UITextRange>, + ) { + let Some(range) = range else { + return; + }; + unsafe { + self.text_input() + .setBaseWritingDirection_forRange(writing_direction, range) + } + } + + #[method(firstRectForRange:)] + fn firstRectForRange(&self, range: Option<&UITextRange>) -> CGRect { + range.map_or(CGRect::ZERO, |range| unsafe { + self.text_input().firstRectForRange(range) + }) + } + + #[method(caretRectForPosition:)] + fn caretRectForPosition(&self, position: Option<&UITextPosition>) -> CGRect { + position.map_or(CGRect::ZERO, |position| unsafe { + self.text_input().caretRectForPosition(position) + }) + } + + #[method_id(selectionRectsForRange:)] + fn selectionRectsForRange( + &self, + range: Option<&UITextRange>, + ) -> Retained> { + range.map_or_else(NSArray::new, |range| unsafe { + self.text_input().selectionRectsForRange(range) + }) + } + + #[method_id(closestPositionToPoint:)] + fn closestPositionToPoint(&self, point: CGPoint) -> Option> { + unsafe { self.text_input().closestPositionToPoint(point) } + } + + #[method_id(closestPositionToPoint:withinRange:)] + fn closestPositionToPoint_withinRange( + &self, + point: CGPoint, + range: Option<&UITextRange>, + ) -> Option> { + range.and_then(|range| unsafe { + self.text_input() + .closestPositionToPoint_withinRange(point, range) + }) + } + + #[method_id(characterRangeAtPoint:)] + fn characterRangeAtPoint(&self, point: CGPoint) -> Option> { + unsafe { self.text_input().characterRangeAtPoint(point) } + } + + #[method_id(textInputView)] + fn textInputView(&self) -> Retained { + self.surrogate() + } + } +); + +impl TextInputNode { + /// Like Flutter, which only does this for text fields, a spin button + /// only gets a [`TextInputNode`] if it has text to edit; otherwise it's + /// adjustable. + pub(crate) fn is_needed_for(node: &NodeRef) -> bool { + node.is_text_input() + && !node.is_read_only() + && (node.role() != Role::SpinButton + || node.supports_text_ranges() + || node.supports_action(Action::ReplaceSelectedText, &filter)) + } + + pub(crate) fn new(context: &Rc, node_id: FullNodeId) -> Option> { + let (ivars, container) = PlatformNode::init_args(context, node_id)?; + let this = context.mtm.alloc::().set_ivars(TextInputNodeIvars { + inactive: InactiveTextInput::new(context, node_id), + }); + unsafe { msg_send_id![super(this), initWithAccessKitIvars: ivars, container: &*container] } + } + + /// The inactive stand-in is brought up to date first. + fn surrogate(&self) -> Retained { + let active_view = self + .resolve_with_context(|node, _, context| { + let active = context.active_text_input.borrow(); + let active = active + .as_ref() + .filter(|active| node.locate() == (active.node_id, active.tree_id))?; + active.view.load() + }) + .flatten(); + if let Some(view) = active_view { + return view; + } + + let inactive = &self.ivars().inactive; + self.resolve(|node| { + let (text, selection) = contents(node); + inactive.set_contents(&text, selection, node.is_password_input()); + }); + Retained::into_super(inactive.clone()) + } + + fn text_input(&self) -> Retained> { + // SAFETY: `InactiveTextInput` conforms to `UITextInput`, and the + // caller of `Adapter::set_text_input_view` promised that the view it + // passed does too. + unsafe { Retained::cast(self.surrogate()) } + } + + fn forward_edit_action(&self, action: Sel, sender: Option<&AnyObject>) { + let surrogate = self.surrogate(); + if surrogate.respondsToSelector(action) { + unsafe { + let _: *mut AnyObject = + msg_send![&*surrogate, performSelector: action, withObject: sender]; + } + } + } +} + +fn contents(node: &NodeRef) -> (String, Option>) { + if !node.supports_text_ranges() { + return (node.value().unwrap_or_default(), None); + } + let selection = node + .text_selection() + .map(|range| range.start().to_global_utf16_index()..range.end().to_global_utf16_index()); + (node.document_range().text(), selection) +} + +#[cfg(test)] +mod tests { + use super::*; + use accesskit::{Node, NodeId, TreeId, TreeInfo, TreeUpdate}; + + fn is_needed_for(node: Node) -> bool { + let tree = accesskit_consumer::Tree::new( + TreeUpdate { + nodes: vec![(NodeId(0), node)], + tree: Some(TreeInfo::new(NodeId(0))), + tree_id: TreeId::ROOT, + focus: NodeId(0), + }, + false, + ); + let state = tree.state(); + TextInputNode::is_needed_for( + &state + .node_by_tree_local_id(NodeId(0), TreeId::ROOT) + .unwrap(), + ) + } + + #[test] + fn spin_buttons_need_text_to_be_text_inputs() { + let mut node = Node::new(Role::SpinButton); + node.set_numeric_value(42.0); + node.add_action(Action::Increment); + node.add_action(Action::Decrement); + assert!(!is_needed_for(node.clone())); + node.add_action(Action::ReplaceSelectedText); + assert!(is_needed_for(node)); + } + + #[test] + fn text_inputs_need_to_be_editable() { + assert!(is_needed_for(Node::new(Role::TextInput))); + let mut node = Node::new(Role::TextInput); + node.set_read_only(); + assert!(!is_needed_for(node)); + } +} diff --git a/adapters/ios/tests/integration/main.rs b/adapters/ios/tests/integration/main.rs index c756fae50..8be9ad7b5 100644 --- a/adapters/ios/tests/integration/main.rs +++ b/adapters/ios/tests/integration/main.rs @@ -5,8 +5,14 @@ mod harness; mod subclassing_adapter; +mod text; +mod text_input; mod util; fn main() -> std::process::ExitCode { - harness::run(&[("subclassing_adapter", subclassing_adapter::TESTS)]) + harness::run(&[ + ("subclassing_adapter", subclassing_adapter::TESTS), + ("text", text::TESTS), + ("text_input", text_input::TESTS), + ]) } diff --git a/adapters/ios/tests/integration/text.rs b/adapters/ios/tests/integration/text.rs new file mode 100644 index 000000000..107de7bde --- /dev/null +++ b/adapters/ios/tests/integration/text.rs @@ -0,0 +1,40 @@ +// Copyright 2026 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit_ios::{TextPosition, TextRange}; +use objc2::rc::Retained; +use objc2_foundation::{MainThreadMarker, NSCopying}; +use objc2_ui_kit::{UITextPosition, UITextRange}; + +use crate::harness::{Test, tests}; + +pub const TESTS: &[Test] = tests![ + foreign_positions_have_no_index, + ranges_expose_their_start_and_end, + copies_preserve_the_range, +]; + +fn foreign_positions_have_no_index() { + let mtm = MainThreadMarker::new().unwrap(); + let position: Retained = unsafe { UITextPosition::new(mtm) }; + assert_eq!(TextPosition::index(&position), None); + let range: Retained = unsafe { UITextRange::new(mtm) }; + assert_eq!(TextRange::range(&range), None); +} + +fn ranges_expose_their_start_and_end() { + let range = TextRange::new(MainThreadMarker::new().unwrap(), 1..4); + let range: &UITextRange = ⦥ + unsafe { + assert_eq!(TextPosition::index(&range.start()), Some(1)); + assert_eq!(TextPosition::index(&range.end()), Some(4)); + assert!(!range.isEmpty()); + } +} + +fn copies_preserve_the_range() { + let range = TextRange::new(MainThreadMarker::new().unwrap(), 2..4); + assert_eq!(TextRange::range(&range.copy()), Some(2..4)); +} diff --git a/adapters/ios/tests/integration/text_input.rs b/adapters/ios/tests/integration/text_input.rs new file mode 100644 index 000000000..451fad349 --- /dev/null +++ b/adapters/ios/tests/integration/text_input.rs @@ -0,0 +1,555 @@ +// Copyright 2026 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use std::{cell::RefCell, ffi::c_void, ops::Range, rc::Rc}; + +use accesskit::{ + Action, ActionHandler, ActionRequest, ActivationHandler, Node, NodeId, Rect, Role, + TextDirection, TextSelection, TreeId, TreeInfo, TreeUpdate, +}; +use accesskit_ios::{Adapter, TextPosition, TextRange}; +use objc2::rc::Retained; +use objc2::runtime::{Bool, NSObjectProtocol, ProtocolObject}; +use objc2::{ProtocolType, msg_send, msg_send_id}; +use objc2_foundation::{ + CGPoint, CGRect, CGSize, MainThreadMarker, NSArray, NSComparisonResult, NSInteger, NSObject, + NSString, +}; +use objc2_ui_kit::{ + UIKeyInput, UITextField, UITextGranularity, UITextInput, UITextInputStringTokenizer, + UITextInputTokenizer, UITextInputTraits, UITextLayoutDirection, UITextPosition, UITextRange, + UITextSelectionRect, UITextStorageDirection, UIView, UIWindow, +}; + +use crate::harness::{Test, tests}; +use crate::util::*; + +pub const TESTS: &[Test] = tests![ + the_element_is_replaced_when_the_input_becomes_read_only, + text_is_indexed_in_utf16_code_units, + text_in_out_of_bounds_range_is_none, + text_in_foreign_range_is_none, + selection_follows_the_tree, + positions_offset_within_the_text, + nil_positions_and_ranges_are_ignored, + positions_offset_in_utf16_code_units, + moving_left_or_right_steps_over_emoji, + character_ranges_cover_emoji, + lines_follow_the_text_runs, + the_edited_view_has_the_lines_of_its_node, + positions_move_between_lines, + has_text_follows_the_tree, + passwords_are_secure_text_entries, + activating_an_input_that_is_not_edited_clicks_it, + the_view_answers_while_editing, + inactive_rects_follow_the_text_runs, + inactive_positions_follow_points, + focus_is_redirected_to_the_edited_input, + focus_is_not_redirected_to_the_input_voiceover_is_on, + the_edited_input_can_be_set_before_activation, +]; + +const INPUT: NodeId = NodeId(0); +const RUN: NodeId = NodeId(1); + +fn input(role: Role, text: &str, character_selection: Option>) -> TreeUpdate { + let mut input = Node::new(role); + input.set_children(vec![RUN]); + input.add_action(Action::Focus); + input.add_action(Action::Click); + input.add_action(Action::SetTextSelection); + if let Some(selection) = character_selection { + let position = |character_index| accesskit::TextPosition { + node: RUN, + character_index, + }; + input.set_text_selection(TextSelection { + anchor: position(selection.start), + focus: position(selection.end), + }); + } + let mut run = Node::new(Role::TextRun); + run.set_value(text); + run.set_character_lengths(text.chars().map(|c| c.len_utf8() as u8).collect::>()); + TreeUpdate { + nodes: vec![(INPUT, input), (RUN, run)], + tree: Some(TreeInfo::new(INPUT)), + tree_id: TreeId::ROOT, + focus: INPUT, + } +} + +fn read_only_input(text: &str) -> TreeUpdate { + let mut update = input(Role::TextInput, text, None); + update.nodes[0].1.set_read_only(); + update +} + +const CHARACTER_WIDTH: f64 = 10.0; +const LINE_HEIGHT: f64 = 20.0; +const TEXT_X: f64 = 10.0; + +/// A multiline input with a text run per line, each character +/// `CHARACTER_WIDTH` wide. +fn laid_out_input(lines: &[&str]) -> TreeUpdate { + let run_ids = (1..=lines.len() as u64).map(NodeId); + let mut input = Node::new(Role::MultilineTextInput); + input.set_bounds(Rect::new(0.0, 0.0, 200.0, LINE_HEIGHT * lines.len() as f64)); + input.set_children(run_ids.clone().collect::>()); + let mut nodes = vec![(INPUT, input)]; + for ((index, text), id) in lines.iter().enumerate().zip(run_ids) { + let y0 = index as f64 * LINE_HEIGHT; + let mut run = Node::new(Role::TextRun); + run.set_bounds(Rect::new( + TEXT_X, + y0, + TEXT_X + text.chars().count() as f64 * CHARACTER_WIDTH, + y0 + LINE_HEIGHT, + )); + run.set_text_direction(TextDirection::LeftToRight); + run.set_value(*text); + run.set_character_lengths(text.chars().map(|c| c.len_utf8() as u8).collect::>()); + run.set_character_positions( + (0..text.chars().count()) + .map(|i| i as f32 * CHARACTER_WIDTH as f32) + .collect::>(), + ); + run.set_character_widths(vec![CHARACTER_WIDTH as f32; text.chars().count()]); + nodes.push((id, run)); + } + TreeUpdate { + nodes, + tree: Some(TreeInfo::new(INPUT)), + tree_id: TreeId::ROOT, + focus: INPUT, + } +} + +struct InitialTree(Option); + +impl ActivationHandler for InitialTree { + fn request_initial_tree(&mut self) -> Option { + self.0.take() + } +} + +struct RecordedActions(Rc>>); + +impl ActionHandler for RecordedActions { + fn do_action(&mut self, request: ActionRequest) { + self.0.borrow_mut().push(request); + } +} + +struct Fixture { + adapter: Adapter, + actions: Rc>>, + view: Retained, +} + +impl Fixture { + fn new(update: TreeUpdate) -> Self { + let view = new_view(); + let actions = Rc::default(); + let adapter = unsafe { + Adapter::new( + Retained::as_ptr(&view) as *mut c_void, + InitialTree(Some(update)), + RecordedActions(Rc::clone(&actions)), + NoDeactivation, + ) + }; + Self { + adapter, + actions, + view, + } + } + + fn update(&self, update: TreeUpdate) { + let _ = self.adapter.update_if_active(|| update); + } + + fn element(&self) -> Retained { + let elements: Retained> = + unsafe { Retained::retain(self.adapter.accessibility_elements()) }.unwrap(); + unsafe { elements.firstObject() }.unwrap() + } + + fn edit(&self, view: &UITextField) { + unsafe { + self.adapter.set_text_input_view( + view as *const UITextField as *mut c_void, + INPUT, + TreeId::ROOT, + ) + }; + } + + /// Screen coordinates are then those of the view, scaled. + fn in_window(&self) -> (Retained, f64) { + let mtm = mtm(); + let frame = CGRect::new(CGPoint::ZERO, CGSize::new(400.0, 400.0)); + let window = unsafe { UIWindow::initWithFrame(mtm.alloc(), frame) }; + unsafe { window.addSubview(&self.view) }; + (window, self.view.contentScaleFactor()) + } + + fn text_input(&self) -> Retained> { + let element = self.element(); + assert!(is_text_input(&element)); + unsafe { Retained::cast(element) } + } +} + +fn is_text_input(element: &NSObject) -> bool { + element.conformsToProtocol(::protocol().unwrap()) +} + +fn mtm() -> MainThreadMarker { + MainThreadMarker::new().unwrap() +} + +fn whole_text(input: &ProtocolObject) -> String { + unsafe { + let range = input + .textRangeFromPosition_toPosition(&input.beginningOfDocument(), &input.endOfDocument()) + .unwrap(); + input.textInRange(&range).unwrap().to_string() + } +} + +fn the_element_is_replaced_when_the_input_becomes_read_only() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let editable = fixture.element(); + fixture.update(read_only_input("hello")); + let read_only = fixture.element(); + assert!(!is_text_input(&read_only)); + assert!(!read_only.isEqual(&editable)); + fixture.update(input(Role::TextInput, "hello", None)); + assert!(is_text_input(&fixture.element())); +} + +fn text_is_indexed_in_utf16_code_units() { + let fixture = Fixture::new(input(Role::TextInput, "a😀b", None)); + let input = fixture.text_input(); + let range = TextRange::new(mtm(), 1..3); + assert_eq!( + unsafe { input.textInRange(&range) }.unwrap().to_string(), + "😀" + ); + assert_eq!( + TextPosition::index(&*unsafe { input.endOfDocument() }), + Some(4) + ); +} + +fn text_in_out_of_bounds_range_is_none() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let range = TextRange::new(mtm(), 3..10); + assert!(unsafe { fixture.text_input().textInRange(&range) }.is_none()); +} + +fn text_in_foreign_range_is_none() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let range = unsafe { UITextRange::new(mtm()) }; + assert!(unsafe { fixture.text_input().textInRange(&range) }.is_none()); +} + +fn selection_follows_the_tree() { + let fixture = Fixture::new(input(Role::TextInput, "a😀b", Some(1..2))); + let range = unsafe { fixture.text_input().selectedTextRange() }.unwrap(); + assert_eq!(TextRange::range(&range), Some(1..3)); + fixture.update(input(Role::TextInput, "a😀b", None)); + assert!(unsafe { fixture.text_input().selectedTextRange() }.is_none()); +} + +fn positions_offset_within_the_text() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let input = fixture.text_input(); + unsafe { + let start = input.beginningOfDocument(); + let position = input.positionFromPosition_offset(&start, 5).unwrap(); + assert_eq!(TextPosition::index(&position), Some(5)); + assert_eq!(input.offsetFromPosition_toPosition(&position, &start), -5); + assert_eq!( + input.comparePosition_toPosition(&start, &position), + NSComparisonResult::Ascending + ); + } +} + +fn nil_positions_and_ranges_are_ignored() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let element = fixture.element(); + let start = unsafe { fixture.text_input().beginningOfDocument() }; + let (no_position, no_range) = (None::<&UITextPosition>, None::<&UITextRange>); + unsafe { + let text: Option> = msg_send_id![&*element, textInRange: no_range]; + assert!(text.is_none()); + let position: Option> = + msg_send_id![&*element, positionFromPosition: no_position, offset: 1 as NSInteger]; + assert!(position.is_none()); + let range: Option> = + msg_send_id![&*element, textRangeFromPosition: &*start, toPosition: no_position]; + assert!(range.is_none()); + let offset: NSInteger = + msg_send![&*element, offsetFromPosition: no_position, toPosition: &*start]; + assert_eq!(offset, 0); + } +} + +fn positions_offset_in_utf16_code_units() { + let fixture = Fixture::new(input(Role::TextInput, "a😀b", None)); + let input = fixture.text_input(); + let offset = |index, offset| unsafe { + let position = TextPosition::new(mtm(), index); + input + .positionFromPosition_offset(&position, offset) + .and_then(|position| TextPosition::index(&position)) + }; + assert_eq!(offset(1, 1), Some(2)); + assert_eq!(offset(3, -1), Some(2)); + assert_eq!(offset(0, 4), Some(4)); + assert_eq!(offset(0, 5), None); + assert_eq!(offset(4, -5), None); +} + +fn moving_left_or_right_steps_over_emoji() { + let fixture = Fixture::new(input(Role::TextInput, "a😀b", None)); + let input = fixture.text_input(); + let step = |index, direction| unsafe { + let position = TextPosition::new(mtm(), index); + input + .positionFromPosition_inDirection_offset(&position, direction, 1) + .and_then(|position| TextPosition::index(&position)) + }; + assert_eq!(step(1, UITextLayoutDirection::Right), Some(3)); + assert_eq!(step(3, UITextLayoutDirection::Left), Some(1)); +} + +fn character_ranges_cover_emoji() { + let fixture = Fixture::new(input(Role::TextInput, "a😀b", None)); + let input = fixture.text_input(); + let extend = |index, direction| unsafe { + let position = TextPosition::new(mtm(), index); + input + .characterRangeByExtendingPosition_inDirection(&position, direction) + .and_then(|range| TextRange::range(&range)) + }; + assert_eq!(extend(1, UITextLayoutDirection::Right), Some(1..3)); + assert_eq!(extend(3, UITextLayoutDirection::Left), Some(1..3)); + assert_eq!(extend(4, UITextLayoutDirection::Right), Some(4..4)); +} + +fn line_at( + tokenizer: &ProtocolObject, + index: usize, + direction: UITextStorageDirection, +) -> Option> { + unsafe { + let position = TextPosition::new(mtm(), index); + tokenizer + .rangeEnclosingPosition_withGranularity_inDirection( + &position, + UITextGranularity::Line, + direction.0, + ) + .and_then(|range| TextRange::range(&range)) + } +} + +fn lines_follow_the_text_runs() { + let fixture = Fixture::new(laid_out_input(&["first line\n", "hello ", "world"])); + let tokenizer = unsafe { fixture.text_input().tokenizer() }; + let line = |index, direction| line_at(&tokenizer, index, direction); + let (forward, backward) = ( + UITextStorageDirection::Forward, + UITextStorageDirection::Backward, + ); + assert_eq!(line(0, forward), Some(0..10)); + assert_eq!(line(10, forward), Some(0..10)); + assert_eq!(line(11, backward), Some(0..10)); + assert_eq!(line(11, forward), Some(11..17)); + assert_eq!(line(17, backward), Some(11..17)); + assert_eq!(line(17, forward), Some(17..22)); + assert_eq!(line(22, backward), Some(17..22)); + assert_eq!(line(22, forward), None); + assert_eq!(line(0, backward), None); +} + +fn the_edited_view_has_the_lines_of_its_node() { + let fixture = Fixture::new(laid_out_input(&["hello ", "world"])); + let _ = fixture.element(); + let view = unsafe { UITextField::new(mtm()) }; + let tokenizer = unsafe { + fixture + .adapter + .text_tokenizer(Retained::as_ptr(&view) as *mut c_void) + }; + let tokenizer: &UITextInputStringTokenizer = &tokenizer; + let tokenizer = ProtocolObject::from_ref(tokenizer); + let forward = UITextStorageDirection::Forward; + assert_eq!(line_at(tokenizer, 7, forward), None); + fixture.edit(&view); + assert_eq!(line_at(tokenizer, 7, forward), Some(6..11)); + fixture.adapter.clear_text_input_view(); + assert_eq!(line_at(tokenizer, 7, forward), None); +} + +fn positions_move_between_lines() { + let fixture = Fixture::new(laid_out_input(&["hello ", "hi"])); + let (_window, _) = fixture.in_window(); + let input = fixture.text_input(); + let moved = |index, direction, offset| unsafe { + let position = TextPosition::new(mtm(), index); + input + .positionFromPosition_inDirection_offset(&position, direction, offset) + .and_then(|position| TextPosition::index(&position)) + }; + let (up, down) = (UITextLayoutDirection::Up, UITextLayoutDirection::Down); + assert_eq!(moved(1, down, 1), Some(7)); + assert_eq!(moved(7, up, 1), Some(1)); + assert_eq!(moved(5, down, 1), Some(8)); + assert_eq!(moved(1, down, 2), Some(8)); + assert_eq!(moved(7, up, 2), Some(0)); + assert_eq!(moved(1, UITextLayoutDirection::Right, 2), Some(3)); + let extended = unsafe { + input + .characterRangeByExtendingPosition_inDirection(&TextPosition::new(mtm(), 7), up) + .and_then(|range| TextRange::range(&range)) + }; + assert_eq!(extended, Some(1..7)); +} + +fn has_text_follows_the_tree() { + let fixture = Fixture::new(input(Role::TextInput, "", None)); + assert!(!unsafe { fixture.text_input().hasText() }); + fixture.update(input(Role::TextInput, "a", None)); + assert!(unsafe { fixture.text_input().hasText() }); +} + +fn passwords_are_secure_text_entries() { + let is_secure = |role| { + let fixture = Fixture::new(input(role, "secret", None)); + let element = fixture.element(); + let traits: &ProtocolObject = + unsafe { &*(&*element as *const NSObject).cast() }; + unsafe { traits.isSecureTextEntry() } + }; + assert!(!is_secure(Role::TextInput)); + assert!(is_secure(Role::PasswordInput)); +} + +fn activating_an_input_that_is_not_edited_clicks_it() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let handled: Bool = unsafe { msg_send![&*fixture.element(), accessibilityActivate] }; + assert!(handled.as_bool()); + let actions = fixture.actions.borrow(); + assert_eq!(actions.len(), 1); + assert_eq!(actions[0].action, Action::Click); + assert_eq!(actions[0].target_node, INPUT); +} + +fn the_view_answers_while_editing() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let view = unsafe { UITextField::new(mtm()) }; + unsafe { view.setText(Some(&NSString::from_str("typed"))) }; + fixture.edit(&view); + // `UITextField` doesn't use `TextPosition`, which is fine as long as the + // positions given out before editing aren't passed to it. + assert_eq!(whole_text(&fixture.text_input()), "typed"); + fixture.adapter.clear_text_input_view(); + assert_eq!(whole_text(&fixture.text_input()), "hello"); +} + +fn focus_is_redirected_to_the_edited_input() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let _ = fixture.element(); + assert!(fixture.adapter.redirect_accessibility_focus().is_none()); + let view = unsafe { UITextField::new(mtm()) }; + fixture.edit(&view); + assert!(fixture.adapter.redirect_accessibility_focus().is_some()); + fixture.adapter.clear_text_input_view(); + assert!(fixture.adapter.redirect_accessibility_focus().is_none()); +} + +fn focus_is_not_redirected_to_the_input_voiceover_is_on() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let view = unsafe { UITextField::new(mtm()) }; + fixture.edit(&view); + let _: () = unsafe { msg_send![&*fixture.element(), accessibilityElementDidBecomeFocused] }; + assert!(fixture.adapter.redirect_accessibility_focus().is_none()); +} + +fn the_edited_input_can_be_set_before_activation() { + let fixture = Fixture::new(input(Role::TextInput, "hello", None)); + let view = unsafe { UITextField::new(mtm()) }; + fixture.edit(&view); + assert!(fixture.adapter.redirect_accessibility_focus().is_none()); + let _ = fixture.element(); + assert!(fixture.adapter.redirect_accessibility_focus().is_some()); +} + +fn rect(x: f64, y: f64, width: f64, scale: f64) -> CGRect { + CGRect::new( + CGPoint::new(x / scale, y / scale), + CGSize::new(width / scale, LINE_HEIGHT / scale), + ) +} + +fn inactive_rects_follow_the_text_runs() { + let fixture = Fixture::new(laid_out_input(&["hello ", "world"])); + let (_window, scale) = fixture.in_window(); + let input = fixture.text_input(); + let (w, h) = (CHARACTER_WIDTH, LINE_HEIGHT); + unsafe { + let caret = input.caretRectForPosition(&TextPosition::new(mtm(), 2)); + assert_eq!(caret, rect(TEXT_X + 2.0 * w, 0.0, 0.0, scale)); + let range = TextRange::new(mtm(), 1..8); + assert_eq!( + input.firstRectForRange(&range), + rect(TEXT_X + w, 0.0, 5.0 * w, scale) + ); + let rects = input.selectionRectsForRange(&range); + assert_eq!(rects.count(), 2); + let line = |index| { + let rect: Retained = rects.objectAtIndex(index); + (rect.rect(), rect.containsStart(), rect.containsEnd()) + }; + assert_eq!( + line(0), + (rect(TEXT_X + w, 0.0, 5.0 * w, scale), true, false) + ); + assert_eq!(line(1), (rect(TEXT_X, h, 2.0 * w, scale), false, true)); + } +} + +fn inactive_positions_follow_points() { + let fixture = Fixture::new(laid_out_input(&["hello ", "world"])); + let (_window, scale) = fixture.in_window(); + let input = fixture.text_input(); + let point = |x: f64, y: f64| CGPoint::new(x / scale, y / scale); + let index = |position: Option>| { + position.and_then(|position| TextPosition::index(&position)) + }; + let (w, h) = (CHARACTER_WIDTH, LINE_HEIGHT); + unsafe { + let on_first_line = point(TEXT_X + 2.5 * w, 0.5 * h); + assert_eq!(index(input.closestPositionToPoint(on_first_line)), Some(2)); + let on_second_line = point(TEXT_X + 1.5 * w, 1.5 * h); + assert_eq!(index(input.closestPositionToPoint(on_second_line)), Some(7)); + let range = TextRange::new(mtm(), 0..1); + assert_eq!( + index(input.closestPositionToPoint_withinRange(on_first_line, &range)), + Some(1) + ); + let character = input.characterRangeAtPoint(on_first_line); + assert_eq!( + character.and_then(|range| TextRange::range(&range)), + Some(2..3) + ); + } +} From 01da16ea673c09f29f2f10a404bfcea20be64158 Mon Sep 17 00:00:00 2001 From: Arnold Loubriat Date: Mon, 23 Nov 2026 00:47:29 +0100 Subject: [PATCH 3/4] Support selecting text in iOS text inputs --- adapters/ios/src/event.rs | 95 +++++++- adapters/ios/src/text_input.rs | 221 +++++++++++++++++-- adapters/ios/tests/integration/text_input.rs | 18 +- 3 files changed, 308 insertions(+), 26 deletions(-) diff --git a/adapters/ios/src/event.rs b/adapters/ios/src/event.rs index 13413f968..9ad58fdb4 100644 --- a/adapters/ios/src/event.rs +++ b/adapters/ios/src/event.rs @@ -21,7 +21,7 @@ use crate::{ context::Context, filters::{filter, filter_for_is_accessibility_element}, node::{NodeWrapper, PlatformNode}, - text_input::TextInputNode, + text_input::{TextInputNode, contents}, util::{announcement_priority_high, announcement_priority_key, announcement_priority_low}, }; @@ -231,6 +231,19 @@ fn layout_changed(old_node: &NodeRef, new_node: &NodeRef) -> bool { || !children(old_node).eq(children(new_node)) } +/// A private notification that UIKit posts when the selection of one of its +/// text inputs changes, so that VoiceOver announces the new selection. +const SELECTION_CHANGED_NOTIFICATION: UIAccessibilityNotifications = 1017; + +fn only_selection_changed(old_node: &NodeRef, new_node: &NodeRef) -> bool { + if !new_node.is_text_input() { + return false; + } + let (old_text, old_selection) = contents(old_node); + let (new_text, new_selection) = contents(new_node); + old_selection != new_selection && old_text == new_text +} + impl TreeChangeHandler for EventGenerator { fn node_added(&mut self, node: &NodeRef) { if filter(node) != FilterResult::Include { @@ -265,6 +278,18 @@ impl TreeChangeHandler for EventGenerator { self.insert_layout_changed_event_if_needed(); } + // VoiceOver already reports typing, and only reads the selection of + // the element it is on. + if new_included + && self.platform_focus == Some(new_node.id()) + && only_selection_changed(old_node, new_node) + { + self.events.push(QueuedEvent::Generic { + node_id: None, + notification: SELECTION_CHANGED_NOTIFICATION, + }); + } + if let Some(label) = NodeWrapper(new_node).label() { if new_node.live() != Live::Off && (Some(&label) != NodeWrapper(old_node).label().as_ref() @@ -299,8 +324,11 @@ impl TreeChangeHandler for EventGenerator { #[cfg(test)] mod tests { use super::*; - use accesskit::{Action, Affine, Node, NodeId, Rect, TreeId, TreeInfo, TreeUpdate}; + use accesskit::{ + Action, Affine, Node, NodeId, Rect, TextSelection, TreeId, TreeInfo, TreeUpdate, + }; use accesskit_consumer::Tree; + use std::ops::Range; const ROOT: NodeId = NodeId(0); @@ -353,6 +381,18 @@ mod tests { nodes } + fn selected(mut nodes: Vec<(NodeId, Node)>, selection: Range) -> Vec<(NodeId, Node)> { + let position = |character_index| accesskit::TextPosition { + node: NodeId(1), + character_index, + }; + nodes[0].1.set_text_selection(TextSelection { + anchor: position(selection.start), + focus: position(selection.end), + }); + nodes + } + fn group(children: &[u64]) -> Vec<(NodeId, Node)> { let mut group = Node::new(Role::Group); group.set_children(children.iter().copied().map(NodeId).collect::>()); @@ -438,4 +478,55 @@ mod tests { layout_changed )); } + + #[test] + fn moving_the_caret_only_changes_the_selection() { + let hello = |selection| selected(text_input(&["hello"]), selection); + assert!(compare(hello(1..1), hello(2..2), only_selection_changed)); + assert!(compare(hello(1..1), hello(1..3), only_selection_changed)); + assert!(!compare(hello(1..1), hello(1..1), only_selection_changed)); + } + + #[test] + fn wrapping_a_line_does_not_change_the_selection() { + let mut wrapped = text_input(&["hello ", "world"]); + let caret = accesskit::TextPosition { + node: NodeId(2), + character_index: 0, + }; + wrapped[0].1.set_text_selection(TextSelection { + anchor: caret, + focus: caret, + }); + let changed = compare( + selected(text_input(&["hello world"]), 6..6), + wrapped, + only_selection_changed, + ); + assert!(!changed); + } + + #[test] + fn typing_changes_more_than_the_selection() { + let changed = compare( + selected(text_input(&["hello"]), 5..5), + selected(text_input(&["hello!"]), 6..6), + only_selection_changed, + ); + assert!(!changed); + } + + #[test] + fn only_text_inputs_announce_their_selection() { + let paragraph = |selection| { + let mut nodes = selected(text_input(&["hello"]), selection); + nodes[0].1.set_role(Role::Paragraph); + nodes + }; + assert!(!compare( + paragraph(1..1), + paragraph(2..2), + only_selection_changed + )); + } } diff --git a/adapters/ios/src/text_input.rs b/adapters/ios/src/text_input.rs index 0f2c37aea..bbb466f5a 100644 --- a/adapters/ios/src/text_input.rs +++ b/adapters/ios/src/text_input.rs @@ -13,7 +13,7 @@ //! application's view while the node is being edited, and to an //! [`InactiveTextInput`] otherwise. -use accesskit::{Action, Role}; +use accesskit::{Action, ActionData, ActionRequest, Role, TextSelection}; use accesskit_consumer::{FullNodeId, NodeRef}; use objc2::{ ClassType, DeclaredClass, declare_class, msg_send, msg_send_id, @@ -34,7 +34,12 @@ use objc2_ui_kit::{ }; use std::{ops::Range, rc::Rc}; -use crate::{context::Context, filters::filter, node::PlatformNode, text::InactiveTextInput}; +use crate::{ + context::Context, + filters::filter, + node::PlatformNode, + text::{InactiveTextInput, TextRange}, +}; /// A private trait that native text fields don't have. Left unmasked, it makes /// VoiceOver say "empty line" when the input is tapped and put the caret at @@ -134,9 +139,19 @@ declare_class!( self.forward_edit_action(sel!(paste:), sender); } + // VoiceOver only announces a selection that changed by the time these + // return, so the application's view selects if it can. + + #[method(select:)] + fn select(&self, sender: Option<&AnyObject>) { + self.perform_selection_action(sel!(select:), sender, word_at_caret); + } + #[method(selectAll:)] fn select_all(&self, sender: Option<&AnyObject>) { - self.forward_edit_action(sel!(selectAll:), sender); + self.perform_selection_action(sel!(selectAll:), sender, |node| { + Some(node.document_range().to_text_selection()) + }); } #[method(delete:)] @@ -146,7 +161,15 @@ declare_class!( #[method(canPerformAction:withSender:)] fn can_perform_action(&self, action: Sel, sender: Option<&AnyObject>) -> bool { - unsafe { self.surrogate().canPerformAction_withSender(action, sender) } + let view = self + .active_view() + .filter(|view| view.respondsToSelector(action)); + match view { + Some(view) => unsafe { view.canPerformAction_withSender(action, sender) }, + None => self.can_select(action).unwrap_or_else(|| unsafe { + self.surrogate().canPerformAction_withSender(action, sender) + }), + } } } @@ -214,9 +237,15 @@ declare_class!( unsafe { self.text_input().selectedTextRange() } } + // Unless the node is being edited, the selection only changes once the + // application agrees to it. #[method(setSelectedTextRange:)] fn setSelectedTextRange(&self, range: Option<&UITextRange>) { - unsafe { self.text_input().setSelectedTextRange(range) } + if self.active_view().is_some() { + unsafe { self.text_input().setSelectedTextRange(range) } + } else if let Some(range) = range.and_then(TextRange::range) { + self.request_selection(|node| utf16_selection(node, range)); + } } #[method_id(markedTextRange)] @@ -469,18 +498,20 @@ impl TextInputNode { unsafe { msg_send_id![super(this), initWithAccessKitIvars: ivars, container: &*container] } } + fn active_view(&self) -> Option> { + self.resolve_with_context(|node, _, context| { + let active = context.active_text_input.borrow(); + let active = active + .as_ref() + .filter(|active| node.locate() == (active.node_id, active.tree_id))?; + active.view.load() + }) + .flatten() + } + /// The inactive stand-in is brought up to date first. fn surrogate(&self) -> Retained { - let active_view = self - .resolve_with_context(|node, _, context| { - let active = context.active_text_input.borrow(); - let active = active - .as_ref() - .filter(|active| node.locate() == (active.node_id, active.tree_id))?; - active.view.load() - }) - .flatten(); - if let Some(view) = active_view { + if let Some(view) = self.active_view() { return view; } @@ -499,6 +530,75 @@ impl TextInputNode { unsafe { Retained::cast(self.surrogate()) } } + fn request_selection(&self, selection: impl FnOnce(&NodeRef) -> Option) -> bool { + self.resolve_with_context(|node, tree, context| { + if !can_set_selection(node) { + return false; + } + let (Some(selection), Some((target_node, target_tree))) = + (selection(node), tree.state().locate_node(node.id())) + else { + return false; + }; + context.do_action(ActionRequest { + action: Action::SetTextSelection, + target_tree, + target_node, + data: Some(ActionData::SetTextSelection(selection)), + }); + true + }) + .unwrap_or(false) + } + + /// Offered when `UITextField` offers them. + fn can_select(&self, action: Sel) -> Option { + let is_select = action == sel!(select:); + if !is_select && action != sel!(selectAll:) { + return None; + } + if self.active_view().is_none() { + return Some(false); + } + let can_select = self.resolve(|node| { + if !can_set_selection(node) || node.document_range().is_degenerate() { + return false; + } + match node.text_selection() { + Some(selection) if is_select => selection.is_degenerate(), + Some(selection) => { + selection.to_text_selection() != node.document_range().to_text_selection() + } + None => !is_select, + } + }); + Some(can_select.unwrap_or(false)) + } + + fn perform_selection_action( + &self, + action: Sel, + sender: Option<&AnyObject>, + selection: impl FnOnce(&NodeRef) -> Option, + ) { + if self.active_view().is_some() && !self.forward_selection_action(action, sender) { + self.request_selection(selection); + } + } + + fn forward_selection_action(&self, action: Sel, sender: Option<&AnyObject>) -> bool { + let Some(view) = self + .active_view() + .filter(|view| view.respondsToSelector(action)) + else { + return false; + }; + unsafe { + let _: *mut AnyObject = msg_send![&*view, performSelector: action, withObject: sender]; + } + true + } + fn forward_edit_action(&self, action: Sel, sender: Option<&AnyObject>) { let surrogate = self.surrogate(); if surrogate.respondsToSelector(action) { @@ -510,7 +610,36 @@ impl TextInputNode { } } -fn contents(node: &NodeRef) -> (String, Option>) { +fn can_set_selection(node: &NodeRef) -> bool { + node.supports_text_ranges() && node.supports_action(Action::SetTextSelection, &filter) +} + +fn word_at_caret(node: &NodeRef) -> Option { + let caret = node.text_selection_focus()?; + let start = if caret.is_word_start() { + caret + } else { + caret.backward_to_word_start() + }; + // AccessKit's words run up to the next one, while UIKit's end before the + // whitespace that follows them. + let mut range = start.to_degenerate_range(); + range.set_end(start.forward_to_word_end()); + while !range.is_degenerate() && range.text().ends_with(char::is_whitespace) { + range.set_end(range.end().backward_to_character_start()); + } + Some(range.to_text_selection()) +} + +fn utf16_selection(node: &NodeRef, range: Range) -> Option { + let start = node.text_position_from_global_utf16_index(range.start)?; + let end = node.text_position_from_global_utf16_index(range.end)?; + let mut range = start.to_degenerate_range(); + range.set_end(end); + Some(range.to_text_selection()) +} + +pub(crate) fn contents(node: &NodeRef) -> (String, Option>) { if !node.supports_text_ranges() { return (node.value().unwrap_or_default(), None); } @@ -525,10 +654,10 @@ mod tests { use super::*; use accesskit::{Node, NodeId, TreeId, TreeInfo, TreeUpdate}; - fn is_needed_for(node: Node) -> bool { + fn with_root(nodes: Vec<(NodeId, Node)>, f: impl FnOnce(&NodeRef) -> R) -> R { let tree = accesskit_consumer::Tree::new( TreeUpdate { - nodes: vec![(NodeId(0), node)], + nodes, tree: Some(TreeInfo::new(NodeId(0))), tree_id: TreeId::ROOT, focus: NodeId(0), @@ -536,11 +665,57 @@ mod tests { false, ); let state = tree.state(); - TextInputNode::is_needed_for( - &state - .node_by_tree_local_id(NodeId(0), TreeId::ROOT) - .unwrap(), - ) + f(&state + .node_by_tree_local_id(NodeId(0), TreeId::ROOT) + .unwrap()) + } + + fn is_needed_for(node: Node) -> bool { + with_root(vec![(NodeId(0), node)], TextInputNode::is_needed_for) + } + + /// `runs` are (text, word starts) pairs, and the result (text run, + /// character index) pairs. + fn word_at(runs: &[(&str, &[u8])], caret: usize) -> Option<((u64, usize), (u64, usize))> { + let mut input = Node::new(Role::MultilineTextInput); + input.set_children((1..=runs.len() as u64).map(NodeId).collect::>()); + input.set_text_selection(TextSelection { + anchor: accesskit::TextPosition { + node: NodeId(1), + character_index: caret, + }, + focus: accesskit::TextPosition { + node: NodeId(1), + character_index: caret, + }, + }); + let mut nodes = vec![(NodeId(0), input)]; + for (index, (text, word_starts)) in runs.iter().enumerate() { + let mut run = Node::new(Role::TextRun); + run.set_value(*text); + run.set_character_lengths(text.chars().map(|c| c.len_utf8() as u8).collect::>()); + run.set_word_starts(*word_starts); + nodes.push((NodeId(index as u64 + 1), run)); + } + with_root(nodes, |node| { + let selection = word_at_caret(node)?; + let position = + |position: accesskit::TextPosition| (position.node.0, position.character_index); + Some((position(selection.anchor), position(selection.focus))) + }) + } + + #[test] + fn selected_words_leave_out_the_space_after_them() { + let runs: &[(&str, &[u8])] = &[("hello world", &[0, 6])]; + assert_eq!(word_at(runs, 2), Some(((1, 0), (1, 5)))); + assert_eq!(word_at(runs, 8), Some(((1, 6), (1, 11)))); + } + + #[test] + fn selected_words_leave_out_the_line_break_after_them() { + let runs: &[(&str, &[u8])] = &[("hello\n", &[0]), ("world", &[0])]; + assert_eq!(word_at(runs, 2), Some(((1, 0), (1, 5)))); } #[test] diff --git a/adapters/ios/tests/integration/text_input.rs b/adapters/ios/tests/integration/text_input.rs index 451fad349..381de4368 100644 --- a/adapters/ios/tests/integration/text_input.rs +++ b/adapters/ios/tests/integration/text_input.rs @@ -6,7 +6,7 @@ use std::{cell::RefCell, ffi::c_void, ops::Range, rc::Rc}; use accesskit::{ - Action, ActionHandler, ActionRequest, ActivationHandler, Node, NodeId, Rect, Role, + Action, ActionData, ActionHandler, ActionRequest, ActivationHandler, Node, NodeId, Rect, Role, TextDirection, TextSelection, TreeId, TreeInfo, TreeUpdate, }; use accesskit_ios::{Adapter, TextPosition, TextRange}; @@ -49,6 +49,7 @@ pub const TESTS: &[Test] = tests![ focus_is_redirected_to_the_edited_input, focus_is_not_redirected_to_the_input_voiceover_is_on, the_edited_input_can_be_set_before_activation, + selecting_a_range_asks_the_application, ]; const INPUT: NodeId = NodeId(0); @@ -553,3 +554,18 @@ fn inactive_positions_follow_points() { ); } } + +fn selecting_a_range_asks_the_application() { + let fixture = Fixture::new(input(Role::TextInput, "a😀b", None)); + let range = TextRange::new(mtm(), 1..3); + unsafe { fixture.text_input().setSelectedTextRange(Some(&range)) }; + let actions = fixture.actions.borrow(); + assert_eq!(actions.len(), 1); + assert_eq!(actions[0].action, Action::SetTextSelection); + let Some(ActionData::SetTextSelection(selection)) = &actions[0].data else { + panic!("no selection in {:?}", actions[0]); + }; + let position = |position: accesskit::TextPosition| (position.node, position.character_index); + assert_eq!(position(selection.anchor), (RUN, 1)); + assert_eq!(position(selection.focus), (RUN, 2)); +} From 05380300c11c608699952307daa13204893db942 Mon Sep 17 00:00:00 2001 From: Arnold Loubriat Date: Mon, 23 Nov 2026 00:47:29 +0100 Subject: [PATCH 4/4] Let the iOS example edit text with the keyboard --- adapters/ios/Cargo.toml | 10 +- .../{showcase.rs => showcase/main.rs} | 69 +- adapters/ios/examples/showcase/text_input.rs | 1064 +++++++++++++++++ example_common/src/lib.rs | 47 +- example_common/src/widgets/mod.rs | 7 +- example_common/src/widgets/text_input.rs | 213 +++- 6 files changed, 1360 insertions(+), 50 deletions(-) rename adapters/ios/examples/{showcase.rs => showcase/main.rs} (83%) create mode 100644 adapters/ios/examples/showcase/text_input.rs diff --git a/adapters/ios/Cargo.toml b/adapters/ios/Cargo.toml index 02d443a8e..c39c5dbd9 100644 --- a/adapters/ios/Cargo.toml +++ b/adapters/ios/Cargo.toml @@ -51,8 +51,14 @@ objc2-ui-kit = { version = "0.2.0", features = [ [dev-dependencies] example_common = { path = "../../example_common" } libtest-mimic = "0.8.2" -objc2-foundation = { version = "0.2.0", features = ["NSObjCRuntime", "NSRunLoop"] } +objc2-foundation = { version = "0.2.0", features = [ + "NSObjCRuntime", + "NSRange", + "NSRunLoop", + "NSZone", +] } objc2-ui-kit = { version = "0.2.0", features = [ + "NSText", "UIApplication", "UIColor", "UIControl", @@ -60,6 +66,8 @@ objc2-ui-kit = { version = "0.2.0", features = [ "UISceneOptions", "UISceneSession", "UITextField", + "UITextInput", + "UITextInputTraits", "UIWindowScene", ] } diff --git a/adapters/ios/examples/showcase.rs b/adapters/ios/examples/showcase/main.rs similarity index 83% rename from adapters/ios/examples/showcase.rs rename to adapters/ios/examples/showcase/main.rs index ab1a2d13e..c027be2db 100644 --- a/adapters/ios/examples/showcase.rs +++ b/adapters/ios/examples/showcase/main.rs @@ -1,8 +1,11 @@ +mod text_input; + use accesskit::{ - ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler, Size, TreeUpdate, Vec2, + Action, ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler, NodeId, Size, + TreeUpdate, Vec2, }; use accesskit_ios::Adapter; -use example_common::UiState; +use example_common::{KeyEvent, UiState, widgets::ImeEdit}; use objc2::{ ClassType, DeclaredClass, declare_class, msg_send, msg_send_id, mutability::MainThreadOnly, @@ -20,10 +23,11 @@ use objc2_ui_kit::{ UIView, UIViewAutoresizing, UIViewController, UIWindow, UIWindowScene, UIWindowSceneDelegate, }; use std::{ - cell::RefCell, + cell::{Cell, RefCell}, ffi::{CString, c_char, c_int, c_void}, ptr::{NonNull, null_mut}, }; +use text_input::TextInputView; // The handlers only hold weak references to the view, which owns the adapter, // which owns the handlers. @@ -77,6 +81,8 @@ struct ContentViewIvars { adapter: RefCell>, ui: RefCell, pending_actions: RefCell>, + text_input_view: RefCell>>, + show_keyboard: Cell, } declare_class!( @@ -151,6 +157,13 @@ declare_class!( let mut ui = self.ivars().ui.borrow_mut(); for request in &requests { ui.do_action(request); + if request.action == Action::Click + && ui + .focused_text_input() + .is_some_and(|input| input.id == request.target_node) + { + self.ivars().show_keyboard.set(true); + } } } self.after_input(); @@ -161,9 +174,15 @@ declare_class!( let processed = self.ivars().ui.borrow_mut().process_due_messages(); if processed { self.update(); + self.sync_keyboard(); } self.schedule_next_message(); } + + #[method(syncKeyboard)] + fn sync_keyboard_later(&self) { + self.sync_keyboard(); + } } ); @@ -173,6 +192,8 @@ impl ContentView { adapter: RefCell::new(None), ui: RefCell::new(UiState::new()), pending_actions: RefCell::new(Vec::new()), + text_input_view: RefCell::new(None), + show_keyboard: Cell::new(false), }); let this: Retained = unsafe { msg_send_id![super(this), initWithFrame: frame] }; @@ -194,8 +215,19 @@ impl ContentView { ShowcaseDeactivationHandler { view: weak }, ) }; + let text_input_view = TextInputView::new(mtm, &this, &adapter); *this.ivars().adapter.borrow_mut() = Some(adapter); + // Like Flutter's `FlutterTextInputViewAccessibilityHider`, so that + // VoiceOver doesn't see the text input twice. + let text_input_hider = unsafe { UIView::new(mtm) }; + unsafe { + let _: () = msg_send![&text_input_hider, setAccessibilityElementsHidden: true]; + this.addSubview(&text_input_hider); + } + unsafe { text_input_hider.addSubview(&text_input_view) }; + *this.ivars().text_input_view.borrow_mut() = Some(text_input_view); + this } @@ -234,6 +266,37 @@ impl ContentView { fn after_input(&self) { self.update(); self.schedule_next_message(); + self.sync_keyboard(); + } + + fn sync_keyboard(&self) { + let text_input_view = self.ivars().text_input_view.borrow().clone(); + if let Some(text_input_view) = text_input_view { + text_input_view.sync(self.ivars().show_keyboard.take()); + } + } + + fn edit_text(&self, id: NodeId, edits: &[ImeEdit]) { + { + let mut ui = self.ivars().ui.borrow_mut(); + for edit in edits { + ui.edit_text(id, edit); + } + } + self.after_keyboard_input(); + } + + fn handle_key(&self, event: KeyEvent) { + self.ivars().ui.borrow_mut().handle_key(event); + self.after_keyboard_input(); + } + + /// The keyboard is in the middle of a call into the text input view, so + /// focus changes have to wait for the run loop. + fn after_keyboard_input(&self) { + self.update(); + self.schedule_next_message(); + self.perform_after_delay(sel!(syncKeyboard), 0.0); } fn schedule_next_message(&self) { diff --git a/adapters/ios/examples/showcase/text_input.rs b/adapters/ios/examples/showcase/text_input.rs new file mode 100644 index 000000000..6930c49bb --- /dev/null +++ b/adapters/ios/examples/showcase/text_input.rs @@ -0,0 +1,1064 @@ +//! The view that the keyboard types into. Like Flutter's +//! `FlutterTextInputView`, it's hidden from VoiceOver, which should only see +//! the element of the text input. + +use example_common::{ + Key, KeyEvent, KeyState, Modifiers, + widgets::{ImeEdit, InputType, TextInputInfo, TextLayout}, +}; +use objc2::{ + ClassType, DeclaredClass, declare_class, msg_send, msg_send_id, + mutability::MainThreadOnly, + rc::{Retained, WeakId}, + runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject, Sel}, + sel, +}; +use objc2_foundation::{ + CGPoint, CGRect, CGSize, MainThreadMarker, NSArray, NSAttributedStringKey, NSComparisonResult, + NSDictionary, NSInteger, NSRange, NSString, +}; +use objc2_ui_kit::{ + NSWritingDirection, UIKeyInput, UIKeyboardType, UIResponder, UIReturnKeyType, + UITextAutocapitalizationType, UITextAutocorrectionType, UITextInput, UITextInputDelegate, + UITextInputTokenizer, UITextInputTraits, UITextLayoutDirection, UITextPosition, UITextRange, + UITextSelectionRect, UITextStorageDirection, UIView, +}; +use std::{ + cell::{Cell, OnceCell, RefCell}, + ffi::c_void, + ops::Range, + ptr::null_mut, +}; + +use super::ContentView; +use accesskit::{NodeId, Point, Rect, TreeId}; +use accesskit_ios::{Adapter, TextPosition, TextRange, TextSelectionRect, TextTokenizer}; + +pub(crate) struct TextInputViewIvars { + content_view: WeakId, + input_delegate: RefCell>>>, + tokenizer: OnceCell>, + /// Like Flutter's `FlutterTextInputView`, answer from a copy, so that the + /// input system can be told about a change before it's made. It keeps + /// editing this input even once another widget is focused. + reported: RefCell>, + deleted_character: RefCell>>, + accessibility_enabled: Cell, +} + +/// Following Flutter, this keeps VoiceOver from focusing the view while the +/// accessibility tree is updated as editing starts. +const ACCESSIBILITY_ENABLING_DELAY: f64 = 0.5; + +const PASSWORD_MASK: &str = "\u{2022}"; + +declare_class!( + pub(crate) struct TextInputView; + + unsafe impl ClassType for TextInputView { + #[inherits(UIResponder, NSObject)] + type Super = UIView; + type Mutability = MainThreadOnly; + const NAME: &'static str = "AccessKitExampleTextInputView"; + } + + impl DeclaredClass for TextInputView { + type Ivars = TextInputViewIvars; + } + + unsafe impl NSObjectProtocol for TextInputView {} + + unsafe impl TextInputView { + #[method(canBecomeFirstResponder)] + fn can_become_first_responder(&self) -> bool { + true + } + + // Like Flutter's `FlutterTextInputView`, editing ends however the + // keyboard goes away, for example when VoiceOver dismisses it. The + // input system finishes its last edits while resigning. + #[method(resignFirstResponder)] + fn resign_first_responder(&self) -> bool { + let resigned: bool = unsafe { msg_send![super(self), resignFirstResponder] }; + if resigned { + self.disable_accessibility(); + self.set_edited_node(None); + *self.ivars().reported.borrow_mut() = None; + *self.ivars().deleted_character.borrow_mut() = None; + } + resigned + } + + // Though hidden, this view is what assistive technologies read while + // it edits. + #[method_id(accessibilityValue)] + fn accessibility_value(&self) -> Option> { + if self.input_type() == Some(InputType::Password) { + Some(NSString::from_str(&PASSWORD_MASK.repeat(self.utf16_len()))) + } else { + unsafe { msg_send_id![super(self), accessibilityValue] } + } + } + + #[method(accessibilityElementsHidden)] + fn accessibility_elements_hidden(&self) -> bool { + !self.ivars().accessibility_enabled.get() + } + + #[method(enableAccessibility)] + fn enable_accessibility(&self) { + if unsafe { self.isFirstResponder() } { + self.ivars().accessibility_enabled.set(true); + } + } + + // Like `UITextField`, the selection changes before these return, so + // VoiceOver can announce it. + + #[method(select:)] + fn select(&self, _sender: Option<&AnyObject>) { + if let Some(word) = self.input().and_then(|input| word_at_caret(&input)) { + self.set_selection(word); + } + } + + #[method(selectAll:)] + fn select_all(&self, _sender: Option<&AnyObject>) { + self.set_selection(0..self.utf16_len()); + } + + #[method(canPerformAction:withSender:)] + fn can_perform_action(&self, action: Sel, sender: Option<&AnyObject>) -> bool { + let input = self.input(); + if action == sel!(select:) { + input.is_some_and(|input| { + utf16_selection(&input).is_empty() && word_at_caret(&input).is_some() + }) + } else if action == sel!(selectAll:) { + input.is_some_and(|input| utf16_selection(&input) != (0..utf16(&input.text).len())) + && self.utf16_len() > 0 + } else { + unsafe { msg_send![super(self), canPerformAction: action, withSender: sender] } + } + } + + // VoiceOver should be on the element of the text input instead. The + // element also forwards this when VoiceOver lands on it, in which + // case VoiceOver isn't actually here. + #[method(accessibilityElementDidBecomeFocused)] + fn accessibility_element_did_become_focused(&self) { + let is_focused: bool = unsafe { msg_send![self, accessibilityElementIsFocused] }; + let content_view = self + .ivars() + .content_view + .load() + .filter(|_| is_focused); + let Some(content_view) = content_view else { + return; + }; + let events = content_view + .ivars() + .adapter + .borrow() + .as_ref() + .and_then(Adapter::redirect_accessibility_focus); + if let Some(events) = events { + events.raise(); + } + } + } + + unsafe impl UITextInputTraits for TextInputView { + #[method(keyboardType)] + fn keyboard_type(&self) -> UIKeyboardType { + match self.input_type() { + Some(InputType::Email) => UIKeyboardType::EmailAddress, + _ => UIKeyboardType::Default, + } + } + + #[method(isSecureTextEntry)] + fn is_secure_text_entry(&self) -> bool { + self.input_type() == Some(InputType::Password) + } + + #[method(autocapitalizationType)] + fn autocapitalization_type(&self) -> UITextAutocapitalizationType { + match self.input_type() { + Some(InputType::Email | InputType::Password) => { + UITextAutocapitalizationType::None + } + _ => UITextAutocapitalizationType::Sentences, + } + } + + #[method(autocorrectionType)] + fn autocorrection_type(&self) -> UITextAutocorrectionType { + match self.input_type() { + Some(InputType::Email | InputType::Password) => UITextAutocorrectionType::No, + _ => UITextAutocorrectionType::Default, + } + } + + #[method(returnKeyType)] + fn return_key_type(&self) -> UIReturnKeyType { + match self.input() { + Some(input) if input.input_type == InputType::Multiline => { + UIReturnKeyType::UIReturnKeyDefault + } + Some(input) if input.can_submit => UIReturnKeyType::UIReturnKeyDone, + _ => UIReturnKeyType::UIReturnKeyNext, + } + } + } + + #[allow(non_snake_case)] + unsafe impl UIKeyInput for TextInputView { + #[method(hasText)] + fn hasText(&self) -> bool { + self.input() + .is_some_and(|input| !input.text.is_empty()) + } + + // Like Flutter, work around iOS sending only the first half of a + // character that was just deleted, such as an emoji, when it's typed + // again (https://github.com/flutter/flutter/issues/111494). + #[method(insertText:)] + fn insertText(&self, text: &NSString) { + let Some(input) = self.input() else { + return; + }; + let mut text = utf16_units(text); + let deleted = self.ivars().deleted_character.take(); + if let (Some(deleted), [unit]) = (deleted, text.as_slice()) { + if is_surrogate(*unit) && deleted.first() == Some(unit) { + text = deleted; + } + } + let text = String::from_utf16_lossy(&text); + if text == "\n" && input.input_type != InputType::Multiline { + if input.can_submit { + self.edit(&[ImeEdit::Submit]); + } else if let Some(content_view) = self.ivars().content_view.load() { + content_view.handle_key(KeyEvent { + key: Key::Tab, + state: KeyState::Pressed, + modifiers: Modifiers::default(), + }); + } + return; + } + let range = input + .composition + .clone() + .unwrap_or_else(|| byte_selection(&input)); + self.replace(range, text); + } + + #[method(deleteBackward)] + fn deleteBackward(&self) { + let Some(input) = self.input() else { + return; + }; + match input.composition.clone() { + Some(composition) => self.replace(composition, String::new()), + None => { + let deleted = deleted_character(&input) + .filter(|text| text.iter().any(|unit| is_surrogate(*unit))); + *self.ivars().deleted_character.borrow_mut() = deleted; + self.press(Key::Backspace); + } + } + } + } + + #[allow(non_snake_case)] + unsafe impl UITextInput for TextInputView { + #[method_id(textInRange:)] + fn textInRange(&self, range: Option<&UITextRange>) -> Option> { + range.and_then(|range| self.text_in_range(range)) + } + + #[method(replaceRange:withText:)] + fn replaceRange_withText(&self, range: Option<&UITextRange>, text: &NSString) { + let Some(range) = range.and_then(TextRange::range) else { + return; + }; + let Some(input) = self.input() else { + return; + }; + self.replace(byte_range(&input.text, range), string(text)); + } + + #[method_id(selectedTextRange)] + fn selectedTextRange(&self) -> Option> { + self.input() + .map(|input| self.range(utf16_selection(&input))) + } + + #[method(setSelectedTextRange:)] + fn setSelectedTextRange(&self, range: Option<&UITextRange>) { + if let Some(range) = range.and_then(TextRange::range) { + self.set_selection(range); + } + } + + #[method_id(markedTextRange)] + fn markedTextRange(&self) -> Option> { + self.input() + .and_then(|input| utf16_composition(&input)) + .map(|composition| self.range(composition)) + } + + #[method_id(markedTextStyle)] + fn markedTextStyle( + &self, + ) -> Option>> { + None + } + + #[method(setMarkedTextStyle:)] + fn setMarkedTextStyle( + &self, + _style: Option<&NSDictionary>, + ) { + } + + #[method(setMarkedText:selectedRange:)] + fn setMarkedText_selectedRange( + &self, + marked_text: Option<&NSString>, + selected_range: NSRange, + ) { + let Some(input) = self.input() else { + return; + }; + let range = input + .composition + .clone() + .unwrap_or_else(|| byte_selection(&input)); + let text = marked_text.map(string).unwrap_or_default(); + let start = range.start; + let selection = byte_range( + &text, + selected_range.location..selected_range.location + selected_range.length, + ); + let composition = (!text.is_empty()).then(|| start..start + text.len()); + self.edit(&[ + ImeEdit::Replace { range, text }, + ImeEdit::SetComposition(composition), + ImeEdit::SetSelection { + anchor: start + selection.start, + focus: start + selection.end, + }, + ]); + } + + #[method(unmarkText)] + fn unmarkText(&self) { + self.edit(&[ImeEdit::SetComposition(None)]); + } + + #[method_id(beginningOfDocument)] + fn beginningOfDocument(&self) -> Retained { + self.position(0) + } + + #[method_id(endOfDocument)] + fn endOfDocument(&self) -> Retained { + self.position(self.utf16_len()) + } + + #[method_id(textRangeFromPosition:toPosition:)] + fn textRangeFromPosition_toPosition( + &self, + from_position: Option<&UITextPosition>, + to_position: Option<&UITextPosition>, + ) -> Option> { + let from = from_position.and_then(TextPosition::index); + let to = to_position.and_then(TextPosition::index); + from.zip(to) + .map(|(from, to)| self.range(from.min(to)..from.max(to))) + } + + // UIKit's tokenizer finds characters by stepping over code units, even + // in the middle of a character. + #[method_id(positionFromPosition:offset:)] + fn positionFromPosition_offset( + &self, + position: Option<&UITextPosition>, + offset: NSInteger, + ) -> Option> { + let index = position.and_then(TextPosition::index); + let index = index.and_then(|index| index.checked_add_signed(offset)); + index + .filter(|index| *index <= self.utf16_len()) + .map(|index| self.position(index)) + } + + #[method_id(positionFromPosition:inDirection:offset:)] + fn positionFromPosition_inDirection_offset( + &self, + position: Option<&UITextPosition>, + direction: UITextLayoutDirection, + offset: NSInteger, + ) -> Option> { + position.and_then(|position| match direction { + UITextLayoutDirection::Up => self.vertical_position(position, -offset), + UITextLayoutDirection::Down => self.vertical_position(position, offset), + UITextLayoutDirection::Left => self.position_by_characters(position, -offset), + _ => self.position_by_characters(position, offset), + }) + } + + #[method(comparePosition:toPosition:)] + fn comparePosition_toPosition( + &self, + position: Option<&UITextPosition>, + other: Option<&UITextPosition>, + ) -> NSComparisonResult { + let (Some(position), Some(other)) = ( + position.and_then(TextPosition::index), + other.and_then(TextPosition::index), + ) else { + return NSComparisonResult::Same; + }; + position.cmp(&other).into() + } + + #[method(offsetFromPosition:toPosition:)] + fn offsetFromPosition_toPosition( + &self, + from: Option<&UITextPosition>, + to_position: Option<&UITextPosition>, + ) -> NSInteger { + let (Some(from), Some(to)) = ( + from.and_then(TextPosition::index), + to_position.and_then(TextPosition::index), + ) else { + return 0; + }; + to as NSInteger - from as NSInteger + } + + #[method_id(inputDelegate)] + fn inputDelegate(&self) -> Option>> { + self.input_delegate() + } + + #[method(setInputDelegate:)] + fn setInputDelegate(&self, delegate: Option<&ProtocolObject>) { + *self.ivars().input_delegate.borrow_mut() = delegate.map(retain_delegate); + } + + #[method_id(tokenizer)] + fn tokenizer(&self) -> Retained> { + let tokenizer = self.ivars().tokenizer.get().expect("set by `new`").clone(); + ProtocolObject::from_retained(Retained::into_super(tokenizer)) + } + + #[method_id(positionWithinRange:farthestInDirection:)] + fn positionWithinRange_farthestInDirection( + &self, + range: Option<&UITextRange>, + direction: UITextLayoutDirection, + ) -> Option> { + range.and_then(TextRange::range).map(|range| { + let index = match direction { + UITextLayoutDirection::Left | UITextLayoutDirection::Up => range.start, + _ => range.end, + }; + self.position(index) + }) + } + + #[method_id(characterRangeByExtendingPosition:inDirection:)] + fn characterRangeByExtendingPosition_inDirection( + &self, + position: Option<&UITextPosition>, + direction: UITextLayoutDirection, + ) -> Option> { + let index = position.and_then(TextPosition::index); + index.and_then(|index| self.character_range_by_extending(index, direction)) + } + + #[method(baseWritingDirectionForPosition:inDirection:)] + fn baseWritingDirectionForPosition_inDirection( + &self, + _position: Option<&UITextPosition>, + _direction: UITextStorageDirection, + ) -> NSWritingDirection { + NSWritingDirection::Natural + } + + #[method(setBaseWritingDirection:forRange:)] + fn setBaseWritingDirection_forRange( + &self, + _writing_direction: NSWritingDirection, + _range: Option<&UITextRange>, + ) { + } + + #[method(firstRectForRange:)] + fn firstRectForRange(&self, range: Option<&UITextRange>) -> CGRect { + let range = range.and_then(TextRange::range); + range + .and_then(|range| self.rects(range).into_iter().next()) + .unwrap_or(CGRect::ZERO) + } + + #[method(caretRectForPosition:)] + fn caretRectForPosition(&self, position: Option<&UITextPosition>) -> CGRect { + let index = position.and_then(TextPosition::index); + index + .and_then(|index| self.rects(index..index).into_iter().next()) + .unwrap_or(CGRect::ZERO) + } + + #[method_id(selectionRectsForRange:)] + fn selectionRectsForRange( + &self, + range: Option<&UITextRange>, + ) -> Retained> { + let rects = range.and_then(TextRange::range).map_or_else(Vec::new, |range| { + self.rects(range) + }); + TextSelectionRect::array(MainThreadMarker::from(self), &rects) + } + + #[method_id(closestPositionToPoint:)] + fn closestPositionToPoint(&self, point: CGPoint) -> Option> { + self.closest_position(point, 0..self.utf16_len()) + } + + #[method_id(closestPositionToPoint:withinRange:)] + fn closestPositionToPoint_withinRange( + &self, + point: CGPoint, + range: Option<&UITextRange>, + ) -> Option> { + let range = range.and_then(TextRange::range); + range.and_then(|range| self.closest_position(point, range)) + } + + #[method_id(characterRangeAtPoint:)] + fn characterRangeAtPoint(&self, point: CGPoint) -> Option> { + self.character_range_at(point) + } + } +); + +impl TextInputView { + pub(crate) fn new( + mtm: MainThreadMarker, + content_view: &ContentView, + adapter: &Adapter, + ) -> Retained { + let this = mtm.alloc::().set_ivars(TextInputViewIvars { + content_view: WeakId::new(content_view), + input_delegate: RefCell::new(None), + tokenizer: OnceCell::new(), + reported: RefCell::new(None), + deleted_character: RefCell::new(None), + accessibility_enabled: Cell::new(false), + }); + // The input system ignores a view without a size. + let frame = CGRect::new(CGPoint::ZERO, CGSize::new(1.0, 1.0)); + let this: Retained = unsafe { msg_send_id![super(this), initWithFrame: frame] }; + // SAFETY: This view conforms to `UITextInput`. + let tokenizer = unsafe { adapter.text_tokenizer(Retained::as_ptr(&this) as *mut c_void) }; + let _ = this.ivars().tokenizer.set(tokenizer); + this + } + + fn input(&self) -> Option { + self.ivars().reported.borrow().clone() + } + + fn focused_text_input(&self) -> Option { + let content_view = self.ivars().content_view.load()?; + content_view.ivars().ui.borrow().focused_text_input() + } + + fn input_type(&self) -> Option { + self.input().map(|input| input.input_type) + } + + fn utf16_len(&self) -> usize { + self.input().map_or(0, |input| utf16(&input.text).len()) + } + + fn position(&self, index: usize) -> Retained { + Retained::into_super(TextPosition::new(MainThreadMarker::from(self), index)) + } + + fn range(&self, range: Range) -> Retained { + Retained::into_super(TextRange::new(MainThreadMarker::from(self), range)) + } + + fn text_in_range(&self, range: &UITextRange) -> Option> { + let range = TextRange::range(range)?; + let text = utf16(&self.input()?.text); + let text = text.get(range)?; + Some(NSString::from_str(&String::from_utf16_lossy(text))) + } + + fn character_range_by_extending( + &self, + index: usize, + direction: UITextLayoutDirection, + ) -> Option> { + let lines = match direction { + UITextLayoutDirection::Up => -1, + UITextLayoutDirection::Down => 1, + _ => 0, + }; + if lines != 0 { + let other = self.vertical_index(index, lines)?; + return Some(self.range(index.min(other)..index.max(other))); + } + let text = NSString::from_str(&self.input()?.text); + if index > text.length() { + return None; + } + let range = match direction { + UITextLayoutDirection::Left if index > 0 => { + composed_character_range(&text, index - 1).start..index + } + UITextLayoutDirection::Left => index..index, + _ if index < text.length() => index..composed_character_range(&text, index).end, + _ => index..index, + }; + Some(self.range(range)) + } + + fn position_by_characters( + &self, + position: &UITextPosition, + offset: NSInteger, + ) -> Option> { + let text = NSString::from_str(&self.input()?.text); + let mut index = TextPosition::index(position)?; + if index > text.length() { + return None; + } + for _ in 0..offset.unsigned_abs() { + index = if offset > 0 { + (index < text.length()).then(|| composed_character_range(&text, index).end)? + } else { + (index > 0).then(|| composed_character_range(&text, index - 1).start)? + }; + } + Some(self.position(index)) + } + + fn vertical_position( + &self, + position: &UITextPosition, + lines: NSInteger, + ) -> Option> { + let index = TextPosition::index(position)?; + Some(self.position(self.vertical_index(index, lines)?)) + } + + fn vertical_index(&self, index: usize, lines: NSInteger) -> Option { + let (input, layout) = self.layout()?; + if index > utf16(&input.text).len() { + return None; + } + let offset = layout.vertical_offset(byte_offset(&input.text, index), lines); + Some(utf16_offset(&input.text, offset)) + } + + fn layout(&self) -> Option<(TextInputInfo, TextLayout)> { + let input = self.input()?; + let content_view = self.ivars().content_view.load()?; + let ui = content_view.ivars().ui.borrow(); + // The input system can ask about the text it was last told about, + // before `sync` tells it about the UI's newer text. + if ui.text_input(input.id)?.text != input.text { + return None; + } + let layout = ui.text_layout(input.id)?; + Some((input, layout)) + } + + fn rects(&self, range: Range) -> Vec { + let Some((input, layout)) = self.layout() else { + return Vec::new(); + }; + let range = byte_range(&input.text, range); + let rects = if range.is_empty() { + vec![layout.caret_bounds(range.start)] + } else { + layout.range_bounds(range) + }; + rects + .into_iter() + .filter_map(|rect| self.view_rect(rect)) + .collect() + } + + fn closest_position( + &self, + point: CGPoint, + range: Range, + ) -> Option> { + let (input, layout) = self.layout()?; + let range = byte_range(&input.text, range); + let offset = layout.offset_at_point(self.layout_point(point)?, range); + Some(self.position(utf16_offset(&input.text, offset))) + } + + fn character_range_at(&self, point: CGPoint) -> Option> { + let (input, layout) = self.layout()?; + let range = layout.character_at_point(self.layout_point(point)?)?; + Some(self.range(utf16_range(&input.text, range))) + } + + fn view_rect(&self, rect: Rect) -> Option { + let content_view = self.ivars().content_view.load()?; + let scale = content_view.contentScaleFactor(); + let rect = CGRect::new( + CGPoint::new(rect.x0 / scale, rect.y0 / scale), + CGSize::new(rect.width() / scale, rect.height() / scale), + ); + Some(unsafe { self.convertRect_fromView(rect, Some(&content_view)) }) + } + + fn layout_point(&self, point: CGPoint) -> Option { + let content_view = self.ivars().content_view.load()?; + let scale = content_view.contentScaleFactor(); + let point = unsafe { self.convertPoint_toView(point, Some(&content_view)) }; + Some(Point::new(point.x * scale, point.y * scale)) + } + + fn input_delegate(&self) -> Option>> { + self.ivars() + .input_delegate + .borrow() + .as_deref() + .map(retain_delegate) + } + + /// Tells the input system, as Apple does even when an assistive + /// technology is the one selecting. + fn set_selection(&self, range: Range) { + let Some(input) = self.input() else { + return; + }; + let range = round_away_from_caret(&input, range); + let range = byte_range(&input.text, range); + let this: &ProtocolObject = ProtocolObject::from_ref(self); + let delegate = self.input_delegate(); + if let Some(delegate) = &delegate { + unsafe { delegate.selectionWillChange(Some(this)) }; + } + self.edit(&[ImeEdit::SetSelection { + anchor: range.start, + focus: range.end, + }]); + if let Some(delegate) = &delegate { + unsafe { delegate.selectionDidChange(Some(this)) }; + } + } + + fn edit(&self, edits: &[ImeEdit]) { + let (Some(content_view), Some(input)) = (self.ivars().content_view.load(), self.input()) + else { + return; + }; + content_view.edit_text(input.id, edits); + let input = content_view.ivars().ui.borrow().text_input(input.id); + *self.ivars().reported.borrow_mut() = input; + } + + fn replace(&self, byte_range: Range, text: String) { + let caret = byte_range.start + text.len(); + self.edit(&[ + ImeEdit::Replace { + range: byte_range, + text, + }, + ImeEdit::SetComposition(None), + ImeEdit::SetSelection { + anchor: caret, + focus: caret, + }, + ]); + } + + fn press(&self, key: Key) { + let (Some(content_view), Some(input)) = (self.ivars().content_view.load(), self.input()) + else { + return; + }; + if self.focused_text_input().map(|focused| focused.id) != Some(input.id) { + return; + } + content_view.handle_key(KeyEvent { + key, + state: KeyState::Pressed, + modifiers: Modifiers::default(), + }); + let input = content_view.ivars().ui.borrow().text_input(input.id); + *self.ivars().reported.borrow_mut() = input; + } + + pub(crate) fn sync(&self, show_keyboard: bool) { + let input = self.focused_text_input(); + let is_first_responder = unsafe { self.isFirstResponder() }; + let Some(input) = input else { + if is_first_responder { + unsafe { self.resignFirstResponder() }; + } + *self.ivars().reported.borrow_mut() = None; + return; + }; + if !is_first_responder { + if show_keyboard { + let id = input.id; + *self.ivars().reported.borrow_mut() = Some(input); + if unsafe { self.becomeFirstResponder() } { + self.move_caret_to_end(); + self.disable_accessibility(); + unsafe { + let _: () = msg_send![ + self, + performSelector: sel!(enableAccessibility), + withObject: null_mut::(), + afterDelay: ACCESSIBILITY_ENABLING_DELAY, + ]; + } + self.set_edited_node(Some(id)); + } + } + return; + } + + let Some(reported) = self.input() else { + *self.ivars().reported.borrow_mut() = Some(input); + return; + }; + let is_other_input = reported.id != input.id; + if is_other_input && reported.composition.is_some() { + // The input system thinks the composition is over once it is + // editing another text input. + if let Some(content_view) = self.ivars().content_view.load() { + content_view.edit_text(reported.id, &[ImeEdit::SetComposition(None)]); + } + } + let is_same_input = reported.id == input.id + && reported.input_type == input.input_type + && reported.can_submit == input.can_submit; + let text_changed = !is_same_input + || reported.text != input.text + || reported.composition != input.composition; + let selection_changed = utf16_selection(&reported) != utf16_selection(&input); + + // The input system compares what the view says before and after, as + // VoiceOver does to announce what was selected or unselected, so the + // view must only say what changed in between. + let this: &ProtocolObject = ProtocolObject::from_ref(self); + let delegate = self.input_delegate(); + if let Some(delegate) = &delegate { + unsafe { + if text_changed { + delegate.textWillChange(Some(this)); + } + if selection_changed { + delegate.selectionWillChange(Some(this)); + } + } + } + let id = input.id; + *self.ivars().reported.borrow_mut() = Some(input); + if !is_same_input { + self.set_edited_node(Some(id)); + } + if let Some(delegate) = &delegate { + unsafe { + if selection_changed { + delegate.selectionDidChange(Some(this)); + } + if text_changed { + delegate.textDidChange(Some(this)); + } + } + } + if !is_same_input { + // The keyboard only picks up new traits, like those of a password + // being shown, when reloaded. + unsafe { self.reloadInputViews() }; + } + if is_other_input { + self.move_caret_to_end(); + } + } + + fn move_caret_to_end(&self) { + let len = self.utf16_len(); + self.set_selection(len..len); + } +} + +impl TextInputView { + fn disable_accessibility(&self) { + self.ivars().accessibility_enabled.set(false); + unsafe { + let _: () = msg_send![ + NSObject::class(), + cancelPreviousPerformRequestsWithTarget: self, + selector: sel!(enableAccessibility), + object: null_mut::(), + ]; + } + } + + fn set_edited_node(&self, node_id: Option) { + let Some(content_view) = self.ivars().content_view.load() else { + return; + }; + let adapter = content_view.ivars().adapter.borrow(); + let Some(adapter) = &*adapter else { + return; + }; + match node_id { + // SAFETY: This view conforms to `UITextInput`. + Some(node_id) => unsafe { + adapter.set_text_input_view( + self as *const Self as *mut c_void, + node_id, + TreeId::ROOT, + ) + }, + None => adapter.clear_text_input_view(), + } + } +} + +fn retain_delegate( + delegate: &ProtocolObject, +) -> Retained> { + // SAFETY: The pointer comes from a valid reference, so it isn't null. + unsafe { Retained::retain(delegate as *const _ as *mut _) }.unwrap() +} + +fn word_at_caret(input: &TextInputInfo) -> Option> { + let caret = utf16_offset(&input.text, input.selection_focus); + let mut words = Vec::new(); + let mut index = 0; + let mut start = None; + for c in input.text.chars() { + match (c.is_alphanumeric(), start) { + (true, None) => start = Some(index), + (false, Some(word_start)) => { + words.push(word_start..index); + start = None; + } + _ => (), + } + index += c.len_utf16(); + } + words.extend(start.map(|word_start| word_start..index)); + words + .into_iter() + .find(|word| word.start <= caret && caret <= word.end) +} + +fn utf16(text: &str) -> Vec { + text.encode_utf16().collect() +} + +/// The UTF-16 code units of `text`, which, unlike `NSString::to_string`, +/// copes with half of a character. +fn utf16_units(text: &NSString) -> Vec { + (0..text.length()) + .map(|index| unsafe { text.characterAtIndex(index) }) + .collect() +} + +fn string(text: &NSString) -> String { + String::from_utf16_lossy(&utf16_units(text)) +} + +fn is_surrogate(unit: u16) -> bool { + (0xd800..=0xdfff).contains(&unit) +} + +fn composed_character_range(text: &NSString, index: usize) -> Range { + let range = unsafe { text.rangeOfComposedCharacterSequenceAtIndex(index) }; + range.location..range.location + range.length +} + +/// Like Flutter, only the first character, since iOS only breaks the +/// insertion of a single one. +fn deleted_character(input: &TextInputInfo) -> Option> { + let text = utf16(&input.text); + let ns_text = NSString::from_str(&input.text); + let selection = utf16_selection(input); + let range = if selection.is_empty() { + let caret = selection.start.checked_sub(1)?; + composed_character_range(&ns_text, caret).start..selection.end + } else { + let character = composed_character_range(&ns_text, selection.start); + character.start..character.end.min(selection.end) + }; + text.get(range).map(<[u16]>::to_vec) +} + +fn utf16_offset(text: &str, offset: usize) -> usize { + text[..offset].encode_utf16().count() +} + +/// Rounded down to a code point boundary. +fn byte_offset(text: &str, utf16_offset: usize) -> usize { + let mut utf16_length = 0; + text.char_indices() + .find(|(_, c)| { + utf16_length += c.len_utf16(); + utf16_length > utf16_offset + }) + .map_or(text.len(), |(offset, _)| offset) +} + +// VoiceOver moves through a password by code units, so rounding toward the +// caret would keep it from ever crossing an emoji. +fn round_away_from_caret(input: &TextInputInfo, range: Range) -> Range { + let text = NSString::from_str(&input.text); + let caret = utf16_selection(input).start; + let round = |index: usize| { + if index >= text.length() { + return index; + } + let character = composed_character_range(&text, index); + if index == character.start || index < caret { + character.start + } else { + character.end + } + }; + round(range.start)..round(range.end) +} + +fn byte_range(text: &str, range: Range) -> Range { + byte_offset(text, range.start)..byte_offset(text, range.end) +} + +fn utf16_range(text: &str, range: Range) -> Range { + utf16_offset(text, range.start)..utf16_offset(text, range.end) +} + +fn byte_selection(input: &TextInputInfo) -> Range { + let (anchor, focus) = (input.selection_anchor, input.selection_focus); + anchor.min(focus)..anchor.max(focus) +} + +fn utf16_selection(input: &TextInputInfo) -> Range { + utf16_range(&input.text, byte_selection(input)) +} + +fn utf16_composition(input: &TextInputInfo) -> Option> { + let composition = input.composition.clone()?; + Some(utf16_range(&input.text, composition)) +} diff --git a/example_common/src/lib.rs b/example_common/src/lib.rs index cc3b293b7..3f6ca0151 100644 --- a/example_common/src/lib.rs +++ b/example_common/src/lib.rs @@ -17,7 +17,8 @@ use std::{ time::{Duration, Instant}, }; use widgets::{ - ImeEdit, Response, ScrollPosition, TextInputInfo, TextInputState, Widget, Window, bubble, visit, + ImeEdit, Response, ScrollPosition, TextInputInfo, TextInputState, TextLayout, Widget, Window, + bubble, visit, }; /// The title of the example's window. @@ -39,6 +40,12 @@ struct Viewport { size: Size, } +impl Viewport { + fn logical_to_window(&self) -> Affine { + Affine::translate(self.safe_area_inset) * Affine::scale(self.scale_factor) + } +} + #[derive(Clone, Debug)] enum Message { ViewportChanged(Viewport), @@ -112,10 +119,7 @@ impl Model { if let Some(viewport) = &self.viewport { root = root .with_bounds(Rect::from_origin_size((0.0, 0.0), viewport.size)) - .with_transform( - Affine::translate(viewport.safe_area_inset) - * Affine::scale(viewport.scale_factor), - ); + .with_transform(viewport.logical_to_window()); } let size = self.viewport.map_or(DEFAULT_SIZE, |viewport| viewport.size); let root = match &self.screen { @@ -266,22 +270,47 @@ impl UiState { /// The state of the focused text input, if any. pub fn focused_text_input(&self) -> Option { - let focus = self.model.focus; + self.text_input(self.model.focus) + } + + /// The state of the text input `id`, if it is one. + pub fn text_input(&self, id: NodeId) -> Option { let view = self.model.view(); let mut result = None; visit(&view.root, &mut |widget| { - if widget.id() == focus { + if widget.id() == id { result = widget.text_input(); } }); result } + /// Where the characters of the text input `id` are, if it is one. + pub fn text_layout(&self, id: NodeId) -> Option { + let view = self.model.view(); + let mut result = None; + visit(&view.root, &mut |widget| { + if widget.id() == id { + result = widget.text_layout(); + } + }); + let transform = self + .model + .viewport + .map_or(Affine::IDENTITY, |viewport| viewport.logical_to_window()); + result.map(|layout| layout.with_transform(transform)) + } + /// Handles an edit from the platform's input method. Returns whether it /// was handled. pub fn edit_focused_text(&mut self, edit: &ImeEdit) -> bool { - let focus = self.model.focus; - let response = bubble(&self.model.view().root, focus, &mut |widget| { + self.edit_text(self.model.focus, edit) + } + + /// Handles an edit to the text input `id`, which an input method may + /// still be making after focus moved on. + pub fn edit_text(&mut self, id: NodeId, edit: &ImeEdit) -> bool { + let response = bubble(&self.model.view().root, id, &mut |widget| { widget.on_ime_edit(edit) }); self.handle_response(response) diff --git a/example_common/src/widgets/mod.rs b/example_common/src/widgets/mod.rs index 4ac205288..9dae97401 100644 --- a/example_common/src/widgets/mod.rs +++ b/example_common/src/widgets/mod.rs @@ -14,7 +14,7 @@ pub use label::Label; pub use list_box::{ListBox, ListItem}; pub use scroll_bar::{ScrollBar, ScrollPosition}; pub use spinner::Spinner; -pub use text_input::{ImeEdit, InputType, TextInput, TextInputInfo, TextInputState}; +pub use text_input::{ImeEdit, InputType, TextInput, TextInputInfo, TextInputState, TextLayout}; pub use toggle_button::ToggleButton; pub use window::Window; @@ -71,6 +71,11 @@ pub trait Widget { None } + /// Where the characters of the widget are, if it is a text input. + fn text_layout(&self) -> Option { + None + } + /// Handles an edit from the platform's input method when the widget has /// focus. fn on_ime_edit(&self, _edit: &ImeEdit) -> Response { diff --git a/example_common/src/widgets/text_input.rs b/example_common/src/widgets/text_input.rs index 74fb4dd67..9eeec697c 100644 --- a/example_common/src/widgets/text_input.rs +++ b/example_common/src/widgets/text_input.rs @@ -1,6 +1,6 @@ use accesskit::{ - Action, ActionData, ActionRequest, Node, NodeId, Rect, Role, TextDirection, TextPosition, - TextSelection, + Action, ActionData, ActionRequest, Affine, Node, NodeId, Point, Rect, Role, TextDirection, + TextPosition, TextSelection, }; use std::ops::Range; use unicode_segmentation::UnicodeSegmentation; @@ -307,6 +307,160 @@ fn wrap(characters: &[&str], width: usize) -> Vec { } } +/// The line a caret before the character at `index` is on: at a soft line +/// break, the one starting there. +fn line_index(lines: &[Line], index: usize) -> usize { + lines + .iter() + .rposition(|line| line.start <= index) + .unwrap_or(0) +} + +fn line_end(lines: &[Line], line_index: usize) -> usize { + let end = lines[line_index].end; + if line_index + 1 == lines.len() { + end + } else { + end - 1 + } +} + +fn vertical_move(lines: &[Line], index: usize, count: isize) -> usize { + let line_index = line_index(lines, index); + let column = index - lines[line_index].start; + let target = line_index + .checked_add_signed(count) + .filter(|target| *target < lines.len()); + match target { + Some(target) => (lines[target].start + column).min(line_end(lines, target)), + None if count > 0 => lines[lines.len() - 1].end, + None => 0, + } +} + +/// Where the characters of a [`TextInput`] are, in the window's coordinates, +/// as AccessKit places the nodes of the tree. +/// +/// Offsets are byte offsets into the text, rounded to character boundaries. +#[derive(Clone, Debug)] +pub struct TextLayout { + /// Where each character starts in the text, followed by the text's + /// length. + character_offsets: Vec, + is_hard_line_break: Vec, + lines: Vec, + origin: Point, + transform: Affine, +} + +impl TextLayout { + pub(crate) fn with_transform(mut self, transform: Affine) -> Self { + self.transform = transform; + self + } + + fn character_index(&self, offset: usize) -> usize { + self.character_offsets + .partition_point(|start| *start < offset) + .min(self.character_offsets.len() - 1) + } + + fn local_caret(&self, index: usize) -> (f64, f64) { + let line_index = line_index(&self.lines, index); + let column = index - self.lines[line_index].start; + ( + self.origin.x + (column as f32 * CHARACTER_WIDTH) as f64, + self.origin.y + line_index as f64 * LINE_HEIGHT, + ) + } + + fn local_range_bounds(&self, range: Range) -> Vec { + let mut rects = Vec::<(usize, Rect)>::new(); + for index in range { + let line_index = line_index(&self.lines, index); + let (x0, y0) = self.local_caret(index); + let width = if self.is_hard_line_break[index] { + 0.0 + } else { + CHARACTER_WIDTH as f64 + }; + match rects.last_mut() { + Some((line, rect)) if *line == line_index => rect.x1 = x0 + width, + _ => rects.push((line_index, Rect::new(x0, y0, x0 + width, y0 + LINE_HEIGHT))), + } + } + rects.into_iter().map(|(_, rect)| rect).collect() + } + + fn transform_rect(&self, rect: Rect) -> Rect { + self.transform.transform_rect_bbox(rect) + } + + /// A rectangle without width, before the character at `offset`. + pub fn caret_bounds(&self, offset: usize) -> Rect { + let (x, y) = self.local_caret(self.character_index(offset)); + self.transform_rect(Rect::new(x, y, x, y + LINE_HEIGHT)) + } + + /// The bounds of the characters in `range`, one rectangle per line. + pub fn range_bounds(&self, range: Range) -> Vec { + let range = self.character_index(range.start)..self.character_index(range.end); + self.local_range_bounds(range) + .into_iter() + .map(|rect| self.transform_rect(rect)) + .collect() + } + + /// The character boundary in `range` closest to `point`, on the closest + /// line. + pub fn offset_at_point(&self, point: Point, range: Range) -> usize { + let point = self.transform.inverse() * point; + let range = self.character_index(range.start)..=self.character_index(range.end); + let index = range + .min_by(|a, b| { + let distance = |index| { + let (x, y) = self.local_caret(index); + ( + distance_outside(point.y, y, y + LINE_HEIGHT), + (point.x - x).abs(), + ) + }; + distance(*a).partial_cmp(&distance(*b)).unwrap() + }) + .unwrap_or(0); + self.character_offsets[index] + } + + /// The offset `count` lines below `offset`, or above if negative, in the + /// same column as far as the line allows. Going past the first or last + /// line goes to the start or end of the text. + pub fn vertical_offset(&self, offset: usize, count: isize) -> usize { + let index = vertical_move(&self.lines, self.character_index(offset), count); + self.character_offsets[index] + } + + /// The byte range of the character closest to `point`, on the closest + /// line. + pub fn character_at_point(&self, point: Point) -> Option> { + let point = self.transform.inverse() * point; + let index = (0..self.character_offsets.len() - 1).min_by(|a, b| { + let distance = |index| { + let rect = self.local_range_bounds(index..index + 1)[0]; + ( + distance_outside(point.y, rect.y0, rect.y1), + distance_outside(point.x, rect.x0, rect.x1), + ) + }; + distance(*a).partial_cmp(&distance(*b)).unwrap() + })?; + Some(self.character_offsets[index]..self.character_offsets[index + 1]) + } +} + +fn distance_outside(value: f64, start: f64, end: f64) -> f64 { + (start - value).max(value - end).max(0.0) +} + /// A text input. /// /// The text is exposed as text runs, so that assistive technologies can @@ -456,40 +610,9 @@ impl TextInput { - 1 } - fn character_count(&self) -> usize { - self.character_offsets.len() - 1 - } - - fn line_index(&self, index: usize) -> usize { - self.lines - .iter() - .rposition(|line| line.start <= index) - .unwrap_or(0) - } - - fn line_end(&self, line_index: usize) -> usize { - let end = self.lines[line_index].end; - if line_index + 1 == self.lines.len() { - end - } else { - end - 1 - } - } - fn vertical_move(&self, down: bool) -> usize { let focus = self.character_index(self.state.focus); - let line_index = self.line_index(focus); - let column = focus - self.lines[line_index].start; - let target = if down { - Some(line_index + 1).filter(|target| *target < self.lines.len()) - } else { - line_index.checked_sub(1) - }; - match target { - Some(target) => (self.lines[target].start + column).min(self.line_end(target)), - None if down => self.character_count(), - None => 0, - } + vertical_move(&self.lines, focus, if down { 1 } else { -1 }) } /// The position of the character containing the byte at `offset` in the @@ -581,7 +704,7 @@ impl Widget for TextInput { } let is_multiline = self.input_type == InputType::Multiline; let extend = event.modifiers.shift; - let line_index = self.line_index(self.character_index(self.state.focus)); + let line_index = line_index(&self.lines, self.character_index(self.state.focus)); let mut state = self.state.clone(); state.composition = None; match event.key { @@ -606,7 +729,10 @@ impl Widget for TextInput { Key::Home => { state.move_to(self.character_offsets[self.lines[line_index].start], extend) } - Key::End => state.move_to(self.character_offsets[self.line_end(line_index)], extend), + Key::End => state.move_to( + self.character_offsets[line_end(&self.lines, line_index)], + extend, + ), } self.respond(state) } @@ -636,6 +762,21 @@ impl Widget for TextInput { } } + fn text_layout(&self) -> Option { + let characters = &self.state.text; + Some(TextLayout { + character_offsets: self.character_offsets.clone(), + is_hard_line_break: self + .character_offsets + .windows(2) + .map(|offsets| is_hard_line_break(&characters[offsets[0]..offsets[1]])) + .collect(), + lines: self.lines.clone(), + origin: Point::new(self.bounds.x0 + PADDING, self.bounds.y0 + PADDING), + transform: Affine::IDENTITY, + }) + } + fn text_input(&self) -> Option { if self.disabled { return None;