Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui_ios: Add iOS platform backend (#63068)

Anthony Eida47f721832e5
diff --git a/Cargo.lock b/Cargo.lock
index 13e3e1e3d9f..b6c76d52ac6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7496,6 +7496,36 @@ dependencies = [
"zed-font-kit",
]
+[[package]]
+name = "gpui_ios"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "block2 0.6.2",
+ "futures 0.3.34",
+ "gpui",
+ "gpui_apple",
+ "log",
+ "objc2 0.6.3",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+ "objc2-quartz-core 0.3.2",
+ "objc2-ui-kit",
+ "parking_lot",
+ "raw-window-handle",
+ "slotmap",
+ "uuid",
+]
+
+[[package]]
+name = "gpui_ios_example"
+version = "0.1.0"
+dependencies = [
+ "gpui",
+ "gpui_ios",
+ "gpui_platform",
+]
+
[[package]]
name = "gpui_linux"
version = "0.1.0"
@@ -7600,6 +7630,7 @@ dependencies = [
"console_error_panic_hook",
"criterion",
"gpui",
+ "gpui_ios",
"gpui_linux",
"gpui_macos",
"gpui_web",
@@ -11948,6 +11979,20 @@ dependencies = [
"objc2-core-foundation",
]
+[[package]]
+name = "objc2-ui-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"
+dependencies = [
+ "bitflags 2.13.1",
+ "block2 0.6.2",
+ "objc2 0.6.3",
+ "objc2-core-foundation",
+ "objc2-foundation 0.3.2",
+ "objc2-quartz-core 0.3.2",
+]
+
[[package]]
name = "objc2-user-notifications"
version = "0.3.2"
diff --git a/Cargo.toml b/Cargo.toml
index b3d85a3bee1..4ec681efe43 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -94,6 +94,8 @@ members = [
"crates/google_ai",
"crates/gpui",
"crates/gpui_apple",
+ "crates/gpui_ios",
+ "crates/gpui_ios/examples/ios",
"crates/gpui_linux",
"crates/gpui_macos",
"crates/gpui_macros",
@@ -366,6 +368,7 @@ go_to_line = { path = "crates/go_to_line" }
google_ai = { path = "crates/google_ai" }
gpui = { path = "crates/gpui", default-features = false }
gpui_apple = { path = "crates/gpui_apple" }
+gpui_ios = { path = "crates/gpui_ios" }
gpui_linux = { path = "crates/gpui_linux", default-features = false }
gpui_macos = { path = "crates/gpui_macos", default-features = false }
gpui_macros = { path = "crates/gpui_macros" }
@@ -701,6 +704,34 @@ notify-rust = "4"
nucleo = { package = "nucleo-matcher", version = "0.3" }
objc = "0.2"
objc2 = "0.6"
+objc2-ui-kit = { version = "0.3.2", default-features = false, features = [
+ "std",
+ "block2",
+ "objc2-quartz-core",
+ "objc2-core-foundation",
+ "NSText",
+ "UIApplication",
+ "UIEvent",
+ "UIGeometry",
+ "UIInterface",
+ "UIOpenURLContext",
+ "UIPasteboard",
+ "UIResponder",
+ "UIScene",
+ "UISceneConfiguration",
+ "UISceneDefinitions",
+ "UISceneOptions",
+ "UISceneSession",
+ "UIScreen",
+ "UITextInput",
+ "UITextInputTraits",
+ "UITouch",
+ "UITraitCollection",
+ "UIView",
+ "UIViewController",
+ "UIWindow",
+ "UIWindowScene",
+] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = [
"NSAlert",
"NSApplication",
diff --git a/crates/gpui/examples/input.rs b/crates/gpui/examples/input.rs
index eadc2d2f393..106d06dc7e3 100644
--- a/crates/gpui/examples/input.rs
+++ b/crates/gpui/examples/input.rs
@@ -49,41 +49,41 @@ struct TextInput {
}
impl TextInput {
- fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
+ fn left(&mut self, _: &Left, window: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
- self.move_to(self.previous_boundary(self.cursor_offset()), cx);
+ self.move_to(self.previous_boundary(self.cursor_offset()), window, cx);
} else {
- self.move_to(self.selected_range.start, cx)
+ self.move_to(self.selected_range.start, window, cx)
}
}
- fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
+ fn right(&mut self, _: &Right, window: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
- self.move_to(self.next_boundary(self.selected_range.end), cx);
+ self.move_to(self.next_boundary(self.selected_range.end), window, cx);
} else {
- self.move_to(self.selected_range.end, cx)
+ self.move_to(self.selected_range.end, window, cx)
}
}
- fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
- self.select_to(self.previous_boundary(self.cursor_offset()), cx);
+ fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
+ self.select_to(self.previous_boundary(self.cursor_offset()), window, cx);
}
- fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
- self.select_to(self.next_boundary(self.cursor_offset()), cx);
+ fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
+ self.select_to(self.next_boundary(self.cursor_offset()), window, cx);
}
- fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
- self.move_to(0, cx);
- self.select_to(self.content.len(), cx)
+ fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
+ self.move_to(0, window, cx);
+ self.select_to(self.content.len(), window, cx)
}
- fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
- self.move_to(0, cx);
+ fn home(&mut self, _: &Home, window: &mut Window, cx: &mut Context<Self>) {
+ self.move_to(0, window, cx);
}
- fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
- self.move_to(self.content.len(), cx);
+ fn end(&mut self, _: &End, window: &mut Window, cx: &mut Context<Self>) {
+ self.move_to(self.content.len(), window, cx);
}
fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
@@ -93,7 +93,7 @@ impl TextInput {
window.play_system_bell();
return;
}
- self.select_to(prev, cx)
+ self.select_to(prev, window, cx)
}
self.replace_text_in_range(None, "", window, cx)
}
@@ -105,7 +105,7 @@ impl TextInput {
window.play_system_bell();
return;
}
- self.select_to(next, cx)
+ self.select_to(next, window, cx)
}
self.replace_text_in_range(None, "", window, cx)
}
@@ -113,15 +113,16 @@ impl TextInput {
fn on_mouse_down(
&mut self,
event: &MouseDownEvent,
- _window: &mut Window,
+ window: &mut Window,
cx: &mut Context<Self>,
) {
self.is_selecting = true;
+ window.request_virtual_keyboard();
if event.modifiers.shift {
- self.select_to(self.index_for_mouse_position(event.position), cx);
+ self.select_to(self.index_for_mouse_position(event.position), window, cx);
} else {
- self.move_to(self.index_for_mouse_position(event.position), cx)
+ self.move_to(self.index_for_mouse_position(event.position), window, cx)
}
}
@@ -129,9 +130,14 @@ impl TextInput {
self.is_selecting = false;
}
- fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
+ fn on_mouse_move(
+ &mut self,
+ event: &MouseMoveEvent,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
if self.is_selecting {
- self.select_to(self.index_for_mouse_position(event.position), cx);
+ self.select_to(self.index_for_mouse_position(event.position), window, cx);
}
}
@@ -166,8 +172,10 @@ impl TextInput {
}
}
- fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
+ fn move_to(&mut self, offset: usize, window: &Window, cx: &mut Context<Self>) {
self.selected_range = offset..offset;
+ self.selection_reversed = false;
+ window.notify_text_selection_changed(&self.focus_handle);
cx.notify()
}
@@ -197,7 +205,7 @@ impl TextInput {
line.closest_index_for_x(position.x - bounds.left())
}
- fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
+ fn select_to(&mut self, offset: usize, window: &Window, cx: &mut Context<Self>) {
if self.selection_reversed {
self.selected_range.start = offset
} else {
@@ -207,6 +215,7 @@ impl TextInput {
self.selection_reversed = !self.selection_reversed;
self.selected_range = self.selected_range.end..self.selected_range.start;
}
+ window.notify_text_selection_changed(&self.focus_handle);
cx.notify()
}
@@ -263,7 +272,7 @@ impl TextInput {
.unwrap_or(self.content.len())
}
- fn reset(&mut self) {
+ fn reset(&mut self, window: &Window, cx: &mut Context<Self>) {
self.content = "".into();
self.selected_range = 0..0;
self.selection_reversed = false;
@@ -271,6 +280,8 @@ impl TextInput {
self.last_layout = None;
self.last_bounds = None;
self.is_selecting = false;
+ window.notify_text_input_changed(&self.focus_handle);
+ cx.notify();
}
}
@@ -299,6 +310,26 @@ impl EntityInputHandler for TextInput {
})
}
+ fn set_selected_text_range(
+ &mut self,
+ range_utf16: Range<usize>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.selected_range = self.range_from_utf16(&range_utf16);
+ self.selection_reversed = false;
+ window.notify_text_selection_changed(&self.focus_handle);
+ cx.notify();
+ }
+
+ fn text_length_utf16(
+ &mut self,
+ _window: &mut Window,
+ _cx: &mut Context<Self>,
+ ) -> Option<usize> {
+ Some(self.content.encode_utf16().count())
+ }
+
fn marked_text_range(
&self,
_window: &mut Window,
@@ -309,15 +340,17 @@ impl EntityInputHandler for TextInput {
.map(|range| self.range_to_utf16(range))
}
- fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
+ fn unmark_text(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.marked_range = None;
+ window.notify_text_input_changed(&self.focus_handle);
+ cx.notify();
}
fn replace_text_in_range(
&mut self,
range_utf16: Option<Range<usize>>,
new_text: &str,
- _: &mut Window,
+ window: &mut Window,
cx: &mut Context<Self>,
) {
let range = range_utf16
@@ -330,7 +363,9 @@ impl EntityInputHandler for TextInput {
(self.content[0..range.start].to_owned() + new_text + &self.content[range.end..])
.into();
self.selected_range = range.start + new_text.len()..range.start + new_text.len();
+ self.selection_reversed = false;
self.marked_range.take();
+ window.notify_text_input_changed(&self.focus_handle);
cx.notify();
}
@@ -339,7 +374,7 @@ impl EntityInputHandler for TextInput {
range_utf16: Option<Range<usize>>,
new_text: &str,
new_selected_range_utf16: Option<Range<usize>>,
- _window: &mut Window,
+ window: &mut Window,
cx: &mut Context<Self>,
) {
let range = range_utf16
@@ -356,12 +391,19 @@ impl EntityInputHandler for TextInput {
} else {
self.marked_range = None;
}
+ let insertion_start_utf16 = self.offset_to_utf16(range.start);
+ let inserted_length_utf16 = new_text.encode_utf16().count();
self.selected_range = new_selected_range_utf16
- .as_ref()
- .map(|range_utf16| self.range_from_utf16(range_utf16))
- .map(|new_range| new_range.start + range.start..new_range.end + range.end)
+ .map(|selected| {
+ self.range_from_utf16(
+ &(insertion_start_utf16 + selected.start.min(inserted_length_utf16)
+ ..insertion_start_utf16 + selected.end.min(inserted_length_utf16)),
+ )
+ })
.unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
+ self.selection_reversed = false;
+ window.notify_text_input_changed(&self.focus_handle);
cx.notify();
}
@@ -373,6 +415,9 @@ impl EntityInputHandler for TextInput {
_cx: &mut Context<Self>,
) -> Option<Bounds<Pixels>> {
let last_layout = self.last_layout.as_ref()?;
+ if last_layout.text != self.content {
+ return None;
+ }
let range = self.range_from_utf16(&range_utf16);
Some(Bounds::from_corners(
point(
@@ -386,6 +431,18 @@ impl EntityInputHandler for TextInput {
))
}
+ fn selection_bounds_for_range(
+ &mut self,
+ range_utf16: Range<usize>,
+ bounds: Bounds<Pixels>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Vec<Bounds<Pixels>> {
+ self.bounds_for_range(range_utf16, bounds, window, cx)
+ .into_iter()
+ .collect()
+ }
+
fn character_index_for_point(
&mut self,
point: gpui::Point<Pixels>,
@@ -395,8 +452,10 @@ impl EntityInputHandler for TextInput {
let line_point = self.last_bounds?.localize(&point)?;
let last_layout = self.last_layout.as_ref()?;
- assert_eq!(last_layout.text, self.content);
- let utf8_index = last_layout.index_for_x(point.x - line_point.x)?;
+ if last_layout.text != self.content {
+ return None;
+ }
+ let utf8_index = last_layout.closest_index_for_x(line_point.x);
Some(self.offset_to_utf16(utf8_index))
}
}
@@ -642,10 +701,10 @@ impl Focusable for InputExample {
}
impl InputExample {
- fn on_reset_click(&mut self, _: &MouseUpEvent, _window: &mut Window, cx: &mut Context<Self>) {
+ fn on_reset_click(&mut self, _: &MouseUpEvent, window: &mut Window, cx: &mut Context<Self>) {
self.recent_keystrokes.clear();
self.text_input
- .update(cx, |text_input, _cx| text_input.reset());
+ .update(cx, |text_input, cx| text_input.reset(window, cx));
cx.notify();
}
}
@@ -782,3 +841,80 @@ pub fn start() {
gpui_platform::web_init();
run_example();
}
+
+#[cfg(all(test, feature = "test-support"))]
+mod tests {
+ use super::*;
+ use gpui::TestAppContext;
+
+ fn input(content: &'static str, cx: &mut Context<TextInput>) -> TextInput {
+ TextInput {
+ focus_handle: cx.focus_handle(),
+ content: content.into(),
+ placeholder: "".into(),
+ selected_range: 0..0,
+ selection_reversed: false,
+ marked_range: None,
+ last_layout: None,
+ last_bounds: None,
+ is_selecting: false,
+ }
+ }
+
+ #[gpui::test]
+ fn native_selection_and_length_use_utf16(cx: &mut TestAppContext) {
+ let window = cx.add_window(|_, cx| input("e🙂漢", cx));
+ window
+ .update(cx, |input, window, cx| {
+ assert_eq!(input.text_length_utf16(window, cx), Some(4));
+ input.set_selected_text_range(1..3, window, cx);
+ assert_eq!(input.selected_range, 1..5);
+ assert_eq!(
+ input.selected_text_range(false, window, cx).unwrap().range,
+ 1..3
+ );
+ input.set_selected_text_range(3..99, window, cx);
+ assert_eq!(input.selected_range, 5..8);
+ })
+ .unwrap();
+ }
+
+ #[gpui::test]
+ fn marked_selection_is_relative_to_inserted_text(cx: &mut TestAppContext) {
+ let window = cx.add_window(|_, cx| input("A🙂Z", cx));
+ window
+ .update(cx, |input, window, cx| {
+ input.replace_and_mark_text_in_range(Some(1..3), "é🙂", Some(1..3), window, cx);
+ assert_eq!(input.content, "Aé🙂Z");
+ assert_eq!(input.marked_range, Some(1..7));
+ assert_eq!(input.selected_range, 3..7);
+
+ input.replace_and_mark_text_in_range(None, "漢", Some(1..1), window, cx);
+ assert_eq!(input.content, "A漢Z");
+ assert_eq!(input.marked_range, Some(1..4));
+ assert_eq!(input.selected_range, 4..4);
+
+ input.replace_and_mark_text_in_range(None, "", Some(0..0), window, cx);
+ assert_eq!(input.content, "AZ");
+ assert_eq!(input.marked_range, None);
+ assert_eq!(input.selected_range, 1..1);
+ })
+ .unwrap();
+ }
+
+ #[gpui::test]
+ fn long_single_line_selection_uses_one_geometry_fragment(cx: &mut TestAppContext) {
+ let (view, cx) = cx.add_window_view(|_, cx| input("", cx));
+ view.update(cx, |input, cx| {
+ input.content = "a".repeat(10_000).into();
+ cx.notify();
+ });
+ cx.run_until_parked();
+ view.update_in(cx, |input, window, cx| {
+ let bounds = input.last_bounds.expect("input was painted");
+ let rectangles = input.selection_bounds_for_range(0..10_000, bounds, window, cx);
+ assert_eq!(rectangles.len(), 1);
+ assert!(rectangles[0].size.width > px(0.));
+ });
+ }
+}
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
index cdbd5593b11..33456df65e4 100644
--- a/crates/gpui/src/app.rs
+++ b/crates/gpui/src/app.rs
@@ -45,17 +45,17 @@ use crate::InspectorElementRegistry;
use crate::asset_cache::CachedLoad;
use crate::{
Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
- AnyWindowHandle, AppContext, Arena, ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds,
- ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase, DisplayChanges, DisplayEvent,
- DisplayId, EventEmitter, ExternalDragPayload, FocusHandle, FocusMap, ForegroundExecutor,
- Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId, Menu, MenuItem, MissingGlyph,
- OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout,
- PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton, PromptHandle,
- PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation, ScreenCaptureSource,
- SharedString, SubscriberSet, Subscription, SvgRenderer, SystemNotification,
- SystemNotificationResponse, Task, TextRenderingMode, TextSystem, ThermalState, Window,
- WindowAppearance, WindowButtonLayout, WindowHandle, WindowId, WindowInvalidator,
- WindowingRequest,
+ AnyWindowHandle, AppContext, AppLifecyclePhase, Arena, ArenaBox, Asset, AssetSource,
+ BackgroundExecutor, Bounds, ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase,
+ DisplayChanges, DisplayEvent, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle,
+ FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke, LayoutId,
+ Menu, MenuItem, MissingGlyph, OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay,
+ PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority, PromptBuilder, PromptButton,
+ PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation,
+ ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer,
+ SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem,
+ ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId,
+ WindowInvalidator, WindowingRequest,
colors::{Colors, GlobalColors},
hash, init_app_menus,
};
@@ -334,6 +334,7 @@ impl Application {
}
type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
+type AppLifecycleHandler = Box<dyn FnMut(AppLifecyclePhase, &mut App) -> bool + 'static>;
type DisplayHandler = Box<dyn FnMut(DisplayEvent, &mut App) -> bool + 'static>;
/// The properties of a display that GPUI reports changes to.
@@ -852,6 +853,8 @@ pub struct App {
displays: HashMap<DisplayId, DisplayState>,
pub(crate) system_sleep_observers: SubscriberSet<(), Handler>,
pub(crate) system_wake_observers: SubscriberSet<(), Handler>,
+ app_lifecycle_observers: SubscriberSet<(), AppLifecycleHandler>,
+ memory_warning_observers: SubscriberSet<(), Handler>,
pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
@@ -990,6 +993,8 @@ impl App {
displays: read_displays(platform.as_ref()),
system_sleep_observers: SubscriberSet::new(),
system_wake_observers: SubscriberSet::new(),
+ app_lifecycle_observers: SubscriberSet::new(),
+ memory_warning_observers: SubscriberSet::new(),
global_observers: SubscriberSet::new(),
quit_observers: SubscriberSet::new(),
restart_observers: SubscriberSet::new(),
@@ -1084,6 +1089,32 @@ impl App {
}
}));
+ platform.on_app_lifecycle(Box::new({
+ let app = Rc::downgrade(&app);
+ move |phase| {
+ if let Some(app) = app.upgrade() {
+ app.borrow_mut().update(|cx| {
+ cx.app_lifecycle_observers
+ .clone()
+ .retain(&(), |callback| callback(phase, cx));
+ });
+ }
+ }
+ }));
+
+ platform.on_memory_warning(Box::new({
+ let app = Rc::downgrade(&app);
+ move || {
+ if let Some(app) = app.upgrade() {
+ app.borrow_mut().update(|cx| {
+ cx.memory_warning_observers
+ .clone()
+ .retain(&(), |callback| callback(cx));
+ });
+ }
+ }
+ }));
+
platform.on_quit(Box::new({
let cx = Rc::downgrade(&app);
move || {
@@ -1694,6 +1725,42 @@ impl App {
subscription
}
+ /// Observes mobile application lifecycle changes. Desktop platforms do not
+ /// emit these events. On iOS these currently describe the single connected
+ /// scene, not individual windows.
+ ///
+ /// Save important changes incrementally: neither disconnection nor quit is
+ /// guaranteed before the system terminates a backgrounded application.
+ /// Dropping the returned subscription removes the observer.
+ pub fn on_app_lifecycle(
+ &self,
+ mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
+ ) -> Subscription {
+ let (subscription, activate) = self.app_lifecycle_observers.insert(
+ (),
+ Box::new(move |phase, cx| {
+ callback(phase, cx);
+ true
+ }),
+ );
+ activate();
+ subscription
+ }
+
+ /// Observes mobile memory-pressure warnings so applications can release
+ /// expendable caches. Dropping the subscription removes the observer.
+ pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {
+ let (subscription, activate) = self.memory_warning_observers.insert(
+ (),
+ Box::new(move |cx| {
+ callback(cx);
+ true
+ }),
+ );
+ activate();
+ subscription
+ }
+
/// Returns the appearance of the application's windows.
pub fn window_appearance(&self) -> WindowAppearance {
self.platform.window_appearance()
diff --git a/crates/gpui/src/app/test_context.rs b/crates/gpui/src/app/test_context.rs
index 16328437de9..b8a120f942c 100644
--- a/crates/gpui/src/app/test_context.rs
+++ b/crates/gpui/src/app/test_context.rs
@@ -1282,6 +1282,74 @@ mod tests {
use std::path::PathBuf;
use std::rc::Rc;
+ #[gpui::test]
+ fn test_mobile_lifecycle_subscriptions(cx: &mut TestAppContext) {
+ use crate::AppLifecyclePhase;
+
+ let phases = Rc::new(RefCell::new(Vec::new()));
+ let subscription = cx.update(|cx| {
+ cx.on_app_lifecycle({
+ let phases = phases.clone();
+ move |phase, cx| {
+ phases.borrow_mut().push(phase);
+ cx.defer(|cx| {
+ cx.set_global(LifecycleObserved);
+ });
+ }
+ })
+ });
+ struct LifecycleObserved;
+ impl crate::Global for LifecycleObserved {}
+
+ let mut callback = cx
+ .test_platform
+ .app_lifecycle_callback
+ .borrow_mut()
+ .take()
+ .expect("App registers the native lifecycle callback");
+ for phase in [
+ AppLifecyclePhase::Foreground,
+ AppLifecyclePhase::Active,
+ AppLifecyclePhase::Inactive,
+ AppLifecyclePhase::Background,
+ AppLifecyclePhase::Disconnected,
+ ] {
+ callback(phase);
+ }
+ assert_eq!(phases.borrow().len(), 5);
+ assert_eq!(
+ phases.borrow().last(),
+ Some(&AppLifecyclePhase::Disconnected)
+ );
+ cx.update(|cx| assert!(cx.has_global::<LifecycleObserved>()));
+ drop(subscription);
+ callback(AppLifecyclePhase::Foreground);
+ assert_eq!(phases.borrow().len(), 5);
+ }
+
+ #[gpui::test]
+ fn test_memory_warning_subscriptions(cx: &mut TestAppContext) {
+ let warnings = Rc::new(std::cell::Cell::new(0));
+ let subscription = cx.update(|cx| {
+ cx.on_memory_warning({
+ let warnings = warnings.clone();
+ move |_| warnings.set(warnings.get() + 1)
+ })
+ });
+ let mut callback = cx
+ .test_platform
+ .memory_warning_callback
+ .borrow_mut()
+ .take()
+ .expect("App registers the native memory warning callback");
+ callback();
+ callback();
+ assert_eq!(warnings.get(), 2);
+ drop(subscription);
+ callback();
+ assert_eq!(warnings.get(), 2);
+ }
+
#[gpui::test]
async fn test_system_notifications_require_identity_and_replace_matching_tags(
cx: &mut TestAppContext,
diff --git a/crates/gpui/src/elements/div.rs b/crates/gpui/src/elements/div.rs
index fc292f2a81e..5d3b03b057b 100644
--- a/crates/gpui/src/elements/div.rs
+++ b/crates/gpui/src/elements/div.rs
@@ -5250,6 +5250,96 @@ mod tests {
);
}
+ #[test]
+ fn touch_tap_out_fires_once_after_release() {
+ let mut test_app = TestAppContext::single();
+ let mouse_down_out_count = Rc::new(RefCell::new(0));
+ let window = test_app.add_window({
+ let mouse_down_out_count = mouse_down_out_count.clone();
+ move |_, _| MouseDownOutOwner {
+ mouse_down_out_count,
+ }
+ });
+ let any_window: AnyWindowHandle = window.into();
+
+ test_app
+ .update_window(any_window, |_, window, cx| {
+ window.draw(cx).clear(cx);
+ let started = TouchEvent {
+ id: TouchId(1),
+ phase: TouchPhase::Started,
+ position: point(px(75.), px(75.)),
+ force: None,
+ predicted_position: None,
+ };
+ window.dispatch_event(started.clone().to_platform_input(), cx);
+ assert_eq!(*mouse_down_out_count.borrow(), 0);
+ window.dispatch_event(
+ TouchEvent {
+ phase: TouchPhase::Ended,
+ ..started
+ }
+ .to_platform_input(),
+ cx,
+ );
+ })
+ .unwrap();
+
+ assert_eq!(
+ *mouse_down_out_count.borrow(),
+ 1,
+ "a touch tap outside the element should use mouse-down-out listeners"
+ );
+ }
+
+ #[crate::test]
+ fn touch_pan_and_cancel_do_not_fire_mouse_down_out(cx: &mut TestAppContext) {
+ let mouse_down_out_count = Rc::new(RefCell::new(0));
+ let window = cx.add_window({
+ let mouse_down_out_count = mouse_down_out_count.clone();
+ move |_, _| MouseDownOutOwner {
+ mouse_down_out_count,
+ }
+ });
+ cx.update_window(window.into(), |_, window, cx| {
+ window.draw(cx).clear(cx);
+ for (id, samples) in [
+ (
+ TouchId(1),
+ [
+ (TouchPhase::Started, 100.),
+ (TouchPhase::Moved, 75.),
+ (TouchPhase::Ended, 75.),
+ ],
+ ),
+ (
+ TouchId(2),
+ [
+ (TouchPhase::Started, 100.),
+ (TouchPhase::Moved, 100.),
+ (TouchPhase::Cancelled, 100.),
+ ],
+ ),
+ ] {
+ for (phase, vertical_position) in samples {
+ window.dispatch_event(
+ TouchEvent {
+ id,
+ phase,
+ position: point(px(75.), px(vertical_position)),
+ predicted_position: None,
+ force: None,
+ }
+ .to_platform_input(),
+ cx,
+ );
+ }
+ }
+ })
+ .unwrap();
+ assert_eq!(*mouse_down_out_count.borrow(), 0);
+ }
+
#[test]
fn test_accessibility_id_builder_writes_author_id() {
let mut element = div()
diff --git a/crates/gpui/src/gestures.rs b/crates/gpui/src/gestures.rs
index ec611576efb..e42fbaa4014 100644
--- a/crates/gpui/src/gestures.rs
+++ b/crates/gpui/src/gestures.rs
@@ -1,14 +1,10 @@
//! Touch gesture recognition vocabulary.
//!
-//! GPUI recognizes gestures from raw [`TouchEvent`](crate::TouchEvent)s in a
-//! single, portable arena in gpui core: recognizers compete for in-flight
-//! touches, winners claim them, and losers are cancelled. Recognized gestures
-//! are surfaced through *existing* semantic events wherever possible, a tap
-//! becomes [`ClickEvent::Touch`](crate::ClickEvent), a pan becomes
-//! [`ScrollWheelEvent`](crate::ScrollWheelEvent)s carrying a
-//! [`TouchPhase`](crate::TouchPhase), and a pinch becomes
-//! [`PinchEvent`](crate::PinchEvent)s — so components written against
-//! `on_click` and scroll containers work untouched on mobile.
+//! GPUI recognizes gestures from raw [`TouchEvent`](crate::TouchEvent)s using
+//! a portable recognizer. Taps synthesize mouse presses and releases so
+//! existing click listeners and text selection work on mobile. Pans produce
+//! [`ScrollWheelEvent`](crate::ScrollWheelEvent)s, including post-release
+//! momentum. Long presses and touch drags can be claimed by element listeners.
use std::collections::VecDeque;
use std::mem;
@@ -351,7 +347,7 @@ mod friction_spline {
/// portable recognizers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct GestureKinds {
- /// Tap (and multi-tap), surfaced as [`ClickEvent::Touch`](crate::ClickEvent).
+ /// Tap (and multi-tap), synthesized as mouse presses by the portable recognizer.
pub tap: bool,
/// Long press, surfaced as [`LongPressEvent`].
pub long_press: bool,
diff --git a/crates/gpui/src/input.rs b/crates/gpui/src/input.rs
index 4167aa09905..815ea9246e8 100644
--- a/crates/gpui/src/input.rs
+++ b/crates/gpui/src/input.rs
@@ -9,6 +9,19 @@ use std::ops::Range;
/// Once your view implements this trait, you can use it to construct an [`ElementInputHandler<V>`].
/// This input handler can then be assigned during paint by calling [`Window::handle_input`].
///
+/// Dismissing the software keyboard can leave the component focused. Call
+/// [`Window::request_virtual_keyboard`] from an editing gesture, such as tapping
+/// the field, to reopen it; repainting alone should not undo a dismissal.
+///
+/// After application-driven edits or selection changes, also call
+/// [`Window::notify_text_input_changed`] or [`Window::notify_text_selection_changed`]
+/// so native text services can invalidate their state.
+///
+/// UIKit text input also needs `text_length_utf16` (or a bounded
+/// `text_input_editable_range`) and native selection updates through
+/// `set_selected_text_range`. Supply `selection_bounds_for_range` for native
+/// selection rectangles; it should return line/run fragments in one batch.
+///
/// See [`InputHandler`] for details on how to implement each method.
pub trait EntityInputHandler: 'static + Sized {
/// See [`InputHandler::text_for_range`] for details
@@ -73,6 +86,17 @@ pub trait EntityInputHandler: 'static + Sized {
cx: &mut Context<Self>,
) -> Option<Bounds<Pixels>>;
+ /// See [`InputHandler::selection_bounds_for_range`] for details.
+ fn selection_bounds_for_range(
+ &mut self,
+ _range_utf16: Range<usize>,
+ _element_bounds: Bounds<Pixels>,
+ _window: &mut Window,
+ _cx: &mut Context<Self>,
+ ) -> Vec<Bounds<Pixels>> {
+ Vec::new()
+ }
+
/// See [`InputHandler::character_index_for_point`] for details
fn character_index_for_point(
&mut self,
@@ -223,6 +247,17 @@ impl<V: EntityInputHandler> InputHandler for ElementInputHandler<V> {
})
}
+ fn selection_bounds_for_range(
+ &mut self,
+ range_utf16: Range<usize>,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> Vec<Bounds<Pixels>> {
+ self.view.update(cx, |view, cx| {
+ view.selection_bounds_for_range(range_utf16, self.element_bounds, window, cx)
+ })
+ }
+
fn character_index_for_point(
&mut self,
point: crate::Point<Pixels>,
@@ -304,6 +339,7 @@ mod tests {
move |_, cx| ConfigurationTestView {
focus_handle: cx.focus_handle(),
configuration: custom,
+ accepts_text_input: true,
}
});
let view = window.root(cx).unwrap();
@@ -381,9 +417,95 @@ mod tests {
);
}
+ #[gpui::test]
+ fn text_notifications_require_a_focused_input_and_track_field_changes(cx: &mut TestAppContext) {
+ let window = cx.add_window(|_, cx| ConfigurationTestView {
+ focus_handle: cx.focus_handle(),
+ configuration: TextInputConfiguration::default(),
+ accepts_text_input: true,
+ });
+ let view = window.root(cx).unwrap();
+ let mut test_window = cx.test_window(window.into());
+ let window = AnyWindowHandle::from(window);
+ let first_focus = view.read_with(cx, |view, _| view.focus_handle.clone());
+ cx.update_window(window, |_, window, cx| {
+ window.focus(&first_focus, cx);
+ window.draw(cx).clear(cx);
+ window.notify_text_input_changed(&first_focus);
+ window.notify_text_selection_changed(&first_focus);
+ })
+ .unwrap();
+
+ use crate::PlatformWindow as _;
+ let mut installed_handler = test_window.take_input_handler().unwrap();
+ assert!(installed_handler.query_accepts_focused_text_input());
+ assert_eq!(installed_handler.focus_id(), Some(first_focus.id));
+ let second_focus = cx
+ .update_window(window, |_, window, cx| {
+ let second_focus = view.update(cx, |view, cx| {
+ view.focus_handle = cx.focus_handle();
+ cx.notify();
+ view.focus_handle.clone()
+ });
+ window.focus(&second_focus, cx);
+ second_focus
+ })
+ .unwrap();
+ assert!(!installed_handler.query_accepts_focused_text_input());
+ test_window.set_input_handler(installed_handler);
+ cx.update_window(window, |_, window, cx| {
+ window.draw(cx).clear(cx);
+ window.notify_text_input_changed(&first_focus);
+ })
+ .unwrap();
+ assert_eq!(
+ test_window.text_input_state_changes(),
+ [
+ TextInputStateChange::FocusGained,
+ TextInputStateChange::ContentChanged,
+ TextInputStateChange::SelectionChanged,
+ ]
+ );
+
+ let installed_handler = test_window.take_input_handler().unwrap();
+ assert_eq!(installed_handler.focus_id(), Some(second_focus.id));
+ test_window.set_input_handler(installed_handler);
+ cx.update_window(window, |_, window, cx| {
+ window.draw(cx).clear(cx);
+ window.notify_text_selection_changed(&second_focus);
+ })
+ .unwrap();
+
+ view.update(cx, |view, cx| {
+ view.accepts_text_input = false;
+ cx.notify();
+ });
+ cx.update_window(window, |_, window, cx| {
+ window.draw(cx).clear(cx);
+ window.notify_text_input_changed(&second_focus);
+ window.notify_text_selection_changed(&second_focus);
+ let ordinary_focus = cx.focus_handle();
+ window.focus(&ordinary_focus, cx);
+ window.draw(cx).clear(cx);
+ window.notify_text_input_changed(&ordinary_focus);
+ })
+ .unwrap();
+ assert_eq!(
+ test_window.text_input_state_changes(),
+ [
+ TextInputStateChange::FocusGained,
+ TextInputStateChange::ContentChanged,
+ TextInputStateChange::SelectionChanged,
+ TextInputStateChange::SelectionChanged,
+ TextInputStateChange::FocusLost,
+ ]
+ );
+ }
+
struct ConfigurationTestView {
focus_handle: FocusHandle,
configuration: TextInputConfiguration,
+ accepts_text_input: bool,
}
impl Render for ConfigurationTestView {
@@ -407,6 +529,10 @@ mod tests {
}
impl EntityInputHandler for ConfigurationTestView {
+ fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
+ self.accepts_text_input
+ }
+
fn text_for_range(
&mut self,
_range: std::ops::Range<usize>,
diff --git a/crates/gpui/src/key_dispatch.rs b/crates/gpui/src/key_dispatch.rs
index 2f755b1d3dc..0670f88b4a7 100644
--- a/crates/gpui/src/key_dispatch.rs
+++ b/crates/gpui/src/key_dispatch.rs
@@ -1351,6 +1351,14 @@ mod tests {
let count_after_focus_change = *pending_input_changed_count.borrow();
assert!(count_after_focus_change > *count_after_pending_for_assertion.borrow());
});
+ assert_eq!(
+ cx.test_window(cx.window_handle())
+ .text_input_state_changes(),
+ [
+ crate::TextInputStateChange::FocusGained,
+ crate::TextInputStateChange::FocusLost,
+ ]
+ );
cx.update(|window, cx| window.focus(&focus_handle, cx));
cx.simulate_keystrokes("ctrl-b");
diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
index c08d9646fe4..193f94c601c 100644
--- a/crates/gpui/src/platform.rs
+++ b/crates/gpui/src/platform.rs
@@ -1143,6 +1143,10 @@ pub enum AppLifecyclePhase {
Background,
/// Becoming visible again, before input is restored.
Foreground,
+ /// The native scene has disconnected. Its windows may reconnect later.
+ /// This is not a process-termination notification or a guaranteed final
+ /// opportunity to save state.
+ Disconnected,
}
/// Regions of a window that are obscured or reserved by the system.
@@ -1983,6 +1987,7 @@ impl From<TileId> for etagere::AllocId {
pub struct PlatformInputHandler {
cx: AsyncWindowContext,
handler: Box<dyn InputHandler>,
+ focus_id: Option<crate::FocusId>,
}
#[expect(missing_docs)]
@@ -1995,7 +2000,24 @@ pub struct PlatformInputHandler {
)]
impl PlatformInputHandler {
pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
- Self { cx, handler }
+ Self {
+ cx,
+ handler,
+ focus_id: None,
+ }
+ }
+
+ pub(crate) fn with_focus(mut self, focus_id: crate::FocusId) -> Self {
+ self.focus_id = Some(focus_id);
+ self
+ }
+
+ /// Identifies the input field registered through [`Window::handle_input`].
+ ///
+ /// This identity survives adapter replacement during repaint. Backends can
+ /// use it to detect a field change without restarting the keyboard session.
+ pub fn focus_id(&self) -> Option<crate::FocusId> {
+ self.focus_id
}
pub fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
@@ -2082,6 +2104,15 @@ impl PlatformInputHandler {
.flatten()
}
+ pub fn selection_bounds_for_range(&mut self, range_utf16: Range<usize>) -> Vec<Bounds<Pixels>> {
+ self.cx
+ .update(|window, cx| {
+ self.handler
+ .selection_bounds_for_range(range_utf16, window, cx)
+ })
+ .unwrap_or_default()
+ }
+
#[allow(dead_code)]
pub fn apple_press_and_hold_enabled(&mut self) -> bool {
self.handler.apple_press_and_hold_enabled()
@@ -2188,6 +2219,21 @@ impl PlatformInputHandler {
.unwrap_or(true)
}
+ /// Checks eligibility against the current focus, including before the next frame is drawn.
+ ///
+ /// Unlike the legacy acceptance query, this fails closed when the window cannot
+ /// be updated and requires registration through `Window::handle_input`.
+ pub fn query_accepts_focused_text_input(&mut self) -> bool {
+ let focus_id = self.focus_id;
+ self.cx
+ .update(|window, cx| {
+ focus_id.is_some()
+ && window.focus == focus_id
+ && self.handler.accepts_text_input(window, cx)
+ })
+ .unwrap_or(false)
+ }
+
/// See [`InputHandler::prefers_ime_for_printable_keys`].
///
/// This is not a pure delegation to the handler: while a multi-stroke binding is pending this
@@ -2233,10 +2279,10 @@ pub struct UTF16Selection {
pub reversed: bool,
}
-/// Zed's interface for handling text input from the platform's IME system
-/// This is currently a 1:1 exposure of the NSTextInputClient API:
+/// GPUI's interface for native text input, IME composition, and selection.
+/// Platform backends translate their native text protocols into these operations.
///
-/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
+/// Text offsets and ranges use UTF-16 code units unless stated otherwise.
pub trait InputHandler: 'static {
/// Get the range of the user's currently selected text, if any
/// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
@@ -2310,7 +2356,7 @@ pub trait InputHandler: 'static {
}
}
- /// Get the bounds of the given document range in screen coordinates
+ /// Get the bounds of the given document range in window coordinates.
/// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
///
/// This is used for positioning the IME candidate window
@@ -2321,6 +2367,21 @@ pub trait InputHandler: 'static {
cx: &mut App,
) -> Option<Bounds<Pixels>>;
+ /// Returns selection rectangles in document order, in window coordinates.
+ ///
+ /// Return line or shaped-run fragments, not one rectangle per character. The
+ /// first and last rectangles contain the range's start and end respectively.
+ /// Empty means native selection geometry is unavailable; caret/IME geometry can
+ /// still be supplied by `bounds_for_range`.
+ fn selection_bounds_for_range(
+ &mut self,
+ _range_utf16: Range<usize>,
+ _window: &mut Window,
+ _cx: &mut App,
+ ) -> Vec<Bounds<Pixels>> {
+ Vec::new()
+ }
+
/// Get the character offset for the given point in terms of UTF16 characters
///
/// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
diff --git a/crates/gpui/src/platform/test/platform.rs b/crates/gpui/src/platform/test/platform.rs
index 9062c4fe5a6..3c65219d36b 100644
--- a/crates/gpui/src/platform/test/platform.rs
+++ b/crates/gpui/src/platform/test/platform.rs
@@ -3,12 +3,13 @@ use crate::NoopTextSystem;
#[cfg(any(test, feature = "test-support"))]
use crate::PathPromptOptions;
use crate::{
- ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DevicePixels,
- DisplayId, DummyKeyboardMapper, ForegroundExecutor, Keymap, OwnedMenu, Platform,
- PlatformDisplay, PlatformHeadlessRenderer, PlatformKeyboardLayout, PlatformKeyboardMapper,
- PlatformTextSystem, PromptButton, ScreenCaptureFrame, ScreenCaptureSource, ScreenCaptureStream,
- SharedString, SourceMetadata, SystemNotification, SystemNotificationResponse, Task,
- TestDisplay, TestWindow, ThermalState, WindowAppearance, WindowParams, size,
+ ActivityGuard, AnyWindowHandle, AppLifecyclePhase, BackgroundExecutor, ClipboardItem,
+ CursorStyle, DevicePixels, DisplayId, DummyKeyboardMapper, ForegroundExecutor, Keymap,
+ OwnedMenu, Platform, PlatformDisplay, PlatformHeadlessRenderer, PlatformKeyboardLayout,
+ PlatformKeyboardMapper, PlatformTextSystem, PromptButton, ScreenCaptureFrame,
+ ScreenCaptureSource, ScreenCaptureStream, SharedString, SourceMetadata, SystemNotification,
+ SystemNotificationResponse, Task, TestDisplay, TestWindow, ThermalState, WindowAppearance,
+ WindowParams, size,
};
use anyhow::Result;
#[cfg(any(test, feature = "test-support"))]
@@ -55,6 +56,8 @@ pub(crate) struct TestPlatform {
Option<Box<dyn Fn() -> anyhow::Result<Option<Box<dyn PlatformHeadlessRenderer>>>>>,
weak: Weak<Self>,
menus: RefCell<Vec<OwnedMenu>>,
+ pub(crate) app_lifecycle_callback: RefCell<Option<Box<dyn FnMut(AppLifecyclePhase)>>>,
+ pub(crate) memory_warning_callback: RefCell<Option<Box<dyn FnMut()>>>,
}
#[derive(Clone)]
@@ -225,6 +228,8 @@ impl TestPlatform {
text_system,
headless_renderer_factory,
menus: Default::default(),
+ app_lifecycle_callback: Default::default(),
+ memory_warning_callback: Default::default(),
})
}
@@ -657,6 +662,14 @@ impl Platform for TestPlatform {
fn on_system_wake(&self, _callback: Box<dyn FnMut()>) {}
+ fn on_app_lifecycle(&self, callback: Box<dyn FnMut(AppLifecyclePhase)>) {
+ *self.app_lifecycle_callback.borrow_mut() = Some(callback);
+ }
+
+ fn on_memory_warning(&self, callback: Box<dyn FnMut()>) {
+ *self.memory_warning_callback.borrow_mut() = Some(callback);
+ }
+
fn set_app_identity(&self, identifier: &str, name: &str) {
self.system_notifications.borrow_mut().app_identity =
Some((identifier.to_string().into(), name.to_string().into()));
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 1214b0351a2..27c8a3e5b2c 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -21,8 +21,8 @@ use crate::{
SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextInputConfiguration,
TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance,
- WindowBounds, WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
- WindowVisibility, point, prelude::*, px, rems, size, transparent_black,
+ WindowBounds, WindowControls, WindowDecorations, WindowInsets, WindowOptions, WindowParams,
+ WindowTextSystem, WindowVisibility, point, prelude::*, px, rems, size, transparent_black,
};
use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
@@ -1245,7 +1245,7 @@ pub struct Window {
/// window, so that only actual changes are forwarded (reconfiguring a live
/// input session can restart the IME connection).
last_text_input_configuration: Option<TextInputConfiguration>,
- focused_text_input_active: bool,
+ focused_text_input: Option<FocusId>,
pub(crate) image_cache_stack: Vec<AnyImageCache>,
pub(crate) rendered_frame: Frame,
pub(crate) next_frame: Frame,
@@ -2146,7 +2146,7 @@ impl Window {
element_opacity: 1.0,
requested_autoscroll: None,
last_text_input_configuration: None,
- focused_text_input_active: false,
+ focused_text_input: None,
rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
next_frame_callbacks,
@@ -2864,6 +2864,11 @@ impl Window {
self.platform_window.bounds()
}
+ /// Returns the regions of this window obscured by system UI and the keyboard.
+ pub fn insets(&self) -> WindowInsets {
+ self.platform_window.insets()
+ }
+
/// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image.
/// This does not present the frame to screen - useful for visual testing where we want
/// to capture what would be rendered without displaying it or requiring the window to be visible.
@@ -3408,7 +3413,8 @@ impl Window {
self.last_input_modality == InputModality::Keyboard
}
- pub(crate) fn last_input_was_touch(&self) -> bool {
+ /// Returns whether the last input event came from a touch screen.
+ pub fn last_input_was_touch(&self) -> bool {
self.last_input_modality == InputModality::Touch
}
@@ -3479,7 +3485,7 @@ impl Window {
// paint_range indices remain valid for reuse_paint on the next frame.
// Search backwards to find the last Some entry, since reuse_paint may
// have copied None slots from the previous frame. (Fixes #50456)
- let focused_text_input_active = if let Some(mut input_handler) = self
+ let focused_text_input = if let Some(mut input_handler) = self
.next_frame
.input_handlers
.iter_mut()
@@ -3488,15 +3494,15 @@ impl Window {
{
let accepts_text_input = input_handler.accepts_text_input(self, cx);
self.platform_window.set_input_handler(input_handler);
- accepts_text_input
+ self.focus.filter(|_| accepts_text_input)
} else {
- false
+ None
};
self.apply_text_input_configuration(cx);
- if focused_text_input_active != self.focused_text_input_active {
- self.focused_text_input_active = focused_text_input_active;
+ let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
+ if previous.is_some() != focused_text_input.is_some() {
self.platform_window
- .text_input_state_changed(if focused_text_input_active {
+ .text_input_state_changed(if focused_text_input.is_some() {
TextInputStateChange::FocusGained
} else {
TextInputStateChange::FocusLost
@@ -5398,9 +5404,31 @@ impl Window {
if focus_handle.is_focused(self) {
let cx = self.to_async(cx);
- self.next_frame
- .input_handlers
- .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
+ self.next_frame.input_handlers.push(Some(
+ PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
+ ));
+ }
+ }
+
+ /// Notifies native text services that the focused component's text changed.
+ ///
+ /// Text components should call this after application-driven edits, in addition
+ /// to notifying GPUI to redraw. Unfocused or unregistered components are ignored.
+ pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
+ if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
+ self.platform_window
+ .text_input_state_changed(TextInputStateChange::ContentChanged);
+ }
+ }
+
+ /// Notifies native text services that the focused component's selection changed.
+ ///
+ /// Text components should call this after application-driven selection changes,
+ /// in addition to notifying GPUI to redraw.
+ pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
+ if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
+ self.platform_window
+ .text_input_state_changed(TextInputStateChange::SelectionChanged);
}
}
@@ -8229,7 +8257,7 @@ mod tests {
assert!(platform_window.frame_wake_count() > wakes);
platform_window.simulate_frame_request(RequestFrameOptions::default());
let wakes = platform_window.frame_wake_count();
- platform_window.simulate_insets_change(crate::WindowInsets {
+ let insets = crate::WindowInsets {
safe_area: crate::Edges {
top: px(60.),
right: px(20.),
@@ -8240,10 +8268,14 @@ mod tests {
bottom: px(350.),
..Default::default()
},
- });
+ };
+ platform_window.simulate_insets_change(insets.clone());
assert!(platform_window.frame_wake_count() > wakes);
window
- .update(cx, |_, window, _| {
+ .update(cx, |_, window, cx| {
+ let focus = cx.focus_handle();
+ window.focus(&focus, cx);
+ assert_eq!(window.insets(), insets);
assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
assert_eq!(window.visual_viewport_bounds(), visual_bounds);
assert_eq!(
@@ -8252,6 +8284,7 @@ mod tests {
);
window.request_virtual_keyboard();
window.dismiss_virtual_keyboard();
+ assert!(focus.is_focused(window));
assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
})
.unwrap();
@@ -8274,6 +8307,16 @@ mod tests {
);
})
.unwrap();
+
+ // Some backends update geometry snapshots without delivering inset callbacks.
+ use crate::PlatformWindow as _;
+ platform_window.on_insets_changed(Box::new(|_| {}));
+ platform_window.simulate_insets_change(crate::WindowInsets::default());
+ window
+ .update(cx, |_, window, _| {
+ assert_eq!(window.insets(), crate::WindowInsets::default());
+ })
+ .unwrap();
}
struct EmptyView;
diff --git a/crates/gpui_ios/Cargo.toml b/crates/gpui_ios/Cargo.toml
new file mode 100644
index 00000000000..eecaf13ccac
--- /dev/null
+++ b/crates/gpui_ios/Cargo.toml
@@ -0,0 +1,44 @@
+[package]
+name = "gpui_ios"
+version = "0.1.0"
+edition.workspace = true
+publish.workspace = true
+license = "Apache-2.0"
+
+[lints]
+workspace = true
+
+[lib]
+path = "src/gpui_ios.rs"
+crate-type = ["staticlib", "rlib"]
+doctest = false
+
+[[test]]
+name = "text_input"
+path = "tests/text_input.rs"
+harness = false
+
+[features]
+runtime_shaders = ["gpui_apple/runtime_shaders"]
+
+[dependencies]
+gpui.workspace = true
+
+[target.'cfg(target_os = "ios")'.dev-dependencies]
+objc2-ui-kit = { workspace = true, features = ["UIConversationContext"] }
+slotmap.workspace = true
+
+[target.'cfg(target_os = "ios")'.dependencies]
+anyhow.workspace = true
+block2.workspace = true
+futures.workspace = true
+gpui_apple = { workspace = true, features = ["font-kit"] }
+log.workspace = true
+objc2.workspace = true
+objc2-foundation = { workspace = true, features = ["NSThread", "NSOperation", "block2"] }
+objc2-ui-kit.workspace = true
+objc2-quartz-core = { workspace = true, features = ["CADisplayLink"] }
+objc2-core-foundation = { workspace = true, default-features = true }
+parking_lot.workspace = true
+raw-window-handle.workspace = true
+uuid = { workspace = true, features = ["v5"] }
diff --git a/crates/gpui_ios/LICENSE-APACHE b/crates/gpui_ios/LICENSE-APACHE
new file mode 120000
index 00000000000..1cd601d0a3a
--- /dev/null
+++ b/crates/gpui_ios/LICENSE-APACHE
@@ -0,0 +1 @@
+../../LICENSE-APACHE
\ No newline at end of file
diff --git a/crates/gpui_ios/examples/ios/Cargo.toml b/crates/gpui_ios/examples/ios/Cargo.toml
new file mode 100644
index 00000000000..41e1b7ca03e
--- /dev/null
+++ b/crates/gpui_ios/examples/ios/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+name = "gpui_ios_example"
+version = "0.1.0"
+edition.workspace = true
+publish = false
+license = "Apache-2.0"
+
+[lints]
+workspace = true
+
+[[bin]]
+name = "gpui_ios_example"
+path = "src/gpui_ios_example.rs"
+test = false
+bench = false
+
+[target.'cfg(target_os = "ios")'.dependencies]
+gpui.workspace = true
+gpui_ios.workspace = true
+gpui_platform.workspace = true
diff --git a/crates/gpui_ios/examples/ios/LICENSE-APACHE b/crates/gpui_ios/examples/ios/LICENSE-APACHE
new file mode 120000
index 00000000000..15824831a24
--- /dev/null
+++ b/crates/gpui_ios/examples/ios/LICENSE-APACHE
@@ -0,0 +1 @@
+../../../../LICENSE-APACHE
\ No newline at end of file
diff --git a/crates/gpui_ios/examples/ios/app/Info.plist b/crates/gpui_ios/examples/ios/app/Info.plist
new file mode 100644
index 00000000000..55221922d79
--- /dev/null
+++ b/crates/gpui_ios/examples/ios/app/Info.plist
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleExecutable</key>
+ <string>gpui_ios_example</string>
+ <key>CFBundleIdentifier</key>
+ <string>dev.zed.gpui-ios-example</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>GPUIIosExample</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>1.0</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>MinimumOSVersion</key>
+ <string>15.0</string>
+ <key>UIApplicationSceneManifest</key>
+ <dict>
+ <key>UIApplicationSupportsMultipleScenes</key>
+ <false/>
+ <key>UISceneConfigurations</key>
+ <dict>
+ <key>UIWindowSceneSessionRoleApplication</key>
+ <array>
+ <dict>
+ <key>UISceneConfigurationName</key>
+ <string>Default Configuration</string>
+ <!-- Restored sessions may skip the app delegate's configuration callback. -->
+ <key>UISceneDelegateClassName</key>
+ <string>GPUIIosSceneDelegate</string>
+ </dict>
+ </array>
+ </dict>
+ </dict>
+ <key>UILaunchScreen</key>
+ <dict/>
+ <key>UIRequiresFullScreen</key>
+ <true/>
+ <key>UISupportedInterfaceOrientations</key>
+ <array>
+ <string>UIInterfaceOrientationPortrait</string>
+ <string>UIInterfaceOrientationLandscapeLeft</string>
+ <string>UIInterfaceOrientationLandscapeRight</string>
+ </array>
+</dict>
+</plist>
diff --git a/crates/gpui_ios/examples/ios/build-simulator.sh b/crates/gpui_ios/examples/ios/build-simulator.sh
new file mode 100755
index 00000000000..390955f54dc
--- /dev/null
+++ b/crates/gpui_ios/examples/ios/build-simulator.sh
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+repository_root="$(git rev-parse --show-toplevel)"
+example_directory="$repository_root/crates/gpui_ios/examples/ios"
+target_directory="${CARGO_TARGET_DIR:-"$repository_root/target"}"
+if [[ "$target_directory" != /* ]]; then
+ target_directory="$repository_root/$target_directory"
+fi
+app_directory="$target_directory/gpui-ios-example/GPUIIosExample.app"
+
+cd "$repository_root"
+mkdir -p "$target_directory"
+build_output="$(mktemp "$target_directory/gpui-ios-build.XXXXXX")"
+trap 'rm -f "$build_output"' EXIT
+
+# Corgi does not currently support iOS targets. Extra arguments are passed to Cargo.
+IPHONEOS_DEPLOYMENT_TARGET=15.0 \
+ cargo build -p gpui_ios_example --target aarch64-apple-ios-sim \
+ --message-format=json-render-diagnostics "$@" > "$build_output"
+
+executable="$(python3 - "$build_output" <<'PY'
+import json
+import sys
+
+with open(sys.argv[1]) as output:
+ executables = [
+ event["executable"]
+ for event in map(json.loads, output)
+ if event.get("reason") == "compiler-artifact"
+ and event.get("target", {}).get("name") == "gpui_ios_example"
+ and event.get("executable")
+ ]
+if len(executables) != 1:
+ sys.exit("Expected one gpui_ios_example executable in Cargo's build output")
+print(executables[0])
+PY
+)"
+mkdir -p "$app_directory"
+cp "$executable" "$app_directory/gpui_ios_example"
+cp "$example_directory/app/Info.plist" "$app_directory/Info.plist"
+codesign --force --sign - "$app_directory"
+printf 'Built simulator app: %s\n' "$app_directory"
diff --git a/crates/gpui_ios/examples/ios/src/gpui_ios_example.rs b/crates/gpui_ios/examples/ios/src/gpui_ios_example.rs
new file mode 100644
index 00000000000..de6c401d329
--- /dev/null
+++ b/crates/gpui_ios/examples/ios/src/gpui_ios_example.rs
@@ -0,0 +1,64 @@
+//! Native iOS smoke application for GPUI.
+//!
+//! This uses the same platform-neutral application entry point as desktop GPUI apps.
+
+#[cfg(target_os = "ios")]
+use gpui::{Context, Window, WindowOptions, div, prelude::*, px, rgb};
+
+#[cfg(target_os = "ios")]
+struct IosExample {
+ tap_count: usize,
+}
+
+#[cfg(target_os = "ios")]
+impl Render for IosExample {
+ fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ div()
+ .size_full()
+ .flex()
+ .flex_col()
+ .items_center()
+ .justify_center()
+ .gap_6()
+ .bg(rgb(0x101622))
+ .text_color(rgb(0xf5f7ff))
+ .child(div().text_3xl().child("GPUI on iOS"))
+ .child(
+ div()
+ .id("tap-counter")
+ .px_6()
+ .py_3()
+ .rounded_lg()
+ .bg(rgb(0x246bfd))
+ .text_xl()
+ .on_click(cx.listener(|this, _, _, cx| {
+ this.tap_count += 1;
+ cx.notify();
+ }))
+ .child(format!("Taps: {}", self.tap_count)),
+ )
+ .child(
+ div()
+ .max_w(px(320.))
+ .text_center()
+ .child("Rust app, native UIKit loop, GPUI rendering"),
+ )
+ }
+}
+
+#[cfg(target_os = "ios")]
+fn main() {
+ gpui_platform::application().run(|cx| {
+ gpui_ios::ios::set_status_bar_style(gpui_ios::StatusBarContentStyle::Light);
+ cx.open_window(WindowOptions::default(), |_, cx| {
+ cx.new(|_| IosExample { tap_count: 0 })
+ })
+ .unwrap();
+ cx.activate(true);
+ });
+}
+
+#[cfg(not(target_os = "ios"))]
+fn main() {
+ eprintln!("Build this example for an iOS target and package it with build-simulator.sh.");
+}
diff --git a/crates/gpui_ios/src/gpui_ios.rs b/crates/gpui_ios/src/gpui_ios.rs
new file mode 100644
index 00000000000..00650aa4a8c
--- /dev/null
+++ b/crates/gpui_ios/src/gpui_ios.rs
@@ -0,0 +1,21 @@
+//! Native iOS platform support for GPUI.
+//!
+//! This crate connects GPUI to UIKit, CoreText, and Metal through the shared
+//! Apple renderer. It owns iOS application lifecycle, windowing, native
+//! text input, safe-area and keyboard insets, and raw touch delivery.
+
+#[cfg(target_os = "ios")]
+pub mod ios;
+
+#[cfg(target_os = "ios")]
+pub use ios::{IosPlatform, current_platform};
+
+/// The foreground color used by the iOS status bar.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum StatusBarContentStyle {
+ /// Light status-bar content for dark backgrounds.
+ Light,
+ /// Dark status-bar content for light backgrounds.
+ #[default]
+ Dark,
+}
diff --git a/crates/gpui_ios/src/ios.rs b/crates/gpui_ios/src/ios.rs
new file mode 100644
index 00000000000..350a36db859
--- /dev/null
+++ b/crates/gpui_ios/src/ios.rs
@@ -0,0 +1,58 @@
+//! UIKit-backed implementation details for the iOS GPUI platform.
+
+mod application;
+mod display;
+mod events;
+mod platform;
+mod text_input;
+mod window;
+
+use std::cell::{Cell, RefCell};
+
+pub(super) struct CallbackSlot<T> {
+ value: RefCell<Option<T>>,
+ generation: Cell<u64>,
+}
+
+impl<T> Default for CallbackSlot<T> {
+ fn default() -> Self {
+ Self {
+ value: RefCell::new(None),
+ generation: Cell::new(0),
+ }
+ }
+}
+
+impl<T> CallbackSlot<T> {
+ pub(super) fn set(&self, value: T) {
+ self.generation.set(self.generation.get().wrapping_add(1));
+ drop(self.value.replace(Some(value)));
+ }
+
+ pub(super) fn take(&self) -> Option<T> {
+ // Even an empty take can mean the focused handler was withdrawn during a callback.
+ self.generation.set(self.generation.get().wrapping_add(1));
+ self.value.borrow_mut().take()
+ }
+
+ pub(super) fn with<R>(&self, callback: impl FnOnce(&mut T) -> R) -> Option<R> {
+ let mut value = self.value.borrow_mut().take()?;
+ let generation = self.generation.get();
+ let result = callback(&mut value);
+ // Do not resurrect a handler that application code replaced or removed.
+ if self.generation.get() == generation {
+ drop(self.value.replace(Some(value)));
+ }
+ Some(result)
+ }
+}
+
+pub(crate) use display::*;
+pub use platform::*;
+pub use window::set_status_bar_style;
+pub(crate) use window::*;
+
+/// Returns the native platform implementation for iOS.
+pub fn current_platform(_headless: bool) -> std::rc::Rc<dyn gpui::Platform> {
+ std::rc::Rc::new(IosPlatform::new())
+}
diff --git a/crates/gpui_ios/src/ios/application.rs b/crates/gpui_ios/src/ios/application.rs
new file mode 100644
index 00000000000..aac23f33f1d
--- /dev/null
+++ b/crates/gpui_ios/src/ios/application.rs
@@ -0,0 +1,482 @@
+use super::{CallbackSlot, platform::IosPlatformState, window::IosWindowState};
+use gpui::{AppLifecyclePhase, WindowVisibility};
+use objc2::{
+ ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, extern_class,
+ extern_methods, msg_send,
+ rc::{Allocated, Retained},
+ runtime::AnyObject,
+ sel,
+};
+use objc2_foundation::{
+ NSDictionary, NSObject, NSObjectProtocol, NSRunLoop, NSRunLoopCommonModes, NSSet, NSString,
+};
+use objc2_quartz_core::CADisplayLink;
+use objc2_ui_kit::{
+ UIApplication, UIApplicationDelegate, UIApplicationLaunchOptionsKey, UIOpenURLContext, UIScene,
+ UISceneConfiguration, UISceneConnectionOptions, UISceneDelegate, UISceneSession, UIWindowScene,
+ UIWindowSceneDelegate,
+};
+use std::{
+ cell::{Cell, RefCell},
+ rc::{Rc, Weak},
+};
+
+#[derive(Default)]
+pub(super) struct IosApplicationState {
+ running: Cell<bool>,
+ finish_launching: CallbackSlot<Box<dyn FnOnce()>>,
+ pub(super) quit: CallbackSlot<Box<dyn FnMut()>>,
+ pub(super) open_urls: CallbackSlot<Box<dyn FnMut(Vec<String>)>>,
+ pub(super) app_lifecycle: CallbackSlot<Box<dyn FnMut(AppLifecyclePhase)>>,
+ pub(super) memory_warning: CallbackSlot<Box<dyn FnMut()>>,
+ scene: RefCell<Option<Retained<UIWindowScene>>>,
+ // The link retains its delegate target, which only weakly references this state.
+ display_link: RefCell<Option<Retained<CADisplayLink>>>,
+ windows: RefCell<Vec<Weak<IosWindowState>>>,
+}
+
+thread_local! {
+ // UIKit constructs delegates by class name, including on scene restoration.
+ // Only delegate initialization and the legacy status-bar setter consult this.
+ static CURRENT_PLATFORM: RefCell<Weak<IosPlatformState>> = RefCell::default();
+}
+
+pub(super) fn current_platform() -> Option<Rc<IosPlatformState>> {
+ CURRENT_PLATFORM.with_borrow(Weak::upgrade)
+}
+
+pub(super) fn run(platform: &Rc<IosPlatformState>, on_finish_launching: Box<dyn FnOnce()>) {
+ let main_thread = MainThreadMarker::new().expect("UIKit requires the main thread");
+ CURRENT_PLATFORM.with_borrow_mut(|current| {
+ assert!(
+ current.upgrade().is_none(),
+ "the iOS application is already running"
+ );
+ *current = Rc::downgrade(platform);
+ });
+ assert!(
+ !platform.application.running.replace(true),
+ "the iOS application is already running"
+ );
+ platform
+ .application
+ .finish_launching
+ .set(on_finish_launching);
+ // UIKit can restore a scene delegate by class name without asking for a new configuration.
+ SceneDelegate::class();
+ let delegate_class = NSString::from_class(AppDelegate::class());
+ UIApplication::main(None, Some(&delegate_class), main_thread);
+}
+
+impl IosApplicationState {
+ fn set_display_link_paused(&self, paused: bool) {
+ let display_link = self.display_link.borrow().clone();
+ if let Some(display_link) = display_link {
+ display_link.setPaused(paused);
+ }
+ }
+
+ fn stop_display_link(&self) {
+ let display_link = self.display_link.borrow_mut().take();
+ if let Some(display_link) = display_link {
+ display_link.invalidate();
+ }
+ }
+
+ pub(super) fn window_scene(&self) -> Option<Retained<UIWindowScene>> {
+ self.scene.borrow().clone()
+ }
+
+ pub(super) fn register_window(&self, window: &Rc<IosWindowState>) {
+ self.windows.borrow_mut().push(Rc::downgrade(window));
+ }
+
+ pub(super) fn unregister_window(&self, window: &Rc<IosWindowState>) {
+ let window = Rc::downgrade(window);
+ self.windows
+ .borrow_mut()
+ .retain(|entry| !entry.ptr_eq(&window));
+ }
+
+ pub(super) fn with_windows(&self, mut callback: impl FnMut(&IosWindowState)) {
+ // Native callbacks may open or close windows. Do not hold a registry borrow
+ // across them, and skip snapshot entries that have since been unregistered.
+ let windows = self.windows.borrow().clone();
+ for window in windows {
+ if self
+ .windows
+ .borrow()
+ .iter()
+ .any(|entry| entry.ptr_eq(&window))
+ {
+ // The snapshot's Weak keeps its allocation identity from being reused.
+ // The strong guard survives synchronous closure of this window.
+ if let Some(window) = window.upgrade() {
+ callback(&window);
+ }
+ }
+ }
+ }
+
+ fn finish_launching(&self) {
+ let callback = self.finish_launching.take();
+ if let Some(callback) = callback {
+ callback();
+ }
+ }
+
+ fn notify_memory_warning(&self) {
+ self.memory_warning.with(|callback| callback());
+ }
+
+ fn notify_app_lifecycle(&self, phase: AppLifecyclePhase) {
+ match phase {
+ AppLifecyclePhase::Foreground => self.with_windows(|window| {
+ window.notify_visibility_change(WindowVisibility::Visible);
+ }),
+ AppLifecyclePhase::Active => {
+ self.with_windows(|window| window.notify_active_status_change(true));
+ }
+ AppLifecyclePhase::Inactive => {
+ self.with_windows(|window| window.notify_active_status_change(false));
+ }
+ AppLifecyclePhase::Background | AppLifecyclePhase::Disconnected => {
+ self.with_windows(|window| window.notify_active_status_change(false));
+ // An activation observer may have closed a window; revisit the registry.
+ self.with_windows(|window| {
+ window.notify_visibility_change(WindowVisibility::Hidden)
+ });
+ }
+ }
+ self.app_lifecycle.with(|callback| callback(phase));
+ }
+
+ fn open_urls(&self, contexts: &NSSet<UIOpenURLContext>) {
+ if contexts.is_empty() {
+ return;
+ }
+ let urls = contexts
+ .iter()
+ .filter_map(|context| context.URL().absoluteString().map(|url| url.to_string()))
+ .collect();
+ self.open_urls.with(|callback| callback(urls));
+ }
+}
+
+impl Drop for IosApplicationState {
+ fn drop(&mut self) {
+ self.stop_display_link();
+ }
+}
+
+extern_class!(
+ #[unsafe(super = NSObject)]
+ #[name = "UISceneConnectionOptions"]
+ struct SceneConnectionOptions;
+);
+
+impl SceneConnectionOptions {
+ extern_methods!(
+ // iOS 18 can return nil on an ordinary launch despite the SDK's nonnull annotation.
+ #[unsafe(method(URLContexts))]
+ #[unsafe(method_family = none)]
+ fn url_contexts(&self) -> Option<Retained<NSSet<UIOpenURLContext>>>;
+ );
+}
+
+define_class!(
+ #[unsafe(super = NSObject)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUIIosAppDelegate"]
+ #[ivars = Weak<IosPlatformState>]
+ struct AppDelegate;
+
+ unsafe impl NSObjectProtocol for AppDelegate {}
+
+ impl AppDelegate {
+ #[unsafe(method_id(init))]
+ fn init(this: Allocated<Self>) -> Retained<Self> {
+ let platform = current_platform()
+ .map(|platform| Rc::downgrade(&platform))
+ .unwrap_or_default();
+ let this = this.set_ivars(platform);
+ unsafe { msg_send![super(this), init] }
+ }
+ }
+
+ unsafe impl UIApplicationDelegate for AppDelegate {
+ #[unsafe(method(application:didFinishLaunchingWithOptions:))]
+ unsafe fn did_finish_launching(
+ &self,
+ _application: &UIApplication,
+ _options: Option<&NSDictionary<UIApplicationLaunchOptionsKey, AnyObject>>,
+ ) -> bool {
+ // GPUI's launch callback runs when a scene is ready to host its window.
+ true
+ }
+
+ #[unsafe(method_id(application:configurationForConnectingSceneSession:options:))]
+ fn configuration_for_scene(
+ &self,
+ _application: &UIApplication,
+ session: &UISceneSession,
+ _options: &UISceneConnectionOptions,
+ ) -> Retained<UISceneConfiguration> {
+ let configuration = UISceneConfiguration::initWithName_sessionRole(
+ UISceneConfiguration::alloc(self.mtm()),
+ Some(&NSString::from_str("Default Configuration")),
+ &session.role(),
+ );
+ unsafe {
+ configuration.setDelegateClass(Some(SceneDelegate::class()));
+ }
+ configuration
+ }
+
+ #[unsafe(method(applicationDidReceiveMemoryWarning:))]
+ fn did_receive_memory_warning(&self, _application: &UIApplication) {
+ if let Some(platform) = self.ivars().upgrade() {
+ platform.application.notify_memory_warning();
+ }
+ }
+
+ #[unsafe(method(applicationWillTerminate:))]
+ fn will_terminate(&self, _application: &UIApplication) {
+ if let Some(platform) = self.ivars().upgrade() {
+ if let Some(mut callback) = platform.application.quit.take() {
+ callback();
+ }
+ }
+ }
+ }
+);
+
+define_class!(
+ #[unsafe(super = NSObject)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUIIosSceneDelegate"]
+ #[ivars = Weak<IosPlatformState>]
+ struct SceneDelegate;
+
+ unsafe impl NSObjectProtocol for SceneDelegate {}
+ unsafe impl UIWindowSceneDelegate for SceneDelegate {}
+
+ impl SceneDelegate {
+ #[unsafe(method_id(init))]
+ fn init(this: Allocated<Self>) -> Retained<Self> {
+ let platform = current_platform()
+ .map(|platform| Rc::downgrade(&platform))
+ .unwrap_or_default();
+ let this = this.set_ivars(platform);
+ unsafe { msg_send![super(this), init] }
+ }
+
+ #[unsafe(method(renderFrame:))]
+ fn render_frame(&self, _display_link: &CADisplayLink) {
+ if let Some(platform) = self.ivars().upgrade() {
+ platform.application.with_windows(IosWindowState::request_frame);
+ }
+ }
+ }
+
+ unsafe impl UISceneDelegate for SceneDelegate {
+ #[unsafe(method(scene:willConnectToSession:options:))]
+ fn will_connect(
+ &self,
+ scene: &UIScene,
+ _session: &UISceneSession,
+ options: &SceneConnectionOptions,
+ ) {
+ let Some(scene) = scene.downcast_ref::<UIWindowScene>() else {
+ return;
+ };
+ let Some(platform) = self.ivars().upgrade() else {
+ return;
+ };
+ let application = &platform.application;
+ if application.window_scene().is_some() {
+ log::error!("GPUI iOS currently supports one connected window scene");
+ return;
+ }
+ *application.scene.borrow_mut() = Some(scene.retain());
+ application.finish_launching();
+ // UIKit can reconnect a scene without restarting the Rust application.
+ application.with_windows(|window| window.attach_to_scene(scene));
+ if let Some(contexts) = options.url_contexts() {
+ application.open_urls(&contexts);
+ }
+
+ application.stop_display_link();
+ let display_link = unsafe {
+ let display_link =
+ CADisplayLink::displayLinkWithTarget_selector(self, sel!(renderFrame:));
+ display_link.setPaused(true);
+ display_link.addToRunLoop_forMode(
+ &NSRunLoop::mainRunLoop(),
+ NSRunLoopCommonModes,
+ );
+ display_link
+ };
+ *application.display_link.borrow_mut() = Some(display_link);
+ }
+
+ #[unsafe(method(sceneDidDisconnect:))]
+ fn did_disconnect(&self, scene: &UIScene) {
+ if let Some(platform) = self.platform_for_scene(scene) {
+ platform.application.stop_display_link();
+ platform.application.scene.borrow_mut().take();
+ platform.application.notify_app_lifecycle(AppLifecyclePhase::Disconnected);
+ }
+ }
+
+ #[unsafe(method(sceneWillEnterForeground:))]
+ fn will_enter_foreground(&self, scene: &UIScene) {
+ if let Some(platform) = self.platform_for_scene(scene) {
+ platform.application.set_display_link_paused(false);
+ platform.application.notify_app_lifecycle(AppLifecyclePhase::Foreground);
+ }
+ }
+
+ #[unsafe(method(sceneDidBecomeActive:))]
+ fn did_become_active(&self, scene: &UIScene) {
+ if let Some(platform) = self.platform_for_scene(scene) {
+ platform.application.notify_app_lifecycle(AppLifecyclePhase::Active);
+ }
+ }
+
+ #[unsafe(method(sceneWillResignActive:))]
+ fn will_resign_active(&self, scene: &UIScene) {
+ if let Some(platform) = self.platform_for_scene(scene) {
+ platform.application.notify_app_lifecycle(AppLifecyclePhase::Inactive);
+ }
+ }
+
+ #[unsafe(method(sceneDidEnterBackground:))]
+ fn did_enter_background(&self, scene: &UIScene) {
+ if let Some(platform) = self.platform_for_scene(scene) {
+ platform.application.set_display_link_paused(true);
+ platform.application.notify_app_lifecycle(AppLifecyclePhase::Background);
+ }
+ }
+
+ #[unsafe(method(scene:openURLContexts:))]
+ fn open_url_contexts(&self, scene: &UIScene, contexts: &NSSet<UIOpenURLContext>) {
+ if let Some(platform) = self.platform_for_scene(scene) {
+ platform.application.open_urls(contexts);
+ }
+ }
+ }
+);
+
+impl SceneDelegate {
+ fn platform_for_scene(&self, scene: &UIScene) -> Option<Rc<IosPlatformState>> {
+ let platform = self.ivars().upgrade()?;
+ let owns_scene = platform
+ .application
+ .window_scene()
+ .is_some_and(|current| std::ptr::eq::<UIScene>(&**current, scene));
+ owns_scene.then_some(platform)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::{cell::Cell, rc::Rc};
+
+ #[test]
+ fn launch_callback_runs_once_and_can_register_callbacks() {
+ let state = Rc::new(IosApplicationState::default());
+ let launches = Rc::new(Cell::new(0));
+ state.finish_launching.set(Box::new({
+ let state = Rc::downgrade(&state);
+ let launches = launches.clone();
+ move || {
+ launches.set(launches.get() + 1);
+ state.upgrade().unwrap().memory_warning.set(Box::new(|| {}));
+ }
+ }));
+ state.finish_launching();
+ state.finish_launching();
+ assert_eq!(launches.get(), 1);
+ assert!(state.memory_warning.take().is_some());
+ }
+
+ #[test]
+ fn lifecycle_callback_replacement_survives_dispatch() {
+ let state = Rc::new(IosApplicationState::default());
+ let events = Rc::new(RefCell::new(Vec::new()));
+ state.app_lifecycle.set(Box::new({
+ let state = Rc::downgrade(&state);
+ let events = events.clone();
+ move |phase| {
+ events.borrow_mut().push((0, phase));
+ state.upgrade().unwrap().app_lifecycle.set(Box::new({
+ let events = events.clone();
+ move |phase| events.borrow_mut().push((1, phase))
+ }));
+ }
+ }));
+ state.notify_app_lifecycle(AppLifecyclePhase::Foreground);
+ state.notify_app_lifecycle(AppLifecyclePhase::Active);
+ assert_eq!(
+ *events.borrow(),
+ [
+ (0, AppLifecyclePhase::Foreground),
+ (1, AppLifecyclePhase::Active)
+ ]
+ );
+ }
+
+ #[test]
+ fn memory_warning_callback_is_restored_after_dispatch() {
+ let state = Rc::new(IosApplicationState::default());
+ let warnings = Rc::new(Cell::new(0));
+ state.memory_warning.set(Box::new({
+ let state = Rc::downgrade(&state);
+ let warnings = warnings.clone();
+ move || {
+ warnings.set(warnings.get() + 1);
+ state.upgrade().unwrap().quit.set(Box::new(|| {}));
+ }
+ }));
+ state.notify_memory_warning();
+ state.notify_memory_warning();
+ assert_eq!(warnings.get(), 2);
+ assert!(state.quit.take().is_some());
+ }
+
+ #[test]
+ fn lifecycle_removal_survives_reentrant_dispatch() {
+ let state = Rc::new(IosApplicationState::default());
+ let events = Rc::new(RefCell::new(Vec::new()));
+ state.app_lifecycle.set(Box::new({
+ let state = Rc::downgrade(&state);
+ let events = events.clone();
+ move |phase| {
+ events.borrow_mut().push(phase);
+ let state = state.upgrade().unwrap();
+ state.app_lifecycle.take();
+ state.notify_app_lifecycle(AppLifecyclePhase::Inactive);
+ }
+ }));
+ state.notify_app_lifecycle(AppLifecyclePhase::Disconnected);
+ state.notify_app_lifecycle(AppLifecyclePhase::Foreground);
+ assert_eq!(*events.borrow(), [AppLifecyclePhase::Disconnected]);
+ }
+
+ #[test]
+ fn application_callbacks_are_not_shared_between_platforms() {
+ let first = IosApplicationState::default();
+ let second = IosApplicationState::default();
+ let warnings = Rc::new(Cell::new(0));
+ first.memory_warning.set(Box::new({
+ let warnings = warnings.clone();
+ move || warnings.set(warnings.get() + 1)
+ }));
+ second.notify_memory_warning();
+ assert_eq!(warnings.get(), 0);
+ first.notify_memory_warning();
+ assert_eq!(warnings.get(), 1);
+ }
+}
diff --git a/crates/gpui_ios/src/ios/display.rs b/crates/gpui_ios/src/ios/display.rs
new file mode 100644
index 00000000000..c142a31583d
--- /dev/null
+++ b/crates/gpui_ios/src/ios/display.rs
@@ -0,0 +1,96 @@
+//! iOS display handling using UIScreen.
+//!
+//! iOS has a simpler display model than macOS - typically just the main screen
+//! and possibly an external display via AirPlay or USB-C.
+
+use anyhow::Result;
+use gpui::{Bounds, DisplayId, Pixels, PlatformDisplay, px, size};
+use objc2::{MainThreadMarker, rc::Retained};
+use objc2_core_foundation::CGRect;
+use objc2_ui_kit::UIScreen;
+use std::time::Duration;
+use uuid::Uuid;
+
+/// Represents an iOS display (UIScreen).
+#[derive(Debug)]
+pub(crate) struct IosDisplay {
+ /// The UIScreen object
+ screen: Retained<UIScreen>,
+}
+
+unsafe impl Send for IosDisplay {}
+unsafe impl Sync for IosDisplay {}
+
+impl IosDisplay {
+ pub fn from_screen(screen: Retained<UIScreen>) -> Self {
+ Self { screen }
+ }
+
+ /// Get the main screen.
+ #[allow(deprecated)] // Platform display queries can precede scene creation.
+ pub fn main() -> Self {
+ let screen =
+ UIScreen::mainScreen(MainThreadMarker::new().expect("UIKit requires the main thread"));
+ Self { screen }
+ }
+
+ /// Get all connected screens.
+ #[allow(deprecated)] // Preserve external screens even before they have a GPUI scene.
+ pub fn all() -> impl Iterator<Item = Self> {
+ let screens =
+ UIScreen::screens(MainThreadMarker::new().expect("UIKit requires the main thread"));
+ screens.to_vec().into_iter().map(|screen| Self { screen })
+ }
+
+ /// Get the screen bounds in points.
+ fn bounds_in_points(&self) -> CGRect {
+ self.screen.bounds()
+ }
+
+ /// Get the native scale factor of this screen.
+ pub fn native_scale(&self) -> f32 {
+ self.screen.nativeScale() as f32
+ }
+
+ /// Get the current scale factor (may differ from native if zoomed).
+ pub fn scale(&self) -> f32 {
+ self.screen.scale() as f32
+ }
+}
+
+impl PlatformDisplay for IosDisplay {
+ fn refresh_interval(&self) -> Option<Duration> {
+ gpui::refresh_interval_from_hz(self.screen.maximumFramesPerSecond() as f64)
+ }
+
+ fn id(&self) -> DisplayId {
+ // iOS doesn't have display IDs like macOS, so we use the screen pointer as an ID
+ DisplayId::new(Retained::as_ptr(&self.screen) as u64)
+ }
+
+ fn uuid(&self) -> Result<Uuid> {
+ // iOS doesn't provide persistent UUIDs for displays like macOS does.
+ // We generate a deterministic UUID based on the screen properties.
+ let bounds = self.bounds_in_points();
+ let scale = self.native_scale();
+
+ // Create a deterministic UUID from screen properties
+ let bytes = format!(
+ "ios-screen-{}-{}-{}",
+ bounds.size.width as u32,
+ bounds.size.height as u32,
+ (scale * 100.0) as u32
+ );
+
+ Ok(Uuid::new_v5(&Uuid::NAMESPACE_OID, bytes.as_bytes()))
+ }
+
+ fn bounds(&self) -> Bounds<Pixels> {
+ let bounds = self.bounds_in_points();
+
+ Bounds {
+ origin: Default::default(),
+ size: size(px(bounds.size.width as f32), px(bounds.size.height as f32)),
+ }
+ }
+}
diff --git a/crates/gpui_ios/src/ios/events.rs b/crates/gpui_ios/src/ios/events.rs
new file mode 100644
index 00000000000..0cb93587dbd
--- /dev/null
+++ b/crates/gpui_ios/src/ios/events.rs
@@ -0,0 +1,30 @@
+//! Conversion from UIKit events to GPUI input events.
+
+use gpui::{Pixels, Point, TouchId, TouchPhase, px};
+use objc2_ui_kit::{UITouch, UITouchPhase, UIView};
+
+pub fn touch_location_in_view(touch: &UITouch, view: &UIView) -> Point<Pixels> {
+ let location = touch.locationInView(Some(view));
+ Point::new(px(location.x as f32), px(location.y as f32))
+}
+
+pub fn touch_phase(touch: &UITouch) -> TouchPhase {
+ match touch.phase() {
+ UITouchPhase::Began => TouchPhase::Started,
+ UITouchPhase::Moved | UITouchPhase::Stationary => TouchPhase::Moved,
+ UITouchPhase::Ended => TouchPhase::Ended,
+ _ => TouchPhase::Cancelled,
+ }
+}
+
+pub fn touch_id(touch: &UITouch) -> TouchId {
+ TouchId(touch as *const UITouch as usize as u64)
+}
+
+pub fn touch_force(touch: &UITouch) -> Option<f32> {
+ let maximum_force = touch.maximumPossibleForce();
+ if maximum_force <= 0.0 {
+ return None;
+ }
+ Some((touch.force() / maximum_force).clamp(0.0, 1.0) as f32)
+}
diff --git a/crates/gpui_ios/src/ios/platform.rs b/crates/gpui_ios/src/ios/platform.rs
new file mode 100644
index 00000000000..9463e235ad1
--- /dev/null
+++ b/crates/gpui_ios/src/ios/platform.rs
@@ -0,0 +1,501 @@
+//! iOS Platform implementation.
+//!
+//! This implements the Platform trait for iOS using UIKit.
+//! Key differences from macOS:
+//! - Uses UIApplication instead of NSApplication
+//! - No menu bar (iOS apps don't have traditional menus)
+//! - No windowed mode (iOS apps are always fullscreen on their display)
+//! - Touch-based input instead of mouse
+//! - System keyboard handling differs significantly
+
+use super::{CallbackSlot, application::IosApplicationState};
+use super::{IosDisplay, IosWindow};
+use anyhow::anyhow;
+use block2::RcBlock;
+use futures::{
+ StreamExt,
+ channel::{mpsc, oneshot},
+};
+use gpui::{
+ Action, AnyWindowHandle, AppLifecyclePhase, BackgroundExecutor, ClipboardItem, CursorStyle,
+ DummyKeyboardMapper, ForegroundExecutor, Keymap, Menu, MenuItem, PathPromptOptions, Platform,
+ PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
+ PlatformWindow, Result, Task, ThermalState, WindowAppearance, WindowParams,
+};
+use gpui_apple::{
+ AppleDispatcher, keychain,
+ thermal::{self, ThermalObserver},
+};
+use objc2::{MainThreadMarker, MainThreadOnly, rc::Retained, runtime::ProtocolObject};
+use objc2_foundation::{
+ NSBundle, NSDictionary, NSNotification, NSNotificationCenter, NSObjectProtocol, NSString, NSURL,
+};
+use objc2_ui_kit::{
+ UIApplication, UIPasteboard, UIScreenModeDidChangeNotification, UITraitEnvironment,
+ UIUserInterfaceStyle, UIViewController,
+};
+#[allow(deprecated)]
+// Match UIScreen enumeration, including displays without a connected scene.
+use objc2_ui_kit::{UIScreenDidConnectNotification, UIScreenDidDisconnectNotification};
+use std::{
+ cell::RefCell,
+ path::{Path, PathBuf},
+ rc::Rc,
+ sync::Arc,
+};
+
+pub struct IosPlatform(Rc<IosPlatformState>);
+
+pub(crate) struct IosPlatformState {
+ pub(super) application: IosApplicationState,
+ background_executor: BackgroundExecutor,
+ foreground_executor: ForegroundExecutor,
+ text_system: Arc<dyn PlatformTextSystem>,
+ thermal_observer: RefCell<Option<ThermalObserver>>,
+ display_observers: RefCell<Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>>,
+ display_task: RefCell<Option<Task<()>>>,
+ displays_changed_callback: CallbackSlot<Box<dyn FnMut()>>,
+}
+
+impl Default for IosPlatform {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl IosPlatform {
+ pub fn new() -> Self {
+ let dispatcher = Arc::new(AppleDispatcher::new());
+
+ let text_system: Arc<dyn PlatformTextSystem> = Arc::new(gpui_apple::AppleTextSystem::new());
+
+ let state = Rc::new(IosPlatformState {
+ application: IosApplicationState::default(),
+ background_executor: BackgroundExecutor::new(dispatcher.clone()),
+ foreground_executor: ForegroundExecutor::new(dispatcher),
+ text_system,
+ thermal_observer: RefCell::new(None),
+ display_observers: RefCell::new(Vec::new()),
+ display_task: RefCell::new(None),
+ displays_changed_callback: CallbackSlot::default(),
+ });
+ let (sender, mut receiver) = mpsc::unbounded();
+ let block = RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
+ if sender.unbounded_send(()).is_err() {
+ log::debug!("display observer stopped before notification delivery");
+ }
+ });
+ // UIKit may deliver these synchronously. Defer entering GPUI until the
+ // current native callback has unwound, as with thermal notifications.
+ #[allow(deprecated)] // Screen enumeration is independent of our single connected scene.
+ unsafe {
+ for name in [
+ UIScreenDidConnectNotification,
+ UIScreenDidDisconnectNotification,
+ UIScreenModeDidChangeNotification,
+ ] {
+ let observer = NSNotificationCenter::defaultCenter()
+ .addObserverForName_object_queue_usingBlock(Some(name), None, None, &block);
+ state.display_observers.borrow_mut().push(observer);
+ }
+ }
+ let weak_state = Rc::downgrade(&state);
+ let task = state.foreground_executor.spawn(async move {
+ while receiver.next().await.is_some() {
+ if let Some(state) = weak_state.upgrade() {
+ state.displays_changed_callback.with(|callback| callback());
+ }
+ }
+ });
+ state.display_task.replace(Some(task));
+ Self(state)
+ }
+
+ fn root_view_controller(&self) -> Option<Retained<UIViewController>> {
+ let window = if let Some(scene) = self.0.application.window_scene() {
+ let windows = scene.windows();
+ windows
+ .iter()
+ .find(|window| window.isKeyWindow())
+ .or_else(|| windows.firstObject())
+ } else {
+ // Legacy hosts can create a GPUI window without supplying a scene.
+ #[allow(deprecated)]
+ UIApplication::sharedApplication(
+ MainThreadMarker::new().expect("UIKit requires the main thread"),
+ )
+ .keyWindow()
+ }?;
+ window.rootViewController()
+ }
+
+ fn presented_view_controller(&self) -> Option<Retained<UIViewController>> {
+ let mut view_controller = self.root_view_controller()?;
+ while let Some(presented) = view_controller.presentedViewController() {
+ view_controller = presented;
+ }
+ Some(view_controller)
+ }
+
+ fn dismiss_presented_browser(&self) {
+ let mut view_controller = match self.root_view_controller() {
+ Some(view_controller) => view_controller,
+ None => return,
+ };
+
+ loop {
+ let Some(presented) = view_controller.presentedViewController() else {
+ return;
+ };
+
+ if presented.downcast_ref::<SFSafariViewController>().is_some() {
+ presented.dismissViewControllerAnimated_completion(true, None);
+ return;
+ }
+
+ view_controller = presented;
+ }
+ }
+
+ fn open_url_with_system(url: &NSURL) {
+ unsafe {
+ let app = UIApplication::sharedApplication(
+ MainThreadMarker::new().expect("UIKit requires the main thread"),
+ );
+ app.openURL_options_completionHandler(url, &NSDictionary::new(), None);
+ }
+ }
+}
+
+/// A simple iOS keyboard layout.
+struct IosKeyboardLayout;
+
+impl PlatformKeyboardLayout for IosKeyboardLayout {
+ fn id(&self) -> &str {
+ "ios-default"
+ }
+
+ fn name(&self) -> &str {
+ "iOS Default"
+ }
+}
+
+impl Platform for IosPlatform {
+ fn on_displays_changed(&self, callback: Box<dyn FnMut()>) {
+ self.0.displays_changed_callback.set(callback);
+ }
+
+ fn background_executor(&self) -> BackgroundExecutor {
+ self.0.background_executor.clone()
+ }
+
+ fn foreground_executor(&self) -> ForegroundExecutor {
+ self.0.foreground_executor.clone()
+ }
+
+ fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
+ self.0.text_system.clone()
+ }
+
+ fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
+ super::application::run(&self.0, on_finish_launching);
+ }
+
+ fn quit(&self) {
+ // iOS apps cannot programmatically quit - they can only be terminated by the user
+ // or the system. We can suspend to background though.
+ log::warn!("iOS apps cannot programmatically quit");
+ }
+
+ fn restart(&self, _binary_path: Option<PathBuf>, _arguments: Vec<std::ffi::OsString>) {
+ // iOS apps cannot restart themselves
+ log::warn!("iOS apps cannot restart themselves");
+ }
+
+ fn activate(&self, _ignoring_other_apps: bool) {
+ self.dismiss_presented_browser();
+ }
+
+ fn hide(&self) {
+ // iOS apps cannot hide themselves
+ }
+
+ fn hide_other_apps(&self) {
+ // Not applicable on iOS
+ }
+
+ fn unhide_other_apps(&self) {
+ // Not applicable on iOS
+ }
+
+ fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
+ IosDisplay::all()
+ .map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
+ .collect()
+ }
+
+ fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
+ Some(Rc::new(IosDisplay::main()))
+ }
+
+ fn active_window(&self) -> Option<AnyWindowHandle> {
+ // iOS typically has one active window
+ // This would need to track the current key window
+ None
+ }
+
+ fn open_window(
+ &self,
+ handle: AnyWindowHandle,
+ options: WindowParams,
+ ) -> anyhow::Result<Box<dyn PlatformWindow>> {
+ let window = Box::new(IosWindow::new(handle, options, &self.0)?);
+ window.register();
+ Ok(window)
+ }
+
+ fn window_appearance(&self) -> WindowAppearance {
+ unsafe {
+ let Some(controller) = self.root_view_controller() else {
+ return WindowAppearance::Light;
+ };
+ match controller.traitCollection().userInterfaceStyle() {
+ UIUserInterfaceStyle::Dark => WindowAppearance::Dark,
+ _ => WindowAppearance::Light,
+ }
+ }
+ }
+
+ fn open_url(&self, url: &str) {
+ unsafe {
+ let Some(native_url) = NSURL::URLWithString(&NSString::from_str(url)) else {
+ log::error!("GPUI iOS: Could not parse URL: {url}");
+ return;
+ };
+
+ if url.starts_with("https://") || url.starts_with("http://") {
+ if let Some(view_controller) = self.presented_view_controller() {
+ let browser = SFSafariViewController::init_with_url(
+ SFSafariViewController::alloc(view_controller.mtm()),
+ &native_url,
+ );
+ view_controller.presentViewController_animated_completion(&browser, true, None);
+ return;
+ }
+ }
+
+ Self::open_url_with_system(&native_url);
+ }
+ }
+
+ fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
+ self.0.application.open_urls.set(callback);
+ }
+
+ fn register_url_scheme(&self, _url: &str) -> Task<Result<()>> {
+ // URL schemes on iOS are registered in Info.plist, not programmatically
+ Task::ready(Ok(()))
+ }
+
+ fn prompt_for_paths(
+ &self,
+ _options: PathPromptOptions,
+ ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
+ let (tx, rx) = oneshot::channel();
+ if tx
+ .send(Err(anyhow!("File picker not yet implemented for iOS")))
+ .is_err()
+ {
+ log::debug!("GPUI iOS: File picker receiver was dropped");
+ }
+ rx
+ }
+
+ fn prompt_for_new_path(
+ &self,
+ _directory: &Path,
+ _suggested_name: Option<&str>,
+ ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
+ let (tx, rx) = oneshot::channel();
+ if tx
+ .send(Err(anyhow!("Save dialog not yet implemented for iOS")))
+ .is_err()
+ {
+ log::debug!("GPUI iOS: Save dialog receiver was dropped");
+ }
+ rx
+ }
+
+ fn can_select_mixed_files_and_dirs(&self) -> bool {
+ false
+ }
+
+ fn reveal_path(&self, _path: &Path) {
+ // iOS doesn't have a file manager like Finder
+ }
+
+ fn open_with_system(&self, _path: &Path) {
+ // Would use UIDocumentInteractionController or UIActivityViewController
+ }
+
+ fn on_quit(&self, mut callback: Box<dyn FnMut() -> bool>) {
+ self.0.application.quit.set(Box::new(move || {
+ // UIKit's termination notification cannot be vetoed.
+ callback();
+ }));
+ }
+
+ fn on_reopen(&self, _callback: Box<dyn FnMut()>) {
+ // iOS handles app reopening through scene lifecycle
+ }
+
+ fn on_system_wake(&self, _callback: Box<dyn FnMut()>) {}
+
+ fn on_system_sleep(&self, _callback: Box<dyn FnMut()>) {}
+
+ fn prevent_idle_sleep(&self, _reason: &str) -> Task<Result<gpui::ActivityGuard>> {
+ Task::ready(Err(anyhow!(
+ "Idle sleep prevention is not implemented for iOS"
+ )))
+ }
+
+ fn on_app_lifecycle(&self, callback: Box<dyn FnMut(AppLifecyclePhase)>) {
+ self.0.application.app_lifecycle.set(callback);
+ }
+
+ fn on_memory_warning(&self, callback: Box<dyn FnMut()>) {
+ self.0.application.memory_warning.set(callback);
+ }
+
+ fn set_menus(&self, _menus: Vec<Menu>, _keymap: &Keymap) {
+ // iOS doesn't have a menu bar
+ // Could potentially integrate with UIMenuBuilder for context menus
+ }
+
+ fn set_dock_menu(&self, _menu: Vec<MenuItem>, _keymap: &Keymap) {
+ // iOS doesn't have a dock menu
+ }
+
+ fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn Action)>) {
+ // Not applicable on iOS
+ }
+
+ fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {
+ // Not applicable on iOS
+ }
+
+ fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn Action) -> bool>) {
+ // Not applicable on iOS
+ }
+
+ fn app_path(&self) -> Result<PathBuf> {
+ Ok(PathBuf::from(
+ NSBundle::mainBundle().bundlePath().to_string(),
+ ))
+ }
+
+ fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
+ let app_path = self.app_path()?;
+ Ok(app_path.join(name))
+ }
+
+ fn set_cursor_style(&self, _style: CursorStyle) {
+ // iOS doesn't have visible cursors (except for Apple Pencil hover on iPad)
+ }
+
+ fn hide_cursor_until_mouse_moves(&self) {}
+
+ fn is_cursor_visible(&self) -> bool {
+ false
+ }
+
+ fn should_auto_hide_scrollbars(&self) -> bool {
+ true // iOS always auto-hides scrollbars
+ }
+
+ fn write_to_clipboard(&self, item: ClipboardItem) {
+ let pasteboard = UIPasteboard::generalPasteboard();
+ if let Some(text) = item.text() {
+ unsafe { pasteboard.setString(Some(&NSString::from_str(&text))) };
+ }
+ }
+
+ fn read_from_clipboard(&self) -> Option<ClipboardItem> {
+ let pasteboard = UIPasteboard::generalPasteboard();
+ Some(ClipboardItem::new_string(
+ unsafe { pasteboard.string() }?.to_string(),
+ ))
+ }
+
+ fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
+ let url = url.to_string();
+ let username = username.to_string();
+ let password = password.to_vec();
+ self.background_executor()
+ .spawn(async move { Ok(keychain::write_credentials(&url, &username, &password)?) })
+ }
+
+ fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
+ let url = url.to_string();
+ self.background_executor()
+ .spawn(async move { Ok(keychain::read_credentials(&url)?) })
+ }
+
+ fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
+ let url = url.to_string();
+ self.background_executor()
+ .spawn(async move { Ok(keychain::delete_credentials(&url)?) })
+ }
+
+ fn on_keyboard_layout_change(&self, _callback: Box<dyn FnMut()>) {
+ // iOS handles keyboard layout changes differently
+ }
+
+ fn thermal_state(&self) -> ThermalState {
+ thermal::thermal_state()
+ }
+
+ fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>) {
+ let observer = ThermalObserver::new(&self.0.foreground_executor, callback);
+ self.0.thermal_observer.replace(Some(observer));
+ }
+
+ fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
+ Box::new(IosKeyboardLayout)
+ }
+
+ fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
+ Rc::new(DummyKeyboardMapper)
+ }
+}
+
+impl Drop for IosPlatformState {
+ fn drop(&mut self) {
+ for observer in self.display_observers.get_mut().drain(..) {
+ unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
+ }
+ }
+}
+
+// objc2-safari-services 0.3.2 only includes the macOS SafariServices API.
+// Keep the missing iOS initializer typed here until the generated crate includes it.
+#[link(name = "SafariServices", kind = "framework")]
+unsafe extern "C" {}
+
+objc2::extern_class!(
+ #[unsafe(super(
+ UIViewController,
+ objc2_ui_kit::UIResponder,
+ objc2_foundation::NSObject
+ ))]
+ #[thread_kind = MainThreadOnly]
+ struct SFSafariViewController;
+);
+
+impl SFSafariViewController {
+ objc2::extern_methods!(
+ #[unsafe(method(initWithURL:))]
+ #[unsafe(method_family = init)]
+ unsafe fn init_with_url(this: objc2::rc::Allocated<Self>, url: &NSURL) -> Retained<Self>;
+ );
+}
diff --git a/crates/gpui_ios/src/ios/text_input.rs b/crates/gpui_ios/src/ios/text_input.rs
new file mode 100644
index 00000000000..5464d6f7c85
--- /dev/null
+++ b/crates/gpui_ios/src/ios/text_input.rs
@@ -0,0 +1,1111 @@
+use super::window::{IosWindowState, WindowReference};
+use gpui::{
+ Autocapitalize, PlatformInputHandler, TextInputAction, TextInputConfiguration,
+ TextInputStateChange, px,
+};
+use objc2::rc::{Retained, Weak};
+use objc2::runtime::{AnyObject, ProtocolObject};
+use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send, sel};
+use objc2_core_foundation::{CGPoint, CGRect, CGSize};
+use objc2_foundation::{
+ NSArray, NSAttributedStringKey, NSComparisonResult, NSCopying, NSDictionary,
+ NSObjectNSDelayedPerforming, NSObjectProtocol, NSRange, NSString,
+};
+use objc2_ui_kit::*;
+use std::{
+ cell::{Cell, RefCell},
+ ops::Range,
+ rc::Rc,
+};
+
+struct TextPositionIvars {
+ offset: usize,
+ session: Rc<()>,
+}
+
+define_class!(
+ #[unsafe(super = UITextPosition)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUITextPosition"]
+ #[ivars = TextPositionIvars]
+ struct TextPosition;
+ unsafe impl NSObjectProtocol for TextPosition {}
+);
+
+impl TextPosition {
+ fn new(
+ offset: usize,
+ session: Rc<()>,
+ main_thread: MainThreadMarker,
+ ) -> Retained<UITextPosition> {
+ let this = Self::alloc(main_thread).set_ivars(TextPositionIvars { offset, session });
+ let this: Retained<Self> = unsafe { msg_send![super(this), init] };
+ this.into_super()
+ }
+}
+
+struct TextRangeIvars {
+ range: Range<usize>,
+ session: Rc<()>,
+}
+
+define_class!(
+ #[unsafe(super = UITextRange)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUITextRange"]
+ #[ivars = TextRangeIvars]
+ struct TextRange;
+ unsafe impl NSObjectProtocol for TextRange {}
+ impl TextRange {
+ #[unsafe(method_id(start))]
+ fn start(&self) -> Retained<UITextPosition> {
+ TextPosition::new(self.ivars().range.start, self.ivars().session.clone(), self.mtm())
+ }
+ #[unsafe(method_id(end))]
+ fn end(&self) -> Retained<UITextPosition> {
+ TextPosition::new(self.ivars().range.end, self.ivars().session.clone(), self.mtm())
+ }
+ #[unsafe(method(isEmpty))]
+ fn is_empty(&self) -> bool { self.ivars().range.is_empty() }
+ }
+);
+
+impl TextRange {
+ fn new(
+ range: Range<usize>,
+ session: Rc<()>,
+ main_thread: MainThreadMarker,
+ ) -> Retained<UITextRange> {
+ let this = Self::alloc(main_thread).set_ivars(TextRangeIvars { range, session });
+ let this: Retained<Self> = unsafe { msg_send![super(this), init] };
+ this.into_super()
+ }
+}
+
+struct SelectionRectIvars {
+ rect: CGRect,
+ contains_start: bool,
+ contains_end: bool,
+}
+
+define_class!(
+ #[unsafe(super = UITextSelectionRect)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUITextSelectionRect"]
+ #[ivars = SelectionRectIvars]
+ struct SelectionRect;
+ unsafe impl NSObjectProtocol for SelectionRect {}
+ impl SelectionRect {
+ #[unsafe(method(rect))]
+ fn rect(&self) -> CGRect { self.ivars().rect }
+ #[unsafe(method(containsStart))]
+ fn contains_start(&self) -> bool { self.ivars().contains_start }
+ #[unsafe(method(containsEnd))]
+ fn contains_end(&self) -> bool { self.ivars().contains_end }
+ #[unsafe(method(isVertical))]
+ fn is_vertical(&self) -> bool { false }
+ #[unsafe(method(writingDirection))]
+ fn writing_direction(&self) -> NSWritingDirection { NSWritingDirection::Natural }
+ }
+);
+
+pub(super) struct TextInputIvars {
+ window: WindowReference,
+ input_field: Cell<Option<gpui::FocusId>>,
+ session: RefCell<Rc<()>>,
+ configuration: RefCell<TextInputConfiguration>,
+ delegate: RefCell<Weak<ProtocolObject<dyn UITextInputDelegate>>>,
+ marked_style: RefCell<Option<Retained<NSDictionary<NSAttributedStringKey, AnyObject>>>>,
+ keyboard_desired: Cell<bool>,
+ keyboard_eligible: Cell<bool>,
+ reconciling_responder: Cell<bool>,
+ update_pending: Cell<bool>,
+ configuration_changed: Cell<bool>,
+ selection_changed: Cell<bool>,
+ content_changed: Cell<bool>,
+ native_edit: Cell<bool>,
+}
+
+define_class!(
+ #[unsafe(super = UIView)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUITextInputView"]
+ #[ivars = TextInputIvars]
+ pub(super) struct TextInputView;
+
+ unsafe impl NSObjectProtocol for TextInputView {}
+
+ impl TextInputView {
+ #[unsafe(method(canBecomeFirstResponder))]
+ fn can_become_first_responder(&self) -> bool {
+ self.ivars().keyboard_desired.get()
+ && self.ivars().keyboard_eligible.get()
+ }
+
+ #[unsafe(method(resignFirstResponder))]
+ fn resign_first_responder(&self) -> bool {
+ let was_first_responder = self.isFirstResponder();
+ let resigned: bool = unsafe { msg_send![super(self), resignFirstResponder] };
+ if resigned && was_first_responder && !self.ivars().reconciling_responder.get() {
+ // UIKit can end native editing or transfer it to another view
+ // without changing GPUI focus. A repaint must not reclaim it.
+ self.ivars().keyboard_desired.set(false);
+ self.ivars().keyboard_eligible.set(false);
+ }
+ resigned
+ }
+
+ #[unsafe(method(reconcileTextInput))]
+ fn reconcile_text_input(&self) {
+ self.ivars().update_pending.set(false);
+ let eligible = self.ivars().keyboard_desired.get()
+ && self.with_handler(|handler| {
+ if !handler.query_accepts_focused_text_input() { return false; }
+ let Some(document) = document_range(handler) else { return false; };
+ handler.selected_text_range(false)
+ .is_some_and(|selection| contains_range(&document, &selection.range))
+ }).unwrap_or(false);
+ self.ivars().keyboard_eligible.set(eligible);
+ if self.canBecomeFirstResponder() {
+ if !self.isFirstResponder() { self.becomeFirstResponder(); }
+ } else if self.isFirstResponder() {
+ let previous = self.ivars().reconciling_responder.replace(true);
+ self.resignFirstResponder();
+ self.ivars().reconciling_responder.set(previous);
+ }
+ if self.ivars().configuration_changed.replace(false) && self.isFirstResponder() {
+ self.reloadInputViews();
+ }
+ let content_changed = self.ivars().content_changed.replace(false);
+ let selection_changed = self.ivars().selection_changed.replace(false);
+ if content_changed || selection_changed {
+ if let Some(delegate) = self.inputDelegate() {
+ let input = Some(ProtocolObject::from_ref(self));
+ // GPUI only reports post-edit invalidation. Defer until its
+ // Window borrow is released before UIKit queries the handler.
+ if content_changed { delegate.textWillChange(input); }
+ delegate.selectionWillChange(input);
+ delegate.selectionDidChange(input);
+ if content_changed { delegate.textDidChange(input); }
+ }
+ }
+ }
+
+ }
+
+ unsafe impl UIKeyInput for TextInputView {
+ #[unsafe(method(hasText))]
+ fn has_text(&self) -> bool {
+ self.document_range().is_some_and(|range| !range.is_empty())
+ }
+ #[unsafe(method(insertText:))]
+ fn insert_text(&self, text: &NSString) {
+ self.edit(|handler| handler.replace_text_in_range(None, &text.to_string()));
+ }
+ #[unsafe(method(deleteBackward))]
+ fn delete_backward(&self) {
+ self.edit(|handler| {
+ let Some(selection) = handler.selected_text_range(false) else { return; };
+ let mut range = selection.range;
+ if range.is_empty() {
+ let start = handler.text_input_editable_range().map_or(0, |range| range.start);
+ if range.start <= start { return; }
+ let Some(text) = read_text(handler, start..range.start) else { return; };
+ let Some(character) = composed_character_range(&text, text.length().saturating_sub(1)) else { return; };
+ range.start = start + character.start;
+ }
+ if allowed_range(handler, &range) {
+ handler.replace_text_in_range(Some(range), "");
+ }
+ });
+ }
+ }
+
+ unsafe impl UITextInputTraits for TextInputView {
+ #[unsafe(method(keyboardType))]
+ fn keyboard_type(&self) -> UIKeyboardType { UIKeyboardType::Default }
+ #[unsafe(method(autocorrectionType))]
+ fn autocorrection_type(&self) -> UITextAutocorrectionType {
+ if self.ivars().configuration.borrow().autocorrect { UITextAutocorrectionType::Yes } else { UITextAutocorrectionType::No }
+ }
+ #[unsafe(method(autocapitalizationType))]
+ fn autocapitalization_type(&self) -> UITextAutocapitalizationType {
+ match self.ivars().configuration.borrow().autocapitalize {
+ Autocapitalize::None => UITextAutocapitalizationType::None,
+ Autocapitalize::Words => UITextAutocapitalizationType::Words,
+ Autocapitalize::Sentences => UITextAutocapitalizationType::Sentences,
+ Autocapitalize::Characters => UITextAutocapitalizationType::AllCharacters,
+ }
+ }
+ #[unsafe(method(spellCheckingType))]
+ fn spell_checking_type(&self) -> UITextSpellCheckingType {
+ if self.ivars().configuration.borrow().suggestions { UITextSpellCheckingType::Yes } else { UITextSpellCheckingType::No }
+ }
+ #[unsafe(method(inlinePredictionType))]
+ fn inline_prediction_type(&self) -> UITextInlinePredictionType {
+ if self.ivars().configuration.borrow().suggestions { UITextInlinePredictionType::Yes } else { UITextInlinePredictionType::No }
+ }
+ #[unsafe(method(returnKeyType))]
+ fn return_key_type(&self) -> UIReturnKeyType {
+ match self.ivars().configuration.borrow().input_action {
+ TextInputAction::Unspecified | TextInputAction::Enter | TextInputAction::Previous => UIReturnKeyType::Default,
+ TextInputAction::Done => UIReturnKeyType::Done,
+ TextInputAction::Go => UIReturnKeyType::Go,
+ TextInputAction::Next => UIReturnKeyType::Next,
+ TextInputAction::Search => UIReturnKeyType::Search,
+ TextInputAction::Send => UIReturnKeyType::Send,
+ }
+ }
+ }
+
+ unsafe impl UITextInput for TextInputView {
+ #[unsafe(method_id(textInRange:))]
+ fn text_in_range(&self, range: &UITextRange) -> Option<Retained<NSString>> {
+ (|| {
+ let range = self.validated_range(range)?;
+ self.with_handler(|handler| read_text(handler, range)).flatten()
+ })()
+ }
+ #[unsafe(method(replaceRange:withText:))]
+ fn replace_range(&self, range: &UITextRange, text: &NSString) {
+ if let Some(range) = self.validated_range(range) {
+ self.edit(|handler| {
+ if allowed_range(handler, &range) {
+ handler.replace_text_in_range(Some(range), &text.to_string());
+ }
+ });
+ }
+ }
+ #[unsafe(method_id(selectedTextRange))]
+ fn selected_text_range(&self) -> Option<Retained<UITextRange>> {
+ self.with_handler(|handler| {
+ let selection = handler.selected_text_range(false)?;
+ allowed_range(handler, &selection.range).then_some(selection)
+ }).flatten().map(|selection| self.new_range(selection.range))
+ }
+ #[unsafe(method(setSelectedTextRange:))]
+ fn set_selected_text_range(&self, range: Option<&UITextRange>) {
+ if let Some(range) = range.and_then(|range| self.validated_range(range)) {
+ self.edit(|handler| {
+ if allowed_range(handler, &range) { handler.set_selected_text_range(range); }
+ });
+ }
+ }
+ #[unsafe(method_id(markedTextRange))]
+ fn marked_text_range(&self) -> Option<Retained<UITextRange>> {
+ self.with_handler(|handler| {
+ let range = handler.marked_text_range()?;
+ allowed_range(handler, &range).then_some(range)
+ }).flatten().map(|range| self.new_range(range))
+ }
+ #[unsafe(method_id(markedTextStyle))]
+ fn marked_text_style(&self) -> Option<Retained<NSDictionary<NSAttributedStringKey, AnyObject>>> {
+ self.ivars().marked_style.borrow().clone()
+ }
+ #[unsafe(method(setMarkedTextStyle:))]
+ unsafe fn set_marked_text_style(&self, style: Option<&NSDictionary<NSAttributedStringKey, AnyObject>>) {
+ *self.ivars().marked_style.borrow_mut() = style.map(|style| style.copy());
+ }
+ #[unsafe(method(setMarkedText:selectedRange:))]
+ fn set_marked_text(&self, text: Option<&NSString>, selection: NSRange) {
+ let text = text.map(|text| text.to_string()).unwrap_or_default();
+ let selection = checked_range(selection.location, selection.length, text.encode_utf16().count());
+ self.edit(|handler| handler.replace_and_mark_text_in_range(None, &text, selection));
+ }
+ #[unsafe(method(unmarkText))]
+ fn unmark_text(&self) { self.edit(PlatformInputHandler::unmark_text); }
+ #[unsafe(method_id(beginningOfDocument))]
+ fn beginning_of_document(&self) -> Retained<UITextPosition> {
+ self.new_position(self.document_range().map_or(0, |range| range.start))
+ }
+ #[unsafe(method_id(endOfDocument))]
+ fn end_of_document(&self) -> Retained<UITextPosition> {
+ self.new_position(self.document_range().map_or(0, |range| range.end))
+ }
+ #[unsafe(method_id(textRangeFromPosition:toPosition:))]
+ fn text_range(&self, start: &UITextPosition, end: &UITextPosition) -> Option<Retained<UITextRange>> {
+ (|| {
+ let start = self.validated_offset(start)?;
+ let end = self.validated_offset(end)?;
+ Some(self.new_range(start.min(end)..start.max(end)))
+ })()
+ }
+ #[unsafe(method_id(positionFromPosition:offset:))]
+ fn position_offset(&self, position: &UITextPosition, offset: isize) -> Option<Retained<UITextPosition>> {
+ (|| {
+ let position = self.validated_offset(position)?;
+ let range = self.document_range()?;
+ let offset = checked_offset(position, offset, range.end)?;
+ (offset >= range.start).then(|| self.new_position(offset))
+ })()
+ }
+ #[unsafe(method_id(positionFromPosition:inDirection:offset:))]
+ fn position_direction(&self, position: &UITextPosition, direction: UITextLayoutDirection, offset: isize) -> Option<Retained<UITextPosition>> {
+ (|| {
+ self.validated_offset(position)?;
+ if direction == UITextLayoutDirection::Left {
+ return self.positionFromPosition_offset(position, offset.checked_neg()?);
+ }
+ if direction == UITextLayoutDirection::Right {
+ return self.positionFromPosition_offset(position, offset);
+ }
+ let rectangle = self.caretRectForPosition(position);
+ let sign = if direction == UITextLayoutDirection::Up { -1.0 } else { 1.0 };
+ self.closestPositionToPoint(CGPoint::new(rectangle.origin.x, rectangle.origin.y + rectangle.size.height * (0.5 + sign * offset as f64)))
+ })()
+ }
+ #[unsafe(method(comparePosition:toPosition:))]
+ fn compare_position(&self, position: &UITextPosition, other: &UITextPosition) -> NSComparisonResult {
+ let (Some(position), Some(other)) = (self.validated_offset(position), self.validated_offset(other)) else {
+ return NSComparisonResult::Same;
+ };
+ match position.cmp(&other) {
+ std::cmp::Ordering::Less => NSComparisonResult::Ascending,
+ std::cmp::Ordering::Equal => NSComparisonResult::Same,
+ std::cmp::Ordering::Greater => NSComparisonResult::Descending,
+ }
+ }
+ #[unsafe(method(offsetFromPosition:toPosition:))]
+ fn offset_from_position(&self, start: &UITextPosition, end: &UITextPosition) -> isize {
+ let (Some(start), Some(end)) = (
+ self.validated_offset(start).and_then(|offset| isize::try_from(offset).ok()),
+ self.validated_offset(end).and_then(|offset| isize::try_from(offset).ok()),
+ ) else { return 0; };
+ end.saturating_sub(start)
+ }
+ #[unsafe(method_id(inputDelegate))]
+ fn input_delegate(&self) -> Option<Retained<ProtocolObject<dyn UITextInputDelegate>>> { self.ivars().delegate.borrow().load() }
+ #[unsafe(method(setInputDelegate:))]
+ fn set_input_delegate(&self, delegate: Option<&ProtocolObject<dyn UITextInputDelegate>>) {
+ *self.ivars().delegate.borrow_mut() = delegate.map(Weak::new).unwrap_or_default();
+ }
+ #[unsafe(method_id(tokenizer))]
+ fn input_tokenizer(&self) -> Retained<ProtocolObject<dyn UITextInputTokenizer>> {
+ let tokenizer = unsafe { UITextInputStringTokenizer::initWithTextInput(UITextInputStringTokenizer::alloc(self.mtm()), self) };
+ ProtocolObject::from_retained(tokenizer)
+ }
+ #[unsafe(method_id(positionWithinRange:farthestInDirection:))]
+ fn farthest_position(&self, range: &UITextRange, direction: UITextLayoutDirection) -> Option<Retained<UITextPosition>> {
+ (|| {
+ let range = self.validated_range(range)?;
+ let offset = if direction == UITextLayoutDirection::Left || direction == UITextLayoutDirection::Up { range.start } else { range.end };
+ Some(self.new_position(offset))
+ })()
+ }
+ #[unsafe(method_id(characterRangeByExtendingPosition:inDirection:))]
+ fn extending_range(&self, position: &UITextPosition, direction: UITextLayoutDirection) -> Option<Retained<UITextRange>> {
+ (|| {
+ let offset = self.validated_offset(position)?;
+ let backwards = direction == UITextLayoutDirection::Left || direction == UITextLayoutDirection::Up;
+ self.character_range(if backwards { offset.checked_sub(1)? } else { offset })
+ })()
+ }
+ #[unsafe(method(baseWritingDirectionForPosition:inDirection:))]
+ fn base_writing_direction(&self, position: &UITextPosition, _direction: UITextStorageDirection) -> NSWritingDirection {
+ if self.validated_offset(position).is_none() { return NSWritingDirection::Natural; }
+ NSWritingDirection::Natural
+ }
+ #[unsafe(method(setBaseWritingDirection:forRange:))]
+ fn set_base_writing_direction(&self, direction: NSWritingDirection, range: &UITextRange) {
+ if self.validated_range(range).is_none() { return; }
+ if direction != NSWritingDirection::Natural {
+ log::warn!("GPUI input handlers do not support overriding paragraph writing direction");
+ }
+ }
+ #[unsafe(method(firstRectForRange:))]
+ fn first_rect(&self, range: &UITextRange) -> CGRect {
+ self.validated_range(range).and_then(|range| self.bounds(range)).unwrap_or(CGRect::ZERO)
+ }
+ #[unsafe(method(caretRectForPosition:))]
+ fn caret_rect(&self, position: &UITextPosition) -> CGRect {
+ self.validated_offset(position)
+ .and_then(|offset| self.bounds(offset..offset))
+ .map(nonempty_caret_rect)
+ .unwrap_or(CGRect::ZERO)
+ }
+ #[unsafe(method_id(selectionRectsForRange:))]
+ fn selection_rects(&self, range: &UITextRange) -> Retained<NSArray<UITextSelectionRect>> {
+ (|| {
+ let Some(range) = self.validated_range(range) else { return NSArray::new(); };
+ let bounds = self.with_handler(|handler| {
+ if !allowed_range(handler, &range) { return Vec::new(); }
+ handler.selection_bounds_for_range(range)
+ }).unwrap_or_default();
+ let count = bounds.len();
+ let rectangles = bounds.into_iter().enumerate().map(|(index, bounds)| {
+ let this = SelectionRect::alloc(self.mtm()).set_ivars(SelectionRectIvars {
+ rect: native_rect(bounds),
+ contains_start: index == 0,
+ contains_end: index + 1 == count,
+ });
+ let this: Retained<SelectionRect> = unsafe { msg_send![super(this), init] };
+ this.into_super()
+ }).collect::<Vec<_>>();
+ NSArray::from_retained_slice(&rectangles)
+ })()
+ }
+ #[unsafe(method_id(closestPositionToPoint:))]
+ fn closest_position(&self, point: CGPoint) -> Option<Retained<UITextPosition>> {
+ self.with_handler(|handler| {
+ let offset = handler.character_index_for_point(gpui::point(px(point.x as f32), px(point.y as f32)))?;
+ allowed_range(handler, &(offset..offset)).then_some(offset)
+ }).flatten()
+ .map(|offset| self.new_position(offset))
+ }
+ #[unsafe(method_id(closestPositionToPoint:withinRange:))]
+ fn closest_position_within_range(&self, point: CGPoint, range: &UITextRange) -> Option<Retained<UITextPosition>> {
+ (|| {
+ let range = self.validated_range(range)?;
+ let position = self.closestPositionToPoint(point)?;
+ Some(self.new_position(self.validated_offset(&position)?.clamp(range.start, range.end)))
+ })()
+ }
+ #[unsafe(method_id(characterRangeAtPoint:))]
+ fn character_range_at_point(&self, point: CGPoint) -> Option<Retained<UITextRange>> {
+ (|| {
+ let position = self.closestPositionToPoint(point)?;
+ self.character_range(self.validated_offset(&position)?)
+ })()
+ }
+ #[unsafe(method_id(textInputView))]
+ fn text_input_view(&self) -> Retained<UIView> {
+ // GPUI's bounds and hit testing use the rendering view's coordinate space,
+ // not the hidden responder's one-point frame.
+ self.superview().unwrap_or_else(|| self.retain().into_super())
+ }
+ }
+
+);
+
+impl TextInputView {
+ pub(super) fn new(frame: CGRect, main_thread: MainThreadMarker) -> Retained<Self> {
+ let this = Self::alloc(main_thread).set_ivars(TextInputIvars {
+ window: WindowReference::default(),
+ input_field: Cell::new(None),
+ session: RefCell::new(Rc::new(())),
+ configuration: RefCell::new(TextInputConfiguration::default()),
+ delegate: RefCell::new(Weak::default()),
+ marked_style: RefCell::new(None),
+ keyboard_desired: Cell::new(false),
+ keyboard_eligible: Cell::new(false),
+ reconciling_responder: Cell::new(false),
+ update_pending: Cell::new(false),
+ configuration_changed: Cell::new(false),
+ selection_changed: Cell::new(false),
+ content_changed: Cell::new(false),
+ native_edit: Cell::new(false),
+ });
+ unsafe { msg_send![super(this), initWithFrame: frame] }
+ }
+
+ pub(super) fn set_window(&self, window: std::rc::Weak<IosWindowState>) {
+ *self.ivars().window.0.borrow_mut() = window;
+ }
+
+ fn validated_offset(&self, position: &UITextPosition) -> Option<usize> {
+ let position = position.downcast_ref::<TextPosition>()?;
+ Rc::ptr_eq(&position.ivars().session, &self.ivars().session.borrow())
+ .then_some(position.ivars().offset)
+ }
+
+ fn validated_range(&self, range: &UITextRange) -> Option<Range<usize>> {
+ let range = range.downcast_ref::<TextRange>()?;
+ Rc::ptr_eq(&range.ivars().session, &self.ivars().session.borrow())
+ .then(|| range.ivars().range.clone())
+ }
+
+ fn new_position(&self, offset: usize) -> Retained<UITextPosition> {
+ TextPosition::new(offset, self.ivars().session.borrow().clone(), self.mtm())
+ }
+
+ fn new_range(&self, range: Range<usize>) -> Retained<UITextRange> {
+ TextRange::new(range, self.ivars().session.borrow().clone(), self.mtm())
+ }
+
+ fn invalidate_session(&self) {
+ // Retaining the token in native objects prevents identity reuse, even
+ // after returning to a field or destroying and recreating a responder.
+ *self.ivars().session.borrow_mut() = Rc::new(());
+ }
+
+ fn with_handler<R>(&self, callback: impl FnOnce(&mut PlatformInputHandler) -> R) -> Option<R> {
+ self.ivars()
+ .window
+ .with_window(|window| window.with_input_handler(callback))
+ .flatten()
+ }
+
+ fn edit(&self, callback: impl FnOnce(&mut PlatformInputHandler)) {
+ let previous = self.ivars().native_edit.replace(true);
+ self.with_handler(|handler| {
+ let selected = handler.selected_text_range(false);
+ let marked = handler.marked_text_range();
+ let selection_allowed =
+ selected.is_some_and(|selection| allowed_range(handler, &selection.range));
+ let marked_allowed = marked.is_none_or(|range| allowed_range(handler, &range));
+ if handler.query_accepts_focused_text_input() && selection_allowed && marked_allowed {
+ callback(handler);
+ }
+ });
+ self.ivars().native_edit.set(previous);
+ }
+
+ fn document_range(&self) -> Option<Range<usize>> {
+ self.with_handler(document_range).flatten()
+ }
+
+ fn bounds(&self, range: Range<usize>) -> Option<CGRect> {
+ self.with_handler(|handler| {
+ if !allowed_range(handler, &range) {
+ return None;
+ }
+ handler.bounds_for_range(range)
+ })
+ .flatten()
+ .map(native_rect)
+ }
+
+ fn character_range(&self, offset: usize) -> Option<Retained<UITextRange>> {
+ let (document_range, text) = self.document_text()?;
+ let character = composed_character_range(&text, offset.checked_sub(document_range.start)?)?;
+ Some(self.new_range(
+ (document_range.start + character.start)..(document_range.start + character.end),
+ ))
+ }
+
+ fn document_text(&self) -> Option<(Range<usize>, Retained<NSString>)> {
+ self.with_handler(|handler| {
+ let range = document_range(handler)?;
+ let text = read_text(handler, range.clone())?;
+ Some((range, text))
+ })
+ .flatten()
+ }
+
+ pub(super) fn set_keyboard_visible(&self, visible: bool) {
+ self.ivars().keyboard_desired.set(visible);
+ self.refresh_keyboard();
+ }
+
+ pub(super) fn set_input_field(&self, field: Option<gpui::FocusId>) {
+ // Taking the handler during draw must not clear this identity: the
+ // replacement adapter can still represent the same focused document.
+ if self.ivars().input_field.replace(field) != field {
+ self.invalidate_session();
+ if field.is_some() {
+ self.ivars().content_changed.set(true);
+ self.ivars().selection_changed.set(true);
+ self.set_keyboard_visible(true);
+ }
+ }
+ }
+
+ pub(super) fn refresh_keyboard(&self) {
+ if self.ivars().update_pending.replace(true) {
+ return;
+ }
+ // Draw temporarily takes the handler and owns the GPUI Window borrow.
+ // A single deferred reconciliation observes its final state, never a
+ // stale queued request to become first responder after focus was lost.
+ unsafe {
+ self.performSelector_withObject_afterDelay(sel!(reconcileTextInput), None, 0.0);
+ }
+ }
+
+ pub(super) fn set_configuration(&self, configuration: &TextInputConfiguration) {
+ if *self.ivars().configuration.borrow() == *configuration {
+ return;
+ }
+ *self.ivars().configuration.borrow_mut() = configuration.clone();
+ self.ivars().configuration_changed.set(true);
+ self.refresh_keyboard();
+ }
+
+ pub(super) fn state_changed(&self, change: TextInputStateChange) {
+ match change {
+ TextInputStateChange::FocusGained => {
+ self.ivars().content_changed.set(true);
+ self.ivars().selection_changed.set(true);
+ self.set_keyboard_visible(true);
+ }
+ TextInputStateChange::FocusLost => {
+ self.invalidate_session();
+ self.ivars().input_field.set(None);
+ self.set_keyboard_visible(false);
+ }
+ TextInputStateChange::SelectionChanged | TextInputStateChange::ContentChanged => {
+ if self.ivars().native_edit.get() {
+ return;
+ }
+ self.ivars().selection_changed.set(true);
+ if matches!(change, TextInputStateChange::ContentChanged) {
+ self.ivars().content_changed.set(true);
+ }
+ self.refresh_keyboard();
+ }
+ }
+ }
+}
+
+fn native_rect(bounds: gpui::Bounds<gpui::Pixels>) -> CGRect {
+ CGRect::new(
+ CGPoint::new(f64::from(bounds.origin.x), f64::from(bounds.origin.y)),
+ CGSize::new(f64::from(bounds.size.width), f64::from(bounds.size.height)),
+ )
+}
+
+fn nonempty_caret_rect(mut rect: CGRect) -> CGRect {
+ // GPUI can report a zero-width insertion location; UIKit needs a visible caret.
+ rect.size.width = rect.size.width.max(1.);
+ rect
+}
+
+fn contains_range(outer: &Range<usize>, inner: &Range<usize>) -> bool {
+ outer.start <= inner.start && inner.start <= inner.end && inner.end <= outer.end
+}
+
+fn document_range(handler: &mut PlatformInputHandler) -> Option<Range<usize>> {
+ handler
+ .text_input_editable_range()
+ .or_else(|| handler.text_length_utf16().map(|length| 0..length))
+ .filter(|range| range.start <= range.end)
+}
+
+fn allowed_range(handler: &mut PlatformInputHandler, range: &Range<usize>) -> bool {
+ document_range(handler).is_some_and(|editable| contains_range(&editable, range))
+}
+
+fn read_text(
+ handler: &mut PlatformInputHandler,
+ range: Range<usize>,
+) -> Option<Retained<NSString>> {
+ if !allowed_range(handler, &range) {
+ return None;
+ }
+ let mut adjusted = None;
+ let text = handler.text_for_range(range.clone(), &mut adjusted)?;
+ // UIKit cannot represent an adjusted range alongside the returned string.
+ // Do not shift the origin or expose text across an editable-region boundary.
+ if adjusted.is_some_and(|adjusted| adjusted != range)
+ || text.encode_utf16().count() != range.len()
+ {
+ return None;
+ }
+ Some(NSString::from_str(&text))
+}
+
+fn checked_range(location: usize, length: usize, document_length: usize) -> Option<Range<usize>> {
+ let end = location.checked_add(length)?;
+ (end <= document_length).then_some(location..end)
+}
+
+fn composed_character_range(text: &NSString, offset: usize) -> Option<Range<usize>> {
+ // NSString uses UTF-16 and keeps surrogate pairs, combining marks, and
+ // emoji sequences together. Check first: its API raises on an invalid index.
+ if offset >= text.length() {
+ return None;
+ }
+ let range = text.rangeOfComposedCharacterSequenceAtIndex(offset);
+ checked_range(range.location, range.length, text.length())
+}
+
+fn checked_offset(position: usize, offset: isize, document_length: usize) -> Option<usize> {
+ let position = position.checked_add_signed(offset)?;
+ (position <= document_length).then_some(position)
+}
+
+#[cfg(test)]
+pub(super) mod tests {
+ use super::*;
+
+ #[test]
+ fn insertion_geometry_has_a_visible_caret_width() {
+ let rect = nonempty_caret_rect(CGRect::new(CGPoint::new(12., 20.), CGSize::new(0., 30.)));
+ assert_eq!(rect.origin, CGPoint::new(12., 20.));
+ assert_eq!(rect.size, CGSize::new(1., 30.));
+ }
+
+ define_class!(
+ #[unsafe(super = UIView)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUICompetingResponderTestView"]
+ struct CompetingResponder;
+
+ unsafe impl NSObjectProtocol for CompetingResponder {}
+
+ impl CompetingResponder {
+ #[unsafe(method(canBecomeFirstResponder))]
+ fn can_become_first_responder(&self) -> bool { true }
+ }
+ );
+
+ define_class!(
+ #[unsafe(super = objc2_foundation::NSObject)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUITextInputTestDelegate"]
+ #[ivars = RefCell<Vec<&'static str>>]
+ struct InputDelegate;
+
+ unsafe impl NSObjectProtocol for InputDelegate {}
+ unsafe impl UITextInputDelegate for InputDelegate {
+ #[unsafe(method(selectionWillChange:))]
+ fn selection_will_change(&self, _input: Option<&ProtocolObject<dyn UITextInput>>) {
+ self.ivars().borrow_mut().push("selection-will");
+ }
+ #[unsafe(method(selectionDidChange:))]
+ fn selection_did_change(&self, _input: Option<&ProtocolObject<dyn UITextInput>>) {
+ self.ivars().borrow_mut().push("selection-did");
+ }
+ #[unsafe(method(textWillChange:))]
+ fn text_will_change(&self, _input: Option<&ProtocolObject<dyn UITextInput>>) {
+ self.ivars().borrow_mut().push("text-will");
+ }
+ #[unsafe(method(textDidChange:))]
+ fn text_did_change(&self, _input: Option<&ProtocolObject<dyn UITextInput>>) {
+ self.ivars().borrow_mut().push("text-did");
+ }
+ #[unsafe(method(conversationContext:didChange:))]
+ fn conversation_context_did_change(
+ &self,
+ _context: Option<&UIConversationContext>,
+ _input: Option<&ProtocolObject<dyn UITextInput>>,
+ ) {
+ self.ivars().borrow_mut().push("conversation-did");
+ }
+ }
+ );
+
+ #[allow(
+ dead_code,
+ reason = "called by the main-thread integration-test harness"
+ )]
+ pub(crate) fn native_protocol_smoke_test(main_thread: MainThreadMarker) {
+ stale_native_objects_test(main_thread);
+ let view = TextInputView::new(CGRect::ZERO, main_thread);
+ let position = view.new_position(3);
+ assert_eq!(view.validated_offset(&position), Some(3));
+ let range = view.new_range(1..3);
+ assert_eq!(view.validated_offset(&range.start()), Some(1));
+ assert_eq!(view.validated_offset(&range.end()), Some(3));
+ assert!(!range.isEmpty());
+ assert!(view.new_range(3..3).isEmpty());
+
+ let text = NSString::from_str("a😀e\u{301}👨‍👩‍👧‍👦");
+ assert_eq!(composed_character_range(&text, 1), Some(1..3));
+ assert_eq!(composed_character_range(&text, 2), Some(1..3));
+ assert_eq!(composed_character_range(&text, 4), Some(3..5));
+ assert_eq!(composed_character_range(&text, 6), Some(5..16));
+ assert_eq!(composed_character_range(&text, 16), None);
+
+ view.set_window(std::rc::Weak::new());
+ assert!(!view.canBecomeFirstResponder());
+ view.set_keyboard_visible(true);
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ assert!(!view.canBecomeFirstResponder());
+ assert!(!view.hasText());
+ assert!(view.selectedTextRange().is_none());
+ assert!(view.markedTextRange().is_none());
+ assert_eq!(view.validated_offset(&view.beginningOfDocument()), Some(0));
+ assert_eq!(view.validated_offset(&view.endOfDocument()), Some(0));
+ assert_eq!(
+ view.offsetFromPosition_toPosition(&range.start(), &range.end()),
+ 2
+ );
+ assert_eq!(
+ view.comparePosition_toPosition(&range.start(), &range.end()),
+ NSComparisonResult::Ascending
+ );
+ assert!(
+ view.textRangeFromPosition_toPosition(&range.end(), &range.start())
+ .is_some()
+ );
+ view.tokenizer();
+ let delegate = InputDelegate::alloc(main_thread).set_ivars(RefCell::default());
+ let delegate: Retained<InputDelegate> = unsafe { msg_send![super(delegate), init] };
+ view.setInputDelegate(Some(ProtocolObject::from_ref(&*delegate)));
+ view.state_changed(TextInputStateChange::ContentChanged);
+ view.state_changed(TextInputStateChange::SelectionChanged);
+ assert!(delegate.ivars().borrow().is_empty());
+ objc2::rc::autoreleasepool(|_| {
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ });
+ assert_eq!(
+ *delegate.ivars().borrow(),
+ ["text-will", "selection-will", "selection-did", "text-did"]
+ );
+
+ // Delegate queries may leave autoreleased references on the native pool.
+ objc2::rc::autoreleasepool(|_| {
+ let mut fields = slotmap::SlotMap::<gpui::FocusId, ()>::with_key();
+ let first_field = fields.insert(());
+ let second_field = fields.insert(());
+ delegate.ivars().borrow_mut().clear();
+ view.set_input_field(Some(first_field));
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ assert_eq!(
+ *delegate.ivars().borrow(),
+ ["text-will", "selection-will", "selection-did", "text-did"]
+ );
+
+ view.set_keyboard_visible(false);
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ assert_eq!(view.ivars().input_field.get(), Some(first_field));
+ delegate.ivars().borrow_mut().clear();
+ view.set_input_field(Some(first_field));
+ view.refresh_keyboard();
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ assert!(!view.ivars().keyboard_desired.get());
+ assert!(delegate.ivars().borrow().is_empty());
+
+ view.set_keyboard_visible(true);
+ assert_eq!(view.ivars().input_field.get(), Some(first_field));
+ assert!(view.ivars().keyboard_desired.get());
+
+ view.set_input_field(Some(second_field));
+ assert!(view.ivars().keyboard_desired.get());
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ assert_eq!(
+ *delegate.ivars().borrow(),
+ ["text-will", "selection-will", "selection-did", "text-did"]
+ );
+ view.state_changed(TextInputStateChange::FocusLost);
+ assert_eq!(view.ivars().input_field.get(), None);
+ assert!(!view.ivars().keyboard_desired.get());
+ });
+
+ drop(delegate);
+ assert!(view.inputDelegate().is_none());
+ view.setMarkedText_selectedRange(Some(&text), NSRange::new(1, 2));
+ view.unmarkText();
+ view.set_configuration(&TextInputConfiguration {
+ autocorrect: true,
+ autocapitalize: Autocapitalize::Sentences,
+ suggestions: true,
+ input_action: TextInputAction::Search,
+ });
+ assert_eq!(view.autocorrectionType(), UITextAutocorrectionType::Yes);
+ assert_eq!(
+ view.autocapitalizationType(),
+ UITextAutocapitalizationType::Sentences
+ );
+ assert_eq!(view.spellCheckingType(), UITextSpellCheckingType::Yes);
+ assert_eq!(view.returnKeyType(), UIReturnKeyType::Search);
+ view.set_keyboard_visible(false);
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ assert!(!view.canBecomeFirstResponder());
+
+ #[allow(deprecated)] // The standalone protocol harness has no UIApplication scene.
+ let window = UIWindow::initWithFrame(
+ UIWindow::alloc(main_thread),
+ CGRect::new(CGPoint::ZERO, CGSize::new(320., 480.)),
+ );
+ let controller = UIViewController::new(main_thread);
+ controller.setView(Some(&view));
+ window.setRootViewController(Some(&controller));
+ window.makeKeyAndVisible();
+ view.set_keyboard_visible(true);
+ // This fixture has no GPUI handler; permit native responder activation
+ // directly to isolate UIKit-driven resignation from document queries.
+ view.ivars().keyboard_eligible.set(true);
+ assert!(view.becomeFirstResponder());
+ assert!(view.isFirstResponder());
+ assert!(view.resignFirstResponder());
+ assert!(!view.isFirstResponder());
+ assert!(
+ !view.ivars().keyboard_desired.get(),
+ "native resignation must cancel the outstanding keyboard request"
+ );
+
+ view.refresh_keyboard();
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ assert!(!view.ivars().keyboard_desired.get());
+ assert!(!view.isFirstResponder());
+
+ view.set_keyboard_visible(true);
+ view.ivars().keyboard_eligible.set(true);
+ assert!(view.becomeFirstResponder());
+ let other = CompetingResponder::alloc(main_thread).set_ivars(());
+ let other: Retained<CompetingResponder> =
+ unsafe { msg_send![super(other), initWithFrame: CGRect::ZERO] };
+ view.addSubview(&other);
+ assert!(other.becomeFirstResponder());
+ assert!(!view.isFirstResponder());
+ assert!(!view.ivars().keyboard_desired.get());
+ view.refresh_keyboard();
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ assert!(other.isFirstResponder());
+
+ view.set_keyboard_visible(true);
+ view.ivars().keyboard_eligible.set(true);
+ assert!(view.becomeFirstResponder());
+ // A temporary lack of an eligible handler during reconciliation must
+ // not discard a still-pending application request to show the keyboard.
+ view.reconcile_text_input(sel!(reconcileTextInput));
+ assert!(!view.isFirstResponder());
+ assert!(view.ivars().keyboard_desired.get());
+ // Resigning an already inactive view must not cancel a queued request.
+ view.resignFirstResponder();
+ assert!(view.ivars().keyboard_desired.get());
+ window.setHidden(true);
+ }
+
+ fn stale_native_objects_test(main_thread: MainThreadMarker) {
+ let view = TextInputView::new(CGRect::ZERO, main_thread);
+ let mut fields = slotmap::SlotMap::<gpui::FocusId, ()>::with_key();
+ let first = fields.insert(());
+ let second = fields.insert(());
+ view.set_input_field(Some(first));
+ let old_start = view.beginningOfDocument();
+ let old_range = view.new_range(1..3);
+ assert_eq!(view.validated_range(&old_range), Some(1..3));
+ assert!(contains_range(&(0..4), &(1..3)));
+
+ // Both documents have the same UTF-16 extent: bounds checks alone
+ // cannot distinguish the old A range from a valid B range.
+ view.set_input_field(Some(second));
+ assert_eq!(
+ view.validated_range(&old_range),
+ None,
+ "A range must be rejected immediately on switching to equally-sized B"
+ );
+ assert!(
+ view.textRangeFromPosition_toPosition(&old_start, &view.endOfDocument())
+ .is_none(),
+ "the native protocol must reject a stale position before reconciliation"
+ );
+ let fresh_start = view.beginningOfDocument();
+ let fresh_range = view.new_range(1..3);
+ assert_eq!(view.validated_offset(&fresh_start), Some(0));
+ assert_eq!(view.validated_range(&fresh_range), Some(1..3));
+ assert_eq!(view.validated_offset(&old_range.start()), None);
+ assert_eq!(view.validated_offset(&old_range.end()), None);
+ assert_eq!(
+ view.comparePosition_toPosition(&old_range.start(), &fresh_start),
+ NSComparisonResult::Same
+ );
+ assert_eq!(
+ view.offsetFromPosition_toPosition(&old_range.start(), &fresh_start),
+ 0
+ );
+ assert!(
+ view.positionWithinRange_farthestInDirection(&old_range, UITextLayoutDirection::Right)
+ .is_none()
+ );
+ assert!(
+ view.positionWithinRange_farthestInDirection(
+ &fresh_range,
+ UITextLayoutDirection::Right
+ )
+ .is_some()
+ );
+ assert!(
+ view.positionFromPosition_inDirection_offset(
+ &old_start,
+ UITextLayoutDirection::Down,
+ 1
+ )
+ .is_none()
+ );
+ assert!(
+ view.textRangeFromPosition_toPosition(&fresh_start, &view.endOfDocument())
+ .is_some()
+ );
+ view.set_input_field(Some(first));
+ assert_eq!(
+ view.validated_range(&old_range),
+ None,
+ "A→B→A must not revive A objects"
+ );
+ assert_eq!(view.validated_offset(&old_start), None);
+ let returned_start = view.beginningOfDocument();
+ let returned_range = view.new_range(1..3);
+ view.set_input_field(Some(first));
+ view.state_changed(TextInputStateChange::ContentChanged);
+ assert_eq!(view.validated_offset(&returned_start), Some(0));
+ assert_eq!(view.validated_range(&returned_range), Some(1..3));
+ view.state_changed(TextInputStateChange::FocusLost);
+ assert_eq!(view.validated_offset(&returned_start), None);
+ assert_eq!(view.validated_range(&returned_range), None);
+ let foreign = TextInputView::new(CGRect::ZERO, main_thread);
+ assert_eq!(foreign.validated_offset(&view.beginningOfDocument()), None);
+ assert_eq!(foreign.validated_range(&view.new_range(1..3)), None);
+ assert!(
+ foreign
+ .textRangeFromPosition_toPosition(
+ &view.beginningOfDocument(),
+ &foreign.endOfDocument()
+ )
+ .is_none()
+ );
+ }
+
+ #[allow(
+ dead_code,
+ reason = "called by the main-thread integration-test harness"
+ )]
+ pub(crate) fn stale_objects_do_not_route_to_handler(
+ main_thread: MainThreadMarker,
+ handler_queries: impl Fn() -> usize,
+ ) {
+ let view = TextInputView::new(CGRect::ZERO, main_thread);
+ let mut fields = slotmap::SlotMap::<gpui::FocusId, ()>::with_key();
+ view.set_input_field(Some(fields.insert(())));
+ let old_range = view.new_range(1..3);
+ let old_position = old_range.start();
+ view.set_input_field(Some(fields.insert(())));
+ let queries_before = handler_queries();
+ let replacement = NSString::from_str("x");
+ view.replaceRange_withText(&old_range, &replacement);
+ view.setSelectedTextRange(Some(&old_range));
+ assert!(view.textInRange(&old_range).is_none());
+ assert_eq!(view.firstRectForRange(&old_range), CGRect::ZERO);
+ assert_eq!(view.caretRectForPosition(&old_position), CGRect::ZERO);
+ assert!(view.selectionRectsForRange(&old_range).is_empty());
+ assert!(view.positionFromPosition_offset(&old_position, 1).is_none());
+ assert!(
+ view.characterRangeByExtendingPosition_inDirection(
+ &old_position,
+ UITextLayoutDirection::Right
+ )
+ .is_none()
+ );
+ assert!(
+ view.closestPositionToPoint_withinRange(CGPoint::ZERO, &old_range)
+ .is_none()
+ );
+ assert_eq!(
+ handler_queries(),
+ queries_before,
+ "stale mutations and reads must be rejected before resolving B's handler"
+ );
+
+ // The fixture has no GPUI document, but counts attempts to resolve one.
+ // Fresh mutations must reach that boundary, so an absent-handler no-op
+ // cannot make the stale-object assertion pass vacuously.
+ let fresh_range = view.new_range(1..3);
+ view.replaceRange_withText(&fresh_range, &replacement);
+ assert_eq!(handler_queries(), queries_before + 1);
+ view.setSelectedTextRange(Some(&fresh_range));
+ assert_eq!(handler_queries(), queries_before + 2);
+ }
+
+ #[test]
+ fn utf16_ranges_and_offsets() {
+ assert!(contains_range(&(4..8), &(4..4)));
+ assert!(contains_range(&(4..8), &(8..8)));
+ assert!(!contains_range(&(4..8), &(3..5)));
+ assert!(!contains_range(&(4..8), &(7..9)));
+ let reversed_range = Range { start: 6, end: 5 };
+ assert!(!contains_range(&(4..8), &reversed_range));
+ let length = "a😀e\u{301}".encode_utf16().count();
+ assert_eq!(length, 5);
+ assert_eq!(checked_range(1, 2, length), Some(1..3));
+ assert_eq!(checked_range(length, 0, length), Some(length..length));
+ assert_eq!(checked_range(usize::MAX, 1, length), None);
+ assert_eq!(checked_range(4, 2, length), None);
+ assert_eq!(checked_offset(3, -2, length), Some(1));
+ assert_eq!(checked_offset(0, -1, length), None);
+ assert_eq!(checked_offset(length, 1, length), None);
+ assert_eq!(checked_offset(0, isize::MIN, length), None);
+ }
+}
diff --git a/crates/gpui_ios/src/ios/window.rs b/crates/gpui_ios/src/ios/window.rs
new file mode 100644
index 00000000000..2c574dc3f96
--- /dev/null
+++ b/crates/gpui_ios/src/ios/window.rs
@@ -0,0 +1,952 @@
+//! iOS Window implementation using UIWindow and UIViewController.
+//!
+//! iOS windows are fundamentally different from desktop windows:
+//! - Always fullscreen (or split-screen on iPad)
+//! - No title bar or window chrome
+//! - Touch-based input
+//! - Safe area insets for notch/home indicator
+//!
+//! The window is backed by a UIWindow containing a UIViewController
+//! whose view hosts a CAMetalLayer.
+
+use super::events::*;
+use super::text_input::TextInputView;
+use super::{CallbackSlot, IosDisplay, platform::IosPlatformState};
+use gpui::{
+ AnyWindowHandle, Bounds, Capslock, DevicePixels, DispatchEventResult, DisplayId, Edges,
+ GpuSpecs, Modifiers, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
+ PlatformInputHandler, PlatformWindow, Point, PromptButton, PromptLevel, RequestFrameOptions,
+ Scene, Size, TextInputConfiguration, TextInputStateChange, TouchEvent, TouchId, TouchPhase,
+ WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowInsets,
+ WindowParams, WindowVisibility, px, size,
+};
+use gpui_apple::metal_renderer::{Context as MetalContext, MetalRenderer};
+use objc2::rc::Retained;
+use objc2::runtime::AnyClass;
+use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
+use objc2_core_foundation::{CGPoint, CGRect, CGSize};
+use objc2_foundation::{NSNotification, NSNotificationCenter, NSObjectProtocol, NSSet, NSValue};
+use objc2_quartz_core::CAMetalLayer;
+use objc2_ui_kit::{
+ NSValueUIGeometryExtensions, UIKeyboardFrameEndUserInfoKey,
+ UIKeyboardWillChangeFrameNotification, UIKeyboardWillHideNotification, UIStatusBarStyle,
+};
+use objc2_ui_kit::{
+ UIEvent, UIScreen, UITouch, UITraitCollection, UITraitEnvironment, UIUserInterfaceStyle,
+ UIView, UIViewAutoresizing, UIViewController, UIWindow, UIWindowScene,
+};
+use parking_lot::Mutex;
+use raw_window_handle::{HasDisplayHandle, HasWindowHandle, UiKitDisplayHandle, UiKitWindowHandle};
+use std::{
+ cell::{Cell, RefCell},
+ ffi::c_void,
+ ptr::NonNull,
+ rc::{Rc, Weak},
+ sync::Arc,
+};
+
+const KEYBOARD_DISMISS_DISTANCE: Pixels = px(24.);
+
+#[derive(Clone, Copy)]
+struct KeyboardDismissTouch {
+ id: TouchId,
+ start_position: Point<Pixels>,
+}
+
+/// Global storage for the current status bar style.
+/// 0 = default (dark content), 1 = light content.
+/// Accessed from the main thread only.
+static STATUS_BAR_STYLE: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
+
+#[derive(Default)]
+pub(super) struct WindowReference(pub(super) RefCell<Weak<IosWindowState>>);
+
+impl WindowReference {
+ pub(super) fn with_window<R>(&self, callback: impl FnOnce(&IosWindowState) -> R) -> Option<R> {
+ let window = self.0.borrow().upgrade()?;
+ // Keep callback storage and native objects alive even if the callback
+ // synchronously closes the platform window.
+ Some(callback(&window))
+ }
+}
+
+define_class!(
+ #[unsafe(super = UIViewController)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUIViewController"]
+ #[ivars = WindowReference]
+ struct ViewController;
+
+ impl ViewController {
+ #[unsafe(method(preferredStatusBarStyle))]
+ fn preferred_status_bar_style(&self) -> UIStatusBarStyle {
+ let style = STATUS_BAR_STYLE.load(std::sync::atomic::Ordering::Relaxed);
+ if style == 1 {
+ UIStatusBarStyle::LightContent
+ } else {
+ UIStatusBarStyle::DarkContent
+ }
+ }
+
+ #[unsafe(method(viewDidLayoutSubviews))]
+ fn view_did_layout_subviews(&self) {
+ unsafe {
+ let _: () = msg_send![super(self), viewDidLayoutSubviews];
+ }
+ self.ivars().with_window(IosWindowState::handle_layout_change);
+ }
+ }
+);
+
+impl ViewController {
+ fn new(main_thread: MainThreadMarker) -> Retained<Self> {
+ let this = Self::alloc(main_thread).set_ivars(WindowReference::default());
+ unsafe { msg_send![super(this), init] }
+ }
+}
+
+/// Set the iOS status bar content style (light or dark text/icons).
+///
+/// This updates the stored style and asks the root view controller
+/// to re-query `preferredStatusBarStyle`.
+pub fn set_status_bar_style(style: crate::StatusBarContentStyle) {
+ use crate::StatusBarContentStyle;
+
+ let value = match style {
+ StatusBarContentStyle::Light => 1,
+ StatusBarContentStyle::Dark => 0,
+ };
+ STATUS_BAR_STYLE.store(value, std::sync::atomic::Ordering::Relaxed);
+
+ // This public free function predates explicit platform ownership.
+ // Keep its single-application behavior without making runtime events global.
+ if let Some(platform) = super::application::current_platform() {
+ platform.application.with_windows(|window| {
+ window.view_controller.setNeedsStatusBarAppearanceUpdate();
+ });
+ }
+}
+
+define_class!(
+ #[unsafe(super = UIView)]
+ #[thread_kind = MainThreadOnly]
+ #[name = "GPUIMetalView"]
+ #[ivars = WindowReference]
+ struct MetalView;
+
+ unsafe impl NSObjectProtocol for MetalView {}
+
+ impl MetalView {
+ #[unsafe(method(layerClass))]
+ fn layer_class() -> &'static AnyClass {
+ CAMetalLayer::class()
+ }
+
+ // This callback also covers iOS 15/16, before UIKit's trait-registration API.
+ #[unsafe(method(traitCollectionDidChange:))]
+ fn trait_collection_did_change(&self, previous: Option<&UITraitCollection>) {
+ unsafe {
+ let _: () = msg_send![super(self), traitCollectionDidChange: previous];
+ if self
+ .traitCollection()
+ .hasDifferentColorAppearanceComparedToTraitCollection(previous)
+ {
+ self.ivars()
+ .with_window(IosWindowState::notify_appearance_changed);
+ }
+ }
+ }
+
+ #[unsafe(method(touchesBegan:withEvent:))]
+ fn touches_began(&self, touches: &NSSet<UITouch>, event: Option<&UIEvent>) {
+ self.handle_touches(touches, event);
+ }
+
+ #[unsafe(method(touchesMoved:withEvent:))]
+ fn touches_moved(&self, touches: &NSSet<UITouch>, event: Option<&UIEvent>) {
+ self.handle_touches(touches, event);
+ }
+
+ #[unsafe(method(touchesEnded:withEvent:))]
+ fn touches_ended(&self, touches: &NSSet<UITouch>, event: Option<&UIEvent>) {
+ self.handle_touches(touches, event);
+ }
+
+ #[unsafe(method(touchesCancelled:withEvent:))]
+ fn touches_cancelled(&self, touches: &NSSet<UITouch>, event: Option<&UIEvent>) {
+ self.handle_touches(touches, event);
+ }
+
+ }
+);
+
+impl MetalView {
+ fn new(frame: CGRect, main_thread: MainThreadMarker) -> Retained<Self> {
+ let this = Self::alloc(main_thread).set_ivars(WindowReference::default());
+ unsafe { msg_send![super(this), initWithFrame: frame] }
+ }
+
+ fn handle_touches(&self, touches: &NSSet<UITouch>, event: Option<&UIEvent>) {
+ for touch in touches {
+ self.ivars()
+ .with_window(|window| window.handle_touch(&touch, event));
+ }
+ }
+}
+
+pub(crate) struct IosWindow {
+ state: Rc<IosWindowState>,
+}
+
+impl std::ops::Deref for IosWindow {
+ type Target = IosWindowState;
+
+ fn deref(&self) -> &Self::Target {
+ &self.state
+ }
+}
+
+#[allow(clippy::type_complexity)]
+pub(crate) struct IosWindowState {
+ platform: Weak<IosPlatformState>,
+ keyboard_observers:
+ RefCell<Vec<Retained<objc2::runtime::ProtocolObject<dyn NSObjectProtocol>>>>,
+ /// The UIWindow object
+ window: Retained<UIWindow>,
+ /// The UIViewController
+ view_controller: Retained<ViewController>,
+ /// The Metal-backed UIView
+ view: Retained<MetalView>,
+ /// The hidden text input view for keyboard input
+ text_input_view: Retained<TextInputView>,
+ /// Current bounds in pixels
+ bounds: Cell<Bounds<Pixels>>,
+ /// Scale factor
+ scale_factor: Cell<f32>,
+ /// Input handler for text input
+ input_handler: CallbackSlot<PlatformInputHandler>,
+ request_frame_callback: CallbackSlot<Box<dyn FnMut(RequestFrameOptions)>>,
+ force_next_frame: Cell<bool>,
+ /// Callback for input events
+ input_callback: CallbackSlot<Box<dyn FnMut(PlatformInput) -> DispatchEventResult>>,
+ /// Callback for active status changes
+ active_status_callback: CallbackSlot<Box<dyn FnMut(bool)>>,
+ visibility: Cell<WindowVisibility>,
+ visibility_callback: CallbackSlot<Box<dyn FnMut(WindowVisibility)>>,
+ /// Callback for hover status changes (not really applicable on iOS)
+ hover_status_callback: CallbackSlot<Box<dyn FnMut(bool)>>,
+ /// Callback for resize events
+ resize_callback: CallbackSlot<Box<dyn FnMut(Size<Pixels>, f32)>>,
+ display_id: Cell<DisplayId>,
+ display_changed_callback: CallbackSlot<Box<dyn FnMut()>>,
+ /// Callback for move events (not applicable on iOS)
+ moved_callback: CallbackSlot<Box<dyn FnMut()>>,
+ /// Callback for should close
+ should_close_callback: CallbackSlot<Box<dyn FnMut() -> bool>>,
+ /// Callback for hit test
+ hit_test_callback: CallbackSlot<Box<dyn FnMut() -> Option<WindowControlArea>>>,
+ /// Callback for close
+ close_callback: CallbackSlot<Box<dyn FnOnce()>>,
+ /// Callback for appearance changes
+ appearance_changed_callback: CallbackSlot<Box<dyn FnMut()>>,
+ insets_changed_callback: CallbackSlot<Box<dyn FnMut(WindowInsets)>>,
+ keyboard_dismiss_touch: Cell<Option<KeyboardDismissTouch>>,
+ keyboard_height: Cell<f32>,
+ /// Current mouse position (from touch)
+ mouse_position: Cell<Point<Pixels>>,
+ /// Current modifiers
+ modifiers: Cell<Modifiers>,
+ renderer: Mutex<MetalRenderer>,
+}
+
+impl IosWindow {
+ #[allow(deprecated)] // Window construction can precede scene connection.
+ pub fn new(
+ _handle: AnyWindowHandle,
+ _params: WindowParams,
+ platform: &Rc<IosPlatformState>,
+ ) -> anyhow::Result<Self> {
+ // Create the window on the main screen
+ let screen = IosDisplay::main();
+ let screen_bounds = screen.bounds();
+ let scale_factor = screen.scale();
+
+ let main_thread = MainThreadMarker::new().expect("UIKit requires the main thread");
+ // Create UIWindow
+ let window_scene = platform.application.window_scene();
+ let window_scene = window_scene.as_deref();
+ let (window, screen_bounds_cg, scale) = if let Some(scene) = window_scene {
+ let screen = scene.screen();
+ let bounds = screen.bounds();
+ let window = UIWindow::initWithWindowScene(UIWindow::alloc(main_thread), scene);
+ window.setFrame(bounds);
+ (window, bounds, screen.scale())
+ } else {
+ let screen = UIScreen::mainScreen(main_thread);
+ let bounds = screen.bounds();
+ let window = UIWindow::initWithFrame(UIWindow::alloc(main_thread), bounds);
+ (window, bounds, screen.scale())
+ };
+
+ let metal_frame = CGRect::new(CGPoint::ZERO, screen_bounds_cg.size);
+ let view = MetalView::new(metal_frame, main_thread);
+
+ let layer = view.layer();
+ layer.setContentsScale(scale);
+
+ // Auto-resize the Metal view when the parent view changes size
+ // (e.g. rotation). UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight
+ view.setAutoresizingMask(
+ UIViewAutoresizing::FlexibleWidth | UIViewAutoresizing::FlexibleHeight,
+ );
+
+ // Enable user interaction on the Metal view for touch handling
+ view.setUserInteractionEnabled(true);
+ view.setMultipleTouchEnabled(true);
+
+ let view_controller = ViewController::new(main_thread);
+ view_controller.setView(Some(&view));
+ window.setRootViewController(Some(&view_controller));
+
+ // Make the window visible
+ window.makeKeyAndVisible();
+
+ // Create a hidden text input view for keyboard handling.
+ // Uses our custom GPUITextInputView which implements UIKeyInput
+ // so iOS actually routes keyboard text to us.
+ let text_input_frame = CGRect::new(CGPoint::ZERO, CGSize::new(1.0, 1.0));
+ let text_input_view = TextInputView::new(text_input_frame, main_thread);
+ text_input_view.setAlpha(0.01);
+ text_input_view.setUserInteractionEnabled(true);
+ view.addSubview(&text_input_view);
+
+ let pixel_w = (screen_bounds_cg.size.width * scale) as i32;
+ let pixel_h = (screen_bounds_cg.size.height * scale) as i32;
+ let mut renderer = MetalRenderer::from_layer(
+ MetalContext::default(),
+ layer
+ .downcast_ref::<CAMetalLayer>()
+ .ok_or_else(|| anyhow::anyhow!("UIKit view must have a CAMetalLayer"))?,
+ false,
+ );
+ renderer.update_drawable_size(size(DevicePixels(pixel_w), DevicePixels(pixel_h)));
+
+ let state = IosWindowState {
+ platform: Rc::downgrade(platform),
+ keyboard_observers: RefCell::default(),
+ display_id: Cell::new(IosDisplay::from_screen(window.screen()).id()),
+ display_changed_callback: CallbackSlot::default(),
+ window,
+ view_controller,
+ view,
+ text_input_view,
+ bounds: Cell::new(screen_bounds),
+ scale_factor: Cell::new(scale_factor),
+ input_handler: CallbackSlot::default(),
+ request_frame_callback: CallbackSlot::default(),
+ force_next_frame: Cell::new(true),
+ input_callback: CallbackSlot::default(),
+ active_status_callback: CallbackSlot::default(),
+ visibility: Cell::new(WindowVisibility::Visible),
+ visibility_callback: CallbackSlot::default(),
+ hover_status_callback: CallbackSlot::default(),
+ resize_callback: CallbackSlot::default(),
+ moved_callback: CallbackSlot::default(),
+ should_close_callback: CallbackSlot::default(),
+ hit_test_callback: CallbackSlot::default(),
+ close_callback: CallbackSlot::default(),
+ appearance_changed_callback: CallbackSlot::default(),
+ insets_changed_callback: CallbackSlot::default(),
+ keyboard_dismiss_touch: Cell::new(None),
+ keyboard_height: Cell::new(0.),
+ mouse_position: Cell::new(Point::default()),
+ modifiers: Cell::new(Modifiers::default()),
+ renderer: Mutex::new(renderer),
+ };
+
+ Ok(Self {
+ state: Rc::new(state),
+ })
+ }
+
+ pub(crate) fn register(&self) {
+ if let Some(platform) = self.platform.upgrade() {
+ platform.application.register_window(&self.state);
+ }
+
+ let window = Rc::downgrade(&self.state);
+ *self.view_controller.ivars().0.borrow_mut() = window.clone();
+ *self.view.ivars().0.borrow_mut() = window.clone();
+ self.text_input_view.set_window(window);
+
+ self.state.register_keyboard_observers();
+ }
+}
+
+impl IosWindowState {
+ pub(super) fn attach_to_scene(&self, scene: &UIWindowScene) {
+ self.window.setWindowScene(Some(scene));
+ self.window.makeKeyAndVisible();
+ self.handle_layout_change();
+ }
+
+ fn register_keyboard_observers(self: &Rc<Self>) {
+ unsafe {
+ let notification_center = NSNotificationCenter::defaultCenter();
+
+ let window = Rc::downgrade(self);
+ let frame_change_block =
+ block2::RcBlock::new(move |notification: NonNull<NSNotification>| {
+ let Some(user_info) = notification.as_ref().userInfo() else {
+ return;
+ };
+ let Some(frame_value) = user_info.objectForKey(UIKeyboardFrameEndUserInfoKey)
+ else {
+ return;
+ };
+ let Some(frame_value) = frame_value.downcast_ref::<NSValue>() else {
+ return;
+ };
+ let frame = frame_value.CGRectValue();
+ if let Some(window) = window.upgrade() {
+ window.set_keyboard_height(frame.size.height as f32);
+ }
+ });
+
+ let window = Rc::downgrade(self);
+ let hide_block = block2::RcBlock::new(move |_notification: NonNull<NSNotification>| {
+ if let Some(window) = window.upgrade() {
+ window.set_keyboard_height(0.);
+ }
+ });
+
+ let frame_observer = notification_center.addObserverForName_object_queue_usingBlock(
+ Some(UIKeyboardWillChangeFrameNotification),
+ None,
+ None,
+ &frame_change_block,
+ );
+ let hide_observer = notification_center.addObserverForName_object_queue_usingBlock(
+ Some(UIKeyboardWillHideNotification),
+ None,
+ None,
+ &hide_block,
+ );
+ self.keyboard_observers
+ .borrow_mut()
+ .extend([frame_observer, hide_observer]);
+ }
+ }
+
+ /// Delivers a UIKit touch through GPUI's platform-neutral touch API.
+ pub fn handle_touch(&self, touch: &UITouch, _event: Option<&UIEvent>) {
+ // GPUI timestamps delivery itself. Replaying UIKit's historical coalesced
+ // samples here would make them appear simultaneous and distort fling velocity.
+ let id = touch_id(touch);
+ self.handle_touch_sample(touch, id);
+ }
+
+ fn handle_touch_sample(&self, touch: &UITouch, id: TouchId) {
+ let position = touch_location_in_view(touch, &self.view);
+ self.mouse_position.set(position);
+
+ let event = TouchEvent {
+ id,
+ phase: touch_phase(touch),
+ position,
+ predicted_position: None,
+ force: touch_force(touch),
+ };
+ self.handle_keyboard_dismiss_touch(&event);
+ self.input_callback
+ .with(|callback| callback(PlatformInput::Touch(event)));
+ }
+
+ fn handle_keyboard_dismiss_touch(&self, event: &TouchEvent) {
+ if self.keyboard_height.get() <= 0. {
+ self.keyboard_dismiss_touch.set(None);
+ return;
+ }
+
+ match event.phase {
+ TouchPhase::Started if self.keyboard_dismiss_touch.get().is_none() => {
+ self.keyboard_dismiss_touch.set(Some(KeyboardDismissTouch {
+ id: event.id,
+ start_position: event.position,
+ }));
+ }
+ TouchPhase::Moved => {
+ let Some(touch) = self
+ .keyboard_dismiss_touch
+ .get()
+ .filter(|touch| touch.id == event.id)
+ else {
+ return;
+ };
+ let delta = event.position - touch.start_position;
+ if delta.y >= KEYBOARD_DISMISS_DISTANCE && delta.y.abs() > delta.x.abs() * 1.25 {
+ self.keyboard_dismiss_touch.set(None);
+ self.hide_keyboard();
+ }
+ }
+ TouchPhase::Ended | TouchPhase::Cancelled => {
+ if self
+ .keyboard_dismiss_touch
+ .get()
+ .is_some_and(|touch| touch.id == event.id)
+ {
+ self.keyboard_dismiss_touch.set(None);
+ }
+ }
+ TouchPhase::Started => {}
+ }
+ }
+
+ pub(super) fn request_frame(&self) {
+ self.request_frame_callback.with(|callback| {
+ let force_render = self.force_next_frame.replace(false);
+ callback(RequestFrameOptions {
+ force_render,
+ ..Default::default()
+ });
+ });
+ }
+
+ /// Query the safe area insets from the UIView.
+ ///
+ /// Returns `(top, bottom, left, right)` in logical points.
+ /// These represent the areas occupied by system UI (status bar,
+ /// home indicator, camera notch) that content should avoid.
+ fn safe_area_insets(&self) -> (f32, f32, f32, f32) {
+ let insets = self.view.safeAreaInsets();
+ (
+ insets.top as f32,
+ insets.bottom as f32,
+ insets.left as f32,
+ insets.right as f32,
+ )
+ }
+
+ fn current_insets(&self) -> WindowInsets {
+ let (top, bottom, left, right) = self.safe_area_insets();
+ WindowInsets {
+ safe_area: Edges {
+ top: px(top),
+ right: px(right),
+ bottom: px(bottom),
+ left: px(left),
+ },
+ ime: Edges {
+ bottom: px(self.keyboard_height.get()),
+ ..Default::default()
+ },
+ }
+ }
+
+ fn notify_insets_changed(&self) {
+ self.insets_changed_callback
+ .with(|callback| callback(self.current_insets()));
+ }
+
+ fn notify_appearance_changed(&self) {
+ self.appearance_changed_callback.with(|callback| callback());
+ }
+
+ fn set_keyboard_height(&self, height: f32) {
+ let height = height.max(0.);
+ if (self.keyboard_height.get() - height).abs() <= 0.5 {
+ return;
+ }
+ self.keyboard_height.set(height);
+ if height <= 0. {
+ self.keyboard_dismiss_touch.set(None);
+ }
+ self.notify_insets_changed();
+ }
+
+ pub fn show_keyboard(&self) {
+ self.text_input_view.set_keyboard_visible(true);
+ }
+
+ pub fn hide_keyboard(&self) {
+ self.text_input_view.set_keyboard_visible(false);
+ }
+
+ pub(super) fn with_input_handler<R>(
+ &self,
+ callback: impl FnOnce(&mut PlatformInputHandler) -> R,
+ ) -> Option<R> {
+ self.input_handler.with(callback)
+ }
+
+ /// Notify the window when its UIKit scene becomes active or inactive.
+ pub fn notify_active_status_change(&self, is_active: bool) {
+ log::info!("GPUI iOS: Window active status changed to: {}", is_active);
+
+ self.active_status_callback
+ .with(|callback| callback(is_active));
+ }
+
+ pub(crate) fn notify_visibility_change(&self, visibility: WindowVisibility) {
+ if self.visibility.replace(visibility) != visibility {
+ self.visibility_callback
+ .with(|callback| callback(visibility));
+ }
+ }
+
+ pub fn handle_layout_change(&self) {
+ let view_bounds = self.view.bounds();
+ let display = IosDisplay::from_screen(self.window.screen());
+ if self.display_id.replace(display.id()) != display.id() {
+ self.display_changed_callback.with(|callback| callback());
+ }
+ let scale = display.scale() as f64;
+
+ let width = view_bounds.size.width as f32;
+ let height = view_bounds.size.height as f32;
+ let new_scale = scale as f32;
+
+ let old_bounds = self.bounds.get();
+ let old_scale = self.scale_factor.get();
+
+ let new_size = size(px(width), px(height));
+ self.notify_insets_changed();
+
+ if old_bounds.size == new_size && (old_scale - new_scale).abs() < 0.01 {
+ return;
+ }
+
+ log::info!(
+ "GPUI iOS: Layout changed — {:?} @{:.1}x → {:?} @{:.1}x",
+ old_bounds.size,
+ old_scale,
+ new_size,
+ new_scale,
+ );
+
+ // Update stored bounds (in logical pixels, matching GPUI convention).
+ let new_bounds = Bounds {
+ origin: Default::default(),
+ size: new_size,
+ };
+ self.bounds.set(new_bounds);
+ self.scale_factor.set(new_scale);
+ // Update the Metal layer's contentsScale so the drawable has the
+ // correct pixel dimensions.
+ self.view.layer().setContentsScale(scale);
+
+ let pixel_width = (width * new_scale) as i32;
+ let pixel_height = (height * new_scale) as i32;
+ self.renderer
+ .lock()
+ .update_drawable_size(size(DevicePixels(pixel_width), DevicePixels(pixel_height)));
+
+ self.resize_callback
+ .with(|callback| callback(new_size, new_scale));
+ }
+}
+
+impl Drop for IosWindow {
+ fn drop(&mut self) {
+ if let Some(platform) = self.platform.upgrade() {
+ platform.application.unregister_window(&self.state);
+ }
+ let observers = std::mem::take(&mut *self.keyboard_observers.borrow_mut());
+ for observer in observers {
+ unsafe { NSNotificationCenter::defaultCenter().removeObserver((&*observer).as_ref()) };
+ }
+
+ *self.view_controller.ivars().0.borrow_mut() = Weak::new();
+ *self.view.ivars().0.borrow_mut() = Weak::new();
+ self.text_input_view.set_window(Weak::new());
+ self.text_input_view.removeFromSuperview();
+ }
+}
+
+impl HasWindowHandle for IosWindow {
+ fn window_handle(
+ &self,
+ ) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError>
+ {
+ let view = NonNull::new(Retained::as_ptr(&self.view).cast_mut().cast::<c_void>())
+ .ok_or(raw_window_handle::HandleError::Unavailable)?;
+ let handle = UiKitWindowHandle::new(view);
+ Ok(unsafe { raw_window_handle::WindowHandle::borrow_raw(handle.into()) })
+ }
+}
+
+impl HasDisplayHandle for IosWindow {
+ fn display_handle(
+ &self,
+ ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError>
+ {
+ let handle = UiKitDisplayHandle::new();
+ Ok(unsafe { raw_window_handle::DisplayHandle::borrow_raw(handle.into()) })
+ }
+}
+
+impl PlatformWindow for IosWindow {
+ fn bounds(&self) -> Bounds<Pixels> {
+ self.bounds.get()
+ }
+
+ fn is_maximized(&self) -> bool {
+ true // iOS windows are always "maximized"
+ }
+
+ fn window_bounds(&self) -> WindowBounds {
+ WindowBounds::Fullscreen(self.bounds.get())
+ }
+
+ fn content_size(&self) -> Size<Pixels> {
+ self.bounds.get().size
+ }
+
+ fn resize(&mut self, _size: Size<Pixels>) {
+ // iOS windows cannot be resized programmatically
+ }
+
+ fn scale_factor(&self) -> f32 {
+ self.scale_factor.get()
+ }
+
+ fn appearance(&self) -> WindowAppearance {
+ match unsafe { self.view.traitCollection().userInterfaceStyle() } {
+ UIUserInterfaceStyle::Dark => WindowAppearance::Dark,
+ _ => WindowAppearance::Light,
+ }
+ }
+
+ fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
+ Some(Rc::new(IosDisplay::from_screen(self.window.screen())))
+ }
+
+ fn on_display_changed(&self, callback: Box<dyn FnMut()>) {
+ self.display_changed_callback.set(callback);
+ }
+
+ fn mouse_position(&self) -> Point<Pixels> {
+ self.mouse_position.get()
+ }
+
+ fn modifiers(&self) -> Modifiers {
+ self.modifiers.get()
+ }
+
+ fn capslock(&self) -> Capslock {
+ // Would need to check UIKeyModifierFlags
+ Capslock { on: false }
+ }
+
+ fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
+ self.text_input_view
+ .set_input_field(input_handler.focus_id());
+ self.input_handler.set(input_handler);
+ self.text_input_view.refresh_keyboard();
+ }
+
+ fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
+ let handler = self.input_handler.take();
+ self.text_input_view.refresh_keyboard();
+ handler
+ }
+
+ fn prompt(
+ &self,
+ _level: PromptLevel,
+ _msg: &str,
+ _detail: Option<&str>,
+ _answers: &[PromptButton],
+ ) -> Option<futures::channel::oneshot::Receiver<usize>> {
+ None
+ }
+
+ fn activate(&self) {
+ self.window.makeKeyAndVisible();
+ }
+
+ fn is_active(&self) -> bool {
+ self.window.isKeyWindow()
+ }
+
+ fn is_hovered(&self) -> bool {
+ // Hover isn't really applicable on iOS
+ false
+ }
+
+ fn set_title(&mut self, _title: &str) {
+ // iOS apps don't have window titles
+ }
+
+ fn background_appearance(&self) -> WindowBackgroundAppearance {
+ WindowBackgroundAppearance::Opaque
+ }
+
+ fn set_background_appearance(&self, _background_appearance: WindowBackgroundAppearance) {
+ // Could adjust view background color
+ }
+
+ fn minimize(&self) {
+ // iOS apps cannot be minimized
+ }
+
+ fn zoom(&self) {
+ // iOS apps cannot be zoomed
+ }
+
+ fn toggle_fullscreen(&self) {
+ // iOS apps are always fullscreen
+ }
+
+ fn is_fullscreen(&self) -> bool {
+ true
+ }
+
+ fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
+ self.request_frame_callback.set(callback);
+ }
+
+ fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
+ self.input_callback.set(callback);
+ }
+
+ fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
+ self.active_status_callback.set(callback);
+ }
+
+ fn visibility(&self) -> WindowVisibility {
+ self.visibility.get()
+ }
+
+ fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>) {
+ self.visibility_callback.set(callback);
+ }
+
+ fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
+ self.hover_status_callback.set(callback);
+ }
+
+ fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
+ self.resize_callback.set(callback);
+ }
+
+ fn on_moved(&self, callback: Box<dyn FnMut()>) {
+ self.moved_callback.set(callback);
+ }
+
+ fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
+ self.should_close_callback.set(callback);
+ }
+
+ fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
+ self.hit_test_callback.set(callback);
+ }
+
+ fn on_close(&self, callback: Box<dyn FnOnce()>) {
+ self.close_callback.set(callback);
+ }
+
+ fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
+ self.appearance_changed_callback.set(callback);
+ }
+
+ fn draw(&self, scene: &Scene) {
+ self.renderer.lock().draw(scene);
+ }
+
+ fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
+ self.renderer.lock().sprite_atlas().clone()
+ }
+
+ fn is_subpixel_rendering_supported(&self) -> bool {
+ false
+ }
+
+ fn gpu_specs(&self) -> Option<GpuSpecs> {
+ None
+ }
+
+ fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
+ // iOS handles IME positioning automatically
+ }
+
+ fn insets(&self) -> WindowInsets {
+ self.current_insets()
+ }
+
+ fn on_insets_changed(&self, callback: Box<dyn FnMut(WindowInsets)>) {
+ self.insets_changed_callback.set(callback);
+ }
+
+ fn show_soft_keyboard(&self) {
+ self.show_keyboard();
+ }
+
+ fn hide_soft_keyboard(&self) {
+ self.hide_keyboard();
+ }
+
+ fn text_input_state_changed(&self, change: TextInputStateChange) {
+ self.text_input_view.state_changed(change);
+ }
+
+ fn set_text_input_configuration(&mut self, configuration: TextInputConfiguration) {
+ self.text_input_view.set_configuration(&configuration);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::CallbackSlot;
+
+ #[test]
+ fn callback_is_unavailable_during_dispatch_and_restored_afterward() {
+ let slot = CallbackSlot::default();
+ slot.set(1);
+ assert_eq!(
+ slot.with(|value| {
+ *value += 1;
+ assert!(
+ slot.with(|_| panic!("reentered the same handler"))
+ .is_none()
+ );
+ *value
+ }),
+ Some(2)
+ );
+ assert_eq!(slot.with(|value| *value), Some(2));
+ }
+
+ #[test]
+ fn callback_replacement_during_dispatch_is_preserved() {
+ let slot = CallbackSlot::default();
+ slot.set(1);
+ slot.with(|_| {
+ slot.set(2);
+ slot.with(|value| *value += 1);
+ });
+ assert_eq!(slot.take(), Some(3));
+ }
+
+ #[test]
+ fn withdrawing_an_in_flight_handler_does_not_restore_it() {
+ let slot = CallbackSlot::default();
+ slot.set(1);
+ slot.with(|_| assert!(slot.take().is_none()));
+ assert!(
+ slot.with(|_| panic!("restored a withdrawn handler"))
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn removing_a_replacement_does_not_resurrect_the_previous_handler() {
+ let slot = CallbackSlot::default();
+ slot.set(1);
+ slot.with(|_| {
+ slot.set(2);
+ assert_eq!(slot.take(), Some(2));
+ });
+ assert!(slot.take().is_none());
+ }
+}
diff --git a/crates/gpui_ios/tests/text_input.rs b/crates/gpui_ios/tests/text_input.rs
new file mode 100644
index 00000000000..158f1e234b0
--- /dev/null
+++ b/crates/gpui_ios/tests/text_input.rs
@@ -0,0 +1,59 @@
+#[cfg(target_os = "ios")]
+#[path = "../src/ios/text_input.rs"]
+mod text_input;
+
+// Native protocol construction does not need a GPUI window, renderer, or a
+// second text model. This fixture deliberately has no registered input handler.
+#[cfg(target_os = "ios")]
+mod window {
+ use gpui::PlatformInputHandler;
+ use std::{
+ cell::{Cell, RefCell},
+ rc::Weak,
+ };
+
+ thread_local! {
+ static HANDLER_QUERIES: Cell<usize> = const { Cell::new(0) };
+ }
+
+ pub(crate) fn handler_queries() -> usize {
+ HANDLER_QUERIES.with(Cell::get)
+ }
+
+ pub(crate) struct IosWindowState;
+
+ impl IosWindowState {
+ pub(crate) fn with_input_handler<R>(
+ &self,
+ _callback: impl FnOnce(&mut PlatformInputHandler) -> R,
+ ) -> Option<R> {
+ None
+ }
+ }
+
+ #[derive(Default)]
+ pub(crate) struct WindowReference(pub(crate) RefCell<Weak<IosWindowState>>);
+
+ impl WindowReference {
+ pub(crate) fn with_window<R>(
+ &self,
+ callback: impl FnOnce(&IosWindowState) -> R,
+ ) -> Option<R> {
+ HANDLER_QUERIES.with(|queries| queries.set(queries.get() + 1));
+ self.0.borrow().upgrade().map(|window| callback(&window))
+ }
+ }
+}
+
+fn main() {
+ #[cfg(target_os = "ios")]
+ {
+ let main_thread = objc2::MainThreadMarker::new().expect("native test runs on main thread");
+ text_input::tests::native_protocol_smoke_test(main_thread);
+ text_input::tests::stale_objects_do_not_route_to_handler(
+ main_thread,
+ window::handler_queries,
+ );
+ println!("UIKit text input native protocol smoke test passed");
+ }
+}
diff --git a/crates/gpui_platform/Cargo.toml b/crates/gpui_platform/Cargo.toml
index 11ff9e182b1..0d95d3e6a7f 100644
--- a/crates/gpui_platform/Cargo.toml
+++ b/crates/gpui_platform/Cargo.toml
@@ -22,7 +22,7 @@ font-kit = ["gpui_macos/font-kit"]
inspector = ["gpui/inspector"]
test-support = ["gpui/test-support", "gpui_macos/test-support", "gpui_windows/test-support", "gpui_wgpu/test-support"]
screen-capture = ["gpui/screen-capture", "gpui_macos/screen-capture", "gpui_windows/screen-capture", "gpui_linux/screen-capture"]
-runtime_shaders = ["gpui_macos/runtime_shaders"]
+runtime_shaders = ["gpui_macos/runtime_shaders", "gpui_ios/runtime_shaders"]
wayland = ["gpui_linux/wayland"]
x11 = ["gpui_linux/x11"]
@@ -47,6 +47,9 @@ criterion.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
gpui_macos.workspace = true
+[target.'cfg(target_os = "ios")'.dependencies]
+gpui_ios.workspace = true
+
[target.'cfg(target_os = "windows")'.dependencies]
gpui_windows.workspace = true
gpui = { workspace = true, features = ["windows-manifest"] }
diff --git a/crates/gpui_platform/src/gpui_platform.rs b/crates/gpui_platform/src/gpui_platform.rs
index cb48a79d442..c55da39b25f 100644
--- a/crates/gpui_platform/src/gpui_platform.rs
+++ b/crates/gpui_platform/src/gpui_platform.rs
@@ -65,6 +65,11 @@ pub fn web_init() {
/// Returns the default [`Platform`] for the current OS.
pub fn current_platform(headless: bool) -> Rc<dyn Platform> {
+ #[cfg(target_os = "ios")]
+ {
+ gpui_ios::current_platform(headless)
+ }
+
#[cfg(target_os = "macos")]
{
Rc::new(gpui_macos::MacPlatform::new(headless))