use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
pub type WindowToken = u64;
thread_local! {
static ACTIVE: Cell<WindowToken> = const { Cell::new(0) };
}
pub fn set_active_window(token: WindowToken) {
ACTIVE.with(|active| active.set(token));
}
pub fn active_window() -> WindowToken {
ACTIVE.with(Cell::get)
}
static CURRENT_WINDOW: AtomicU64 = AtomicU64::new(0);
pub fn set_current_window_token(token: WindowToken) {
CURRENT_WINDOW.store(token, Ordering::Relaxed);
}
pub fn current_window_token() -> Option<WindowToken> {
let token = CURRENT_WINDOW.load(Ordering::Relaxed);
(token != 0).then_some(token)
}
static MAXIMIZED: AtomicBool = AtomicBool::new(false);
pub fn set_maximized(value: bool) {
MAXIMIZED.store(value, Ordering::Relaxed);
}
pub fn is_maximized() -> bool {
MAXIMIZED.load(Ordering::Relaxed)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WindowCommand {
Close,
Minimize,
Maximize,
Restore,
ToggleMaximize,
Show,
Hide,
OpenModal,
OpenWindow,
Open(String),
CloseWindow(String),
ShowWindow(String),
HideWindow(String),
}
type Sender = Box<dyn FnMut(WindowToken, WindowCommand) + Send + 'static>;
static SENDER: OnceLock<Mutex<Sender>> = OnceLock::new();
pub fn set_command_sender(sender: impl FnMut(WindowToken, WindowCommand) + Send + 'static) {
let _ = SENDER.set(Mutex::new(Box::new(sender)));
}
pub fn request(command: WindowCommand) {
if let Some(sender) = SENDER.get()
&& let Ok(mut sender) = sender.lock()
{
let token = ACTIVE.with(Cell::get);
sender(token, command);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FocusCommand {
Focus(String),
Blur,
}
thread_local! {
static FOCUS_COMMAND: RefCell<Option<FocusCommand>> = const { RefCell::new(None) };
static FOCUSED_KEY: RefCell<Option<String>> = const { RefCell::new(None) };
}
pub fn focus(key: impl Into<String>) {
FOCUS_COMMAND.with(|slot| *slot.borrow_mut() = Some(FocusCommand::Focus(key.into())));
}
pub fn blur() {
FOCUS_COMMAND.with(|slot| *slot.borrow_mut() = Some(FocusCommand::Blur));
}
pub fn focused_key() -> Option<String> {
FOCUSED_KEY.with(|key| key.borrow().clone())
}
pub fn take_focus_command() -> Option<FocusCommand> {
FOCUS_COMMAND.with(|slot| slot.borrow_mut().take())
}
pub fn set_focused_key(key: Option<String>) {
FOCUSED_KEY.with(|slot| *slot.borrow_mut() = key);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn focus_request_round_trips() {
set_focused_key(None);
assert_eq!(focused_key(), None);
assert_eq!(take_focus_command(), None);
focus("field");
assert_eq!(
take_focus_command(),
Some(FocusCommand::Focus("field".into()))
);
assert_eq!(take_focus_command(), None, "запрос потребляется один раз");
blur();
assert_eq!(take_focus_command(), Some(FocusCommand::Blur));
set_focused_key(Some("field".into()));
assert_eq!(focused_key().as_deref(), Some("field"));
set_focused_key(None);
}
}