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: Add mobile/touch API surface (#60496)

Mikayla Maki9c3273201ce6
diff --git a/crates/editor/src/runnables.rs b/crates/editor/src/runnables.rs
index 956e4dd2e09..a0e1f585617 100644
--- a/crates/editor/src/runnables.rs
+++ b/crates/editor/src/runnables.rs
@@ -537,6 +537,7 @@ impl Editor {
let quick_launch = match e {
ClickEvent::Keyboard(_) => true,
ClickEvent::Mouse(e) => e.down.button == MouseButton::Left,
+ ClickEvent::Touch(_) => true,
};
window.focus(&editor.focus_handle(cx), cx);
diff --git a/crates/gpui/src/gestures.rs b/crates/gpui/src/gestures.rs
new file mode 100644
index 00000000000..5e14d4249bc
--- /dev/null
+++ b/crates/gpui/src/gestures.rs
@@ -0,0 +1,123 @@
+//! 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.
+
+use std::time::Duration;
+
+use crate::{Pixels, Point, px};
+
+/// Feel constants consumed by gesture recognizers. Provided on a best-effort
+/// basis, depending on each platform's support, defaulting to GPUI's own
+/// (iOS flavored) values
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct GestureTuning {
+ /// Distance a touch may travel before it stops being a potential tap and
+ /// becomes a pan/drag.
+ pub touch_slop: Pixels,
+ /// Maximum interval between taps for them to accumulate a tap count.
+ pub multi_tap_interval: Duration,
+ /// Maximum distance between taps for them to accumulate a tap count.
+ pub multi_tap_slop: Pixels,
+ /// How long a touch must remain within [`Self::touch_slop`] to be
+ /// recognized as a long press.
+ pub long_press_duration: Duration,
+ /// Per-millisecond decay factor applied to scroll momentum after a fling.
+ /// (`UIScrollView` uses `0.998` per millisecond for its normal
+ /// deceleration rate.)
+ pub momentum_decay_per_ms: f32,
+ /// Minimum release velocity, in pixels per second, required to start
+ /// scroll momentum.
+ pub min_fling_velocity: f32,
+}
+
+impl Default for GestureTuning {
+ fn default() -> Self {
+ Self {
+ touch_slop: px(8.),
+ multi_tap_interval: Duration::from_millis(400),
+ multi_tap_slop: px(16.),
+ long_press_duration: Duration::from_millis(500),
+ momentum_decay_per_ms: 0.998,
+ min_fling_velocity: 50.,
+ }
+ }
+}
+
+/// The set of gesture kinds that participate in recognition.
+///
+/// Used by [`PlatformGestures::native_recognizers`] to declare which gestures
+/// the platform recognizes natively rather than leaving to gpui core's
+/// portable recognizers.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct GestureKinds {
+ /// Tap (and multi-tap), surfaced as [`ClickEvent::Touch`](crate::ClickEvent).
+ pub tap: bool,
+ /// Long press, surfaced as [`LongPressEvent`].
+ pub long_press: bool,
+ /// Pan/scroll (including fling momentum), surfaced as
+ /// [`ScrollWheelEvent`](crate::ScrollWheelEvent)s.
+ pub pan: bool,
+ /// Pinch to zoom, surfaced as [`PinchEvent`](crate::PinchEvent)s.
+ pub pinch: bool,
+}
+
+impl GestureKinds {
+ /// No gestures; gpui core's portable recognizers handle everything.
+ pub const NONE: Self = Self {
+ tap: false,
+ long_press: false,
+ pan: false,
+ pinch: false,
+ };
+
+ /// All gesture kinds.
+ pub const ALL: Self = Self {
+ tap: true,
+ long_press: true,
+ pan: true,
+ pinch: true,
+ };
+}
+
+/// A long-press gesture, mobile's context-menu trigger.
+///
+/// A bare long press is surfaced as a [`ClickEvent`](crate::ClickEvent) with
+/// `long_press: true`, delivered to aux-click listeners alongside right
+/// clicks. This event is the raw hook for elements that need the gesture
+/// itself (e.g. long-press to start a drag); the registration API ships
+/// together with the gesture arena.
+#[derive(Clone, Debug, Default)]
+pub struct LongPressEvent {
+ /// The position of the touch that was recognized as a long press.
+ pub position: Point<Pixels>,
+}
+
+/// Platform gesture recognition services.
+///
+/// If your mobile platform supports native gesture recognition, use this
+/// to share it with GPUI.
+pub trait PlatformGestures {
+ /// Feel constants for the portable recognizers on this platform.
+ fn tuning(&self) -> GestureTuning {
+ GestureTuning::default()
+ }
+
+ /// The gesture kinds this platform recognizes natively.
+ fn native_recognizers(&self) -> GestureKinds {
+ GestureKinds::NONE
+ }
+}
+
+/// A no-op [`PlatformGestures`] implementation: no native recognizers and
+/// default tuning. Suitable for desktop platforms and tests.
+pub struct NullPlatformGestures;
+
+impl PlatformGestures for NullPlatformGestures {}
diff --git a/crates/gpui/src/gpui.rs b/crates/gpui/src/gpui.rs
index a81ff265c3e..4b1679cbe44 100644
--- a/crates/gpui/src/gpui.rs
+++ b/crates/gpui/src/gpui.rs
@@ -24,6 +24,7 @@ mod executor;
mod platform_scheduler;
pub(crate) use platform_scheduler::PlatformScheduler;
mod geometry;
+mod gestures;
mod global;
mod input;
mod inspector;
@@ -98,6 +99,7 @@ pub use element::*;
pub use elements::*;
pub use executor::*;
pub use geometry::*;
+pub use gestures::*;
pub use global::*;
pub use gpui_macros::{
AppContext, IntoElement, Render, VisualContext, bench, property_test, register_action, test,
diff --git a/crates/gpui/src/input.rs b/crates/gpui/src/input.rs
index 10ca46501d8..4e204e97880 100644
--- a/crates/gpui/src/input.rs
+++ b/crates/gpui/src/input.rs
@@ -71,6 +71,24 @@ pub trait EntityInputHandler: 'static + Sized {
cx: &mut Context<Self>,
) -> Option<usize>;
+ /// See [`InputHandler::set_selected_text_range`] for details
+ fn set_selected_text_range(
+ &mut self,
+ _range_utf16: Range<usize>,
+ _window: &mut Window,
+ _cx: &mut Context<Self>,
+ ) {
+ }
+
+ /// See [`InputHandler::text_length_utf16`] for details
+ fn text_length_utf16(
+ &mut self,
+ _window: &mut Window,
+ _cx: &mut Context<Self>,
+ ) -> Option<usize> {
+ None
+ }
+
/// See [`InputHandler::accepts_text_input`] for details
fn accepts_text_input(&self, _window: &mut Window, _cx: &mut Context<Self>) -> bool {
true
@@ -183,6 +201,26 @@ impl<V: EntityInputHandler> InputHandler for ElementInputHandler<V> {
})
}
+ fn set_selected_text_range(
+ &mut self,
+ range_utf16: Range<usize>,
+ window: &mut Window,
+ cx: &mut App,
+ ) {
+ self.view.update(cx, |view, cx| {
+ view.set_selected_text_range(range_utf16, window, cx)
+ })
+ }
+
+ fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
+ Some(self.element_bounds)
+ }
+
+ fn text_length_utf16(&mut self, window: &mut Window, cx: &mut App) -> Option<usize> {
+ self.view
+ .update(cx, |view, cx| view.text_length_utf16(window, cx))
+ }
+
fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
self.view
.update(cx, |view, cx| view.accepts_text_input(window, cx))
diff --git a/crates/gpui/src/interactive.rs b/crates/gpui/src/interactive.rs
index 0c7f2f9c97c..1feee49edb0 100644
--- a/crates/gpui/src/interactive.rs
+++ b/crates/gpui/src/interactive.rs
@@ -84,7 +84,7 @@ impl Deref for ModifiersChangedEvent {
/// The phase of a touch motion event.
/// Based on the winit enum of the same name.
-#[derive(Clone, Copy, Debug, Default)]
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TouchPhase {
/// The touch started.
Started,
@@ -93,6 +93,45 @@ pub enum TouchPhase {
Moved,
/// The touch phase has ended
Ended,
+ /// The touch was cancelled: the system took it and it will not end
+ /// normally. Consumers must fully unwind any in-progress interaction,
+ /// treating the touch as if it never committed.
+ Cancelled,
+}
+
+/// Identifies one touch (finger or stylus contact) for its lifetime, from
+/// [`TouchPhase::Started`] through [`TouchPhase::Ended`] or
+/// [`TouchPhase::Cancelled`].
+///
+/// The value is opaque and platform-defined; it is only guaranteed to be
+/// stable for the duration of the touch and unique among concurrent touches.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct TouchId(pub u64);
+
+/// A raw touch event from the platform.
+///
+///
+/// Dispatch contract (core implementation pending): a touch is hit-tested
+/// once, at [`TouchPhase::Started`], occlusion-aware; all subsequent events
+/// for the same [`TouchId`] are delivered to the elements under the starting
+/// position, even after the touch moves outside them.
+#[derive(Clone, Debug, Default)]
+pub struct TouchEvent {
+ /// Which touch this event belongs to.
+ pub id: TouchId,
+ /// The phase of the touch.
+ pub phase: TouchPhase,
+ /// The position of the touch in window coordinates.
+ pub position: Point<Pixels>,
+ /// Normalized touch force in `0.0..=1.0`, if the hardware reports it.
+ pub force: Option<f32>,
+}
+
+impl Sealed for TouchEvent {}
+impl InputEvent for TouchEvent {
+ fn to_platform_input(self) -> PlatformInput {
+ PlatformInput::Touch(self)
+ }
}
/// A mouse down event from the platform
@@ -221,13 +260,31 @@ pub struct KeyboardClickEvent {
pub bounds: Bounds<Pixels>,
}
-/// A click event, generated when a mouse button or keyboard button is pressed and released.
+/// A click event that was generated by a recognized tap gesture on a touch
+/// screen.
+#[derive(Clone, Debug, Default)]
+pub struct TouchClickEvent {
+ /// The position of the tap in window coordinates.
+ pub position: Point<Pixels>,
+ /// The number of consecutive taps at this location (double tap = 2),
+ /// analogous to the mouse `click_count`.
+ pub tap_count: usize,
+ /// Whether this was a long press rather than a tap. Long presses are
+ /// touch's secondary activation: they are delivered to aux-click
+ /// listeners alongside right clicks, not to primary click listeners.
+ pub long_press: bool,
+}
+
+/// A click event, generated when a mouse button or keyboard button is pressed and released,
+/// or when a tap gesture is recognized on a touch screen.
#[derive(Clone, Debug)]
pub enum ClickEvent {
/// A click event trigger by a mouse button being pressed and released.
Mouse(MouseClickEvent),
/// A click event trigger by a keyboard button being pressed and released.
Keyboard(KeyboardClickEvent),
+ /// A click event triggered by a recognized tap gesture on a touch screen.
+ Touch(TouchClickEvent),
}
impl Default for ClickEvent {
@@ -249,6 +306,8 @@ impl ClickEvent {
// tested via observing the behavior of the `ClickEvent.shiftKey` field in Chrome 138
// under various combinations of modifiers and keyUp / keyDown events.
ClickEvent::Mouse(event) => event.up.modifiers,
+ // Touch screens have no modifier keys.
+ ClickEvent::Touch(_) => Modifiers::default(),
}
}
@@ -256,10 +315,12 @@ impl ClickEvent {
///
/// `Keyboard`: The bottom left corner of the clicked hitbox
/// `Mouse`: The position of the mouse when the button was released.
+ /// `Touch`: The position of the tap.
pub fn position(&self) -> Point<Pixels> {
match self {
ClickEvent::Keyboard(event) => event.bounds.bottom_left(),
ClickEvent::Mouse(event) => event.up.position,
+ ClickEvent::Touch(event) => event.position,
}
}
@@ -267,10 +328,12 @@ impl ClickEvent {
///
/// `Keyboard`: None
/// `Mouse`: The position of the mouse when the button was released.
+ /// `Touch`: None, touches are not mouse input and there is no cursor.
pub fn mouse_position(&self) -> Option<Point<Pixels>> {
match self {
ClickEvent::Keyboard(_) => None,
ClickEvent::Mouse(event) => Some(event.up.position),
+ ClickEvent::Touch(_) => None,
}
}
@@ -284,6 +347,7 @@ impl ClickEvent {
ClickEvent::Mouse(event) => {
event.down.button == MouseButton::Right && event.up.button == MouseButton::Right
}
+ ClickEvent::Touch(_) => false,
}
}
@@ -297,6 +361,21 @@ impl ClickEvent {
ClickEvent::Mouse(event) => {
event.down.button == MouseButton::Middle && event.up.button == MouseButton::Middle
}
+ ClickEvent::Touch(_) => false,
+ }
+ }
+
+ /// Returns whether the click is a secondary activation, i.e. a context
+ /// menu trigger: a right click from a mouse (macOS ctrl-clicks arrive
+ /// already converted to right clicks by the platform layer), or a long
+ /// press on a touch screen.
+ pub fn is_secondary(&self) -> bool {
+ match self {
+ ClickEvent::Keyboard(_) => false,
+ ClickEvent::Mouse(event) => {
+ event.down.button == MouseButton::Right && event.up.button == MouseButton::Right
+ }
+ ClickEvent::Touch(event) => event.long_press,
}
}
@@ -304,12 +383,14 @@ impl ClickEvent {
///
/// `Keyboard`: Always true
/// `Mouse`: Left button pressed and released
+ /// `Touch`: A tap, but not a long press
pub fn standard_click(&self) -> bool {
match self {
ClickEvent::Keyboard(_) => true,
ClickEvent::Mouse(event) => {
event.down.button == MouseButton::Left && event.up.button == MouseButton::Left
}
+ ClickEvent::Touch(event) => !event.long_press,
}
}
@@ -317,10 +398,12 @@ impl ClickEvent {
///
/// `Keyboard`: false, keyboard clicks only work if an element is already focused
/// `Mouse`: Whether this was the first focusing click
+ /// `Touch`: false, mobile windows are already active when tappable
pub fn first_focus(&self) -> bool {
match self {
ClickEvent::Keyboard(_) => false,
ClickEvent::Mouse(event) => event.down.first_mouse,
+ ClickEvent::Touch(_) => false,
}
}
@@ -328,17 +411,19 @@ impl ClickEvent {
///
/// `Keyboard`: Always 1
/// `Mouse`: Count of clicks from MouseUpEvent
+ /// `Touch`: Count of consecutive taps
pub fn click_count(&self) -> usize {
match self {
ClickEvent::Keyboard(_) => 1,
ClickEvent::Mouse(event) => event.up.click_count,
+ ClickEvent::Touch(event) => event.tap_count,
}
}
/// Returns whether the click event is generated by a keyboard event
pub fn is_keyboard(&self) -> bool {
match self {
- ClickEvent::Mouse(_) => false,
+ ClickEvent::Mouse(_) | ClickEvent::Touch(_) => false,
ClickEvent::Keyboard(_) => true,
}
}
@@ -670,6 +755,8 @@ pub enum PlatformInput {
Pinch(PinchEvent),
/// Files were dragged and dropped onto the window.
FileDrop(FileDropEvent),
+ /// A raw touch event on a touch screen.
+ Touch(TouchEvent),
}
impl PlatformInput {
@@ -686,6 +773,7 @@ impl PlatformInput {
PlatformInput::ScrollWheel(event) => Some(event),
PlatformInput::Pinch(event) => Some(event),
PlatformInput::FileDrop(event) => Some(event),
+ PlatformInput::Touch(_) => None,
}
}
@@ -702,6 +790,15 @@ impl PlatformInput {
PlatformInput::ScrollWheel(_) => None,
PlatformInput::Pinch(_) => None,
PlatformInput::FileDrop(_) => None,
+ PlatformInput::Touch(_) => None,
+ }
+ }
+
+ /// Returns the touch event contained in this input, if any.
+ pub fn touch_event(&self) -> Option<&TouchEvent> {
+ match self {
+ PlatformInput::Touch(event) => Some(event),
+ _ => None,
}
}
}
diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
index 2a37d0b19b2..52b2f0066a1 100644
--- a/crates/gpui/src/platform.rs
+++ b/crates/gpui/src/platform.rs
@@ -36,11 +36,11 @@ pub(crate) type PlatformScreenCaptureFrame = core_video::image_buffer::CVImageBu
use crate::{
Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
- DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun,
- ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap, LineLayout, Pixels,
- PlatformInput, Point, Priority, RenderGlyphParams, RenderImage, RenderImageParams,
- RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString, Size, SvgRenderer,
- SystemWindowTab, Task, Window, WindowControlArea, hash, point, px, size,
+ DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Edges, Font, FontId, FontMetrics,
+ FontRun, ForegroundExecutor, GlyphId, GpuSpecs, Hsla, ImageSource, Keymap, LineLayout, Pixels,
+ PlatformGestures, PlatformInput, Point, Priority, RenderGlyphParams, RenderImage,
+ RenderImageParams, RenderSvgParams, Scene, ShapedGlyph, ShapedRun, SharedString, Size,
+ SvgRenderer, SystemWindowTab, Task, Window, WindowControlArea, hash, point, px, size,
};
use anyhow::Result;
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
@@ -193,6 +193,30 @@ pub trait Platform: 'static {
fn on_reopen(&self, callback: Box<dyn FnMut()>);
fn on_system_wake(&self, callback: Box<dyn FnMut()>);
+ // Mobile platform methods. On mobile the OS owns the application
+ // lifecycle: apps are backgrounded, foregrounded, and killed at the
+ // system's discretion, and must react rather than decide.
+
+ /// Registers a callback invoked whenever the application's lifecycle
+ /// phase changes. See [`AppLifecyclePhase`] for the phase vocabulary and
+ /// its mapping onto iOS and Android.
+ ///
+ /// Desktop platforms never invoke this.
+ fn on_app_lifecycle(&self, _callback: Box<dyn FnMut(AppLifecyclePhase)>) {}
+
+ /// Registers a callback invoked when the OS signals memory pressure
+ /// (iOS `didReceiveMemoryWarning`, Android `onTrimMemory`).
+ ///
+ /// Desktop platforms never invoke this.
+ fn on_memory_warning(&self, _callback: Box<dyn FnMut()>) {}
+
+ /// The platform's gesture recognition services, if it provides any
+ /// beyond gpui's portable recognizers. See
+ /// [`PlatformGestures`](crate::PlatformGestures).
+ fn gestures(&self) -> Option<Rc<dyn PlatformGestures>> {
+ None
+ }
+
fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
None
@@ -620,6 +644,75 @@ pub struct RequestFrameOptions {
pub force_render: bool,
}
+/// The application's lifecycle phase, as owned and reported by a mobile OS.
+///
+/// `Inactive` means visible but not receiving input (a system dialog on
+/// top), while `Background` means not visible at all, with process death
+/// possible at any time thereafter.
+///
+/// | Phase | iOS | Android |
+/// |--------------|------------------------------|--------------|
+/// | `Active` | `didBecomeActive` | `onResume` |
+/// | `Inactive` | `willResignActive` | `onPause` |
+/// | `Background` | `didEnterBackground` | `onStop` |
+/// | `Foreground` | `willEnterForeground` | `onStart` |
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
+pub enum AppLifecyclePhase {
+ /// Foreground and receiving input.
+ Active,
+ /// Foreground (visible) but not receiving input.
+ Inactive,
+ /// Not visible. The GPU surface may be destroyed while backgrounded and
+ /// the process may be killed without further notice.
+ Background,
+ /// Becoming visible again, before input is restored.
+ Foreground,
+}
+
+/// Regions of a window that are obscured or reserved by the system.
+///
+/// Mobile applications often share space in their window with system-specific
+/// geometry, from keyboards to camera notches. In GPUI, all this is abstracted
+/// into a single "inset" which should be overlaid on the window's bounds.
+/// It is up to the application develop to determine how to handle these cases.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct WindowInsets {
+ /// Regions covered by system UI or hardware: status bar, display
+ /// cutouts/notch, home indicator, navigation bars.
+ /// (iOS: `safeAreaInsets`. Android: `WindowInsets` of types
+ /// `systemBars() | displayCutout()`.)
+ pub safe_area: Edges<Pixels>,
+ /// The region covered by the keyboard, when present.
+ /// (iOS: derived from `keyboardWillShow`/frame-change notifications.
+ /// Android: `WindowInsets.Type.ime()`.)
+ pub ime: Edges<Pixels>,
+}
+
+impl WindowInsets {
+ /// The combined inset content should avoid.
+ pub fn effective(&self) -> Edges<Pixels> {
+ Edges {
+ top: self.safe_area.top.max(self.ime.top),
+ right: self.safe_area.right.max(self.ime.right),
+ bottom: self.safe_area.bottom.max(self.ime.bottom),
+ left: self.safe_area.left.max(self.ime.left),
+ }
+ }
+}
+
+/// A change in the state of the focused text input.
+#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
+pub enum TextInputStateChange {
+ /// An editable element gained focus.
+ FocusGained,
+ /// The focused editable element lost focus.
+ FocusLost,
+ /// The selection or caret moved
+ SelectionChanged,
+ /// The document content changed outside of platform-initiated edits.
+ ContentChanged,
+}
+
#[expect(missing_docs)]
pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
fn bounds(&self) -> Bounds<Pixels>;
@@ -721,6 +814,38 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
fn update_ime_position(&self, _bounds: Bounds<Pixels>);
+ // Mobile platform methods.
+
+ /// The regions of this window currently obscured or reserved by the
+ /// system. Zero on platforms without such regions.
+ fn insets(&self) -> WindowInsets {
+ WindowInsets::default()
+ }
+
+ /// Registers a callback invoked whenever [`Self::insets`] change.
+ ///
+ /// Contract: fires continuously during animated transitions (Android
+ /// `WindowInsetsAnimation` progress; on iOS the platform interpolates
+ /// the keyboard animation curve on frame ticks) and is exact at rest.
+ fn on_insets_changed(&self, _callback: Box<dyn FnMut(WindowInsets)>) {}
+
+ /// Sets the handler for the system back action (Android back
+ /// button/gesture; no source on iOS or desktop).
+ fn set_back_handler(&self, _callback: Box<dyn FnMut()>) {}
+
+ /// Declares whether the application would currently handle the system
+ /// back action (e.g. navigation depth > 0).
+ fn set_back_enabled(&self, _enabled: bool) {}
+
+ /// Requests that the soft keyboard be shown.
+ fn show_soft_keyboard(&self) {}
+
+ /// Requests that the soft keyboard be hidden.
+ fn hide_soft_keyboard(&self) {}
+
+ /// Inform the operating system that the text input state has changed
+ fn text_input_state_changed(&self, _change: TextInputStateChange) {}
+
fn play_system_bell(&self) {}
/// Initialize the accessibility adapter with callbacks.
@@ -1334,6 +1459,32 @@ impl PlatformInputHandler {
.flatten()
}
+ /// See [`InputHandler::set_selected_text_range`].
+ pub fn set_selected_text_range(&mut self, range_utf16: Range<usize>) {
+ self.cx
+ .update(|window, cx| {
+ self.handler
+ .set_selected_text_range(range_utf16, window, cx)
+ })
+ .ok();
+ }
+
+ /// See [`InputHandler::element_bounds`].
+ pub fn element_bounds(&mut self) -> Option<Bounds<Pixels>> {
+ self.cx
+ .update(|window, cx| self.handler.element_bounds(window, cx))
+ .ok()
+ .flatten()
+ }
+
+ /// See [`InputHandler::text_length_utf16`].
+ pub fn text_length_utf16(&mut self) -> Option<usize> {
+ self.cx
+ .update(|window, cx| self.handler.text_length_utf16(window, cx))
+ .ok()
+ .flatten()
+ }
+
#[allow(dead_code)]
pub fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
self.handler.accepts_text_input(window, cx)
@@ -1452,6 +1603,38 @@ pub trait InputHandler: 'static {
cx: &mut App,
) -> Option<usize>;
+ /// Set the range of the user's currently selected text.
+ ///
+ /// This is the reverse data-flow direction from [`Self::selected_text_range`]:
+ /// platforms call it when the system text machinery moves the selection on the
+ /// application's behalf — e.g. the user drags a system selection handle or
+ /// invokes Select All from system UI (iOS `UITextInput setSelectedTextRange:`,
+ /// Android `InputConnection.setSelection`).
+ ///
+ /// range_utf16 is in terms of UTF-16 characters, from 0 to the length of the document
+ fn set_selected_text_range(
+ &mut self,
+ _range_utf16: Range<usize>,
+ _window: &mut Window,
+ _cx: &mut App,
+ ) {
+ }
+
+ /// Get the bounds of the focused text element in window coordinates, if known.
+ ///
+ /// This is the pull counterpart to the [`PlatformWindow::update_ime_position`]
+ /// push: mobile platforms ask for the focused element's geometry when they
+ /// need it (e.g. to frame system text-interaction UI overlaid on the focused
+ /// element).
+ fn element_bounds(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Bounds<Pixels>> {
+ None
+ }
+
+ /// Get the length of the document in UTF-16 characters, if known.
+ fn text_length_utf16(&mut self, _window: &mut Window, _cx: &mut App) -> Option<usize> {
+ None
+ }
+
/// Allows a given input context to opt into getting raw key repeats instead of
/// sending these to the platform.
/// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 7059cf863a6..11a3fb4d9ad 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -982,6 +982,7 @@ impl Frame {
enum InputModality {
Mouse,
Keyboard,
+ Touch,
}
/// Holds the state for a specific window.
@@ -4541,6 +4542,7 @@ impl Window {
self.last_input_modality = match &event {
PlatformInput::KeyDown(_) => InputModality::Keyboard,
PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
+ PlatformInput::Touch(_) => InputModality::Touch,
_ => self.last_input_modality,
};
if self.last_input_modality != old_modality {
@@ -4634,6 +4636,7 @@ impl Window {
PlatformInput::FileDrop(FileDropEvent::Exited)
}
},
+ PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
};
diff --git a/crates/terminal/src/terminal.rs b/crates/terminal/src/terminal.rs
index 8d0521d3975..a1e1c1c937e 100644
--- a/crates/terminal/src/terminal.rs
+++ b/crates/terminal/src/terminal.rs
@@ -2675,7 +2675,8 @@ impl Terminal {
Some(new_offset - old_offset)
}
- TouchPhase::Ended => None,
+ // Cancellation does not commit a scroll, same as a plain end.
+ TouchPhase::Ended | TouchPhase::Cancelled => None,
}
}