diff options
Diffstat (limited to 'winit/src/application.rs')
-rw-r--r-- | winit/src/application.rs | 601 |
1 files changed, 348 insertions, 253 deletions
diff --git a/winit/src/application.rs b/winit/src/application.rs index 12f92053..c43eed11 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -1,13 +1,23 @@ //! Create interactive, native cross-platform applications. +mod state; + +pub use state::State; + use crate::conversion; use crate::mouse; use crate::{ Clipboard, Color, Command, Debug, Error, Executor, Mode, Proxy, Runtime, Settings, Size, Subscription, }; + +use iced_futures::futures; +use iced_futures::futures::channel::mpsc; use iced_graphics::window; -use iced_graphics::Viewport; -use iced_native::program::{self, Program}; +use iced_native::program::Program; +use iced_native::Menu; +use iced_native::{Cache, UserInterface}; + +use std::mem::ManuallyDrop; /// An interactive, native cross-platform application. /// @@ -15,17 +25,13 @@ use iced_native::program::{self, Program}; /// 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. +/// An [`Application`] can execute asynchronous actions by returning a +/// [`Command`] in some of its methods. /// /// When using an [`Application`] with the `debug` feature enabled, a debug view /// can be toggled by pressing `F12`. -/// -/// [`Application`]: trait.Application.html -pub trait Application: Program { +pub trait Application: Program<Clipboard = Clipboard> { /// The data needed to initialize your [`Application`]. - /// - /// [`Application`]: trait.Application.html type Flags; /// Initializes the [`Application`] with the flags provided to @@ -33,22 +39,15 @@ pub trait Application: Program { /// /// 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`]: ../settings/struct.Settings.html + /// Additionally, you can return a [`Command`] 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. 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; /// Returns the event `Subscription` for the current state of the @@ -70,8 +69,6 @@ pub trait Application: Program { /// is returned. /// /// By default, an application will run in windowed mode. - /// - /// [`Application`]: trait.Application.html fn mode(&self) -> Mode { Mode::Windowed } @@ -79,10 +76,6 @@ pub trait Application: Program { /// Returns the background [`Color`] of the [`Application`]. /// /// By default, it returns [`Color::WHITE`]. - /// - /// [`Color`]: struct.Color.html - /// [`Application`]: trait.Application.html - /// [`Color::WHITE`]: struct.Color.html#const.WHITE fn background_color(&self) -> Color { Color::WHITE } @@ -96,17 +89,27 @@ pub trait Application: Program { /// while a scale factor of `0.5` will shrink them to half their size. /// /// By default, it returns `1.0`. - /// - /// [`Application`]: trait.Application.html fn scale_factor(&self) -> f64 { 1.0 } + + /// Returns whether the [`Application`] should be terminated. + /// + /// By default, it returns `false`. + fn should_exit(&self) -> bool { + false + } + + /// Returns the current system [`Menu`] of the [`Application`]. + /// + /// By default, it returns an empty [`Menu`]. + fn menu(&self) -> Menu<Self::Message> { + Menu::new() + } } /// Runs an [`Application`] with an executor, compositor, and the provided /// settings. -/// -/// [`Application`]: trait.Application.html pub fn run<A, E, C>( settings: Settings<A::Flags>, compositor_settings: C::Settings, @@ -116,279 +119,340 @@ where E: Executor + 'static, C: window::Compositor<Renderer = A::Renderer> + 'static, { - use winit::{ - event, - event_loop::{ControlFlow, EventLoop}, - }; + use futures::task; + use futures::Future; + use winit::event_loop::EventLoop; let mut debug = Debug::new(); debug.startup_started(); let event_loop = EventLoop::with_user_event(); + let mut runtime = { - let executor = E::new().map_err(Error::ExecutorCreationFailed)?; let proxy = Proxy::new(event_loop.create_proxy()); + let executor = E::new().map_err(Error::ExecutorCreationFailed)?; Runtime::new(executor, proxy) }; - let flags = settings.flags; - let (application, init_command) = runtime.enter(|| A::new(flags)); - runtime.spawn(init_command); + let (application, init_command) = { + let flags = settings.flags; + + runtime.enter(|| A::new(flags)) + }; let subscription = application.subscription(); - runtime.track(subscription); - let mut title = application.title(); - let mut mode = application.mode(); - let mut background_color = application.background_color(); - let mut scale_factor = application.scale_factor(); + runtime.spawn(init_command); + runtime.track(subscription); let window = settings .window - .into_builder(&title, mode, event_loop.primary_monitor()) + .into_builder( + &application.title(), + application.mode(), + event_loop.primary_monitor(), + settings.id, + ) + .with_menu(Some(conversion::menu(&application.menu()))) .build(&event_loop) .map_err(Error::WindowCreationFailed)?; - let clipboard = Clipboard::new(&window); - // TODO: Encode cursor availability in the type-system - let mut cursor_position = winit::dpi::PhysicalPosition::new(-1.0, -1.0); - let mut mouse_interaction = mouse::Interaction::default(); - let mut modifiers = winit::event::ModifiersState::default(); - - let physical_size = window.inner_size(); - let mut viewport = Viewport::with_physical_size( - Size::new(physical_size.width, physical_size.height), - window.scale_factor() * scale_factor, - ); - let mut resized = false; + let (compositor, renderer) = C::new(compositor_settings, Some(&window))?; - let (mut compositor, mut renderer) = C::new(compositor_settings)?; - - let surface = compositor.create_surface(&window); + let (mut sender, receiver) = mpsc::unbounded(); - let mut swap_chain = compositor.create_swap_chain( - &surface, - physical_size.width, - physical_size.height, - ); - - let mut state = program::State::new( + let mut instance = Box::pin(run_instance::<A, E, C>( application, - viewport.logical_size(), - conversion::cursor_position(cursor_position, viewport.scale_factor()), - &mut renderer, - &mut debug, - ); - debug.startup_finished(); + compositor, + renderer, + runtime, + debug, + receiver, + window, + settings.exit_on_close_request, + )); + + let mut context = task::Context::from_waker(task::noop_waker_ref()); + + event_loop.run(move |event, _, control_flow| { + use winit::event_loop::ControlFlow; + + if let ControlFlow::Exit = control_flow { + return; + } - event_loop.run(move |event, _, control_flow| match event { - event::Event::MainEventsCleared => { - if state.is_queue_empty() { - return; - } + let event = match event { + winit::event::Event::WindowEvent { + event: + winit::event::WindowEvent::ScaleFactorChanged { + new_inner_size, + .. + }, + window_id, + } => Some(winit::event::Event::WindowEvent { + event: winit::event::WindowEvent::Resized(*new_inner_size), + window_id, + }), + _ => event.to_static(), + }; + + if let Some(event) = event { + sender.start_send(event).expect("Send event"); + + let poll = instance.as_mut().poll(&mut context); + + *control_flow = match poll { + task::Poll::Pending => ControlFlow::Wait, + task::Poll::Ready(_) => ControlFlow::Exit, + }; + } + }); +} - let command = runtime.enter(|| { - state.update( - viewport.logical_size(), - conversion::cursor_position( - cursor_position, - viewport.scale_factor(), - ), - clipboard.as_ref().map(|c| c as _), - &mut renderer, - &mut debug, - ) - }); +async fn run_instance<A, E, C>( + mut application: A, + mut compositor: C, + mut renderer: A::Renderer, + mut runtime: Runtime<E, Proxy<A::Message>, A::Message>, + mut debug: Debug, + mut receiver: mpsc::UnboundedReceiver<winit::event::Event<'_, A::Message>>, + window: winit::window::Window, + exit_on_close_request: bool, +) where + A: Application + 'static, + E: Executor + 'static, + C: window::Compositor<Renderer = A::Renderer> + 'static, +{ + use iced_futures::futures::stream::StreamExt; + use winit::event; - // If the application was updated - if let Some(command) = command { - runtime.spawn(command); + let surface = compositor.create_surface(&window); + let mut clipboard = Clipboard::connect(&window); + + let mut state = State::new(&application, &window); + let mut viewport_version = state.viewport_version(); + let mut swap_chain = { + let physical_size = state.physical_size(); + + compositor.create_swap_chain( + &surface, + physical_size.width, + physical_size.height, + ) + }; - let program = state.program(); + let mut user_interface = ManuallyDrop::new(build_user_interface( + &mut application, + Cache::default(), + &mut renderer, + state.logical_size(), + &mut debug, + )); - // Update subscriptions - let subscription = program.subscription(); - runtime.track(subscription); + let mut primitive = + user_interface.draw(&mut renderer, state.cursor_position()); + let mut mouse_interaction = mouse::Interaction::default(); - // Update window title - let new_title = program.title(); + let mut events = Vec::new(); + let mut messages = Vec::new(); - if title != new_title { - window.set_title(&new_title); + debug.startup_finished(); - title = new_title; + while let Some(event) = receiver.next().await { + match event { + event::Event::MainEventsCleared => { + if events.is_empty() && messages.is_empty() { + continue; } - // Update window mode - let new_mode = program.mode(); + debug.event_processing_started(); - if mode != new_mode { - window.set_fullscreen(conversion::fullscreen( - window.current_monitor(), - new_mode, - )); + let statuses = user_interface.update( + &events, + state.cursor_position(), + &mut renderer, + &mut clipboard, + &mut messages, + ); + + debug.event_processing_finished(); - mode = new_mode; + for event in events.drain(..).zip(statuses.into_iter()) { + runtime.broadcast(event); } - // Update background color - background_color = program.background_color(); + if !messages.is_empty() { + let cache = + ManuallyDrop::into_inner(user_interface).into_cache(); - // Update scale factor - let new_scale_factor = program.scale_factor(); + // Update application + update( + &mut application, + &mut runtime, + &mut debug, + &mut clipboard, + &mut messages, + ); - if scale_factor != new_scale_factor { - let size = window.inner_size(); + // Update window + state.synchronize(&application, &window); - viewport = Viewport::with_physical_size( - Size::new(size.width, size.height), - window.scale_factor() * new_scale_factor, - ); + let should_exit = application.should_exit(); - // We relayout the UI with the new logical size. - // The queue is empty, therefore this will never produce - // a `Command`. - // - // TODO: Properly queue `WindowResized` - let _ = state.update( - viewport.logical_size(), - conversion::cursor_position( - cursor_position, - viewport.scale_factor(), - ), - clipboard.as_ref().map(|c| c as _), + user_interface = ManuallyDrop::new(build_user_interface( + &mut application, + cache, &mut renderer, + state.logical_size(), &mut debug, - ); + )); - scale_factor = new_scale_factor; + if should_exit { + break; + } } + + debug.draw_started(); + primitive = + user_interface.draw(&mut renderer, state.cursor_position()); + debug.draw_finished(); + + window.request_redraw(); + } + event::Event::PlatformSpecific(event::PlatformSpecific::MacOS( + event::MacOS::ReceivedUrl(url), + )) => { + use iced_native::event; + events.push(iced_native::Event::PlatformSpecific( + event::PlatformSpecific::MacOS(event::MacOS::ReceivedUrl( + url, + )), + )); + } + event::Event::UserEvent(message) => { + messages.push(message); } + event::Event::RedrawRequested(_) => { + let physical_size = state.physical_size(); - window.request_redraw(); - } - event::Event::UserEvent(message) => { - state.queue_message(message); - } - event::Event::RedrawRequested(_) => { - debug.render_started(); + if physical_size.width == 0 || physical_size.height == 0 { + continue; + } - if resized { - let physical_size = viewport.physical_size(); + debug.render_started(); + let current_viewport_version = state.viewport_version(); - swap_chain = compositor.create_swap_chain( - &surface, - physical_size.width, - physical_size.height, - ); + if viewport_version != current_viewport_version { + let logical_size = state.logical_size(); - resized = false; - } + debug.layout_started(); + user_interface = ManuallyDrop::new( + ManuallyDrop::into_inner(user_interface) + .relayout(logical_size, &mut renderer), + ); + debug.layout_finished(); - let new_mouse_interaction = compositor.draw( - &mut renderer, - &mut swap_chain, - &viewport, - background_color, - state.primitive(), - &debug.overlay(), - ); + debug.draw_started(); + primitive = user_interface + .draw(&mut renderer, state.cursor_position()); + debug.draw_finished(); - debug.render_finished(); + swap_chain = compositor.create_swap_chain( + &surface, + physical_size.width, + physical_size.height, + ); - if new_mouse_interaction != mouse_interaction { - window.set_cursor_icon(conversion::mouse_interaction( - new_mouse_interaction, - )); + viewport_version = current_viewport_version; + } - mouse_interaction = new_mouse_interaction; + match compositor.draw( + &mut renderer, + &mut swap_chain, + state.viewport(), + state.background_color(), + &primitive, + &debug.overlay(), + ) { + Ok(new_mouse_interaction) => { + debug.render_finished(); + + if new_mouse_interaction != mouse_interaction { + window.set_cursor_icon( + conversion::mouse_interaction( + new_mouse_interaction, + ), + ); + + mouse_interaction = new_mouse_interaction; + } + + // TODO: Handle animations! + // Maybe we can use `ControlFlow::WaitUntil` for this. + } + Err(error) => match error { + // This is an unrecoverable error. + window::SwapChainError::OutOfMemory => { + panic!("{}", error); + } + _ => { + debug.render_finished(); + + // Try rendering again next frame. + window.request_redraw(); + } + }, + } + } + event::Event::WindowEvent { + event: event::WindowEvent::MenuEntryActivated(entry_id), + .. + } => { + if let Some(message) = + conversion::menu_message(state.menu(), entry_id) + { + messages.push(message); + } } + event::Event::WindowEvent { + event: window_event, + .. + } => { + if requests_exit(&window_event, state.modifiers()) + && exit_on_close_request + { + break; + } - // TODO: Handle animations! - // Maybe we can use `ControlFlow::WaitUntil` for this. - } - event::Event::WindowEvent { - event: window_event, - .. - } => { - handle_window_event( - &window_event, - &window, - scale_factor, - control_flow, - &mut cursor_position, - &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); + state.update(&window, &window_event, &mut debug); + + if let Some(event) = conversion::window_event( + &window_event, + state.scale_factor(), + state.modifiers(), + ) { + events.push(event); + } } + _ => {} } - _ => { - *control_flow = ControlFlow::Wait; - } - }) + } + + // Manually drop the user interface + drop(ManuallyDrop::into_inner(user_interface)); } -/// Handles a `WindowEvent` and mutates the provided control flow, keyboard -/// modifiers, viewport, and resized flag accordingly. -pub fn handle_window_event( +/// Returns true if the provided event should cause an [`Application`] to +/// exit. +pub fn requests_exit( event: &winit::event::WindowEvent<'_>, - window: &winit::window::Window, - scale_factor: f64, - control_flow: &mut winit::event_loop::ControlFlow, - cursor_position: &mut winit::dpi::PhysicalPosition<f64>, - modifiers: &mut winit::event::ModifiersState, - viewport: &mut Viewport, - resized: &mut bool, - _debug: &mut Debug, -) { - use winit::{event::WindowEvent, event_loop::ControlFlow}; + _modifiers: winit::event::ModifiersState, +) -> bool { + use winit::event::WindowEvent; match event { - WindowEvent::Resized(new_size) => { - let size = Size::new(new_size.width, new_size.height); - - *viewport = Viewport::with_physical_size( - size, - window.scale_factor() * scale_factor, - ); - *resized = true; - } - WindowEvent::ScaleFactorChanged { - scale_factor: new_scale_factor, - new_inner_size, - } => { - let size = Size::new(new_inner_size.width, new_inner_size.height); - - *viewport = Viewport::with_physical_size( - size, - new_scale_factor * scale_factor, - ); - *resized = true; - } - WindowEvent::CloseRequested => { - *control_flow = ControlFlow::Exit; - } - WindowEvent::CursorMoved { position, .. } => { - *cursor_position = *position; - } - WindowEvent::CursorLeft { .. } => { - // TODO: Encode cursor availability in the type-system - *cursor_position = winit::dpi::PhysicalPosition::new(-1.0, -1.0); - } - WindowEvent::ModifiersChanged(new_modifiers) => { - *modifiers = *new_modifiers; - } + WindowEvent::CloseRequested => true, #[cfg(target_os = "macos")] WindowEvent::KeyboardInput { input: @@ -398,19 +462,50 @@ pub fn handle_window_event( .. }, .. - } if modifiers.logo() => { - *control_flow = ControlFlow::Exit; - } - #[cfg(feature = "debug")] - WindowEvent::KeyboardInput { - input: - winit::event::KeyboardInput { - virtual_keycode: Some(winit::event::VirtualKeyCode::F12), - state: winit::event::ElementState::Pressed, - .. - }, - .. - } => _debug.toggle(), - _ => {} + } if _modifiers.logo() => true, + _ => false, + } +} + +/// Builds a [`UserInterface`] for the provided [`Application`], logging +/// [`struct@Debug`] information accordingly. +pub fn build_user_interface<'a, A: Application>( + application: &'a mut A, + cache: Cache, + renderer: &mut A::Renderer, + size: Size, + debug: &mut Debug, +) -> UserInterface<'a, A::Message, A::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 +} + +/// Updates an [`Application`] by feeding it the provided messages, spawning any +/// resulting [`Command`], and tracking its [`Subscription`]. +pub fn update<A: Application, E: Executor>( + application: &mut A, + runtime: &mut Runtime<E, Proxy<A::Message>, A::Message>, + debug: &mut Debug, + clipboard: &mut A::Clipboard, + messages: &mut Vec<A::Message>, +) { + for message in messages.drain(..) { + debug.log_message(&message); + + debug.update_started(); + let command = runtime.enter(|| application.update(message, clipboard)); + debug.update_finished(); + + runtime.spawn(command); } + + let subscription = application.subscription(); + runtime.track(subscription); } |