use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use tilo_clock::time::{Duration, Instant};
use tilo_lock::MutexRecover as _;
use winit::window::Window;
pub fn set_content_type(window: &Window, hint: u32, purpose: u32) {
#[cfg(target_os = "linux")]
{
use winit::platform::wayland::WindowExtWayland;
window.set_ime_content_type(Some(winit::platform::wayland::ImeContentType {
hint,
purpose,
}));
}
#[cfg(not(target_os = "linux"))]
let _ = (window, hint, purpose);
}
pub fn publish(window: &Window, snapshot: Option<[u8; 32]>) -> bool {
#[cfg(target_os = "linux")]
{
use winit::platform::wayland::WindowExtWayland;
window.private_text_input(snapshot)
}
#[cfg(not(target_os = "linux"))]
{
let _ = (window, snapshot);
false
}
}
pub fn acknowledge(window: &Window, serial: u32, outcome: u32) {
#[cfg(target_os = "linux")]
{
use winit::platform::wayland::WindowExtWayland;
window.acknowledge_private_text_input(serial, outcome);
}
#[cfg(not(target_os = "linux"))]
let _ = (window, serial, outcome);
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum InputPurpose {
#[default]
Text,
Name,
Search,
Email,
Url,
Number,
Decimal,
Phone,
Pin,
OneTimeCode,
Password,
Date,
Time,
Terminal,
}
#[must_use]
pub fn edit_fingerprint(text: &str, anchor: usize, focus: usize, key: &[u8; 32]) -> [u8; 32] {
let mut hash = blake3::Hasher::new_keyed(key);
hash.update(&anchor.to_le_bytes());
hash.update(&focus.to_le_bytes());
hash.update(text.as_bytes());
*hash.finalize().as_bytes()
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct UndoStatus {
pub can_undo: bool,
pub can_redo: bool,
pub undo_summary: Option<String>,
pub redo_summary: Option<String>,
}
impl UndoStatus {
#[must_use]
pub fn empty() -> Self {
Self::default()
}
#[must_use]
pub fn can(&self, which: UndoRequest) -> bool {
match which {
UndoRequest::Undo => self.can_undo,
UndoRequest::Redo => self.can_redo,
}
}
#[must_use]
pub fn summary(&self, which: UndoRequest) -> Option<&str> {
match which {
UndoRequest::Undo => self.undo_summary.as_deref(),
UndoRequest::Redo => self.redo_summary.as_deref(),
}
}
#[must_use]
pub fn description(&self, which: UndoRequest) -> String {
if !self.can(which) {
return format!("Nothing to {}", which.verb());
}
match self.summary(which) {
Some(s) => format!("{}: {s}", which.title()),
None => which.title().to_string(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UndoRequest {
Undo,
Redo,
}
impl UndoRequest {
#[must_use]
pub fn verb(self) -> &'static str {
match self {
Self::Undo => "undo",
Self::Redo => "redo",
}
}
#[must_use]
pub fn title(self) -> &'static str {
match self {
Self::Undo => "Undo",
Self::Redo => "Redo",
}
}
#[must_use]
pub fn shortcut(self) -> &'static str {
match self {
Self::Undo => "Ctrl+Z",
Self::Redo => "Ctrl+Shift+Z",
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Lease(String, bool);
impl Lease {
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
(value.len() == 32
&& value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
.then(|| Self(value.into(), false))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn multiline(&self) -> bool {
self.1
}
pub fn set_multiline(&mut self, multiline: bool) {
self.1 = multiline;
}
#[must_use]
pub fn stamp(&self, key: &[u8; 32]) -> [u8; 32] {
edit_fingerprint(&self.0, usize::from(self.1), 0, key)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Failure {
Busy,
Retired,
Rejected,
Unknown,
}
pub type Outcome = Result<Option<Lease>, Failure>;
#[derive(Clone)]
pub struct Receipt {
result: Arc<Mutex<Option<Outcome>>>,
canceled: Arc<AtomicBool>,
history: Arc<Mutex<Option<(UndoStatus, Instant)>>>,
deadline: Instant,
}
pub struct Resolver(Receipt);
impl Resolver {
pub fn complete(self, result: Result<Option<Lease>, Failure>) {
self.0.complete(result);
}
}
impl Receipt {
pub fn channel() -> (Self, Resolver) {
let receipt = Self::pending();
(receipt.clone(), Resolver(receipt))
}
pub fn was_canceled(&self) -> bool {
self.is_canceled()
}
#[must_use]
#[allow(
clippy::arithmetic_side_effects,
reason = "ten seconds past a monotonic reading cannot overflow an Instant"
)]
pub fn pending() -> Self {
Self {
result: Arc::new(Mutex::new(None)),
canceled: Arc::new(AtomicBool::new(false)),
history: Arc::new(Mutex::new(None)),
deadline: tilo_clock::now() + Duration::from_secs(10),
}
}
#[must_use]
pub fn history_status(&self) -> Option<UndoStatus> {
let (status, expires) = self.history.lock().ok()?.clone()?;
(tilo_clock::now() < expires && !self.is_canceled()).then_some(status)
}
pub fn failed(failure: Failure) -> Self {
let receipt = Self::pending();
receipt.complete(Err(failure));
receipt
}
pub fn poll(&self) -> Option<Result<Option<Lease>, Failure>> {
let mut result = self.result.lock_recover();
if result.is_none() && tilo_clock::now() >= self.deadline {
*result = Some(Err(Failure::Unknown));
}
result.clone()
}
pub fn cancel(&self) {
self.canceled.store(true, Ordering::Release);
self.complete(Err(Failure::Unknown));
}
pub fn record_history(&self, status: UndoStatus, expires: Instant) {
*self.history.lock_recover() = Some((status, expires));
}
fn is_canceled(&self) -> bool {
self.canceled.load(Ordering::Acquire)
}
pub fn complete(&self, value: Result<Option<Lease>, Failure>) {
let mut result = self.result.lock_recover();
if result.is_none() {
*result = Some(value);
}
}
}