Skip to main content

cranpose_ui/
text_input_session.rs

1//! Platform text-input session: soft-keyboard visibility hooks.
2//!
3//! Platforms with an on-screen keyboard (Android, iOS, some Linux shells)
4//! install a [`PlatformTextInputHandler`] so the framework can tell them when
5//! editable text gains or loses focus. The text-field focus manager
6//! ([`crate::text_field_focus`]) fires these notifications:
7//!
8//! - a text field acquired focus → `notify_text_input_focus_gained` →
9//!   `show_keyboard`
10//! - focus was explicitly cleared, or the focused field left the composition →
11//!   `notify_text_input_focus_lost` → `hide_keyboard`
12//!
13//! `show_keyboard` fires on *every* focus request, including taps on an
14//! already-focused field. This is intentional: the user may have dismissed the
15//! keyboard (e.g. Android back gesture) without the framework knowing, and
16//! tapping the field again must bring it back. Platform show/hide calls are
17//! expected to be idempotent. `hide_keyboard` is only forwarded when the
18//! framework previously requested the keyboard, so repeated stale-focus checks
19//! do not spam the platform.
20//!
21//! The handler is stored per [`AppContext`](crate::render_state::AppContext),
22//! like the focus state itself, so multiple app instances in one process do
23//! not observe each other's keyboards.
24
25use std::{
26    cell::{Cell, RefCell},
27    rc::Rc,
28};
29
30/// Callbacks a platform installs to control its on-screen keyboard.
31///
32/// Implementations must be idempotent: `show_keyboard` may be invoked while
33/// the keyboard is already visible (every tap on a text field re-requests it)
34/// and `hide_keyboard` may race a keyboard the user already dismissed.
35pub trait PlatformTextInputHandler {
36    /// A text field gained focus; the platform should show its soft keyboard.
37    fn show_keyboard(&self);
38    /// No text field is focused anymore; the platform should hide its soft
39    /// keyboard.
40    fn hide_keyboard(&self);
41}
42
43pub(crate) struct PlatformTextInputState {
44    handler: RefCell<Option<Rc<dyn PlatformTextInputHandler>>>,
45    keyboard_requested: Cell<bool>,
46}
47
48impl PlatformTextInputState {
49    pub(crate) fn new() -> Self {
50        Self {
51            handler: RefCell::new(None),
52            keyboard_requested: Cell::new(false),
53        }
54    }
55
56    fn set_handler(&self, handler: Option<Rc<dyn PlatformTextInputHandler>>) {
57        *self.handler.borrow_mut() = handler;
58        self.keyboard_requested.set(false);
59    }
60
61    fn handler(&self) -> Option<Rc<dyn PlatformTextInputHandler>> {
62        self.handler.borrow().clone()
63    }
64}
65
66/// Installs the platform soft-keyboard handler for the current app context.
67///
68/// Replaces any previously installed handler. Must be called inside an app
69/// context (platform runtimes go through
70/// `AppShell::set_platform_text_input`).
71pub fn set_platform_text_input_handler(handler: Rc<dyn PlatformTextInputHandler>) {
72    crate::render_state::with_text_input_session(|state| state.set_handler(Some(handler)));
73}
74
75/// Removes the installed platform soft-keyboard handler, if any.
76pub fn clear_platform_text_input_handler() {
77    crate::render_state::with_text_input_session(|state| state.set_handler(None));
78}
79
80pub(crate) fn notify_text_input_focus_gained() {
81    let handler = crate::render_state::with_text_input_session(|state| {
82        let handler = state.handler();
83        if handler.is_some() {
84            state.keyboard_requested.set(true);
85        }
86        handler
87    });
88    if let Some(handler) = handler {
89        handler.show_keyboard();
90    }
91}
92
93pub(crate) fn notify_text_input_focus_lost() {
94    let handler = crate::render_state::with_text_input_session(|state| {
95        if !state.keyboard_requested.replace(false) {
96            return None;
97        }
98        state.handler()
99    });
100    if let Some(handler) = handler {
101        handler.hide_keyboard();
102    }
103}
104
105/// Notifies the framework that the host app was paused (backgrounded — e.g.
106/// Android `onPause`).
107///
108/// Any outstanding soft-keyboard request is withdrawn and the platform is told
109/// to hide its keyboard, clearing the "keyboard shown" state so it cannot
110/// survive into the next resume. Without this, a platform that remembers the
111/// last editor view (Android's `InputMethodManager`) re-shows the keyboard when
112/// the app returns to the foreground even though the framework no longer has a
113/// focused field. Gated on an outstanding request, so it is a no-op when the
114/// keyboard was not showing.
115pub fn notify_app_paused() {
116    notify_text_input_focus_lost();
117}
118
119/// Notifies the framework that the host app resumed (foregrounded — e.g.
120/// Android `onResume`).
121///
122/// The soft keyboard is **never** auto-shown on resume, even when a text field
123/// is still focused. A warm resume (return from HOME / task switch / back-exit
124/// then relaunch) restores the process with the field's focus and caret intact,
125/// but the framework must not resurrect the keyboard for it: the platform's
126/// `InputMethodManager` remembers the last editor and would otherwise pop the
127/// keyboard back open on its own. The user brings it back by tapping the field
128/// (which re-requests it through `notify_text_input_focus_gained`).
129///
130/// Always returns `false` so the platform runtime force-hides the OS-restored
131/// keyboard. Pruning stale focus here keeps the keyboard-request bookkeeping
132/// consistent (a focused-but-detached field is dropped and its outstanding
133/// request withdrawn) without ever calling `show`.
134pub fn notify_app_resumed() -> bool {
135    let _ = crate::text_field_focus::has_focused_field();
136    false
137}
138
139#[cfg(test)]
140#[path = "tests/text_input_session_tests.rs"]
141mod tests;