use crate::event::{self, Event};
use crate::window;
use crate::Hasher;
use iced_futures::futures::{self, Future, Stream};
use iced_futures::{BoxStream, MaybeSend};
use std::hash::Hash;
pub type Subscription<T> =
iced_futures::Subscription<Hasher, (Event, event::Status), T>;
pub type EventStream = BoxStream<(Event, event::Status)>;
pub type Tracker =
iced_futures::subscription::Tracker<Hasher, (Event, event::Status)>;
pub use iced_futures::subscription::Recipe;
pub fn events() -> Subscription<Event> {
events_with(|event, status| match status {
event::Status::Ignored => Some(event),
event::Status::Captured => None,
})
}
pub fn events_with<Message>(
f: fn(Event, event::Status) -> Option<Message>,
) -> Subscription<Message>
where
Message: 'static + MaybeSend,
{
#[derive(Hash)]
struct EventsWith;
Subscription::from_recipe(Runner {
id: (EventsWith, f),
spawn: move |events| {
use futures::future;
use futures::stream::StreamExt;
events.filter_map(move |(event, status)| {
future::ready(match event {
Event::Window(window::Event::RedrawRequested(_)) => None,
_ => f(event, status),
})
})
},
})
}
pub(crate) fn raw_events<Message>(
f: fn(Event, event::Status) -> Option<Message>,
) -> Subscription<Message>
where
Message: 'static + MaybeSend,
{
#[derive(Hash)]
struct RawEvents;
Subscription::from_recipe(Runner {
id: (RawEvents, f),
spawn: move |events| {
use futures::future;
use futures::stream::StreamExt;
events.filter_map(move |(event, status)| {
future::ready(f(event, status))
})
},
})
}
pub fn run<I, S, Message>(id: I, stream: S) -> Subscription<Message>
where
I: Hash + 'static,
S: Stream<Item = Message> + MaybeSend + 'static,
Message: 'static,
{
Subscription::from_recipe(Runner {
id,
spawn: move |_| stream,
})
}
pub fn unfold<I, T, Fut, Message>(
id: I,
initial: T,
mut f: impl FnMut(T) -> Fut + MaybeSend + Sync + 'static,
) -> Subscription<Message>
where
I: Hash + 'static,
T: MaybeSend + 'static,
Fut: Future<Output = (Option<Message>, T)> + MaybeSend + 'static,
Message: 'static + MaybeSend,
{
use futures::future::{self, FutureExt};
use futures::stream::StreamExt;
run(
id,
futures::stream::unfold(initial, move |state| f(state).map(Some))
.filter_map(future::ready),
)
}
struct Runner<I, F, S, Message>
where
F: FnOnce(EventStream) -> S,
S: Stream<Item = Message>,
{
id: I,
spawn: F,
}
impl<I, S, F, Message> Recipe<Hasher, (Event, event::Status)>
for Runner<I, F, S, Message>
where
I: Hash + 'static,
F: FnOnce(EventStream) -> S,
S: Stream<Item = Message> + MaybeSend + 'static,
{
type Output = Message;
fn hash(&self, state: &mut Hasher) {
std::any::TypeId::of::<I>().hash(state);
self.id.hash(state);
}
fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> {
iced_futures::boxed_stream((self.spawn)(input))
}
}