icedwright-probe 0.1.4

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
Documentation
//! Key events a client sent, for the app's key subscriptions.
//!
//! A window's [`Root`](super::Root) hands synthetic events to the widgets, but iced 0.14
//! broadcasts only real input to subscriptions, so `keyboard::listen` and shortcut
//! subscriptions never hear a client's keys. The probe republishes each key event it
//! delivered, with the status the widgets gave it, on a [`KeyHub`]; [`synthetic_keys`] is a
//! stream of them in the shape a subscription's own input has, so an app or a widget library
//! can merge it into the stream it already reads.

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;

/// Hands every key event the probe delivers to each open [`subscribe`](Self::subscribe)
/// stream.
#[derive(Debug, Default)]
pub struct KeyHub {
    listeners: Mutex<Vec<mpsc::UnboundedSender<subscription::Event>>>,
}

static HUB: OnceLock<Arc<KeyHub>> = OnceLock::new();

impl KeyHub {
    /// A hub with no listeners.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// The process-wide hub the endpoint publishes to and [`synthetic_keys`] reads.
    #[must_use]
    pub fn global() -> Arc<Self> {
        Arc::clone(HUB.get_or_init(Arc::default))
    }

    /// Every key event published from now on, until the stream is dropped.
    #[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()
    }

    /// Hands `event` to every listener if it is a keyboard event; anything else is left out.
    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)
    }
}

/// The key presses, releases and modifier changes a remote client sends through a window's
/// widgets, each after the widgets had it and with the status they gave it, as
/// [`subscription::Event::Interaction`]s.
///
/// iced 0.14 does not broadcast these to subscriptions, so a shortcut handled only by a
/// subscription never hears them. Merge this stream into the one the subscription reads, or
/// use `Subscription::run(synthetic_keys)` beside it, to give remote sessions working
/// shortcuts. Outside a remote session it yields nothing. Keys a client sends through the OS
/// keyboard reach subscriptions as real input and are not repeated here.
#[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());
    }
}