Replace Command with a new Task API with chain support

This commit is contained in:
Héctor Ramón Jiménez 2024-06-14 01:47:39 +02:00
parent e6d0b3bda5
commit a25b1af456
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
74 changed files with 1351 additions and 1767 deletions

View file

@ -10,7 +10,6 @@ use crate::{
Widget, Widget,
}; };
use std::any::Any;
use std::borrow::Borrow; use std::borrow::Borrow;
/// A generic [`Widget`]. /// A generic [`Widget`].
@ -305,63 +304,9 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<B>, operation: &mut dyn widget::Operation<()>,
) { ) {
struct MapOperation<'a, B> { self.widget.operate(tree, layout, renderer, operation);
operation: &'a mut dyn widget::Operation<B>,
}
impl<'a, T, B> widget::Operation<T> for MapOperation<'a, B> {
fn container(
&mut self,
id: Option<&widget::Id>,
bounds: Rectangle,
operate_on_children: &mut dyn FnMut(
&mut dyn widget::Operation<T>,
),
) {
self.operation.container(id, bounds, &mut |operation| {
operate_on_children(&mut MapOperation { operation });
});
}
fn focusable(
&mut self,
state: &mut dyn widget::operation::Focusable,
id: Option<&widget::Id>,
) {
self.operation.focusable(state, id);
}
fn scrollable(
&mut self,
state: &mut dyn widget::operation::Scrollable,
id: Option<&widget::Id>,
bounds: Rectangle,
translation: Vector,
) {
self.operation.scrollable(state, id, bounds, translation);
}
fn text_input(
&mut self,
state: &mut dyn widget::operation::TextInput,
id: Option<&widget::Id>,
) {
self.operation.text_input(state, id);
}
fn custom(&mut self, state: &mut dyn Any, id: Option<&widget::Id>) {
self.operation.custom(state, id);
}
}
self.widget.operate(
tree,
layout,
renderer,
&mut MapOperation { operation },
);
} }
fn on_event( fn on_event(
@ -495,7 +440,7 @@ where
state: &mut Tree, state: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
self.element self.element
.widget .widget

View file

@ -35,6 +35,7 @@ mod color;
mod content_fit; mod content_fit;
mod element; mod element;
mod length; mod length;
mod maybe;
mod padding; mod padding;
mod pixels; mod pixels;
mod point; mod point;
@ -59,6 +60,7 @@ pub use font::Font;
pub use gradient::Gradient; pub use gradient::Gradient;
pub use layout::Layout; pub use layout::Layout;
pub use length::Length; pub use length::Length;
pub use maybe::{MaybeSend, MaybeSync};
pub use overlay::Overlay; pub use overlay::Overlay;
pub use padding::Padding; pub use padding::Padding;
pub use pixels::Pixels; pub use pixels::Pixels;

View file

@ -41,7 +41,7 @@ where
&mut self, &mut self,
_layout: Layout<'_>, _layout: Layout<'_>,
_renderer: &Renderer, _renderer: &Renderer,
_operation: &mut dyn widget::Operation<Message>, _operation: &mut dyn widget::Operation<()>,
) { ) {
} }

View file

@ -5,9 +5,7 @@ use crate::layout;
use crate::mouse; use crate::mouse;
use crate::renderer; use crate::renderer;
use crate::widget; use crate::widget;
use crate::{Clipboard, Layout, Point, Rectangle, Shell, Size, Vector}; use crate::{Clipboard, Layout, Point, Rectangle, Shell, Size};
use std::any::Any;
/// A generic [`Overlay`]. /// A generic [`Overlay`].
#[allow(missing_debug_implementations)] #[allow(missing_debug_implementations)]
@ -94,7 +92,7 @@ where
&mut self, &mut self,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
self.overlay.operate(layout, renderer, operation); self.overlay.operate(layout, renderer, operation);
} }
@ -146,59 +144,9 @@ where
&mut self, &mut self,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<B>, operation: &mut dyn widget::Operation<()>,
) { ) {
struct MapOperation<'a, B> { self.content.operate(layout, renderer, operation);
operation: &'a mut dyn widget::Operation<B>,
}
impl<'a, T, B> widget::Operation<T> for MapOperation<'a, B> {
fn container(
&mut self,
id: Option<&widget::Id>,
bounds: Rectangle,
operate_on_children: &mut dyn FnMut(
&mut dyn widget::Operation<T>,
),
) {
self.operation.container(id, bounds, &mut |operation| {
operate_on_children(&mut MapOperation { operation });
});
}
fn focusable(
&mut self,
state: &mut dyn widget::operation::Focusable,
id: Option<&widget::Id>,
) {
self.operation.focusable(state, id);
}
fn scrollable(
&mut self,
state: &mut dyn widget::operation::Scrollable,
id: Option<&widget::Id>,
bounds: Rectangle,
translation: Vector,
) {
self.operation.scrollable(state, id, bounds, translation);
}
fn text_input(
&mut self,
state: &mut dyn widget::operation::TextInput,
id: Option<&widget::Id>,
) {
self.operation.text_input(state, id);
}
fn custom(&mut self, state: &mut dyn Any, id: Option<&widget::Id>) {
self.operation.custom(state, id);
}
}
self.content
.operate(layout, renderer, &mut MapOperation { operation });
} }
fn on_event( fn on_event(

View file

@ -132,7 +132,7 @@ where
&mut self, &mut self,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
operation.container(None, layout.bounds(), &mut |operation| { operation.container(None, layout.bounds(), &mut |operation| {
self.children.iter_mut().zip(layout.children()).for_each( self.children.iter_mut().zip(layout.children()).for_each(

View file

@ -105,7 +105,7 @@ where
_state: &mut Tree, _state: &mut Tree,
_layout: Layout<'_>, _layout: Layout<'_>,
_renderer: &Renderer, _renderer: &Renderer,
_operation: &mut dyn Operation<Message>, _operation: &mut dyn Operation<()>,
) { ) {
} }

View file

@ -8,15 +8,15 @@ pub use scrollable::Scrollable;
pub use text_input::TextInput; pub use text_input::TextInput;
use crate::widget::Id; use crate::widget::Id;
use crate::{Rectangle, Vector}; use crate::{MaybeSend, Rectangle, Vector};
use std::any::Any; use std::any::Any;
use std::fmt; use std::fmt;
use std::rc::Rc; use std::sync::Arc;
/// A piece of logic that can traverse the widget tree of an application in /// A piece of logic that can traverse the widget tree of an application in
/// order to query or update some widget state. /// order to query or update some widget state.
pub trait Operation<T> { pub trait Operation<T>: MaybeSend {
/// Operates on a widget that contains other widgets. /// Operates on a widget that contains other widgets.
/// ///
/// The `operate_on_children` function can be called to return control to /// The `operate_on_children` function can be called to return control to
@ -81,7 +81,7 @@ where
/// Maps the output of an [`Operation`] using the given function. /// Maps the output of an [`Operation`] using the given function.
pub fn map<A, B>( pub fn map<A, B>(
operation: Box<dyn Operation<A>>, operation: Box<dyn Operation<A>>,
f: impl Fn(A) -> B + 'static, f: impl Fn(A) -> B + Send + Sync + 'static,
) -> impl Operation<B> ) -> impl Operation<B>
where where
A: 'static, A: 'static,
@ -90,7 +90,7 @@ where
#[allow(missing_debug_implementations)] #[allow(missing_debug_implementations)]
struct Map<A, B> { struct Map<A, B> {
operation: Box<dyn Operation<A>>, operation: Box<dyn Operation<A>>,
f: Rc<dyn Fn(A) -> B>, f: Arc<dyn Fn(A) -> B + Send + Sync>,
} }
impl<A, B> Operation<B> for Map<A, B> impl<A, B> Operation<B> for Map<A, B>
@ -197,7 +197,7 @@ where
Map { Map {
operation, operation,
f: Rc::new(f), f: Arc::new(f),
} }
} }

View file

@ -4,7 +4,7 @@ use iced::widget::{
button, column, container, horizontal_space, pick_list, row, text, button, column, container, horizontal_space, pick_list, row, text,
text_editor, tooltip, text_editor, tooltip,
}; };
use iced::{Alignment, Command, Element, Font, Length, Subscription, Theme}; use iced::{Alignment, Element, Font, Length, Subscription, Task, Theme};
use std::ffi; use std::ffi;
use std::io; use std::io;
@ -51,26 +51,26 @@ impl Editor {
} }
} }
fn load() -> Command<Message> { fn load() -> Task<Message> {
Command::perform( Task::perform(
load_file(format!("{}/src/main.rs", env!("CARGO_MANIFEST_DIR"))), load_file(format!("{}/src/main.rs", env!("CARGO_MANIFEST_DIR"))),
Message::FileOpened, Message::FileOpened,
) )
} }
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::ActionPerformed(action) => { Message::ActionPerformed(action) => {
self.is_dirty = self.is_dirty || action.is_edit(); self.is_dirty = self.is_dirty || action.is_edit();
self.content.perform(action); self.content.perform(action);
Command::none() Task::none()
} }
Message::ThemeSelected(theme) => { Message::ThemeSelected(theme) => {
self.theme = theme; self.theme = theme;
Command::none() Task::none()
} }
Message::NewFile => { Message::NewFile => {
if !self.is_loading { if !self.is_loading {
@ -78,15 +78,15 @@ impl Editor {
self.content = text_editor::Content::new(); self.content = text_editor::Content::new();
} }
Command::none() Task::none()
} }
Message::OpenFile => { Message::OpenFile => {
if self.is_loading { if self.is_loading {
Command::none() Task::none()
} else { } else {
self.is_loading = true; self.is_loading = true;
Command::perform(open_file(), Message::FileOpened) Task::perform(open_file(), Message::FileOpened)
} }
} }
Message::FileOpened(result) => { Message::FileOpened(result) => {
@ -98,15 +98,15 @@ impl Editor {
self.content = text_editor::Content::with_text(&contents); self.content = text_editor::Content::with_text(&contents);
} }
Command::none() Task::none()
} }
Message::SaveFile => { Message::SaveFile => {
if self.is_loading { if self.is_loading {
Command::none() Task::none()
} else { } else {
self.is_loading = true; self.is_loading = true;
Command::perform( Task::perform(
save_file(self.file.clone(), self.content.text()), save_file(self.file.clone(), self.content.text()),
Message::FileSaved, Message::FileSaved,
) )
@ -120,7 +120,7 @@ impl Editor {
self.is_dirty = false; self.is_dirty = false;
} }
Command::none() Task::none()
} }
} }
} }

View file

@ -2,7 +2,7 @@ use iced::alignment;
use iced::event::{self, Event}; use iced::event::{self, Event};
use iced::widget::{button, center, checkbox, text, Column}; use iced::widget::{button, center, checkbox, text, Column};
use iced::window; use iced::window;
use iced::{Alignment, Command, Element, Length, Subscription}; use iced::{Alignment, Element, Length, Subscription, Task};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::program("Events - Iced", Events::update, Events::view) iced::program("Events - Iced", Events::update, Events::view)
@ -25,7 +25,7 @@ enum Message {
} }
impl Events { impl Events {
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::EventOccurred(event) if self.enabled => { Message::EventOccurred(event) if self.enabled => {
self.last.push(event); self.last.push(event);
@ -34,19 +34,19 @@ impl Events {
let _ = self.last.remove(0); let _ = self.last.remove(0);
} }
Command::none() Task::none()
} }
Message::EventOccurred(event) => { Message::EventOccurred(event) => {
if let Event::Window(window::Event::CloseRequested) = event { if let Event::Window(window::Event::CloseRequested) = event {
window::close(window::Id::MAIN) window::close(window::Id::MAIN)
} else { } else {
Command::none() Task::none()
} }
} }
Message::Toggled(enabled) => { Message::Toggled(enabled) => {
self.enabled = enabled; self.enabled = enabled;
Command::none() Task::none()
} }
Message::Exit => window::close(window::Id::MAIN), Message::Exit => window::close(window::Id::MAIN),
} }

View file

@ -1,6 +1,6 @@
use iced::widget::{button, center, column}; use iced::widget::{button, center, column};
use iced::window; use iced::window;
use iced::{Alignment, Command, Element}; use iced::{Alignment, Element, Task};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::program("Exit - Iced", Exit::update, Exit::view).run() iced::program("Exit - Iced", Exit::update, Exit::view).run()
@ -18,13 +18,13 @@ enum Message {
} }
impl Exit { impl Exit {
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::Confirm => window::close(window::Id::MAIN), Message::Confirm => window::close(window::Id::MAIN),
Message::Exit => { Message::Exit => {
self.show_confirm = true; self.show_confirm = true;
Command::none() Task::none()
} }
} }
} }

View file

@ -9,7 +9,7 @@ use iced::time;
use iced::widget::{ use iced::widget::{
button, checkbox, column, container, pick_list, row, slider, text, button, checkbox, column, container, pick_list, row, slider, text,
}; };
use iced::{Alignment, Command, Element, Length, Subscription, Theme}; use iced::{Alignment, Element, Length, Subscription, Task, Theme};
use std::time::Duration; use std::time::Duration;
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
@ -56,7 +56,7 @@ impl GameOfLife {
} }
} }
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::Grid(message, version) => { Message::Grid(message, version) => {
if version == self.version { if version == self.version {
@ -75,7 +75,7 @@ impl GameOfLife {
let version = self.version; let version = self.version;
return Command::perform(task, move |message| { return Task::perform(task, move |message| {
Message::Grid(message, version) Message::Grid(message, version)
}); });
} }
@ -103,7 +103,7 @@ impl GameOfLife {
} }
} }
Command::none() Task::none()
} }
fn subscription(&self) -> Subscription<Message> { fn subscription(&self) -> Subscription<Message> {

View file

@ -2,7 +2,7 @@ use iced_wgpu::Renderer;
use iced_widget::{column, container, row, slider, text, text_input}; use iced_widget::{column, container, row, slider, text, text_input};
use iced_winit::core::alignment; use iced_winit::core::alignment;
use iced_winit::core::{Color, Element, Length, Theme}; use iced_winit::core::{Color, Element, Length, Theme};
use iced_winit::runtime::{Command, Program}; use iced_winit::runtime::{Program, Task};
pub struct Controls { pub struct Controls {
background_color: Color, background_color: Color,
@ -33,7 +33,7 @@ impl Program for Controls {
type Message = Message; type Message = Message;
type Renderer = Renderer; type Renderer = Renderer;
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::BackgroundColorChanged(color) => { Message::BackgroundColorChanged(color) => {
self.background_color = color; self.background_color = color;
@ -43,7 +43,7 @@ impl Program for Controls {
} }
} }
Command::none() Task::none()
} }
fn view(&self) -> Element<Message, Theme, Renderer> { fn view(&self) -> Element<Message, Theme, Renderer> {

View file

@ -119,10 +119,7 @@ impl Builder {
fn point(p: impl Into<Point>) -> lyon_algorithms::geom::Point<f32> { fn point(p: impl Into<Point>) -> lyon_algorithms::geom::Point<f32> {
let p: Point = p.into(); let p: Point = p.into();
lyon_algorithms::geom::point( lyon_algorithms::geom::point(p.x.clamp(0.0, 1.0), p.y.clamp(0.0, 1.0))
p.x.min(1.0).max(0.0),
p.y.min(1.0).max(0.0),
)
} }
} }

View file

@ -5,7 +5,7 @@ use iced::widget::{
self, button, center, column, container, horizontal_space, mouse_area, self, button, center, column, container, horizontal_space, mouse_area,
opaque, pick_list, row, stack, text, text_input, opaque, pick_list, row, stack, text, text_input,
}; };
use iced::{Alignment, Color, Command, Element, Length, Subscription}; use iced::{Alignment, Color, Element, Length, Subscription, Task};
use std::fmt; use std::fmt;
@ -39,7 +39,7 @@ impl App {
event::listen().map(Message::Event) event::listen().map(Message::Event)
} }
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::ShowModal => { Message::ShowModal => {
self.show_modal = true; self.show_modal = true;
@ -47,26 +47,26 @@ impl App {
} }
Message::HideModal => { Message::HideModal => {
self.hide_modal(); self.hide_modal();
Command::none() Task::none()
} }
Message::Email(email) => { Message::Email(email) => {
self.email = email; self.email = email;
Command::none() Task::none()
} }
Message::Password(password) => { Message::Password(password) => {
self.password = password; self.password = password;
Command::none() Task::none()
} }
Message::Plan(plan) => { Message::Plan(plan) => {
self.plan = plan; self.plan = plan;
Command::none() Task::none()
} }
Message::Submit => { Message::Submit => {
if !self.email.is_empty() && !self.password.is_empty() { if !self.email.is_empty() && !self.password.is_empty() {
self.hide_modal(); self.hide_modal();
} }
Command::none() Task::none()
} }
Message::Event(event) => match event { Message::Event(event) => match event {
Event::Keyboard(keyboard::Event::KeyPressed { Event::Keyboard(keyboard::Event::KeyPressed {
@ -85,9 +85,9 @@ impl App {
.. ..
}) => { }) => {
self.hide_modal(); self.hide_modal();
Command::none() Task::none()
} }
_ => Command::none(), _ => Task::none(),
}, },
} }
} }

View file

@ -6,7 +6,7 @@ use iced::widget::{
}; };
use iced::window; use iced::window;
use iced::{ use iced::{
Alignment, Command, Element, Length, Point, Settings, Subscription, Theme, Alignment, Element, Length, Point, Settings, Subscription, Task, Theme,
Vector, Vector,
}; };
@ -48,13 +48,13 @@ impl multi_window::Application for Example {
type Theme = Theme; type Theme = Theme;
type Flags = (); type Flags = ();
fn new(_flags: ()) -> (Self, Command<Message>) { fn new(_flags: ()) -> (Self, Task<Message>) {
( (
Example { Example {
windows: HashMap::from([(window::Id::MAIN, Window::new(1))]), windows: HashMap::from([(window::Id::MAIN, Window::new(1))]),
next_window_pos: window::Position::Default, next_window_pos: window::Position::Default,
}, },
Command::none(), Task::none(),
) )
} }
@ -65,14 +65,14 @@ impl multi_window::Application for Example {
.unwrap_or("Example".to_string()) .unwrap_or("Example".to_string())
} }
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::ScaleInputChanged(id, scale) => { Message::ScaleInputChanged(id, scale) => {
let window = let window =
self.windows.get_mut(&id).expect("Window not found!"); self.windows.get_mut(&id).expect("Window not found!");
window.scale_input = scale; window.scale_input = scale;
Command::none() Task::none()
} }
Message::ScaleChanged(id, scale) => { Message::ScaleChanged(id, scale) => {
let window = let window =
@ -83,7 +83,7 @@ impl multi_window::Application for Example {
.unwrap_or(window.current_scale) .unwrap_or(window.current_scale)
.clamp(0.5, 5.0); .clamp(0.5, 5.0);
Command::none() Task::none()
} }
Message::TitleChanged(id, title) => { Message::TitleChanged(id, title) => {
let window = let window =
@ -91,12 +91,12 @@ impl multi_window::Application for Example {
window.title = title; window.title = title;
Command::none() Task::none()
} }
Message::CloseWindow(id) => window::close(id), Message::CloseWindow(id) => window::close(id),
Message::WindowClosed(id) => { Message::WindowClosed(id) => {
self.windows.remove(&id); self.windows.remove(&id);
Command::none() Task::none()
} }
Message::WindowOpened(id, position) => { Message::WindowOpened(id, position) => {
if let Some(position) = position { if let Some(position) = position {
@ -108,13 +108,13 @@ impl multi_window::Application for Example {
if let Some(window) = self.windows.get(&id) { if let Some(window) = self.windows.get(&id) {
text_input::focus(window.input_id.clone()) text_input::focus(window.input_id.clone())
} else { } else {
Command::none() Task::none()
} }
} }
Message::NewWindow => { Message::NewWindow => {
let count = self.windows.len() + 1; let count = self.windows.len() + 1;
let (id, spawn_window) = window::spawn(window::Settings { let (id, spawn_window) = window::open(window::Settings {
position: self.next_window_pos, position: self.next_window_pos,
exit_on_close_request: count % 2 == 0, exit_on_close_request: count % 2 == 0,
..Default::default() ..Default::default()

View file

@ -1,6 +1,6 @@
use iced::futures; use iced::futures;
use iced::widget::{self, center, column, image, row, text}; use iced::widget::{self, center, column, image, row, text};
use iced::{Alignment, Command, Element, Length}; use iced::{Alignment, Element, Length, Task};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::program(Pokedex::title, Pokedex::update, Pokedex::view) iced::program(Pokedex::title, Pokedex::update, Pokedex::view)
@ -25,8 +25,8 @@ enum Message {
} }
impl Pokedex { impl Pokedex {
fn search() -> Command<Message> { fn search() -> Task<Message> {
Command::perform(Pokemon::search(), Message::PokemonFound) Task::perform(Pokemon::search(), Message::PokemonFound)
} }
fn title(&self) -> String { fn title(&self) -> String {
@ -39,20 +39,20 @@ impl Pokedex {
format!("{subtitle} - Pokédex") format!("{subtitle} - Pokédex")
} }
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::PokemonFound(Ok(pokemon)) => { Message::PokemonFound(Ok(pokemon)) => {
*self = Pokedex::Loaded { pokemon }; *self = Pokedex::Loaded { pokemon };
Command::none() Task::none()
} }
Message::PokemonFound(Err(_error)) => { Message::PokemonFound(Err(_error)) => {
*self = Pokedex::Errored; *self = Pokedex::Errored;
Command::none() Task::none()
} }
Message::Search => match self { Message::Search => match self {
Pokedex::Loading => Command::none(), Pokedex::Loading => Task::none(),
_ => { _ => {
*self = Pokedex::Loading; *self = Pokedex::Loading;

View file

@ -4,7 +4,7 @@ use iced::widget::{button, column, container, image, row, text, text_input};
use iced::window; use iced::window;
use iced::window::screenshot::{self, Screenshot}; use iced::window::screenshot::{self, Screenshot};
use iced::{ use iced::{
Alignment, Command, ContentFit, Element, Length, Rectangle, Subscription, Alignment, ContentFit, Element, Length, Rectangle, Subscription, Task,
}; };
use ::image as img; use ::image as img;
@ -44,13 +44,11 @@ enum Message {
} }
impl Example { impl Example {
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::Screenshot => { Message::Screenshot => {
return iced::window::screenshot( return iced::window::screenshot(window::Id::MAIN)
window::Id::MAIN, .map(Message::ScreenshotData);
Message::ScreenshotData,
);
} }
Message::ScreenshotData(screenshot) => { Message::ScreenshotData(screenshot) => {
self.screenshot = Some(screenshot); self.screenshot = Some(screenshot);
@ -59,7 +57,7 @@ impl Example {
if let Some(screenshot) = &self.screenshot { if let Some(screenshot) = &self.screenshot {
self.png_saving = true; self.png_saving = true;
return Command::perform( return Task::perform(
save_to_png(screenshot.clone()), save_to_png(screenshot.clone()),
Message::PngSaved, Message::PngSaved,
); );
@ -103,7 +101,7 @@ impl Example {
} }
} }
Command::none() Task::none()
} }
fn view(&self) -> Element<'_, Message> { fn view(&self) -> Element<'_, Message> {

View file

@ -3,7 +3,7 @@ use iced::widget::{
button, column, container, horizontal_space, progress_bar, radio, row, button, column, container, horizontal_space, progress_bar, radio, row,
scrollable, slider, text, vertical_space, Scrollable, scrollable, slider, text, vertical_space, Scrollable,
}; };
use iced::{Alignment, Border, Color, Command, Element, Length, Theme}; use iced::{Alignment, Border, Color, Element, Length, Task, Theme};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -59,7 +59,7 @@ impl ScrollableDemo {
} }
} }
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::SwitchDirection(direction) => { Message::SwitchDirection(direction) => {
self.current_scroll_offset = scrollable::RelativeOffset::START; self.current_scroll_offset = scrollable::RelativeOffset::START;
@ -82,17 +82,17 @@ impl ScrollableDemo {
Message::ScrollbarWidthChanged(width) => { Message::ScrollbarWidthChanged(width) => {
self.scrollbar_width = width; self.scrollbar_width = width;
Command::none() Task::none()
} }
Message::ScrollbarMarginChanged(margin) => { Message::ScrollbarMarginChanged(margin) => {
self.scrollbar_margin = margin; self.scrollbar_margin = margin;
Command::none() Task::none()
} }
Message::ScrollerWidthChanged(width) => { Message::ScrollerWidthChanged(width) => {
self.scroller_width = width; self.scroller_width = width;
Command::none() Task::none()
} }
Message::ScrollToBeginning => { Message::ScrollToBeginning => {
self.current_scroll_offset = scrollable::RelativeOffset::START; self.current_scroll_offset = scrollable::RelativeOffset::START;
@ -113,7 +113,7 @@ impl ScrollableDemo {
Message::Scrolled(viewport) => { Message::Scrolled(viewport) => {
self.current_scroll_offset = viewport.relative_offset(); self.current_scroll_offset = viewport.relative_offset();
Command::none() Task::none()
} }
} }
} }

View file

@ -1,5 +1,5 @@
use iced::widget::{button, center, column, text}; use iced::widget::{button, center, column, text};
use iced::{system, Command, Element}; use iced::{system, Element, Task};
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
iced::program("System Information - Iced", Example::update, Example::view) iced::program("System Information - Iced", Example::update, Example::view)
@ -24,19 +24,20 @@ enum Message {
} }
impl Example { impl Example {
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::Refresh => { Message::Refresh => {
*self = Self::Loading; *self = Self::Loading;
return system::fetch_information(Message::InformationReceived); return system::fetch_information()
.map(Message::InformationReceived);
} }
Message::InformationReceived(information) => { Message::InformationReceived(information) => {
*self = Self::Loaded { information }; *self = Self::Loaded { information };
} }
} }
Command::none() Task::none()
} }
fn view(&self) -> Element<Message> { fn view(&self) -> Element<Message> {

View file

@ -4,7 +4,7 @@ use iced::keyboard::key;
use iced::widget::{ use iced::widget::{
self, button, center, column, pick_list, row, slider, text, text_input, self, button, center, column, pick_list, row, slider, text, text_input,
}; };
use iced::{Alignment, Command, Element, Length, Subscription}; use iced::{Alignment, Element, Length, Subscription, Task};
use toast::{Status, Toast}; use toast::{Status, Toast};
@ -49,7 +49,7 @@ impl App {
event::listen().map(Message::Event) event::listen().map(Message::Event)
} }
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::Add => { Message::Add => {
if !self.editing.title.is_empty() if !self.editing.title.is_empty()
@ -57,27 +57,27 @@ impl App {
{ {
self.toasts.push(std::mem::take(&mut self.editing)); self.toasts.push(std::mem::take(&mut self.editing));
} }
Command::none() Task::none()
} }
Message::Close(index) => { Message::Close(index) => {
self.toasts.remove(index); self.toasts.remove(index);
Command::none() Task::none()
} }
Message::Title(title) => { Message::Title(title) => {
self.editing.title = title; self.editing.title = title;
Command::none() Task::none()
} }
Message::Body(body) => { Message::Body(body) => {
self.editing.body = body; self.editing.body = body;
Command::none() Task::none()
} }
Message::Status(status) => { Message::Status(status) => {
self.editing.status = status; self.editing.status = status;
Command::none() Task::none()
} }
Message::Timeout(timeout) => { Message::Timeout(timeout) => {
self.timeout_secs = timeout as u64; self.timeout_secs = timeout as u64;
Command::none() Task::none()
} }
Message::Event(Event::Keyboard(keyboard::Event::KeyPressed { Message::Event(Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Named(key::Named::Tab), key: keyboard::Key::Named(key::Named::Tab),
@ -88,7 +88,7 @@ impl App {
key: keyboard::Key::Named(key::Named::Tab), key: keyboard::Key::Named(key::Named::Tab),
.. ..
})) => widget::focus_next(), })) => widget::focus_next(),
Message::Event(_) => Command::none(), Message::Event(_) => Task::none(),
} }
} }
@ -347,7 +347,7 @@ mod toast {
state: &mut Tree, state: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
operation.container(None, layout.bounds(), &mut |operation| { operation.container(None, layout.bounds(), &mut |operation| {
self.content.as_widget().operate( self.content.as_widget().operate(
@ -589,7 +589,7 @@ mod toast {
&mut self, &mut self,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
operation.container(None, layout.bounds(), &mut |operation| { operation.container(None, layout.bounds(), &mut |operation| {
self.toasts self.toasts

View file

@ -5,7 +5,7 @@ use iced::widget::{
scrollable, text, text_input, Text, scrollable, text, text_input, Text,
}; };
use iced::window; use iced::window;
use iced::{Command, Element, Font, Length, Subscription}; use iced::{Element, Font, Length, Subscription, Task as Command};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};

View file

@ -5,8 +5,8 @@ use iced::widget::{
}; };
use iced::window; use iced::window;
use iced::{ use iced::{
Alignment, Color, Command, Element, Font, Length, Point, Rectangle, Alignment, Color, Element, Font, Length, Point, Rectangle, Subscription,
Subscription, Theme, Task, Theme,
}; };
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
@ -33,14 +33,14 @@ enum Message {
} }
impl Example { impl Example {
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::MouseMoved(position) => { Message::MouseMoved(position) => {
self.mouse_position = Some(position); self.mouse_position = Some(position);
Command::none() Task::none()
} }
Message::Scrolled | Message::WindowResized => Command::batch(vec![ Message::Scrolled | Message::WindowResized => Task::batch(vec![
container::visible_bounds(OUTER_CONTAINER.clone()) container::visible_bounds(OUTER_CONTAINER.clone())
.map(Message::OuterBoundsFetched), .map(Message::OuterBoundsFetched),
container::visible_bounds(INNER_CONTAINER.clone()) container::visible_bounds(INNER_CONTAINER.clone())
@ -49,12 +49,12 @@ impl Example {
Message::OuterBoundsFetched(outer_bounds) => { Message::OuterBoundsFetched(outer_bounds) => {
self.outer_bounds = outer_bounds; self.outer_bounds = outer_bounds;
Command::none() Task::none()
} }
Message::InnerBoundsFetched(inner_bounds) => { Message::InnerBoundsFetched(inner_bounds) => {
self.inner_bounds = inner_bounds; self.inner_bounds = inner_bounds;
Command::none() Task::none()
} }
} }
} }

View file

@ -4,7 +4,7 @@ use iced::alignment::{self, Alignment};
use iced::widget::{ use iced::widget::{
self, button, center, column, row, scrollable, text, text_input, self, button, center, column, row, scrollable, text, text_input,
}; };
use iced::{color, Command, Element, Length, Subscription}; use iced::{color, Element, Length, Subscription, Task};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
pub fn main() -> iced::Result { pub fn main() -> iced::Result {
@ -30,19 +30,19 @@ enum Message {
} }
impl WebSocket { impl WebSocket {
fn load() -> Command<Message> { fn load() -> Task<Message> {
Command::batch([ Task::batch([
Command::perform(echo::server::run(), |_| Message::Server), Task::perform(echo::server::run(), |_| Message::Server),
widget::focus_next(), widget::focus_next(),
]) ])
} }
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Task<Message> {
match message { match message {
Message::NewMessageChanged(new_message) => { Message::NewMessageChanged(new_message) => {
self.new_message = new_message; self.new_message = new_message;
Command::none() Task::none()
} }
Message::Send(message) => match &mut self.state { Message::Send(message) => match &mut self.state {
State::Connected(connection) => { State::Connected(connection) => {
@ -50,9 +50,9 @@ impl WebSocket {
connection.send(message); connection.send(message);
Command::none() Task::none()
} }
State::Disconnected => Command::none(), State::Disconnected => Task::none(),
}, },
Message::Echo(event) => match event { Message::Echo(event) => match event {
echo::Event::Connected(connection) => { echo::Event::Connected(connection) => {
@ -60,14 +60,14 @@ impl WebSocket {
self.messages.push(echo::Message::connected()); self.messages.push(echo::Message::connected());
Command::none() Task::none()
} }
echo::Event::Disconnected => { echo::Event::Disconnected => {
self.state = State::Disconnected; self.state = State::Disconnected;
self.messages.push(echo::Message::disconnected()); self.messages.push(echo::Message::disconnected());
Command::none() Task::none()
} }
echo::Event::MessageReceived(message) => { echo::Event::MessageReceived(message) => {
self.messages.push(message); self.messages.push(message);
@ -78,7 +78,7 @@ impl WebSocket {
) )
} }
}, },
Message::Server => Command::none(), Message::Server => Task::none(),
} }
} }

View file

@ -1,8 +1,8 @@
//! Listen to runtime events. //! Listen to runtime events.
use crate::core::event::{self, Event}; use crate::core::event::{self, Event};
use crate::core::window; use crate::core::window;
use crate::core::MaybeSend;
use crate::subscription::{self, Subscription}; use crate::subscription::{self, Subscription};
use crate::MaybeSend;
/// Returns a [`Subscription`] to all the ignored runtime events. /// Returns a [`Subscription`] to all the ignored runtime events.
/// ///

View file

@ -1,5 +1,5 @@
//! Choose your preferred executor to power a runtime. //! Choose your preferred executor to power a runtime.
use crate::MaybeSend; use crate::core::MaybeSend;
use futures::Future; use futures::Future;
/// A type that can run futures. /// A type that can run futures.

View file

@ -2,8 +2,8 @@
use crate::core; use crate::core;
use crate::core::event; use crate::core::event;
use crate::core::keyboard::{Event, Key, Modifiers}; use crate::core::keyboard::{Event, Key, Modifiers};
use crate::core::MaybeSend;
use crate::subscription::{self, Subscription}; use crate::subscription::{self, Subscription};
use crate::MaybeSend;
/// Listens to keyboard key presses and calls the given function /// Listens to keyboard key presses and calls the given function
/// map them into actual messages. /// map them into actual messages.

View file

@ -8,7 +8,6 @@
pub use futures; pub use futures;
pub use iced_core as core; pub use iced_core as core;
mod maybe;
mod runtime; mod runtime;
pub mod backend; pub mod backend;
@ -18,7 +17,6 @@ pub mod keyboard;
pub mod subscription; pub mod subscription;
pub use executor::Executor; pub use executor::Executor;
pub use maybe::{MaybeSend, MaybeSync};
pub use platform::*; pub use platform::*;
pub use runtime::Runtime; pub use runtime::Runtime;
pub use subscription::Subscription; pub use subscription::Subscription;

View file

@ -1,6 +1,7 @@
//! Run commands and keep track of subscriptions. //! Run commands and keep track of subscriptions.
use crate::core::MaybeSend;
use crate::subscription; use crate::subscription;
use crate::{BoxFuture, BoxStream, Executor, MaybeSend}; use crate::{BoxFuture, BoxStream, Executor};
use futures::{channel::mpsc, Sink}; use futures::{channel::mpsc, Sink};
use std::marker::PhantomData; use std::marker::PhantomData;

View file

@ -5,8 +5,9 @@ pub use tracker::Tracker;
use crate::core::event; use crate::core::event;
use crate::core::window; use crate::core::window;
use crate::core::MaybeSend;
use crate::futures::{Future, Stream}; use crate::futures::{Future, Stream};
use crate::{BoxStream, MaybeSend}; use crate::BoxStream;
use futures::channel::mpsc; use futures::channel::mpsc;
use futures::never::Never; use futures::never::Never;

View file

@ -1,5 +1,6 @@
use crate::core::MaybeSend;
use crate::subscription::{Event, Hasher, Recipe}; use crate::subscription::{Event, Hasher, Recipe};
use crate::{BoxFuture, MaybeSend}; use crate::BoxFuture;
use futures::channel::mpsc; use futures::channel::mpsc;
use futures::sink::{Sink, SinkExt}; use futures::sink::{Sink, SinkExt};

View file

@ -1,7 +1,6 @@
//! A compositor is responsible for initializing a renderer and managing window //! A compositor is responsible for initializing a renderer and managing window
//! surfaces. //! surfaces.
use crate::core::Color; use crate::core::{Color, MaybeSend, MaybeSync};
use crate::futures::{MaybeSend, MaybeSync};
use crate::{Error, Settings, Viewport}; use crate::{Error, Settings, Viewport};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle}; use raw_window_handle::{HasDisplayHandle, HasWindowHandle};

View file

@ -1,80 +1,62 @@
//! Access the clipboard. //! Access the clipboard.
use crate::command::{self, Command};
use crate::core::clipboard::Kind; use crate::core::clipboard::Kind;
use crate::futures::MaybeSend; use crate::futures::futures::channel::oneshot;
use crate::Task;
use std::fmt; /// A clipboard action to be performed by some [`Task`].
/// A clipboard action to be performed by some [`Command`].
/// ///
/// [`Command`]: crate::Command /// [`Task`]: crate::Task
pub enum Action<T> { #[derive(Debug)]
pub enum Action {
/// Read the clipboard and produce `T` with the result. /// Read the clipboard and produce `T` with the result.
Read(Box<dyn Fn(Option<String>) -> T>, Kind), Read {
/// The clipboard target.
target: Kind,
/// The channel to send the read contents.
channel: oneshot::Sender<Option<String>>,
},
/// Write the given contents to the clipboard. /// Write the given contents to the clipboard.
Write(String, Kind), Write {
} /// The clipboard target.
target: Kind,
impl<T> Action<T> { /// The contents to be written.
/// Maps the output of a clipboard [`Action`] using the provided closure. contents: String,
pub fn map<A>( },
self,
f: impl Fn(T) -> A + 'static + MaybeSend + Sync,
) -> Action<A>
where
T: 'static,
{
match self {
Self::Read(o, target) => {
Action::Read(Box::new(move |s| f(o(s))), target)
}
Self::Write(content, target) => Action::Write(content, target),
}
}
}
impl<T> fmt::Debug for Action<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Read(_, target) => write!(f, "Action::Read{target:?}"),
Self::Write(_, target) => write!(f, "Action::Write({target:?})"),
}
}
} }
/// Read the current contents of the clipboard. /// Read the current contents of the clipboard.
pub fn read<Message>( pub fn read() -> Task<Option<String>> {
f: impl Fn(Option<String>) -> Message + 'static, Task::oneshot(|channel| {
) -> Command<Message> { crate::Action::Clipboard(Action::Read {
Command::single(command::Action::Clipboard(Action::Read( target: Kind::Standard,
Box::new(f), channel,
Kind::Standard, })
))) })
} }
/// Read the current contents of the primary clipboard. /// Read the current contents of the primary clipboard.
pub fn read_primary<Message>( pub fn read_primary() -> Task<Option<String>> {
f: impl Fn(Option<String>) -> Message + 'static, Task::oneshot(|channel| {
) -> Command<Message> { crate::Action::Clipboard(Action::Read {
Command::single(command::Action::Clipboard(Action::Read( target: Kind::Primary,
Box::new(f), channel,
Kind::Primary, })
))) })
} }
/// Write the given contents to the clipboard. /// Write the given contents to the clipboard.
pub fn write<Message>(contents: String) -> Command<Message> { pub fn write<T>(contents: String) -> Task<T> {
Command::single(command::Action::Clipboard(Action::Write( Task::effect(crate::Action::Clipboard(Action::Write {
target: Kind::Standard,
contents, contents,
Kind::Standard, }))
)))
} }
/// Write the given contents to the primary clipboard. /// Write the given contents to the primary clipboard.
pub fn write_primary<Message>(contents: String) -> Command<Message> { pub fn write_primary<Message>(contents: String) -> Task<Message> {
Command::single(command::Action::Clipboard(Action::Write( Task::effect(crate::Action::Clipboard(Action::Write {
target: Kind::Primary,
contents, contents,
Kind::Primary, }))
)))
} }

View file

@ -1,147 +0,0 @@
//! Run asynchronous actions.
mod action;
pub use action::Action;
use crate::core::widget;
use crate::futures::futures;
use crate::futures::MaybeSend;
use futures::channel::mpsc;
use futures::Stream;
use std::fmt;
use std::future::Future;
/// A set of asynchronous actions to be performed by some runtime.
#[must_use = "`Command` must be returned to runtime to take effect"]
pub struct Command<T>(Internal<Action<T>>);
#[derive(Debug)]
enum Internal<T> {
None,
Single(T),
Batch(Vec<T>),
}
impl<T> Command<T> {
/// Creates an empty [`Command`].
///
/// In other words, a [`Command`] that does nothing.
pub const fn none() -> Self {
Self(Internal::None)
}
/// Creates a [`Command`] that performs a single [`Action`].
pub const fn single(action: Action<T>) -> Self {
Self(Internal::Single(action))
}
/// Creates a [`Command`] that performs a [`widget::Operation`].
pub fn widget(operation: impl widget::Operation<T> + 'static) -> Self {
Self::single(Action::Widget(Box::new(operation)))
}
/// Creates a [`Command`] that performs the action of the given future.
pub fn perform<A>(
future: impl Future<Output = A> + 'static + MaybeSend,
f: impl FnOnce(A) -> T + 'static + MaybeSend,
) -> Command<T> {
use futures::FutureExt;
Command::single(Action::Future(Box::pin(future.map(f))))
}
/// Creates a [`Command`] that runs the given stream to completion.
pub fn run<A>(
stream: impl Stream<Item = A> + 'static + MaybeSend,
f: impl Fn(A) -> T + 'static + MaybeSend,
) -> Command<T> {
use futures::StreamExt;
Command::single(Action::Stream(Box::pin(stream.map(f))))
}
/// Creates a [`Command`] that performs the actions of all the given
/// commands.
///
/// Once this command is run, all the commands will be executed at once.
pub fn batch(commands: impl IntoIterator<Item = Command<T>>) -> Self {
let mut batch = Vec::new();
for Command(command) in commands {
match command {
Internal::None => {}
Internal::Single(command) => batch.push(command),
Internal::Batch(commands) => batch.extend(commands),
}
}
Self(Internal::Batch(batch))
}
/// Applies a transformation to the result of a [`Command`].
pub fn map<A>(
self,
f: impl Fn(T) -> A + 'static + MaybeSend + Sync + Clone,
) -> Command<A>
where
T: 'static,
A: 'static,
{
match self.0 {
Internal::None => Command::none(),
Internal::Single(action) => Command::single(action.map(f)),
Internal::Batch(batch) => Command(Internal::Batch(
batch
.into_iter()
.map(|action| action.map(f.clone()))
.collect(),
)),
}
}
/// Returns all of the actions of the [`Command`].
pub fn actions(self) -> Vec<Action<T>> {
let Command(command) = self;
match command {
Internal::None => Vec::new(),
Internal::Single(action) => vec![action],
Internal::Batch(batch) => batch,
}
}
}
impl<Message> From<()> for Command<Message> {
fn from(_value: ()) -> Self {
Self::none()
}
}
impl<T> fmt::Debug for Command<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Command(command) = self;
command.fmt(f)
}
}
/// Creates a [`Command`] that produces the `Message`s published from a [`Future`]
/// to an [`mpsc::Sender`] with the given bounds.
pub fn channel<Fut, Message>(
size: usize,
f: impl FnOnce(mpsc::Sender<Message>) -> Fut + MaybeSend + 'static,
) -> Command<Message>
where
Fut: Future<Output = ()> + MaybeSend + 'static,
Message: 'static + MaybeSend,
{
use futures::future;
use futures::stream::{self, StreamExt};
let (sender, receiver) = mpsc::channel(size);
let runner = stream::once(f(sender)).filter_map(|_| future::ready(None));
Command::single(Action::Stream(Box::pin(stream::select(receiver, runner))))
}

View file

@ -1,100 +0,0 @@
use crate::clipboard;
use crate::core::widget;
use crate::font;
use crate::futures::MaybeSend;
use crate::system;
use crate::window;
use std::any::Any;
use std::borrow::Cow;
use std::fmt;
/// An action that a [`Command`] can perform.
///
/// [`Command`]: crate::Command
pub enum Action<T> {
/// Run a [`Future`] to completion.
///
/// [`Future`]: iced_futures::BoxFuture
Future(iced_futures::BoxFuture<T>),
/// Run a [`Stream`] to completion.
///
/// [`Stream`]: iced_futures::BoxStream
Stream(iced_futures::BoxStream<T>),
/// Run a clipboard action.
Clipboard(clipboard::Action<T>),
/// Run a window action.
Window(window::Action<T>),
/// Run a system action.
System(system::Action<T>),
/// Run a widget action.
Widget(Box<dyn widget::Operation<T>>),
/// Load a font from its bytes.
LoadFont {
/// The bytes of the font to load.
bytes: Cow<'static, [u8]>,
/// The message to produce when the font has been loaded.
tagger: Box<dyn Fn(Result<(), font::Error>) -> T>,
},
/// A custom action supported by a specific runtime.
Custom(Box<dyn Any>),
}
impl<T> Action<T> {
/// Applies a transformation to the result of a [`Command`].
///
/// [`Command`]: crate::Command
pub fn map<A>(
self,
f: impl Fn(T) -> A + 'static + MaybeSend + Sync,
) -> Action<A>
where
A: 'static,
T: 'static,
{
use iced_futures::futures::{FutureExt, StreamExt};
match self {
Self::Future(future) => Action::Future(Box::pin(future.map(f))),
Self::Stream(stream) => Action::Stream(Box::pin(stream.map(f))),
Self::Clipboard(action) => Action::Clipboard(action.map(f)),
Self::Window(window) => Action::Window(window.map(f)),
Self::System(system) => Action::System(system.map(f)),
Self::Widget(operation) => {
Action::Widget(Box::new(widget::operation::map(operation, f)))
}
Self::LoadFont { bytes, tagger } => Action::LoadFont {
bytes,
tagger: Box::new(move |result| f(tagger(result))),
},
Self::Custom(custom) => Action::Custom(custom),
}
}
}
impl<T> fmt::Debug for Action<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Future(_) => write!(f, "Action::Future"),
Self::Stream(_) => write!(f, "Action::Stream"),
Self::Clipboard(action) => {
write!(f, "Action::Clipboard({action:?})")
}
Self::Window(action) => {
write!(f, "Action::Window({action:?})")
}
Self::System(action) => write!(f, "Action::System({action:?})"),
Self::Widget(_action) => write!(f, "Action::Widget"),
Self::LoadFont { .. } => write!(f, "Action::LoadFont"),
Self::Custom(_) => write!(f, "Action::Custom"),
}
}
}

View file

@ -1,7 +1,5 @@
//! Load and use fonts. //! Load and use fonts.
pub use iced_core::font::*; use crate::{Action, Task};
use crate::command::{self, Command};
use std::borrow::Cow; use std::borrow::Cow;
/// An error while loading a font. /// An error while loading a font.
@ -9,11 +7,9 @@ use std::borrow::Cow;
pub enum Error {} pub enum Error {}
/// Load a font from its bytes. /// Load a font from its bytes.
pub fn load( pub fn load(bytes: impl Into<Cow<'static, [u8]>>) -> Task<Result<(), Error>> {
bytes: impl Into<Cow<'static, [u8]>>, Task::oneshot(|channel| Action::LoadFont {
) -> Command<Result<(), Error>> {
Command::single(command::Action::LoadFont {
bytes: bytes.into(), bytes: bytes.into(),
tagger: Box::new(std::convert::identity), channel,
}) })
} }

View file

@ -10,7 +10,6 @@
)] )]
#![cfg_attr(docsrs, feature(doc_auto_cfg))] #![cfg_attr(docsrs, feature(doc_auto_cfg))]
pub mod clipboard; pub mod clipboard;
pub mod command;
pub mod font; pub mod font;
pub mod keyboard; pub mod keyboard;
pub mod overlay; pub mod overlay;
@ -22,6 +21,8 @@ pub mod window;
#[cfg(feature = "multi-window")] #[cfg(feature = "multi-window")]
pub mod multi_window; pub mod multi_window;
mod task;
// 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")]
@ -34,8 +35,81 @@ mod debug;
pub use iced_core as core; pub use iced_core as core;
pub use iced_futures as futures; pub use iced_futures as futures;
pub use command::Command;
pub use debug::Debug; pub use debug::Debug;
pub use font::Font;
pub use program::Program; pub use program::Program;
pub use task::Task;
pub use user_interface::UserInterface; pub use user_interface::UserInterface;
use crate::core::widget;
use crate::futures::futures::channel::oneshot;
use std::borrow::Cow;
use std::fmt;
/// An action that the iced runtime can perform.
pub enum Action<T> {
/// Output some value.
Output(T),
/// Load a font from its bytes.
LoadFont {
/// The bytes of the font to load.
bytes: Cow<'static, [u8]>,
/// The channel to send back the load result.
channel: oneshot::Sender<Result<(), font::Error>>,
},
/// Run a widget operation.
Widget(Box<dyn widget::Operation<()> + Send>),
/// Run a clipboard action.
Clipboard(clipboard::Action),
/// Run a window action.
Window(window::Action),
/// Run a system action.
System(system::Action),
}
impl<T> Action<T> {
/// Creates a new [`Action::Widget`] with the given [`widget::Operation`].
pub fn widget(operation: impl widget::Operation<()> + 'static) -> Self {
Self::Widget(Box::new(operation))
}
fn output<O>(self) -> Result<T, Action<O>> {
match self {
Action::Output(output) => Ok(output),
Action::LoadFont { bytes, channel } => {
Err(Action::LoadFont { bytes, channel })
}
Action::Widget(operation) => Err(Action::Widget(operation)),
Action::Clipboard(action) => Err(Action::Clipboard(action)),
Action::Window(action) => Err(Action::Window(action)),
Action::System(action) => Err(Action::System(action)),
}
}
}
impl<T> fmt::Debug for Action<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Action::Output(output) => write!(f, "Action::Output({output:?})"),
Action::LoadFont { .. } => {
write!(f, "Action::LoadFont")
}
Action::Widget { .. } => {
write!(f, "Action::Widget")
}
Action::Clipboard(action) => {
write!(f, "Action::Clipboard({action:?})")
}
Action::Window(_) => write!(f, "Action::Window"),
Action::System(action) => write!(f, "Action::System({action:?})"),
}
}
}

View file

@ -2,7 +2,7 @@
use crate::core::text; use crate::core::text;
use crate::core::window; use crate::core::window;
use crate::core::{Element, Renderer}; use crate::core::{Element, Renderer};
use crate::Command; use crate::Task;
/// The core of a user interface for a multi-window application following The Elm Architecture. /// The core of a user interface for a multi-window application following The Elm Architecture.
pub trait Program: Sized { pub trait Program: Sized {
@ -21,9 +21,9 @@ pub trait Program: Sized {
/// produced by either user interactions or commands, will be handled by /// produced by either user interactions or commands, will be handled by
/// this method. /// this method.
/// ///
/// Any [`Command`] returned will be executed immediately in the /// Any [`Task`] returned will be executed immediately in the background by the
/// background by shells. /// runtime.
fn update(&mut self, message: Self::Message) -> Command<Self::Message>; fn update(&mut self, message: Self::Message) -> Task<Self::Message>;
/// Returns the widgets to display in the [`Program`] for the `window`. /// Returns the widgets to display in the [`Program`] for the `window`.
/// ///

View file

@ -5,7 +5,7 @@ use crate::core::renderer;
use crate::core::widget::operation::{self, Operation}; use crate::core::widget::operation::{self, Operation};
use crate::core::{Clipboard, Size}; use crate::core::{Clipboard, Size};
use crate::user_interface::{self, UserInterface}; use crate::user_interface::{self, UserInterface};
use crate::{Command, Debug, Program}; use crate::{Debug, Program, Task};
/// The execution state of a multi-window [`Program`]. It leverages caching, event /// The execution state of a multi-window [`Program`]. It leverages caching, event
/// processing, and rendering primitive storage. /// processing, and rendering primitive storage.
@ -85,7 +85,7 @@ where
/// the widgets of the linked [`Program`] if necessary. /// the widgets of the linked [`Program`] if necessary.
/// ///
/// Returns a list containing the instances of [`Event`] that were not /// Returns a list containing the instances of [`Event`] that were not
/// captured by any widget, and the [`Command`] obtained from [`Program`] /// captured by any widget, and the [`Task`] obtained from [`Program`]
/// after updating it, only if an update was necessary. /// after updating it, only if an update was necessary.
pub fn update( pub fn update(
&mut self, &mut self,
@ -96,7 +96,7 @@ where
style: &renderer::Style, style: &renderer::Style,
clipboard: &mut dyn Clipboard, clipboard: &mut dyn Clipboard,
debug: &mut Debug, debug: &mut Debug,
) -> (Vec<Event>, Option<Command<P::Message>>) { ) -> (Vec<Event>, Option<Task<P::Message>>) {
let mut user_interfaces = build_user_interfaces( let mut user_interfaces = build_user_interfaces(
&self.program, &self.program,
self.caches.take().unwrap(), self.caches.take().unwrap(),
@ -163,14 +163,14 @@ where
drop(user_interfaces); drop(user_interfaces);
let commands = Command::batch(messages.into_iter().map(|msg| { let commands = Task::batch(messages.into_iter().map(|msg| {
debug.log_message(&msg); debug.log_message(&msg);
debug.update_started(); debug.update_started();
let command = self.program.update(msg); let task = self.program.update(msg);
debug.update_finished(); debug.update_finished();
command task
})); }));
let mut user_interfaces = build_user_interfaces( let mut user_interfaces = build_user_interfaces(
@ -205,7 +205,7 @@ where
pub fn operate( pub fn operate(
&mut self, &mut self,
renderer: &mut P::Renderer, renderer: &mut P::Renderer,
operations: impl Iterator<Item = Box<dyn Operation<P::Message>>>, operations: impl Iterator<Item = Box<dyn Operation<()>>>,
bounds: Size, bounds: Size,
debug: &mut Debug, debug: &mut Debug,
) { ) {
@ -227,9 +227,7 @@ where
match operation.finish() { match operation.finish() {
operation::Outcome::None => {} operation::Outcome::None => {}
operation::Outcome::Some(message) => { operation::Outcome::Some(()) => {}
self.queued_messages.push(message);
}
operation::Outcome::Chain(next) => { operation::Outcome::Chain(next) => {
current_operation = Some(next); current_operation = Some(next);
} }

View file

@ -131,13 +131,13 @@ where
&mut self, &mut self,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
fn recurse<Message, Theme, Renderer>( fn recurse<Message, Theme, Renderer>(
element: &mut overlay::Element<'_, Message, Theme, Renderer>, element: &mut overlay::Element<'_, Message, Theme, Renderer>,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) where ) where
Renderer: renderer::Renderer, Renderer: renderer::Renderer,
{ {

View file

@ -1,5 +1,5 @@
//! Build interactive programs using The Elm Architecture. //! Build interactive programs using The Elm Architecture.
use crate::Command; use crate::Task;
use iced_core::text; use iced_core::text;
use iced_core::Element; use iced_core::Element;
@ -25,9 +25,9 @@ pub trait Program: Sized {
/// produced by either user interactions or commands, will be handled by /// produced by either user interactions or commands, will be handled by
/// this method. /// this method.
/// ///
/// Any [`Command`] returned will be executed immediately in the /// Any [`Task`] returned will be executed immediately in the
/// background by shells. /// background by shells.
fn update(&mut self, message: Self::Message) -> Command<Self::Message>; fn update(&mut self, message: Self::Message) -> Task<Self::Message>;
/// Returns the widgets to display in the [`Program`]. /// Returns the widgets to display in the [`Program`].
/// ///

View file

@ -4,7 +4,7 @@ use crate::core::renderer;
use crate::core::widget::operation::{self, Operation}; use crate::core::widget::operation::{self, Operation};
use crate::core::{Clipboard, Size}; use crate::core::{Clipboard, Size};
use crate::user_interface::{self, UserInterface}; use crate::user_interface::{self, UserInterface};
use crate::{Command, Debug, Program}; use crate::{Debug, Program, Task};
/// The execution state of a [`Program`]. It leverages caching, event /// The execution state of a [`Program`]. It leverages caching, event
/// processing, and rendering primitive storage. /// processing, and rendering primitive storage.
@ -84,7 +84,7 @@ where
/// the widgets of the linked [`Program`] if necessary. /// the widgets of the linked [`Program`] if necessary.
/// ///
/// Returns a list containing the instances of [`Event`] that were not /// Returns a list containing the instances of [`Event`] that were not
/// captured by any widget, and the [`Command`] obtained from [`Program`] /// captured by any widget, and the [`Task`] obtained from [`Program`]
/// after updating it, only if an update was necessary. /// after updating it, only if an update was necessary.
pub fn update( pub fn update(
&mut self, &mut self,
@ -95,7 +95,7 @@ where
style: &renderer::Style, style: &renderer::Style,
clipboard: &mut dyn Clipboard, clipboard: &mut dyn Clipboard,
debug: &mut Debug, debug: &mut Debug,
) -> (Vec<Event>, Option<Command<P::Message>>) { ) -> (Vec<Event>, Option<Task<P::Message>>) {
let mut user_interface = build_user_interface( let mut user_interface = build_user_interface(
&mut self.program, &mut self.program,
self.cache.take().unwrap(), self.cache.take().unwrap(),
@ -129,7 +129,7 @@ where
messages.append(&mut self.queued_messages); messages.append(&mut self.queued_messages);
debug.event_processing_finished(); debug.event_processing_finished();
let command = if messages.is_empty() { let task = if messages.is_empty() {
debug.draw_started(); debug.draw_started();
self.mouse_interaction = self.mouse_interaction =
user_interface.draw(renderer, theme, style, cursor); user_interface.draw(renderer, theme, style, cursor);
@ -143,15 +143,14 @@ where
// for now :^) // for now :^)
let temp_cache = user_interface.into_cache(); let temp_cache = user_interface.into_cache();
let commands = let tasks = Task::batch(messages.into_iter().map(|message| {
Command::batch(messages.into_iter().map(|message| {
debug.log_message(&message); debug.log_message(&message);
debug.update_started(); debug.update_started();
let command = self.program.update(message); let task = self.program.update(message);
debug.update_finished(); debug.update_finished();
command task
})); }));
let mut user_interface = build_user_interface( let mut user_interface = build_user_interface(
@ -169,17 +168,17 @@ where
self.cache = Some(user_interface.into_cache()); self.cache = Some(user_interface.into_cache());
Some(commands) Some(tasks)
}; };
(uncaptured_events, command) (uncaptured_events, task)
} }
/// Applies [`Operation`]s to the [`State`] /// Applies [`Operation`]s to the [`State`]
pub fn operate( pub fn operate(
&mut self, &mut self,
renderer: &mut P::Renderer, renderer: &mut P::Renderer,
operations: impl Iterator<Item = Box<dyn Operation<P::Message>>>, operations: impl Iterator<Item = Box<dyn Operation<()>>>,
bounds: Size, bounds: Size,
debug: &mut Debug, debug: &mut Debug,
) { ) {
@ -199,9 +198,7 @@ where
match operation.finish() { match operation.finish() {
operation::Outcome::None => {} operation::Outcome::None => {}
operation::Outcome::Some(message) => { operation::Outcome::Some(()) => {}
self.queued_messages.push(message);
}
operation::Outcome::Chain(next) => { operation::Outcome::Chain(next) => {
current_operation = Some(next); current_operation = Some(next);
} }

View file

@ -1,6 +1,39 @@
//! Access the native system. //! Access the native system.
mod action; use crate::futures::futures::channel::oneshot;
mod information;
pub use action::Action; /// An operation to be performed on the system.
pub use information::Information; #[derive(Debug)]
pub enum Action {
/// Query system information and produce `T` with the result.
QueryInformation(oneshot::Sender<Information>),
}
/// Contains informations about the system (e.g. system name, processor, memory, graphics adapter).
#[derive(Clone, Debug)]
pub struct Information {
/// The operating system name
pub system_name: Option<String>,
/// Operating system kernel version
pub system_kernel: Option<String>,
/// Long operating system version
///
/// Examples:
/// - MacOS 10.15 Catalina
/// - Windows 10 Pro
/// - Ubuntu 20.04 LTS (Focal Fossa)
pub system_version: Option<String>,
/// Short operating system version number
pub system_short_version: Option<String>,
/// Detailed processor model information
pub cpu_brand: String,
/// The number of physical cores on the processor
pub cpu_cores: Option<usize>,
/// Total RAM size, in bytes
pub memory_total: u64,
/// Memory used by this process, in bytes
pub memory_used: Option<u64>,
/// Underlying graphics backend for rendering
pub graphics_backend: String,
/// Model information for the active graphics adapter
pub graphics_adapter: String,
}

View file

@ -1,39 +0,0 @@
use crate::system;
use iced_futures::MaybeSend;
use std::fmt;
/// An operation to be performed on the system.
pub enum Action<T> {
/// Query system information and produce `T` with the result.
QueryInformation(Box<dyn Closure<T>>),
}
pub trait Closure<T>: Fn(system::Information) -> T + MaybeSend {}
impl<T, O> Closure<O> for T where T: Fn(system::Information) -> O + MaybeSend {}
impl<T> Action<T> {
/// Maps the output of a system [`Action`] using the provided closure.
pub fn map<A>(
self,
f: impl Fn(T) -> A + 'static + MaybeSend + Sync,
) -> Action<A>
where
T: 'static,
{
match self {
Self::QueryInformation(o) => {
Action::QueryInformation(Box::new(move |s| f(o(s))))
}
}
}
}
impl<T> fmt::Debug for Action<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::QueryInformation(_) => write!(f, "Action::QueryInformation"),
}
}
}

View file

@ -1,29 +0,0 @@
/// Contains informations about the system (e.g. system name, processor, memory, graphics adapter).
#[derive(Clone, Debug)]
pub struct Information {
/// The operating system name
pub system_name: Option<String>,
/// Operating system kernel version
pub system_kernel: Option<String>,
/// Long operating system version
///
/// Examples:
/// - MacOS 10.15 Catalina
/// - Windows 10 Pro
/// - Ubuntu 20.04 LTS (Focal Fossa)
pub system_version: Option<String>,
/// Short operating system version number
pub system_short_version: Option<String>,
/// Detailed processor model information
pub cpu_brand: String,
/// The number of physical cores on the processor
pub cpu_cores: Option<usize>,
/// Total RAM size, in bytes
pub memory_total: u64,
/// Memory used by this process, in bytes
pub memory_used: Option<u64>,
/// Underlying graphics backend for rendering
pub graphics_backend: String,
/// Model information for the active graphics adapter
pub graphics_adapter: String,
}

214
runtime/src/task.rs Normal file
View file

@ -0,0 +1,214 @@
use crate::core::widget;
use crate::core::MaybeSend;
use crate::futures::futures::channel::mpsc;
use crate::futures::futures::channel::oneshot;
use crate::futures::futures::future::{self, FutureExt};
use crate::futures::futures::never::Never;
use crate::futures::futures::stream::{self, Stream, StreamExt};
use crate::futures::{boxed_stream, BoxStream};
use crate::Action;
use std::future::Future;
/// A set of concurrent actions to be performed by the iced runtime.
///
/// A [`Task`] _may_ produce a bunch of values of type `T`.
#[allow(missing_debug_implementations)]
pub struct Task<T>(Option<BoxStream<Action<T>>>);
impl<T> Task<T> {
/// Creates a [`Task`] that does nothing.
pub fn none() -> Self {
Self(None)
}
/// Creates a new [`Task`] that instantly produces the given value.
pub fn done(value: T) -> Self
where
T: MaybeSend + 'static,
{
Self::future(future::ready(value))
}
/// Creates a new [`Task`] that runs the given [`Future`] and produces
/// its output.
pub fn future(future: impl Future<Output = T> + MaybeSend + 'static) -> Self
where
T: 'static,
{
Self::stream(stream::once(future))
}
/// Creates a new [`Task`] that runs the given [`Stream`] and produces
/// each of its items.
pub fn stream(stream: impl Stream<Item = T> + MaybeSend + 'static) -> Self
where
T: 'static,
{
Self(Some(boxed_stream(stream.map(Action::Output))))
}
/// Creates a new [`Task`] that runs the given [`widget::Operation`] and produces
/// its output.
pub fn widget(operation: impl widget::Operation<T> + 'static) -> Task<T>
where
T: MaybeSend + 'static,
{
Self::channel(move |sender| {
let operation =
widget::operation::map(Box::new(operation), move |value| {
let _ = sender.clone().try_send(value);
});
Action::Widget(Box::new(operation))
})
}
/// Creates a new [`Task`] that executes the [`Action`] returned by the closure and
/// produces the value fed to the [`oneshot::Sender`].
pub fn oneshot(f: impl FnOnce(oneshot::Sender<T>) -> Action<T>) -> Task<T>
where
T: MaybeSend + 'static,
{
let (sender, receiver) = oneshot::channel();
let action = f(sender);
Self(Some(boxed_stream(
stream::once(async move { action }).chain(
receiver.into_stream().filter_map(|result| async move {
Some(Action::Output(result.ok()?))
}),
),
)))
}
/// Creates a new [`Task`] that executes the [`Action`] returned by the closure and
/// produces the values fed to the [`mpsc::Sender`].
pub fn channel(f: impl FnOnce(mpsc::Sender<T>) -> Action<T>) -> Task<T>
where
T: MaybeSend + 'static,
{
let (sender, receiver) = mpsc::channel(1);
let action = f(sender);
Self(Some(boxed_stream(
stream::once(async move { action })
.chain(receiver.map(|result| Action::Output(result))),
)))
}
/// Creates a new [`Task`] that executes the given [`Action`] and produces no output.
pub fn effect(action: impl Into<Action<Never>>) -> Self {
let action = action.into();
Self(Some(boxed_stream(stream::once(async move {
action.output().expect_err("no output")
}))))
}
/// Maps the output of a [`Task`] with the given closure.
pub fn map<O>(
self,
mut f: impl FnMut(T) -> O + MaybeSend + 'static,
) -> Task<O>
where
T: MaybeSend + 'static,
O: MaybeSend + 'static,
{
self.then(move |output| Task::done(f(output)))
}
/// Performs a new [`Task`] for every output of the current [`Task`] using the
/// given closure.
///
/// This is the monadic interface of [`Task`]—analogous to [`Future`] and
/// [`Stream`].
pub fn then<O>(
self,
mut f: impl FnMut(T) -> Task<O> + MaybeSend + 'static,
) -> Task<O>
where
T: MaybeSend + 'static,
O: MaybeSend + 'static,
{
Task(match self.0 {
None => None,
Some(stream) => {
Some(boxed_stream(stream.flat_map(move |action| {
match action.output() {
Ok(output) => f(output)
.0
.unwrap_or_else(|| boxed_stream(stream::empty())),
Err(action) => {
boxed_stream(stream::once(async move { action }))
}
}
})))
}
})
}
/// Chains a new [`Task`] to be performed once the current one finishes completely.
pub fn chain(self, task: Self) -> Self
where
T: 'static,
{
match self.0 {
None => task,
Some(first) => match task.0 {
None => Task::none(),
Some(second) => Task(Some(boxed_stream(first.chain(second)))),
},
}
}
/// Creates a [`Task`] that runs the given [`Future`] to completion.
pub fn perform<A>(
future: impl Future<Output = A> + MaybeSend + 'static,
f: impl Fn(A) -> T + MaybeSend + 'static,
) -> Self
where
T: MaybeSend + 'static,
A: MaybeSend + 'static,
{
Self::future(future.map(f))
}
/// Creates a [`Task`] that runs the given [`Stream`] to completion.
pub fn run<A>(
stream: impl Stream<Item = A> + MaybeSend + 'static,
f: impl Fn(A) -> T + 'static + MaybeSend,
) -> Self
where
T: 'static,
{
Self::stream(stream.map(f))
}
/// Combines the given tasks and produces a single [`Task`] that will run all of them
/// in parallel.
pub fn batch(tasks: impl IntoIterator<Item = Self>) -> Self
where
T: 'static,
{
Self(Some(boxed_stream(stream::select_all(
tasks.into_iter().filter_map(|task| task.0),
))))
}
/// Returns the underlying [`Stream`] of the [`Task`].
pub fn into_stream(self) -> Option<BoxStream<Action<T>>> {
self.0
}
}
impl<T> From<()> for Task<T>
where
T: MaybeSend + 'static,
{
fn from(_value: ()) -> Self {
Self::none()
}
}

View file

@ -566,7 +566,7 @@ where
pub fn operate( pub fn operate(
&mut self, &mut self,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
self.root.as_widget().operate( self.root.as_widget().operate(
&mut self.state, &mut self.state,

View file

@ -1,24 +1,145 @@
//! Build window-based GUI applications. //! Build window-based GUI applications.
mod action;
pub mod screenshot; pub mod screenshot;
pub use action::Action;
pub use screenshot::Screenshot; pub use screenshot::Screenshot;
use crate::command::{self, Command};
use crate::core::time::Instant; use crate::core::time::Instant;
use crate::core::window::{ use crate::core::window::{
Event, Icon, Id, Level, Mode, Settings, UserAttention, Event, Icon, Id, Level, Mode, Settings, UserAttention,
}; };
use crate::core::{Point, Size}; use crate::core::{MaybeSend, Point, Size};
use crate::futures::event; use crate::futures::event;
use crate::futures::futures::channel::oneshot;
use crate::futures::Subscription; use crate::futures::Subscription;
use crate::Task;
pub use raw_window_handle; pub use raw_window_handle;
use raw_window_handle::WindowHandle; use raw_window_handle::WindowHandle;
/// An operation to be performed on some window.
#[allow(missing_debug_implementations)]
pub enum Action {
/// Opens a new window with some [`Settings`].
Open(Id, Settings),
/// Close the window and exits the application.
Close(Id),
/// Move the window with the left mouse button until the button is
/// released.
///
/// Theres no guarantee that this will work unless the left mouse
/// button was pressed immediately before this function is called.
Drag(Id),
/// Resize the window to the given logical dimensions.
Resize(Id, Size),
/// Fetch the current logical dimensions of the window.
FetchSize(Id, oneshot::Sender<Size>),
/// Fetch if the current window is maximized or not.
FetchMaximized(Id, oneshot::Sender<bool>),
/// Set the window to maximized or back
Maximize(Id, bool),
/// Fetch if the current window is minimized or not.
///
/// ## Platform-specific
/// - **Wayland:** Always `None`.
FetchMinimized(Id, oneshot::Sender<Option<bool>>),
/// Set the window to minimized or back
Minimize(Id, bool),
/// Fetch the current logical coordinates of the window.
FetchPosition(Id, oneshot::Sender<Option<Point>>),
/// Move the window to the given logical coordinates.
///
/// Unsupported on Wayland.
Move(Id, Point),
/// Change the [`Mode`] of the window.
ChangeMode(Id, Mode),
/// Fetch the current [`Mode`] of the window.
FetchMode(Id, oneshot::Sender<Mode>),
/// Toggle the window to maximized or back
ToggleMaximize(Id),
/// Toggle whether window has decorations.
///
/// ## Platform-specific
/// - **X11:** Not implemented.
/// - **Web:** Unsupported.
ToggleDecorations(Id),
/// Request user attention to the window, this has no effect if the application
/// is already focused. How requesting for user attention manifests is platform dependent,
/// see [`UserAttention`] for details.
///
/// Providing `None` will unset the request for user attention. Unsetting the request for
/// user attention might not be done automatically by the WM when the window receives input.
///
/// ## Platform-specific
///
/// - **iOS / Android / Web:** Unsupported.
/// - **macOS:** `None` has no effect.
/// - **X11:** Requests for user attention must be manually cleared.
/// - **Wayland:** Requires `xdg_activation_v1` protocol, `None` has no effect.
RequestUserAttention(Id, Option<UserAttention>),
/// Bring the window to the front and sets input focus. Has no effect if the window is
/// already in focus, minimized, or not visible.
///
/// This method steals input focus from other applications. Do not use this method unless
/// you are certain that's what the user wants. Focus stealing can cause an extremely disruptive
/// user experience.
///
/// ## Platform-specific
///
/// - **Web / Wayland:** Unsupported.
GainFocus(Id),
/// Change the window [`Level`].
ChangeLevel(Id, Level),
/// Show the system menu at cursor position.
///
/// ## Platform-specific
/// Android / iOS / macOS / Orbital / Web / X11: Unsupported.
ShowSystemMenu(Id),
/// Fetch the raw identifier unique to the window.
FetchRawId(Id, oneshot::Sender<u64>),
/// Change the window [`Icon`].
///
/// On Windows and X11, this is typically the small icon in the top-left
/// corner of the titlebar.
///
/// ## Platform-specific
///
/// - **Web / Wayland / macOS:** Unsupported.
///
/// - **Windows:** Sets `ICON_SMALL`. The base size for a window icon is 16x16, but it's
/// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32.
///
/// - **X11:** Has no universal guidelines for icon sizes, so you're at the whims of the WM. That
/// said, it's usually in the same ballpark as on Windows.
ChangeIcon(Id, Icon),
/// Runs the closure with the native window handle of the window with the given [`Id`].
RunWithHandle(Id, Box<dyn FnOnce(WindowHandle<'_>) + Send>),
/// Screenshot the viewport of the window.
Screenshot(Id, oneshot::Sender<Screenshot>),
}
/// Subscribes to the frames of the window of the running application. /// Subscribes to the frames of the window of the running application.
/// ///
/// The resulting [`Subscription`] will produce items at a rate equal to the /// The resulting [`Subscription`] will produce items at a rate equal to the
@ -34,110 +155,96 @@ pub fn frames() -> Subscription<Instant> {
}) })
} }
/// Spawns a new window with the given `settings`. /// Opens a new window with the given `settings`.
/// ///
/// Returns the new window [`Id`] alongside the [`Command`]. /// Returns the new window [`Id`] alongside the [`Task`].
pub fn spawn<Message>(settings: Settings) -> (Id, Command<Message>) { pub fn open<T>(settings: Settings) -> (Id, Task<T>) {
let id = Id::unique(); let id = Id::unique();
( (
id, id,
Command::single(command::Action::Window(Action::Spawn(id, settings))), Task::effect(crate::Action::Window(Action::Open(id, settings))),
) )
} }
/// Closes the window with `id`. /// Closes the window with `id`.
pub fn close<Message>(id: Id) -> Command<Message> { pub fn close<T>(id: Id) -> Task<T> {
Command::single(command::Action::Window(Action::Close(id))) Task::effect(crate::Action::Window(Action::Close(id)))
} }
/// Begins dragging the window while the left mouse button is held. /// Begins dragging the window while the left mouse button is held.
pub fn drag<Message>(id: Id) -> Command<Message> { pub fn drag<T>(id: Id) -> Task<T> {
Command::single(command::Action::Window(Action::Drag(id))) Task::effect(crate::Action::Window(Action::Drag(id)))
} }
/// Resizes the window to the given logical dimensions. /// Resizes the window to the given logical dimensions.
pub fn resize<Message>(id: Id, new_size: Size) -> Command<Message> { pub fn resize<T>(id: Id, new_size: Size) -> Task<T> {
Command::single(command::Action::Window(Action::Resize(id, new_size))) Task::effect(crate::Action::Window(Action::Resize(id, new_size)))
} }
/// Fetches the window's size in logical dimensions. /// Fetches the window's size in logical dimensions.
pub fn fetch_size<Message>( pub fn fetch_size(id: Id) -> Task<Size> {
id: Id, Task::oneshot(move |channel| {
f: impl FnOnce(Size) -> Message + 'static, crate::Action::Window(Action::FetchSize(id, channel))
) -> Command<Message> { })
Command::single(command::Action::Window(Action::FetchSize(id, Box::new(f))))
} }
/// Fetches if the window is maximized. /// Fetches if the window is maximized.
pub fn fetch_maximized<Message>( pub fn fetch_maximized(id: Id) -> Task<bool> {
id: Id, Task::oneshot(move |channel| {
f: impl FnOnce(bool) -> Message + 'static, crate::Action::Window(Action::FetchMaximized(id, channel))
) -> Command<Message> { })
Command::single(command::Action::Window(Action::FetchMaximized(
id,
Box::new(f),
)))
} }
/// Maximizes the window. /// Maximizes the window.
pub fn maximize<Message>(id: Id, maximized: bool) -> Command<Message> { pub fn maximize<T>(id: Id, maximized: bool) -> Task<T> {
Command::single(command::Action::Window(Action::Maximize(id, maximized))) Task::effect(crate::Action::Window(Action::Maximize(id, maximized)))
} }
/// Fetches if the window is minimized. /// Fetches if the window is minimized.
pub fn fetch_minimized<Message>( pub fn fetch_minimized(id: Id) -> Task<Option<bool>> {
id: Id, Task::oneshot(move |channel| {
f: impl FnOnce(Option<bool>) -> Message + 'static, crate::Action::Window(Action::FetchMinimized(id, channel))
) -> Command<Message> { })
Command::single(command::Action::Window(Action::FetchMinimized(
id,
Box::new(f),
)))
} }
/// Minimizes the window. /// Minimizes the window.
pub fn minimize<Message>(id: Id, minimized: bool) -> Command<Message> { pub fn minimize<T>(id: Id, minimized: bool) -> Task<T> {
Command::single(command::Action::Window(Action::Minimize(id, minimized))) Task::effect(crate::Action::Window(Action::Minimize(id, minimized)))
} }
/// Fetches the current window position in logical coordinates. /// Fetches the current window position in logical coordinates.
pub fn fetch_position<Message>( pub fn fetch_position(id: Id) -> Task<Option<Point>> {
id: Id, Task::oneshot(move |channel| {
f: impl FnOnce(Option<Point>) -> Message + 'static, crate::Action::Window(Action::FetchPosition(id, channel))
) -> Command<Message> { })
Command::single(command::Action::Window(Action::FetchPosition(
id,
Box::new(f),
)))
} }
/// Moves the window to the given logical coordinates. /// Moves the window to the given logical coordinates.
pub fn move_to<Message>(id: Id, position: Point) -> Command<Message> { pub fn move_to<T>(id: Id, position: Point) -> Task<T> {
Command::single(command::Action::Window(Action::Move(id, position))) Task::effect(crate::Action::Window(Action::Move(id, position)))
} }
/// Changes the [`Mode`] of the window. /// Changes the [`Mode`] of the window.
pub fn change_mode<Message>(id: Id, mode: Mode) -> Command<Message> { pub fn change_mode<T>(id: Id, mode: Mode) -> Task<T> {
Command::single(command::Action::Window(Action::ChangeMode(id, mode))) Task::effect(crate::Action::Window(Action::ChangeMode(id, mode)))
} }
/// Fetches the current [`Mode`] of the window. /// Fetches the current [`Mode`] of the window.
pub fn fetch_mode<Message>( pub fn fetch_mode(id: Id) -> Task<Mode> {
id: Id, Task::oneshot(move |channel| {
f: impl FnOnce(Mode) -> Message + 'static, crate::Action::Window(Action::FetchMode(id, channel))
) -> Command<Message> { })
Command::single(command::Action::Window(Action::FetchMode(id, Box::new(f))))
} }
/// Toggles the window to maximized or back. /// Toggles the window to maximized or back.
pub fn toggle_maximize<Message>(id: Id) -> Command<Message> { pub fn toggle_maximize<T>(id: Id) -> Task<T> {
Command::single(command::Action::Window(Action::ToggleMaximize(id))) Task::effect(crate::Action::Window(Action::ToggleMaximize(id)))
} }
/// Toggles the window decorations. /// Toggles the window decorations.
pub fn toggle_decorations<Message>(id: Id) -> Command<Message> { pub fn toggle_decorations<T>(id: Id) -> Task<T> {
Command::single(command::Action::Window(Action::ToggleDecorations(id))) Task::effect(crate::Action::Window(Action::ToggleDecorations(id)))
} }
/// Request user attention to the window. This has no effect if the application /// Request user attention to the window. This has no effect if the application
@ -146,11 +253,11 @@ pub fn toggle_decorations<Message>(id: Id) -> Command<Message> {
/// ///
/// Providing `None` will unset the request for user attention. Unsetting the request for /// Providing `None` will unset the request for user attention. Unsetting the request for
/// user attention might not be done automatically by the WM when the window receives input. /// user attention might not be done automatically by the WM when the window receives input.
pub fn request_user_attention<Message>( pub fn request_user_attention<T>(
id: Id, id: Id,
user_attention: Option<UserAttention>, user_attention: Option<UserAttention>,
) -> Command<Message> { ) -> Task<T> {
Command::single(command::Action::Window(Action::RequestUserAttention( Task::effect(crate::Action::Window(Action::RequestUserAttention(
id, id,
user_attention, user_attention,
))) )))
@ -159,59 +266,61 @@ pub fn request_user_attention<Message>(
/// Brings the window to the front and sets input focus. Has no effect if the window is /// Brings the window to the front and sets input focus. Has no effect if the window is
/// already in focus, minimized, or not visible. /// already in focus, minimized, or not visible.
/// ///
/// This [`Command`] steals input focus from other applications. Do not use this method unless /// This [`Task`] steals input focus from other applications. Do not use this method unless
/// you are certain that's what the user wants. Focus stealing can cause an extremely disruptive /// you are certain that's what the user wants. Focus stealing can cause an extremely disruptive
/// user experience. /// user experience.
pub fn gain_focus<Message>(id: Id) -> Command<Message> { pub fn gain_focus<T>(id: Id) -> Task<T> {
Command::single(command::Action::Window(Action::GainFocus(id))) Task::effect(crate::Action::Window(Action::GainFocus(id)))
} }
/// Changes the window [`Level`]. /// Changes the window [`Level`].
pub fn change_level<Message>(id: Id, level: Level) -> Command<Message> { pub fn change_level<T>(id: Id, level: Level) -> Task<T> {
Command::single(command::Action::Window(Action::ChangeLevel(id, level))) Task::effect(crate::Action::Window(Action::ChangeLevel(id, level)))
} }
/// Show the [system menu] at cursor position. /// Show the [system menu] at cursor position.
/// ///
/// [system menu]: https://en.wikipedia.org/wiki/Common_menus_in_Microsoft_Windows#System_menu /// [system menu]: https://en.wikipedia.org/wiki/Common_menus_in_Microsoft_Windows#System_menu
pub fn show_system_menu<Message>(id: Id) -> Command<Message> { pub fn show_system_menu<T>(id: Id) -> Task<T> {
Command::single(command::Action::Window(Action::ShowSystemMenu(id))) Task::effect(crate::Action::Window(Action::ShowSystemMenu(id)))
} }
/// Fetches an identifier unique to the window, provided by the underlying windowing system. This is /// Fetches an identifier unique to the window, provided by the underlying windowing system. This is
/// not to be confused with [`Id`]. /// not to be confused with [`Id`].
pub fn fetch_id<Message>( pub fn fetch_raw_id<Message>(id: Id) -> Task<u64> {
id: Id, Task::oneshot(|channel| {
f: impl FnOnce(u64) -> Message + 'static, crate::Action::Window(Action::FetchRawId(id, channel))
) -> Command<Message> { })
Command::single(command::Action::Window(Action::FetchId(id, Box::new(f))))
} }
/// Changes the [`Icon`] of the window. /// Changes the [`Icon`] of the window.
pub fn change_icon<Message>(id: Id, icon: Icon) -> Command<Message> { pub fn change_icon<T>(id: Id, icon: Icon) -> Task<T> {
Command::single(command::Action::Window(Action::ChangeIcon(id, icon))) Task::effect(crate::Action::Window(Action::ChangeIcon(id, icon)))
} }
/// Runs the given callback with the native window handle for the window with the given id. /// Runs the given callback with the native window handle for the window with the given id.
/// ///
/// Note that if the window closes before this call is processed the callback will not be run. /// Note that if the window closes before this call is processed the callback will not be run.
pub fn run_with_handle<Message>( pub fn run_with_handle<T>(
id: Id, id: Id,
f: impl FnOnce(WindowHandle<'_>) -> Message + 'static, f: impl FnOnce(WindowHandle<'_>) -> T + MaybeSend + 'static,
) -> Command<Message> { ) -> Task<T>
Command::single(command::Action::Window(Action::RunWithHandle( where
T: MaybeSend + 'static,
{
Task::oneshot(move |channel| {
crate::Action::Window(Action::RunWithHandle(
id, id,
Box::new(f), Box::new(move |handle| {
))) let _ = channel.send(f(handle));
}),
))
})
} }
/// Captures a [`Screenshot`] from the window. /// Captures a [`Screenshot`] from the window.
pub fn screenshot<Message>( pub fn screenshot(id: Id) -> Task<Screenshot> {
id: Id, Task::oneshot(move |channel| {
f: impl FnOnce(Screenshot) -> Message + Send + 'static, crate::Action::Window(Action::Screenshot(id, channel))
) -> Command<Message> { })
Command::single(command::Action::Window(Action::Screenshot(
id,
Box::new(f),
)))
} }

View file

@ -1,230 +0,0 @@
use crate::core::window::{Icon, Id, Level, Mode, Settings, UserAttention};
use crate::core::{Point, Size};
use crate::futures::MaybeSend;
use crate::window::Screenshot;
use raw_window_handle::WindowHandle;
use std::fmt;
/// An operation to be performed on some window.
pub enum Action<T> {
/// Spawns a new window with some [`Settings`].
Spawn(Id, Settings),
/// Close the window and exits the application.
Close(Id),
/// Move the window with the left mouse button until the button is
/// released.
///
/// Theres no guarantee that this will work unless the left mouse
/// button was pressed immediately before this function is called.
Drag(Id),
/// Resize the window to the given logical dimensions.
Resize(Id, Size),
/// Fetch the current logical dimensions of the window.
FetchSize(Id, Box<dyn FnOnce(Size) -> T + 'static>),
/// Fetch if the current window is maximized or not.
///
/// ## Platform-specific
/// - **iOS / Android / Web:** Unsupported.
FetchMaximized(Id, Box<dyn FnOnce(bool) -> T + 'static>),
/// Set the window to maximized or back
Maximize(Id, bool),
/// Fetch if the current window is minimized or not.
///
/// ## Platform-specific
/// - **Wayland:** Always `None`.
/// - **iOS / Android / Web:** Unsupported.
FetchMinimized(Id, Box<dyn FnOnce(Option<bool>) -> T + 'static>),
/// Set the window to minimized or back
Minimize(Id, bool),
/// Fetch the current logical coordinates of the window.
FetchPosition(Id, Box<dyn FnOnce(Option<Point>) -> T + 'static>),
/// Move the window to the given logical coordinates.
///
/// Unsupported on Wayland.
Move(Id, Point),
/// Change the [`Mode`] of the window.
ChangeMode(Id, Mode),
/// Fetch the current [`Mode`] of the window.
FetchMode(Id, Box<dyn FnOnce(Mode) -> T + 'static>),
/// Toggle the window to maximized or back
ToggleMaximize(Id),
/// Toggle whether window has decorations.
///
/// ## Platform-specific
/// - **X11:** Not implemented.
/// - **Web:** Unsupported.
ToggleDecorations(Id),
/// Request user attention to the window, this has no effect if the application
/// is already focused. How requesting for user attention manifests is platform dependent,
/// see [`UserAttention`] for details.
///
/// Providing `None` will unset the request for user attention. Unsetting the request for
/// user attention might not be done automatically by the WM when the window receives input.
///
/// ## Platform-specific
///
/// - **iOS / Android / Web:** Unsupported.
/// - **macOS:** `None` has no effect.
/// - **X11:** Requests for user attention must be manually cleared.
/// - **Wayland:** Requires `xdg_activation_v1` protocol, `None` has no effect.
RequestUserAttention(Id, Option<UserAttention>),
/// Bring the window to the front and sets input focus. Has no effect if the window is
/// already in focus, minimized, or not visible.
///
/// This method steals input focus from other applications. Do not use this method unless
/// you are certain that's what the user wants. Focus stealing can cause an extremely disruptive
/// user experience.
///
/// ## Platform-specific
///
/// - **Web / Wayland:** Unsupported.
GainFocus(Id),
/// Change the window [`Level`].
ChangeLevel(Id, Level),
/// Show the system menu at cursor position.
///
/// ## Platform-specific
/// Android / iOS / macOS / Orbital / Web / X11: Unsupported.
ShowSystemMenu(Id),
/// Fetch the raw identifier unique to the window.
FetchId(Id, Box<dyn FnOnce(u64) -> T + 'static>),
/// Change the window [`Icon`].
///
/// On Windows and X11, this is typically the small icon in the top-left
/// corner of the titlebar.
///
/// ## Platform-specific
///
/// - **Web / Wayland / macOS:** Unsupported.
///
/// - **Windows:** Sets `ICON_SMALL`. The base size for a window icon is 16x16, but it's
/// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32.
///
/// - **X11:** Has no universal guidelines for icon sizes, so you're at the whims of the WM. That
/// said, it's usually in the same ballpark as on Windows.
ChangeIcon(Id, Icon),
/// Runs the closure with the native window handle of the window with the given [`Id`].
RunWithHandle(Id, Box<dyn FnOnce(WindowHandle<'_>) -> T + 'static>),
/// Screenshot the viewport of the window.
Screenshot(Id, Box<dyn FnOnce(Screenshot) -> T + 'static>),
}
impl<T> Action<T> {
/// Maps the output of a window [`Action`] using the provided closure.
pub fn map<A>(
self,
f: impl Fn(T) -> A + 'static + MaybeSend + Sync,
) -> Action<A>
where
T: 'static,
{
match self {
Self::Spawn(id, settings) => Action::Spawn(id, settings),
Self::Close(id) => Action::Close(id),
Self::Drag(id) => Action::Drag(id),
Self::Resize(id, size) => Action::Resize(id, size),
Self::FetchSize(id, o) => {
Action::FetchSize(id, Box::new(move |s| f(o(s))))
}
Self::FetchMaximized(id, o) => {
Action::FetchMaximized(id, Box::new(move |s| f(o(s))))
}
Self::Maximize(id, maximized) => Action::Maximize(id, maximized),
Self::FetchMinimized(id, o) => {
Action::FetchMinimized(id, Box::new(move |s| f(o(s))))
}
Self::Minimize(id, minimized) => Action::Minimize(id, minimized),
Self::FetchPosition(id, o) => {
Action::FetchPosition(id, Box::new(move |s| f(o(s))))
}
Self::Move(id, position) => Action::Move(id, position),
Self::ChangeMode(id, mode) => Action::ChangeMode(id, mode),
Self::FetchMode(id, o) => {
Action::FetchMode(id, Box::new(move |s| f(o(s))))
}
Self::ToggleMaximize(id) => Action::ToggleMaximize(id),
Self::ToggleDecorations(id) => Action::ToggleDecorations(id),
Self::RequestUserAttention(id, attention_type) => {
Action::RequestUserAttention(id, attention_type)
}
Self::GainFocus(id) => Action::GainFocus(id),
Self::ChangeLevel(id, level) => Action::ChangeLevel(id, level),
Self::ShowSystemMenu(id) => Action::ShowSystemMenu(id),
Self::FetchId(id, o) => {
Action::FetchId(id, Box::new(move |s| f(o(s))))
}
Self::ChangeIcon(id, icon) => Action::ChangeIcon(id, icon),
Self::RunWithHandle(id, o) => {
Action::RunWithHandle(id, Box::new(move |s| f(o(s))))
}
Self::Screenshot(id, tag) => Action::Screenshot(
id,
Box::new(move |screenshot| f(tag(screenshot))),
),
}
}
}
impl<T> fmt::Debug for Action<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Spawn(id, settings) => {
write!(f, "Action::Spawn({id:?}, {settings:?})")
}
Self::Close(id) => write!(f, "Action::Close({id:?})"),
Self::Drag(id) => write!(f, "Action::Drag({id:?})"),
Self::Resize(id, size) => {
write!(f, "Action::Resize({id:?}, {size:?})")
}
Self::FetchSize(id, _) => write!(f, "Action::FetchSize({id:?})"),
Self::FetchMaximized(id, _) => {
write!(f, "Action::FetchMaximized({id:?})")
}
Self::Maximize(id, maximized) => {
write!(f, "Action::Maximize({id:?}, {maximized})")
}
Self::FetchMinimized(id, _) => {
write!(f, "Action::FetchMinimized({id:?})")
}
Self::Minimize(id, minimized) => {
write!(f, "Action::Minimize({id:?}, {minimized}")
}
Self::FetchPosition(id, _) => {
write!(f, "Action::FetchPosition({id:?})")
}
Self::Move(id, position) => {
write!(f, "Action::Move({id:?}, {position})")
}
Self::ChangeMode(id, mode) => {
write!(f, "Action::SetMode({id:?}, {mode:?})")
}
Self::FetchMode(id, _) => write!(f, "Action::FetchMode({id:?})"),
Self::ToggleMaximize(id) => {
write!(f, "Action::ToggleMaximize({id:?})")
}
Self::ToggleDecorations(id) => {
write!(f, "Action::ToggleDecorations({id:?})")
}
Self::RequestUserAttention(id, _) => {
write!(f, "Action::RequestUserAttention({id:?})")
}
Self::GainFocus(id) => write!(f, "Action::GainFocus({id:?})"),
Self::ChangeLevel(id, level) => {
write!(f, "Action::ChangeLevel({id:?}, {level:?})")
}
Self::ShowSystemMenu(id) => {
write!(f, "Action::ShowSystemMenu({id:?})")
}
Self::FetchId(id, _) => write!(f, "Action::FetchId({id:?})"),
Self::ChangeIcon(id, _icon) => {
write!(f, "Action::ChangeIcon({id:?})")
}
Self::RunWithHandle(id, _) => {
write!(f, "Action::RunWithHandle({id:?})")
}
Self::Screenshot(id, _) => write!(f, "Action::Screenshot({id:?})"),
}
}
}

View file

@ -2,7 +2,7 @@
use crate::core::text; use crate::core::text;
use crate::graphics::compositor; use crate::graphics::compositor;
use crate::shell::application; use crate::shell::application;
use crate::{Command, Element, Executor, Settings, Subscription}; use crate::{Element, Executor, Settings, Subscription, Task};
pub use application::{Appearance, DefaultStyle}; pub use application::{Appearance, DefaultStyle};
@ -16,7 +16,7 @@ pub use application::{Appearance, DefaultStyle};
/// document. /// document.
/// ///
/// An [`Application`] can execute asynchronous actions by returning a /// An [`Application`] can execute asynchronous actions by returning a
/// [`Command`] in some of its methods. /// [`Task`] in some of its methods.
/// ///
/// When using an [`Application`] with the `debug` feature enabled, a debug view /// When using an [`Application`] with the `debug` feature enabled, a debug view
/// can be toggled by pressing `F12`. /// can be toggled by pressing `F12`.
@ -62,7 +62,7 @@ pub use application::{Appearance, DefaultStyle};
/// ```no_run /// ```no_run
/// use iced::advanced::Application; /// use iced::advanced::Application;
/// use iced::executor; /// use iced::executor;
/// use iced::{Command, Element, Settings, Theme, Renderer}; /// use iced::{Task, Element, Settings, Theme, Renderer};
/// ///
/// pub fn main() -> iced::Result { /// pub fn main() -> iced::Result {
/// Hello::run(Settings::default()) /// Hello::run(Settings::default())
@ -77,16 +77,16 @@ pub use application::{Appearance, DefaultStyle};
/// type Theme = Theme; /// type Theme = Theme;
/// type Renderer = Renderer; /// type Renderer = Renderer;
/// ///
/// fn new(_flags: ()) -> (Hello, Command<Self::Message>) { /// fn new(_flags: ()) -> (Hello, Task<Self::Message>) {
/// (Hello, Command::none()) /// (Hello, Task::none())
/// } /// }
/// ///
/// fn title(&self) -> String { /// fn title(&self) -> String {
/// String::from("A cool application") /// String::from("A cool application")
/// } /// }
/// ///
/// fn update(&mut self, _message: Self::Message) -> Command<Self::Message> { /// fn update(&mut self, _message: Self::Message) -> Task<Self::Message> {
/// Command::none() /// Task::none()
/// } /// }
/// ///
/// fn view(&self) -> Element<Self::Message> { /// fn view(&self) -> Element<Self::Message> {
@ -123,12 +123,12 @@ where
/// ///
/// Here is where you should return the initial state of your app. /// Here is where you should return the initial state of your app.
/// ///
/// Additionally, you can return a [`Command`] if you need to perform some /// Additionally, you can return a [`Task`] if you need to perform some
/// async action in the background on startup. This is useful if you want to /// async action in the background on startup. This is useful if you want to
/// load state from a file, perform an initial HTTP request, etc. /// load state from a file, perform an initial HTTP request, etc.
/// ///
/// [`run`]: Self::run /// [`run`]: Self::run
fn new(flags: Self::Flags) -> (Self, Command<Self::Message>); fn new(flags: Self::Flags) -> (Self, Task<Self::Message>);
/// Returns the current title of the [`Application`]. /// Returns the current title of the [`Application`].
/// ///
@ -142,8 +142,8 @@ where
/// produced by either user interactions or commands, will be handled by /// produced by either user interactions or commands, will be handled by
/// this method. /// this method.
/// ///
/// Any [`Command`] returned will be executed immediately in the background. /// Any [`Task`] returned will be executed immediately in the background.
fn update(&mut self, message: Self::Message) -> Command<Self::Message>; fn update(&mut self, message: Self::Message) -> Task<Self::Message>;
/// Returns the widgets to display in the [`Application`]. /// Returns the widgets to display in the [`Application`].
/// ///
@ -234,7 +234,7 @@ where
type Theme = A::Theme; type Theme = A::Theme;
type Renderer = A::Renderer; type Renderer = A::Renderer;
fn update(&mut self, message: Self::Message) -> Command<Self::Message> { fn update(&mut self, message: Self::Message) -> Task<Self::Message> {
self.0.update(message) self.0.update(message)
} }
@ -250,7 +250,7 @@ where
{ {
type Flags = A::Flags; type Flags = A::Flags;
fn new(flags: Self::Flags) -> (Self, Command<A::Message>) { fn new(flags: Self::Flags) -> (Self, Task<A::Message>) {
let (app, command) = A::new(flags); let (app, command) = A::new(flags);
(Instance(app), command) (Instance(app), command)

View file

@ -203,6 +203,7 @@ pub use crate::core::{
Length, Padding, Pixels, Point, Radians, Rectangle, Rotation, Shadow, Size, Length, Padding, Pixels, Point, Radians, Rectangle, Rotation, Shadow, Size,
Theme, Transformation, Vector, Theme, Transformation, Vector,
}; };
pub use crate::runtime::Task;
pub mod clipboard { pub mod clipboard {
//! Access the clipboard. //! Access the clipboard.
@ -256,11 +257,6 @@ pub mod mouse {
}; };
} }
pub mod command {
//! Run asynchronous actions.
pub use crate::runtime::command::{channel, Command};
}
pub mod subscription { pub mod subscription {
//! Listen to external events in your application. //! Listen to external events in your application.
pub use iced_futures::subscription::{ pub use iced_futures::subscription::{
@ -312,7 +308,6 @@ pub mod widget {
mod runtime {} mod runtime {}
} }
pub use command::Command;
pub use error::Error; pub use error::Error;
pub use event::Event; pub use event::Event;
pub use executor::Executor; pub use executor::Executor;

View file

@ -1,6 +1,6 @@
//! Leverage multi-window support in your application. //! Leverage multi-window support in your application.
use crate::window; use crate::window;
use crate::{Command, Element, Executor, Settings, Subscription}; use crate::{Element, Executor, Settings, Subscription, Task};
pub use crate::application::{Appearance, DefaultStyle}; pub use crate::application::{Appearance, DefaultStyle};
@ -14,7 +14,7 @@ pub use crate::application::{Appearance, DefaultStyle};
/// document and display only the contents of the `window::Id::MAIN` window. /// document and display only the contents of the `window::Id::MAIN` window.
/// ///
/// An [`Application`] can execute asynchronous actions by returning a /// An [`Application`] can execute asynchronous actions by returning a
/// [`Command`] in some of its methods. /// [`Task`] in some of its methods.
/// ///
/// When using an [`Application`] with the `debug` feature enabled, a debug view /// When using an [`Application`] with the `debug` feature enabled, a debug view
/// can be toggled by pressing `F12`. /// can be toggled by pressing `F12`.
@ -29,7 +29,7 @@ pub use crate::application::{Appearance, DefaultStyle};
/// ///
/// ```no_run /// ```no_run
/// use iced::{executor, window}; /// use iced::{executor, window};
/// use iced::{Command, Element, Settings, Theme}; /// use iced::{Task, Element, Settings, Theme};
/// use iced::multi_window::{self, Application}; /// use iced::multi_window::{self, Application};
/// ///
/// pub fn main() -> iced::Result { /// pub fn main() -> iced::Result {
@ -44,16 +44,16 @@ pub use crate::application::{Appearance, DefaultStyle};
/// type Message = (); /// type Message = ();
/// type Theme = Theme; /// type Theme = Theme;
/// ///
/// fn new(_flags: ()) -> (Hello, Command<Self::Message>) { /// fn new(_flags: ()) -> (Hello, Task<Self::Message>) {
/// (Hello, Command::none()) /// (Hello, Task::none())
/// } /// }
/// ///
/// fn title(&self, _window: window::Id) -> String { /// fn title(&self, _window: window::Id) -> String {
/// String::from("A cool application") /// String::from("A cool application")
/// } /// }
/// ///
/// fn update(&mut self, _message: Self::Message) -> Command<Self::Message> { /// fn update(&mut self, _message: Self::Message) -> Task<Self::Message> {
/// Command::none() /// Task::none()
/// } /// }
/// ///
/// fn view(&self, _window: window::Id) -> Element<Self::Message> { /// fn view(&self, _window: window::Id) -> Element<Self::Message> {
@ -89,12 +89,12 @@ where
/// ///
/// Here is where you should return the initial state of your app. /// Here is where you should return the initial state of your app.
/// ///
/// Additionally, you can return a [`Command`] if you need to perform some /// Additionally, you can return a [`Task`] if you need to perform some
/// async action in the background on startup. This is useful if you want to /// async action in the background on startup. This is useful if you want to
/// load state from a file, perform an initial HTTP request, etc. /// load state from a file, perform an initial HTTP request, etc.
/// ///
/// [`run`]: Self::run /// [`run`]: Self::run
fn new(flags: Self::Flags) -> (Self, Command<Self::Message>); fn new(flags: Self::Flags) -> (Self, Task<Self::Message>);
/// Returns the current title of the `window` of the [`Application`]. /// Returns the current title of the `window` of the [`Application`].
/// ///
@ -108,8 +108,8 @@ where
/// produced by either user interactions or commands, will be handled by /// produced by either user interactions or commands, will be handled by
/// this method. /// this method.
/// ///
/// Any [`Command`] returned will be executed immediately in the background. /// Any [`Task`] returned will be executed immediately in the background.
fn update(&mut self, message: Self::Message) -> Command<Self::Message>; fn update(&mut self, message: Self::Message) -> Task<Self::Message>;
/// Returns the widgets to display in the `window` of the [`Application`]. /// Returns the widgets to display in the `window` of the [`Application`].
/// ///
@ -207,7 +207,7 @@ where
type Theme = A::Theme; type Theme = A::Theme;
type Renderer = crate::Renderer; type Renderer = crate::Renderer;
fn update(&mut self, message: Self::Message) -> Command<Self::Message> { fn update(&mut self, message: Self::Message) -> Task<Self::Message> {
self.0.update(message) self.0.update(message)
} }
@ -226,7 +226,7 @@ where
{ {
type Flags = A::Flags; type Flags = A::Flags;
fn new(flags: Self::Flags) -> (Self, Command<A::Message>) { fn new(flags: Self::Flags) -> (Self, Task<A::Message>) {
let (app, command) = A::new(flags); let (app, command) = A::new(flags);
(Instance(app), command) (Instance(app), command)

View file

@ -35,7 +35,7 @@ use crate::core::text;
use crate::executor::{self, Executor}; use crate::executor::{self, Executor};
use crate::graphics::compositor; use crate::graphics::compositor;
use crate::window; use crate::window;
use crate::{Command, Element, Font, Result, Settings, Size, Subscription}; use crate::{Element, Font, Result, Settings, Size, Subscription, Task};
pub use crate::application::{Appearance, DefaultStyle}; pub use crate::application::{Appearance, DefaultStyle};
@ -76,7 +76,7 @@ pub fn program<State, Message, Theme, Renderer>(
) -> Program<impl Definition<State = State, Message = Message, Theme = Theme>> ) -> Program<impl Definition<State = State, Message = Message, Theme = Theme>>
where where
State: 'static, State: 'static,
Message: Send + std::fmt::Debug, Message: Send + std::fmt::Debug + 'static,
Theme: Default + DefaultStyle, Theme: Default + DefaultStyle,
Renderer: self::Renderer, Renderer: self::Renderer,
{ {
@ -94,7 +94,7 @@ where
impl<State, Message, Theme, Renderer, Update, View> Definition impl<State, Message, Theme, Renderer, Update, View> Definition
for Application<State, Message, Theme, Renderer, Update, View> for Application<State, Message, Theme, Renderer, Update, View>
where where
Message: Send + std::fmt::Debug, Message: Send + std::fmt::Debug + 'static,
Theme: Default + DefaultStyle, Theme: Default + DefaultStyle,
Renderer: self::Renderer, Renderer: self::Renderer,
Update: self::Update<State, Message>, Update: self::Update<State, Message>,
@ -106,15 +106,15 @@ where
type Renderer = Renderer; type Renderer = Renderer;
type Executor = executor::Default; type Executor = executor::Default;
fn load(&self) -> Command<Self::Message> { fn load(&self) -> Task<Self::Message> {
Command::none() Task::none()
} }
fn update( fn update(
&self, &self,
state: &mut Self::State, state: &mut Self::State,
message: Self::Message, message: Self::Message,
) -> Command<Self::Message> { ) -> Task<Self::Message> {
self.update.update(state, message).into() self.update.update(state, message).into()
} }
@ -197,7 +197,7 @@ impl<P: Definition> Program<P> {
fn new( fn new(
(program, initialize): Self::Flags, (program, initialize): Self::Flags,
) -> (Self, Command<Self::Message>) { ) -> (Self, Task<Self::Message>) {
let state = initialize(); let state = initialize();
let command = program.load(); let command = program.load();
@ -218,7 +218,7 @@ impl<P: Definition> Program<P> {
fn update( fn update(
&mut self, &mut self,
message: Self::Message, message: Self::Message,
) -> Command<Self::Message> { ) -> Task<Self::Message> {
self.program.update(&mut self.state, message) self.program.update(&mut self.state, message)
} }
@ -357,10 +357,10 @@ impl<P: Definition> Program<P> {
} }
} }
/// Runs the [`Command`] produced by the closure at startup. /// Runs the [`Task`] produced by the closure at startup.
pub fn load( pub fn load(
self, self,
f: impl Fn() -> Command<P::Message>, f: impl Fn() -> Task<P::Message>,
) -> Program< ) -> Program<
impl Definition<State = P::State, Message = P::Message, Theme = P::Theme>, impl Definition<State = P::State, Message = P::Message, Theme = P::Theme>,
> { > {
@ -420,7 +420,7 @@ pub trait Definition: Sized {
type State; type State;
/// The message of the program. /// The message of the program.
type Message: Send + std::fmt::Debug; type Message: Send + std::fmt::Debug + 'static;
/// The theme of the program. /// The theme of the program.
type Theme: Default + DefaultStyle; type Theme: Default + DefaultStyle;
@ -431,13 +431,13 @@ pub trait Definition: Sized {
/// The executor of the program. /// The executor of the program.
type Executor: Executor; type Executor: Executor;
fn load(&self) -> Command<Self::Message>; fn load(&self) -> Task<Self::Message>;
fn update( fn update(
&self, &self,
state: &mut Self::State, state: &mut Self::State,
message: Self::Message, message: Self::Message,
) -> Command<Self::Message>; ) -> Task<Self::Message>;
fn view<'a>( fn view<'a>(
&self, &self,
@ -484,7 +484,7 @@ fn with_title<P: Definition>(
type Renderer = P::Renderer; type Renderer = P::Renderer;
type Executor = P::Executor; type Executor = P::Executor;
fn load(&self) -> Command<Self::Message> { fn load(&self) -> Task<Self::Message> {
self.program.load() self.program.load()
} }
@ -496,7 +496,7 @@ fn with_title<P: Definition>(
&self, &self,
state: &mut Self::State, state: &mut Self::State,
message: Self::Message, message: Self::Message,
) -> Command<Self::Message> { ) -> Task<Self::Message> {
self.program.update(state, message) self.program.update(state, message)
} }
@ -532,7 +532,7 @@ fn with_title<P: Definition>(
fn with_load<P: Definition>( fn with_load<P: Definition>(
program: P, program: P,
f: impl Fn() -> Command<P::Message>, f: impl Fn() -> Task<P::Message>,
) -> impl Definition<State = P::State, Message = P::Message, Theme = P::Theme> { ) -> impl Definition<State = P::State, Message = P::Message, Theme = P::Theme> {
struct WithLoad<P, F> { struct WithLoad<P, F> {
program: P, program: P,
@ -541,7 +541,7 @@ fn with_load<P: Definition>(
impl<P: Definition, F> Definition for WithLoad<P, F> impl<P: Definition, F> Definition for WithLoad<P, F>
where where
F: Fn() -> Command<P::Message>, F: Fn() -> Task<P::Message>,
{ {
type State = P::State; type State = P::State;
type Message = P::Message; type Message = P::Message;
@ -549,15 +549,15 @@ fn with_load<P: Definition>(
type Renderer = P::Renderer; type Renderer = P::Renderer;
type Executor = executor::Default; type Executor = executor::Default;
fn load(&self) -> Command<Self::Message> { fn load(&self) -> Task<Self::Message> {
Command::batch([self.program.load(), (self.load)()]) Task::batch([self.program.load(), (self.load)()])
} }
fn update( fn update(
&self, &self,
state: &mut Self::State, state: &mut Self::State,
message: Self::Message, message: Self::Message,
) -> Command<Self::Message> { ) -> Task<Self::Message> {
self.program.update(state, message) self.program.update(state, message)
} }
@ -621,7 +621,7 @@ fn with_subscription<P: Definition>(
(self.subscription)(state) (self.subscription)(state)
} }
fn load(&self) -> Command<Self::Message> { fn load(&self) -> Task<Self::Message> {
self.program.load() self.program.load()
} }
@ -629,7 +629,7 @@ fn with_subscription<P: Definition>(
&self, &self,
state: &mut Self::State, state: &mut Self::State,
message: Self::Message, message: Self::Message,
) -> Command<Self::Message> { ) -> Task<Self::Message> {
self.program.update(state, message) self.program.update(state, message)
} }
@ -686,7 +686,7 @@ fn with_theme<P: Definition>(
(self.theme)(state) (self.theme)(state)
} }
fn load(&self) -> Command<Self::Message> { fn load(&self) -> Task<Self::Message> {
self.program.load() self.program.load()
} }
@ -698,7 +698,7 @@ fn with_theme<P: Definition>(
&self, &self,
state: &mut Self::State, state: &mut Self::State,
message: Self::Message, message: Self::Message,
) -> Command<Self::Message> { ) -> Task<Self::Message> {
self.program.update(state, message) self.program.update(state, message)
} }
@ -755,7 +755,7 @@ fn with_style<P: Definition>(
(self.style)(state, theme) (self.style)(state, theme)
} }
fn load(&self) -> Command<Self::Message> { fn load(&self) -> Task<Self::Message> {
self.program.load() self.program.load()
} }
@ -767,7 +767,7 @@ fn with_style<P: Definition>(
&self, &self,
state: &mut Self::State, state: &mut Self::State,
message: Self::Message, message: Self::Message,
) -> Command<Self::Message> { ) -> Task<Self::Message> {
self.program.update(state, message) self.program.update(state, message)
} }
@ -822,26 +822,26 @@ where
/// The update logic of some [`Program`]. /// The update logic of some [`Program`].
/// ///
/// This trait allows the [`program`] builder to take any closure that /// This trait allows the [`program`] builder to take any closure that
/// returns any `Into<Command<Message>>`. /// returns any `Into<Task<Message>>`.
pub trait Update<State, Message> { pub trait Update<State, Message> {
/// Processes the message and updates the state of the [`Program`]. /// Processes the message and updates the state of the [`Program`].
fn update( fn update(
&self, &self,
state: &mut State, state: &mut State,
message: Message, message: Message,
) -> impl Into<Command<Message>>; ) -> impl Into<Task<Message>>;
} }
impl<T, State, Message, C> Update<State, Message> for T impl<T, State, Message, C> Update<State, Message> for T
where where
T: Fn(&mut State, Message) -> C, T: Fn(&mut State, Message) -> C,
C: Into<Command<Message>>, C: Into<Task<Message>>,
{ {
fn update( fn update(
&self, &self,
state: &mut State, state: &mut State,
message: Message, message: Message,
) -> impl Into<Command<Message>> { ) -> impl Into<Task<Message>> {
self(state, message) self(state, message)
} }
} }

View file

@ -205,7 +205,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
operation.container(None, layout.bounds(), &mut |operation| { operation.container(None, layout.bounds(), &mut |operation| {
self.content.as_widget().operate( self.content.as_widget().operate(

View file

@ -208,7 +208,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
operation.container(None, layout.bounds(), &mut |operation| { operation.container(None, layout.bounds(), &mut |operation| {
self.children self.children

View file

@ -13,7 +13,7 @@ use crate::core::{
Padding, Pixels, Point, Rectangle, Shadow, Shell, Size, Theme, Vector, Padding, Pixels, Point, Rectangle, Shadow, Shell, Size, Theme, Vector,
Widget, Widget,
}; };
use crate::runtime::Command; use crate::runtime::Task;
/// An element decorating some content. /// An element decorating some content.
/// ///
@ -258,7 +258,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
operation.container( operation.container(
self.id.as_ref().map(|id| &id.0), self.id.as_ref().map(|id| &id.0),
@ -457,9 +457,9 @@ impl From<Id> for widget::Id {
} }
} }
/// Produces a [`Command`] that queries the visible screen bounds of the /// Produces a [`Task`] that queries the visible screen bounds of the
/// [`Container`] with the given [`Id`]. /// [`Container`] with the given [`Id`].
pub fn visible_bounds(id: Id) -> Command<Option<Rectangle>> { pub fn visible_bounds(id: Id) -> Task<Option<Rectangle>> {
struct VisibleBounds { struct VisibleBounds {
target: widget::Id, target: widget::Id,
depth: usize, depth: usize,
@ -538,7 +538,7 @@ pub fn visible_bounds(id: Id) -> Command<Option<Rectangle>> {
} }
} }
Command::widget(VisibleBounds { Task::widget(VisibleBounds {
target: id.into(), target: id.into(),
depth: 0, depth: 0,
scrollables: Vec::new(), scrollables: Vec::new(),

View file

@ -12,7 +12,7 @@ use crate::pick_list::{self, PickList};
use crate::progress_bar::{self, ProgressBar}; use crate::progress_bar::{self, ProgressBar};
use crate::radio::{self, Radio}; use crate::radio::{self, Radio};
use crate::rule::{self, Rule}; use crate::rule::{self, Rule};
use crate::runtime::Command; use crate::runtime::{Action, Task};
use crate::scrollable::{self, Scrollable}; use crate::scrollable::{self, Scrollable};
use crate::slider::{self, Slider}; use crate::slider::{self, Slider};
use crate::text::{self, Text}; use crate::text::{self, Text};
@ -275,7 +275,7 @@ where
state: &mut Tree, state: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn operation::Operation<Message>, operation: &mut dyn operation::Operation<()>,
) { ) {
self.content self.content
.as_widget() .as_widget()
@ -477,7 +477,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn operation::Operation<Message>, operation: &mut dyn operation::Operation<()>,
) { ) {
let children = [&self.base, &self.top] let children = [&self.base, &self.top]
.into_iter() .into_iter()
@ -929,19 +929,13 @@ where
} }
/// Focuses the previous focusable widget. /// Focuses the previous focusable widget.
pub fn focus_previous<Message>() -> Command<Message> pub fn focus_previous<T>() -> Task<T> {
where Task::effect(Action::widget(operation::focusable::focus_previous()))
Message: 'static,
{
Command::widget(operation::focusable::focus_previous())
} }
/// Focuses the next focusable widget. /// Focuses the next focusable widget.
pub fn focus_next<Message>() -> Command<Message> pub fn focus_next<T>() -> Task<T> {
where Task::effect(Action::widget(operation::focusable::focus_next()))
Message: 'static,
{
Command::widget(operation::focusable::focus_next())
} }
/// A container intercepting mouse events. /// A container intercepting mouse events.

View file

@ -265,7 +265,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
operation.container(None, layout.bounds(), &mut |operation| { operation.container(None, layout.bounds(), &mut |operation| {
self.children self.children

View file

@ -182,7 +182,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
self.with_element(|element| { self.with_element(|element| {
element.as_widget().operate( element.as_widget().operate(

View file

@ -59,7 +59,7 @@ pub trait Component<Message, Theme = crate::Theme, Renderer = crate::Renderer> {
fn operate( fn operate(
&self, &self,
_state: &mut Self::State, _state: &mut Self::State,
_operation: &mut dyn widget::Operation<Message>, _operation: &mut dyn widget::Operation<()>,
) { ) {
} }
@ -172,7 +172,7 @@ where
fn rebuild_element_with_operation( fn rebuild_element_with_operation(
&self, &self,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
let heads = self.state.borrow_mut().take().unwrap().into_heads(); let heads = self.state.borrow_mut().take().unwrap().into_heads();
@ -358,70 +358,17 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
self.rebuild_element_with_operation(operation); self.rebuild_element_with_operation(operation);
struct MapOperation<'a, B> {
operation: &'a mut dyn widget::Operation<B>,
}
impl<'a, T, B> widget::Operation<T> for MapOperation<'a, B> {
fn container(
&mut self,
id: Option<&widget::Id>,
bounds: Rectangle,
operate_on_children: &mut dyn FnMut(
&mut dyn widget::Operation<T>,
),
) {
self.operation.container(id, bounds, &mut |operation| {
operate_on_children(&mut MapOperation { operation });
});
}
fn focusable(
&mut self,
state: &mut dyn widget::operation::Focusable,
id: Option<&widget::Id>,
) {
self.operation.focusable(state, id);
}
fn text_input(
&mut self,
state: &mut dyn widget::operation::TextInput,
id: Option<&widget::Id>,
) {
self.operation.text_input(state, id);
}
fn scrollable(
&mut self,
state: &mut dyn widget::operation::Scrollable,
id: Option<&widget::Id>,
bounds: Rectangle,
translation: Vector,
) {
self.operation.scrollable(state, id, bounds, translation);
}
fn custom(
&mut self,
state: &mut dyn std::any::Any,
id: Option<&widget::Id>,
) {
self.operation.custom(state, id);
}
}
let tree = tree.state.downcast_mut::<Rc<RefCell<Option<Tree>>>>(); let tree = tree.state.downcast_mut::<Rc<RefCell<Option<Tree>>>>();
self.with_element(|element| { self.with_element(|element| {
element.as_widget().operate( element.as_widget().operate(
&mut tree.borrow_mut().as_mut().unwrap().children[0], &mut tree.borrow_mut().as_mut().unwrap().children[0],
layout, layout,
renderer, renderer,
&mut MapOperation { operation }, operation,
); );
}); });
} }

View file

@ -161,7 +161,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
let state = tree.state.downcast_mut::<State>(); let state = tree.state.downcast_mut::<State>();
let mut content = self.content.borrow_mut(); let mut content = self.content.borrow_mut();

View file

@ -178,7 +178,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
self.content.as_widget().operate( self.content.as_widget().operate(
&mut tree.children[0], &mut tree.children[0],

View file

@ -324,7 +324,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
operation.container(None, layout.bounds(), &mut |operation| { operation.container(None, layout.bounds(), &mut |operation| {
self.contents self.contents

View file

@ -214,7 +214,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
let body_layout = if let Some(title_bar) = &self.title_bar { let body_layout = if let Some(title_bar) = &self.title_bar {
let mut children = layout.children(); let mut children = layout.children();

View file

@ -278,7 +278,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn widget::Operation<Message>, operation: &mut dyn widget::Operation<()>,
) { ) {
let mut children = layout.children(); let mut children = layout.children();
let padded = children.next().unwrap(); let padded = children.next().unwrap();

View file

@ -197,7 +197,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
operation.container(None, layout.bounds(), &mut |operation| { operation.container(None, layout.bounds(), &mut |operation| {
self.children self.children

View file

@ -15,7 +15,7 @@ use crate::core::{
self, Background, Border, Clipboard, Color, Element, Layout, Length, self, Background, Border, Clipboard, Color, Element, Layout, Length,
Pixels, Point, Rectangle, Shell, Size, Theme, Vector, Widget, Pixels, Point, Rectangle, Shell, Size, Theme, Vector, Widget,
}; };
use crate::runtime::Command; use crate::runtime::{Action, Task};
pub use operation::scrollable::{AbsoluteOffset, RelativeOffset}; pub use operation::scrollable::{AbsoluteOffset, RelativeOffset};
@ -295,7 +295,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
let state = tree.state.downcast_mut::<State>(); let state = tree.state.downcast_mut::<State>();
@ -952,22 +952,18 @@ impl From<Id> for widget::Id {
} }
} }
/// Produces a [`Command`] that snaps the [`Scrollable`] with the given [`Id`] /// Produces a [`Task`] that snaps the [`Scrollable`] with the given [`Id`]
/// to the provided `percentage` along the x & y axis. /// to the provided `percentage` along the x & y axis.
pub fn snap_to<Message: 'static>( pub fn snap_to<T>(id: Id, offset: RelativeOffset) -> Task<T> {
id: Id, Task::effect(Action::widget(operation::scrollable::snap_to(id.0, offset)))
offset: RelativeOffset,
) -> Command<Message> {
Command::widget(operation::scrollable::snap_to(id.0, offset))
} }
/// Produces a [`Command`] that scrolls the [`Scrollable`] with the given [`Id`] /// Produces a [`Task`] that scrolls the [`Scrollable`] with the given [`Id`]
/// to the provided [`AbsoluteOffset`] along the x & y axis. /// to the provided [`AbsoluteOffset`] along the x & y axis.
pub fn scroll_to<Message: 'static>( pub fn scroll_to<T>(id: Id, offset: AbsoluteOffset) -> Task<T> {
id: Id, Task::effect(Action::widget(operation::scrollable::scroll_to(
offset: AbsoluteOffset, id.0, offset,
) -> Command<Message> { )))
Command::widget(operation::scrollable::scroll_to(id.0, offset))
} }
/// Returns [`true`] if the viewport actually changed. /// Returns [`true`] if the viewport actually changed.

View file

@ -189,7 +189,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
operation.container(None, layout.bounds(), &mut |operation| { operation.container(None, layout.bounds(), &mut |operation| {
self.children self.children

View file

@ -30,7 +30,7 @@ use crate::core::{
Background, Border, Color, Element, Layout, Length, Padding, Pixels, Point, Background, Border, Color, Element, Layout, Length, Padding, Pixels, Point,
Rectangle, Shell, Size, Theme, Vector, Widget, Rectangle, Shell, Size, Theme, Vector, Widget,
}; };
use crate::runtime::Command; use crate::runtime::{Action, Task};
/// A field that can be filled with text. /// A field that can be filled with text.
/// ///
@ -540,7 +540,7 @@ where
tree: &mut Tree, tree: &mut Tree,
_layout: Layout<'_>, _layout: Layout<'_>,
_renderer: &Renderer, _renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>(); let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>();
@ -1140,35 +1140,38 @@ impl From<Id> for widget::Id {
} }
} }
/// Produces a [`Command`] that focuses the [`TextInput`] with the given [`Id`]. /// Produces a [`Task`] that focuses the [`TextInput`] with the given [`Id`].
pub fn focus<Message: 'static>(id: Id) -> Command<Message> { pub fn focus<T>(id: Id) -> Task<T> {
Command::widget(operation::focusable::focus(id.0)) Task::effect(Action::widget(operation::focusable::focus(id.0)))
} }
/// Produces a [`Command`] that moves the cursor of the [`TextInput`] with the given [`Id`] to the /// Produces a [`Task`] that moves the cursor of the [`TextInput`] with the given [`Id`] to the
/// end. /// end.
pub fn move_cursor_to_end<Message: 'static>(id: Id) -> Command<Message> { pub fn move_cursor_to_end<T>(id: Id) -> Task<T> {
Command::widget(operation::text_input::move_cursor_to_end(id.0)) Task::effect(Action::widget(operation::text_input::move_cursor_to_end(
id.0,
)))
} }
/// Produces a [`Command`] that moves the cursor of the [`TextInput`] with the given [`Id`] to the /// Produces a [`Task`] that moves the cursor of the [`TextInput`] with the given [`Id`] to the
/// front. /// front.
pub fn move_cursor_to_front<Message: 'static>(id: Id) -> Command<Message> { pub fn move_cursor_to_front<T>(id: Id) -> Task<T> {
Command::widget(operation::text_input::move_cursor_to_front(id.0)) Task::effect(Action::widget(operation::text_input::move_cursor_to_front(
id.0,
)))
} }
/// Produces a [`Command`] that moves the cursor of the [`TextInput`] with the given [`Id`] to the /// Produces a [`Task`] that moves the cursor of the [`TextInput`] with the given [`Id`] to the
/// provided position. /// provided position.
pub fn move_cursor_to<Message: 'static>( pub fn move_cursor_to<T>(id: Id, position: usize) -> Task<T> {
id: Id, Task::effect(Action::widget(operation::text_input::move_cursor_to(
position: usize, id.0, position,
) -> Command<Message> { )))
Command::widget(operation::text_input::move_cursor_to(id.0, position))
} }
/// Produces a [`Command`] that selects all the content of the [`TextInput`] with the given [`Id`]. /// Produces a [`Task`] that selects all the content of the [`TextInput`] with the given [`Id`].
pub fn select_all<Message: 'static>(id: Id) -> Command<Message> { pub fn select_all<T>(id: Id) -> Task<T> {
Command::widget(operation::text_input::select_all(id.0)) Task::effect(Action::widget(operation::text_input::select_all(id.0)))
} }
/// The state of a [`TextInput`]. /// The state of a [`TextInput`].

View file

@ -104,7 +104,7 @@ where
tree: &mut Tree, tree: &mut Tree,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
self.content self.content
.as_widget() .as_widget()
@ -236,7 +236,7 @@ where
&mut self, &mut self,
layout: Layout<'_>, layout: Layout<'_>,
renderer: &Renderer, renderer: &Renderer,
operation: &mut dyn Operation<Message>, operation: &mut dyn Operation<()>,
) { ) {
self.content.operate(layout, renderer, operation); self.content.operate(layout, renderer, operation);
} }

View file

@ -19,7 +19,7 @@ use crate::graphics::compositor::{self, Compositor};
use crate::runtime::clipboard; use crate::runtime::clipboard;
use crate::runtime::program::Program; use crate::runtime::program::Program;
use crate::runtime::user_interface::{self, UserInterface}; use crate::runtime::user_interface::{self, UserInterface};
use crate::runtime::{Command, Debug}; use crate::runtime::{Action, Debug, Task};
use crate::{Clipboard, Error, Proxy, Settings}; use crate::{Clipboard, Error, Proxy, Settings};
use futures::channel::mpsc; use futures::channel::mpsc;
@ -36,7 +36,7 @@ use std::sync::Arc;
/// its own window. /// its own window.
/// ///
/// An [`Application`] can execute asynchronous actions by returning a /// An [`Application`] can execute asynchronous actions by returning a
/// [`Command`] in some of its methods. /// [`Task`] in some of its methods.
/// ///
/// When using an [`Application`] with the `debug` feature enabled, a debug view /// When using an [`Application`] with the `debug` feature enabled, a debug view
/// can be toggled by pressing `F12`. /// can be toggled by pressing `F12`.
@ -52,10 +52,10 @@ where
/// ///
/// Here is where you should return the initial state of your app. /// Here is where you should return the initial state of your app.
/// ///
/// Additionally, you can return a [`Command`] if you need to perform some /// Additionally, you can return a [`Task`] if you need to perform some
/// async action in the background on startup. This is useful if you want to /// async action in the background on startup. This is useful if you want to
/// load state from a file, perform an initial HTTP request, etc. /// load state from a file, perform an initial HTTP request, etc.
fn new(flags: Self::Flags) -> (Self, Command<Self::Message>); fn new(flags: Self::Flags) -> (Self, Task<Self::Message>);
/// Returns the current title of the [`Application`]. /// Returns the current title of the [`Application`].
/// ///
@ -155,19 +155,23 @@ where
let (proxy, worker) = Proxy::new(event_loop.create_proxy()); let (proxy, worker) = Proxy::new(event_loop.create_proxy());
let runtime = { let mut runtime = {
let executor = E::new().map_err(Error::ExecutorCreationFailed)?; let executor = E::new().map_err(Error::ExecutorCreationFailed)?;
executor.spawn(worker); executor.spawn(worker);
Runtime::new(executor, proxy.clone()) Runtime::new(executor, proxy.clone())
}; };
let (application, init_command) = { let (application, task) = {
let flags = settings.flags; let flags = settings.flags;
runtime.enter(|| A::new(flags)) runtime.enter(|| A::new(flags))
}; };
if let Some(stream) = task.into_stream() {
runtime.run(stream);
}
let id = settings.id; let id = settings.id;
let title = application.title(); let title = application.title();
@ -183,7 +187,6 @@ where
boot_receiver, boot_receiver,
event_receiver, event_receiver,
control_sender, control_sender,
init_command,
settings.fonts, settings.fonts,
)); ));
@ -193,7 +196,7 @@ where
instance: std::pin::Pin<Box<F>>, instance: std::pin::Pin<Box<F>>,
context: task::Context<'static>, context: task::Context<'static>,
boot: Option<BootConfig<C>>, boot: Option<BootConfig<C>>,
sender: mpsc::UnboundedSender<winit::event::Event<Message>>, sender: mpsc::UnboundedSender<winit::event::Event<Action<Message>>>,
receiver: mpsc::UnboundedReceiver<winit::event_loop::ControlFlow>, receiver: mpsc::UnboundedReceiver<winit::event_loop::ControlFlow>,
error: Option<Error>, error: Option<Error>,
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
@ -229,7 +232,7 @@ where
queued_events: Vec::new(), queued_events: Vec::new(),
}; };
impl<Message, F, C> winit::application::ApplicationHandler<Message> impl<Message, F, C> winit::application::ApplicationHandler<Action<Message>>
for Runner<Message, F, C> for Runner<Message, F, C>
where where
F: Future<Output = ()>, F: Future<Output = ()>,
@ -393,11 +396,11 @@ where
fn user_event( fn user_event(
&mut self, &mut self,
event_loop: &winit::event_loop::ActiveEventLoop, event_loop: &winit::event_loop::ActiveEventLoop,
message: Message, action: Action<Message>,
) { ) {
self.process_event( self.process_event(
event_loop, event_loop,
winit::event::Event::UserEvent(message), winit::event::Event::UserEvent(action),
); );
} }
@ -416,7 +419,7 @@ where
fn process_event( fn process_event(
&mut self, &mut self,
event_loop: &winit::event_loop::ActiveEventLoop, event_loop: &winit::event_loop::ActiveEventLoop,
event: winit::event::Event<Message>, event: winit::event::Event<Action<Message>>,
) { ) {
// On Wasm, events may start being processed before the compositor // On Wasm, events may start being processed before the compositor
// boots up. We simply queue them and process them once ready. // boots up. We simply queue them and process them once ready.
@ -480,15 +483,14 @@ struct Boot<C> {
async fn run_instance<A, E, C>( async fn run_instance<A, E, C>(
mut application: A, mut application: A,
mut runtime: Runtime<E, Proxy<A::Message>, A::Message>, mut runtime: Runtime<E, Proxy<A::Message>, Action<A::Message>>,
mut proxy: Proxy<A::Message>, mut proxy: Proxy<A::Message>,
mut debug: Debug, mut debug: Debug,
mut boot: oneshot::Receiver<Boot<C>>, mut boot: oneshot::Receiver<Boot<C>>,
mut event_receiver: mpsc::UnboundedReceiver< mut event_receiver: mpsc::UnboundedReceiver<
winit::event::Event<A::Message>, winit::event::Event<Action<A::Message>>,
>, >,
mut control_sender: mpsc::UnboundedSender<winit::event_loop::ControlFlow>, mut control_sender: mpsc::UnboundedSender<winit::event_loop::ControlFlow>,
init_command: Command<A::Message>,
fonts: Vec<Cow<'static, [u8]>>, fonts: Vec<Cow<'static, [u8]>>,
) where ) where
A: Application + 'static, A: Application + 'static,
@ -518,7 +520,7 @@ async fn run_instance<A, E, C>(
let physical_size = state.physical_size(); let physical_size = state.physical_size();
let mut clipboard = Clipboard::connect(&window); let mut clipboard = Clipboard::connect(&window);
let mut cache = user_interface::Cache::default(); let cache = user_interface::Cache::default();
let mut surface = compositor.create_surface( let mut surface = compositor.create_surface(
window.clone(), window.clone(),
physical_size.width, physical_size.width,
@ -530,22 +532,12 @@ async fn run_instance<A, E, C>(
window.set_visible(true); window.set_visible(true);
} }
run_command( runtime.track(
&application, application
&mut compositor, .subscription()
&mut surface, .map(Action::Output)
&mut cache, .into_recipes(),
&state,
&mut renderer,
init_command,
&mut runtime,
&mut clipboard,
&mut should_exit,
&mut proxy,
&mut debug,
&window,
); );
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,
@ -581,8 +573,21 @@ async fn run_instance<A, E, C>(
), ),
)); ));
} }
event::Event::UserEvent(message) => { event::Event::UserEvent(action) => {
messages.push(message); run_action(
action,
&mut user_interface,
&mut compositor,
&mut surface,
&state,
&mut renderer,
&mut messages,
&mut clipboard,
&mut should_exit,
&mut debug,
&window,
);
user_events += 1; user_events += 1;
} }
event::Event::WindowEvent { event::Event::WindowEvent {
@ -756,21 +761,14 @@ async fn run_instance<A, E, C>(
user_interface::State::Outdated user_interface::State::Outdated
) )
{ {
let mut cache = let cache =
ManuallyDrop::into_inner(user_interface).into_cache(); ManuallyDrop::into_inner(user_interface).into_cache();
// Update application // Update application
update( update(
&mut application, &mut application,
&mut compositor,
&mut surface,
&mut cache,
&mut state, &mut state,
&mut renderer,
&mut runtime, &mut runtime,
&mut clipboard,
&mut should_exit,
&mut proxy,
&mut debug, &mut debug,
&mut messages, &mut messages,
&window, &window,
@ -855,148 +853,114 @@ where
} }
/// Updates an [`Application`] by feeding it the provided messages, spawning any /// Updates an [`Application`] by feeding it the provided messages, spawning any
/// resulting [`Command`], and tracking its [`Subscription`]. /// resulting [`Task`], and tracking its [`Subscription`].
pub fn update<A: Application, C, E: Executor>( pub fn update<A: Application, E: Executor>(
application: &mut A, application: &mut A,
compositor: &mut C,
surface: &mut C::Surface,
cache: &mut user_interface::Cache,
state: &mut State<A>, state: &mut State<A>,
renderer: &mut A::Renderer, runtime: &mut Runtime<E, Proxy<A::Message>, Action<A::Message>>,
runtime: &mut Runtime<E, Proxy<A::Message>, A::Message>,
clipboard: &mut Clipboard,
should_exit: &mut bool,
proxy: &mut Proxy<A::Message>,
debug: &mut Debug, debug: &mut Debug,
messages: &mut Vec<A::Message>, messages: &mut Vec<A::Message>,
window: &winit::window::Window, window: &winit::window::Window,
) where ) where
C: Compositor<Renderer = A::Renderer> + 'static,
A::Theme: DefaultStyle, A::Theme: DefaultStyle,
{ {
for message in messages.drain(..) { for message in messages.drain(..) {
debug.log_message(&message); debug.log_message(&message);
debug.update_started(); debug.update_started();
let command = runtime.enter(|| application.update(message)); let task = runtime.enter(|| application.update(message));
debug.update_finished(); debug.update_finished();
run_command( if let Some(stream) = task.into_stream() {
application, runtime.run(stream);
compositor, }
surface,
cache,
state,
renderer,
command,
runtime,
clipboard,
should_exit,
proxy,
debug,
window,
);
} }
state.synchronize(application, window); state.synchronize(application, window);
let subscription = application.subscription(); let subscription = application.subscription();
runtime.track(subscription.into_recipes()); runtime.track(subscription.map(Action::Output).into_recipes());
} }
/// Runs the actions of a [`Command`]. /// Runs the actions of a [`Task`].
pub fn run_command<A, C, E>( pub fn run_action<A, C>(
application: &A, action: Action<A::Message>,
user_interface: &mut UserInterface<'_, A::Message, A::Theme, C::Renderer>,
compositor: &mut C, compositor: &mut C,
surface: &mut C::Surface, surface: &mut C::Surface,
cache: &mut user_interface::Cache,
state: &State<A>, state: &State<A>,
renderer: &mut A::Renderer, renderer: &mut A::Renderer,
command: Command<A::Message>, messages: &mut Vec<A::Message>,
runtime: &mut Runtime<E, Proxy<A::Message>, A::Message>,
clipboard: &mut Clipboard, clipboard: &mut Clipboard,
should_exit: &mut bool, should_exit: &mut bool,
proxy: &mut Proxy<A::Message>,
debug: &mut Debug, debug: &mut Debug,
window: &winit::window::Window, window: &winit::window::Window,
) where ) where
A: Application, A: Application,
E: Executor,
C: Compositor<Renderer = A::Renderer> + 'static, C: Compositor<Renderer = A::Renderer> + 'static,
A::Theme: DefaultStyle, A::Theme: DefaultStyle,
{ {
use crate::runtime::command;
use crate::runtime::system; use crate::runtime::system;
use crate::runtime::window; use crate::runtime::window;
for action in command.actions() {
match action { match action {
command::Action::Future(future) => { Action::Clipboard(action) => match action {
runtime.spawn(future); clipboard::Action::Read { target, channel } => {
let _ = channel.send(clipboard.read(target));
} }
command::Action::Stream(stream) => { clipboard::Action::Write { target, contents } => {
runtime.run(stream); clipboard.write(target, contents);
}
command::Action::Clipboard(action) => match action {
clipboard::Action::Read(tag, kind) => {
let message = tag(clipboard.read(kind));
proxy.send(message);
}
clipboard::Action::Write(contents, kind) => {
clipboard.write(kind, contents);
} }
}, },
command::Action::Window(action) => match action { Action::Window(action) => match action {
window::Action::Close(_id) => { window::Action::Close(_id) => {
*should_exit = true; *should_exit = true;
} }
window::Action::Drag(_id) => { window::Action::Drag(_id) => {
let _res = window.drag_window(); let _res = window.drag_window();
} }
window::Action::Spawn { .. } => { window::Action::Open { .. } => {
log::warn!( log::warn!(
"Spawning a window is only available with \ "Spawning a window is only available with \
multi-window applications." multi-window applications."
); );
} }
window::Action::Resize(_id, size) => { window::Action::Resize(_id, size) => {
let _ = let _ = window.request_inner_size(winit::dpi::LogicalSize {
window.request_inner_size(winit::dpi::LogicalSize {
width: size.width, width: size.width,
height: size.height, height: size.height,
}); });
} }
window::Action::FetchSize(_id, callback) => { window::Action::FetchSize(_id, channel) => {
let size = let size =
window.inner_size().to_logical(window.scale_factor()); window.inner_size().to_logical(window.scale_factor());
proxy.send(callback(Size::new(size.width, size.height))); let _ = channel.send(Size::new(size.width, size.height));
} }
window::Action::FetchMaximized(_id, callback) => { window::Action::FetchMaximized(_id, channel) => {
proxy.send(callback(window.is_maximized())); let _ = channel.send(window.is_maximized());
} }
window::Action::Maximize(_id, maximized) => { window::Action::Maximize(_id, maximized) => {
window.set_maximized(maximized); window.set_maximized(maximized);
} }
window::Action::FetchMinimized(_id, callback) => { window::Action::FetchMinimized(_id, channel) => {
proxy.send(callback(window.is_minimized())); let _ = channel.send(window.is_minimized());
} }
window::Action::Minimize(_id, minimized) => { window::Action::Minimize(_id, minimized) => {
window.set_minimized(minimized); window.set_minimized(minimized);
} }
window::Action::FetchPosition(_id, callback) => { window::Action::FetchPosition(_id, channel) => {
let position = window let position = window
.inner_position() .inner_position()
.map(|position| { .map(|position| {
let position = position let position =
.to_logical::<f32>(window.scale_factor()); position.to_logical::<f32>(window.scale_factor());
Point::new(position.x, position.y) Point::new(position.x, position.y)
}) })
.ok(); .ok();
proxy.send(callback(position)); let _ = channel.send(position);
} }
window::Action::Move(_id, position) => { window::Action::Move(_id, position) => {
window.set_outer_position(winit::dpi::LogicalPosition { window.set_outer_position(winit::dpi::LogicalPosition {
@ -1014,14 +978,14 @@ pub fn run_command<A, C, E>(
window::Action::ChangeIcon(_id, icon) => { window::Action::ChangeIcon(_id, icon) => {
window.set_window_icon(conversion::icon(icon)); window.set_window_icon(conversion::icon(icon));
} }
window::Action::FetchMode(_id, tag) => { window::Action::FetchMode(_id, channel) => {
let mode = if window.is_visible().unwrap_or(true) { let mode = if window.is_visible().unwrap_or(true) {
conversion::mode(window.fullscreen()) conversion::mode(window.fullscreen())
} else { } else {
core::window::Mode::Hidden core::window::Mode::Hidden
}; };
proxy.send(tag(mode)); let _ = channel.send(mode);
} }
window::Action::ToggleMaximize(_id) => { window::Action::ToggleMaximize(_id) => {
window.set_maximized(!window.is_maximized()); window.set_maximized(!window.is_maximized());
@ -1048,18 +1012,18 @@ pub fn run_command<A, C, E>(
}); });
} }
} }
window::Action::FetchId(_id, tag) => { window::Action::FetchRawId(_id, channel) => {
proxy.send(tag(window.id().into())); let _ = channel.send(window.id().into());
} }
window::Action::RunWithHandle(_id, tag) => { window::Action::RunWithHandle(_id, f) => {
use window::raw_window_handle::HasWindowHandle; use window::raw_window_handle::HasWindowHandle;
if let Ok(handle) = window.window_handle() { if let Ok(handle) = window.window_handle() {
proxy.send(tag(handle)); f(handle);
} }
} }
window::Action::Screenshot(_id, tag) => { window::Action::Screenshot(_id, channel) => {
let bytes = compositor.screenshot( let bytes = compositor.screenshot(
renderer, renderer,
surface, surface,
@ -1068,69 +1032,51 @@ pub fn run_command<A, C, E>(
&debug.overlay(), &debug.overlay(),
); );
proxy.send(tag(window::Screenshot::new( let _ = channel.send(window::Screenshot::new(
bytes, bytes,
state.physical_size(), state.physical_size(),
state.viewport().scale_factor(), state.viewport().scale_factor(),
))); ));
} }
}, },
command::Action::System(action) => match action { Action::System(action) => match action {
system::Action::QueryInformation(_tag) => { system::Action::QueryInformation(_channel) => {
#[cfg(feature = "system")] #[cfg(feature = "system")]
{ {
let graphics_info = compositor.fetch_information(); let graphics_info = compositor.fetch_information();
let mut proxy = proxy.clone();
let _ = std::thread::spawn(move || { let _ = std::thread::spawn(move || {
let information = let information =
crate::system::information(graphics_info); crate::system::information(graphics_info);
let message = _tag(information); let _ = _channel.send(information);
proxy.send(message);
}); });
} }
} }
}, },
command::Action::Widget(action) => { Action::Widget(operation) => {
let mut current_cache = std::mem::take(cache); let mut current_operation = Some(operation);
let mut current_operation = Some(action);
let mut user_interface = build_user_interface(
application,
current_cache,
renderer,
state.logical_size(),
debug,
);
while let Some(mut operation) = current_operation.take() { while let Some(mut operation) = current_operation.take() {
user_interface.operate(renderer, operation.as_mut()); user_interface.operate(renderer, operation.as_mut());
match operation.finish() { match operation.finish() {
operation::Outcome::None => {} operation::Outcome::None => {}
operation::Outcome::Some(message) => { operation::Outcome::Some(()) => {}
proxy.send(message);
}
operation::Outcome::Chain(next) => { operation::Outcome::Chain(next) => {
current_operation = Some(next); current_operation = Some(next);
} }
} }
} }
current_cache = user_interface.into_cache();
*cache = current_cache;
} }
command::Action::LoadFont { bytes, tagger } => { Action::LoadFont { bytes, channel } => {
// TODO: Error handling (?) // TODO: Error handling (?)
compositor.load_font(bytes); compositor.load_font(bytes);
proxy.send(tagger(Ok(()))); let _ = channel.send(Ok(()));
}
command::Action::Custom(_) => {
log::warn!("Unsupported custom action in `iced_winit` shell");
} }
Action::Output(message) => {
messages.push(message);
} }
} }
} }

View file

@ -21,10 +21,10 @@ use crate::futures::{Executor, Runtime};
use crate::graphics; use crate::graphics;
use crate::graphics::{compositor, Compositor}; use crate::graphics::{compositor, Compositor};
use crate::multi_window::window_manager::WindowManager; use crate::multi_window::window_manager::WindowManager;
use crate::runtime::command::{self, Command};
use crate::runtime::multi_window::Program; use crate::runtime::multi_window::Program;
use crate::runtime::user_interface::{self, UserInterface}; use crate::runtime::user_interface::{self, UserInterface};
use crate::runtime::Debug; use crate::runtime::Debug;
use crate::runtime::{Action, Task};
use crate::{Clipboard, Error, Proxy, Settings}; use crate::{Clipboard, Error, Proxy, Settings};
pub use crate::application::{default, Appearance, DefaultStyle}; pub use crate::application::{default, Appearance, DefaultStyle};
@ -41,7 +41,7 @@ use std::time::Instant;
/// its own window. /// its own window.
/// ///
/// An [`Application`] can execute asynchronous actions by returning a /// An [`Application`] can execute asynchronous actions by returning a
/// [`Command`] in some of its methods. /// [`Task`] in some of its methods.
/// ///
/// When using an [`Application`] with the `debug` feature enabled, a debug view /// When using an [`Application`] with the `debug` feature enabled, a debug view
/// can be toggled by pressing `F12`. /// can be toggled by pressing `F12`.
@ -57,10 +57,10 @@ where
/// ///
/// Here is where you should return the initial state of your app. /// Here is where you should return the initial state of your app.
/// ///
/// Additionally, you can return a [`Command`] if you need to perform some /// Additionally, you can return a [`Task`] if you need to perform some
/// async action in the background on startup. This is useful if you want to /// async action in the background on startup. This is useful if you want to
/// load state from a file, perform an initial HTTP request, etc. /// load state from a file, perform an initial HTTP request, etc.
fn new(flags: Self::Flags) -> (Self, Command<Self::Message>); fn new(flags: Self::Flags) -> (Self, Task<Self::Message>);
/// Returns the current title of the [`Application`]. /// Returns the current title of the [`Application`].
/// ///
@ -127,19 +127,23 @@ where
let (proxy, worker) = Proxy::new(event_loop.create_proxy()); let (proxy, worker) = Proxy::new(event_loop.create_proxy());
let runtime = { let mut runtime = {
let executor = E::new().map_err(Error::ExecutorCreationFailed)?; let executor = E::new().map_err(Error::ExecutorCreationFailed)?;
executor.spawn(worker); executor.spawn(worker);
Runtime::new(executor, proxy.clone()) Runtime::new(executor, proxy.clone())
}; };
let (application, init_command) = { let (application, task) = {
let flags = settings.flags; let flags = settings.flags;
runtime.enter(|| A::new(flags)) runtime.enter(|| A::new(flags))
}; };
if let Some(stream) = task.into_stream() {
runtime.run(stream);
}
let id = settings.id; let id = settings.id;
let title = application.title(window::Id::MAIN); let title = application.title(window::Id::MAIN);
@ -155,7 +159,6 @@ where
boot_receiver, boot_receiver,
event_receiver, event_receiver,
control_sender, control_sender,
init_command,
)); ));
let context = task::Context::from_waker(task::noop_waker_ref()); let context = task::Context::from_waker(task::noop_waker_ref());
@ -448,13 +451,12 @@ enum Control {
async fn run_instance<A, E, C>( async fn run_instance<A, E, C>(
mut application: A, mut application: A,
mut runtime: Runtime<E, Proxy<A::Message>, A::Message>, mut runtime: Runtime<E, Proxy<A::Message>, Action<A::Message>>,
mut proxy: Proxy<A::Message>, mut proxy: Proxy<A::Message>,
mut debug: Debug, mut debug: Debug,
mut boot: oneshot::Receiver<Boot<C>>, mut boot: oneshot::Receiver<Boot<C>>,
mut event_receiver: mpsc::UnboundedReceiver<Event<A::Message>>, mut event_receiver: mpsc::UnboundedReceiver<Event<Action<A::Message>>>,
mut control_sender: mpsc::UnboundedSender<Control>, mut control_sender: mpsc::UnboundedSender<Control>,
init_command: Command<A::Message>,
) where ) where
A: Application + 'static, A: Application + 'static,
E: Executor + 'static, E: Executor + 'static,
@ -511,21 +513,13 @@ async fn run_instance<A, E, C>(
)]), )]),
)); ));
run_command( runtime.track(
&application, application
&mut compositor, .subscription()
init_command, .map(Action::Output)
&mut runtime, .into_recipes(),
&mut clipboard,
&mut control_sender,
&mut proxy,
&mut debug,
&mut window_manager,
&mut ui_caches,
); );
runtime.track(application.subscription().into_recipes());
let mut messages = Vec::new(); let mut messages = Vec::new();
let mut user_events = 0; let mut user_events = 0;
@ -594,8 +588,19 @@ async fn run_instance<A, E, C>(
), ),
); );
} }
event::Event::UserEvent(message) => { event::Event::UserEvent(action) => {
messages.push(message); run_action(
action,
&application,
&mut compositor,
&mut messages,
&mut clipboard,
&mut control_sender,
&mut debug,
&mut user_interfaces,
&mut window_manager,
&mut ui_caches,
);
user_events += 1; user_events += 1;
} }
event::Event::WindowEvent { event::Event::WindowEvent {
@ -888,7 +893,7 @@ async fn run_instance<A, E, C>(
// TODO mw application update returns which window IDs to update // TODO mw application update returns which window IDs to update
if !messages.is_empty() || uis_stale { if !messages.is_empty() || uis_stale {
let mut cached_interfaces: FxHashMap< let cached_interfaces: FxHashMap<
window::Id, window::Id,
user_interface::Cache, user_interface::Cache,
> = ManuallyDrop::into_inner(user_interfaces) > = ManuallyDrop::into_inner(user_interfaces)
@ -899,15 +904,9 @@ async fn run_instance<A, E, C>(
// Update application // Update application
update( update(
&mut application, &mut application,
&mut compositor,
&mut runtime, &mut runtime,
&mut clipboard,
&mut control_sender,
&mut proxy,
&mut debug, &mut debug,
&mut messages, &mut messages,
&mut window_manager,
&mut cached_interfaces,
); );
// we must synchronize all window states with application state after an // we must synchronize all window states with application state after an
@ -971,63 +970,46 @@ where
user_interface user_interface
} }
/// Updates a multi-window [`Application`] by feeding it messages, spawning any fn update<A: Application, E: Executor>(
/// resulting [`Command`], and tracking its [`Subscription`].
fn update<A: Application, C, E: Executor>(
application: &mut A, application: &mut A,
compositor: &mut C, runtime: &mut Runtime<E, Proxy<A::Message>, Action<A::Message>>,
runtime: &mut Runtime<E, Proxy<A::Message>, A::Message>,
clipboard: &mut Clipboard,
control_sender: &mut mpsc::UnboundedSender<Control>,
proxy: &mut Proxy<A::Message>,
debug: &mut Debug, debug: &mut Debug,
messages: &mut Vec<A::Message>, messages: &mut Vec<A::Message>,
window_manager: &mut WindowManager<A, C>,
ui_caches: &mut FxHashMap<window::Id, user_interface::Cache>,
) where ) where
C: Compositor<Renderer = A::Renderer> + 'static,
A::Theme: DefaultStyle, A::Theme: DefaultStyle,
{ {
for message in messages.drain(..) { for message in messages.drain(..) {
debug.log_message(&message); debug.log_message(&message);
debug.update_started(); debug.update_started();
let command = runtime.enter(|| application.update(message)); let task = runtime.enter(|| application.update(message));
debug.update_finished(); debug.update_finished();
run_command( if let Some(stream) = task.into_stream() {
application, runtime.run(stream);
compositor, }
command,
runtime,
clipboard,
control_sender,
proxy,
debug,
window_manager,
ui_caches,
);
} }
let subscription = application.subscription(); let subscription = application.subscription();
runtime.track(subscription.into_recipes()); runtime.track(subscription.map(Action::Output).into_recipes());
} }
/// Runs the actions of a [`Command`]. fn run_action<A, C>(
fn run_command<A, C, E>( action: Action<A::Message>,
application: &A, application: &A,
compositor: &mut C, compositor: &mut C,
command: Command<A::Message>, messages: &mut Vec<A::Message>,
runtime: &mut Runtime<E, Proxy<A::Message>, A::Message>,
clipboard: &mut Clipboard, clipboard: &mut Clipboard,
control_sender: &mut mpsc::UnboundedSender<Control>, control_sender: &mut mpsc::UnboundedSender<Control>,
proxy: &mut Proxy<A::Message>,
debug: &mut Debug, debug: &mut Debug,
interfaces: &mut FxHashMap<
window::Id,
UserInterface<'_, A::Message, A::Theme, A::Renderer>,
>,
window_manager: &mut WindowManager<A, C>, window_manager: &mut WindowManager<A, C>,
ui_caches: &mut FxHashMap<window::Id, user_interface::Cache>, ui_caches: &mut FxHashMap<window::Id, user_interface::Cache>,
) where ) where
A: Application, A: Application,
E: Executor,
C: Compositor<Renderer = A::Renderer> + 'static, C: Compositor<Renderer = A::Renderer> + 'static,
A::Theme: DefaultStyle, A::Theme: DefaultStyle,
{ {
@ -1035,26 +1017,20 @@ fn run_command<A, C, E>(
use crate::runtime::system; use crate::runtime::system;
use crate::runtime::window; use crate::runtime::window;
for action in command.actions() {
match action { match action {
command::Action::Future(future) => { Action::Output(message) => {
runtime.spawn(Box::pin(future)); messages.push(message);
} }
command::Action::Stream(stream) => { Action::Clipboard(action) => match action {
runtime.run(Box::pin(stream)); clipboard::Action::Read { target, channel } => {
let _ = channel.send(clipboard.read(target));
} }
command::Action::Clipboard(action) => match action { clipboard::Action::Write { target, contents } => {
clipboard::Action::Read(tag, kind) => { clipboard.write(target, contents);
let message = tag(clipboard.read(kind));
proxy.send(message);
}
clipboard::Action::Write(contents, kind) => {
clipboard.write(kind, contents);
} }
}, },
command::Action::Window(action) => match action { Action::Window(action) => match action {
window::Action::Spawn(id, settings) => { window::Action::Open(id, settings) => {
let monitor = window_manager.last_monitor(); let monitor = window_manager.last_monitor();
control_sender control_sender
@ -1091,20 +1067,19 @@ fn run_command<A, C, E>(
); );
} }
} }
window::Action::FetchSize(id, callback) => { window::Action::FetchSize(id, channel) => {
if let Some(window) = window_manager.get_mut(id) { if let Some(window) = window_manager.get_mut(id) {
let size = window let size = window
.raw .raw
.inner_size() .inner_size()
.to_logical(window.raw.scale_factor()); .to_logical(window.raw.scale_factor());
proxy let _ = channel.send(Size::new(size.width, size.height));
.send(callback(Size::new(size.width, size.height)));
} }
} }
window::Action::FetchMaximized(id, callback) => { window::Action::FetchMaximized(id, channel) => {
if let Some(window) = window_manager.get_mut(id) { if let Some(window) = window_manager.get_mut(id) {
proxy.send(callback(window.raw.is_maximized())); let _ = channel.send(window.raw.is_maximized());
} }
} }
window::Action::Maximize(id, maximized) => { window::Action::Maximize(id, maximized) => {
@ -1112,9 +1087,9 @@ fn run_command<A, C, E>(
window.raw.set_maximized(maximized); window.raw.set_maximized(maximized);
} }
} }
window::Action::FetchMinimized(id, callback) => { window::Action::FetchMinimized(id, channel) => {
if let Some(window) = window_manager.get_mut(id) { if let Some(window) = window_manager.get_mut(id) {
proxy.send(callback(window.raw.is_minimized())); let _ = channel.send(window.raw.is_minimized());
} }
} }
window::Action::Minimize(id, minimized) => { window::Action::Minimize(id, minimized) => {
@ -1122,21 +1097,20 @@ fn run_command<A, C, E>(
window.raw.set_minimized(minimized); window.raw.set_minimized(minimized);
} }
} }
window::Action::FetchPosition(id, callback) => { window::Action::FetchPosition(id, channel) => {
if let Some(window) = window_manager.get_mut(id) { if let Some(window) = window_manager.get_mut(id) {
let position = window let position = window
.raw .raw
.inner_position() .inner_position()
.map(|position| { .map(|position| {
let position = position.to_logical::<f32>( let position = position
window.raw.scale_factor(), .to_logical::<f32>(window.raw.scale_factor());
);
Point::new(position.x, position.y) Point::new(position.x, position.y)
}) })
.ok(); .ok();
proxy.send(callback(position)); let _ = channel.send(position);
} }
} }
window::Action::Move(id, position) => { window::Action::Move(id, position) => {
@ -1163,7 +1137,7 @@ fn run_command<A, C, E>(
window.raw.set_window_icon(conversion::icon(icon)); window.raw.set_window_icon(conversion::icon(icon));
} }
} }
window::Action::FetchMode(id, tag) => { window::Action::FetchMode(id, channel) => {
if let Some(window) = window_manager.get_mut(id) { if let Some(window) = window_manager.get_mut(id) {
let mode = if window.raw.is_visible().unwrap_or(true) { let mode = if window.raw.is_visible().unwrap_or(true) {
conversion::mode(window.raw.fullscreen()) conversion::mode(window.raw.fullscreen())
@ -1171,7 +1145,7 @@ fn run_command<A, C, E>(
core::window::Mode::Hidden core::window::Mode::Hidden
}; };
proxy.send(tag(mode)); let _ = channel.send(mode);
} }
} }
window::Action::ToggleMaximize(id) => { window::Action::ToggleMaximize(id) => {
@ -1217,22 +1191,22 @@ fn run_command<A, C, E>(
} }
} }
} }
window::Action::FetchId(id, tag) => { window::Action::FetchRawId(id, channel) => {
if let Some(window) = window_manager.get_mut(id) { if let Some(window) = window_manager.get_mut(id) {
proxy.send(tag(window.raw.id().into())); let _ = channel.send(window.raw.id().into());
} }
} }
window::Action::RunWithHandle(id, tag) => { window::Action::RunWithHandle(id, f) => {
use window::raw_window_handle::HasWindowHandle; use window::raw_window_handle::HasWindowHandle;
if let Some(handle) = window_manager if let Some(handle) = window_manager
.get_mut(id) .get_mut(id)
.and_then(|window| window.raw.window_handle().ok()) .and_then(|window| window.raw.window_handle().ok())
{ {
proxy.send(tag(handle)); f(handle);
} }
} }
window::Action::Screenshot(id, tag) => { window::Action::Screenshot(id, channel) => {
if let Some(window) = window_manager.get_mut(id) { if let Some(window) = window_manager.get_mut(id) {
let bytes = compositor.screenshot( let bytes = compositor.screenshot(
&mut window.renderer, &mut window.renderer,
@ -1242,44 +1216,34 @@ fn run_command<A, C, E>(
&debug.overlay(), &debug.overlay(),
); );
proxy.send(tag(window::Screenshot::new( let _ = channel.send(window::Screenshot::new(
bytes, bytes,
window.state.physical_size(), window.state.physical_size(),
window.state.viewport().scale_factor(), window.state.viewport().scale_factor(),
))); ));
} }
} }
}, },
command::Action::System(action) => match action { Action::System(action) => match action {
system::Action::QueryInformation(_tag) => { system::Action::QueryInformation(_channel) => {
#[cfg(feature = "system")] #[cfg(feature = "system")]
{ {
let graphics_info = compositor.fetch_information(); let graphics_info = compositor.fetch_information();
let mut proxy = proxy.clone();
let _ = std::thread::spawn(move || { let _ = std::thread::spawn(move || {
let information = let information =
crate::system::information(graphics_info); crate::system::information(graphics_info);
let message = _tag(information); let _ = _channel.send(information);
proxy.send(message);
}); });
} }
} }
}, },
command::Action::Widget(action) => { Action::Widget(operation) => {
let mut current_operation = Some(action); let mut current_operation = Some(operation);
let mut uis = build_user_interfaces(
application,
debug,
window_manager,
std::mem::take(ui_caches),
);
while let Some(mut operation) = current_operation.take() { while let Some(mut operation) = current_operation.take() {
for (id, ui) in uis.iter_mut() { for (id, ui) in interfaces.iter_mut() {
if let Some(window) = window_manager.get_mut(*id) { if let Some(window) = window_manager.get_mut(*id) {
ui.operate(&window.renderer, operation.as_mut()); ui.operate(&window.renderer, operation.as_mut());
} }
@ -1287,27 +1251,18 @@ fn run_command<A, C, E>(
match operation.finish() { match operation.finish() {
operation::Outcome::None => {} operation::Outcome::None => {}
operation::Outcome::Some(message) => { operation::Outcome::Some(()) => {}
proxy.send(message);
}
operation::Outcome::Chain(next) => { operation::Outcome::Chain(next) => {
current_operation = Some(next); current_operation = Some(next);
} }
} }
} }
*ui_caches =
uis.drain().map(|(id, ui)| (id, ui.into_cache())).collect();
} }
command::Action::LoadFont { bytes, tagger } => { Action::LoadFont { bytes, channel } => {
// TODO: Error handling (?) // TODO: Error handling (?)
compositor.load_font(bytes.clone()); compositor.load_font(bytes.clone());
proxy.send(tagger(Ok(()))); let _ = channel.send(Ok(()));
}
command::Action::Custom(_) => {
log::warn!("Unsupported custom action in `iced_winit` shell");
}
} }
} }
} }

View file

@ -4,17 +4,18 @@ use crate::futures::futures::{
task::{Context, Poll}, task::{Context, Poll},
Future, Sink, StreamExt, Future, Sink, StreamExt,
}; };
use crate::runtime::Action;
use std::pin::Pin; use std::pin::Pin;
/// An event loop proxy with backpressure that implements `Sink`. /// An event loop proxy with backpressure that implements `Sink`.
#[derive(Debug)] #[derive(Debug)]
pub struct Proxy<Message: 'static> { pub struct Proxy<T: 'static> {
raw: winit::event_loop::EventLoopProxy<Message>, raw: winit::event_loop::EventLoopProxy<Action<T>>,
sender: mpsc::Sender<Message>, sender: mpsc::Sender<Action<T>>,
notifier: mpsc::Sender<usize>, notifier: mpsc::Sender<usize>,
} }
impl<Message: 'static> Clone for Proxy<Message> { impl<T: 'static> Clone for Proxy<T> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self { Self {
raw: self.raw.clone(), raw: self.raw.clone(),
@ -24,12 +25,12 @@ impl<Message: 'static> Clone for Proxy<Message> {
} }
} }
impl<Message: 'static> Proxy<Message> { impl<T: 'static> Proxy<T> {
const MAX_SIZE: usize = 100; const MAX_SIZE: usize = 100;
/// Creates a new [`Proxy`] from an `EventLoopProxy`. /// Creates a new [`Proxy`] from an `EventLoopProxy`.
pub fn new( pub fn new(
raw: winit::event_loop::EventLoopProxy<Message>, raw: winit::event_loop::EventLoopProxy<Action<T>>,
) -> (Self, impl Future<Output = ()>) { ) -> (Self, impl Future<Output = ()>) {
let (notifier, mut processed) = mpsc::channel(Self::MAX_SIZE); let (notifier, mut processed) = mpsc::channel(Self::MAX_SIZE);
let (sender, mut receiver) = mpsc::channel(Self::MAX_SIZE); let (sender, mut receiver) = mpsc::channel(Self::MAX_SIZE);
@ -72,16 +73,16 @@ impl<Message: 'static> Proxy<Message> {
) )
} }
/// Sends a `Message` to the event loop. /// Sends a value to the event loop.
/// ///
/// Note: This skips the backpressure mechanism with an unbounded /// Note: This skips the backpressure mechanism with an unbounded
/// channel. Use sparingly! /// channel. Use sparingly!
pub fn send(&mut self, message: Message) pub fn send(&mut self, value: T)
where where
Message: std::fmt::Debug, T: std::fmt::Debug,
{ {
self.raw self.raw
.send_event(message) .send_event(Action::Output(value))
.expect("Send message to event loop"); .expect("Send message to event loop");
} }
@ -92,7 +93,7 @@ impl<Message: 'static> Proxy<Message> {
} }
} }
impl<Message: 'static> Sink<Message> for Proxy<Message> { impl<T: 'static> Sink<Action<T>> for Proxy<T> {
type Error = mpsc::SendError; type Error = mpsc::SendError;
fn poll_ready( fn poll_ready(
@ -104,9 +105,9 @@ impl<Message: 'static> Sink<Message> for Proxy<Message> {
fn start_send( fn start_send(
mut self: Pin<&mut Self>, mut self: Pin<&mut Self>,
message: Message, action: Action<T>,
) -> Result<(), Self::Error> { ) -> Result<(), Self::Error> {
self.sender.start_send(message) self.sender.start_send(action)
} }
fn poll_flush( fn poll_flush(

View file

@ -1,15 +1,13 @@
//! Access the native system. //! Access the native system.
use crate::graphics::compositor; use crate::graphics::compositor;
use crate::runtime::command::{self, Command};
use crate::runtime::system::{Action, Information}; use crate::runtime::system::{Action, Information};
use crate::runtime::{self, Task};
/// Query for available system information. /// Query for available system information.
pub fn fetch_information<Message>( pub fn fetch_information() -> Task<Information> {
f: impl Fn(Information) -> Message + Send + 'static, Task::oneshot(|channel| {
) -> Command<Message> { runtime::Action::System(Action::QueryInformation(channel))
Command::single(command::Action::System(Action::QueryInformation( })
Box::new(f),
)))
} }
pub(crate) fn information( pub(crate) fn information(