use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use futures::channel::mpsc;
use futures::stream::StreamExt;
use iced_core::{Event, event, window};
use iced_program::futures::BoxStream;
use iced_program::futures::subscription;
#[derive(Debug, Default)]
pub struct KeyHub {
listeners: Mutex<Vec<mpsc::UnboundedSender<subscription::Event>>>,
}
static HUB: OnceLock<Arc<KeyHub>> = OnceLock::new();
impl KeyHub {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn global() -> Arc<Self> {
Arc::clone(HUB.get_or_init(Arc::default))
}
#[must_use = "the stream only hears keys while it is kept and polled"]
pub fn subscribe(&self) -> BoxStream<subscription::Event> {
let (sender, receiver) = mpsc::unbounded();
self.lock().push(sender);
receiver.boxed()
}
pub fn publish(&self, window: window::Id, event: &Event, status: event::Status) {
if !matches!(event, Event::Keyboard(_)) {
return;
}
let interaction = subscription::Event::Interaction {
window,
event: event.clone(),
status,
};
self.lock()
.retain(|listener| listener.unbounded_send(interaction.clone()).is_ok());
}
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<mpsc::UnboundedSender<subscription::Event>>> {
self.listeners
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
}
#[must_use = "the stream only hears keys while it is kept and polled"]
pub fn synthetic_keys() -> BoxStream<subscription::Event> {
KeyHub::global().subscribe()
}
#[cfg(test)]
mod tests {
use futures::FutureExt;
use iced_core::keyboard::{self, Key, Location, Modifiers, key};
use iced_core::{Point, mouse};
use super::*;
fn press(c: &str) -> Event {
Event::Keyboard(keyboard::Event::KeyPressed {
key: Key::Character(c.into()),
modified_key: Key::Character(c.into()),
physical_key: key::Physical::Unidentified(key::NativeCode::Unidentified),
location: Location::Standard,
modifiers: Modifiers::CTRL,
text: None,
repeat: false,
})
}
fn next(stream: &mut BoxStream<subscription::Event>) -> Option<subscription::Event> {
stream.next().now_or_never().flatten()
}
#[test]
fn every_listener_gets_each_key_event_with_its_window_and_status() {
let hub = KeyHub::new();
let mut first = hub.subscribe();
let mut second = hub.subscribe();
let window = window::Id::unique();
hub.publish(window, &press("k"), event::Status::Ignored);
let expected = subscription::Event::Interaction {
window,
event: press("k"),
status: event::Status::Ignored,
};
assert_eq!(next(&mut first), Some(expected.clone()));
assert_eq!(next(&mut second), Some(expected));
assert_eq!(next(&mut first), None);
}
#[test]
fn pointer_events_are_left_out() {
let hub = KeyHub::new();
let mut keys = hub.subscribe();
let moved = Event::Mouse(mouse::Event::CursorMoved {
position: Point::new(1.0, 1.0),
});
hub.publish(window::Id::unique(), &moved, event::Status::Ignored);
assert_eq!(next(&mut keys), None);
}
#[test]
fn a_dropped_stream_stops_listening() {
let hub = KeyHub::new();
drop(hub.subscribe());
let mut kept = hub.subscribe();
hub.publish(window::Id::unique(), &press("k"), event::Status::Captured);
assert_eq!(hub.lock().len(), 1);
assert!(next(&mut kept).is_some());
}
}