Remove Executor::block_on and simplify Compositor creation

This commit is contained in:
Héctor Ramón Jiménez 2025-04-02 10:39:27 +02:00
parent baadcc150f
commit 57cb14ce38
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
13 changed files with 58 additions and 108 deletions

View file

@ -22,7 +22,7 @@ all-features = true
maintenance = { status = "actively-developed" } maintenance = { status = "actively-developed" }
[features] [features]
default = ["wgpu", "tiny-skia", "auto-detect-theme", "futures-executor"] default = ["wgpu", "tiny-skia", "auto-detect-theme", "thread-pool"]
# Enables the `wgpu` GPU-accelerated renderer backend # Enables the `wgpu` GPU-accelerated renderer backend
wgpu = ["iced_renderer/wgpu", "iced_widget/wgpu"] wgpu = ["iced_renderer/wgpu", "iced_widget/wgpu"]
# Enables the `tiny-skia` software renderer backend # Enables the `tiny-skia` software renderer backend
@ -43,8 +43,8 @@ markdown = ["iced_widget/markdown"]
lazy = ["iced_widget/lazy"] lazy = ["iced_widget/lazy"]
# Enables a debug view in native platforms (press F12) # Enables a debug view in native platforms (press F12)
debug = ["iced_winit/debug"] debug = ["iced_winit/debug"]
# Enables `futures-executor` as the `executor::Default` on native platforms # Enables the `thread-pool` futures executor as the `executor::Default` on native platforms
futures-executor = ["iced_futures/thread-pool"] thread-pool = ["iced_futures/thread-pool"]
# Enables `tokio` as the `executor::Default` on native platforms # Enables `tokio` as the `executor::Default` on native platforms
tokio = ["iced_futures/tokio"] tokio = ["iced_futures/tokio"]
# Enables `async-std` as the `executor::Default` on native platforms # Enables `async-std` as the `executor::Default` on native platforms
@ -152,7 +152,7 @@ bytemuck = { version = "1.0", features = ["derive"] }
bytes = "1.6" bytes = "1.6"
cosmic-text = "0.13" cosmic-text = "0.13"
dark-light = "2.0" dark-light = "2.0"
futures = { version = "0.3", default-features = false, features = ["std", "async-await"] } futures = { version = "0.3", default-features = false }
glam = "0.25" glam = "0.25"
cryoglyph = { git = "https://github.com/iced-rs/cryoglyph.git", rev = "be2defe4a13fd7c97c6f4c81e8e085463eb578dc" } cryoglyph = { git = "https://github.com/iced-rs/cryoglyph.git", rev = "be2defe4a13fd7c97c6f4c81e8e085463eb578dc" }
guillotiere = "0.6" guillotiere = "0.6"

View file

@ -24,6 +24,8 @@ thread-pool = ["futures/thread-pool"]
iced_core.workspace = true iced_core.workspace = true
futures.workspace = true futures.workspace = true
futures.features = ["std"]
log.workspace = true log.workspace = true
rustc-hash.workspace = true rustc-hash.workspace = true

View file

@ -13,10 +13,6 @@ impl crate::Executor for Executor {
fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) { fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
let _ = async_std::task::spawn(future); let _ = async_std::task::spawn(future);
} }
fn block_on(future: impl Future<Output = ()> + 'static) {
async_std::task::block_on(future);
}
} }
pub mod time { pub mod time {

View file

@ -12,10 +12,6 @@ impl crate::Executor for Executor {
fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) { fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
smol::spawn(future).detach(); smol::spawn(future).detach();
} }
fn block_on(future: impl Future<Output = ()> + 'static) {
smol::block_on(future);
}
} }
pub mod time { pub mod time {

View file

@ -11,10 +11,6 @@ impl crate::Executor for Executor {
fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) { fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
self.spawn_ok(future); self.spawn_ok(future);
} }
fn block_on(future: impl Future<Output = ()> + 'static) {
futures::executor::block_on(future);
}
} }
pub mod time { pub mod time {

View file

@ -17,13 +17,6 @@ impl crate::Executor for Executor {
let _guard = tokio::runtime::Runtime::enter(self); let _guard = tokio::runtime::Runtime::enter(self);
f() f()
} }
fn block_on(future: impl Future<Output = ()> + 'static) {
tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(future);
}
} }
pub mod time { pub mod time {

View file

@ -1,4 +1,5 @@
//! A backend that does nothing! //! A backend that does nothing!
use crate::MaybeSend;
/// An executor that drops all the futures, instead of spawning them. /// An executor that drops all the futures, instead of spawning them.
#[derive(Debug)] #[derive(Debug)]
@ -9,17 +10,7 @@ impl crate::Executor for Executor {
Ok(Self) Ok(Self)
} }
#[cfg(not(target_arch = "wasm32"))] fn spawn(&self, _future: impl Future<Output = ()> + MaybeSend + 'static) {}
fn spawn(&self, _future: impl Future<Output = ()> + Send + 'static) {}
#[cfg(target_arch = "wasm32")]
fn spawn(&self, _future: impl Future<Output = ()> + 'static) {}
#[cfg(not(target_arch = "wasm32"))]
fn block_on(_future: impl Future<Output = ()> + 'static) {}
#[cfg(target_arch = "wasm32")]
fn block_on(_future: impl Future<Output = ()> + 'static) {}
} }
pub mod time { pub mod time {

View file

@ -12,10 +12,6 @@ impl crate::Executor for Executor {
fn spawn(&self, future: impl futures::Future<Output = ()> + 'static) { fn spawn(&self, future: impl futures::Future<Output = ()> + 'static) {
wasm_bindgen_futures::spawn_local(future); wasm_bindgen_futures::spawn_local(future);
} }
fn block_on(future: impl futures::Future<Output = ()> + 'static) {
wasm_bindgen_futures::spawn_local(future);
}
} }
pub mod time { pub mod time {

View file

@ -20,7 +20,4 @@ pub trait Executor: Sized {
fn enter<R>(&self, f: impl FnOnce() -> R) -> R { fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
f() f()
} }
/// Runs the future on the current thread, blocking it until it is completed.
fn block_on(future: impl Future<Output = ()> + 'static);
} }

View file

@ -1,6 +1,6 @@
//! Run commands and keep track of subscriptions. //! Run commands and keep track of subscriptions.
use crate::subscription; use crate::subscription;
use crate::{BoxFuture, BoxStream, Executor, MaybeSend}; use crate::{BoxStream, Executor, MaybeSend};
use futures::{Sink, channel::mpsc}; use futures::{Sink, channel::mpsc};
use std::marker::PhantomData; use std::marker::PhantomData;
@ -51,20 +51,10 @@ where
} }
/// Spawns a [`Future`] in the [`Runtime`]. /// Spawns a [`Future`] in the [`Runtime`].
/// pub fn spawn(
/// The resulting `Message` will be forwarded to the `Sender` of the &mut self,
/// [`Runtime`]. future: impl Future<Output = ()> + MaybeSend + 'static,
/// ) {
/// [`Future`]: BoxFuture
pub fn spawn(&mut self, future: BoxFuture<Message>) {
use futures::{FutureExt, SinkExt};
let mut sender = self.sender.clone();
let future = future.then(|message| async move {
let _ = sender.send(message).await;
});
self.executor.spawn(future); self.executor.spawn(future);
} }

View file

@ -10,7 +10,7 @@ use thiserror::Error;
use std::borrow::Cow; use std::borrow::Cow;
/// A graphics compositor that can draw to windows. /// A graphics compositor that can draw to windows.
pub trait Compositor: Sized { pub trait Compositor: Sized + MaybeSend {
/// The iced renderer of the backend. /// The iced renderer of the backend.
type Renderer; type Renderer;
@ -21,7 +21,7 @@ pub trait Compositor: Sized {
fn new<W: Window + Clone>( fn new<W: Window + Clone>(
settings: Settings, settings: Settings,
compatible_window: W, compatible_window: W,
) -> impl Future<Output = Result<Self, Error>> { ) -> impl Future<Output = Result<Self, Error>> + MaybeSend {
Self::with_backend(settings, compatible_window, None) Self::with_backend(settings, compatible_window, None)
} }
@ -33,7 +33,7 @@ pub trait Compositor: Sized {
_settings: Settings, _settings: Settings,
_compatible_window: W, _compatible_window: W,
_backend: Option<&str>, _backend: Option<&str>,
) -> impl Future<Output = Result<Self, Error>>; ) -> impl Future<Output = Result<Self, Error>> + MaybeSend;
/// Creates a [`Self::Renderer`] for the [`Compositor`]. /// Creates a [`Self::Renderer`] for the [`Compositor`].
fn create_renderer(&self) -> Self::Renderer; fn create_renderer(&self) -> Self::Renderer;

View file

@ -480,6 +480,13 @@ use iced_winit::runtime;
pub use iced_futures::futures; pub use iced_futures::futures;
pub use iced_futures::stream; pub use iced_futures::stream;
#[cfg(not(any(feature = "thread-pool", feature = "tokio", feature = "smol")))]
compile_error!(
"No futures executor has been enabled! You must enable an
executor feature.\n
Available options: thread-pool, tokio, smol, or async-std."
);
#[cfg(feature = "highlighter")] #[cfg(feature = "highlighter")]
pub use iced_highlighter as highlighter; pub use iced_highlighter as highlighter;

View file

@ -18,7 +18,7 @@ use crate::futures::futures::channel::oneshot;
use crate::futures::futures::task; use crate::futures::futures::task;
use crate::futures::futures::{Future, StreamExt}; use crate::futures::futures::{Future, StreamExt};
use crate::futures::subscription::{self, Subscription}; use crate::futures::subscription::{self, Subscription};
use crate::futures::{Executor, Runtime}; use crate::futures::{Executor, MaybeSend, Runtime};
use crate::graphics; use crate::graphics;
use crate::graphics::{Compositor, compositor}; use crate::graphics::{Compositor, compositor};
use crate::runtime::Debug; use crate::runtime::Debug;
@ -149,7 +149,7 @@ pub fn run<P, C>(
) -> Result<(), Error> ) -> Result<(), Error>
where where
P: Program + 'static, P: Program + 'static,
C: Compositor<Renderer = P::Renderer> + 'static, C: Compositor<Renderer = P::Renderer> + MaybeSend + 'static,
P::Theme: theme::Base, P::Theme: theme::Base,
{ {
use winit::event_loop::EventLoop; use winit::event_loop::EventLoop;
@ -494,9 +494,7 @@ where
event_loop.exit(); event_loop.exit();
} }
}, },
_ => { _ => break,
break;
}
}, },
task::Poll::Ready(_) => { task::Poll::Ready(_) => {
event_loop.exit(); event_loop.exit();
@ -562,7 +560,7 @@ async fn run_instance<P, C>(
default_fonts: Vec<Cow<'static, [u8]>>, default_fonts: Vec<Cow<'static, [u8]>>,
) where ) where
P: Program + 'static, P: Program + 'static,
C: Compositor<Renderer = P::Renderer> + 'static, C: Compositor<Renderer = P::Renderer> + MaybeSend + 'static,
P::Theme: theme::Base, P::Theme: theme::Base,
{ {
use winit::event; use winit::event;
@ -579,35 +577,11 @@ async fn run_instance<P, C>(
let mut ui_caches = FxHashMap::default(); let mut ui_caches = FxHashMap::default();
let mut user_interfaces = ManuallyDrop::new(FxHashMap::default()); let mut user_interfaces = ManuallyDrop::new(FxHashMap::default());
let mut clipboard = Clipboard::unconnected(); let mut clipboard = Clipboard::unconnected();
let mut compositor_receiver: Option<oneshot::Receiver<_>> = None;
debug.startup_finished(); debug.startup_finished();
loop { loop {
let event = if compositor_receiver.is_some() { let event = if let Ok(event) = event_receiver.try_next() {
let compositor_receiver =
compositor_receiver.take().expect("Waiting for compositor");
match compositor_receiver.await {
Ok(Ok((new_compositor, event))) => {
compositor = Some(new_compositor);
Some(event)
}
Ok(Err(error)) => {
control_sender
.start_send(Control::Crash(
Error::GraphicsCreationFailed(error),
))
.expect("Send control action");
break;
}
Err(error) => {
panic!("Compositor initialization failed: {error}")
}
}
// Empty the queue if possible
} else if let Ok(event) = event_receiver.try_next() {
event event
} else { } else {
event_receiver.next().await event_receiver.next().await
@ -626,17 +600,17 @@ async fn run_instance<P, C>(
on_open, on_open,
} => { } => {
if compositor.is_none() { if compositor.is_none() {
let (compositor_sender, new_compositor_receiver) = let (compositor_sender, compositor_receiver) =
oneshot::channel(); oneshot::channel();
compositor_receiver = Some(new_compositor_receiver);
let create_compositor = { let create_compositor = {
let window = window.clone();
let mut proxy = proxy.clone();
let default_fonts = default_fonts.clone(); let default_fonts = default_fonts.clone();
async move { async move {
let mut compositor = let mut compositor =
C::new(graphics_settings, window.clone()).await; C::new(graphics_settings, window).await;
if let Ok(compositor) = &mut compositor { if let Ok(compositor) = &mut compositor {
for font in default_fonts { for font in default_fonts {
@ -645,26 +619,38 @@ async fn run_instance<P, C>(
} }
compositor_sender compositor_sender
.send(compositor.map(|compositor| { .send(compositor)
(
compositor,
Event::WindowCreated {
id,
window,
exit_on_close_request,
make_visible,
on_open,
},
)
}))
.ok() .ok()
.expect("Send compositor"); .expect("Send compositor");
// HACK! Send a proxy event on completion to trigger
// a runtime re-poll
// TODO: Send compositor through proxy (?)
{
let (sender, _receiver) = oneshot::channel();
proxy.send_action(Action::Window(
runtime::window::Action::GetLatest(sender),
));
}
} }
}; };
P::Executor::block_on(create_compositor); runtime.spawn(create_compositor);
continue; match compositor_receiver
.await
.expect("Wait for compositor")
{
Ok(new_compositor) => {
compositor = Some(new_compositor);
}
Err(error) => {
let _ = control_sender
.start_send(Control::Crash(error.into()));
break;
}
}
} }
let window = window_manager.insert( let window = window_manager.insert(