1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
52pub enum InputPurpose {
53 #[default]
55 Text,
56 Name,
58 Search,
59 Email,
60 Url,
61 Number,
63 Decimal,
65 Phone,
66 Pin,
68 OneTimeCode,
70 Password,
71 Date,
72 Time,
73 Terminal,
75}
76
77#[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#[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 #[must_use]
100 pub fn empty() -> Self {
101 Self::default()
102 }
103
104 #[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 #[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#[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 #[must_use]
148 pub fn verb(self) -> &'static str {
149 match self {
150 Self::Undo => "undo",
151 Self::Redo => "redo",
152 }
153 }
154
155 #[must_use]
157 pub fn title(self) -> &'static str {
158 match self {
159 Self::Undo => "Undo",
160 Self::Redo => "Redo",
161 }
162 }
163
164 #[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 #[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 #[must_use]
192 pub fn as_str(&self) -> &str {
193 &self.0
194 }
195
196 #[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 #[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
221pub type Outcome = Result<Option<Lease>, Failure>;
223
224#[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
233pub 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 pub fn channel() -> (Self, Resolver) {
245 let receipt = Self::pending();
246 (receipt.clone(), Resolver(receipt))
247 }
248
249 pub fn was_canceled(&self) -> bool {
251 self.is_canceled()
252 }
253 #[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 #[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 pub fn cancel(&self) {
293 self.canceled.store(true, Ordering::Release);
294 self.complete(Err(Failure::Unknown));
295 }
296
297 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 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}