Remove generic Hasher and Event from subscription::Recipe

This commit is contained in:
Héctor Ramón Jiménez 2023-03-05 04:15:10 +01:00
parent 5fed065dc3
commit f4cf488e0b
No known key found for this signature in database
GPG key ID: 140CC052C94F138E
20 changed files with 341 additions and 406 deletions

View file

@ -7,8 +7,6 @@ publish = false
[dependencies] [dependencies]
iced = { path = "../..", features = ["tokio"] } iced = { path = "../..", features = ["tokio"] }
iced_native = { path = "../../native" }
iced_futures = { path = "../../futures" }
[dependencies.reqwest] [dependencies.reqwest]
version = "0.11" version = "0.11"

View file

@ -1,4 +1,4 @@
use iced_native::subscription; use iced::subscription;
use std::hash::Hash; use std::hash::Hash;

View file

@ -7,8 +7,6 @@ publish = false
[dependencies] [dependencies]
iced = { path = "../..", features = ["tokio", "debug"] } iced = { path = "../..", features = ["tokio", "debug"] }
iced_native = { path = "../../native" }
iced_futures = { path = "../../futures" }
once_cell = "1.15" once_cell = "1.15"
[dependencies.async-tungstenite] [dependencies.async-tungstenite]

View file

@ -1,7 +1,7 @@
pub mod server; pub mod server;
use iced_futures::futures; use iced::futures;
use iced_native::subscription::{self, Subscription}; use iced::subscription::{self, Subscription};
use futures::channel::mpsc; use futures::channel::mpsc;
use futures::sink::SinkExt; use futures::sink::SinkExt;

View file

@ -1,4 +1,4 @@
use iced_futures::futures; use iced::futures;
use futures::channel::mpsc; use futures::channel::mpsc;
use futures::{SinkExt, StreamExt}; use futures::{SinkExt, StreamExt};

View file

@ -16,6 +16,10 @@ thread-pool = ["futures/thread-pool"]
[dependencies] [dependencies]
log = "0.4" log = "0.4"
[dependencies.iced_core]
version = "0.8"
path = "../core"
[dependencies.futures] [dependencies.futures]
version = "0.3" version = "0.3"

View file

@ -18,28 +18,26 @@ impl crate::Executor for Executor {
pub mod time { pub mod time {
//! Listen and react to time. //! Listen and react to time.
use crate::core::Hasher;
use crate::subscription::{self, Subscription}; use crate::subscription::{self, Subscription};
/// Returns a [`Subscription`] that produces messages at a set interval. /// Returns a [`Subscription`] that produces messages at a set interval.
/// ///
/// The first message is produced after a `duration`, and then continues to /// The first message is produced after a `duration`, and then continues to
/// produce more messages every `duration` after that. /// produce more messages every `duration` after that.
pub fn every<H: std::hash::Hasher, E>( pub fn every(
duration: std::time::Duration, duration: std::time::Duration,
) -> Subscription<H, E, std::time::Instant> { ) -> Subscription<std::time::Instant> {
Subscription::from_recipe(Every(duration)) Subscription::from_recipe(Every(duration))
} }
#[derive(Debug)] #[derive(Debug)]
struct Every(std::time::Duration); struct Every(std::time::Duration);
impl<H, E> subscription::Recipe<H, E> for Every impl subscription::Recipe for Every {
where
H: std::hash::Hasher,
{
type Output = std::time::Instant; type Output = std::time::Instant;
fn hash(&self, state: &mut H) { fn hash(&self, state: &mut Hasher) {
use std::hash::Hash; use std::hash::Hash;
std::any::TypeId::of::<Self>().hash(state); std::any::TypeId::of::<Self>().hash(state);
@ -48,7 +46,7 @@ pub mod time {
fn stream( fn stream(
self: Box<Self>, self: Box<Self>,
_input: futures::stream::BoxStream<'static, E>, _input: subscription::EventStream,
) -> futures::stream::BoxStream<'static, Self::Output> { ) -> futures::stream::BoxStream<'static, Self::Output> {
use futures::stream::StreamExt; use futures::stream::StreamExt;

View file

@ -19,28 +19,26 @@ impl crate::Executor for Executor {
pub mod time { pub mod time {
//! Listen and react to time. //! Listen and react to time.
use crate::core::Hasher;
use crate::subscription::{self, Subscription}; use crate::subscription::{self, Subscription};
/// Returns a [`Subscription`] that produces messages at a set interval. /// Returns a [`Subscription`] that produces messages at a set interval.
/// ///
/// The first message is produced after a `duration`, and then continues to /// The first message is produced after a `duration`, and then continues to
/// produce more messages every `duration` after that. /// produce more messages every `duration` after that.
pub fn every<H: std::hash::Hasher, E>( pub fn every(
duration: std::time::Duration, duration: std::time::Duration,
) -> Subscription<H, E, std::time::Instant> { ) -> Subscription<std::time::Instant> {
Subscription::from_recipe(Every(duration)) Subscription::from_recipe(Every(duration))
} }
#[derive(Debug)] #[derive(Debug)]
struct Every(std::time::Duration); struct Every(std::time::Duration);
impl<H, E> subscription::Recipe<H, E> for Every impl subscription::Recipe for Every {
where
H: std::hash::Hasher,
{
type Output = std::time::Instant; type Output = std::time::Instant;
fn hash(&self, state: &mut H) { fn hash(&self, state: &mut Hasher) {
use std::hash::Hash; use std::hash::Hash;
std::any::TypeId::of::<Self>().hash(state); std::any::TypeId::of::<Self>().hash(state);
@ -49,7 +47,7 @@ pub mod time {
fn stream( fn stream(
self: Box<Self>, self: Box<Self>,
_input: futures::stream::BoxStream<'static, E>, _input: subscription::EventStream,
) -> futures::stream::BoxStream<'static, Self::Output> { ) -> futures::stream::BoxStream<'static, Self::Output> {
use futures::stream::StreamExt; use futures::stream::StreamExt;

View file

@ -22,28 +22,26 @@ impl crate::Executor for Executor {
pub mod time { pub mod time {
//! Listen and react to time. //! Listen and react to time.
use crate::core::Hasher;
use crate::subscription::{self, Subscription}; use crate::subscription::{self, Subscription};
/// Returns a [`Subscription`] that produces messages at a set interval. /// Returns a [`Subscription`] that produces messages at a set interval.
/// ///
/// The first message is produced after a `duration`, and then continues to /// The first message is produced after a `duration`, and then continues to
/// produce more messages every `duration` after that. /// produce more messages every `duration` after that.
pub fn every<H: std::hash::Hasher, E>( pub fn every(
duration: std::time::Duration, duration: std::time::Duration,
) -> Subscription<H, E, std::time::Instant> { ) -> Subscription<std::time::Instant> {
Subscription::from_recipe(Every(duration)) Subscription::from_recipe(Every(duration))
} }
#[derive(Debug)] #[derive(Debug)]
struct Every(std::time::Duration); struct Every(std::time::Duration);
impl<H, E> subscription::Recipe<H, E> for Every impl subscription::Recipe for Every {
where
H: std::hash::Hasher,
{
type Output = std::time::Instant; type Output = std::time::Instant;
fn hash(&self, state: &mut H) { fn hash(&self, state: &mut Hasher) {
use std::hash::Hash; use std::hash::Hash;
std::any::TypeId::of::<Self>().hash(state); std::any::TypeId::of::<Self>().hash(state);
@ -52,7 +50,7 @@ pub mod time {
fn stream( fn stream(
self: Box<Self>, self: Box<Self>,
_input: futures::stream::BoxStream<'static, E>, _input: subscription::EventStream,
) -> futures::stream::BoxStream<'static, Self::Output> { ) -> futures::stream::BoxStream<'static, Self::Output> {
use futures::stream::StreamExt; use futures::stream::StreamExt;

View file

@ -18,6 +18,7 @@
#![allow(clippy::inherent_to_string, clippy::type_complexity)] #![allow(clippy::inherent_to_string, clippy::type_complexity)]
#![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(docsrs, feature(doc_cfg))]
pub use futures; pub use futures;
pub use iced_core as core;
mod command; mod command;
mod maybe_send; mod maybe_send;

View file

@ -1,6 +1,7 @@
//! Run commands and keep track of subscriptions. //! Run commands and keep track of subscriptions.
use crate::core::event::{self, Event};
use crate::subscription; use crate::subscription;
use crate::{BoxFuture, Executor, MaybeSend, Subscription}; use crate::{BoxFuture, Executor, MaybeSend};
use futures::{channel::mpsc, Sink}; use futures::{channel::mpsc, Sink};
use std::marker::PhantomData; use std::marker::PhantomData;
@ -12,18 +13,15 @@ use std::marker::PhantomData;
/// ///
/// [`Command`]: crate::Command /// [`Command`]: crate::Command
#[derive(Debug)] #[derive(Debug)]
pub struct Runtime<Hasher, Event, Executor, Sender, Message> { pub struct Runtime<Executor, Sender, Message> {
executor: Executor, executor: Executor,
sender: Sender, sender: Sender,
subscriptions: subscription::Tracker<Hasher, Event>, subscriptions: subscription::Tracker,
_message: PhantomData<Message>, _message: PhantomData<Message>,
} }
impl<Hasher, Event, Executor, Sender, Message> impl<Executor, Sender, Message> Runtime<Executor, Sender, Message>
Runtime<Hasher, Event, Executor, Sender, Message>
where where
Hasher: std::hash::Hasher + Default,
Event: Send + Clone + 'static,
Executor: self::Executor, Executor: self::Executor,
Sender: Sink<Message, Error = mpsc::SendError> Sender: Sink<Message, Error = mpsc::SendError>
+ Unpin + Unpin
@ -79,7 +77,9 @@ where
/// [`Tracker::update`]: subscription::Tracker::update /// [`Tracker::update`]: subscription::Tracker::update
pub fn track( pub fn track(
&mut self, &mut self,
subscription: Subscription<Hasher, Event, Message>, recipes: impl IntoIterator<
Item = Box<dyn subscription::Recipe<Output = Message>>,
>,
) { ) {
let Runtime { let Runtime {
executor, executor,
@ -88,8 +88,9 @@ where
.. ..
} = self; } = self;
let futures = executor let futures = executor.enter(|| {
.enter(|| subscriptions.update(subscription, sender.clone())); subscriptions.update(recipes.into_iter(), sender.clone())
});
for future in futures { for future in futures {
executor.spawn(future); executor.spawn(future);
@ -102,7 +103,7 @@ where
/// See [`Tracker::broadcast`] to learn more. /// See [`Tracker::broadcast`] to learn more.
/// ///
/// [`Tracker::broadcast`]: subscription::Tracker::broadcast /// [`Tracker::broadcast`]: subscription::Tracker::broadcast
pub fn broadcast(&mut self, event: Event) { pub fn broadcast(&mut self, event: Event, status: event::Status) {
self.subscriptions.broadcast(event); self.subscriptions.broadcast(event, status);
} }
} }

View file

@ -3,7 +3,18 @@ mod tracker;
pub use tracker::Tracker; pub use tracker::Tracker;
use crate::BoxStream; use crate::core::event::{self, Event};
use crate::core::window;
use crate::core::Hasher;
use crate::futures::{Future, Stream};
use crate::{BoxStream, MaybeSend};
use std::hash::Hash;
/// A stream of runtime events.
///
/// It is the input of a [`Subscription`].
pub type EventStream = BoxStream<(Event, event::Status)>;
/// A request to listen to external events. /// A request to listen to external events.
/// ///
@ -16,19 +27,13 @@ use crate::BoxStream;
/// For instance, you can use a [`Subscription`] to listen to a WebSocket /// For instance, you can use a [`Subscription`] to listen to a WebSocket
/// connection, keyboard presses, mouse events, time ticks, etc. /// connection, keyboard presses, mouse events, time ticks, etc.
/// ///
/// This type is normally aliased by runtimes with a specific `Event` and/or
/// `Hasher`.
///
/// [`Command`]: crate::Command /// [`Command`]: crate::Command
#[must_use = "`Subscription` must be returned to runtime to take effect"] #[must_use = "`Subscription` must be returned to runtime to take effect"]
pub struct Subscription<Hasher, Event, Output> { pub struct Subscription<Message> {
recipes: Vec<Box<dyn Recipe<Hasher, Event, Output = Output>>>, recipes: Vec<Box<dyn Recipe<Output = Message>>>,
} }
impl<H, E, O> Subscription<H, E, O> impl<Message> Subscription<Message> {
where
H: std::hash::Hasher,
{
/// Returns an empty [`Subscription`] that will not produce any output. /// Returns an empty [`Subscription`] that will not produce any output.
pub fn none() -> Self { pub fn none() -> Self {
Self { Self {
@ -38,7 +43,7 @@ where
/// Creates a [`Subscription`] from a [`Recipe`] describing it. /// Creates a [`Subscription`] from a [`Recipe`] describing it.
pub fn from_recipe( pub fn from_recipe(
recipe: impl Recipe<H, E, Output = O> + 'static, recipe: impl Recipe<Output = Message> + 'static,
) -> Self { ) -> Self {
Self { Self {
recipes: vec![Box::new(recipe)], recipes: vec![Box::new(recipe)],
@ -48,7 +53,7 @@ where
/// Batches all the provided subscriptions and returns the resulting /// Batches all the provided subscriptions and returns the resulting
/// [`Subscription`]. /// [`Subscription`].
pub fn batch( pub fn batch(
subscriptions: impl IntoIterator<Item = Subscription<H, E, O>>, subscriptions: impl IntoIterator<Item = Subscription<Message>>,
) -> Self { ) -> Self {
Self { Self {
recipes: subscriptions recipes: subscriptions
@ -59,18 +64,16 @@ where
} }
/// Returns the different recipes of the [`Subscription`]. /// Returns the different recipes of the [`Subscription`].
pub fn recipes(self) -> Vec<Box<dyn Recipe<H, E, Output = O>>> { pub fn into_recipes(self) -> Vec<Box<dyn Recipe<Output = Message>>> {
self.recipes self.recipes
} }
/// Adds a value to the [`Subscription`] context. /// Adds a value to the [`Subscription`] context.
/// ///
/// The value will be part of the identity of a [`Subscription`]. /// The value will be part of the identity of a [`Subscription`].
pub fn with<T>(mut self, value: T) -> Subscription<H, E, (T, O)> pub fn with<T>(mut self, value: T) -> Subscription<(T, Message)>
where where
H: 'static, Message: 'static,
E: 'static,
O: 'static,
T: std::hash::Hash + Clone + Send + Sync + 'static, T: std::hash::Hash + Clone + Send + Sync + 'static,
{ {
Subscription { Subscription {
@ -79,18 +82,16 @@ where
.drain(..) .drain(..)
.map(|recipe| { .map(|recipe| {
Box::new(With::new(recipe, value.clone())) Box::new(With::new(recipe, value.clone()))
as Box<dyn Recipe<H, E, Output = (T, O)>> as Box<dyn Recipe<Output = (T, Message)>>
}) })
.collect(), .collect(),
} }
} }
/// Transforms the [`Subscription`] output with the given function. /// Transforms the [`Subscription`] output with the given function.
pub fn map<A>(mut self, f: fn(O) -> A) -> Subscription<H, E, A> pub fn map<A>(mut self, f: fn(Message) -> A) -> Subscription<A>
where where
H: 'static, Message: 'static,
E: 'static,
O: 'static,
A: 'static, A: 'static,
{ {
Subscription { Subscription {
@ -98,15 +99,14 @@ where
.recipes .recipes
.drain(..) .drain(..)
.map(|recipe| { .map(|recipe| {
Box::new(Map::new(recipe, f)) Box::new(Map::new(recipe, f)) as Box<dyn Recipe<Output = A>>
as Box<dyn Recipe<H, E, Output = A>>
}) })
.collect(), .collect(),
} }
} }
} }
impl<I, O, H> std::fmt::Debug for Subscription<I, O, H> { impl<Message> std::fmt::Debug for Subscription<Message> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Subscription").finish() f.debug_struct("Subscription").finish()
} }
@ -129,7 +129,7 @@ impl<I, O, H> std::fmt::Debug for Subscription<I, O, H> {
/// [examples]: https://github.com/iced-rs/iced/tree/0.8/examples /// [examples]: https://github.com/iced-rs/iced/tree/0.8/examples
/// [`download_progress`]: https://github.com/iced-rs/iced/tree/0.8/examples/download_progress /// [`download_progress`]: https://github.com/iced-rs/iced/tree/0.8/examples/download_progress
/// [`stopwatch`]: https://github.com/iced-rs/iced/tree/0.8/examples/stopwatch /// [`stopwatch`]: https://github.com/iced-rs/iced/tree/0.8/examples/stopwatch
pub trait Recipe<Hasher: std::hash::Hasher, Event> { pub trait Recipe {
/// The events that will be produced by a [`Subscription`] with this /// The events that will be produced by a [`Subscription`] with this
/// [`Recipe`]. /// [`Recipe`].
type Output; type Output;
@ -141,45 +141,33 @@ pub trait Recipe<Hasher: std::hash::Hasher, Event> {
/// Executes the [`Recipe`] and produces the stream of events of its /// Executes the [`Recipe`] and produces the stream of events of its
/// [`Subscription`]. /// [`Subscription`].
/// fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output>;
/// It receives some stream of generic events, which is normally defined by
/// shells.
fn stream(
self: Box<Self>,
input: BoxStream<Event>,
) -> BoxStream<Self::Output>;
} }
struct Map<Hasher, Event, A, B> { struct Map<A, B> {
recipe: Box<dyn Recipe<Hasher, Event, Output = A>>, recipe: Box<dyn Recipe<Output = A>>,
mapper: fn(A) -> B, mapper: fn(A) -> B,
} }
impl<H, E, A, B> Map<H, E, A, B> { impl<A, B> Map<A, B> {
fn new( fn new(recipe: Box<dyn Recipe<Output = A>>, mapper: fn(A) -> B) -> Self {
recipe: Box<dyn Recipe<H, E, Output = A>>,
mapper: fn(A) -> B,
) -> Self {
Map { recipe, mapper } Map { recipe, mapper }
} }
} }
impl<H, E, A, B> Recipe<H, E> for Map<H, E, A, B> impl<A, B> Recipe for Map<A, B>
where where
A: 'static, A: 'static,
B: 'static, B: 'static,
H: std::hash::Hasher,
{ {
type Output = B; type Output = B;
fn hash(&self, state: &mut H) { fn hash(&self, state: &mut Hasher) {
use std::hash::Hash;
self.recipe.hash(state); self.recipe.hash(state);
self.mapper.hash(state); self.mapper.hash(state);
} }
fn stream(self: Box<Self>, input: BoxStream<E>) -> BoxStream<Self::Output> { fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> {
use futures::StreamExt; use futures::StreamExt;
let mapper = self.mapper; let mapper = self.mapper;
@ -188,34 +176,31 @@ where
} }
} }
struct With<Hasher, Event, A, B> { struct With<A, B> {
recipe: Box<dyn Recipe<Hasher, Event, Output = A>>, recipe: Box<dyn Recipe<Output = A>>,
value: B, value: B,
} }
impl<H, E, A, B> With<H, E, A, B> { impl<A, B> With<A, B> {
fn new(recipe: Box<dyn Recipe<H, E, Output = A>>, value: B) -> Self { fn new(recipe: Box<dyn Recipe<Output = A>>, value: B) -> Self {
With { recipe, value } With { recipe, value }
} }
} }
impl<H, E, A, B> Recipe<H, E> for With<H, E, A, B> impl<A, B> Recipe for With<A, B>
where where
A: 'static, A: 'static,
B: 'static + std::hash::Hash + Clone + Send + Sync, B: 'static + std::hash::Hash + Clone + Send + Sync,
H: std::hash::Hasher,
{ {
type Output = (B, A); type Output = (B, A);
fn hash(&self, state: &mut H) { fn hash(&self, state: &mut Hasher) {
use std::hash::Hash;
std::any::TypeId::of::<B>().hash(state); std::any::TypeId::of::<B>().hash(state);
self.value.hash(state); self.value.hash(state);
self.recipe.hash(state); self.recipe.hash(state);
} }
fn stream(self: Box<Self>, input: BoxStream<E>) -> BoxStream<Self::Output> { fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> {
use futures::StreamExt; use futures::StreamExt;
let value = self.value; let value = self.value;
@ -227,3 +212,222 @@ where
) )
} }
} }
/// Returns a [`Subscription`] to all the ignored runtime events.
///
/// This subscription will notify your application of any [`Event`] that was
/// not captured by any widget.
pub fn events() -> Subscription<Event> {
events_with(|event, status| match status {
event::Status::Ignored => Some(event),
event::Status::Captured => None,
})
}
/// Returns a [`Subscription`] that filters all the runtime events with the
/// provided function, producing messages accordingly.
///
/// This subscription will call the provided function for every [`Event`]
/// handled by the runtime. If the function:
///
/// - Returns `None`, the [`Event`] will be discarded.
/// - Returns `Some` message, the `Message` will be produced.
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),
})
})
},
})
}
/// Returns a [`Subscription`] that produces a message for every runtime event,
/// including the redraw request events.
///
/// **Warning:** This [`Subscription`], if unfiltered, may produce messages in
/// an infinite loop.
pub 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))
})
},
})
}
/// Returns a [`Subscription`] that will call the given function to create and
/// asynchronously run the given [`Stream`].
pub fn run<S, Message>(builder: fn() -> S) -> Subscription<Message>
where
S: Stream<Item = Message> + MaybeSend + 'static,
Message: 'static,
{
Subscription::from_recipe(Runner {
id: builder,
spawn: move |_| builder(),
})
}
/// Returns a [`Subscription`] that will create and asynchronously run the
/// given [`Stream`].
///
/// The `id` will be used to uniquely identify the [`Subscription`].
pub fn run_with_id<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,
})
}
/// Returns a [`Subscription`] that will create and asynchronously run a
/// [`Stream`] that will call the provided closure to produce every `Message`.
///
/// The `id` will be used to uniquely identify the [`Subscription`].
///
/// # Creating an asynchronous worker with bidirectional communication
/// You can leverage this helper to create a [`Subscription`] that spawns
/// an asynchronous worker in the background and establish a channel of
/// communication with an `iced` application.
///
/// You can achieve this by creating an `mpsc` channel inside the closure
/// and returning the `Sender` as a `Message` for the `Application`:
///
/// ```
/// use iced_futures::subscription::{self, Subscription};
/// use iced_futures::futures;
///
/// use futures::channel::mpsc;
///
/// pub enum Event {
/// Ready(mpsc::Sender<Input>),
/// WorkFinished,
/// // ...
/// }
///
/// enum Input {
/// DoSomeWork,
/// // ...
/// }
///
/// enum State {
/// Starting,
/// Ready(mpsc::Receiver<Input>),
/// }
///
/// fn some_worker() -> Subscription<Event> {
/// struct SomeWorker;
///
/// subscription::unfold(std::any::TypeId::of::<SomeWorker>(), State::Starting, |state| async move {
/// match state {
/// State::Starting => {
/// // Create channel
/// let (sender, receiver) = mpsc::channel(100);
///
/// (Some(Event::Ready(sender)), State::Ready(receiver))
/// }
/// State::Ready(mut receiver) => {
/// use futures::StreamExt;
///
/// // Read next input sent from `Application`
/// let input = receiver.select_next_some().await;
///
/// match input {
/// Input::DoSomeWork => {
/// // Do some async work...
///
/// // Finally, we can optionally return a message to tell the
/// // `Application` the work is done
/// (Some(Event::WorkFinished), State::Ready(receiver))
/// }
/// }
/// }
/// }
/// })
/// }
/// ```
///
/// Check out the [`websocket`] example, which showcases this pattern to maintain a WebSocket
/// connection open.
///
/// [`websocket`]: https://github.com/iced-rs/iced/tree/0.8/examples/websocket
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_with_id(
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 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> {
crate::boxed_stream((self.spawn)(input))
}
}

View file

@ -1,38 +1,35 @@
use crate::{BoxFuture, MaybeSend, Subscription}; use crate::core::event::{self, Event};
use crate::core::Hasher;
use crate::subscription::Recipe;
use crate::{BoxFuture, MaybeSend};
use futures::{ use futures::channel::mpsc;
channel::mpsc, use futures::sink::{Sink, SinkExt};
sink::{Sink, SinkExt},
}; use std::collections::HashMap;
use std::{collections::HashMap, marker::PhantomData}; use std::hash::Hasher as _;
/// A registry of subscription streams. /// A registry of subscription streams.
/// ///
/// If you have an application that continuously returns a [`Subscription`], /// If you have an application that continuously returns a [`Subscription`],
/// you can use a [`Tracker`] to keep track of the different recipes and keep /// you can use a [`Tracker`] to keep track of the different recipes and keep
/// its executions alive. /// its executions alive.
#[derive(Debug)] #[derive(Debug, Default)]
pub struct Tracker<Hasher, Event> { pub struct Tracker {
subscriptions: HashMap<u64, Execution<Event>>, subscriptions: HashMap<u64, Execution>,
_hasher: PhantomData<Hasher>,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Execution<Event> { pub struct Execution {
_cancel: futures::channel::oneshot::Sender<()>, _cancel: futures::channel::oneshot::Sender<()>,
listener: Option<futures::channel::mpsc::Sender<Event>>, listener: Option<futures::channel::mpsc::Sender<(Event, event::Status)>>,
} }
impl<Hasher, Event> Tracker<Hasher, Event> impl Tracker {
where
Hasher: std::hash::Hasher + Default,
Event: 'static + Send + Clone,
{
/// Creates a new empty [`Tracker`]. /// Creates a new empty [`Tracker`].
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
subscriptions: HashMap::new(), subscriptions: HashMap::new(),
_hasher: PhantomData,
} }
} }
@ -56,7 +53,7 @@ where
/// [`Recipe`]: crate::subscription::Recipe /// [`Recipe`]: crate::subscription::Recipe
pub fn update<Message, Receiver>( pub fn update<Message, Receiver>(
&mut self, &mut self,
subscription: Subscription<Hasher, Event, Message>, recipes: impl Iterator<Item = Box<dyn Recipe<Output = Message>>>,
receiver: Receiver, receiver: Receiver,
) -> Vec<BoxFuture<()>> ) -> Vec<BoxFuture<()>>
where where
@ -70,8 +67,6 @@ where
use futures::stream::StreamExt; use futures::stream::StreamExt;
let mut futures: Vec<BoxFuture<()>> = Vec::new(); let mut futures: Vec<BoxFuture<()>> = Vec::new();
let recipes = subscription.recipes();
let mut alive = std::collections::HashSet::new(); let mut alive = std::collections::HashSet::new();
for recipe in recipes { for recipe in recipes {
@ -142,12 +137,12 @@ where
/// currently open. /// currently open.
/// ///
/// [`Recipe::stream`]: crate::subscription::Recipe::stream /// [`Recipe::stream`]: crate::subscription::Recipe::stream
pub fn broadcast(&mut self, event: Event) { pub fn broadcast(&mut self, event: Event, status: event::Status) {
self.subscriptions self.subscriptions
.values_mut() .values_mut()
.filter_map(|connection| connection.listener.as_mut()) .filter_map(|connection| connection.listener.as_mut())
.for_each(|listener| { .for_each(|listener| {
if let Err(error) = listener.try_send(event.clone()) { if let Err(error) = listener.try_send((event.clone(), status)) {
log::warn!( log::warn!(
"Error sending event to subscription: {:?}", "Error sending event to subscription: {:?}",
error error
@ -156,13 +151,3 @@ where
}); });
} }
} }
impl<Hasher, Event> Default for Tracker<Hasher, Event>
where
Hasher: std::hash::Hasher + Default,
Event: 'static + Send + Clone,
{
fn default() -> Self {
Self::new()
}
}

View file

@ -48,14 +48,11 @@ pub mod command;
pub mod font; pub mod font;
pub mod keyboard; pub mod keyboard;
pub mod program; pub mod program;
pub mod subscription;
pub mod system; pub mod system;
pub mod user_interface; pub mod user_interface;
pub mod widget; pub mod widget;
pub mod window; pub mod window;
mod runtime;
// We disable debug capabilities on release builds unless the `debug` feature // We disable debug capabilities on release builds unless the `debug` feature
// is explicitly enabled. // is explicitly enabled.
#[cfg(feature = "debug")] #[cfg(feature = "debug")]
@ -72,6 +69,4 @@ pub use command::Command;
pub use debug::Debug; pub use debug::Debug;
pub use font::Font; pub use font::Font;
pub use program::Program; pub use program::Program;
pub use runtime::Runtime;
pub use subscription::Subscription;
pub use user_interface::UserInterface; pub use user_interface::UserInterface;

View file

@ -1,18 +0,0 @@
//! Run commands and subscriptions.
use iced_core::event::{self, Event};
use iced_core::Hasher;
/// A native runtime with a generic executor and receiver of results.
///
/// It can be used by shells to easily spawn a [`Command`] or track a
/// [`Subscription`].
///
/// [`Command`]: crate::Command
/// [`Subscription`]: crate::Subscription
pub type Runtime<Executor, Receiver, Message> = iced_futures::Runtime<
Hasher,
(Event, event::Status),
Executor,
Receiver,
Message,
>;

View file

@ -3,247 +3,7 @@ use crate::core::event::{self, Event};
use crate::core::window; use crate::core::window;
use crate::core::Hasher; use crate::core::Hasher;
use crate::futures::futures::{self, Future, Stream}; use crate::futures::futures::{self, Future, Stream};
use crate::futures::subscription::{EventStream, Recipe, Subscription};
use crate::futures::{BoxStream, MaybeSend}; use crate::futures::{BoxStream, MaybeSend};
use std::hash::Hash; use std::hash::Hash;
/// A request to listen to external events.
///
/// Besides performing async actions on demand with [`Command`], most
/// applications also need to listen to external events passively.
///
/// A [`Subscription`] is normally provided to some runtime, like a [`Command`],
/// and it will generate events as long as the user keeps requesting it.
///
/// For instance, you can use a [`Subscription`] to listen to a WebSocket
/// connection, keyboard presses, mouse events, time ticks, etc.
///
/// [`Command`]: crate::Command
pub type Subscription<T> =
iced_futures::Subscription<Hasher, (Event, event::Status), T>;
/// A stream of runtime events.
///
/// It is the input of a [`Subscription`] in the native runtime.
pub type EventStream = BoxStream<(Event, event::Status)>;
/// A native [`Subscription`] tracker.
pub type Tracker =
iced_futures::subscription::Tracker<Hasher, (Event, event::Status)>;
pub use iced_futures::subscription::Recipe;
/// Returns a [`Subscription`] to all the ignored runtime events.
///
/// This subscription will notify your application of any [`Event`] that was
/// not captured by any widget.
pub fn events() -> Subscription<Event> {
events_with(|event, status| match status {
event::Status::Ignored => Some(event),
event::Status::Captured => None,
})
}
/// Returns a [`Subscription`] that filters all the runtime events with the
/// provided function, producing messages accordingly.
///
/// This subscription will call the provided function for every [`Event`]
/// handled by the runtime. If the function:
///
/// - Returns `None`, the [`Event`] will be discarded.
/// - Returns `Some` message, the `Message` will be produced.
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))
})
},
})
}
/// Returns a [`Subscription`] that will call the given function to create and
/// asynchronously run the given [`Stream`].
pub fn run<S, Message>(builder: fn() -> S) -> Subscription<Message>
where
S: Stream<Item = Message> + MaybeSend + 'static,
Message: 'static,
{
Subscription::from_recipe(Runner {
id: builder,
spawn: move |_| builder(),
})
}
/// Returns a [`Subscription`] that will create and asynchronously run the
/// given [`Stream`].
///
/// The `id` will be used to uniquely identify the [`Subscription`].
pub fn run_with_id<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,
})
}
/// Returns a [`Subscription`] that will create and asynchronously run a
/// [`Stream`] that will call the provided closure to produce every `Message`.
///
/// The `id` will be used to uniquely identify the [`Subscription`].
///
/// # Creating an asynchronous worker with bidirectional communication
/// You can leverage this helper to create a [`Subscription`] that spawns
/// an asynchronous worker in the background and establish a channel of
/// communication with an `iced` application.
///
/// You can achieve this by creating an `mpsc` channel inside the closure
/// and returning the `Sender` as a `Message` for the `Application`:
///
/// ```
/// use iced_native::subscription::{self, Subscription};
/// use iced_native::futures::futures;
///
/// use futures::channel::mpsc;
///
/// pub enum Event {
/// Ready(mpsc::Sender<Input>),
/// WorkFinished,
/// // ...
/// }
///
/// enum Input {
/// DoSomeWork,
/// // ...
/// }
///
/// enum State {
/// Starting,
/// Ready(mpsc::Receiver<Input>),
/// }
///
/// fn some_worker() -> Subscription<Event> {
/// struct SomeWorker;
///
/// subscription::unfold(std::any::TypeId::of::<SomeWorker>(), State::Starting, |state| async move {
/// match state {
/// State::Starting => {
/// // Create channel
/// let (sender, receiver) = mpsc::channel(100);
///
/// (Some(Event::Ready(sender)), State::Ready(receiver))
/// }
/// State::Ready(mut receiver) => {
/// use futures::StreamExt;
///
/// // Read next input sent from `Application`
/// let input = receiver.select_next_some().await;
///
/// match input {
/// Input::DoSomeWork => {
/// // Do some async work...
///
/// // Finally, we can optionally return a message to tell the
/// // `Application` the work is done
/// (Some(Event::WorkFinished), State::Ready(receiver))
/// }
/// }
/// }
/// }
/// })
/// }
/// ```
///
/// Check out the [`websocket`] example, which showcases this pattern to maintain a WebSocket
/// connection open.
///
/// [`websocket`]: https://github.com/iced-rs/iced/tree/0.8/examples/websocket
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_with_id(
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))
}
}

View file

@ -5,7 +5,7 @@ pub use action::Action;
use crate::core::time::Instant; use crate::core::time::Instant;
use crate::core::window::Event; use crate::core::window::Event;
use crate::subscription::{self, Subscription}; use crate::futures::subscription::{self, Subscription};
/// Subscribes to the frames of the window of the running application. /// Subscribes to the frames of the window of the running application.
/// ///

View file

@ -7,3 +7,8 @@ pub use crate::core::svg;
pub use crate::core::text::{self, Text}; pub use crate::core::text::{self, Text};
pub use crate::core::widget::{self, Widget}; pub use crate::core::widget::{self, Widget};
pub use crate::core::{Clipboard, Shell}; pub use crate::core::{Clipboard, Shell};
pub mod subscription {
//! Write your own subscriptions.
pub use crate::native::futures::subscription::{EventStream, Recipe};
}

View file

@ -193,7 +193,6 @@ pub use crate::core::{
Rectangle, Size, Vector, Rectangle, Size, Vector,
}; };
pub use crate::native::Command; pub use crate::native::Command;
pub use native::subscription;
pub mod clipboard { pub mod clipboard {
//! Access the clipboard. //! Access the clipboard.
@ -233,6 +232,13 @@ pub mod mouse {
pub use crate::core::mouse::{Button, Event, Interaction, ScrollDelta}; pub use crate::core::mouse::{Button, Event, Interaction, ScrollDelta};
} }
pub mod subscription {
//! Listen to external events in your application.
pub use iced_futures::subscription::{
events, events_with, run, run_with_id, unfold, Subscription,
};
}
#[cfg(feature = "system")] #[cfg(feature = "system")]
pub mod system { pub mod system {
//! Retrieve system information. //! Retrieve system information.

View file

@ -14,12 +14,12 @@ use crate::core::widget::operation;
use crate::core::window; use crate::core::window;
use crate::core::{Event, Size}; use crate::core::{Event, Size};
use crate::futures::futures; use crate::futures::futures;
use crate::futures::Executor; use crate::futures::{Executor, Runtime, Subscription};
use crate::graphics::compositor::{self, Compositor}; use crate::graphics::compositor::{self, Compositor};
use crate::native::clipboard; use crate::native::clipboard;
use crate::native::program::Program; use crate::native::program::Program;
use crate::native::user_interface::{self, UserInterface}; use crate::native::user_interface::{self, UserInterface};
use crate::native::{Command, Debug, Runtime, Subscription}; use crate::native::{Command, Debug};
use crate::style::application::{Appearance, StyleSheet}; use crate::style::application::{Appearance, StyleSheet};
use crate::{Clipboard, Error, Proxy, Settings}; use crate::{Clipboard, Error, Proxy, Settings};
@ -316,7 +316,7 @@ async fn run_instance<A, E, C>(
&window, &window,
|| compositor.fetch_information(), || compositor.fetch_information(),
); );
runtime.track(application.subscription()); runtime.track(application.subscription().into_recipes());
let mut user_interface = ManuallyDrop::new(build_user_interface( let mut user_interface = ManuallyDrop::new(build_user_interface(
&application, &application,
@ -360,8 +360,10 @@ async fn run_instance<A, E, C>(
debug.event_processing_finished(); debug.event_processing_finished();
for event in events.drain(..).zip(statuses.into_iter()) { for (event, status) in
runtime.broadcast(event); events.drain(..).zip(statuses.into_iter())
{
runtime.broadcast(event, status);
} }
if !messages.is_empty() if !messages.is_empty()
@ -442,7 +444,7 @@ async fn run_instance<A, E, C>(
} }
window.request_redraw(); window.request_redraw();
runtime.broadcast((redraw_event, core::event::Status::Ignored)); runtime.broadcast(redraw_event, core::event::Status::Ignored);
let _ = control_sender.start_send(match interface_state { let _ = control_sender.start_send(match interface_state {
user_interface::State::Updated { user_interface::State::Updated {
@ -685,7 +687,7 @@ pub fn update<A: Application, E: Executor>(
} }
let subscription = application.subscription(); let subscription = application.subscription();
runtime.track(subscription); runtime.track(subscription.into_recipes());
} }
/// Runs the actions of a [`Command`]. /// Runs the actions of a [`Command`].