Introduce Program and State

This commit is contained in:
Héctor Ramón Jiménez 2020-05-21 04:27:31 +02:00
parent d77492c0c3
commit ae5e2c6c73
14 changed files with 643 additions and 777 deletions

View File

@ -1,154 +1,39 @@
use crate::{ use crate::{mouse, Executor, Runtime, Size};
mouse, Cache, Command, Element, Executor, Runtime, Size, Subscription,
UserInterface,
};
use iced_graphics::window; use iced_graphics::window;
use iced_graphics::Viewport; use iced_graphics::Viewport;
use iced_winit::application;
use iced_winit::conversion; use iced_winit::conversion;
use iced_winit::{Clipboard, Debug, Mode, Proxy, Settings}; use iced_winit::{program, Clipboard, Debug, Proxy, Settings};
/// An interactive, native cross-platform application. pub use iced_winit::Application;
///
/// This trait is the main entrypoint of Iced. Once implemented, you can run
/// your GUI application by simply calling [`run`](#method.run). It will run in
/// its own window.
///
/// An [`Application`](trait.Application.html) can execute asynchronous actions
/// by returning a [`Command`](struct.Command.html) in some of its methods.
///
/// When using an [`Application`] with the `debug` feature enabled, a debug view
/// can be toggled by pressing `F12`.
pub trait Application: Sized {
/// The graphics backend to use to draw the [`Application`].
///
/// [`Application`]: trait.Application.html
type Compositor: window::GLCompositor;
/// The [`Executor`] that will run commands and subscriptions. pub fn run<A, E, C>(
/// settings: Settings<A::Flags>,
/// [`Executor`]: trait.Executor.html compositor_settings: C::Settings,
type Executor: Executor;
/// The type of __messages__ your [`Application`] will produce.
///
/// [`Application`]: trait.Application.html
type Message: std::fmt::Debug + Send;
/// The data needed to initialize your [`Application`].
///
/// [`Application`]: trait.Application.html
type Flags;
/// Initializes the [`Application`] with the flags provided to
/// [`run`] as part of the [`Settings`].
///
/// Here is where you should return the initial state of your app.
///
/// Additionally, you can return a [`Command`](struct.Command.html) if you
/// need to perform some 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.
///
/// [`Application`]: trait.Application.html
/// [`run`]: #method.run.html
/// [`Settings`]: struct.Settings.html
fn new(flags: Self::Flags) -> (Self, Command<Self::Message>);
/// Returns the current title of the [`Application`].
///
/// This title can be dynamic! The runtime will automatically update the
/// title of your application when necessary.
///
/// [`Application`]: trait.Application.html
fn title(&self) -> String;
/// Handles a __message__ and updates the state of the [`Application`].
///
/// This is where you define your __update logic__. All the __messages__,
/// produced by either user interactions or commands, will be handled by
/// this method.
///
/// Any [`Command`] returned will be executed immediately in the background.
///
/// [`Application`]: trait.Application.html
/// [`Command`]: struct.Command.html
fn update(&mut self, message: Self::Message) -> Command<Self::Message>;
/// Returns the event `Subscription` for the current state of the
/// application.
///
/// The messages produced by the `Subscription` will be handled by
/// [`update`](#tymethod.update).
///
/// A `Subscription` will be kept alive as long as you keep returning it!
///
/// By default, it returns an empty subscription.
fn subscription(&self) -> Subscription<Self::Message> {
Subscription::none()
}
/// Returns the widgets to display in the [`Application`].
///
/// These widgets can produce __messages__ based on user interaction.
///
/// [`Application`]: trait.Application.html
fn view(
&mut self,
) -> Element<
'_,
Self::Message,
<Self::Compositor as window::GLCompositor>::Renderer,
>;
/// Returns the current [`Application`] mode.
///
/// The runtime will automatically transition your application if a new mode
/// is returned.
///
/// By default, an application will run in windowed mode.
///
/// [`Application`]: trait.Application.html
fn mode(&self) -> Mode {
Mode::Windowed
}
/// Runs the [`Application`] with the provided [`Settings`].
///
/// On native platforms, this method will take control of the current thread
/// and __will NOT return__.
///
/// It should probably be that last thing you call in your `main` function.
///
/// [`Application`]: trait.Application.html
/// [`Settings`]: struct.Settings.html
fn run(
settings: Settings<Self::Flags>,
backend_settings: <Self::Compositor as window::GLCompositor>::Settings,
) where ) where
Self: 'static, A: Application + 'static,
E: Executor + 'static,
C: window::GLCompositor<Renderer = A::Renderer> + 'static,
{ {
use glutin::{ use glutin::{
event::{self, WindowEvent}, event,
event_loop::{ControlFlow, EventLoop}, event_loop::{ControlFlow, EventLoop},
ContextBuilder, ContextBuilder,
}; };
use iced_graphics::window::GLCompositor as _;
let mut debug = Debug::new(); let mut debug = Debug::new();
debug.startup_started(); debug.startup_started();
let event_loop = EventLoop::with_user_event(); let event_loop = EventLoop::with_user_event();
let mut external_messages = Vec::new();
let mut runtime = { let mut runtime = {
let executor = Self::Executor::new().expect("Create executor"); let executor = E::new().expect("Create executor");
let proxy = Proxy::new(event_loop.create_proxy());
Runtime::new(executor, Proxy::new(event_loop.create_proxy())) Runtime::new(executor, proxy)
}; };
let flags = settings.flags; let flags = settings.flags;
let (mut application, init_command) = let (application, init_command) = runtime.enter(|| A::new(flags));
runtime.enter(|| Self::new(flags));
runtime.spawn(init_command); runtime.spawn(init_command);
let subscription = application.subscription(); let subscription = application.subscription();
@ -158,7 +43,7 @@ pub trait Application: Sized {
let mut mode = application.mode(); let mut mode = application.mode();
let context = { let context = {
let window_builder = settings.window.into_builder( let builder = settings.window.into_builder(
&title, &title,
mode, mode,
event_loop.primary_monitor(), event_loop.primary_monitor(),
@ -166,7 +51,7 @@ pub trait Application: Sized {
let context = ContextBuilder::new() let context = ContextBuilder::new()
.with_vsync(true) .with_vsync(true)
.build_windowed(window_builder, &event_loop) .build_windowed(builder, &event_loop)
.expect("Open window"); .expect("Open window");
#[allow(unsafe_code)] #[allow(unsafe_code)]
@ -175,6 +60,10 @@ pub trait Application: Sized {
} }
}; };
let clipboard = Clipboard::new(&context.window());
let mut mouse_interaction = mouse::Interaction::default();
let mut modifiers = glutin::event::ModifiersState::default();
let physical_size = context.window().inner_size(); let physical_size = context.window().inner_size();
let mut viewport = Viewport::with_physical_size( let mut viewport = Viewport::with_physical_size(
Size::new(physical_size.width, physical_size.height), Size::new(physical_size.width, physical_size.height),
@ -182,91 +71,44 @@ pub trait Application: Sized {
); );
let mut resized = false; let mut resized = false;
let clipboard = Clipboard::new(&context.window());
#[allow(unsafe_code)] #[allow(unsafe_code)]
let (mut compositor, mut renderer) = unsafe { let (mut compositor, mut renderer) = unsafe {
Self::Compositor::new(backend_settings, |address| { C::new(compositor_settings, |address| {
context.get_proc_address(address) context.get_proc_address(address)
}) })
}; };
let user_interface = build_user_interface( let mut state = program::State::new(
&mut application, application,
Cache::default(),
&mut renderer,
viewport.logical_size(), viewport.logical_size(),
&mut renderer,
&mut debug, &mut debug,
); );
debug.draw_started();
let mut primitive = user_interface.draw(&mut renderer);
debug.draw_finished();
let mut cache = Some(user_interface.into_cache());
let mut events = Vec::new();
let mut mouse_interaction = mouse::Interaction::default();
let mut modifiers = glutin::event::ModifiersState::default();
debug.startup_finished(); debug.startup_finished();
context.window().request_redraw();
event_loop.run(move |event, _, control_flow| match event { event_loop.run(move |event, _, control_flow| match event {
event::Event::MainEventsCleared => { event::Event::MainEventsCleared => {
if events.is_empty() && external_messages.is_empty() { let command = runtime.enter(|| {
return; state.update(
} clipboard.as_ref().map(|c| c as _),
let mut user_interface = build_user_interface(
&mut application,
cache.take().unwrap(),
&mut renderer,
viewport.logical_size(), viewport.logical_size(),
&mut renderer,
&mut debug, &mut debug,
); )
});
debug.event_processing_started(); // If the application was updated
events if let Some(command) = command {
.iter()
.cloned()
.for_each(|event| runtime.broadcast(event));
let mut messages = user_interface.update(
events.drain(..),
clipboard
.as_ref()
.map(|c| c as &dyn iced_native::Clipboard),
&renderer,
);
messages.extend(external_messages.drain(..));
debug.event_processing_finished();
if messages.is_empty() {
debug.draw_started();
primitive = user_interface.draw(&mut renderer);
debug.draw_finished();
cache = Some(user_interface.into_cache());
} else {
// When there are messages, we are forced to rebuild twice
// for now :^)
let temp_cache = user_interface.into_cache();
for message in messages {
debug.log_message(&message);
debug.update_started();
let command =
runtime.enter(|| application.update(message));
runtime.spawn(command); runtime.spawn(command);
debug.update_finished();
}
let subscription = application.subscription(); let program = state.program();
// Update subscriptions
let subscription = program.subscription();
runtime.track(subscription); runtime.track(subscription);
// Update window title // Update window title
let new_title = application.title(); let new_title = program.title();
if title != new_title { if title != new_title {
context.window().set_title(&new_title); context.window().set_title(&new_title);
@ -275,38 +117,22 @@ pub trait Application: Sized {
} }
// Update window mode // Update window mode
let new_mode = application.mode(); let new_mode = program.mode();
if mode != new_mode { if mode != new_mode {
context.window().set_fullscreen( context.window().set_fullscreen(conversion::fullscreen(
conversion::fullscreen(
context.window().current_monitor(), context.window().current_monitor(),
new_mode, new_mode,
), ));
);
mode = new_mode; mode = new_mode;
} }
let user_interface = build_user_interface(
&mut application,
temp_cache,
&mut renderer,
viewport.logical_size(),
&mut debug,
);
debug.draw_started();
primitive = user_interface.draw(&mut renderer);
debug.draw_finished();
cache = Some(user_interface.into_cache());
} }
context.window().request_redraw(); context.window().request_redraw();
} }
event::Event::UserEvent(message) => { event::Event::UserEvent(message) => {
external_messages.push(message); state.queue_message(message);
} }
event::Event::RedrawRequested(_) => { event::Event::RedrawRequested(_) => {
debug.render_started(); debug.render_started();
@ -314,10 +140,11 @@ pub trait Application: Sized {
if resized { if resized {
let physical_size = viewport.physical_size(); let physical_size = viewport.physical_size();
context.resize(glutin::dpi::PhysicalSize { context.resize(glutin::dpi::PhysicalSize::new(
width: physical_size.width, physical_size.width,
height: physical_size.height, physical_size.height,
}); ));
compositor.resize_viewport(physical_size); compositor.resize_viewport(physical_size);
resized = false; resized = false;
@ -326,11 +153,12 @@ pub trait Application: Sized {
let new_mouse_interaction = compositor.draw( let new_mouse_interaction = compositor.draw(
&mut renderer, &mut renderer,
&viewport, &viewport,
&primitive, state.primitive(),
&debug.overlay(), &debug.overlay(),
); );
context.swap_buffers().expect("Swap buffers"); context.swap_buffers().expect("Swap buffers");
debug.render_finished(); debug.render_finished();
if new_mouse_interaction != mouse_interaction { if new_mouse_interaction != mouse_interaction {
@ -348,55 +176,23 @@ pub trait Application: Sized {
event: window_event, event: window_event,
.. ..
} => { } => {
match window_event { application::handle_window_event(
WindowEvent::Resized(new_size) => { &window_event,
let size = Size::new(new_size.width, new_size.height); context.window(),
control_flow,
viewport = Viewport::with_physical_size( &mut modifiers,
size, &mut viewport,
context.window().scale_factor(), &mut resized,
&mut debug,
); );
resized = true;
}
WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit;
}
WindowEvent::ModifiersChanged(new_modifiers) => {
modifiers = new_modifiers;
}
#[cfg(target_os = "macos")]
WindowEvent::KeyboardInput {
input:
glutin::event::KeyboardInput {
virtual_keycode:
Some(glutin::event::VirtualKeyCode::Q),
state: glutin::event::ElementState::Pressed,
..
},
..
} if modifiers.logo() => {
*control_flow = ControlFlow::Exit;
}
#[cfg(feature = "debug")]
WindowEvent::KeyboardInput {
input:
glutin::event::KeyboardInput {
virtual_keycode:
Some(glutin::event::VirtualKeyCode::F12),
state: glutin::event::ElementState::Pressed,
..
},
..
} => debug.toggle(),
_ => {}
}
if let Some(event) = conversion::window_event( if let Some(event) = conversion::window_event(
&window_event, &window_event,
viewport.scale_factor(), viewport.scale_factor(),
modifiers, modifiers,
) { ) {
events.push(event); state.queue_event(event.clone());
runtime.broadcast(event);
} }
} }
_ => { _ => {
@ -404,26 +200,3 @@ pub trait Application: Sized {
} }
}) })
} }
}
fn build_user_interface<'a, A: Application>(
application: &'a mut A,
cache: Cache,
renderer: &mut <A::Compositor as window::GLCompositor>::Renderer,
size: Size,
debug: &mut Debug,
) -> UserInterface<
'a,
A::Message,
<A::Compositor as window::GLCompositor>::Renderer,
> {
debug.view_started();
let view = application.view();
debug.view_finished();
debug.layout_started();
let user_interface = UserInterface::build(view, size, cache, renderer);
debug.layout_finished();
user_interface
}

View File

@ -7,7 +7,7 @@
#[doc(no_inline)] #[doc(no_inline)]
pub use iced_native::*; pub use iced_native::*;
mod application; pub mod application;
pub use application::Application; pub use application::Application;

View File

@ -5,7 +5,7 @@ use raw_window_handle::HasRawWindowHandle;
/// A graphics compositor that can draw to windows. /// A graphics compositor that can draw to windows.
pub trait Compositor: Sized { pub trait Compositor: Sized {
/// The settings of the backend. /// The settings of the backend.
type Settings: Default + Clone; type Settings: Default;
/// The iced renderer of the backend. /// The iced renderer of the backend.
type Renderer: iced_native::Renderer; type Renderer: iced_native::Renderer;
@ -19,7 +19,7 @@ pub trait Compositor: Sized {
/// Creates a new [`Backend`]. /// Creates a new [`Backend`].
/// ///
/// [`Backend`]: trait.Backend.html /// [`Backend`]: trait.Backend.html
fn new(settings: Self::Settings) -> Self; fn new(settings: Self::Settings) -> (Self, Self::Renderer);
/// Crates a new [`Surface`] for the given window. /// Crates a new [`Surface`] for the given window.
/// ///
@ -29,11 +29,6 @@ pub trait Compositor: Sized {
window: &W, window: &W,
) -> Self::Surface; ) -> Self::Surface;
/// Crates a new [`Renderer`].
///
/// [`Renderer`]: #associatedtype.Renderer
fn create_renderer(&mut self, settings: Self::Settings) -> Self::Renderer;
/// Crates a new [`SwapChain`] for the given [`Surface`]. /// Crates a new [`SwapChain`] for the given [`Surface`].
/// ///
/// [`SwapChain`]: #associatedtype.SwapChain /// [`SwapChain`]: #associatedtype.SwapChain

View File

@ -7,6 +7,9 @@ description = "A renderer-agnostic library for native GUIs"
license = "MIT" license = "MIT"
repository = "https://github.com/hecrj/iced" repository = "https://github.com/hecrj/iced"
[features]
debug = []
[dependencies] [dependencies]
twox-hash = "1.5" twox-hash = "1.5"
unicode-segmentation = "1.6" unicode-segmentation = "1.6"

View File

@ -34,7 +34,7 @@
//! [`window::Backend`]: window/trait.Backend.html //! [`window::Backend`]: window/trait.Backend.html
//! [`UserInterface`]: struct.UserInterface.html //! [`UserInterface`]: struct.UserInterface.html
//! [renderer]: renderer/index.html //! [renderer]: renderer/index.html
#![deny(missing_docs)] //#![deny(missing_docs)]
#![deny(missing_debug_implementations)] #![deny(missing_debug_implementations)]
#![deny(unused_results)] #![deny(unused_results)]
#![forbid(unsafe_code)] #![forbid(unsafe_code)]
@ -42,6 +42,7 @@
pub mod keyboard; pub mod keyboard;
pub mod layout; pub mod layout;
pub mod mouse; pub mod mouse;
pub mod program;
pub mod renderer; pub mod renderer;
pub mod subscription; pub mod subscription;
pub mod widget; pub mod widget;
@ -54,6 +55,15 @@ mod hasher;
mod runtime; mod runtime;
mod user_interface; mod user_interface;
// We disable debug capabilities on release builds unless the `debug` feature
// is explicitly enabled.
#[cfg(feature = "debug")]
#[path = "debug/basic.rs"]
mod debug;
#[cfg(not(feature = "debug"))]
#[path = "debug/null.rs"]
mod debug;
pub use iced_core::{ pub use iced_core::{
Align, Background, Color, Font, HorizontalAlignment, Length, Point, Align, Background, Color, Font, HorizontalAlignment, Length, Point,
Rectangle, Size, Vector, VerticalAlignment, Rectangle, Size, Vector, VerticalAlignment,
@ -64,10 +74,12 @@ pub use iced_futures::{executor, futures, Command};
pub use executor::Executor; pub use executor::Executor;
pub use clipboard::Clipboard; pub use clipboard::Clipboard;
pub use debug::Debug;
pub use element::Element; pub use element::Element;
pub use event::Event; pub use event::Event;
pub use hasher::Hasher; pub use hasher::Hasher;
pub use layout::Layout; pub use layout::Layout;
pub use program::Program;
pub use renderer::Renderer; pub use renderer::Renderer;
pub use runtime::Runtime; pub use runtime::Runtime;
pub use subscription::Subscription; pub use subscription::Subscription;

39
native/src/program.rs Normal file
View File

@ -0,0 +1,39 @@
//! Build interactive programs using The Elm Architecture.
use crate::{Command, Element, Renderer};
mod state;
pub use state::State;
/// An interactive, native cross-platform program.
pub trait Program: Sized {
/// The graphics backend to use to draw the [`Program`].
///
/// [`Program`]: trait.Program.html
type Renderer: Renderer;
/// The type of __messages__ your [`Program`] will produce.
///
/// [`Application`]: trait.Program.html
type Message: std::fmt::Debug + Send;
/// Handles a __message__ and updates the state of the [`Program`].
///
/// This is where you define your __update logic__. All the __messages__,
/// produced by either user interactions or commands, will be handled by
/// this method.
///
/// Any [`Command`] returned will be executed immediately in the
/// background by shells.
///
/// [`Program`]: trait.Application.html
/// [`Command`]: struct.Command.html
fn update(&mut self, message: Self::Message) -> Command<Self::Message>;
/// Returns the widgets to display in the [`Program`].
///
/// These widgets can produce __messages__ based on user interaction.
///
/// [`Program`]: trait.Application.html
fn view(&mut self) -> Element<'_, Self::Message, Self::Renderer>;
}

154
native/src/program/state.rs Normal file
View File

@ -0,0 +1,154 @@
use crate::{
Cache, Clipboard, Command, Debug, Event, Program, Renderer, Size,
UserInterface,
};
#[allow(missing_debug_implementations)]
pub struct State<P>
where
P: Program + 'static,
{
program: P,
cache: Option<Cache>,
primitive: <P::Renderer as Renderer>::Output,
queued_events: Vec<Event>,
queued_messages: Vec<P::Message>,
}
impl<P> State<P>
where
P: Program + 'static,
{
pub fn new(
mut program: P,
bounds: Size,
renderer: &mut P::Renderer,
debug: &mut Debug,
) -> Self {
let user_interface = build_user_interface(
&mut program,
Cache::default(),
renderer,
bounds,
debug,
);
debug.draw_started();
let primitive = user_interface.draw(renderer);
debug.draw_finished();
let cache = Some(user_interface.into_cache());
State {
program,
cache,
primitive,
queued_events: Vec::new(),
queued_messages: Vec::new(),
}
}
pub fn program(&self) -> &P {
&self.program
}
pub fn primitive(&self) -> &<P::Renderer as Renderer>::Output {
&self.primitive
}
pub fn queue_event(&mut self, event: Event) {
self.queued_events.push(event);
}
pub fn queue_message(&mut self, message: P::Message) {
self.queued_messages.push(message);
}
pub fn update(
&mut self,
clipboard: Option<&dyn Clipboard>,
bounds: Size,
renderer: &mut P::Renderer,
debug: &mut Debug,
) -> Option<Command<P::Message>> {
if self.queued_events.is_empty() && self.queued_messages.is_empty() {
return None;
}
let mut user_interface = build_user_interface(
&mut self.program,
self.cache.take().unwrap(),
renderer,
bounds,
debug,
);
debug.event_processing_started();
let mut messages = user_interface.update(
self.queued_events.drain(..),
clipboard,
renderer,
);
messages.extend(self.queued_messages.drain(..));
debug.event_processing_finished();
if messages.is_empty() {
debug.draw_started();
self.primitive = user_interface.draw(renderer);
debug.draw_finished();
self.cache = Some(user_interface.into_cache());
None
} else {
// When there are messages, we are forced to rebuild twice
// for now :^)
let temp_cache = user_interface.into_cache();
let commands =
Command::batch(messages.into_iter().map(|message| {
debug.log_message(&message);
debug.update_started();
let command = self.program.update(message);
debug.update_finished();
command
}));
let user_interface = build_user_interface(
&mut self.program,
temp_cache,
renderer,
bounds,
debug,
);
debug.draw_started();
self.primitive = user_interface.draw(renderer);
debug.draw_finished();
self.cache = Some(user_interface.into_cache());
Some(commands)
}
}
}
fn build_user_interface<'a, P: Program>(
program: &'a mut P,
cache: Cache,
renderer: &mut P::Renderer,
size: Size,
debug: &mut Debug,
) -> UserInterface<'a, P::Message, P::Renderer> {
debug.view_started();
let view = program.view();
debug.view_finished();
debug.layout_started();
let user_interface = UserInterface::build(view, size, cache, renderer);
debug.layout_finished();
user_interface
}

View File

@ -198,10 +198,11 @@ pub trait Application: Sized {
..iced_glow::Settings::default() ..iced_glow::Settings::default()
}; };
<Instance<Self> as iced_glutin::Application>::run( iced_glutin::application::run::<
settings.into(), Instance<Self>,
glow_settings, Self::Executor,
); iced_glow::window::Compositor,
>(settings.into(), glow_settings);
} }
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
@ -211,15 +212,29 @@ pub trait Application: Sized {
struct Instance<A: Application>(A); struct Instance<A: Application>(A);
#[cfg(not(target_arch = "wasm32"))]
impl<A> iced_glutin::Program for Instance<A>
where
A: Application,
{
type Renderer = iced_glow::Renderer;
type Message = A::Message;
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
self.0.update(message)
}
fn view(&mut self) -> Element<'_, Self::Message> {
self.0.view()
}
}
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
impl<A> iced_glutin::Application for Instance<A> impl<A> iced_glutin::Application for Instance<A>
where where
A: Application, A: Application,
{ {
type Compositor = iced_glow::window::Compositor;
type Executor = A::Executor;
type Flags = A::Flags; type Flags = A::Flags;
type Message = A::Message;
fn new(flags: Self::Flags) -> (Self, Command<A::Message>) { fn new(flags: Self::Flags) -> (Self, Command<A::Message>) {
let (app, command) = A::new(flags); let (app, command) = A::new(flags);
@ -238,17 +253,9 @@ where
} }
} }
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
self.0.update(message)
}
fn subscription(&self) -> Subscription<Self::Message> { fn subscription(&self) -> Subscription<Self::Message> {
self.0.subscription() self.0.subscription()
} }
fn view(&mut self) -> Element<'_, Self::Message> {
self.0.view()
}
} }
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]

View File

@ -18,8 +18,8 @@ impl iced_graphics::window::Compositor for Compositor {
type Surface = wgpu::Surface; type Surface = wgpu::Surface;
type SwapChain = wgpu::SwapChain; type SwapChain = wgpu::SwapChain;
fn new(settings: Self::Settings) -> Self { fn new(settings: Self::Settings) -> (Self, Renderer) {
let (device, queue) = futures::executor::block_on(async { let (mut device, queue) = futures::executor::block_on(async {
let adapter = wgpu::Adapter::request( let adapter = wgpu::Adapter::request(
&wgpu::RequestAdapterOptions { &wgpu::RequestAdapterOptions {
power_preference: if settings.antialiasing.is_none() { power_preference: if settings.antialiasing.is_none() {
@ -44,15 +44,17 @@ impl iced_graphics::window::Compositor for Compositor {
.await .await
}); });
let renderer =
Renderer::new(crate::Backend::new(&mut device, settings));
(
Self { Self {
device, device,
queue, queue,
format: settings.format, format: settings.format,
} },
} renderer,
)
fn create_renderer(&mut self, settings: Settings) -> Renderer {
Renderer::new(crate::Backend::new(&mut self.device, settings))
} }
fn create_surface<W: HasRawWindowHandle>( fn create_surface<W: HasRawWindowHandle>(

View File

@ -11,7 +11,7 @@ keywords = ["gui", "ui", "graphics", "interface", "widgets"]
categories = ["gui"] categories = ["gui"]
[features] [features]
debug = [] debug = ["iced_native/debug"]
[dependencies] [dependencies]
winit = "0.22" winit = "0.22"

View File

@ -1,9 +1,10 @@
use crate::{ use crate::{
conversion, mouse, Cache, Clipboard, Command, Debug, Element, Executor, conversion, mouse, Clipboard, Command, Debug, Executor, Mode, Proxy,
Mode, Proxy, Runtime, Settings, Size, Subscription, UserInterface, Runtime, Settings, Size, Subscription,
}; };
use iced_graphics::window; use iced_graphics::window;
use iced_graphics::Viewport; use iced_graphics::Viewport;
use iced_native::program::{self, Program};
/// An interactive, native cross-platform application. /// An interactive, native cross-platform application.
/// ///
@ -16,22 +17,7 @@ use iced_graphics::Viewport;
/// ///
/// 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`.
pub trait Application: Sized { pub trait Application: Program {
/// The graphics backend to use to draw the [`Application`].
///
/// [`Application`]: trait.Application.html
type Compositor: window::Compositor;
/// The [`Executor`] that will run commands and subscriptions.
///
/// [`Executor`]: trait.Executor.html
type Executor: Executor;
/// The type of __messages__ your [`Application`] will produce.
///
/// [`Application`]: trait.Application.html
type Message: std::fmt::Debug + Send;
/// The data needed to initialize your [`Application`]. /// The data needed to initialize your [`Application`].
/// ///
/// [`Application`]: trait.Application.html /// [`Application`]: trait.Application.html
@ -60,18 +46,6 @@ pub trait Application: Sized {
/// [`Application`]: trait.Application.html /// [`Application`]: trait.Application.html
fn title(&self) -> String; fn title(&self) -> String;
/// Handles a __message__ and updates the state of the [`Application`].
///
/// This is where you define your __update logic__. All the __messages__,
/// produced by either user interactions or commands, will be handled by
/// this method.
///
/// Any [`Command`] returned will be executed immediately in the background.
///
/// [`Application`]: trait.Application.html
/// [`Command`]: struct.Command.html
fn update(&mut self, message: Self::Message) -> Command<Self::Message>;
/// Returns the event `Subscription` for the current state of the /// Returns the event `Subscription` for the current state of the
/// application. /// application.
/// ///
@ -85,19 +59,6 @@ pub trait Application: Sized {
Subscription::none() Subscription::none()
} }
/// Returns the widgets to display in the [`Application`].
///
/// These widgets can produce __messages__ based on user interaction.
///
/// [`Application`]: trait.Application.html
fn view(
&mut self,
) -> Element<
'_,
Self::Message,
<Self::Compositor as window::Compositor>::Renderer,
>;
/// Returns the current [`Application`] mode. /// Returns the current [`Application`] mode.
/// ///
/// The runtime will automatically transition your application if a new mode /// The runtime will automatically transition your application if a new mode
@ -109,43 +70,34 @@ pub trait Application: Sized {
fn mode(&self) -> Mode { fn mode(&self) -> Mode {
Mode::Windowed Mode::Windowed
} }
}
/// Runs the [`Application`] with the provided [`Settings`]. pub fn run<A, E, C>(
/// settings: Settings<A::Flags>,
/// On native platforms, this method will take control of the current thread compositor_settings: C::Settings,
/// and __will NOT return__.
///
/// It should probably be that last thing you call in your `main` function.
///
/// [`Application`]: trait.Application.html
/// [`Settings`]: struct.Settings.html
fn run(
settings: Settings<Self::Flags>,
backend_settings: <Self::Compositor as window::Compositor>::Settings,
) where ) where
Self: 'static, A: Application + 'static,
E: Executor + 'static,
C: window::Compositor<Renderer = A::Renderer> + 'static,
{ {
use iced_graphics::window::Compositor as _;
use winit::{ use winit::{
event::{self, WindowEvent}, event,
event_loop::{ControlFlow, EventLoop}, event_loop::{ControlFlow, EventLoop},
}; };
let mut debug = Debug::new(); let mut debug = Debug::new();
debug.startup_started(); debug.startup_started();
let event_loop = EventLoop::with_user_event(); let event_loop = EventLoop::with_user_event();
let mut external_messages = Vec::new();
let mut runtime = { let mut runtime = {
let executor = Self::Executor::new().expect("Create executor"); let executor = E::new().expect("Create executor");
let proxy = Proxy::new(event_loop.create_proxy());
Runtime::new(executor, Proxy::new(event_loop.create_proxy())) Runtime::new(executor, proxy)
}; };
let flags = settings.flags; let flags = settings.flags;
let (mut application, init_command) = let (application, init_command) = runtime.enter(|| A::new(flags));
runtime.enter(|| Self::new(flags));
runtime.spawn(init_command); runtime.spawn(init_command);
let subscription = application.subscription(); let subscription = application.subscription();
@ -160,6 +112,10 @@ pub trait Application: Sized {
.build(&event_loop) .build(&event_loop)
.expect("Open window"); .expect("Open window");
let clipboard = Clipboard::new(&window);
let mut mouse_interaction = mouse::Interaction::default();
let mut modifiers = winit::event::ModifiersState::default();
let physical_size = window.inner_size(); let physical_size = window.inner_size();
let mut viewport = Viewport::with_physical_size( let mut viewport = Viewport::with_physical_size(
Size::new(physical_size.width, physical_size.height), Size::new(physical_size.width, physical_size.height),
@ -167,11 +123,9 @@ pub trait Application: Sized {
); );
let mut resized = false; let mut resized = false;
let clipboard = Clipboard::new(&window); let (mut compositor, mut renderer) = C::new(compositor_settings);
let mut compositor = Self::Compositor::new(backend_settings.clone());
let surface = compositor.create_surface(&window); let surface = compositor.create_surface(&window);
let mut renderer = compositor.create_renderer(backend_settings);
let mut swap_chain = compositor.create_swap_chain( let mut swap_chain = compositor.create_swap_chain(
&surface, &surface,
@ -179,84 +133,37 @@ pub trait Application: Sized {
physical_size.height, physical_size.height,
); );
let user_interface = build_user_interface( let mut state = program::State::new(
&mut application, application,
Cache::default(),
&mut renderer,
viewport.logical_size(), viewport.logical_size(),
&mut renderer,
&mut debug, &mut debug,
); );
debug.draw_started();
let mut primitive = user_interface.draw(&mut renderer);
debug.draw_finished();
let mut cache = Some(user_interface.into_cache());
let mut events = Vec::new();
let mut mouse_interaction = mouse::Interaction::default();
let mut modifiers = winit::event::ModifiersState::default();
debug.startup_finished(); debug.startup_finished();
window.request_redraw();
event_loop.run(move |event, _, control_flow| match event { event_loop.run(move |event, _, control_flow| match event {
event::Event::MainEventsCleared => { event::Event::MainEventsCleared => {
if events.is_empty() && external_messages.is_empty() { let command = runtime.enter(|| {
return; state.update(
} clipboard.as_ref().map(|c| c as _),
let mut user_interface = build_user_interface(
&mut application,
cache.take().unwrap(),
&mut renderer,
viewport.logical_size(), viewport.logical_size(),
&mut renderer,
&mut debug, &mut debug,
); )
});
debug.event_processing_started(); // If the application was updated
events if let Some(command) = command {
.iter()
.cloned()
.for_each(|event| runtime.broadcast(event));
let mut messages = user_interface.update(
events.drain(..),
clipboard
.as_ref()
.map(|c| c as &dyn iced_native::Clipboard),
&renderer,
);
messages.extend(external_messages.drain(..));
debug.event_processing_finished();
if messages.is_empty() {
debug.draw_started();
primitive = user_interface.draw(&mut renderer);
debug.draw_finished();
cache = Some(user_interface.into_cache());
} else {
// When there are messages, we are forced to rebuild twice
// for now :^)
let temp_cache = user_interface.into_cache();
for message in messages {
log::debug!("Updating");
debug.log_message(&message);
debug.update_started();
let command =
runtime.enter(|| application.update(message));
runtime.spawn(command); runtime.spawn(command);
debug.update_finished();
}
let subscription = application.subscription(); let program = state.program();
// Update subscriptions
let subscription = program.subscription();
runtime.track(subscription); runtime.track(subscription);
// Update window title // Update window title
let new_title = application.title(); let new_title = program.title();
if title != new_title { if title != new_title {
window.set_title(&new_title); window.set_title(&new_title);
@ -265,7 +172,7 @@ pub trait Application: Sized {
} }
// Update window mode // Update window mode
let new_mode = application.mode(); let new_mode = program.mode();
if mode != new_mode { if mode != new_mode {
window.set_fullscreen(conversion::fullscreen( window.set_fullscreen(conversion::fullscreen(
@ -275,26 +182,12 @@ pub trait Application: Sized {
mode = new_mode; mode = new_mode;
} }
let user_interface = build_user_interface(
&mut application,
temp_cache,
&mut renderer,
viewport.logical_size(),
&mut debug,
);
debug.draw_started();
primitive = user_interface.draw(&mut renderer);
debug.draw_finished();
cache = Some(user_interface.into_cache());
} }
window.request_redraw(); window.request_redraw();
} }
event::Event::UserEvent(message) => { event::Event::UserEvent(message) => {
external_messages.push(message); state.queue_message(message);
} }
event::Event::RedrawRequested(_) => { event::Event::RedrawRequested(_) => {
debug.render_started(); debug.render_started();
@ -315,7 +208,7 @@ pub trait Application: Sized {
&mut renderer, &mut renderer,
&mut swap_chain, &mut swap_chain,
&viewport, &viewport,
&primitive, state.primitive(),
&debug.overlay(), &debug.overlay(),
); );
@ -336,28 +229,61 @@ pub trait Application: Sized {
event: window_event, event: window_event,
.. ..
} => { } => {
match window_event { handle_window_event(
&window_event,
&window,
control_flow,
&mut modifiers,
&mut viewport,
&mut resized,
&mut debug,
);
if let Some(event) = conversion::window_event(
&window_event,
viewport.scale_factor(),
modifiers,
) {
state.queue_event(event.clone());
runtime.broadcast(event);
}
}
_ => {
*control_flow = ControlFlow::Wait;
}
})
}
pub fn handle_window_event(
event: &winit::event::WindowEvent<'_>,
window: &winit::window::Window,
control_flow: &mut winit::event_loop::ControlFlow,
modifiers: &mut winit::event::ModifiersState,
viewport: &mut Viewport,
resized: &mut bool,
_debug: &mut Debug,
) {
use winit::{event::WindowEvent, event_loop::ControlFlow};
match event {
WindowEvent::Resized(new_size) => { WindowEvent::Resized(new_size) => {
let size = Size::new(new_size.width, new_size.height); let size = Size::new(new_size.width, new_size.height);
viewport = Viewport::with_physical_size( *viewport =
size, Viewport::with_physical_size(size, window.scale_factor());
window.scale_factor(), *resized = true;
);
resized = true;
} }
WindowEvent::CloseRequested => { WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit; *control_flow = ControlFlow::Exit;
} }
WindowEvent::ModifiersChanged(new_modifiers) => { WindowEvent::ModifiersChanged(new_modifiers) => {
modifiers = new_modifiers; *modifiers = *new_modifiers;
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
WindowEvent::KeyboardInput { WindowEvent::KeyboardInput {
input: input:
winit::event::KeyboardInput { winit::event::KeyboardInput {
virtual_keycode: virtual_keycode: Some(winit::event::VirtualKeyCode::Q),
Some(winit::event::VirtualKeyCode::Q),
state: winit::event::ElementState::Pressed, state: winit::event::ElementState::Pressed,
.. ..
}, },
@ -369,49 +295,12 @@ pub trait Application: Sized {
WindowEvent::KeyboardInput { WindowEvent::KeyboardInput {
input: input:
winit::event::KeyboardInput { winit::event::KeyboardInput {
virtual_keycode: virtual_keycode: Some(winit::event::VirtualKeyCode::F12),
Some(winit::event::VirtualKeyCode::F12),
state: winit::event::ElementState::Pressed, state: winit::event::ElementState::Pressed,
.. ..
}, },
.. ..
} => debug.toggle(), } => _debug.toggle(),
_ => {} _ => {}
} }
if let Some(event) = conversion::window_event(
&window_event,
viewport.scale_factor(),
modifiers,
) {
events.push(event);
}
}
_ => {
*control_flow = ControlFlow::Wait;
}
})
}
}
fn build_user_interface<'a, A: Application>(
application: &'a mut A,
cache: Cache,
renderer: &mut <A::Compositor as window::Compositor>::Renderer,
size: Size,
debug: &mut Debug,
) -> UserInterface<
'a,
A::Message,
<A::Compositor as window::Compositor>::Renderer,
> {
debug.view_started();
let view = application.view();
debug.view_finished();
debug.layout_started();
let user_interface = UserInterface::build(view, size, cache, renderer);
debug.layout_finished();
user_interface
} }

View File

@ -25,26 +25,18 @@
pub use iced_native::*; pub use iced_native::*;
pub use winit; pub use winit;
pub mod application;
pub mod conversion; pub mod conversion;
pub mod settings; pub mod settings;
mod application;
mod clipboard; mod clipboard;
mod mode; mod mode;
mod proxy; mod proxy;
// We disable debug capabilities on release builds unless the `debug` feature
// is explicitly enabled.
#[cfg(feature = "debug")]
#[path = "debug/basic.rs"]
mod debug;
#[cfg(not(feature = "debug"))]
#[path = "debug/null.rs"]
mod debug;
pub use application::Application; pub use application::Application;
pub use clipboard::Clipboard; pub use clipboard::Clipboard;
pub use debug::Debug;
pub use mode::Mode; pub use mode::Mode;
pub use proxy::Proxy; pub use proxy::Proxy;
pub use settings::Settings; pub use settings::Settings;
pub use iced_graphics::Viewport;