Skip to main content

tilo_presentation/
text_input.rs

1//! Optional original-field acknowledgements beside standard native IME delivery:
2//! no transcript, and no microphone or input ownership. A field's purpose, its
3//! keyed fingerprint, its editing history's status, and the receipts of edits a
4//! host defers to a field's original owner are named here, so a toolkit and an
5//! engine share them.
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Mutex};
8
9use tilo_clock::time::{Duration, Instant};
10use tilo_lock::MutexRecover as _;
11use winit::window::Window;
12
13pub fn set_content_type(window: &Window, hint: u32, purpose: u32) {
14    #[cfg(target_os = "linux")]
15    {
16        use winit::platform::wayland::WindowExtWayland;
17        window.set_ime_content_type(Some(winit::platform::wayland::ImeContentType {
18            hint,
19            purpose,
20        }));
21    }
22    #[cfg(not(target_os = "linux"))]
23    let _ = (window, hint, purpose);
24}
25
26pub fn publish(window: &Window, snapshot: Option<[u8; 32]>) -> bool {
27    #[cfg(target_os = "linux")]
28    {
29        use winit::platform::wayland::WindowExtWayland;
30        window.private_text_input(snapshot)
31    }
32    #[cfg(not(target_os = "linux"))]
33    {
34        let _ = (window, snapshot);
35        false
36    }
37}
38
39pub fn acknowledge(window: &Window, serial: u32, outcome: u32) {
40    #[cfg(target_os = "linux")]
41    {
42        use winit::platform::wayland::WindowExtWayland;
43        window.acknowledge_private_text_input(serial, outcome);
44    }
45    #[cfg(not(target_os = "linux"))]
46    let _ = (window, serial, outcome);
47}
48
49/// What a field holds, for an input method to pick its layout: an email field gets `@`, a
50/// phone field the dial pad, a PIN the digit pad.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
52pub enum InputPurpose {
53    /// Free text.
54    #[default]
55    Text,
56    /// A person's name.
57    Name,
58    Search,
59    Email,
60    Url,
61    /// A number, with sign and decimal separator.
62    Number,
63    /// A number with a fractional part.
64    Decimal,
65    Phone,
66    /// Digits only, such as a pairing passkey.
67    Pin,
68    /// A code sent to the person to confirm a sign-in.
69    OneTimeCode,
70    Password,
71    Date,
72    Time,
73    /// A terminal, whose keyboard wants the extra keys.
74    Terminal,
75}
76
77/// Keyed, ephemeral equality check for a field's text and selection. This is invalidation
78/// metadata, never a persisted text hash or insertion authority.
79#[must_use]
80pub fn edit_fingerprint(text: &str, anchor: usize, focus: usize, key: &[u8; 32]) -> [u8; 32] {
81    let mut hash = blake3::Hasher::new_keyed(key);
82    hash.update(&anchor.to_le_bytes());
83    hash.update(&focus.to_le_bytes());
84    hash.update(text.as_bytes());
85    *hash.finalize().as_bytes()
86}
87
88/// What the live editing history of a page can do right now, as its engine reports it.
89#[derive(Clone, Debug, Default, PartialEq, Eq)]
90pub struct UndoStatus {
91    pub can_undo: bool,
92    pub can_redo: bool,
93    pub undo_summary: Option<String>,
94    pub redo_summary: Option<String>,
95}
96
97impl UndoStatus {
98    /// The status of a history in which nothing has happened yet.
99    #[must_use]
100    pub fn empty() -> Self {
101        Self::default()
102    }
103
104    /// Whether the verb `which` is available.
105    #[must_use]
106    pub fn can(&self, which: UndoRequest) -> bool {
107        match which {
108            UndoRequest::Undo => self.can_undo,
109            UndoRequest::Redo => self.can_redo,
110        }
111    }
112
113    #[must_use]
114    pub fn summary(&self, which: UndoRequest) -> Option<&str> {
115        match which {
116            UndoRequest::Undo => self.undo_summary.as_deref(),
117            UndoRequest::Redo => self.redo_summary.as_deref(),
118        }
119    }
120
121    /// The sentence an assistive technology should hear as the control's *description*:
122    /// what the verb would do, or the reason it is unavailable. `"Nothing to undo"` when
123    /// unavailable — never a description of an action that is not there.
124    #[must_use]
125    pub fn description(&self, which: UndoRequest) -> String {
126        if !self.can(which) {
127            return format!("Nothing to {}", which.verb());
128        }
129        match self.summary(which) {
130            Some(s) => format!("{}: {s}", which.title()),
131            None => which.title().to_string(),
132        }
133    }
134}
135
136/// A request that the host drive an editing history. The host performs it through the one
137/// undo implementation; a control never touches the stacks.
138#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
139#[serde(rename_all = "snake_case")]
140pub enum UndoRequest {
141    Undo,
142    Redo,
143}
144
145impl UndoRequest {
146    /// Lower-case verb, for composed sentences (`"Nothing to undo"`).
147    #[must_use]
148    pub fn verb(self) -> &'static str {
149        match self {
150            Self::Undo => "undo",
151            Self::Redo => "redo",
152        }
153    }
154
155    /// Title-case label, for a control's accessible name.
156    #[must_use]
157    pub fn title(self) -> &'static str {
158        match self {
159            Self::Undo => "Undo",
160            Self::Redo => "Redo",
161        }
162    }
163
164    /// The keyboard shortcut the host binds to this verb, for a tooltip — so the control
165    /// teaches the shortcut rather than replacing it.
166    #[must_use]
167    pub fn shortcut(self) -> &'static str {
168        match self {
169            Self::Undo => "Ctrl+Z",
170            Self::Redo => "Ctrl+Shift+Z",
171        }
172    }
173}
174
175#[derive(Clone, PartialEq, Eq)]
176pub struct Lease(String, bool);
177
178impl Lease {
179    /// The lease a reply names: 32 lowercase hex digits, single-line unless its multiline
180    /// flag says otherwise.
181    #[must_use]
182    pub fn parse(value: &str) -> Option<Self> {
183        (value.len() == 32
184            && value
185                .bytes()
186                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
187        .then(|| Self(value.into(), false))
188    }
189
190    /// The lease's own 32 hex digits, as a request names it.
191    #[must_use]
192    pub fn as_str(&self) -> &str {
193        &self.0
194    }
195
196    /// Whether the field this lease names takes more than one line.
197    #[must_use]
198    pub fn multiline(&self) -> bool {
199        self.1
200    }
201
202    pub fn set_multiline(&mut self, multiline: bool) {
203        self.1 = multiline;
204    }
205
206    /// The keyed fingerprint of this lease, which changes when its field does.
207    #[must_use]
208    pub fn stamp(&self, key: &[u8; 32]) -> [u8; 32] {
209        edit_fingerprint(&self.0, usize::from(self.1), 0, key)
210    }
211}
212
213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
214pub enum Failure {
215    Busy,
216    Retired,
217    Rejected,
218    Unknown,
219}
220
221/// How a deferred edit ended: the lease it was granted, if any, or why it failed.
222pub type Outcome = Result<Option<Lease>, Failure>;
223
224/// A local receipt shared with the original caller, independent of widget lifetime.
225#[derive(Clone)]
226pub struct Receipt {
227    result: Arc<Mutex<Option<Outcome>>>,
228    canceled: Arc<AtomicBool>,
229    history: Arc<Mutex<Option<(UndoStatus, Instant)>>>,
230    deadline: Instant,
231}
232
233/// The original host's one-shot completion end. Completing it grants no input authority;
234/// the host must first bind delivery to its original field owner.
235pub struct Resolver(Receipt);
236impl Resolver {
237    pub fn complete(self, result: Result<Option<Lease>, Failure>) {
238        self.0.complete(result);
239    }
240}
241
242impl Receipt {
243    /// A bounded private host receipt and its one-shot completion end.
244    pub fn channel() -> (Self, Resolver) {
245        let receipt = Self::pending();
246        (receipt.clone(), Resolver(receipt))
247    }
248
249    /// Observe cancellation of this exact scope, including after start ACK.
250    pub fn was_canceled(&self) -> bool {
251        self.is_canceled()
252    }
253    /// A receipt nothing has completed yet.
254    #[must_use]
255    #[allow(
256        clippy::arithmetic_side_effects,
257        reason = "ten seconds past a monotonic reading cannot overflow an Instant"
258    )]
259    pub fn pending() -> Self {
260        Self {
261            result: Arc::new(Mutex::new(None)),
262            canceled: Arc::new(AtomicBool::new(false)),
263            history: Arc::new(Mutex::new(None)),
264            deadline: tilo_clock::now() + Duration::from_secs(10),
265        }
266    }
267
268    /// What the field's editing history could do when the engine last said, until that
269    /// observation expires or the receipt is canceled.
270    #[must_use]
271    pub fn history_status(&self) -> Option<UndoStatus> {
272        let (status, expires) = self.history.lock().ok()?.clone()?;
273        (tilo_clock::now() < expires && !self.is_canceled()).then_some(status)
274    }
275
276    pub fn failed(failure: Failure) -> Self {
277        let receipt = Self::pending();
278        receipt.complete(Err(failure));
279        receipt
280    }
281
282    pub fn poll(&self) -> Option<Result<Option<Lease>, Failure>> {
283        let mut result = self.result.lock_recover();
284        if result.is_none() && tilo_clock::now() >= self.deadline {
285            *result = Some(Err(Failure::Unknown));
286        }
287        result.clone()
288    }
289
290    /// Stop a final that has not been admitted. After admission its outcome is uncertain
291    /// until the original native reply; never synthesize an undo.
292    pub fn cancel(&self) {
293        self.canceled.store(true, Ordering::Release);
294        self.complete(Err(Failure::Unknown));
295    }
296
297    /// Keep the engine's observation of the field's editing history until `expires`.
298    pub fn record_history(&self, status: UndoStatus, expires: Instant) {
299        *self.history.lock_recover() = Some((status, expires));
300    }
301
302    fn is_canceled(&self) -> bool {
303        self.canceled.load(Ordering::Acquire)
304    }
305
306    /// Complete a receipt once; a later completion is ignored.
307    pub fn complete(&self, value: Result<Option<Lease>, Failure>) {
308        let mut result = self.result.lock_recover();
309        if result.is_none() {
310            *result = Some(value);
311        }
312    }
313}