From 529589d7fe9278858e3f251b559a1118598a8250 Mon Sep 17 00:00:00 2001 From: Richard Date: Fri, 1 Apr 2022 17:16:15 -0300 Subject: [PATCH 01/66] Introduce `multi_window` from `pure` --- Cargo.toml | 2 + src/lib.rs | 3 + src/multi_window.rs | 4 + src/multi_window/application.rs | 196 ++++++++++++++++++++++++++++++++ 4 files changed, 205 insertions(+) create mode 100644 src/multi_window.rs create mode 100644 src/multi_window/application.rs diff --git a/Cargo.toml b/Cargo.toml index 681aae5e91..adcdb79f9e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,8 @@ chrome-trace = [ "iced_wgpu?/tracing", "iced_glow?/tracing", ] +# Enables experimental multi-window support +multi_window = [] [badges] maintenance = { status = "actively-developed" } diff --git a/src/lib.rs b/src/lib.rs index a0e31be4f6..6cda8c419c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -181,6 +181,9 @@ pub mod touch; pub mod widget; pub mod window; +#[cfg(feature = "multi_window")] +pub mod multi_window; + #[cfg(all(not(feature = "glow"), feature = "wgpu"))] use iced_winit as runtime; diff --git a/src/multi_window.rs b/src/multi_window.rs new file mode 100644 index 0000000000..5b7a00b4db --- /dev/null +++ b/src/multi_window.rs @@ -0,0 +1,4 @@ +//! Leverage multi-window support in your application. +mod application; + +pub use application::Application; diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs new file mode 100644 index 0000000000..db41d54a61 --- /dev/null +++ b/src/multi_window/application.rs @@ -0,0 +1,196 @@ +use crate::{Command, Element, Executor, Settings, Subscription}; + +pub use iced_native::application::{Appearance, StyleSheet}; + +/// A pure version of [`Application`]. +/// +/// Unlike the impure version, the `view` method of this trait takes an +/// immutable reference to `self` and returns a pure [`Element`]. +/// +/// [`Application`]: crate::Application +/// [`Element`]: pure::Element +pub trait Application: Sized { + /// The [`Executor`] that will run commands and subscriptions. + /// + /// The [default executor] can be a good starting point! + /// + /// [`Executor`]: Self::Executor + /// [default executor]: crate::executor::Default + type Executor: Executor; + + /// The type of __messages__ your [`Application`] will produce. + type Message: std::fmt::Debug + Send; + + /// The theme of your [`Application`]. + type Theme: Default + StyleSheet; + + /// The data needed to initialize your [`Application`]. + 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`] 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. + /// + /// [`run`]: Self::run + fn new(flags: Self::Flags) -> (Self, Command); + + /// Returns the current title of the [`Application`]. + /// + /// This title can be dynamic! The runtime will automatically update the + /// title of your application when necessary. + 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. + fn update(&mut self, message: Self::Message) -> Command; + + /// Returns the current [`Theme`] of the [`Application`]. + /// + /// [`Theme`]: Self::Theme + fn theme(&self) -> Self::Theme { + Self::Theme::default() + } + + /// Returns the current [`Style`] of the [`Theme`]. + /// + /// [`Style`]: ::Style + /// [`Theme`]: Self::Theme + fn style(&self) -> ::Style { + ::Style::default() + } + + /// Returns the event [`Subscription`] for the current state of the + /// application. + /// + /// A [`Subscription`] will be kept alive as long as you keep returning it, + /// and the __messages__ produced will be handled by + /// [`update`](#tymethod.update). + /// + /// By default, this method returns an empty [`Subscription`]. + fn subscription(&self) -> Subscription { + Subscription::none() + } + + /// Returns the widgets to display in the [`Application`]. + /// + /// These widgets can produce __messages__ based on user interaction. + fn view(&self) -> Element<'_, Self::Message, crate::Renderer>; + + /// Returns the scale factor of the [`Application`]. + /// + /// It can be used to dynamically control the size of the UI at runtime + /// (i.e. zooming). + /// + /// For instance, a scale factor of `2.0` will make widgets twice as big, + /// while a scale factor of `0.5` will shrink them to half their size. + /// + /// By default, it returns `1.0`. + 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 + } + + /// Runs the [`Application`]. + /// + /// On native platforms, this method will take control of the current thread + /// until the [`Application`] exits. + /// + /// On the web platform, this method __will NOT return__ unless there is an + /// [`Error`] during startup. + /// + /// [`Error`]: crate::Error + fn run(settings: Settings) -> crate::Result + where + Self: 'static, + { + #[allow(clippy::needless_update)] + let renderer_settings = crate::renderer::Settings { + default_font: settings.default_font, + default_text_size: settings.default_text_size, + text_multithreading: settings.text_multithreading, + antialiasing: if settings.antialiasing { + Some(crate::renderer::settings::Antialiasing::MSAAx4) + } else { + None + }, + ..crate::renderer::Settings::from_env() + }; + + Ok(crate::runtime::application::run::< + Instance, + Self::Executor, + crate::renderer::window::Compositor, + >(settings.into(), renderer_settings)?) + } +} + +struct Instance(A); + +impl iced_winit::Program for Instance +where + A: Application, +{ + type Renderer = crate::Renderer; + type Message = A::Message; + + fn update(&mut self, message: Self::Message) -> Command { + self.0.update(message) + } + + fn view(&self) -> Element<'_, Self::Message, Self::Renderer> { + self.0.view() + } +} + +impl crate::runtime::Application for Instance +where + A: Application, +{ + type Flags = A::Flags; + + fn new(flags: Self::Flags) -> (Self, Command) { + let (app, command) = A::new(flags); + + (Instance(app), command) + } + + fn title(&self) -> String { + self.0.title() + } + + fn theme(&self) -> A::Theme { + self.0.theme() + } + + fn style(&self) -> ::Style { + self.0.style() + } + + fn subscription(&self) -> Subscription { + self.0.subscription() + } + + fn scale_factor(&self) -> f64 { + self.0.scale_factor() + } + + fn should_exit(&self) -> bool { + self.0.should_exit() + } +} From 287306e1ebec610c31e37782320fe00d20a6c9ac Mon Sep 17 00:00:00 2001 From: Richard Date: Fri, 1 Apr 2022 17:27:19 -0300 Subject: [PATCH 02/66] Introduce `multi_window` in `iced_winit` --- Cargo.toml | 2 +- winit/Cargo.toml | 1 + winit/src/lib.rs | 3 + winit/src/multi_window.rs | 742 ++++++++++++++++++++++++++++++++ winit/src/multi_window/state.rs | 212 +++++++++ 5 files changed, 959 insertions(+), 1 deletion(-) create mode 100644 winit/src/multi_window.rs create mode 100644 winit/src/multi_window/state.rs diff --git a/Cargo.toml b/Cargo.toml index adcdb79f9e..41f5af2fe3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,7 @@ chrome-trace = [ "iced_glow?/tracing", ] # Enables experimental multi-window support -multi_window = [] +multi_window = ["iced_winit/multi_window"] [badges] maintenance = { status = "actively-developed" } diff --git a/winit/Cargo.toml b/winit/Cargo.toml index 94aaa2cad3..2152e7da04 100644 --- a/winit/Cargo.toml +++ b/winit/Cargo.toml @@ -16,6 +16,7 @@ chrome-trace = ["trace", "tracing-chrome"] debug = ["iced_native/debug"] system = ["sysinfo"] application = [] +multi_window = [] [dependencies] window_clipboard = "0.2" diff --git a/winit/src/lib.rs b/winit/src/lib.rs index 06674109c4..9b3c0a024c 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -35,6 +35,9 @@ pub use iced_native::*; pub use winit; +#[cfg(feature = "multi_window")] +pub mod multi_window; + #[cfg(feature = "application")] pub mod application; pub mod clipboard; diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs new file mode 100644 index 0000000000..4ea7383aa4 --- /dev/null +++ b/winit/src/multi_window.rs @@ -0,0 +1,742 @@ +//! Create interactive, native cross-platform applications. +mod state; + +pub use state::State; + +use crate::clipboard::{self, Clipboard}; +use crate::conversion; +use crate::mouse; +use crate::renderer; +use crate::widget::operation; +use crate::{ + Command, Debug, Error, Executor, Proxy, Runtime, Settings, Size, + Subscription, +}; + +use iced_futures::futures; +use iced_futures::futures::channel::mpsc; +use iced_graphics::compositor; +use iced_graphics::window; +use iced_native::program::Program; +use iced_native::user_interface::{self, UserInterface}; + +pub use iced_native::application::{Appearance, StyleSheet}; + +use std::mem::ManuallyDrop; + +/// An interactive, native cross-platform application. +/// +/// This trait is the main entrypoint of Iced. Once implemented, you can run +/// your GUI application by simply calling [`run`]. It will run in +/// its own window. +/// +/// 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`. +pub trait Application: Program +where + ::Theme: StyleSheet, +{ + /// The data needed to initialize your [`Application`]. + 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`] 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); + + /// Returns the current title of the [`Application`]. + /// + /// This title can be dynamic! The runtime will automatically update the + /// title of your application when necessary. + fn title(&self) -> String; + + /// Returns the current [`Theme`] of the [`Application`]. + fn theme(&self) -> ::Theme; + + /// Returns the [`Style`] variation of the [`Theme`]. + fn style( + &self, + ) -> <::Theme as StyleSheet>::Style { + Default::default() + } + + /// 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 { + Subscription::none() + } + + /// Returns the scale factor of the [`Application`]. + /// + /// It can be used to dynamically control the size of the UI at runtime + /// (i.e. zooming). + /// + /// For instance, a scale factor of `2.0` will make widgets twice as big, + /// while a scale factor of `0.5` will shrink them to half their size. + /// + /// By default, it returns `1.0`. + 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 + } +} + +/// Runs an [`Application`] with an executor, compositor, and the provided +/// settings. +pub fn run( + settings: Settings, + compositor_settings: C::Settings, +) -> Result<(), Error> +where + A: Application + 'static, + E: Executor + 'static, + C: window::Compositor + 'static, + ::Theme: StyleSheet, +{ + use futures::task; + use futures::Future; + use winit::event_loop::EventLoopBuilder; + + let mut debug = Debug::new(); + debug.startup_started(); + + let event_loop = EventLoopBuilder::with_user_event().build(); + let proxy = event_loop.create_proxy(); + + let runtime = { + let proxy = Proxy::new(event_loop.create_proxy()); + let executor = E::new().map_err(Error::ExecutorCreationFailed)?; + + Runtime::new(executor, proxy) + }; + + let (application, init_command) = { + let flags = settings.flags; + + runtime.enter(|| A::new(flags)) + }; + + let builder = settings.window.into_builder( + &application.title(), + event_loop.primary_monitor(), + settings.id, + ); + + log::info!("Window builder: {:#?}", builder); + + let window = builder + .build(&event_loop) + .map_err(Error::WindowCreationFailed)?; + + #[cfg(target_arch = "wasm32")] + { + use winit::platform::web::WindowExtWebSys; + + let canvas = window.canvas(); + + let window = web_sys::window().unwrap(); + let document = window.document().unwrap(); + let body = document.body().unwrap(); + + let _ = body + .append_child(&canvas) + .expect("Append canvas to HTML body"); + } + + let (compositor, renderer) = C::new(compositor_settings, Some(&window))?; + + let (mut sender, receiver) = mpsc::unbounded(); + + let mut instance = Box::pin(run_instance::( + application, + compositor, + renderer, + runtime, + proxy, + debug, + receiver, + init_command, + window, + settings.exit_on_close_request, + )); + + let mut context = task::Context::from_waker(task::noop_waker_ref()); + + platform::run(event_loop, move |event, _, control_flow| { + use winit::event_loop::ControlFlow; + + if let ControlFlow::ExitWithCode(_) = control_flow { + 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, + }; + } + }) +} + +async fn run_instance( + mut application: A, + mut compositor: C, + mut renderer: A::Renderer, + mut runtime: Runtime, A::Message>, + mut proxy: winit::event_loop::EventLoopProxy, + mut debug: Debug, + mut receiver: mpsc::UnboundedReceiver>, + init_command: Command, + window: winit::window::Window, + exit_on_close_request: bool, +) where + A: Application + 'static, + E: Executor + 'static, + C: window::Compositor + 'static, + ::Theme: StyleSheet, +{ + use iced_futures::futures::stream::StreamExt; + use winit::event; + + let mut clipboard = Clipboard::connect(&window); + let mut cache = user_interface::Cache::default(); + let mut surface = compositor.create_surface(&window); + + let mut state = State::new(&application, &window); + let mut viewport_version = state.viewport_version(); + + let physical_size = state.physical_size(); + + compositor.configure_surface( + &mut surface, + physical_size.width, + physical_size.height, + ); + + run_command( + &application, + &mut cache, + &state, + &mut renderer, + init_command, + &mut runtime, + &mut clipboard, + &mut proxy, + &mut debug, + &window, + || compositor.fetch_information(), + ); + runtime.track(application.subscription()); + + let mut user_interface = ManuallyDrop::new(build_user_interface( + &application, + user_interface::Cache::default(), + &mut renderer, + state.logical_size(), + &mut debug, + )); + + let mut mouse_interaction = mouse::Interaction::default(); + let mut events = Vec::new(); + let mut messages = Vec::new(); + + debug.startup_finished(); + + while let Some(event) = receiver.next().await { + match event { + event::Event::MainEventsCleared => { + if events.is_empty() && messages.is_empty() { + continue; + } + + debug.event_processing_started(); + + let (interface_state, statuses) = user_interface.update( + &events, + state.cursor_position(), + &mut renderer, + &mut clipboard, + &mut messages, + ); + + debug.event_processing_finished(); + + for event in events.drain(..).zip(statuses.into_iter()) { + runtime.broadcast(event); + } + + if !messages.is_empty() + || matches!( + interface_state, + user_interface::State::Outdated, + ) + { + let mut cache = + ManuallyDrop::into_inner(user_interface).into_cache(); + + // Update application + update( + &mut application, + &mut cache, + &state, + &mut renderer, + &mut runtime, + &mut clipboard, + &mut proxy, + &mut debug, + &mut messages, + &window, + || compositor.fetch_information(), + ); + + // Update window + state.synchronize(&application, &window); + + let should_exit = application.should_exit(); + + user_interface = ManuallyDrop::new(build_user_interface( + &application, + cache, + &mut renderer, + state.logical_size(), + &mut debug, + )); + + if should_exit { + break; + } + } + + debug.draw_started(); + let new_mouse_interaction = user_interface.draw( + &mut renderer, + state.theme(), + &renderer::Style { + text_color: state.text_color(), + }, + state.cursor_position(), + ); + debug.draw_finished(); + + if new_mouse_interaction != mouse_interaction { + window.set_cursor_icon(conversion::mouse_interaction( + new_mouse_interaction, + )); + + mouse_interaction = new_mouse_interaction; + } + + 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(); + + if physical_size.width == 0 || physical_size.height == 0 { + continue; + } + + debug.render_started(); + let current_viewport_version = state.viewport_version(); + + if viewport_version != current_viewport_version { + let logical_size = state.logical_size(); + + debug.layout_started(); + user_interface = ManuallyDrop::new( + ManuallyDrop::into_inner(user_interface) + .relayout(logical_size, &mut renderer), + ); + debug.layout_finished(); + + debug.draw_started(); + let new_mouse_interaction = user_interface.draw( + &mut renderer, + state.theme(), + &renderer::Style { + text_color: state.text_color(), + }, + state.cursor_position(), + ); + + if new_mouse_interaction != mouse_interaction { + window.set_cursor_icon(conversion::mouse_interaction( + new_mouse_interaction, + )); + + mouse_interaction = new_mouse_interaction; + } + debug.draw_finished(); + + compositor.configure_surface( + &mut surface, + physical_size.width, + physical_size.height, + ); + + viewport_version = current_viewport_version; + } + + match compositor.present( + &mut renderer, + &mut surface, + state.viewport(), + state.background_color(), + &debug.overlay(), + ) { + Ok(()) => { + debug.render_finished(); + + // TODO: Handle animations! + // Maybe we can use `ControlFlow::WaitUntil` for this. + } + Err(error) => match error { + // This is an unrecoverable error. + compositor::SurfaceError::OutOfMemory => { + panic!("{:?}", error); + } + _ => { + debug.render_finished(); + + // Try rendering again next frame. + window.request_redraw(); + } + }, + } + } + event::Event::WindowEvent { + event: window_event, + .. + } => { + if requests_exit(&window_event, state.modifiers()) + && exit_on_close_request + { + break; + } + + state.update(&window, &window_event, &mut debug); + + if let Some(event) = conversion::window_event( + &window_event, + state.scale_factor(), + state.modifiers(), + ) { + events.push(event); + } + } + _ => {} + } + } + + // Manually drop the user interface + drop(ManuallyDrop::into_inner(user_interface)); +} + +/// Returns true if the provided event should cause an [`Application`] to +/// exit. +pub fn requests_exit( + event: &winit::event::WindowEvent<'_>, + _modifiers: winit::event::ModifiersState, +) -> bool { + use winit::event::WindowEvent; + + match event { + WindowEvent::CloseRequested => true, + #[cfg(target_os = "macos")] + WindowEvent::KeyboardInput { + input: + winit::event::KeyboardInput { + virtual_keycode: Some(winit::event::VirtualKeyCode::Q), + state: winit::event::ElementState::Pressed, + .. + }, + .. + } 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 A, + cache: user_interface::Cache, + renderer: &mut A::Renderer, + size: Size, + debug: &mut Debug, +) -> UserInterface<'a, A::Message, A::Renderer> +where + ::Theme: StyleSheet, +{ + 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( + application: &mut A, + cache: &mut user_interface::Cache, + state: &State, + renderer: &mut A::Renderer, + runtime: &mut Runtime, A::Message>, + clipboard: &mut Clipboard, + proxy: &mut winit::event_loop::EventLoopProxy, + debug: &mut Debug, + messages: &mut Vec, + window: &winit::window::Window, + graphics_info: impl FnOnce() -> compositor::Information + Copy, +) where + ::Theme: StyleSheet, +{ + for message in messages.drain(..) { + debug.log_message(&message); + + debug.update_started(); + let command = runtime.enter(|| application.update(message)); + debug.update_finished(); + + run_command( + application, + cache, + state, + renderer, + command, + runtime, + clipboard, + proxy, + debug, + window, + graphics_info, + ); + } + + let subscription = application.subscription(); + runtime.track(subscription); +} + +/// Runs the actions of a [`Command`]. +pub fn run_command( + application: &A, + cache: &mut user_interface::Cache, + state: &State, + renderer: &mut A::Renderer, + command: Command, + runtime: &mut Runtime, A::Message>, + clipboard: &mut Clipboard, + proxy: &mut winit::event_loop::EventLoopProxy, + debug: &mut Debug, + window: &winit::window::Window, + _graphics_info: impl FnOnce() -> compositor::Information + Copy, +) where + A: Application, + E: Executor, + ::Theme: StyleSheet, +{ + use iced_native::command; + use iced_native::system; + use iced_native::window; + + for action in command.actions() { + match action { + command::Action::Future(future) => { + runtime.spawn(future); + } + command::Action::Clipboard(action) => match action { + clipboard::Action::Read(tag) => { + let message = tag(clipboard.read()); + + proxy + .send_event(message) + .expect("Send message to event loop"); + } + clipboard::Action::Write(contents) => { + clipboard.write(contents); + } + }, + command::Action::Window(action) => match action { + window::Action::Resize { width, height } => { + window.set_inner_size(winit::dpi::LogicalSize { + width, + height, + }); + } + window::Action::Move { x, y } => { + window.set_outer_position(winit::dpi::LogicalPosition { + x, + y, + }); + } + window::Action::SetMode(mode) => { + window.set_visible(conversion::visible(mode)); + window.set_fullscreen(conversion::fullscreen( + window.primary_monitor(), + mode, + )); + } + window::Action::FetchMode(tag) => { + let mode = if window.is_visible().unwrap_or(true) { + conversion::mode(window.fullscreen()) + } else { + window::Mode::Hidden + }; + + proxy + .send_event(tag(mode)) + .expect("Send message to event loop"); + } + }, + command::Action::System(action) => match action { + system::Action::QueryInformation(_tag) => { + #[cfg(feature = "system")] + { + let graphics_info = _graphics_info(); + let proxy = proxy.clone(); + + let _ = std::thread::spawn(move || { + let information = + crate::system::information(graphics_info); + + let message = _tag(information); + + proxy + .send_event(message) + .expect("Send message to event loop") + }); + } + } + }, + command::Action::Widget(action) => { + let mut current_cache = std::mem::take(cache); + let mut current_operation = Some(action.into_operation()); + + let mut user_interface = build_user_interface( + application, + current_cache, + renderer, + state.logical_size(), + debug, + ); + + while let Some(mut operation) = current_operation.take() { + user_interface.operate(renderer, operation.as_mut()); + + match operation.finish() { + operation::Outcome::None => {} + operation::Outcome::Some(message) => { + proxy + .send_event(message) + .expect("Send message to event loop"); + } + operation::Outcome::Chain(next) => { + current_operation = Some(next); + } + } + } + + current_cache = user_interface.into_cache(); + *cache = current_cache; + } + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +mod platform { + pub fn run( + mut event_loop: winit::event_loop::EventLoop, + event_handler: F, + ) -> Result<(), super::Error> + where + F: 'static + + FnMut( + winit::event::Event<'_, T>, + &winit::event_loop::EventLoopWindowTarget, + &mut winit::event_loop::ControlFlow, + ), + { + use winit::platform::run_return::EventLoopExtRunReturn; + + let _ = event_loop.run_return(event_handler); + + Ok(()) + } +} + +#[cfg(target_arch = "wasm32")] +mod platform { + pub fn run( + event_loop: winit::event_loop::EventLoop, + event_handler: F, + ) -> ! + where + F: 'static + + FnMut( + winit::event::Event<'_, T>, + &winit::event_loop::EventLoopWindowTarget, + &mut winit::event_loop::ControlFlow, + ), + { + event_loop.run(event_handler) + } +} diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs new file mode 100644 index 0000000000..2d120ca1bc --- /dev/null +++ b/winit/src/multi_window/state.rs @@ -0,0 +1,212 @@ +use crate::application::{self, StyleSheet as _}; +use crate::conversion; +use crate::multi_window::Application; +use crate::{Color, Debug, Point, Size, Viewport}; + +use std::marker::PhantomData; +use winit::event::{Touch, WindowEvent}; +use winit::window::Window; + +/// The state of a windowed [`Application`]. +#[allow(missing_debug_implementations)] +pub struct State +where + ::Theme: application::StyleSheet, +{ + title: String, + scale_factor: f64, + viewport: Viewport, + viewport_version: usize, + cursor_position: winit::dpi::PhysicalPosition, + modifiers: winit::event::ModifiersState, + theme: ::Theme, + appearance: application::Appearance, + application: PhantomData, +} + +impl State +where + ::Theme: application::StyleSheet, +{ + /// Creates a new [`State`] for the provided [`Application`] and window. + pub fn new(application: &A, window: &Window) -> Self { + let title = application.title(); + let scale_factor = application.scale_factor(); + let theme = application.theme(); + let appearance = theme.appearance(application.style()); + + let viewport = { + let physical_size = window.inner_size(); + + Viewport::with_physical_size( + Size::new(physical_size.width, physical_size.height), + window.scale_factor() * scale_factor, + ) + }; + + Self { + title, + scale_factor, + viewport, + viewport_version: 0, + // TODO: Encode cursor availability in the type-system + cursor_position: winit::dpi::PhysicalPosition::new(-1.0, -1.0), + modifiers: winit::event::ModifiersState::default(), + theme, + appearance, + application: PhantomData, + } + } + + /// Returns the current [`Viewport`] of the [`State`]. + pub fn viewport(&self) -> &Viewport { + &self.viewport + } + + /// Returns the version of the [`Viewport`] of the [`State`]. + /// + /// The version is incremented every time the [`Viewport`] changes. + pub fn viewport_version(&self) -> usize { + self.viewport_version + } + + /// Returns the physical [`Size`] of the [`Viewport`] of the [`State`]. + pub fn physical_size(&self) -> Size { + self.viewport.physical_size() + } + + /// Returns the logical [`Size`] of the [`Viewport`] of the [`State`]. + pub fn logical_size(&self) -> Size { + self.viewport.logical_size() + } + + /// Returns the current scale factor of the [`Viewport`] of the [`State`]. + pub fn scale_factor(&self) -> f64 { + self.viewport.scale_factor() + } + + /// Returns the current cursor position of the [`State`]. + pub fn cursor_position(&self) -> Point { + conversion::cursor_position( + self.cursor_position, + self.viewport.scale_factor(), + ) + } + + /// Returns the current keyboard modifiers of the [`State`]. + pub fn modifiers(&self) -> winit::event::ModifiersState { + self.modifiers + } + + /// Returns the current theme of the [`State`]. + pub fn theme(&self) -> &::Theme { + &self.theme + } + + /// Returns the current background [`Color`] of the [`State`]. + pub fn background_color(&self) -> Color { + self.appearance.background_color + } + + /// Returns the current text [`Color`] of the [`State`]. + pub fn text_color(&self) -> Color { + self.appearance.text_color + } + + /// Processes the provided window event and updates the [`State`] + /// accordingly. + pub fn update( + &mut self, + window: &Window, + event: &WindowEvent<'_>, + _debug: &mut Debug, + ) { + match event { + WindowEvent::Resized(new_size) => { + let size = Size::new(new_size.width, new_size.height); + + self.viewport = Viewport::with_physical_size( + size, + window.scale_factor() * self.scale_factor, + ); + + self.viewport_version = self.viewport_version.wrapping_add(1); + } + WindowEvent::ScaleFactorChanged { + scale_factor: new_scale_factor, + new_inner_size, + } => { + let size = + Size::new(new_inner_size.width, new_inner_size.height); + + self.viewport = Viewport::with_physical_size( + size, + new_scale_factor * self.scale_factor, + ); + + self.viewport_version = self.viewport_version.wrapping_add(1); + } + WindowEvent::CursorMoved { position, .. } + | WindowEvent::Touch(Touch { + location: position, .. + }) => { + self.cursor_position = *position; + } + WindowEvent::CursorLeft { .. } => { + // TODO: Encode cursor availability in the type-system + self.cursor_position = + winit::dpi::PhysicalPosition::new(-1.0, -1.0); + } + WindowEvent::ModifiersChanged(new_modifiers) => { + self.modifiers = *new_modifiers; + } + #[cfg(feature = "debug")] + WindowEvent::KeyboardInput { + input: + winit::event::KeyboardInput { + virtual_keycode: Some(winit::event::VirtualKeyCode::F12), + state: winit::event::ElementState::Pressed, + .. + }, + .. + } => _debug.toggle(), + _ => {} + } + } + + /// Synchronizes the [`State`] with its [`Application`] and its respective + /// window. + /// + /// Normally an [`Application`] should be synchronized with its [`State`] + /// and window after calling [`Application::update`]. + /// + /// [`Application::update`]: crate::Program::update + pub fn synchronize(&mut self, application: &A, window: &Window) { + // Update window title + let new_title = application.title(); + + if self.title != new_title { + window.set_title(&new_title); + + self.title = new_title; + } + + // Update scale factor + let new_scale_factor = application.scale_factor(); + + if self.scale_factor != new_scale_factor { + let size = window.inner_size(); + + self.viewport = Viewport::with_physical_size( + Size::new(size.width, size.height), + window.scale_factor() * new_scale_factor, + ); + + self.scale_factor = new_scale_factor; + } + + // Update theme and appearance + self.theme = application.theme(); + self.appearance = self.theme.appearance(application.style()); + } +} From b896e41c6e03f1447419194ce41d15fb0db39d96 Mon Sep 17 00:00:00 2001 From: Richard Date: Fri, 1 Apr 2022 17:39:08 -0300 Subject: [PATCH 03/66] Unify `Application` and `Program` Instead of creating a separate `multi_window::Program`, the new `multi_window::Application` unifies both traits --- src/multi_window/application.rs | 28 +++++++++++----------------- winit/src/multi_window.rs | 28 ++++++++++++++++++++++++---- 2 files changed, 35 insertions(+), 21 deletions(-) diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index db41d54a61..fa0c15b1db 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -132,7 +132,7 @@ pub trait Application: Sized { ..crate::renderer::Settings::from_env() }; - Ok(crate::runtime::application::run::< + Ok(crate::runtime::multi_window::run::< Instance, Self::Executor, crate::renderer::window::Compositor, @@ -142,28 +142,14 @@ pub trait Application: Sized { struct Instance(A); -impl iced_winit::Program for Instance +impl crate::runtime::multi_window::Application for Instance where A: Application, { + type Flags = A::Flags; type Renderer = crate::Renderer; type Message = A::Message; - fn update(&mut self, message: Self::Message) -> Command { - self.0.update(message) - } - - fn view(&self) -> Element<'_, Self::Message, Self::Renderer> { - self.0.view() - } -} - -impl crate::runtime::Application for Instance -where - A: Application, -{ - type Flags = A::Flags; - fn new(flags: Self::Flags) -> (Self, Command) { let (app, command) = A::new(flags); @@ -174,6 +160,14 @@ where self.0.title() } + fn update(&mut self, message: Self::Message) -> Command { + self.0.update(message) + } + + fn view(&self) -> Element<'_, Self::Message, Self::Renderer> { + self.0.view() + } + fn theme(&self) -> A::Theme { self.0.theme() } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 4ea7383aa4..b519e4717a 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -9,15 +9,14 @@ use crate::mouse; use crate::renderer; use crate::widget::operation; use crate::{ - Command, Debug, Error, Executor, Proxy, Runtime, Settings, Size, - Subscription, + Command, Debug, Element, Error, Executor, Proxy, Renderer, Runtime, + Settings, Size, Subscription, }; use iced_futures::futures; use iced_futures::futures::channel::mpsc; use iced_graphics::compositor; use iced_graphics::window; -use iced_native::program::Program; use iced_native::user_interface::{self, UserInterface}; pub use iced_native::application::{Appearance, StyleSheet}; @@ -35,13 +34,34 @@ use std::mem::ManuallyDrop; /// /// When using an [`Application`] with the `debug` feature enabled, a debug view /// can be toggled by pressing `F12`. -pub trait Application: Program +pub trait Application: Sized where ::Theme: StyleSheet, { /// The data needed to initialize your [`Application`]. type Flags; + /// The graphics backend to use to draw the [`Program`]. + type Renderer: Renderer; + + /// The type of __messages__ your [`Program`] will produce. + 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. + fn update(&mut self, message: Self::Message) -> Command; + + /// Returns the widgets to display in the [`Program`]. + /// + /// These widgets can produce __messages__ based on user interaction. + fn view(&self) -> Element<'_, Self::Message, Self::Renderer>; + /// Initializes the [`Application`] with the flags provided to /// [`run`] as part of the [`Settings`]. /// From 12538d3c5be08f2109f1dc61936ceb2fda0fc5c6 Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 15 Jun 2022 16:46:37 -0300 Subject: [PATCH 04/66] Use map of windows internally --- winit/src/multi_window.rs | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index b519e4717a..8a9672079c 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -21,6 +21,7 @@ use iced_native::user_interface::{self, UserInterface}; pub use iced_native::application::{Appearance, StyleSheet}; +use std::collections::HashMap; use std::mem::ManuallyDrop; /// An interactive, native cross-platform application. @@ -169,6 +170,10 @@ where .build(&event_loop) .map_err(Error::WindowCreationFailed)?; + let windows: HashMap = + HashMap::from([(0usize, window)]); + let window = windows.values().next().expect("No window found"); + #[cfg(target_arch = "wasm32")] { use winit::platform::web::WindowExtWebSys; @@ -197,7 +202,7 @@ where debug, receiver, init_command, - window, + windows, settings.exit_on_close_request, )); @@ -247,7 +252,7 @@ async fn run_instance( mut debug: Debug, mut receiver: mpsc::UnboundedReceiver>, init_command: Command, - window: winit::window::Window, + windows: HashMap, exit_on_close_request: bool, ) where A: Application + 'static, @@ -258,11 +263,12 @@ async fn run_instance( use iced_futures::futures::stream::StreamExt; use winit::event; - let mut clipboard = Clipboard::connect(&window); + let window = windows.values().next().expect("No window found"); + let mut clipboard = Clipboard::connect(window); let mut cache = user_interface::Cache::default(); let mut surface = compositor.create_surface(&window); - let mut state = State::new(&application, &window); + let mut state = State::new(&application, window); let mut viewport_version = state.viewport_version(); let physical_size = state.physical_size(); @@ -283,7 +289,7 @@ async fn run_instance( &mut clipboard, &mut proxy, &mut debug, - &window, + &windows, || compositor.fetch_information(), ); runtime.track(application.subscription()); @@ -345,12 +351,12 @@ async fn run_instance( &mut proxy, &mut debug, &mut messages, - &window, + &windows, || compositor.fetch_information(), ); // Update window - state.synchronize(&application, &window); + state.synchronize(&application, window); let should_exit = application.should_exit(); @@ -487,7 +493,7 @@ async fn run_instance( break; } - state.update(&window, &window_event, &mut debug); + state.update(window, &window_event, &mut debug); if let Some(event) = conversion::window_event( &window_event, @@ -564,7 +570,7 @@ pub fn update( proxy: &mut winit::event_loop::EventLoopProxy, debug: &mut Debug, messages: &mut Vec, - window: &winit::window::Window, + windows: &HashMap, graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where ::Theme: StyleSheet, @@ -586,7 +592,7 @@ pub fn update( clipboard, proxy, debug, - window, + windows, graphics_info, ); } @@ -606,7 +612,7 @@ pub fn run_command( clipboard: &mut Clipboard, proxy: &mut winit::event_loop::EventLoopProxy, debug: &mut Debug, - window: &winit::window::Window, + windows: &HashMap, _graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where A: Application, @@ -617,6 +623,8 @@ pub fn run_command( use iced_native::system; use iced_native::window; + let window = windows.values().next().expect("No window found"); + for action in command.actions() { match action { command::Action::Future(future) => { From 5919325d9b9ebf86f7358059201e6fc1af2412d8 Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 15 Jun 2022 20:01:50 -0300 Subject: [PATCH 05/66] Internally wrap `Message` with a `Event` enum --- winit/src/multi_window.rs | 43 +++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 8a9672079c..61984b9394 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -13,8 +13,8 @@ use crate::{ Settings, Size, Subscription, }; -use iced_futures::futures; use iced_futures::futures::channel::mpsc; +use iced_futures::futures::{self, FutureExt}; use iced_graphics::compositor; use iced_graphics::window; use iced_native::user_interface::{self, UserInterface}; @@ -24,6 +24,16 @@ pub use iced_native::application::{Appearance, StyleSheet}; use std::collections::HashMap; use std::mem::ManuallyDrop; +/// TODO(derezzedex) +// This is the an wrapper around the `Application::Message` associate type +// to allows the `shell` to create internal messages, while still having +// the current user specified custom messages. +#[derive(Debug, Clone)] +pub enum Event { + /// An [`Application`] generated message + Application(Message), +} + /// An interactive, native cross-platform application. /// /// This trait is the main entrypoint of Iced. Once implemented, you can run @@ -247,10 +257,12 @@ async fn run_instance( mut application: A, mut compositor: C, mut renderer: A::Renderer, - mut runtime: Runtime, A::Message>, - mut proxy: winit::event_loop::EventLoopProxy, + mut runtime: Runtime>, Event>, + mut proxy: winit::event_loop::EventLoopProxy>, mut debug: Debug, - mut receiver: mpsc::UnboundedReceiver>, + mut receiver: mpsc::UnboundedReceiver< + winit::event::Event<'_, Event>, + >, init_command: Command, windows: HashMap, exit_on_close_request: bool, @@ -292,7 +304,7 @@ async fn run_instance( &windows, || compositor.fetch_information(), ); - runtime.track(application.subscription()); + runtime.track(application.subscription().map(Event::Application)); let mut user_interface = ManuallyDrop::new(build_user_interface( &application, @@ -406,6 +418,7 @@ async fn run_instance( )); } event::Event::UserEvent(message) => { + let Event::Application(message) = message; messages.push(message); } event::Event::RedrawRequested(_) => { @@ -565,9 +578,9 @@ pub fn update( cache: &mut user_interface::Cache, state: &State, renderer: &mut A::Renderer, - runtime: &mut Runtime, A::Message>, + runtime: &mut Runtime>, Event>, clipboard: &mut Clipboard, - proxy: &mut winit::event_loop::EventLoopProxy, + proxy: &mut winit::event_loop::EventLoopProxy>, debug: &mut Debug, messages: &mut Vec, windows: &HashMap, @@ -597,7 +610,7 @@ pub fn update( ); } - let subscription = application.subscription(); + let subscription = application.subscription().map(Event::Application); runtime.track(subscription); } @@ -608,9 +621,9 @@ pub fn run_command( state: &State, renderer: &mut A::Renderer, command: Command, - runtime: &mut Runtime, A::Message>, + runtime: &mut Runtime>, Event>, clipboard: &mut Clipboard, - proxy: &mut winit::event_loop::EventLoopProxy, + proxy: &mut winit::event_loop::EventLoopProxy>, debug: &mut Debug, windows: &HashMap, _graphics_info: impl FnOnce() -> compositor::Information + Copy, @@ -628,14 +641,14 @@ pub fn run_command( for action in command.actions() { match action { command::Action::Future(future) => { - runtime.spawn(future); + runtime.spawn(Box::pin(future.map(Event::Application))); } command::Action::Clipboard(action) => match action { clipboard::Action::Read(tag) => { let message = tag(clipboard.read()); proxy - .send_event(message) + .send_event(Event::Application(message)) .expect("Send message to event loop"); } clipboard::Action::Write(contents) => { @@ -670,7 +683,7 @@ pub fn run_command( }; proxy - .send_event(tag(mode)) + .send_event(Event::Application(tag(mode))) .expect("Send message to event loop"); } }, @@ -688,7 +701,7 @@ pub fn run_command( let message = _tag(information); proxy - .send_event(message) + .send_event(Event::Application(message)) .expect("Send message to event loop") }); } @@ -713,7 +726,7 @@ pub fn run_command( operation::Outcome::None => {} operation::Outcome::Some(message) => { proxy - .send_event(message) + .send_event(Event::Application(message)) .expect("Send message to event loop"); } operation::Outcome::Chain(next) => { From 00d6baf861ba57984a341283823e9fea3c262130 Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 15 Jun 2022 20:10:15 -0300 Subject: [PATCH 06/66] fix: temporalily remove the unsafe pointer `HWND` --- winit/src/settings.rs | 6 +++--- winit/src/settings/windows.rs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/winit/src/settings.rs b/winit/src/settings.rs index 9bbdef5cea..94d243a770 100644 --- a/winit/src/settings.rs +++ b/winit/src/settings.rs @@ -154,9 +154,9 @@ impl Window { { use winit::platform::windows::WindowBuilderExtWindows; - if let Some(parent) = self.platform_specific.parent { - window_builder = window_builder.with_parent_window(parent); - } + // if let Some(parent) = self.platform_specific.parent { + // window_builder = window_builder.with_parent_window(parent); + // } window_builder = window_builder .with_drag_and_drop(self.platform_specific.drag_and_drop); diff --git a/winit/src/settings/windows.rs b/winit/src/settings/windows.rs index ff03a9c51e..0891ec2c94 100644 --- a/winit/src/settings/windows.rs +++ b/winit/src/settings/windows.rs @@ -4,7 +4,7 @@ #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PlatformSpecific { /// Parent window - pub parent: Option, + // pub parent: Option, /// Drag and drop support pub drag_and_drop: bool, @@ -13,7 +13,7 @@ pub struct PlatformSpecific { impl Default for PlatformSpecific { fn default() -> Self { Self { - parent: None, + // parent: None, drag_and_drop: true, } } From 8fdd5ee8b60e551088d4a18fb1d58b6c3e62ba7d Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 15 Jun 2022 20:38:51 -0300 Subject: [PATCH 07/66] Synchronize window list with `windows` method --- winit/src/multi_window.rs | 72 +++++++++++++++++++++++++++------ winit/src/multi_window/state.rs | 22 +++++++++- 2 files changed, 79 insertions(+), 15 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 61984b9394..900ee92ac9 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -7,6 +7,7 @@ use crate::clipboard::{self, Clipboard}; use crate::conversion; use crate::mouse; use crate::renderer; +use crate::settings; use crate::widget::operation; use crate::{ Command, Debug, Element, Error, Executor, Proxy, Renderer, Runtime, @@ -28,10 +29,17 @@ use std::mem::ManuallyDrop; // This is the an wrapper around the `Application::Message` associate type // to allows the `shell` to create internal messages, while still having // the current user specified custom messages. -#[derive(Debug, Clone)] +#[derive(Debug)] pub enum Event { /// An [`Application`] generated message Application(Message), + + /// TODO(derezzedex) + // Create a wrapper variant of `window::Event` type instead + // (maybe we should also allow users to listen/react to those internal messages?) + NewWindow(usize, settings::Window), + /// TODO(derezzedex) + WindowCreated(usize, winit::window::Window), } /// An interactive, native cross-platform application. @@ -218,7 +226,7 @@ where let mut context = task::Context::from_waker(task::noop_waker_ref()); - platform::run(event_loop, move |event, _, control_flow| { + platform::run(event_loop, move |event, event_loop, control_flow| { use winit::event_loop::ControlFlow; if let ControlFlow::ExitWithCode(_) = control_flow { @@ -237,6 +245,21 @@ where event: winit::event::WindowEvent::Resized(*new_inner_size), window_id, }), + winit::event::Event::UserEvent(Event::NewWindow(id, settings)) => { + // TODO(derezzedex) + let window = settings + .into_builder( + "fix window title", + event_loop.primary_monitor(), + None, + ) + .build(event_loop) + .expect("Failed to build window"); + + Some(winit::event::Event::UserEvent(Event::WindowCreated( + id, window, + ))) + } _ => event.to_static(), }; @@ -264,7 +287,7 @@ async fn run_instance( winit::event::Event<'_, Event>, >, init_command: Command, - windows: HashMap, + mut windows: HashMap, exit_on_close_request: bool, ) where A: Application + 'static, @@ -275,12 +298,18 @@ async fn run_instance( use iced_futures::futures::stream::StreamExt; use winit::event; - let window = windows.values().next().expect("No window found"); - let mut clipboard = Clipboard::connect(window); + // TODO(derezzedex) + let mut clipboard = + Clipboard::connect(windows.values().next().expect("No window found")); let mut cache = user_interface::Cache::default(); - let mut surface = compositor.create_surface(&window); + let mut surface = compositor + .create_surface(&windows.values().next().expect("No window found")); - let mut state = State::new(&application, window); + // TODO(derezzedex) + let mut state = State::new( + &application, + windows.values().next().expect("No window found"), + ); let mut viewport_version = state.viewport_version(); let physical_size = state.physical_size(); @@ -368,7 +397,7 @@ async fn run_instance( ); // Update window - state.synchronize(&application, window); + state.synchronize(&application, &windows, &proxy); let should_exit = application.should_exit(); @@ -396,6 +425,8 @@ async fn run_instance( ); debug.draw_finished(); + // TODO(derezzedex) + let window = windows.values().next().expect("No window found"); if new_mouse_interaction != mouse_interaction { window.set_cursor_icon(conversion::mouse_interaction( new_mouse_interaction, @@ -417,10 +448,15 @@ async fn run_instance( )), )); } - event::Event::UserEvent(message) => { - let Event::Application(message) = message; - messages.push(message); - } + event::Event::UserEvent(event) => match event { + Event::Application(message) => { + messages.push(message); + } + Event::WindowCreated(id, window) => { + let _ = windows.insert(id, window); + } + Event::NewWindow(_, _) => unreachable!(), + }, event::Event::RedrawRequested(_) => { let physical_size = state.physical_size(); @@ -451,6 +487,9 @@ async fn run_instance( state.cursor_position(), ); + // TODO(derezzedex) + let window = + windows.values().next().expect("No window found"); if new_mouse_interaction != mouse_interaction { window.set_cursor_icon(conversion::mouse_interaction( new_mouse_interaction, @@ -491,7 +530,12 @@ async fn run_instance( debug.render_finished(); // Try rendering again next frame. - window.request_redraw(); + // TODO(derezzedex) + windows + .values() + .next() + .expect("No window found") + .request_redraw(); } }, } @@ -506,6 +550,8 @@ async fn run_instance( break; } + // TODO(derezzedex) + let window = windows.values().next().expect("No window found"); state.update(window, &window_event, &mut debug); if let Some(event) = conversion::window_event( diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index 2d120ca1bc..009a3698b5 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -1,10 +1,12 @@ use crate::application::{self, StyleSheet as _}; use crate::conversion; -use crate::multi_window::Application; +use crate::multi_window::{Application, Event}; use crate::{Color, Debug, Point, Size, Viewport}; +use std::collections::HashMap; use std::marker::PhantomData; use winit::event::{Touch, WindowEvent}; +use winit::event_loop::EventLoopProxy; use winit::window::Window; /// The state of a windowed [`Application`]. @@ -181,7 +183,23 @@ where /// and window after calling [`Application::update`]. /// /// [`Application::update`]: crate::Program::update - pub fn synchronize(&mut self, application: &A, window: &Window) { + pub fn synchronize( + &mut self, + application: &A, + windows: &HashMap, + proxy: &EventLoopProxy>, + ) { + let new_windows = application.windows(); + for (id, settings) in new_windows { + if !windows.contains_key(&id) { + proxy + .send_event(Event::NewWindow(id, settings)) + .expect("Failed to send message"); + } + } + + let window = windows.values().next().expect("No window found"); + // Update window title let new_title = application.title(); From ec56c0686df1a200e37af951a3a8eca562c32a5c Mon Sep 17 00:00:00 2001 From: Richard Date: Tue, 21 Jun 2022 15:59:45 -0300 Subject: [PATCH 08/66] Introduce opaque `window::Id` type --- native/src/window.rs | 2 ++ native/src/window/id.rs | 16 ++++++++++++++++ src/multi_window/application.rs | 14 ++++++++++++++ winit/src/multi_window.rs | 23 +++++++++++++---------- winit/src/multi_window/state.rs | 3 ++- winit/src/window.rs | 2 +- 6 files changed, 48 insertions(+), 12 deletions(-) create mode 100644 native/src/window/id.rs diff --git a/native/src/window.rs b/native/src/window.rs index 1b97e6557a..dc9e2d6612 100644 --- a/native/src/window.rs +++ b/native/src/window.rs @@ -1,10 +1,12 @@ //! Build window-based GUI applications. mod action; mod event; +mod id; mod mode; mod user_attention; pub use action::Action; pub use event::Event; +pub use id::Id; pub use mode::Mode; pub use user_attention::UserAttention; diff --git a/native/src/window/id.rs b/native/src/window/id.rs new file mode 100644 index 0000000000..56496aaa90 --- /dev/null +++ b/native/src/window/id.rs @@ -0,0 +1,16 @@ +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +#[derive(Debug, PartialEq, Eq, Hash)] +/// TODO(derezzedex) +pub struct Id(u64); + +impl Id { + /// TODO(derezzedex) + pub fn new(id: impl Hash) -> Id { + let mut hasher = DefaultHasher::new(); + id.hash(&mut hasher); + + Id(hasher.finish()) + } +} diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index fa0c15b1db..6b3f4676b9 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -1,3 +1,4 @@ +use crate::window; use crate::{Command, Element, Executor, Settings, Subscription}; pub use iced_native::application::{Appearance, StyleSheet}; @@ -45,6 +46,9 @@ pub trait Application: Sized { /// title of your application when necessary. fn title(&self) -> String; + /// TODO(derezzedex) + fn windows(&self) -> Vec<(window::Id, window::Settings)>; + /// Handles a __message__ and updates the state of the [`Application`]. /// /// This is where you define your __update logic__. All the __messages__, @@ -160,6 +164,16 @@ where self.0.title() } + fn windows(&self) -> Vec<(window::Id, iced_winit::settings::Window)> { + self.0 + .windows() + .into_iter() + .map(|(id, settings)| { + (id, iced_winit::settings::Window::from(settings)) + }) + .collect() + } + fn update(&mut self, message: Self::Message) -> Command { self.0.update(message) } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 900ee92ac9..14be4de3b4 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -9,6 +9,7 @@ use crate::mouse; use crate::renderer; use crate::settings; use crate::widget::operation; +use crate::window; use crate::{ Command, Debug, Element, Error, Executor, Proxy, Renderer, Runtime, Settings, Size, Subscription, @@ -17,7 +18,6 @@ use crate::{ use iced_futures::futures::channel::mpsc; use iced_futures::futures::{self, FutureExt}; use iced_graphics::compositor; -use iced_graphics::window; use iced_native::user_interface::{self, UserInterface}; pub use iced_native::application::{Appearance, StyleSheet}; @@ -37,9 +37,9 @@ pub enum Event { /// TODO(derezzedex) // Create a wrapper variant of `window::Event` type instead // (maybe we should also allow users to listen/react to those internal messages?) - NewWindow(usize, settings::Window), + NewWindow(window::Id, settings::Window), /// TODO(derezzedex) - WindowCreated(usize, winit::window::Window), + WindowCreated(window::Id, winit::window::Window), } /// An interactive, native cross-platform application. @@ -66,6 +66,9 @@ where /// The type of __messages__ your [`Program`] will produce. type Message: std::fmt::Debug + Send; + /// TODO(derezzedex) + fn windows(&self) -> Vec<(window::Id, settings::Window)>; + /// Handles a __message__ and updates the state of the [`Program`]. /// /// This is where you define your __update logic__. All the __messages__, @@ -150,7 +153,7 @@ pub fn run( where A: Application + 'static, E: Executor + 'static, - C: window::Compositor + 'static, + C: iced_graphics::window::Compositor + 'static, ::Theme: StyleSheet, { use futures::task; @@ -188,8 +191,8 @@ where .build(&event_loop) .map_err(Error::WindowCreationFailed)?; - let windows: HashMap = - HashMap::from([(0usize, window)]); + let windows: HashMap = + HashMap::from([(window::Id::new(0usize), window)]); let window = windows.values().next().expect("No window found"); #[cfg(target_arch = "wasm32")] @@ -287,12 +290,12 @@ async fn run_instance( winit::event::Event<'_, Event>, >, init_command: Command, - mut windows: HashMap, + mut windows: HashMap, exit_on_close_request: bool, ) where A: Application + 'static, E: Executor + 'static, - C: window::Compositor + 'static, + C: iced_graphics::window::Compositor + 'static, ::Theme: StyleSheet, { use iced_futures::futures::stream::StreamExt; @@ -629,7 +632,7 @@ pub fn update( proxy: &mut winit::event_loop::EventLoopProxy>, debug: &mut Debug, messages: &mut Vec, - windows: &HashMap, + windows: &HashMap, graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where ::Theme: StyleSheet, @@ -671,7 +674,7 @@ pub fn run_command( clipboard: &mut Clipboard, proxy: &mut winit::event_loop::EventLoopProxy>, debug: &mut Debug, - windows: &HashMap, + windows: &HashMap, _graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where A: Application, diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index 009a3698b5..dd2d25ceb5 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -1,6 +1,7 @@ use crate::application::{self, StyleSheet as _}; use crate::conversion; use crate::multi_window::{Application, Event}; +use crate::window; use crate::{Color, Debug, Point, Size, Viewport}; use std::collections::HashMap; @@ -186,7 +187,7 @@ where pub fn synchronize( &mut self, application: &A, - windows: &HashMap, + windows: &HashMap, proxy: &EventLoopProxy>, ) { let new_windows = application.windows(); diff --git a/winit/src/window.rs b/winit/src/window.rs index 89db32628c..f2c7037a37 100644 --- a/winit/src/window.rs +++ b/winit/src/window.rs @@ -2,7 +2,7 @@ use crate::command::{self, Command}; use iced_native::window; -pub use window::{Event, Mode, UserAttention}; +pub use window::{Id, Event, Mode, UserAttention}; /// Closes the current window and exits the application. pub fn close() -> Command { From 64e21535c7e5df9a1ff94b9b9036b6ae5b5c82b0 Mon Sep 17 00:00:00 2001 From: Richard Date: Tue, 28 Jun 2022 14:27:06 -0300 Subject: [PATCH 09/66] Fix `multi_window` example --- examples/multi_window/src/main.rs | 58 +++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 examples/multi_window/src/main.rs diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs new file mode 100644 index 0000000000..0ba6a5915a --- /dev/null +++ b/examples/multi_window/src/main.rs @@ -0,0 +1,58 @@ +use iced::multi_window::Application; +use iced::pure::{button, column, text, Element}; +use iced::{window, Alignment, Command, Settings}; + +pub fn main() -> iced::Result { + Counter::run(Settings::default()) +} + +struct Counter { + value: i32, +} + +#[derive(Debug, Clone, Copy)] +enum Message { + IncrementPressed, + DecrementPressed, +} + +impl Application for Counter { + type Flags = (); + type Executor = iced::executor::Default; + type Message = Message; + + fn new(_flags: ()) -> (Self, Command) { + (Self { value: 0 }, Command::none()) + } + + fn title(&self) -> String { + String::from("MultiWindow - Iced") + } + + fn windows(&self) -> Vec<(window::Id, iced::window::Settings)> { + todo!() + } + + fn update(&mut self, message: Message) -> Command { + match message { + Message::IncrementPressed => { + self.value += 1; + } + Message::DecrementPressed => { + self.value -= 1; + } + } + + Command::none() + } + + fn view(&self) -> Element { + column() + .padding(20) + .align_items(Alignment::Center) + .push(button("Increment").on_press(Message::IncrementPressed)) + .push(text(self.value.to_string()).size(50)) + .push(button("Decrement").on_press(Message::DecrementPressed)) + .into() + } +} From 97914daaab477ce47a8329f07958332b5caa4ed0 Mon Sep 17 00:00:00 2001 From: Richard Date: Tue, 12 Jul 2022 10:26:16 -0300 Subject: [PATCH 10/66] what is this --- native/src/window/id.rs | 2 +- winit/src/multi_window.rs | 421 +++++++++++++++++++++----------- winit/src/multi_window/state.rs | 16 +- 3 files changed, 285 insertions(+), 154 deletions(-) diff --git a/native/src/window/id.rs b/native/src/window/id.rs index 56496aaa90..0ba355af61 100644 --- a/native/src/window/id.rs +++ b/native/src/window/id.rs @@ -1,7 +1,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; -#[derive(Debug, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] /// TODO(derezzedex) pub struct Id(u64); diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 14be4de3b4..82ee30ed86 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -301,50 +301,63 @@ async fn run_instance( use iced_futures::futures::stream::StreamExt; use winit::event; - // TODO(derezzedex) let mut clipboard = Clipboard::connect(windows.values().next().expect("No window found")); let mut cache = user_interface::Cache::default(); - let mut surface = compositor - .create_surface(&windows.values().next().expect("No window found")); + let mut window_ids: HashMap<_, _> = windows + .iter() + .map(|(&id, window)| (window.id(), id)) + .collect(); - // TODO(derezzedex) - let mut state = State::new( - &application, - windows.values().next().expect("No window found"), - ); - let mut viewport_version = state.viewport_version(); + let mut states = HashMap::new(); + let mut interfaces = ManuallyDrop::new(HashMap::new()); - let physical_size = state.physical_size(); + for (&id, window) in windows.keys().zip(windows.values()) { + let mut surface = compositor.create_surface(window); - compositor.configure_surface( - &mut surface, - physical_size.width, - physical_size.height, - ); + let state = State::new(&application, window); - run_command( - &application, - &mut cache, - &state, - &mut renderer, - init_command, - &mut runtime, - &mut clipboard, - &mut proxy, - &mut debug, - &windows, - || compositor.fetch_information(), - ); - runtime.track(application.subscription().map(Event::Application)); + let physical_size = state.physical_size(); - let mut user_interface = ManuallyDrop::new(build_user_interface( - &application, - user_interface::Cache::default(), - &mut renderer, - state.logical_size(), - &mut debug, - )); + compositor.configure_surface( + &mut surface, + physical_size.width, + physical_size.height, + ); + + let user_interface = build_user_interface( + &application, + user_interface::Cache::default(), + &mut renderer, + state.logical_size(), + &mut debug, + ); + + let window_state: WindowState = WindowState { surface, state }; + + let _ = states.insert(id, window_state); + let _ = interfaces.insert(id, user_interface); + } + + { + // TODO(derezzedex) + let window_state = states.values().next().expect("No state found"); + + run_command( + &application, + &mut cache, + &window_state.state, + &mut renderer, + init_command, + &mut runtime, + &mut clipboard, + &mut proxy, + &mut debug, + &windows, + || compositor.fetch_information(), + ); + } + runtime.track(application.subscription().map(Event::Application)); let mut mouse_interaction = mouse::Interaction::default(); let mut events = Vec::new(); @@ -352,93 +365,118 @@ async fn run_instance( debug.startup_finished(); - while let Some(event) = receiver.next().await { + 'main: while let Some(event) = receiver.next().await { match event { event::Event::MainEventsCleared => { - if events.is_empty() && messages.is_empty() { - continue; - } - - debug.event_processing_started(); + dbg!(states.keys().collect::>()); + for id in states.keys().copied().collect::>() { + let cursor_position = + states.get(&id).unwrap().state.cursor_position(); + let window = windows.get(&id).unwrap(); + + if events.is_empty() && messages.is_empty() { + continue; + } - let (interface_state, statuses) = user_interface.update( - &events, - state.cursor_position(), - &mut renderer, - &mut clipboard, - &mut messages, - ); + debug.event_processing_started(); + + let (interface_state, statuses) = { + let user_interface = interfaces.get_mut(&id).unwrap(); + user_interface.update( + &events, + cursor_position, + &mut renderer, + &mut clipboard, + &mut messages, + ) + }; - debug.event_processing_finished(); + debug.event_processing_finished(); - for event in events.drain(..).zip(statuses.into_iter()) { - runtime.broadcast(event); - } + // TODO(derezzedex): only drain events for this window + for event in events.drain(..).zip(statuses.into_iter()) { + runtime.broadcast(event); + } - if !messages.is_empty() - || matches!( - interface_state, - user_interface::State::Outdated, - ) - { - let mut cache = - ManuallyDrop::into_inner(user_interface).into_cache(); - - // Update application - update( - &mut application, - &mut cache, - &state, - &mut renderer, - &mut runtime, - &mut clipboard, - &mut proxy, - &mut debug, - &mut messages, - &windows, - || compositor.fetch_information(), - ); + if !messages.is_empty() + || matches!( + interface_state, + user_interface::State::Outdated, + ) + { + let state = &mut states.get_mut(&id).unwrap().state; + let pure_states: HashMap<_, _> = + ManuallyDrop::into_inner(interfaces) + .drain() + .map( + |(id, interface): ( + window::Id, + UserInterface<'_, _, _>, + )| { + (id, interface.into_cache()) + }, + ) + .collect(); + + // Update application + update( + &mut application, + &mut cache, + state, + &mut renderer, + &mut runtime, + &mut clipboard, + &mut proxy, + &mut debug, + &mut messages, + &windows, + || compositor.fetch_information(), + ); + + // Update window + state.synchronize(&application, &windows, &proxy); + + let should_exit = application.should_exit(); + + interfaces = ManuallyDrop::new(build_user_interfaces( + &application, + &mut renderer, + &mut debug, + &states, + pure_states, + )); - // Update window - state.synchronize(&application, &windows, &proxy); + if should_exit { + break 'main; + } + } - let should_exit = application.should_exit(); + debug.draw_started(); + let new_mouse_interaction = { + let user_interface = interfaces.get_mut(&id).unwrap(); + let state = &states.get(&id).unwrap().state; + + user_interface.draw( + &mut renderer, + state.theme(), + &renderer::Style { + text_color: state.text_color(), + }, + state.cursor_position(), + ) + }; + debug.draw_finished(); - user_interface = ManuallyDrop::new(build_user_interface( - &application, - cache, - &mut renderer, - state.logical_size(), - &mut debug, - )); + if new_mouse_interaction != mouse_interaction { + window.set_cursor_icon(conversion::mouse_interaction( + new_mouse_interaction, + )); - if should_exit { - break; + mouse_interaction = new_mouse_interaction; } - } - - debug.draw_started(); - let new_mouse_interaction = user_interface.draw( - &mut renderer, - state.theme(), - &renderer::Style { - text_color: state.text_color(), - }, - state.cursor_position(), - ); - debug.draw_finished(); - - // TODO(derezzedex) - let window = windows.values().next().expect("No window found"); - if new_mouse_interaction != mouse_interaction { - window.set_cursor_icon(conversion::mouse_interaction( - new_mouse_interaction, - )); - mouse_interaction = new_mouse_interaction; + window.request_redraw(); } - - window.request_redraw(); } event::Event::PlatformSpecific(event::PlatformSpecific::MacOS( event::MacOS::ReceivedUrl(url), @@ -456,43 +494,81 @@ async fn run_instance( messages.push(message); } Event::WindowCreated(id, window) => { + let mut surface = compositor.create_surface(&window); + + let state = State::new(&application, &window); + + let physical_size = state.physical_size(); + + compositor.configure_surface( + &mut surface, + physical_size.width, + physical_size.height, + ); + + let user_interface = build_user_interface( + &application, + user_interface::Cache::default(), + &mut renderer, + state.logical_size(), + &mut debug, + ); + + let window_state: WindowState = + WindowState { surface, state }; + + let _ = states.insert(id, window_state); + let _ = interfaces.insert(id, user_interface); + let _ = window_ids.insert(window.id(), id); let _ = windows.insert(id, window); } Event::NewWindow(_, _) => unreachable!(), }, - event::Event::RedrawRequested(_) => { - let physical_size = state.physical_size(); + event::Event::RedrawRequested(id) => { + let window_state = window_ids + .get(&id) + .and_then(|id| states.get_mut(id)) + .unwrap(); + + let mut user_interface = window_ids + .get(&id) + .and_then(|id| interfaces.remove(id)) + .unwrap(); + + let physical_size = window_state.state.physical_size(); if physical_size.width == 0 || physical_size.height == 0 { continue; } debug.render_started(); - let current_viewport_version = state.viewport_version(); - if viewport_version != current_viewport_version { - let logical_size = state.logical_size(); + if window_state.state.viewport_changed() { + let logical_size = window_state.state.logical_size(); debug.layout_started(); - user_interface = ManuallyDrop::new( - ManuallyDrop::into_inner(user_interface) - .relayout(logical_size, &mut renderer), - ); + user_interface = + user_interface.relayout(logical_size, &mut renderer); debug.layout_finished(); debug.draw_started(); - let new_mouse_interaction = user_interface.draw( - &mut renderer, - state.theme(), - &renderer::Style { - text_color: state.text_color(), - }, - state.cursor_position(), - ); + let new_mouse_interaction = { + let state = &window_state.state; + + user_interface.draw( + &mut renderer, + state.theme(), + &renderer::Style { + text_color: state.text_color(), + }, + state.cursor_position(), + ) + }; - // TODO(derezzedex) - let window = - windows.values().next().expect("No window found"); + let window = window_ids + .get(&id) + .and_then(|id| windows.get(id)) + .unwrap(); if new_mouse_interaction != mouse_interaction { window.set_cursor_icon(conversion::mouse_interaction( new_mouse_interaction, @@ -502,20 +578,21 @@ async fn run_instance( } debug.draw_finished(); + let _ = interfaces + .insert(*window_ids.get(&id).unwrap(), user_interface); + compositor.configure_surface( - &mut surface, + &mut window_state.surface, physical_size.width, physical_size.height, ); - - viewport_version = current_viewport_version; } match compositor.present( &mut renderer, - &mut surface, - state.viewport(), - state.background_color(), + &mut window_state.surface, + window_state.state.viewport(), + window_state.state.background_color(), &debug.overlay(), ) { Ok(()) => { @@ -545,22 +622,30 @@ async fn run_instance( } event::Event::WindowEvent { event: window_event, - .. + window_id, } => { - if requests_exit(&window_event, state.modifiers()) + // dbg!(window_id); + let window = window_ids + .get(&window_id) + .and_then(|id| windows.get(id)) + .unwrap(); + let window_state = window_ids + .get(&window_id) + .and_then(|id| states.get_mut(id)) + .unwrap(); + + if requests_exit(&window_event, window_state.state.modifiers()) && exit_on_close_request { break; } - // TODO(derezzedex) - let window = windows.values().next().expect("No window found"); - state.update(window, &window_event, &mut debug); + window_state.state.update(window, &window_event, &mut debug); if let Some(event) = conversion::window_event( &window_event, - state.scale_factor(), - state.modifiers(), + window_state.state.scale_factor(), + window_state.state.modifiers(), ) { events.push(event); } @@ -570,7 +655,7 @@ async fn run_instance( } // Manually drop the user interface - drop(ManuallyDrop::into_inner(user_interface)); + // drop(ManuallyDrop::into_inner(user_interface)); } /// Returns true if the provided event should cause an [`Application`] to @@ -791,6 +876,54 @@ pub fn run_command( } } +struct WindowState +where + A: Application, + C: iced_graphics::window::Compositor, + ::Theme: StyleSheet, +{ + surface: ::Surface, + state: State, +} + +fn build_user_interfaces<'a, A, C>( + application: &'a A, + renderer: &mut A::Renderer, + debug: &mut Debug, + states: &HashMap>, + mut pure_states: HashMap, +) -> HashMap< + window::Id, + UserInterface< + 'a, + ::Message, + ::Renderer, + >, +> +where + A: Application + 'static, + C: iced_graphics::window::Compositor + 'static, + ::Theme: StyleSheet, +{ + let mut interfaces = HashMap::new(); + + for (id, pure_state) in pure_states.drain() { + let state = &states.get(&id).unwrap().state; + + let user_interface = build_user_interface( + application, + pure_state, + renderer, + state.logical_size(), + debug, + ); + + let _ = interfaces.insert(id, user_interface); + } + + interfaces +} + #[cfg(not(target_arch = "wasm32"))] mod platform { pub fn run( diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index dd2d25ceb5..d22de961d8 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -19,7 +19,7 @@ where title: String, scale_factor: f64, viewport: Viewport, - viewport_version: usize, + viewport_changed: bool, cursor_position: winit::dpi::PhysicalPosition, modifiers: winit::event::ModifiersState, theme: ::Theme, @@ -51,7 +51,7 @@ where title, scale_factor, viewport, - viewport_version: 0, + viewport_changed: false, // TODO: Encode cursor availability in the type-system cursor_position: winit::dpi::PhysicalPosition::new(-1.0, -1.0), modifiers: winit::event::ModifiersState::default(), @@ -66,11 +66,9 @@ where &self.viewport } - /// Returns the version of the [`Viewport`] of the [`State`]. - /// - /// The version is incremented every time the [`Viewport`] changes. - pub fn viewport_version(&self) -> usize { - self.viewport_version + /// TODO(derezzedex) + pub fn viewport_changed(&self) -> bool { + self.viewport_changed } /// Returns the physical [`Size`] of the [`Viewport`] of the [`State`]. @@ -133,7 +131,7 @@ where window.scale_factor() * self.scale_factor, ); - self.viewport_version = self.viewport_version.wrapping_add(1); + self.viewport_changed = true; } WindowEvent::ScaleFactorChanged { scale_factor: new_scale_factor, @@ -147,7 +145,7 @@ where new_scale_factor * self.scale_factor, ); - self.viewport_version = self.viewport_version.wrapping_add(1); + self.viewport_changed = true; } WindowEvent::CursorMoved { position, .. } | WindowEvent::Touch(Touch { From 8f53df560e1bde33e874977e5115cd0f9301640d Mon Sep 17 00:00:00 2001 From: Richard Date: Thu, 14 Jul 2022 10:13:37 -0300 Subject: [PATCH 11/66] fix: temporarily add `window::Id` to events internaly --- winit/src/multi_window.rs | 53 ++++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 18 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 82ee30ed86..6c2dc888dc 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -368,13 +368,27 @@ async fn run_instance( 'main: while let Some(event) = receiver.next().await { match event { event::Event::MainEventsCleared => { - dbg!(states.keys().collect::>()); for id in states.keys().copied().collect::>() { + let (filtered, remaining): (Vec<_>, Vec<_>) = events + .iter() + .cloned() + .partition( + |(window_id, _event): &( + Option, + iced_native::event::Event, + )| { + *window_id == Some(id) || *window_id == None + }, + ); + + events.retain(|el| remaining.contains(el)); + let filtered: Vec<_> = filtered.into_iter().map(|(_id, event)| event.clone()).collect(); + let cursor_position = states.get(&id).unwrap().state.cursor_position(); let window = windows.get(&id).unwrap(); - if events.is_empty() && messages.is_empty() { + if filtered.is_empty() && messages.is_empty() { continue; } @@ -383,7 +397,7 @@ async fn run_instance( let (interface_state, statuses) = { let user_interface = interfaces.get_mut(&id).unwrap(); user_interface.update( - &events, + &filtered, cursor_position, &mut renderer, &mut clipboard, @@ -393,11 +407,11 @@ async fn run_instance( debug.event_processing_finished(); - // TODO(derezzedex): only drain events for this window - for event in events.drain(..).zip(statuses.into_iter()) { + for event in filtered.into_iter().zip(statuses.into_iter()) { runtime.broadcast(event); } + // TODO(derezzedex): Should we redraw every window? We can't know what changed. if !messages.is_empty() || matches!( interface_state, @@ -475,18 +489,22 @@ async fn run_instance( mouse_interaction = new_mouse_interaction; } - window.request_redraw(); + for window in windows.values(){ + 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, - )), + events.push(( + None, + iced_native::Event::PlatformSpecific( + event::PlatformSpecific::MacOS( + event::MacOS::ReceivedUrl(url), + ), + ), )); } event::Event::UserEvent(event) => match event { @@ -529,12 +547,6 @@ async fn run_instance( .get(&id) .and_then(|id| states.get_mut(id)) .unwrap(); - - let mut user_interface = window_ids - .get(&id) - .and_then(|id| interfaces.remove(id)) - .unwrap(); - let physical_size = window_state.state.physical_size(); if physical_size.width == 0 || physical_size.height == 0 { @@ -544,6 +556,11 @@ async fn run_instance( debug.render_started(); if window_state.state.viewport_changed() { + let mut user_interface = window_ids + .get(&id) + .and_then(|id| interfaces.remove(id)) + .unwrap(); + let logical_size = window_state.state.logical_size(); debug.layout_started(); @@ -647,7 +664,7 @@ async fn run_instance( window_state.state.scale_factor(), window_state.state.modifiers(), ) { - events.push(event); + events.push((window_ids.get(&window_id).cloned(), event)); } } _ => {} From 01bad4f89654d65b0d6a65a8df99c387cbadf7fe Mon Sep 17 00:00:00 2001 From: Richard Date: Thu, 14 Jul 2022 10:37:33 -0300 Subject: [PATCH 12/66] duplicate `pane_grid` example to `multi_window` --- examples/multi_window/Cargo.toml | 12 + examples/multi_window/src/main.rs | 370 +++++++++++++++++++++++++++--- 2 files changed, 355 insertions(+), 27 deletions(-) create mode 100644 examples/multi_window/Cargo.toml diff --git a/examples/multi_window/Cargo.toml b/examples/multi_window/Cargo.toml new file mode 100644 index 0000000000..9c3d0f2107 --- /dev/null +++ b/examples/multi_window/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "multi_window" +version = "0.1.0" +authors = ["Richard Custodio "] +edition = "2021" +publish = false +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +iced = { path = "../..", features = ["debug", "multi_window"] } +iced_native = { path = "../../native" } +iced_lazy = { path = "../../lazy" } \ No newline at end of file diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 0ba6a5915a..ae8fa22b0c 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -1,58 +1,374 @@ -use iced::multi_window::Application; -use iced::pure::{button, column, text, Element}; -use iced::{window, Alignment, Command, Settings}; +use iced::alignment::{self, Alignment}; +use iced::executor; +use iced::keyboard; +use iced::theme::{self, Theme}; +use iced::widget::pane_grid::{self, PaneGrid}; +use iced::widget::{button, column, container, row, scrollable, text}; +use iced::{ + Application, Color, Command, Element, Length, Settings, Size, Subscription, +}; +use iced_lazy::responsive; +use iced_native::{event, subscription, Event}; pub fn main() -> iced::Result { - Counter::run(Settings::default()) + Example::run(Settings::default()) } -struct Counter { - value: i32, +struct Example { + panes: pane_grid::State, + panes_created: usize, + focus: Option, } #[derive(Debug, Clone, Copy)] enum Message { - IncrementPressed, - DecrementPressed, + Split(pane_grid::Axis, pane_grid::Pane), + SplitFocused(pane_grid::Axis), + FocusAdjacent(pane_grid::Direction), + Clicked(pane_grid::Pane), + Dragged(pane_grid::DragEvent), + Resized(pane_grid::ResizeEvent), + TogglePin(pane_grid::Pane), + Close(pane_grid::Pane), + CloseFocused, } -impl Application for Counter { - type Flags = (); - type Executor = iced::executor::Default; +impl Application for Example { type Message = Message; + type Theme = Theme; + type Executor = executor::Default; + type Flags = (); fn new(_flags: ()) -> (Self, Command) { - (Self { value: 0 }, Command::none()) - } + let (panes, _) = pane_grid::State::new(Pane::new(0)); - fn title(&self) -> String { - String::from("MultiWindow - Iced") + ( + Example { + panes, + panes_created: 1, + focus: None, + }, + Command::none(), + ) } - fn windows(&self) -> Vec<(window::Id, iced::window::Settings)> { - todo!() + fn title(&self) -> String { + String::from("Pane grid - Iced") } fn update(&mut self, message: Message) -> Command { match message { - Message::IncrementPressed => { - self.value += 1; + Message::Split(axis, pane) => { + let result = self.panes.split( + axis, + &pane, + Pane::new(self.panes_created), + ); + + if let Some((pane, _)) = result { + self.focus = Some(pane); + } + + self.panes_created += 1; + } + Message::SplitFocused(axis) => { + if let Some(pane) = self.focus { + let result = self.panes.split( + axis, + &pane, + Pane::new(self.panes_created), + ); + + if let Some((pane, _)) = result { + self.focus = Some(pane); + } + + self.panes_created += 1; + } + } + Message::FocusAdjacent(direction) => { + if let Some(pane) = self.focus { + if let Some(adjacent) = + self.panes.adjacent(&pane, direction) + { + self.focus = Some(adjacent); + } + } + } + Message::Clicked(pane) => { + self.focus = Some(pane); + } + Message::Resized(pane_grid::ResizeEvent { split, ratio }) => { + self.panes.resize(&split, ratio); + } + Message::Dragged(pane_grid::DragEvent::Dropped { + pane, + target, + }) => { + self.panes.swap(&pane, &target); } - Message::DecrementPressed => { - self.value -= 1; + Message::Dragged(_) => {} + Message::TogglePin(pane) => { + if let Some(Pane { is_pinned, .. }) = self.panes.get_mut(&pane) + { + *is_pinned = !*is_pinned; + } + } + Message::Close(pane) => { + if let Some((_, sibling)) = self.panes.close(&pane) { + self.focus = Some(sibling); + } + } + Message::CloseFocused => { + if let Some(pane) = self.focus { + if let Some(Pane { is_pinned, .. }) = self.panes.get(&pane) + { + if !is_pinned { + if let Some((_, sibling)) = self.panes.close(&pane) + { + self.focus = Some(sibling); + } + } + } + } } } Command::none() } + fn subscription(&self) -> Subscription { + subscription::events_with(|event, status| { + if let event::Status::Captured = status { + return None; + } + + match event { + Event::Keyboard(keyboard::Event::KeyPressed { + modifiers, + key_code, + }) if modifiers.command() => handle_hotkey(key_code), + _ => None, + } + }) + } + fn view(&self) -> Element { - column() - .padding(20) - .align_items(Alignment::Center) - .push(button("Increment").on_press(Message::IncrementPressed)) - .push(text(self.value.to_string()).size(50)) - .push(button("Decrement").on_press(Message::DecrementPressed)) + let focus = self.focus; + let total_panes = self.panes.len(); + + let pane_grid = PaneGrid::new(&self.panes, |id, pane| { + let is_focused = focus == Some(id); + + let pin_button = button( + text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14), + ) + .on_press(Message::TogglePin(id)) + .padding(3); + + let title = row![ + pin_button, + "Pane", + text(pane.id.to_string()).style(if is_focused { + PANE_ID_COLOR_FOCUSED + } else { + PANE_ID_COLOR_UNFOCUSED + }), + ] + .spacing(5); + + let title_bar = pane_grid::TitleBar::new(title) + .controls(view_controls(id, total_panes, pane.is_pinned)) + .padding(10) + .style(if is_focused { + style::title_bar_focused + } else { + style::title_bar_active + }); + + pane_grid::Content::new(responsive(move |size| { + view_content(id, total_panes, pane.is_pinned, size) + })) + .title_bar(title_bar) + .style(if is_focused { + style::pane_focused + } else { + style::pane_active + }) + }) + .width(Length::Fill) + .height(Length::Fill) + .spacing(10) + .on_click(Message::Clicked) + .on_drag(Message::Dragged) + .on_resize(10, Message::Resized); + + container(pane_grid) + .width(Length::Fill) + .height(Length::Fill) + .padding(10) .into() } } + +const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb( + 0xFF as f32 / 255.0, + 0xC7 as f32 / 255.0, + 0xC7 as f32 / 255.0, +); +const PANE_ID_COLOR_FOCUSED: Color = Color::from_rgb( + 0xFF as f32 / 255.0, + 0x47 as f32 / 255.0, + 0x47 as f32 / 255.0, +); + +fn handle_hotkey(key_code: keyboard::KeyCode) -> Option { + use keyboard::KeyCode; + use pane_grid::{Axis, Direction}; + + let direction = match key_code { + KeyCode::Up => Some(Direction::Up), + KeyCode::Down => Some(Direction::Down), + KeyCode::Left => Some(Direction::Left), + KeyCode::Right => Some(Direction::Right), + _ => None, + }; + + match key_code { + KeyCode::V => Some(Message::SplitFocused(Axis::Vertical)), + KeyCode::H => Some(Message::SplitFocused(Axis::Horizontal)), + KeyCode::W => Some(Message::CloseFocused), + _ => direction.map(Message::FocusAdjacent), + } +} + +struct Pane { + id: usize, + pub is_pinned: bool, +} + +impl Pane { + fn new(id: usize) -> Self { + Self { + id, + is_pinned: false, + } + } +} + +fn view_content<'a>( + pane: pane_grid::Pane, + total_panes: usize, + is_pinned: bool, + size: Size, +) -> Element<'a, Message> { + let button = |label, message| { + button( + text(label) + .width(Length::Fill) + .horizontal_alignment(alignment::Horizontal::Center) + .size(16), + ) + .width(Length::Fill) + .padding(8) + .on_press(message) + }; + + let mut controls = column![ + button( + "Split horizontally", + Message::Split(pane_grid::Axis::Horizontal, pane), + ), + button( + "Split vertically", + Message::Split(pane_grid::Axis::Vertical, pane), + ) + ] + .spacing(5) + .max_width(150); + + if total_panes > 1 && !is_pinned { + controls = controls.push( + button("Close", Message::Close(pane)) + .style(theme::Button::Destructive), + ); + } + + let content = column![ + text(format!("{}x{}", size.width, size.height)).size(24), + controls, + ] + .width(Length::Fill) + .spacing(10) + .align_items(Alignment::Center); + + container(scrollable(content)) + .width(Length::Fill) + .height(Length::Fill) + .padding(5) + .center_y() + .into() +} + +fn view_controls<'a>( + pane: pane_grid::Pane, + total_panes: usize, + is_pinned: bool, +) -> Element<'a, Message> { + let mut button = button(text("Close").size(14)) + .style(theme::Button::Destructive) + .padding(3); + + if total_panes > 1 && !is_pinned { + button = button.on_press(Message::Close(pane)); + } + + button.into() +} + +mod style { + use iced::widget::container; + use iced::Theme; + + pub fn title_bar_active(theme: &Theme) -> container::Appearance { + let palette = theme.extended_palette(); + + container::Appearance { + text_color: Some(palette.background.strong.text), + background: Some(palette.background.strong.color.into()), + ..Default::default() + } + } + + pub fn title_bar_focused(theme: &Theme) -> container::Appearance { + let palette = theme.extended_palette(); + + container::Appearance { + text_color: Some(palette.primary.strong.text), + background: Some(palette.primary.strong.color.into()), + ..Default::default() + } + } + + pub fn pane_active(theme: &Theme) -> container::Appearance { + let palette = theme.extended_palette(); + + container::Appearance { + background: Some(palette.background.weak.color.into()), + border_width: 2.0, + border_color: palette.background.strong.color, + ..Default::default() + } + } + + pub fn pane_focused(theme: &Theme) -> container::Appearance { + let palette = theme.extended_palette(); + + container::Appearance { + background: Some(palette.background.weak.color.into()), + border_width: 2.0, + border_color: palette.primary.strong.color, + ..Default::default() + } + } +} From 2fe58e12619186eb3755491db2bdaf02de297afb Mon Sep 17 00:00:00 2001 From: Richard Date: Thu, 21 Jul 2022 09:52:32 -0300 Subject: [PATCH 13/66] add `window::Id` to `view` --- src/multi_window/application.rs | 12 ++++++++--- winit/src/multi_window.rs | 35 ++++++++++++++++++++++++--------- 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index 6b3f4676b9..e849bf2bec 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -88,7 +88,10 @@ pub trait Application: Sized { /// Returns the widgets to display in the [`Application`]. /// /// These widgets can produce __messages__ based on user interaction. - fn view(&self) -> Element<'_, Self::Message, crate::Renderer>; + fn view( + &self, + window: window::Id, + ) -> Element<'_, Self::Message, crate::Renderer>; /// Returns the scale factor of the [`Application`]. /// @@ -178,8 +181,11 @@ where self.0.update(message) } - fn view(&self) -> Element<'_, Self::Message, Self::Renderer> { - self.0.view() + fn view( + &self, + window: window::Id, + ) -> Element<'_, Self::Message, Self::Renderer> { + self.0.view(window) } fn theme(&self) -> A::Theme { diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 6c2dc888dc..dc00d7375f 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -82,7 +82,10 @@ where /// Returns the widgets to display in the [`Program`]. /// /// These widgets can produce __messages__ based on user interaction. - fn view(&self) -> Element<'_, Self::Message, Self::Renderer>; + fn view( + &self, + window: window::Id, + ) -> Element<'_, Self::Message, Self::Renderer>; /// Initializes the [`Application`] with the flags provided to /// [`run`] as part of the [`Settings`]. @@ -331,6 +334,7 @@ async fn run_instance( &mut renderer, state.logical_size(), &mut debug, + id, ); let window_state: WindowState = WindowState { surface, state }; @@ -354,6 +358,7 @@ async fn run_instance( &mut proxy, &mut debug, &windows, + &window_ids, || compositor.fetch_information(), ); } @@ -369,10 +374,8 @@ async fn run_instance( match event { event::Event::MainEventsCleared => { for id in states.keys().copied().collect::>() { - let (filtered, remaining): (Vec<_>, Vec<_>) = events - .iter() - .cloned() - .partition( + let (filtered, remaining): (Vec<_>, Vec<_>) = + events.iter().cloned().partition( |(window_id, _event): &( Option, iced_native::event::Event, @@ -382,7 +385,10 @@ async fn run_instance( ); events.retain(|el| remaining.contains(el)); - let filtered: Vec<_> = filtered.into_iter().map(|(_id, event)| event.clone()).collect(); + let filtered: Vec<_> = filtered + .into_iter() + .map(|(_id, event)| event) + .collect(); let cursor_position = states.get(&id).unwrap().state.cursor_position(); @@ -407,7 +413,8 @@ async fn run_instance( debug.event_processing_finished(); - for event in filtered.into_iter().zip(statuses.into_iter()) { + for event in filtered.into_iter().zip(statuses.into_iter()) + { runtime.broadcast(event); } @@ -444,6 +451,7 @@ async fn run_instance( &mut debug, &mut messages, &windows, + &window_ids, || compositor.fetch_information(), ); @@ -489,7 +497,7 @@ async fn run_instance( mouse_interaction = new_mouse_interaction; } - for window in windows.values(){ + for window in windows.values() { window.request_redraw(); } } @@ -530,6 +538,7 @@ async fn run_instance( &mut renderer, state.logical_size(), &mut debug, + id, ); let window_state: WindowState = @@ -707,12 +716,13 @@ pub fn build_user_interface<'a, A: Application>( renderer: &mut A::Renderer, size: Size, debug: &mut Debug, + id: window::Id, ) -> UserInterface<'a, A::Message, A::Renderer> where ::Theme: StyleSheet, { debug.view_started(); - let view = application.view(); + let view = application.view(id); debug.view_finished(); debug.layout_started(); @@ -735,6 +745,7 @@ pub fn update( debug: &mut Debug, messages: &mut Vec, windows: &HashMap, + window_ids: &HashMap, graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where ::Theme: StyleSheet, @@ -757,6 +768,7 @@ pub fn update( proxy, debug, windows, + window_ids, graphics_info, ); } @@ -777,6 +789,7 @@ pub fn run_command( proxy: &mut winit::event_loop::EventLoopProxy>, debug: &mut Debug, windows: &HashMap, + window_ids: &HashMap, _graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where A: Application, @@ -787,7 +800,9 @@ pub fn run_command( use iced_native::system; use iced_native::window; + // TODO(derezzedex) let window = windows.values().next().expect("No window found"); + let id = *window_ids.get(&window.id()).unwrap(); for action in command.actions() { match action { @@ -868,6 +883,7 @@ pub fn run_command( renderer, state.logical_size(), debug, + id, ); while let Some(mut operation) = current_operation.take() { @@ -933,6 +949,7 @@ where renderer, state.logical_size(), debug, + id, ); let _ = interfaces.insert(id, user_interface); From 3d901d5f1f8e496651a6f9881fec92bc8998d910 Mon Sep 17 00:00:00 2001 From: Richard Date: Thu, 21 Jul 2022 09:52:55 -0300 Subject: [PATCH 14/66] create multi-windowed `pane_grid` example --- examples/multi_window/src/main.rs | 379 ++++++++++++++++++++++-------- 1 file changed, 278 insertions(+), 101 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index ae8fa22b0c..4ad92adb5c 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -1,36 +1,55 @@ use iced::alignment::{self, Alignment}; use iced::executor; use iced::keyboard; +use iced::multi_window::Application; use iced::theme::{self, Theme}; use iced::widget::pane_grid::{self, PaneGrid}; -use iced::widget::{button, column, container, row, scrollable, text}; -use iced::{ - Application, Color, Command, Element, Length, Settings, Size, Subscription, +use iced::widget::{ + button, column, container, pick_list, row, scrollable, text, text_input, }; +use iced::window; +use iced::{Color, Command, Element, Length, Settings, Size, Subscription}; use iced_lazy::responsive; use iced_native::{event, subscription, Event}; +use std::collections::HashMap; + pub fn main() -> iced::Result { Example::run(Settings::default()) } struct Example { - panes: pane_grid::State, + windows: HashMap, panes_created: usize, + _focused: window::Id, +} + +struct Window { + title: String, + panes: pane_grid::State, focus: Option, } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] enum Message { + Window(window::Id, WindowMessage), +} + +#[derive(Debug, Clone)] +enum WindowMessage { Split(pane_grid::Axis, pane_grid::Pane), SplitFocused(pane_grid::Axis), FocusAdjacent(pane_grid::Direction), Clicked(pane_grid::Pane), Dragged(pane_grid::DragEvent), + PopOut(pane_grid::Pane), Resized(pane_grid::ResizeEvent), + TitleChanged(String), + ToggleMoving(pane_grid::Pane), TogglePin(pane_grid::Pane), Close(pane_grid::Pane), CloseFocused, + SelectedWindow(pane_grid::Pane, SelectableWindow), } impl Application for Example { @@ -40,93 +59,158 @@ impl Application for Example { type Flags = (); fn new(_flags: ()) -> (Self, Command) { - let (panes, _) = pane_grid::State::new(Pane::new(0)); + let (panes, _) = + pane_grid::State::new(Pane::new(0, pane_grid::Axis::Horizontal)); + let window = Window { + panes, + focus: None, + title: String::from("Default window"), + }; ( Example { - panes, + windows: HashMap::from([(window::Id::new(0usize), window)]), panes_created: 1, - focus: None, + _focused: window::Id::new(0usize), }, Command::none(), ) } fn title(&self) -> String { - String::from("Pane grid - Iced") + String::from("Multi windowed pane grid - Iced") } fn update(&mut self, message: Message) -> Command { + let Message::Window(id, message) = message; match message { - Message::Split(axis, pane) => { - let result = self.panes.split( + WindowMessage::Split(axis, pane) => { + let window = self.windows.get_mut(&id).unwrap(); + let result = window.panes.split( axis, &pane, - Pane::new(self.panes_created), + Pane::new(self.panes_created, axis), ); if let Some((pane, _)) = result { - self.focus = Some(pane); + window.focus = Some(pane); } self.panes_created += 1; } - Message::SplitFocused(axis) => { - if let Some(pane) = self.focus { - let result = self.panes.split( + WindowMessage::SplitFocused(axis) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.focus { + let result = window.panes.split( axis, &pane, - Pane::new(self.panes_created), + Pane::new(self.panes_created, axis), ); if let Some((pane, _)) = result { - self.focus = Some(pane); + window.focus = Some(pane); } self.panes_created += 1; } } - Message::FocusAdjacent(direction) => { - if let Some(pane) = self.focus { + WindowMessage::FocusAdjacent(direction) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.focus { if let Some(adjacent) = - self.panes.adjacent(&pane, direction) + window.panes.adjacent(&pane, direction) { - self.focus = Some(adjacent); + window.focus = Some(adjacent); } } } - Message::Clicked(pane) => { - self.focus = Some(pane); + WindowMessage::Clicked(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + window.focus = Some(pane); } - Message::Resized(pane_grid::ResizeEvent { split, ratio }) => { - self.panes.resize(&split, ratio); + WindowMessage::Resized(pane_grid::ResizeEvent { split, ratio }) => { + let window = self.windows.get_mut(&id).unwrap(); + window.panes.resize(&split, ratio); } - Message::Dragged(pane_grid::DragEvent::Dropped { + WindowMessage::SelectedWindow(pane, selected) => { + let window = self.windows.get_mut(&id).unwrap(); + let (mut pane, _) = window.panes.close(&pane).unwrap(); + pane.is_moving = false; + + if let Some(window) = self.windows.get_mut(&selected.0) { + let (&first_pane, _) = window.panes.iter().next().unwrap(); + let result = + window.panes.split(pane.axis, &first_pane, pane); + + if let Some((pane, _)) = result { + window.focus = Some(pane); + } + + self.panes_created += 1; + } + } + WindowMessage::ToggleMoving(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.panes.get_mut(&pane) { + pane.is_moving = !pane.is_moving; + } + } + WindowMessage::TitleChanged(title) => { + let window = self.windows.get_mut(&id).unwrap(); + window.title = title; + } + WindowMessage::PopOut(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some((popped, sibling)) = window.panes.close(&pane) { + window.focus = Some(sibling); + + let (panes, _) = pane_grid::State::new(popped); + let window = Window { + panes, + focus: None, + title: format!("New window ({})", self.windows.len()), + }; + + self.windows + .insert(window::Id::new(self.windows.len()), window); + } + } + WindowMessage::Dragged(pane_grid::DragEvent::Dropped { pane, target, }) => { - self.panes.swap(&pane, &target); + let window = self.windows.get_mut(&id).unwrap(); + window.panes.swap(&pane, &target); } - Message::Dragged(_) => {} - Message::TogglePin(pane) => { - if let Some(Pane { is_pinned, .. }) = self.panes.get_mut(&pane) + // WindowMessage::Dragged(pane_grid::DragEvent::Picked { pane }) => { + // println!("Picked {pane:?}"); + // } + WindowMessage::Dragged(_) => {} + WindowMessage::TogglePin(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(Pane { is_pinned, .. }) = + window.panes.get_mut(&pane) { *is_pinned = !*is_pinned; } } - Message::Close(pane) => { - if let Some((_, sibling)) = self.panes.close(&pane) { - self.focus = Some(sibling); + WindowMessage::Close(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some((_, sibling)) = window.panes.close(&pane) { + window.focus = Some(sibling); } } - Message::CloseFocused => { - if let Some(pane) = self.focus { - if let Some(Pane { is_pinned, .. }) = self.panes.get(&pane) + WindowMessage::CloseFocused => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.focus { + if let Some(Pane { is_pinned, .. }) = + window.panes.get(&pane) { if !is_pinned { - if let Some((_, sibling)) = self.panes.close(&pane) + if let Some((_, sibling)) = + window.panes.close(&pane) { - self.focus = Some(sibling); + window.focus = Some(sibling); } } } @@ -147,66 +231,106 @@ impl Application for Example { Event::Keyboard(keyboard::Event::KeyPressed { modifiers, key_code, - }) if modifiers.command() => handle_hotkey(key_code), + }) if modifiers.command() => { + handle_hotkey(key_code).map(|message| { + Message::Window(window::Id::new(0usize), message) + }) + } // TODO(derezzedex) _ => None, } }) } - fn view(&self) -> Element { - let focus = self.focus; - let total_panes = self.panes.len(); - - let pane_grid = PaneGrid::new(&self.panes, |id, pane| { - let is_focused = focus == Some(id); - - let pin_button = button( - text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14), - ) - .on_press(Message::TogglePin(id)) - .padding(3); + fn windows(&self) -> Vec<(window::Id, iced::window::Settings)> { + self.windows + .iter() + .map(|(&id, _window)| (id, iced::window::Settings::default())) + .collect() + } - let title = row![ - pin_button, - "Pane", - text(pane.id.to_string()).style(if is_focused { - PANE_ID_COLOR_FOCUSED - } else { - PANE_ID_COLOR_UNFOCUSED - }), + fn view(&self, window_id: window::Id) -> Element { + if let Some(window) = self.windows.get(&window_id) { + let focus = window.focus; + let total_panes = window.panes.len(); + + let window_controls = row![ + text_input( + "Window title", + &window.title, + WindowMessage::TitleChanged, + ), + button(text("Apply")).style(theme::Button::Primary), ] - .spacing(5); - - let title_bar = pane_grid::TitleBar::new(title) - .controls(view_controls(id, total_panes, pane.is_pinned)) - .padding(10) + .spacing(5) + .align_items(Alignment::Center); + + let pane_grid = PaneGrid::new(&window.panes, |id, pane| { + let is_focused = focus == Some(id); + + let pin_button = button( + text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14), + ) + .on_press(WindowMessage::TogglePin(id)) + .padding(3); + + let title = row![ + pin_button, + "Pane", + text(pane.id.to_string()).style(if is_focused { + PANE_ID_COLOR_FOCUSED + } else { + PANE_ID_COLOR_UNFOCUSED + }), + ] + .spacing(5); + + let title_bar = pane_grid::TitleBar::new(title) + .controls(view_controls( + id, + total_panes, + pane.is_pinned, + pane.is_moving, + &window.title, + window_id, + &self.windows, + )) + .padding(10) + .style(if is_focused { + style::title_bar_focused + } else { + style::title_bar_active + }); + + pane_grid::Content::new(responsive(move |size| { + view_content(id, total_panes, pane.is_pinned, size) + })) + .title_bar(title_bar) .style(if is_focused { - style::title_bar_focused + style::pane_focused } else { - style::title_bar_active - }); - - pane_grid::Content::new(responsive(move |size| { - view_content(id, total_panes, pane.is_pinned, size) - })) - .title_bar(title_bar) - .style(if is_focused { - style::pane_focused - } else { - style::pane_active + style::pane_active + }) }) - }) - .width(Length::Fill) - .height(Length::Fill) - .spacing(10) - .on_click(Message::Clicked) - .on_drag(Message::Dragged) - .on_resize(10, Message::Resized); - - container(pane_grid) .width(Length::Fill) .height(Length::Fill) - .padding(10) + .spacing(10) + .on_click(WindowMessage::Clicked) + .on_drag(WindowMessage::Dragged) + .on_resize(10, WindowMessage::Resized); + + let content: Element<_> = column![window_controls, pane_grid] + .width(Length::Fill) + .height(Length::Fill) + .padding(10) + .into(); + + return content + .map(move |message| Message::Window(window_id, message)); + } + + container(text("This shouldn't be possible!").size(20)) + .center_x() + .center_y() .into() } } @@ -222,7 +346,7 @@ const PANE_ID_COLOR_FOCUSED: Color = Color::from_rgb( 0x47 as f32 / 255.0, ); -fn handle_hotkey(key_code: keyboard::KeyCode) -> Option { +fn handle_hotkey(key_code: keyboard::KeyCode) -> Option { use keyboard::KeyCode; use pane_grid::{Axis, Direction}; @@ -235,23 +359,44 @@ fn handle_hotkey(key_code: keyboard::KeyCode) -> Option { }; match key_code { - KeyCode::V => Some(Message::SplitFocused(Axis::Vertical)), - KeyCode::H => Some(Message::SplitFocused(Axis::Horizontal)), - KeyCode::W => Some(Message::CloseFocused), - _ => direction.map(Message::FocusAdjacent), + KeyCode::V => Some(WindowMessage::SplitFocused(Axis::Vertical)), + KeyCode::H => Some(WindowMessage::SplitFocused(Axis::Horizontal)), + KeyCode::W => Some(WindowMessage::CloseFocused), + _ => direction.map(WindowMessage::FocusAdjacent), + } +} + +#[derive(Debug, Clone)] +struct SelectableWindow(window::Id, String); + +impl PartialEq for SelectableWindow { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } +} + +impl Eq for SelectableWindow {} + +impl std::fmt::Display for SelectableWindow { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.1.fmt(f) } } struct Pane { id: usize, + pub axis: pane_grid::Axis, pub is_pinned: bool, + pub is_moving: bool, } impl Pane { - fn new(id: usize) -> Self { + fn new(id: usize, axis: pane_grid::Axis) -> Self { Self { id, + axis, is_pinned: false, + is_moving: false, } } } @@ -261,7 +406,7 @@ fn view_content<'a>( total_panes: usize, is_pinned: bool, size: Size, -) -> Element<'a, Message> { +) -> Element<'a, WindowMessage> { let button = |label, message| { button( text(label) @@ -277,11 +422,11 @@ fn view_content<'a>( let mut controls = column![ button( "Split horizontally", - Message::Split(pane_grid::Axis::Horizontal, pane), + WindowMessage::Split(pane_grid::Axis::Horizontal, pane), ), button( "Split vertically", - Message::Split(pane_grid::Axis::Vertical, pane), + WindowMessage::Split(pane_grid::Axis::Vertical, pane), ) ] .spacing(5) @@ -289,7 +434,7 @@ fn view_content<'a>( if total_panes > 1 && !is_pinned { controls = controls.push( - button("Close", Message::Close(pane)) + button("Close", WindowMessage::Close(pane)) .style(theme::Button::Destructive), ); } @@ -314,16 +459,48 @@ fn view_controls<'a>( pane: pane_grid::Pane, total_panes: usize, is_pinned: bool, -) -> Element<'a, Message> { - let mut button = button(text("Close").size(14)) + is_moving: bool, + window_title: &'a str, + window_id: window::Id, + windows: &HashMap, +) -> Element<'a, WindowMessage> { + let window_selector = { + let options: Vec<_> = windows + .iter() + .map(|(id, window)| SelectableWindow(*id, window.title.clone())) + .collect(); + pick_list( + options, + Some(SelectableWindow(window_id, window_title.to_string())), + move |window| WindowMessage::SelectedWindow(pane, window), + ) + }; + + let mut move_to = button(text("Move to").size(14)).padding(3); + + let mut pop_out = button(text("Pop Out").size(14)).padding(3); + + let mut close = button(text("Close").size(14)) .style(theme::Button::Destructive) .padding(3); if total_panes > 1 && !is_pinned { - button = button.on_press(Message::Close(pane)); + close = close.on_press(WindowMessage::Close(pane)); + pop_out = pop_out.on_press(WindowMessage::PopOut(pane)); + } + + if windows.len() > 1 && total_panes > 1 && !is_pinned { + move_to = move_to.on_press(WindowMessage::ToggleMoving(pane)); + } + + let mut content = row![].spacing(10); + if is_moving { + content = content.push(pop_out).push(window_selector).push(close); + } else { + content = content.push(pop_out).push(move_to).push(close); } - button.into() + content.into() } mod style { From 35331d0a41a53b8ff5c642b8274c7377ae6c6182 Mon Sep 17 00:00:00 2001 From: Richard Date: Tue, 26 Jul 2022 16:46:12 -0300 Subject: [PATCH 15/66] Allow closing the window from user code --- examples/multi_window/src/main.rs | 9 +++- native/src/window/id.rs | 2 +- winit/src/multi_window.rs | 77 +++++++++++++++++++++++-------- winit/src/multi_window/state.rs | 11 +++++ 4 files changed, 76 insertions(+), 23 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 4ad92adb5c..ca137d480a 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -50,6 +50,7 @@ enum WindowMessage { Close(pane_grid::Pane), CloseFocused, SelectedWindow(pane_grid::Pane, SelectableWindow), + CloseWindow, } impl Application for Example { @@ -128,6 +129,9 @@ impl Application for Example { let window = self.windows.get_mut(&id).unwrap(); window.focus = Some(pane); } + WindowMessage::CloseWindow => { + let _ = self.windows.remove(&id); + } WindowMessage::Resized(pane_grid::ResizeEvent { split, ratio }) => { let window = self.windows.get_mut(&id).unwrap(); window.panes.resize(&split, ratio); @@ -145,8 +149,6 @@ impl Application for Example { if let Some((pane, _)) = result { window.focus = Some(pane); } - - self.panes_created += 1; } } WindowMessage::ToggleMoving(pane) => { @@ -260,6 +262,9 @@ impl Application for Example { WindowMessage::TitleChanged, ), button(text("Apply")).style(theme::Button::Primary), + button(text("Close")) + .on_press(WindowMessage::CloseWindow) + .style(theme::Button::Destructive), ] .spacing(5) .align_items(Alignment::Center); diff --git a/native/src/window/id.rs b/native/src/window/id.rs index 0ba355af61..059cf4e739 100644 --- a/native/src/window/id.rs +++ b/native/src/window/id.rs @@ -1,7 +1,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] /// TODO(derezzedex) pub struct Id(u64); diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index dc00d7375f..3c720a6995 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -39,6 +39,8 @@ pub enum Event { // (maybe we should also allow users to listen/react to those internal messages?) NewWindow(window::Id, settings::Window), /// TODO(derezzedex) + CloseWindow(window::Id), + /// TODO(derezzedex) WindowCreated(window::Id, winit::window::Window), } @@ -549,6 +551,27 @@ async fn run_instance( let _ = window_ids.insert(window.id(), id); let _ = windows.insert(id, window); } + Event::CloseWindow(id) => { + // TODO(derezzedex): log errors + if let Some(window) = windows.get(&id) { + if window_ids.remove(&window.id()).is_none() { + println!("Failed to remove from `window_ids`!"); + } + } + if states.remove(&id).is_none() { + println!("Failed to remove from `states`!") + } + if interfaces.remove(&id).is_none() { + println!("Failed to remove from `interfaces`!"); + } + if windows.remove(&id).is_none() { + println!("Failed to remove from `windows`!") + } + + if windows.is_empty() { + break 'main; + } + } Event::NewWindow(_, _) => unreachable!(), }, event::Event::RedrawRequested(id) => { @@ -651,29 +674,43 @@ async fn run_instance( window_id, } => { // dbg!(window_id); - let window = window_ids - .get(&window_id) - .and_then(|id| windows.get(id)) - .unwrap(); - let window_state = window_ids - .get(&window_id) - .and_then(|id| states.get_mut(id)) - .unwrap(); - - if requests_exit(&window_event, window_state.state.modifiers()) - && exit_on_close_request + if let Some(window) = + window_ids.get(&window_id).and_then(|id| windows.get(id)) { - break; - } + if let Some(window_state) = window_ids + .get(&window_id) + .and_then(|id| states.get_mut(id)) + { + if requests_exit( + &window_event, + window_state.state.modifiers(), + ) && exit_on_close_request + { + break; + } - window_state.state.update(window, &window_event, &mut debug); + window_state.state.update( + window, + &window_event, + &mut debug, + ); - if let Some(event) = conversion::window_event( - &window_event, - window_state.state.scale_factor(), - window_state.state.modifiers(), - ) { - events.push((window_ids.get(&window_id).cloned(), event)); + if let Some(event) = conversion::window_event( + &window_event, + window_state.state.scale_factor(), + window_state.state.modifiers(), + ) { + events.push(( + window_ids.get(&window_id).cloned(), + event, + )); + } + } else { + // TODO(derezzedex): log error + } + } else { + // TODO(derezzedex): log error + // println!("{:?}: {:?}", window_id, window_event); } } _ => {} diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index d22de961d8..ae353e3bb4 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -189,6 +189,17 @@ where proxy: &EventLoopProxy>, ) { let new_windows = application.windows(); + + // Check for windows to close + for window_id in windows.keys() { + if !new_windows.iter().any(|(id, _)| id == window_id) { + proxy + .send_event(Event::CloseWindow(*window_id)) + .expect("Failed to send message"); + } + } + + // Check for windows to spawn for (id, settings) in new_windows { if !windows.contains_key(&id) { proxy From dc86bd03733969033df7389c3d21e78ecc6291bb Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 27 Jul 2022 15:37:48 -0300 Subject: [PATCH 16/66] Introduce `close_requested` for `multi-window` --- examples/multi_window/src/main.rs | 4 ++++ src/multi_window/application.rs | 7 +++++++ winit/src/multi_window.rs | 15 +++++++++++---- winit/src/settings.rs | 4 ++++ 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index ca137d480a..88ddf46f9a 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -250,6 +250,10 @@ impl Application for Example { .collect() } + fn close_requested(&self, window: window::Id) -> Self::Message { + Message::Window(window, WindowMessage::CloseWindow) + } + fn view(&self, window_id: window::Id) -> Element { if let Some(window) = self.windows.get(&window_id) { let focus = window.focus; diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index e849bf2bec..df45ca1eff 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -113,6 +113,9 @@ pub trait Application: Sized { false } + /// TODO(derezzedex) + fn close_requested(&self, window: window::Id) -> Self::Message; + /// Runs the [`Application`]. /// /// On native platforms, this method will take control of the current thread @@ -207,4 +210,8 @@ where fn should_exit(&self) -> bool { self.0.should_exit() } + + fn close_requested(&self, window: window::Id) -> Self::Message { + self.0.close_requested(window) + } } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 3c720a6995..6fbedc5530 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -147,6 +147,9 @@ where fn should_exit(&self) -> bool { false } + + /// TODO(derezzedex) + fn close_requested(&self, window: window::Id) -> Self::Message; } /// Runs an [`Application`] with an executor, compositor, and the provided @@ -296,7 +299,7 @@ async fn run_instance( >, init_command: Command, mut windows: HashMap, - exit_on_close_request: bool, + _exit_on_close_request: bool, ) where A: Application + 'static, E: Executor + 'static, @@ -684,9 +687,13 @@ async fn run_instance( if requests_exit( &window_event, window_state.state.modifiers(), - ) && exit_on_close_request - { - break; + ) { + if let Some(id) = + window_ids.get(&window_id).cloned() + { + let message = application.close_requested(id); + messages.push(message); + } } window_state.state.update( diff --git a/winit/src/settings.rs b/winit/src/settings.rs index 94d243a770..ea0ba361bd 100644 --- a/winit/src/settings.rs +++ b/winit/src/settings.rs @@ -46,6 +46,10 @@ pub struct Settings { /// Whether the [`Application`] should exit when the user requests the /// window to close (e.g. the user presses the close button). /// + /// NOTE: This is not used for `multi-window`, instead check [`Application::close_requested`]. + /// + /// [`close_requested`]: crate::multi_window::Application::close_requested + /// /// [`Application`]: crate::Application pub exit_on_close_request: bool, From 7f35256573db789fa6552c2cfd8aa16dde2a1a4d Mon Sep 17 00:00:00 2001 From: Richard Date: Thu, 15 Sep 2022 05:02:18 -0300 Subject: [PATCH 17/66] Split `Surface` and `Window` --- winit/src/multi_window.rs | 82 +++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 47 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 6fbedc5530..3e7fecd0f1 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -318,6 +318,7 @@ async fn run_instance( .collect(); let mut states = HashMap::new(); + let mut surfaces = HashMap::new(); let mut interfaces = ManuallyDrop::new(HashMap::new()); for (&id, window) in windows.keys().zip(windows.values()) { @@ -342,20 +343,19 @@ async fn run_instance( id, ); - let window_state: WindowState = WindowState { surface, state }; - - let _ = states.insert(id, window_state); + let _ = states.insert(id, state); + let _ = surfaces.insert(id, surface); let _ = interfaces.insert(id, user_interface); } { // TODO(derezzedex) - let window_state = states.values().next().expect("No state found"); + let state = states.values().next().expect("No state found"); run_command( &application, &mut cache, - &window_state.state, + state, &mut renderer, init_command, &mut runtime, @@ -396,7 +396,7 @@ async fn run_instance( .collect(); let cursor_position = - states.get(&id).unwrap().state.cursor_position(); + states.get(&id).unwrap().cursor_position(); let window = windows.get(&id).unwrap(); if filtered.is_empty() && messages.is_empty() { @@ -430,7 +430,7 @@ async fn run_instance( user_interface::State::Outdated, ) { - let state = &mut states.get_mut(&id).unwrap().state; + let state = &mut states.get_mut(&id).unwrap(); let pure_states: HashMap<_, _> = ManuallyDrop::into_inner(interfaces) .drain() @@ -481,7 +481,7 @@ async fn run_instance( debug.draw_started(); let new_mouse_interaction = { let user_interface = interfaces.get_mut(&id).unwrap(); - let state = &states.get(&id).unwrap().state; + let state = states.get(&id).unwrap(); user_interface.draw( &mut renderer, @@ -546,10 +546,8 @@ async fn run_instance( id, ); - let window_state: WindowState = - WindowState { surface, state }; - - let _ = states.insert(id, window_state); + let _ = states.insert(id, state); + let _ = surfaces.insert(id, surface); let _ = interfaces.insert(id, user_interface); let _ = window_ids.insert(window.id(), id); let _ = windows.insert(id, window); @@ -570,6 +568,9 @@ async fn run_instance( if windows.remove(&id).is_none() { println!("Failed to remove from `windows`!") } + if surfaces.remove(&id).is_none() { + println!("Failed to remove from `surfaces`!") + } if windows.is_empty() { break 'main; @@ -578,11 +579,15 @@ async fn run_instance( Event::NewWindow(_, _) => unreachable!(), }, event::Event::RedrawRequested(id) => { - let window_state = window_ids + let state = window_ids .get(&id) .and_then(|id| states.get_mut(id)) .unwrap(); - let physical_size = window_state.state.physical_size(); + let surface = window_ids + .get(&id) + .and_then(|id| surfaces.get_mut(id)) + .unwrap(); + let physical_size = state.physical_size(); if physical_size.width == 0 || physical_size.height == 0 { continue; @@ -590,13 +595,13 @@ async fn run_instance( debug.render_started(); - if window_state.state.viewport_changed() { + if state.viewport_changed() { let mut user_interface = window_ids .get(&id) .and_then(|id| interfaces.remove(id)) .unwrap(); - let logical_size = window_state.state.logical_size(); + let logical_size = state.logical_size(); debug.layout_started(); user_interface = @@ -605,7 +610,7 @@ async fn run_instance( debug.draw_started(); let new_mouse_interaction = { - let state = &window_state.state; + let state = &state; user_interface.draw( &mut renderer, @@ -634,7 +639,7 @@ async fn run_instance( .insert(*window_ids.get(&id).unwrap(), user_interface); compositor.configure_surface( - &mut window_state.surface, + surface, physical_size.width, physical_size.height, ); @@ -642,9 +647,9 @@ async fn run_instance( match compositor.present( &mut renderer, - &mut window_state.surface, - window_state.state.viewport(), - window_state.state.background_color(), + surface, + state.viewport(), + state.background_color(), &debug.overlay(), ) { Ok(()) => { @@ -680,14 +685,11 @@ async fn run_instance( if let Some(window) = window_ids.get(&window_id).and_then(|id| windows.get(id)) { - if let Some(window_state) = window_ids + if let Some(state) = window_ids .get(&window_id) .and_then(|id| states.get_mut(id)) { - if requests_exit( - &window_event, - window_state.state.modifiers(), - ) { + if requests_exit(&window_event, state.modifiers()) { if let Some(id) = window_ids.get(&window_id).cloned() { @@ -696,16 +698,12 @@ async fn run_instance( } } - window_state.state.update( - window, - &window_event, - &mut debug, - ); + state.update(window, &window_event, &mut debug); if let Some(event) = conversion::window_event( &window_event, - window_state.state.scale_factor(), - window_state.state.modifiers(), + state.scale_factor(), + state.modifiers(), ) { events.push(( window_ids.get(&window_id).cloned(), @@ -953,21 +951,12 @@ pub fn run_command( } } -struct WindowState -where - A: Application, - C: iced_graphics::window::Compositor, - ::Theme: StyleSheet, -{ - surface: ::Surface, - state: State, -} - -fn build_user_interfaces<'a, A, C>( +/// TODO(derezzedex) +pub fn build_user_interfaces<'a, A>( application: &'a A, renderer: &mut A::Renderer, debug: &mut Debug, - states: &HashMap>, + states: &HashMap>, mut pure_states: HashMap, ) -> HashMap< window::Id, @@ -979,13 +968,12 @@ fn build_user_interfaces<'a, A, C>( > where A: Application + 'static, - C: iced_graphics::window::Compositor + 'static, ::Theme: StyleSheet, { let mut interfaces = HashMap::new(); for (id, pure_state) in pure_states.drain() { - let state = &states.get(&id).unwrap().state; + let state = &states.get(&id).unwrap(); let user_interface = build_user_interface( application, From 974cc6b6f55178976b0ace626ba03bdd88cde5e0 Mon Sep 17 00:00:00 2001 From: Richard Date: Mon, 19 Sep 2022 16:01:50 -0300 Subject: [PATCH 18/66] Introduce `multi_window` to `iced_glutin` --- Cargo.toml | 2 +- glutin/Cargo.toml | 1 + glutin/src/lib.rs | 3 +++ glutin/src/multi_window.rs | 21 +++++++++++++++++++++ 4 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 glutin/src/multi_window.rs diff --git a/Cargo.toml b/Cargo.toml index 41f5af2fe3..36465a2910 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,7 @@ chrome-trace = [ "iced_glow?/tracing", ] # Enables experimental multi-window support -multi_window = ["iced_winit/multi_window"] +multi_window = ["iced_winit/multi_window", "iced_glutin/multi_window"] [badges] maintenance = { status = "actively-developed" } diff --git a/glutin/Cargo.toml b/glutin/Cargo.toml index 304170cd09..2960a0bd4a 100644 --- a/glutin/Cargo.toml +++ b/glutin/Cargo.toml @@ -14,6 +14,7 @@ categories = ["gui"] trace = ["iced_winit/trace"] debug = ["iced_winit/debug"] system = ["iced_winit/system"] +multi_window = ["iced_winit/multi_window"] [dependencies.log] version = "0.4" diff --git a/glutin/src/lib.rs b/glutin/src/lib.rs index 33afd66435..45d6cb5b41 100644 --- a/glutin/src/lib.rs +++ b/glutin/src/lib.rs @@ -29,5 +29,8 @@ pub use iced_winit::*; pub mod application; +#[cfg(feature = "multi_window")] +pub mod multi_window; + #[doc(no_inline)] pub use application::Application; diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs new file mode 100644 index 0000000000..46d00d81e1 --- /dev/null +++ b/glutin/src/multi_window.rs @@ -0,0 +1,21 @@ +//! Create interactive, native cross-platform applications. +use crate::{Error, Executor}; + +pub use iced_winit::multi_window::{Application, StyleSheet}; + +use iced_winit::Settings; + +/// Runs an [`Application`] with an executor, compositor, and the provided +/// settings. +pub fn run( + _settings: Settings, + _compositor_settings: C::Settings, +) -> Result<(), Error> +where + A: Application + 'static, + E: Executor + 'static, + C: iced_graphics::window::GLCompositor + 'static, + ::Theme: StyleSheet, +{ + unimplemented!("iced_glutin not implemented!") +} From 0ad53a3d5c7b5fb5785a64102ee1ad7df9a5fb2b Mon Sep 17 00:00:00 2001 From: Richard Date: Mon, 19 Sep 2022 20:59:37 -0300 Subject: [PATCH 19/66] add `window::Id` to `Event` and `Action` --- examples/events/src/main.rs | 2 +- examples/integration_opengl/src/main.rs | 2 + examples/integration_wgpu/src/main.rs | 5 +- glutin/src/application.rs | 1 + native/src/command/action.rs | 8 ++- native/src/event.rs | 2 +- native/src/window/id.rs | 3 + winit/src/application.rs | 3 +- winit/src/conversion.rs | 46 +++++++++------ winit/src/multi_window.rs | 77 ++++++++++++------------- winit/src/window.rs | 30 ++++++---- 11 files changed, 100 insertions(+), 79 deletions(-) diff --git a/examples/events/src/main.rs b/examples/events/src/main.rs index 234e14239d..e970937782 100644 --- a/examples/events/src/main.rs +++ b/examples/events/src/main.rs @@ -52,7 +52,7 @@ impl Application for Events { } } Message::EventOccurred(event) => { - if let Event::Window(window::Event::CloseRequested) = event { + if let Event::Window(_, window::Event::CloseRequested) = event { self.should_exit = true; } } diff --git a/examples/integration_opengl/src/main.rs b/examples/integration_opengl/src/main.rs index f161c8a0e0..5647019066 100644 --- a/examples/integration_opengl/src/main.rs +++ b/examples/integration_opengl/src/main.rs @@ -13,6 +13,7 @@ use iced_glow::{Backend, Renderer, Settings, Viewport}; use iced_glutin::conversion; use iced_glutin::glutin; use iced_glutin::renderer; +use iced_glutin::window; use iced_glutin::{program, Clipboard, Color, Debug, Size}; pub fn main() { @@ -107,6 +108,7 @@ pub fn main() { // Map window event to iced event if let Some(event) = iced_winit::conversion::window_event( + window::Id::MAIN, &event, windowed_context.window().scale_factor(), modifiers, diff --git a/examples/integration_wgpu/src/main.rs b/examples/integration_wgpu/src/main.rs index 70f9a48b43..219573ea01 100644 --- a/examples/integration_wgpu/src/main.rs +++ b/examples/integration_wgpu/src/main.rs @@ -6,8 +6,8 @@ use scene::Scene; use iced_wgpu::{wgpu, Backend, Renderer, Settings, Viewport}; use iced_winit::{ - conversion, futures, program, renderer, winit, Clipboard, Color, Debug, - Size, + conversion, futures, program, renderer, window, winit, Clipboard, Color, + Debug, Size, }; use winit::{ @@ -169,6 +169,7 @@ pub fn main() { // Map window event to iced event if let Some(event) = iced_winit::conversion::window_event( + window::Id::MAIN, &event, window.scale_factor(), modifiers, diff --git a/glutin/src/application.rs b/glutin/src/application.rs index 1464bb2d78..108d7ffabd 100644 --- a/glutin/src/application.rs +++ b/glutin/src/application.rs @@ -435,6 +435,7 @@ async fn run_instance( state.update(context.window(), &window_event, &mut debug); if let Some(event) = conversion::window_event( + crate::window::Id::MAIN, &window_event, state.scale_factor(), state.modifiers(), diff --git a/native/src/command/action.rs b/native/src/command/action.rs index a6954f8f75..924f95e6bf 100644 --- a/native/src/command/action.rs +++ b/native/src/command/action.rs @@ -20,7 +20,7 @@ pub enum Action { Clipboard(clipboard::Action), /// Run a window action. - Window(window::Action), + Window(window::Id, window::Action), /// Run a system action. System(system::Action), @@ -46,7 +46,7 @@ impl Action { match self { Self::Future(future) => Action::Future(Box::pin(future.map(f))), Self::Clipboard(action) => Action::Clipboard(action.map(f)), - Self::Window(window) => Action::Window(window.map(f)), + Self::Window(id, window) => Action::Window(id, window.map(f)), Self::System(system) => Action::System(system.map(f)), Self::Widget(widget) => Action::Widget(widget.map(f)), } @@ -60,7 +60,9 @@ impl fmt::Debug for Action { Self::Clipboard(action) => { write!(f, "Action::Clipboard({:?})", action) } - Self::Window(action) => write!(f, "Action::Window({:?})", action), + Self::Window(id, action) => { + write!(f, "Action::Window({:?}, {:?})", id, action) + } Self::System(action) => write!(f, "Action::System({:?})", action), Self::Widget(_action) => write!(f, "Action::Widget"), } diff --git a/native/src/event.rs b/native/src/event.rs index bcfaf891bc..eb8263994a 100644 --- a/native/src/event.rs +++ b/native/src/event.rs @@ -19,7 +19,7 @@ pub enum Event { Mouse(mouse::Event), /// A window event - Window(window::Event), + Window(window::Id, window::Event), /// A touch event Touch(touch::Event), diff --git a/native/src/window/id.rs b/native/src/window/id.rs index 059cf4e739..5060e162af 100644 --- a/native/src/window/id.rs +++ b/native/src/window/id.rs @@ -6,6 +6,9 @@ use std::hash::{Hash, Hasher}; pub struct Id(u64); impl Id { + /// TODO(derezzedex): maybe change `u64` to an enum `Type::{Single, Multi(u64)}` + pub const MAIN: Self = Id(0); + /// TODO(derezzedex) pub fn new(id: impl Hash) -> Id { let mut hasher = DefaultHasher::new(); diff --git a/winit/src/application.rs b/winit/src/application.rs index 74c738153a..4486f5d9d8 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -502,6 +502,7 @@ async fn run_instance( state.update(&window, &window_event, &mut debug); if let Some(event) = conversion::window_event( + crate::window::Id::MAIN, &window_event, state.scale_factor(), state.modifiers(), @@ -667,7 +668,7 @@ pub fn run_command( clipboard.write(contents); } }, - command::Action::Window(action) => match action { + command::Action::Window(_id, action) => match action { window::Action::Close => { *should_exit = true; } diff --git a/winit/src/conversion.rs b/winit/src/conversion.rs index 1418e3461b..6c809d19b8 100644 --- a/winit/src/conversion.rs +++ b/winit/src/conversion.rs @@ -10,6 +10,7 @@ use crate::{Event, Point, Position}; /// Converts a winit window event into an iced event. pub fn window_event( + id: window::Id, event: &winit::event::WindowEvent<'_>, scale_factor: f64, modifiers: winit::event::ModifiersState, @@ -20,21 +21,27 @@ pub fn window_event( WindowEvent::Resized(new_size) => { let logical_size = new_size.to_logical(scale_factor); - Some(Event::Window(window::Event::Resized { - width: logical_size.width, - height: logical_size.height, - })) + Some(Event::Window( + id, + window::Event::Resized { + width: logical_size.width, + height: logical_size.height, + }, + )) } WindowEvent::ScaleFactorChanged { new_inner_size, .. } => { let logical_size = new_inner_size.to_logical(scale_factor); - Some(Event::Window(window::Event::Resized { - width: logical_size.width, - height: logical_size.height, - })) + Some(Event::Window( + id, + window::Event::Resized { + width: logical_size.width, + height: logical_size.height, + }, + )) } WindowEvent::CloseRequested => { - Some(Event::Window(window::Event::CloseRequested)) + Some(Event::Window(id, window::Event::CloseRequested)) } WindowEvent::CursorMoved { position, .. } => { let position = position.to_logical::(scale_factor); @@ -112,19 +119,22 @@ pub fn window_event( WindowEvent::ModifiersChanged(new_modifiers) => Some(Event::Keyboard( keyboard::Event::ModifiersChanged(self::modifiers(*new_modifiers)), )), - WindowEvent::Focused(focused) => Some(Event::Window(if *focused { - window::Event::Focused - } else { - window::Event::Unfocused - })), + WindowEvent::Focused(focused) => Some(Event::Window( + id, + if *focused { + window::Event::Focused + } else { + window::Event::Unfocused + }, + )), WindowEvent::HoveredFile(path) => { - Some(Event::Window(window::Event::FileHovered(path.clone()))) + Some(Event::Window(id, window::Event::FileHovered(path.clone()))) } WindowEvent::DroppedFile(path) => { - Some(Event::Window(window::Event::FileDropped(path.clone()))) + Some(Event::Window(id, window::Event::FileDropped(path.clone()))) } WindowEvent::HoveredFileCancelled => { - Some(Event::Window(window::Event::FilesHoveredLeft)) + Some(Event::Window(id, window::Event::FilesHoveredLeft)) } WindowEvent::Touch(touch) => { Some(Event::Touch(touch_event(*touch, scale_factor))) @@ -133,7 +143,7 @@ pub fn window_event( let winit::dpi::LogicalPosition { x, y } = position.to_logical(scale_factor); - Some(Event::Window(window::Event::Moved { x, y })) + Some(Event::Window(id, window::Event::Moved { x, y })) } _ => None, } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 3e7fecd0f1..9f46b88d02 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -363,7 +363,6 @@ async fn run_instance( &mut proxy, &mut debug, &windows, - &window_ids, || compositor.fetch_information(), ); } @@ -456,7 +455,6 @@ async fn run_instance( &mut debug, &mut messages, &windows, - &window_ids, || compositor.fetch_information(), ); @@ -701,6 +699,7 @@ async fn run_instance( state.update(window, &window_event, &mut debug); if let Some(event) = conversion::window_event( + *window_ids.get(&window_id).unwrap(), &window_event, state.scale_factor(), state.modifiers(), @@ -787,7 +786,6 @@ pub fn update( debug: &mut Debug, messages: &mut Vec, windows: &HashMap, - window_ids: &HashMap, graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where ::Theme: StyleSheet, @@ -810,7 +808,6 @@ pub fn update( proxy, debug, windows, - window_ids, graphics_info, ); } @@ -831,7 +828,6 @@ pub fn run_command( proxy: &mut winit::event_loop::EventLoopProxy>, debug: &mut Debug, windows: &HashMap, - window_ids: &HashMap, _graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where A: Application, @@ -842,10 +838,6 @@ pub fn run_command( use iced_native::system; use iced_native::window; - // TODO(derezzedex) - let window = windows.values().next().expect("No window found"); - let id = *window_ids.get(&window.id()).unwrap(); - for action in command.actions() { match action { command::Action::Future(future) => { @@ -863,38 +855,41 @@ pub fn run_command( clipboard.write(contents); } }, - command::Action::Window(action) => match action { - window::Action::Resize { width, height } => { - window.set_inner_size(winit::dpi::LogicalSize { - width, - height, - }); - } - window::Action::Move { x, y } => { - window.set_outer_position(winit::dpi::LogicalPosition { - x, - y, - }); - } - window::Action::SetMode(mode) => { - window.set_visible(conversion::visible(mode)); - window.set_fullscreen(conversion::fullscreen( - window.primary_monitor(), - mode, - )); - } - window::Action::FetchMode(tag) => { - let mode = if window.is_visible().unwrap_or(true) { - conversion::mode(window.fullscreen()) - } else { - window::Mode::Hidden - }; - - proxy - .send_event(Event::Application(tag(mode))) - .expect("Send message to event loop"); + command::Action::Window(id, action) => { + let window = windows.get(&id).expect("No window found"); + + match action { + window::Action::Resize { width, height } => { + window.set_inner_size(winit::dpi::LogicalSize { + width, + height, + }); + } + window::Action::Move { x, y } => { + window.set_outer_position( + winit::dpi::LogicalPosition { x, y }, + ); + } + window::Action::SetMode(mode) => { + window.set_visible(conversion::visible(mode)); + window.set_fullscreen(conversion::fullscreen( + window.primary_monitor(), + mode, + )); + } + window::Action::FetchMode(tag) => { + let mode = if window.is_visible().unwrap_or(true) { + conversion::mode(window.fullscreen()) + } else { + window::Mode::Hidden + }; + + proxy + .send_event(Event::Application(tag(mode))) + .expect("Send message to event loop"); + } } - }, + } command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { #[cfg(feature = "system")] @@ -925,7 +920,7 @@ pub fn run_command( renderer, state.logical_size(), debug, - id, + window::Id::MAIN, // TODO(derezzedex): run the operation on every widget tree ); while let Some(mut operation) = current_operation.take() { diff --git a/winit/src/window.rs b/winit/src/window.rs index f2c7037a37..d9bc0d83c4 100644 --- a/winit/src/window.rs +++ b/winit/src/window.rs @@ -15,11 +15,15 @@ pub fn drag() -> Command { } /// Resizes the window to the given logical dimensions. -pub fn resize(width: u32, height: u32) -> Command { - Command::single(command::Action::Window(window::Action::Resize { - width, - height, - })) +pub fn resize( + id: window::Id, + width: u32, + height: u32, +) -> Command { + Command::single(command::Action::Window( + id, + window::Action::Resize { width, height }, + )) } /// Sets the window to maximized or back. @@ -33,13 +37,13 @@ pub fn minimize(value: bool) -> Command { } /// Moves a window to the given logical coordinates. -pub fn move_to(x: i32, y: i32) -> Command { - Command::single(command::Action::Window(window::Action::Move { x, y })) +pub fn move_to(id: window::Id, x: i32, y: i32) -> Command { + Command::single(command::Action::Window(id, window::Action::Move { x, y })) } /// Sets the [`Mode`] of the window. -pub fn set_mode(mode: Mode) -> Command { - Command::single(command::Action::Window(window::Action::SetMode(mode))) +pub fn set_mode(id: window::Id, mode: Mode) -> Command { + Command::single(command::Action::Window(id, window::Action::SetMode(mode))) } /// Sets the window to maximized or back. @@ -49,9 +53,11 @@ pub fn toggle_maximize() -> Command { /// Fetches the current [`Mode`] of the window. pub fn fetch_mode( + id: window::Id, f: impl FnOnce(Mode) -> Message + 'static, ) -> Command { - Command::single(command::Action::Window(window::Action::FetchMode( - Box::new(f), - ))) + Command::single(command::Action::Window( + id, + window::Action::FetchMode(Box::new(f)), + )) } From 064407635a0f9d79a067bad62f6f1042acaed18d Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 21 Sep 2022 19:17:25 -0300 Subject: [PATCH 20/66] implement `multi_window` for `iced_glutin` --- examples/multi_window/src/main.rs | 4 +- glutin/src/multi_window.rs | 564 ++++++++++++++++++++++++++- graphics/src/window/gl_compositor.rs | 2 +- 3 files changed, 561 insertions(+), 9 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 88ddf46f9a..0dda1804a1 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -70,9 +70,9 @@ impl Application for Example { ( Example { - windows: HashMap::from([(window::Id::new(0usize), window)]), + windows: HashMap::from([(window::Id::MAIN, window)]), panes_created: 1, - _focused: window::Id::new(0usize), + _focused: window::Id::MAIN, }, Command::none(), ) diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index 46d00d81e1..c3b9e74f62 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -1,15 +1,28 @@ //! Create interactive, native cross-platform applications. -use crate::{Error, Executor}; +use crate::mouse; +use crate::{Error, Executor, Runtime}; -pub use iced_winit::multi_window::{Application, StyleSheet}; +pub use iced_winit::multi_window::{ + self, Application, Event, State, StyleSheet, +}; -use iced_winit::Settings; +use iced_winit::conversion; +use iced_winit::futures; +use iced_winit::futures::channel::mpsc; +use iced_winit::renderer; +use iced_winit::user_interface; +use iced_winit::window; +use iced_winit::{Clipboard, Command, Debug, Proxy, Settings}; + +use glutin::window::Window; +use std::collections::HashMap; +use std::mem::ManuallyDrop; /// Runs an [`Application`] with an executor, compositor, and the provided /// settings. pub fn run( - _settings: Settings, - _compositor_settings: C::Settings, + settings: Settings, + compositor_settings: C::Settings, ) -> Result<(), Error> where A: Application + 'static, @@ -17,5 +30,544 @@ where C: iced_graphics::window::GLCompositor + 'static, ::Theme: StyleSheet, { - unimplemented!("iced_glutin not implemented!") + use futures::task; + use futures::Future; + use glutin::event_loop::EventLoopBuilder; + use glutin::platform::run_return::EventLoopExtRunReturn; + use glutin::ContextBuilder; + + let mut debug = Debug::new(); + debug.startup_started(); + + let mut event_loop = EventLoopBuilder::with_user_event().build(); + let proxy = event_loop.create_proxy(); + + let runtime = { + let executor = E::new().map_err(Error::ExecutorCreationFailed)?; + let proxy = Proxy::new(event_loop.create_proxy()); + + Runtime::new(executor, proxy) + }; + + let (application, init_command) = { + let flags = settings.flags; + + runtime.enter(|| A::new(flags)) + }; + + let context = { + let builder = settings.window.into_builder( + &application.title(), + event_loop.primary_monitor(), + settings.id, + ); + + log::info!("Window builder: {:#?}", builder); + + let opengl_builder = ContextBuilder::new() + .with_vsync(true) + .with_multisampling(C::sample_count(&compositor_settings) as u16); + + let opengles_builder = opengl_builder.clone().with_gl( + glutin::GlRequest::Specific(glutin::Api::OpenGlEs, (2, 0)), + ); + + let (first_builder, second_builder) = if settings.try_opengles_first { + (opengles_builder, opengl_builder) + } else { + (opengl_builder, opengles_builder) + }; + + log::info!("Trying first builder: {:#?}", first_builder); + + let context = first_builder + .build_windowed(builder.clone(), &event_loop) + .or_else(|_| { + log::info!("Trying second builder: {:#?}", second_builder); + second_builder.build_windowed(builder, &event_loop) + }) + .map_err(|error| { + use glutin::CreationError; + use iced_graphics::Error as ContextError; + + match error { + CreationError::Window(error) => { + Error::WindowCreationFailed(error) + } + CreationError::OpenGlVersionNotSupported => { + Error::GraphicsCreationFailed( + ContextError::VersionNotSupported, + ) + } + CreationError::NoAvailablePixelFormat => { + Error::GraphicsCreationFailed( + ContextError::NoAvailablePixelFormat, + ) + } + error => Error::GraphicsCreationFailed( + ContextError::BackendError(error.to_string()), + ), + } + })?; + + #[allow(unsafe_code)] + unsafe { + context.make_current().expect("Make OpenGL context current") + } + }; + + #[allow(unsafe_code)] + let (compositor, renderer) = unsafe { + C::new(compositor_settings, |address| { + context.get_proc_address(address) + })? + }; + + let (mut sender, receiver) = mpsc::unbounded(); + + let mut instance = Box::pin(run_instance::( + application, + compositor, + renderer, + runtime, + proxy, + debug, + receiver, + context, + init_command, + settings.exit_on_close_request, + )); + + let mut context = task::Context::from_waker(task::noop_waker_ref()); + + let _ = event_loop.run_return(move |event, event_loop, control_flow| { + use glutin::event_loop::ControlFlow; + + if let ControlFlow::ExitWithCode(_) = control_flow { + return; + } + + let event = match event { + glutin::event::Event::WindowEvent { + event: + glutin::event::WindowEvent::ScaleFactorChanged { + new_inner_size, + .. + }, + window_id, + } => Some(glutin::event::Event::WindowEvent { + event: glutin::event::WindowEvent::Resized(*new_inner_size), + window_id, + }), + glutin::event::Event::UserEvent(Event::NewWindow(id, settings)) => { + // TODO(derezzedex) + let window = settings + .into_builder( + "fix window title", + event_loop.primary_monitor(), + None, + ) + .build(event_loop) + .expect("Failed to build window"); + + Some(glutin::event::Event::UserEvent(Event::WindowCreated( + id, window, + ))) + } + _ => 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, + }; + } + }); + + Ok(()) +} + +async fn run_instance( + mut application: A, + mut compositor: C, + mut renderer: A::Renderer, + mut runtime: Runtime>, Event>, + mut proxy: glutin::event_loop::EventLoopProxy>, + mut debug: Debug, + mut receiver: mpsc::UnboundedReceiver< + glutin::event::Event<'_, Event>, + >, + context: glutin::ContextWrapper, + init_command: Command, + _exit_on_close_request: bool, +) where + A: Application + 'static, + E: Executor + 'static, + C: iced_graphics::window::GLCompositor + 'static, + ::Theme: StyleSheet, +{ + use glutin::event; + use iced_winit::futures::stream::StreamExt; + + let mut clipboard = Clipboard::connect(context.window()); + let mut cache = user_interface::Cache::default(); + let state = State::new(&application, context.window()); + let user_interface = multi_window::build_user_interface( + &application, + user_interface::Cache::default(), + &mut renderer, + state.logical_size(), + &mut debug, + window::Id::MAIN, + ); + + #[allow(unsafe_code)] + let (mut context, window) = unsafe { context.split() }; + + let mut window_ids = HashMap::from([(window.id(), window::Id::MAIN)]); + let mut windows = HashMap::from([(window::Id::MAIN, window)]); + let mut states = HashMap::from([(window::Id::MAIN, state)]); + let mut interfaces = + ManuallyDrop::new(HashMap::from([(window::Id::MAIN, user_interface)])); + + { + let state = states.get(&window::Id::MAIN).unwrap(); + + multi_window::run_command( + &application, + &mut cache, + state, + &mut renderer, + init_command, + &mut runtime, + &mut clipboard, + &mut proxy, + &mut debug, + &windows, + || compositor.fetch_information(), + ); + } + runtime.track(application.subscription().map(Event::Application)); + + let mut mouse_interaction = mouse::Interaction::default(); + let mut events = Vec::new(); + let mut messages = Vec::new(); + + debug.startup_finished(); + + 'main: while let Some(event) = receiver.next().await { + match event { + event::Event::MainEventsCleared => { + for id in windows.keys().copied() { + let (filtered, remaining): (Vec<_>, Vec<_>) = + events.iter().cloned().partition( + |(window_id, _event): &( + Option, + iced_native::event::Event, + )| { + *window_id == Some(id) || *window_id == None + }, + ); + + events.retain(|el| remaining.contains(el)); + let filtered: Vec<_> = filtered + .into_iter() + .map(|(_id, event)| event) + .collect(); + + let cursor_position = + states.get(&id).unwrap().cursor_position(); + let window = windows.get(&id).unwrap(); + + if filtered.is_empty() && messages.is_empty() { + continue; + } + + debug.event_processing_started(); + + let (interface_state, statuses) = { + let user_interface = interfaces.get_mut(&id).unwrap(); + user_interface.update( + &filtered, + cursor_position, + &mut renderer, + &mut clipboard, + &mut messages, + ) + }; + + debug.event_processing_finished(); + + for event in filtered.into_iter().zip(statuses.into_iter()) + { + runtime.broadcast(event); + } + + if !messages.is_empty() + || matches!( + interface_state, + user_interface::State::Outdated + ) + { + let state = &mut states.get_mut(&id).unwrap(); + let pure_states: HashMap<_, _> = + ManuallyDrop::into_inner(interfaces) + .drain() + .map(|(id, interface)| { + (id, interface.into_cache()) + }) + .collect(); + + // Update application + multi_window::update( + &mut application, + &mut cache, + state, + &mut renderer, + &mut runtime, + &mut clipboard, + &mut proxy, + &mut debug, + &mut messages, + &windows, + || compositor.fetch_information(), + ); + + // Update window + state.synchronize(&application, &windows, &proxy); + + let should_exit = application.should_exit(); + + interfaces = ManuallyDrop::new( + multi_window::build_user_interfaces( + &application, + &mut renderer, + &mut debug, + &states, + pure_states, + ), + ); + + if should_exit { + break 'main; + } + } + + debug.draw_started(); + let new_mouse_interaction = { + let user_interface = interfaces.get_mut(&id).unwrap(); + let state = states.get(&id).unwrap(); + + user_interface.draw( + &mut renderer, + state.theme(), + &renderer::Style { + text_color: state.text_color(), + }, + state.cursor_position(), + ) + }; + debug.draw_finished(); + + if new_mouse_interaction != mouse_interaction { + window.set_cursor_icon(conversion::mouse_interaction( + new_mouse_interaction, + )); + + mouse_interaction = new_mouse_interaction; + } + + window.request_redraw(); + } + } + event::Event::PlatformSpecific(event::PlatformSpecific::MacOS( + event::MacOS::ReceivedUrl(url), + )) => { + use iced_native::event; + events.push(( + None, + iced_native::Event::PlatformSpecific( + event::PlatformSpecific::MacOS( + event::MacOS::ReceivedUrl(url), + ), + ), + )); + } + event::Event::UserEvent(event) => match event { + Event::Application(message) => messages.push(message), + Event::WindowCreated(id, window) => { + let state = State::new(&application, &window); + let user_interface = multi_window::build_user_interface( + &application, + user_interface::Cache::default(), + &mut renderer, + state.logical_size(), + &mut debug, + id, + ); + + let _ = states.insert(id, state); + let _ = interfaces.insert(id, user_interface); + let _ = window_ids.insert(window.id(), id); + let _ = windows.insert(id, window); + } + Event::CloseWindow(id) => { + // TODO(derezzedex): log errors + if let Some(window) = windows.get(&id) { + if window_ids.remove(&window.id()).is_none() { + println!("Failed to remove from `window_ids`!"); + } + } + if states.remove(&id).is_none() { + println!("Failed to remove from `states`!") + } + if interfaces.remove(&id).is_none() { + println!("Failed to remove from `interfaces`!"); + } + if windows.remove(&id).is_none() { + println!("Failed to remove from `windows`!") + } + + if windows.is_empty() { + break 'main; + } + } + Event::NewWindow(_, _) => unreachable!(), + }, + event::Event::RedrawRequested(id) => { + let state = window_ids + .get(&id) + .and_then(|id| states.get_mut(id)) + .unwrap(); + + debug.render_started(); + + #[allow(unsafe_code)] + unsafe { + if !context.is_current() { + context = context + .make_current() + .expect("Make OpenGL context current"); + } + } + + if state.viewport_changed() { + let physical_size = state.physical_size(); + let logical_size = state.logical_size(); + + let mut user_interface = window_ids + .get(&id) + .and_then(|id| interfaces.remove(id)) + .unwrap(); + + debug.layout_started(); + user_interface = + user_interface.relayout(logical_size, &mut renderer); + debug.layout_finished(); + + debug.draw_started(); + let new_mouse_interaction = user_interface.draw( + &mut renderer, + state.theme(), + &renderer::Style { + text_color: state.text_color(), + }, + state.cursor_position(), + ); + debug.draw_finished(); + + if new_mouse_interaction != mouse_interaction { + let window = window_ids + .get(&id) + .and_then(|id| windows.get_mut(id)) + .unwrap(); + + window.set_cursor_icon(conversion::mouse_interaction( + new_mouse_interaction, + )); + + mouse_interaction = new_mouse_interaction; + } + + context.resize(glutin::dpi::PhysicalSize::new( + physical_size.width, + physical_size.height, + )); + + compositor.resize_viewport(physical_size); + + let _ = interfaces + .insert(*window_ids.get(&id).unwrap(), user_interface); + } + + compositor.present( + &mut renderer, + state.viewport(), + state.background_color(), + &debug.overlay(), + ); + + context.swap_buffers().expect("Swap buffers"); + + debug.render_finished(); + + // TODO: Handle animations! + // Maybe we can use `ControlFlow::WaitUntil` for this. + } + event::Event::WindowEvent { + event: window_event, + window_id, + } => { + // dbg!(window_id); + if let Some(window) = + window_ids.get(&window_id).and_then(|id| windows.get(id)) + { + if let Some(state) = window_ids + .get(&window_id) + .and_then(|id| states.get_mut(id)) + { + if multi_window::requests_exit( + &window_event, + state.modifiers(), + ) { + if let Some(id) = + window_ids.get(&window_id).cloned() + { + let message = application.close_requested(id); + messages.push(message); + } + } + + state.update(window, &window_event, &mut debug); + + if let Some(event) = conversion::window_event( + *window_ids.get(&window_id).unwrap(), + &window_event, + state.scale_factor(), + state.modifiers(), + ) { + events.push(( + window_ids.get(&window_id).cloned(), + event, + )); + } + } else { + // TODO(derezzedex): log error + } + } else { + // TODO(derezzedex): log error + // println!("{:?}: {:?}", window_id, window_event); + } + } + _ => {} + } + } + + // Manually drop the user interface + // drop(ManuallyDrop::into_inner(user_interface)); } diff --git a/graphics/src/window/gl_compositor.rs b/graphics/src/window/gl_compositor.rs index a45a7ca114..e6ae2364f9 100644 --- a/graphics/src/window/gl_compositor.rs +++ b/graphics/src/window/gl_compositor.rs @@ -30,7 +30,7 @@ pub trait GLCompositor: Sized { /// The settings of the [`GLCompositor`]. /// /// It's up to you to decide the configuration supported by your renderer! - type Settings: Default; + type Settings: Default + Clone; /// Creates a new [`GLCompositor`] and [`Renderer`] with the given /// [`Settings`] and an OpenGL address loader function. From ce43514eaca0e892ad2f646a63fc29af2150d79c Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 21 Sep 2022 19:37:28 -0300 Subject: [PATCH 21/66] copy `multi_window::Event` from `iced_winit` --- glutin/src/multi_window.rs | 264 +++++++++++++++++++++++++++++-- glutin/src/multi_window/state.rs | 241 ++++++++++++++++++++++++++++ 2 files changed, 491 insertions(+), 14 deletions(-) create mode 100644 glutin/src/multi_window/state.rs diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index c3b9e74f62..4949219fa2 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -1,15 +1,18 @@ //! Create interactive, native cross-platform applications. +mod state; + +pub use state::State; + use crate::mouse; use crate::{Error, Executor, Runtime}; -pub use iced_winit::multi_window::{ - self, Application, Event, State, StyleSheet, -}; +pub use iced_winit::multi_window::{self, Application, StyleSheet}; use iced_winit::conversion; use iced_winit::futures; use iced_winit::futures::channel::mpsc; use iced_winit::renderer; +use iced_winit::settings; use iced_winit::user_interface; use iced_winit::window; use iced_winit::{Clipboard, Command, Debug, Proxy, Settings}; @@ -238,7 +241,7 @@ async fn run_instance( { let state = states.get(&window::Id::MAIN).unwrap(); - multi_window::run_command( + run_command( &application, &mut cache, state, @@ -324,7 +327,7 @@ async fn run_instance( .collect(); // Update application - multi_window::update( + update( &mut application, &mut cache, state, @@ -343,15 +346,13 @@ async fn run_instance( let should_exit = application.should_exit(); - interfaces = ManuallyDrop::new( - multi_window::build_user_interfaces( - &application, - &mut renderer, - &mut debug, - &states, - pure_states, - ), - ); + interfaces = ManuallyDrop::new(build_user_interfaces( + &application, + &mut renderer, + &mut debug, + &states, + pure_states, + )); if should_exit { break 'main; @@ -571,3 +572,238 @@ async fn run_instance( // Manually drop the user interface // drop(ManuallyDrop::into_inner(user_interface)); } + +/// TODO(derezzedex): +// This is the an wrapper around the `Application::Message` associate type +// to allows the `shell` to create internal messages, while still having +// the current user specified custom messages. +#[derive(Debug)] +pub enum Event { + /// An [`Application`] generated message + Application(Message), + + /// TODO(derezzedex) + // Create a wrapper variant of `window::Event` type instead + // (maybe we should also allow users to listen/react to those internal messages?) + NewWindow(window::Id, settings::Window), + /// TODO(derezzedex) + CloseWindow(window::Id), + /// TODO(derezzedex) + WindowCreated(window::Id, glutin::window::Window), +} + +/// Updates an [`Application`] by feeding it the provided messages, spawning any +/// resulting [`Command`], and tracking its [`Subscription`]. +pub fn update( + application: &mut A, + cache: &mut user_interface::Cache, + state: &State, + renderer: &mut A::Renderer, + runtime: &mut Runtime>, Event>, + clipboard: &mut Clipboard, + proxy: &mut glutin::event_loop::EventLoopProxy>, + debug: &mut Debug, + messages: &mut Vec, + windows: &HashMap, + graphics_info: impl FnOnce() -> iced_graphics::compositor::Information + Copy, +) where + ::Theme: StyleSheet, +{ + for message in messages.drain(..) { + debug.log_message(&message); + + debug.update_started(); + let command = runtime.enter(|| application.update(message)); + debug.update_finished(); + + run_command( + application, + cache, + state, + renderer, + command, + runtime, + clipboard, + proxy, + debug, + windows, + graphics_info, + ); + } + + let subscription = application.subscription().map(Event::Application); + runtime.track(subscription); +} + +/// Runs the actions of a [`Command`]. +pub fn run_command( + application: &A, + cache: &mut user_interface::Cache, + state: &State, + renderer: &mut A::Renderer, + command: Command, + runtime: &mut Runtime>, Event>, + clipboard: &mut Clipboard, + proxy: &mut glutin::event_loop::EventLoopProxy>, + debug: &mut Debug, + windows: &HashMap, + _graphics_info: impl FnOnce() -> iced_graphics::compositor::Information + Copy, +) where + A: Application, + E: Executor, + ::Theme: StyleSheet, +{ + use iced_native::command; + use iced_native::system; + use iced_native::window; + use iced_winit::clipboard; + use iced_winit::futures::FutureExt; + + for action in command.actions() { + match action { + command::Action::Future(future) => { + runtime.spawn(Box::pin(future.map(Event::Application))); + } + command::Action::Clipboard(action) => match action { + clipboard::Action::Read(tag) => { + let message = tag(clipboard.read()); + + proxy + .send_event(Event::Application(message)) + .expect("Send message to event loop"); + } + clipboard::Action::Write(contents) => { + clipboard.write(contents); + } + }, + command::Action::Window(id, action) => { + let window = windows.get(&id).expect("No window found"); + + match action { + window::Action::Resize { width, height } => { + window.set_inner_size(glutin::dpi::LogicalSize { + width, + height, + }); + } + window::Action::Move { x, y } => { + window.set_outer_position( + glutin::dpi::LogicalPosition { x, y }, + ); + } + window::Action::SetMode(mode) => { + window.set_visible(conversion::visible(mode)); + window.set_fullscreen(conversion::fullscreen( + window.primary_monitor(), + mode, + )); + } + window::Action::FetchMode(tag) => { + let mode = if window.is_visible().unwrap_or(true) { + conversion::mode(window.fullscreen()) + } else { + window::Mode::Hidden + }; + + proxy + .send_event(Event::Application(tag(mode))) + .expect("Send message to event loop"); + } + } + } + command::Action::System(action) => match action { + system::Action::QueryInformation(_tag) => { + #[cfg(feature = "iced_winit/system")] + { + let graphics_info = _graphics_info(); + let proxy = proxy.clone(); + + let _ = std::thread::spawn(move || { + let information = + crate::system::information(graphics_info); + + let message = _tag(information); + + proxy + .send_event(Event::Application(message)) + .expect("Send message to event loop") + }); + } + } + }, + command::Action::Widget(action) => { + use crate::widget::operation; + + let mut current_cache = std::mem::take(cache); + let mut current_operation = Some(action.into_operation()); + + let mut user_interface = multi_window::build_user_interface( + application, + current_cache, + renderer, + state.logical_size(), + debug, + window::Id::MAIN, // TODO(derezzedex): run the operation on every widget tree + ); + + while let Some(mut operation) = current_operation.take() { + user_interface.operate(renderer, operation.as_mut()); + + match operation.finish() { + operation::Outcome::None => {} + operation::Outcome::Some(message) => { + proxy + .send_event(Event::Application(message)) + .expect("Send message to event loop"); + } + operation::Outcome::Chain(next) => { + current_operation = Some(next); + } + } + } + + current_cache = user_interface.into_cache(); + *cache = current_cache; + } + } + } +} + +/// TODO(derezzedex) +pub fn build_user_interfaces<'a, A>( + application: &'a A, + renderer: &mut A::Renderer, + debug: &mut Debug, + states: &HashMap>, + mut pure_states: HashMap, +) -> HashMap< + window::Id, + iced_winit::UserInterface< + 'a, + ::Message, + ::Renderer, + >, +> +where + A: Application + 'static, + ::Theme: StyleSheet, +{ + let mut interfaces = HashMap::new(); + + for (id, pure_state) in pure_states.drain() { + let state = &states.get(&id).unwrap(); + + let user_interface = multi_window::build_user_interface( + application, + pure_state, + renderer, + state.logical_size(), + debug, + id, + ); + + let _ = interfaces.insert(id, user_interface); + } + + interfaces +} diff --git a/glutin/src/multi_window/state.rs b/glutin/src/multi_window/state.rs new file mode 100644 index 0000000000..163f46bd38 --- /dev/null +++ b/glutin/src/multi_window/state.rs @@ -0,0 +1,241 @@ +use crate::application::{self, StyleSheet as _}; +use crate::conversion; +use crate::multi_window::{Application, Event}; +use crate::window; +use crate::{Color, Debug, Point, Size, Viewport}; + +use glutin::event::{Touch, WindowEvent}; +use glutin::event_loop::EventLoopProxy; +use glutin::window::Window; +use std::collections::HashMap; +use std::marker::PhantomData; + +/// The state of a windowed [`Application`]. +#[allow(missing_debug_implementations)] +pub struct State +where + ::Theme: application::StyleSheet, +{ + title: String, + scale_factor: f64, + viewport: Viewport, + viewport_changed: bool, + cursor_position: glutin::dpi::PhysicalPosition, + modifiers: glutin::event::ModifiersState, + theme: ::Theme, + appearance: iced_winit::application::Appearance, + application: PhantomData, +} + +impl State +where + ::Theme: application::StyleSheet, +{ + /// Creates a new [`State`] for the provided [`Application`] and window. + pub fn new(application: &A, window: &Window) -> Self { + let title = application.title(); + let scale_factor = application.scale_factor(); + let theme = application.theme(); + let appearance = theme.appearance(application.style()); + + let viewport = { + let physical_size = window.inner_size(); + + Viewport::with_physical_size( + Size::new(physical_size.width, physical_size.height), + window.scale_factor() * scale_factor, + ) + }; + + Self { + title, + scale_factor, + viewport, + viewport_changed: false, + // TODO: Encode cursor availability in the type-system + cursor_position: glutin::dpi::PhysicalPosition::new(-1.0, -1.0), + modifiers: glutin::event::ModifiersState::default(), + theme, + appearance, + application: PhantomData, + } + } + + /// Returns the current [`Viewport`] of the [`State`]. + pub fn viewport(&self) -> &Viewport { + &self.viewport + } + + /// TODO(derezzedex) + pub fn viewport_changed(&self) -> bool { + self.viewport_changed + } + + /// Returns the physical [`Size`] of the [`Viewport`] of the [`State`]. + pub fn physical_size(&self) -> Size { + self.viewport.physical_size() + } + + /// Returns the logical [`Size`] of the [`Viewport`] of the [`State`]. + pub fn logical_size(&self) -> Size { + self.viewport.logical_size() + } + + /// Returns the current scale factor of the [`Viewport`] of the [`State`]. + pub fn scale_factor(&self) -> f64 { + self.viewport.scale_factor() + } + + /// Returns the current cursor position of the [`State`]. + pub fn cursor_position(&self) -> Point { + conversion::cursor_position( + self.cursor_position, + self.viewport.scale_factor(), + ) + } + + /// Returns the current keyboard modifiers of the [`State`]. + pub fn modifiers(&self) -> glutin::event::ModifiersState { + self.modifiers + } + + /// Returns the current theme of the [`State`]. + pub fn theme(&self) -> &::Theme { + &self.theme + } + + /// Returns the current background [`Color`] of the [`State`]. + pub fn background_color(&self) -> Color { + self.appearance.background_color + } + + /// Returns the current text [`Color`] of the [`State`]. + pub fn text_color(&self) -> Color { + self.appearance.text_color + } + + /// Processes the provided window event and updates the [`State`] + /// accordingly. + pub fn update( + &mut self, + window: &Window, + event: &WindowEvent<'_>, + _debug: &mut Debug, + ) { + match event { + WindowEvent::Resized(new_size) => { + let size = Size::new(new_size.width, new_size.height); + + self.viewport = Viewport::with_physical_size( + size, + window.scale_factor() * self.scale_factor, + ); + + self.viewport_changed = true; + } + WindowEvent::ScaleFactorChanged { + scale_factor: new_scale_factor, + new_inner_size, + } => { + let size = + Size::new(new_inner_size.width, new_inner_size.height); + + self.viewport = Viewport::with_physical_size( + size, + new_scale_factor * self.scale_factor, + ); + + self.viewport_changed = true; + } + WindowEvent::CursorMoved { position, .. } + | WindowEvent::Touch(Touch { + location: position, .. + }) => { + self.cursor_position = *position; + } + WindowEvent::CursorLeft { .. } => { + // TODO: Encode cursor availability in the type-system + self.cursor_position = + glutin::dpi::PhysicalPosition::new(-1.0, -1.0); + } + WindowEvent::ModifiersChanged(new_modifiers) => { + self.modifiers = *new_modifiers; + } + #[cfg(feature = "debug")] + WindowEvent::KeyboardInput { + input: + glutin::event::KeyboardInput { + virtual_keycode: + Some(glutin::event::VirtualKeyCode::F12), + state: glutin::event::ElementState::Pressed, + .. + }, + .. + } => _debug.toggle(), + _ => {} + } + } + + /// Synchronizes the [`State`] with its [`Application`] and its respective + /// window. + /// + /// Normally an [`Application`] should be synchronized with its [`State`] + /// and window after calling [`Application::update`]. + /// + /// [`Application::update`]: crate::Program::update + pub fn synchronize( + &mut self, + application: &A, + windows: &HashMap, + proxy: &EventLoopProxy>, + ) { + let new_windows = application.windows(); + + // Check for windows to close + for window_id in windows.keys() { + if !new_windows.iter().any(|(id, _)| id == window_id) { + proxy + .send_event(Event::CloseWindow(*window_id)) + .expect("Failed to send message"); + } + } + + // Check for windows to spawn + for (id, settings) in new_windows { + if !windows.contains_key(&id) { + proxy + .send_event(Event::NewWindow(id, settings)) + .expect("Failed to send message"); + } + } + + let window = windows.values().next().expect("No window found"); + + // Update window title + let new_title = application.title(); + + if self.title != new_title { + window.set_title(&new_title); + + self.title = new_title; + } + + // Update scale factor + let new_scale_factor = application.scale_factor(); + + if self.scale_factor != new_scale_factor { + let size = window.inner_size(); + + self.viewport = Viewport::with_physical_size( + Size::new(size.width, size.height), + window.scale_factor() * new_scale_factor, + ); + + self.scale_factor = new_scale_factor; + } + + // Update theme and appearance + self.theme = application.theme(); + self.appearance = self.theme.appearance(application.style()); + } +} From a386788b67bf4e008916e79a8c7dd7289a3ab3cd Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 28 Sep 2022 19:10:47 -0300 Subject: [PATCH 22/66] use `glutin/multi_window` branch --- examples/integration_opengl/src/main.rs | 4 +-- glutin/Cargo.toml | 4 +-- glutin/src/application.rs | 6 ++-- glutin/src/multi_window.rs | 38 ++++++++++++++----------- 4 files changed, 29 insertions(+), 23 deletions(-) diff --git a/examples/integration_opengl/src/main.rs b/examples/integration_opengl/src/main.rs index 5647019066..a9e9c7325d 100644 --- a/examples/integration_opengl/src/main.rs +++ b/examples/integration_opengl/src/main.rs @@ -31,7 +31,7 @@ pub fn main() { .unwrap(); unsafe { - let windowed_context = windowed_context.make_current().unwrap(); + let windowed_context = windowed_context.make_current(todo!("derezzedex")).unwrap(); let gl = glow::Context::from_loader_function(|s| { windowed_context.get_proc_address(s) as *const _ @@ -181,7 +181,7 @@ pub fn main() { ), ); - windowed_context.swap_buffers().unwrap(); + windowed_context.swap_buffers(todo!("derezzedex")).unwrap(); } _ => (), } diff --git a/glutin/Cargo.toml b/glutin/Cargo.toml index 2960a0bd4a..75a38d2288 100644 --- a/glutin/Cargo.toml +++ b/glutin/Cargo.toml @@ -21,8 +21,8 @@ version = "0.4" [dependencies.glutin] version = "0.29" -git = "https://github.com/iced-rs/glutin" -rev = "da8d291486b4c9bec12487a46c119c4b1d386abf" +git = "https://github.com/derezzedex/glutin" +rev = "e72ea919f95106cfdfdce3e7dcfdbf71a432840a" [dependencies.iced_native] version = "0.7" diff --git a/glutin/src/application.rs b/glutin/src/application.rs index 108d7ffabd..7ff6216eaf 100644 --- a/glutin/src/application.rs +++ b/glutin/src/application.rs @@ -120,7 +120,7 @@ where #[allow(unsafe_code)] unsafe { - context.make_current().expect("Make OpenGL context current") + context.make_current(todo!()).expect("Make OpenGL context current") } }; @@ -359,7 +359,7 @@ async fn run_instance( unsafe { if !context.is_current() { context = context - .make_current() + .make_current(todo!()) .expect("Make OpenGL context current"); } } @@ -415,7 +415,7 @@ async fn run_instance( &debug.overlay(), ); - context.swap_buffers().expect("Swap buffers"); + context.swap_buffers(todo!()).expect("Swap buffers"); debug.render_finished(); diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index 4949219fa2..ce34aa31fb 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -58,7 +58,7 @@ where runtime.enter(|| A::new(flags)) }; - let context = { + let (context, window) = { let builder = settings.window.into_builder( &application.title(), event_loop.primary_monitor(), @@ -115,7 +115,14 @@ where #[allow(unsafe_code)] unsafe { - context.make_current().expect("Make OpenGL context current") + let (context, window) = context.split(); + + ( + context + .make_current(&window) + .expect("Make OpenGL context current"), + window, + ) } }; @@ -137,6 +144,7 @@ where debug, receiver, context, + window, init_command, settings.exit_on_close_request, )); @@ -205,7 +213,8 @@ async fn run_instance( mut receiver: mpsc::UnboundedReceiver< glutin::event::Event<'_, Event>, >, - context: glutin::ContextWrapper, + mut context: glutin::RawContext, + window: Window, init_command: Command, _exit_on_close_request: bool, ) where @@ -217,9 +226,9 @@ async fn run_instance( use glutin::event; use iced_winit::futures::stream::StreamExt; - let mut clipboard = Clipboard::connect(context.window()); + let mut clipboard = Clipboard::connect(&window); let mut cache = user_interface::Cache::default(); - let state = State::new(&application, context.window()); + let state = State::new(&application, &window); let user_interface = multi_window::build_user_interface( &application, user_interface::Cache::default(), @@ -229,9 +238,7 @@ async fn run_instance( window::Id::MAIN, ); - #[allow(unsafe_code)] - let (mut context, window) = unsafe { context.split() }; - + let mut current_context_window = window.id(); let mut window_ids = HashMap::from([(window.id(), window::Id::MAIN)]); let mut windows = HashMap::from([(window::Id::MAIN, window)]); let mut states = HashMap::from([(window::Id::MAIN, state)]); @@ -445,15 +452,19 @@ async fn run_instance( .get(&id) .and_then(|id| states.get_mut(id)) .unwrap(); + let window = + window_ids.get(&id).and_then(|id| windows.get(id)).unwrap(); debug.render_started(); #[allow(unsafe_code)] unsafe { - if !context.is_current() { + if current_context_window != id { context = context - .make_current() + .make_current(window) .expect("Make OpenGL context current"); + + current_context_window = id; } } @@ -483,11 +494,6 @@ async fn run_instance( debug.draw_finished(); if new_mouse_interaction != mouse_interaction { - let window = window_ids - .get(&id) - .and_then(|id| windows.get_mut(id)) - .unwrap(); - window.set_cursor_icon(conversion::mouse_interaction( new_mouse_interaction, )); @@ -513,7 +519,7 @@ async fn run_instance( &debug.overlay(), ); - context.swap_buffers().expect("Swap buffers"); + context.swap_buffers(window).expect("Swap buffers"); debug.render_finished(); From 1bc0c480f9747826b244c30e92d8c4a29b576e4a Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 19 Oct 2022 22:56:00 -0300 Subject: [PATCH 23/66] move window settings to `iced_native` --- examples/integration_opengl/src/main.rs | 3 +- glutin/src/application.rs | 4 ++- native/src/window.rs | 4 +++ native/src/window/icon.rs | 12 ++++++++ {winit/src => native/src/window}/position.rs | 0 {src => native/src}/window/settings.rs | 18 ----------- src/window.rs | 11 ++----- src/window/position.rs | 32 -------------------- {src/window => winit/src}/icon.rs | 21 ++++++++----- winit/src/lib.rs | 5 +-- winit/src/settings.rs | 21 +++++++++++++ 11 files changed, 62 insertions(+), 69 deletions(-) create mode 100644 native/src/window/icon.rs rename {winit/src => native/src/window}/position.rs (100%) rename {src => native/src}/window/settings.rs (67%) delete mode 100644 src/window/position.rs rename {src/window => winit/src}/icon.rs (90%) diff --git a/examples/integration_opengl/src/main.rs b/examples/integration_opengl/src/main.rs index a9e9c7325d..fdbd736907 100644 --- a/examples/integration_opengl/src/main.rs +++ b/examples/integration_opengl/src/main.rs @@ -31,7 +31,8 @@ pub fn main() { .unwrap(); unsafe { - let windowed_context = windowed_context.make_current(todo!("derezzedex")).unwrap(); + let windowed_context = + windowed_context.make_current(todo!("derezzedex")).unwrap(); let gl = glow::Context::from_loader_function(|s| { windowed_context.get_proc_address(s) as *const _ diff --git a/glutin/src/application.rs b/glutin/src/application.rs index 7ff6216eaf..cbb2389149 100644 --- a/glutin/src/application.rs +++ b/glutin/src/application.rs @@ -120,7 +120,9 @@ where #[allow(unsafe_code)] unsafe { - context.make_current(todo!()).expect("Make OpenGL context current") + context + .make_current(todo!()) + .expect("Make OpenGL context current") } }; diff --git a/native/src/window.rs b/native/src/window.rs index dc9e2d6612..1c03fcdff0 100644 --- a/native/src/window.rs +++ b/native/src/window.rs @@ -1,12 +1,16 @@ //! Build window-based GUI applications. mod action; mod event; +mod icon; mod id; mod mode; mod user_attention; pub use action::Action; pub use event::Event; +pub use icon::Icon; pub use id::Id; pub use mode::Mode; pub use user_attention::UserAttention; +pub use position::Position; +pub use settings::Settings; diff --git a/native/src/window/icon.rs b/native/src/window/icon.rs new file mode 100644 index 0000000000..e89baf03eb --- /dev/null +++ b/native/src/window/icon.rs @@ -0,0 +1,12 @@ +//! Attach an icon to the window of your application. + +/// The icon of a window. +#[derive(Debug, Clone)] +pub struct Icon { + /// TODO(derezzedex) + pub rgba: Vec, + /// TODO(derezzedex) + pub width: u32, + /// TODO(derezzedex) + pub height: u32, +} diff --git a/winit/src/position.rs b/native/src/window/position.rs similarity index 100% rename from winit/src/position.rs rename to native/src/window/position.rs diff --git a/src/window/settings.rs b/native/src/window/settings.rs similarity index 67% rename from src/window/settings.rs rename to native/src/window/settings.rs index 24d0f4f9ec..67798fbe8a 100644 --- a/src/window/settings.rs +++ b/native/src/window/settings.rs @@ -50,21 +50,3 @@ impl Default for Settings { } } } - -impl From for iced_winit::settings::Window { - fn from(settings: Settings) -> Self { - Self { - size: settings.size, - position: iced_winit::Position::from(settings.position), - min_size: settings.min_size, - max_size: settings.max_size, - visible: settings.visible, - resizable: settings.resizable, - decorations: settings.decorations, - transparent: settings.transparent, - always_on_top: settings.always_on_top, - icon: settings.icon.map(Icon::into), - platform_specific: Default::default(), - } - } -} diff --git a/src/window.rs b/src/window.rs index 2018053fbb..73e90243e4 100644 --- a/src/window.rs +++ b/src/window.rs @@ -1,12 +1,7 @@ //! Configure the window of your application in native platforms. -mod position; -mod settings; - -pub mod icon; - -pub use icon::Icon; -pub use position::Position; -pub use settings::Settings; +pub use iced_native::window::Icon; +pub use iced_native::window::Position; +pub use iced_native::window::Settings; #[cfg(not(target_arch = "wasm32"))] pub use crate::runtime::window::*; diff --git a/src/window/position.rs b/src/window/position.rs deleted file mode 100644 index 6b9fac417b..0000000000 --- a/src/window/position.rs +++ /dev/null @@ -1,32 +0,0 @@ -/// The position of a window in a given screen. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Position { - /// The platform-specific default position for a new window. - Default, - /// The window is completely centered on the screen. - Centered, - /// The window is positioned with specific coordinates: `(X, Y)`. - /// - /// When the decorations of the window are enabled, Windows 10 will add some - /// invisible padding to the window. This padding gets included in the - /// position. So if you have decorations enabled and want the window to be - /// at (0, 0) you would have to set the position to - /// `(PADDING_X, PADDING_Y)`. - Specific(i32, i32), -} - -impl Default for Position { - fn default() -> Self { - Self::Default - } -} - -impl From for iced_winit::Position { - fn from(position: Position) -> Self { - match position { - Position::Default => Self::Default, - Position::Centered => Self::Centered, - Position::Specific(x, y) => Self::Specific(x, y), - } - } -} diff --git a/src/window/icon.rs b/winit/src/icon.rs similarity index 90% rename from src/window/icon.rs rename to winit/src/icon.rs index bacad41a6f..84b88b394a 100644 --- a/src/window/icon.rs +++ b/winit/src/icon.rs @@ -7,7 +7,7 @@ use std::path::Path; /// The icon of a window. #[derive(Debug, Clone)] -pub struct Icon(iced_winit::winit::window::Icon); +pub struct Icon(winit::window::Icon); impl Icon { /// Creates an icon from 32bpp RGBA data. @@ -16,8 +16,7 @@ impl Icon { width: u32, height: u32, ) -> Result { - let raw = - iced_winit::winit::window::Icon::from_rgba(rgba, width, height)?; + let raw = winit::window::Icon::from_rgba(rgba, width, height)?; Ok(Icon(raw)) } @@ -91,9 +90,9 @@ impl From for Error { } } -impl From for Error { - fn from(error: iced_winit::winit::window::BadIcon) -> Self { - use iced_winit::winit::window::BadIcon; +impl From for Error { + fn from(error: winit::window::BadIcon) -> Self { + use winit::window::BadIcon; match error { BadIcon::ByteCountNotDivisibleBy4 { byte_count } => { @@ -114,7 +113,7 @@ impl From for Error { } } -impl From for iced_winit::winit::window::Icon { +impl From for winit::window::Icon { fn from(icon: Icon) -> Self { icon.0 } @@ -170,3 +169,11 @@ impl std::error::Error for Error { Some(self) } } + +impl TryFrom for Icon { + type Error = Error; + + fn try_from(icon: iced_native::window::Icon) -> Result { + Icon::from_rgba(icon.rgba, icon.width, icon.height) + } +} diff --git a/winit/src/lib.rs b/winit/src/lib.rs index 9b3c0a024c..eb58482bc4 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -49,7 +49,7 @@ pub mod window; pub mod system; mod error; -mod position; +mod icon; mod proxy; #[cfg(feature = "application")] @@ -58,8 +58,9 @@ pub use application::Application; pub use application::Profiler; pub use clipboard::Clipboard; pub use error::Error; -pub use position::Position; +pub use icon::Icon; pub use proxy::Proxy; pub use settings::Settings; pub use iced_graphics::Viewport; +pub use iced_native::window::Position; diff --git a/winit/src/settings.rs b/winit/src/settings.rs index ea0ba361bd..78c8c156e7 100644 --- a/winit/src/settings.rs +++ b/winit/src/settings.rs @@ -22,6 +22,7 @@ mod platform; pub use platform::PlatformSpecific; use crate::conversion; +use crate::Icon; use crate::Position; use winit::monitor::MonitorHandle; use winit::window::WindowBuilder; @@ -201,3 +202,23 @@ impl Default for Window { } } } + +impl From for Window { + fn from(settings: iced_native::window::Settings) -> Self { + Self { + size: settings.size, + position: Position::from(settings.position), + min_size: settings.min_size, + max_size: settings.max_size, + visible: settings.visible, + resizable: settings.resizable, + decorations: settings.decorations, + transparent: settings.transparent, + always_on_top: settings.always_on_top, + icon: settings.icon.and_then(|icon| { + Icon::try_from(icon).map(winit::window::Icon::from).ok() + }), + platform_specific: Default::default(), + } + } +} From f93fa0254329ebddca21ea1a79bd8ee6d8b4bdaf Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 19 Oct 2022 23:33:20 -0300 Subject: [PATCH 24/66] introduce `window::spawn` and `window::close` --- glutin/src/multi_window.rs | 79 +++++++++++++++++++++---------------- native/src/window/action.rs | 15 +++++-- winit/src/application.rs | 5 +++ winit/src/multi_window.rs | 79 +++++++++++++++++++++---------------- winit/src/window.rs | 16 ++++++++ 5 files changed, 123 insertions(+), 71 deletions(-) diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index ce34aa31fb..2a66a81692 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -682,41 +682,52 @@ pub fn run_command( clipboard.write(contents); } }, - command::Action::Window(id, action) => { - let window = windows.get(&id).expect("No window found"); - - match action { - window::Action::Resize { width, height } => { - window.set_inner_size(glutin::dpi::LogicalSize { - width, - height, - }); - } - window::Action::Move { x, y } => { - window.set_outer_position( - glutin::dpi::LogicalPosition { x, y }, - ); - } - window::Action::SetMode(mode) => { - window.set_visible(conversion::visible(mode)); - window.set_fullscreen(conversion::fullscreen( - window.primary_monitor(), - mode, - )); - } - window::Action::FetchMode(tag) => { - let mode = if window.is_visible().unwrap_or(true) { - conversion::mode(window.fullscreen()) - } else { - window::Mode::Hidden - }; - - proxy - .send_event(Event::Application(tag(mode))) - .expect("Send message to event loop"); - } + command::Action::Window(id, action) => match action { + window::Action::Spawn { settings } => { + proxy + .send_event(Event::NewWindow(id, settings.into())) + .expect("Send message to event loop"); } - } + window::Action::Close => { + proxy + .send_event(Event::CloseWindow(id)) + .expect("Send message to event loop"); + } + window::Action::Resize { width, height } => { + let window = windows.get(&id).expect("No window found"); + window.set_inner_size(glutin::dpi::LogicalSize { + width, + height, + }); + } + window::Action::Move { x, y } => { + let window = windows.get(&id).expect("No window found"); + window.set_outer_position(glutin::dpi::LogicalPosition { + x, + y, + }); + } + window::Action::SetMode(mode) => { + let window = windows.get(&id).expect("No window found"); + window.set_visible(conversion::visible(mode)); + window.set_fullscreen(conversion::fullscreen( + window.primary_monitor(), + mode, + )); + } + window::Action::FetchMode(tag) => { + let window = windows.get(&id).expect("No window found"); + let mode = if window.is_visible().unwrap_or(true) { + conversion::mode(window.fullscreen()) + } else { + window::Mode::Hidden + }; + + proxy + .send_event(Event::Application(tag(mode))) + .expect("Send message to event loop"); + } + }, command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { #[cfg(feature = "iced_winit/system")] diff --git a/native/src/window/action.rs b/native/src/window/action.rs index 37fcc2730b..0587f25c33 100644 --- a/native/src/window/action.rs +++ b/native/src/window/action.rs @@ -1,4 +1,4 @@ -use crate::window::{Mode, UserAttention}; +use crate::window::{self, Mode, UserAttention}; use iced_futures::MaybeSend; use std::fmt; @@ -13,6 +13,11 @@ pub enum Action { /// There’s no guarantee that this will work unless the left mouse /// button was pressed immediately before this function is called. Drag, + /// TODO(derezzedex) + Spawn { + /// TODO(derezzedex) + settings: window::Settings, + }, /// Resize the window. Resize { /// The new logical width of the window @@ -34,9 +39,9 @@ pub enum Action { y: i32, }, /// Set the [`Mode`] of the window. - SetMode(Mode), + SetMode(window::Mode), /// Fetch the current [`Mode`] of the window. - FetchMode(Box T + 'static>), + FetchMode(Box T + 'static>), /// Sets the window to maximized or back ToggleMaximize, /// Toggles whether window has decorations @@ -81,6 +86,7 @@ impl Action { T: 'static, { match self { + Self::Spawn { settings } => Action::Spawn { settings }, Self::Close => Action::Close, Self::Drag => Action::Drag, Self::Resize { width, height } => Action::Resize { width, height }, @@ -104,6 +110,9 @@ impl fmt::Debug for Action { match self { Self::Close => write!(f, "Action::Close"), Self::Drag => write!(f, "Action::Drag"), + Self::Spawn { settings } => { + write!(f, "Action::Spawn {{ settings: {:?} }}", settings) + } Self::Resize { width, height } => write!( f, "Action::Resize {{ widget: {}, height: {} }}", diff --git a/winit/src/application.rs b/winit/src/application.rs index 4486f5d9d8..910f3d94ff 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -675,6 +675,11 @@ pub fn run_command( window::Action::Drag => { let _res = window.drag_window(); } + window::Action::Spawn { .. } | window::Action::Close => { + log::info!( + "This is only available on `multi_window::Application`" + ) + } window::Action::Resize { width, height } => { window.set_inner_size(winit::dpi::LogicalSize { width, diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 9f46b88d02..1d71d801fe 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -855,41 +855,52 @@ pub fn run_command( clipboard.write(contents); } }, - command::Action::Window(id, action) => { - let window = windows.get(&id).expect("No window found"); - - match action { - window::Action::Resize { width, height } => { - window.set_inner_size(winit::dpi::LogicalSize { - width, - height, - }); - } - window::Action::Move { x, y } => { - window.set_outer_position( - winit::dpi::LogicalPosition { x, y }, - ); - } - window::Action::SetMode(mode) => { - window.set_visible(conversion::visible(mode)); - window.set_fullscreen(conversion::fullscreen( - window.primary_monitor(), - mode, - )); - } - window::Action::FetchMode(tag) => { - let mode = if window.is_visible().unwrap_or(true) { - conversion::mode(window.fullscreen()) - } else { - window::Mode::Hidden - }; - - proxy - .send_event(Event::Application(tag(mode))) - .expect("Send message to event loop"); - } + command::Action::Window(id, action) => match action { + window::Action::Spawn { settings } => { + proxy + .send_event(Event::NewWindow(id, settings.into())) + .expect("Send message to event loop"); } - } + window::Action::Close => { + proxy + .send_event(Event::CloseWindow(id)) + .expect("Send message to event loop"); + } + window::Action::Resize { width, height } => { + let window = windows.get(&id).expect("No window found"); + window.set_inner_size(winit::dpi::LogicalSize { + width, + height, + }); + } + window::Action::Move { x, y } => { + let window = windows.get(&id).expect("No window found"); + window.set_outer_position(winit::dpi::LogicalPosition { + x, + y, + }); + } + window::Action::SetMode(mode) => { + let window = windows.get(&id).expect("No window found"); + window.set_visible(conversion::visible(mode)); + window.set_fullscreen(conversion::fullscreen( + window.primary_monitor(), + mode, + )); + } + window::Action::FetchMode(tag) => { + let window = windows.get(&id).expect("No window found"); + let mode = if window.is_visible().unwrap_or(true) { + conversion::mode(window.fullscreen()) + } else { + window::Mode::Hidden + }; + + proxy + .send_event(Event::Application(tag(mode))) + .expect("Send message to event loop"); + } + }, command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { #[cfg(feature = "system")] diff --git a/winit/src/window.rs b/winit/src/window.rs index d9bc0d83c4..fba863ef6c 100644 --- a/winit/src/window.rs +++ b/winit/src/window.rs @@ -14,6 +14,22 @@ pub fn drag() -> Command { Command::single(command::Action::Window(window::Action::Drag)) } +/// TODO(derezzedex) +pub fn spawn( + id: window::Id, + settings: window::Settings, +) -> Command { + Command::single(command::Action::Window( + id, + window::Action::Spawn { settings }, + )) +} + +/// TODO(derezzedex) +pub fn close(id: window::Id) -> Command { + Command::single(command::Action::Window(id, window::Action::Close)) +} + /// Resizes the window to the given logical dimensions. pub fn resize( id: window::Id, From aa7164fdde0cf879139e457555c3985d4e9111f0 Mon Sep 17 00:00:00 2001 From: Richard Date: Mon, 31 Oct 2022 16:57:57 -0300 Subject: [PATCH 25/66] update `glutin` to 0.30 --- glutin/Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/glutin/Cargo.toml b/glutin/Cargo.toml index 75a38d2288..addaa16c08 100644 --- a/glutin/Cargo.toml +++ b/glutin/Cargo.toml @@ -20,9 +20,9 @@ multi_window = ["iced_winit/multi_window"] version = "0.4" [dependencies.glutin] -version = "0.29" +version = "0.30" git = "https://github.com/derezzedex/glutin" -rev = "e72ea919f95106cfdfdce3e7dcfdbf71a432840a" +rev = "2a2a97209c49929027beced68e1989b8486bdec9" [dependencies.iced_native] version = "0.7" From 0553062be1898873fb057c0446b772ab07b551e5 Mon Sep 17 00:00:00 2001 From: Richard Date: Mon, 31 Oct 2022 20:23:24 -0300 Subject: [PATCH 26/66] update `iced_glutin` to use new surface api --- glutin/Cargo.toml | 3 + glutin/src/application.rs | 338 ++++++++++++++++++++++++++++---------- 2 files changed, 254 insertions(+), 87 deletions(-) diff --git a/glutin/Cargo.toml b/glutin/Cargo.toml index addaa16c08..708207804f 100644 --- a/glutin/Cargo.toml +++ b/glutin/Cargo.toml @@ -16,6 +16,9 @@ debug = ["iced_winit/debug"] system = ["iced_winit/system"] multi_window = ["iced_winit/multi_window"] +[dependencies.raw-window-handle] +version = "0.5.0" + [dependencies.log] version = "0.4" diff --git a/glutin/src/application.rs b/glutin/src/application.rs index cbb2389149..45ff37f009 100644 --- a/glutin/src/application.rs +++ b/glutin/src/application.rs @@ -12,14 +12,33 @@ use iced_winit::futures; use iced_winit::futures::channel::mpsc; use iced_winit::renderer; use iced_winit::user_interface; +use iced_winit::winit; use iced_winit::{Clipboard, Command, Debug, Proxy, Settings}; -use glutin::window::Window; +use glutin::config::{ + Config, ConfigSurfaceTypes, ConfigTemplateBuilder, GlConfig, +}; +use glutin::context::{ + ContextApi, ContextAttributesBuilder, NotCurrentContext, + NotCurrentGlContextSurfaceAccessor, + PossiblyCurrentContextGlSurfaceAccessor, PossiblyCurrentGlContext, +}; +use glutin::display::{Display, DisplayApiPreference, GlDisplay}; +use glutin::surface::{ + GlSurface, Surface, SurfaceAttributesBuilder, WindowSurface, +}; +use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; + +use std::ffi::CString; use std::mem::ManuallyDrop; +use std::num::NonZeroU32; #[cfg(feature = "tracing")] use tracing::{info_span, instrument::Instrument}; +#[allow(unsafe_code)] +const ONE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1) }; + /// Runs an [`Application`] with an executor, compositor, and the provided /// settings. pub fn run( @@ -34,9 +53,8 @@ where { use futures::task; use futures::Future; - use glutin::event_loop::EventLoopBuilder; - use glutin::platform::run_return::EventLoopExtRunReturn; - use glutin::ContextBuilder; + use winit::event_loop::EventLoopBuilder; + use winit::platform::run_return::EventLoopExtRunReturn; #[cfg(feature = "trace")] let _guard = iced_winit::Profiler::init(); @@ -63,76 +81,216 @@ where runtime.enter(|| A::new(flags)) }; - let context = { - let builder = settings.window.into_builder( - &application.title(), - event_loop.primary_monitor(), - settings.id, - ); + let builder = settings.window.into_builder( + &application.title(), + event_loop.primary_monitor(), + settings.id, + ); - log::info!("Window builder: {:#?}", builder); + log::info!("Window builder: {:#?}", builder); - let opengl_builder = ContextBuilder::new() - .with_vsync(true) - .with_multisampling(C::sample_count(&compositor_settings) as u16); + #[allow(unsafe_code)] + let (display, window, surface, context) = unsafe { + struct Configuration(Config); + use std::fmt; + impl fmt::Debug for Configuration { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let config = &self.0; + + f.debug_struct("Configuration") + .field("raw", &config) + .field("samples", &config.num_samples()) + .field("buffer_type", &config.color_buffer_type()) + .field("surface_type", &config.config_surface_types()) + .field("depth", &config.depth_size()) + .field("alpha", &config.alpha_size()) + .field("stencil", &config.stencil_size()) + .field("float_pixels", &config.float_pixels()) + .field("srgb", &config.srgb_capable()) + .field("api", &config.api()) + .finish() + } + } - let opengles_builder = opengl_builder.clone().with_gl( - glutin::GlRequest::Specific(glutin::Api::OpenGlEs, (2, 0)), - ); + impl AsRef for Configuration { + fn as_ref(&self) -> &Config { + &self.0 + } + } + + let display_handle = event_loop.raw_display_handle(); + + #[cfg(all( + any(windows, target_os = "macos"), + not(target_arch = "wasm32") + ))] + let (window, window_handle) = { + let window = builder + .build(&event_loop) + .map_err(Error::WindowCreationFailed)?; + + let handle = window.raw_window_handle(); - let (first_builder, second_builder) = if settings.try_opengles_first { - (opengles_builder, opengl_builder) - } else { - (opengl_builder, opengles_builder) + (window, handle) }; - log::info!("Trying first builder: {:#?}", first_builder); + #[cfg(target_arch = "wasm32")] + let preference = Err(Error::GraphicsCreationFailed( + iced_graphics::Error::BackendError(format!( + "target not supported by backend" + )), + ))?; + + #[cfg(all(windows, not(target_arch = "wasm32")))] + let preference = DisplayApiPreference::WglThenEgl(Some(window_handle)); + + #[cfg(all(target_os = "macos", not(target_arch = "wasm32")))] + let preference = DisplayApiPreference::Cgl; + + #[cfg(all( + unix, + not(target_os = "macos"), + not(target_arch = "wasm32") + ))] + let preference = DisplayApiPreference::GlxThenEgl(Box::new( + winit::platform::unix::register_xlib_error_hook, + )); + + let display = + Display::new(display_handle, preference).map_err(|error| { + Error::GraphicsCreationFailed( + iced_graphics::Error::BackendError(format!( + "failed to create display: {error}" + )), + ) + })?; + + log::debug!("Display: {}", display.version_string()); + + let samples = C::sample_count(&compositor_settings) as u8; + let mut template = ConfigTemplateBuilder::new() + .with_surface_type(ConfigSurfaceTypes::WINDOW); + + if samples != 0 { + template = template.with_multisampling(samples); + } + + #[cfg(all(windows, not(target_arch = "wasm32")))] + let template = template.compatible_with_native_window(window_handle); + + log::debug!("Searching for display configurations"); + let configuration = display + .find_configs(template.build()) + .map_err(|_| { + Error::GraphicsCreationFailed( + iced_graphics::Error::NoAvailablePixelFormat, + ) + })? + .map(Configuration) + .inspect(|config| { + log::trace!("{config:#?}"); + }) + .min_by_key(|config| { + config.as_ref().num_samples().saturating_sub(samples) + }) + .ok_or(Error::GraphicsCreationFailed( + iced_graphics::Error::NoAvailablePixelFormat, + ))?; + + log::debug!("Selected: {configuration:#?}"); + + #[cfg(all( + unix, + not(target_os = "macos"), + not(target_arch = "wasm32") + ))] + let (window, window_handle) = { + use glutin::platform::x11::X11GlConfigExt; + let builder = + if let Some(visual) = configuration.as_ref().x11_visual() { + use winit::platform::unix::WindowBuilderExtUnix; + builder.with_x11_visual(visual.into_raw()) + } else { + builder + }; + + let window = builder + .build(&event_loop) + .map_err(Error::WindowCreationFailed)?; + + let handle = window.raw_window_handle(); + + (window, handle) + }; - let context = first_builder - .build_windowed(builder.clone(), &event_loop) + let attributes = + ContextAttributesBuilder::new().build(Some(window_handle)); + let fallback_attributes = ContextAttributesBuilder::new() + .with_context_api(ContextApi::Gles(None)) + .build(Some(window_handle)); + + let context = display + .create_context(configuration.as_ref(), &attributes) .or_else(|_| { - log::info!("Trying second builder: {:#?}", second_builder); - second_builder.build_windowed(builder, &event_loop) + display.create_context( + configuration.as_ref(), + &fallback_attributes, + ) }) .map_err(|error| { - use glutin::CreationError; - use iced_graphics::Error as ContextError; + Error::GraphicsCreationFailed( + iced_graphics::Error::BackendError(format!( + "failed to create context: {error}" + )), + ) + })?; - match error { - CreationError::Window(error) => { - Error::WindowCreationFailed(error) - } - CreationError::OpenGlVersionNotSupported => { - Error::GraphicsCreationFailed( - ContextError::VersionNotSupported, - ) - } - CreationError::NoAvailablePixelFormat => { - Error::GraphicsCreationFailed( - ContextError::NoAvailablePixelFormat, - ) - } - error => Error::GraphicsCreationFailed( - ContextError::BackendError(error.to_string()), - ), - } + let (width, height) = window.inner_size().into(); + let surface_attributes = + SurfaceAttributesBuilder::::new() + .with_srgb(Some(true)) + .build( + window_handle, + NonZeroU32::new(width).unwrap_or(ONE), + NonZeroU32::new(height).unwrap_or(ONE), + ); + + let surface = display + .create_window_surface(configuration.as_ref(), &surface_attributes) + .map_err(|error| { + Error::GraphicsCreationFailed( + iced_graphics::Error::BackendError(format!( + "failed to create surface: {error}" + )), + ) })?; - #[allow(unsafe_code)] - unsafe { + let context = { context - .make_current(todo!()) - .expect("Make OpenGL context current") + .make_current(&surface) + .expect("make context current") + }; + + if let Err(error) = surface.set_swap_interval( + &context, + glutin::surface::SwapInterval::Wait(ONE), + ) { + log::error!("set swap interval failed: {}", error); } + + (display, window, surface, context) }; #[allow(unsafe_code)] let (compositor, renderer) = unsafe { C::new(compositor_settings, |address| { - context.get_proc_address(address) + let address = CString::new(address).expect("address error"); + display.get_proc_address(address.as_c_str()) })? }; + let context = { context.make_not_current().expect("make context current") }; + let (mut sender, receiver) = mpsc::unbounded(); let mut instance = Box::pin({ @@ -144,6 +302,8 @@ where proxy, debug, receiver, + window, + surface, context, init_command, settings.exit_on_close_request, @@ -159,22 +319,22 @@ where let mut context = task::Context::from_waker(task::noop_waker_ref()); let _ = event_loop.run_return(move |event, _, control_flow| { - use glutin::event_loop::ControlFlow; + use winit::event_loop::ControlFlow; if let ControlFlow::ExitWithCode(_) = control_flow { return; } let event = match event { - glutin::event::Event::WindowEvent { + winit::event::Event::WindowEvent { event: - glutin::event::WindowEvent::ScaleFactorChanged { + winit::event::WindowEvent::ScaleFactorChanged { new_inner_size, .. }, window_id, - } => Some(glutin::event::Event::WindowEvent { - event: glutin::event::WindowEvent::Resized(*new_inner_size), + } => Some(winit::event::Event::WindowEvent { + event: winit::event::WindowEvent::Resized(*new_inner_size), window_id, }), _ => event.to_static(), @@ -200,10 +360,12 @@ async fn run_instance( mut compositor: C, mut renderer: A::Renderer, mut runtime: Runtime, A::Message>, - mut proxy: glutin::event_loop::EventLoopProxy, + mut proxy: winit::event_loop::EventLoopProxy, mut debug: Debug, - mut receiver: mpsc::UnboundedReceiver>, - mut context: glutin::ContextWrapper, + mut receiver: mpsc::UnboundedReceiver>, + window: winit::window::Window, + surface: Surface, + context: NotCurrentContext, init_command: Command, exit_on_close_request: bool, ) where @@ -212,12 +374,18 @@ async fn run_instance( C: window::GLCompositor + 'static, ::Theme: StyleSheet, { - use glutin::event; use iced_winit::futures::stream::StreamExt; + use winit::event; + + let context = { + context + .make_current(&surface) + .expect("make context current") + }; - let mut clipboard = Clipboard::connect(context.window()); + let mut clipboard = Clipboard::connect(&window); let mut cache = user_interface::Cache::default(); - let mut state = application::State::new(&application, context.window()); + let mut state = application::State::new(&application, &window); let mut viewport_version = state.viewport_version(); let mut should_exit = false; @@ -232,7 +400,7 @@ async fn run_instance( &mut should_exit, &mut proxy, &mut debug, - context.window(), + &window, || compositor.fetch_information(), ); runtime.track(application.subscription()); @@ -296,12 +464,12 @@ async fn run_instance( &mut proxy, &mut debug, &mut messages, - context.window(), + &window, || compositor.fetch_information(), ); // Update window - state.synchronize(&application, context.window()); + state.synchronize(&application, &window); user_interface = ManuallyDrop::new(application::build_user_interface( @@ -329,14 +497,14 @@ async fn run_instance( debug.draw_finished(); if new_mouse_interaction != mouse_interaction { - context.window().set_cursor_icon( - conversion::mouse_interaction(new_mouse_interaction), - ); + window.set_cursor_icon(conversion::mouse_interaction( + new_mouse_interaction, + )); mouse_interaction = new_mouse_interaction; } - context.window().request_redraw(); + window.request_redraw(); } event::Event::PlatformSpecific(event::PlatformSpecific::MacOS( event::MacOS::ReceivedUrl(url), @@ -357,13 +525,10 @@ async fn run_instance( debug.render_started(); - #[allow(unsafe_code)] - unsafe { - if !context.is_current() { - context = context - .make_current(todo!()) - .expect("Make OpenGL context current"); - } + if !context.is_current() { + context + .make_current(&surface) + .expect("Make OpenGL context current"); } let current_viewport_version = state.viewport_version(); @@ -391,19 +556,18 @@ async fn run_instance( debug.draw_finished(); if new_mouse_interaction != mouse_interaction { - context.window().set_cursor_icon( - conversion::mouse_interaction( - new_mouse_interaction, - ), - ); + window.set_cursor_icon(conversion::mouse_interaction( + new_mouse_interaction, + )); mouse_interaction = new_mouse_interaction; } - context.resize(glutin::dpi::PhysicalSize::new( - physical_size.width, - physical_size.height, - )); + surface.resize( + &context, + NonZeroU32::new(physical_size.width).unwrap_or(ONE), + NonZeroU32::new(physical_size.height).unwrap_or(ONE), + ); compositor.resize_viewport(physical_size); @@ -417,7 +581,7 @@ async fn run_instance( &debug.overlay(), ); - context.swap_buffers(todo!()).expect("Swap buffers"); + surface.swap_buffers(&context).expect("Swap buffers"); debug.render_finished(); @@ -434,7 +598,7 @@ async fn run_instance( break; } - state.update(context.window(), &window_event, &mut debug); + state.update(&window, &window_event, &mut debug); if let Some(event) = conversion::window_event( crate::window::Id::MAIN, From ac20f35c6245bbafffd4d047764fb04e66dcfe75 Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 2 Nov 2022 10:17:49 -0300 Subject: [PATCH 27/66] update `glutin\multi_window` to new surface api --- glutin/src/multi_window.rs | 372 +++++++++++++++++++++++-------- glutin/src/multi_window/state.rs | 20 +- 2 files changed, 294 insertions(+), 98 deletions(-) diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index 2a66a81692..095e0e2cee 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -15,11 +15,30 @@ use iced_winit::renderer; use iced_winit::settings; use iced_winit::user_interface; use iced_winit::window; +use iced_winit::winit; use iced_winit::{Clipboard, Command, Debug, Proxy, Settings}; -use glutin::window::Window; +use glutin::config::{ + Config, ConfigSurfaceTypes, ConfigTemplateBuilder, GlConfig, +}; +use glutin::context::{ + ContextApi, ContextAttributesBuilder, NotCurrentContext, + NotCurrentGlContextSurfaceAccessor, + PossiblyCurrentContextGlSurfaceAccessor, PossiblyCurrentGlContext, +}; +use glutin::display::{Display, DisplayApiPreference, GlDisplay}; +use glutin::surface::{ + GlSurface, Surface, SurfaceAttributesBuilder, WindowSurface, +}; +use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; + use std::collections::HashMap; +use std::ffi::CString; use std::mem::ManuallyDrop; +use std::num::NonZeroU32; + +#[allow(unsafe_code)] +const ONE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1) }; /// Runs an [`Application`] with an executor, compositor, and the provided /// settings. @@ -35,9 +54,8 @@ where { use futures::task; use futures::Future; - use glutin::event_loop::EventLoopBuilder; - use glutin::platform::run_return::EventLoopExtRunReturn; - use glutin::ContextBuilder; + use winit::event_loop::EventLoopBuilder; + use winit::platform::run_return::EventLoopExtRunReturn; let mut debug = Debug::new(); debug.startup_started(); @@ -58,81 +76,216 @@ where runtime.enter(|| A::new(flags)) }; - let (context, window) = { - let builder = settings.window.into_builder( - &application.title(), - event_loop.primary_monitor(), - settings.id, - ); + let builder = settings.window.into_builder( + &application.title(), + event_loop.primary_monitor(), + settings.id, + ); + + log::info!("Window builder: {:#?}", builder); + + #[allow(unsafe_code)] + let (display, window, configuration, surface, context) = unsafe { + struct Configuration(Config); + use std::fmt; + impl fmt::Debug for Configuration { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let config = &self.0; + + f.debug_struct("Configuration") + .field("raw", &config) + .field("samples", &config.num_samples()) + .field("buffer_type", &config.color_buffer_type()) + .field("surface_type", &config.config_surface_types()) + .field("depth", &config.depth_size()) + .field("alpha", &config.alpha_size()) + .field("stencil", &config.stencil_size()) + .field("float_pixels", &config.float_pixels()) + .field("srgb", &config.srgb_capable()) + .field("api", &config.api()) + .finish() + } + } - log::info!("Window builder: {:#?}", builder); + impl AsRef for Configuration { + fn as_ref(&self) -> &Config { + &self.0 + } + } - let opengl_builder = ContextBuilder::new() - .with_vsync(true) - .with_multisampling(C::sample_count(&compositor_settings) as u16); + let display_handle = event_loop.raw_display_handle(); - let opengles_builder = opengl_builder.clone().with_gl( - glutin::GlRequest::Specific(glutin::Api::OpenGlEs, (2, 0)), - ); + #[cfg(all( + any(windows, target_os = "macos"), + not(target_arch = "wasm32") + ))] + let (window, window_handle) = { + let window = builder + .build(&event_loop) + .map_err(Error::WindowCreationFailed)?; + + let handle = window.raw_window_handle(); + + (window, handle) + }; + + #[cfg(target_arch = "wasm32")] + let preference = Err(Error::GraphicsCreationFailed( + iced_graphics::Error::BackendError(format!( + "target not supported by backend" + )), + ))?; + + #[cfg(all(windows, not(target_arch = "wasm32")))] + let preference = DisplayApiPreference::WglThenEgl(Some(window_handle)); + + #[cfg(all(target_os = "macos", not(target_arch = "wasm32")))] + let preference = DisplayApiPreference::Cgl; + + #[cfg(all( + unix, + not(target_os = "macos"), + not(target_arch = "wasm32") + ))] + let preference = DisplayApiPreference::GlxThenEgl(Box::new( + winit::platform::unix::register_xlib_error_hook, + )); + + let display = + Display::new(display_handle, preference).map_err(|error| { + Error::GraphicsCreationFailed( + iced_graphics::Error::BackendError(format!( + "failed to create display: {error}" + )), + ) + })?; + + log::debug!("Display: {}", display.version_string()); + + let samples = C::sample_count(&compositor_settings) as u8; + let mut template = ConfigTemplateBuilder::new() + .with_surface_type(ConfigSurfaceTypes::WINDOW); + + if samples != 0 { + template = template.with_multisampling(samples); + } + + #[cfg(all(windows, not(target_arch = "wasm32")))] + let template = template.compatible_with_native_window(window_handle); + + log::debug!("Searching for display configurations"); + let configuration = display + .find_configs(template.build()) + .map_err(|_| { + Error::GraphicsCreationFailed( + iced_graphics::Error::NoAvailablePixelFormat, + ) + })? + .map(Configuration) + .inspect(|config| { + log::trace!("{config:#?}"); + }) + .min_by_key(|config| { + config.as_ref().num_samples().saturating_sub(samples) + }) + .ok_or(Error::GraphicsCreationFailed( + iced_graphics::Error::NoAvailablePixelFormat, + ))?; + + log::debug!("Selected: {configuration:#?}"); + + #[cfg(all( + unix, + not(target_os = "macos"), + not(target_arch = "wasm32") + ))] + let (window, window_handle) = { + use glutin::platform::x11::X11GlConfigExt; + let builder = + if let Some(visual) = configuration.as_ref().x11_visual() { + use winit::platform::unix::WindowBuilderExtUnix; + builder.with_x11_visual(visual.into_raw()) + } else { + builder + }; + + let window = builder + .build(&event_loop) + .map_err(Error::WindowCreationFailed)?; + + let handle = window.raw_window_handle(); - let (first_builder, second_builder) = if settings.try_opengles_first { - (opengles_builder, opengl_builder) - } else { - (opengl_builder, opengles_builder) + (window, handle) }; - log::info!("Trying first builder: {:#?}", first_builder); + let attributes = + ContextAttributesBuilder::new().build(Some(window_handle)); + let fallback_attributes = ContextAttributesBuilder::new() + .with_context_api(ContextApi::Gles(None)) + .build(Some(window_handle)); - let context = first_builder - .build_windowed(builder.clone(), &event_loop) + let context = display + .create_context(configuration.as_ref(), &attributes) .or_else(|_| { - log::info!("Trying second builder: {:#?}", second_builder); - second_builder.build_windowed(builder, &event_loop) + display.create_context( + configuration.as_ref(), + &fallback_attributes, + ) }) .map_err(|error| { - use glutin::CreationError; - use iced_graphics::Error as ContextError; + Error::GraphicsCreationFailed( + iced_graphics::Error::BackendError(format!( + "failed to create context: {error}" + )), + ) + })?; - match error { - CreationError::Window(error) => { - Error::WindowCreationFailed(error) - } - CreationError::OpenGlVersionNotSupported => { - Error::GraphicsCreationFailed( - ContextError::VersionNotSupported, - ) - } - CreationError::NoAvailablePixelFormat => { - Error::GraphicsCreationFailed( - ContextError::NoAvailablePixelFormat, - ) - } - error => Error::GraphicsCreationFailed( - ContextError::BackendError(error.to_string()), - ), - } + let (width, height) = window.inner_size().into(); + let surface_attributes = + SurfaceAttributesBuilder::::new() + .with_srgb(Some(true)) + .build( + window_handle, + NonZeroU32::new(width).unwrap_or(ONE), + NonZeroU32::new(height).unwrap_or(ONE), + ); + + let surface = display + .create_window_surface(configuration.as_ref(), &surface_attributes) + .map_err(|error| { + Error::GraphicsCreationFailed( + iced_graphics::Error::BackendError(format!( + "failed to create surface: {error}" + )), + ) })?; - #[allow(unsafe_code)] - unsafe { - let (context, window) = context.split(); + let context = { + context + .make_current(&surface) + .expect("make context current") + }; - ( - context - .make_current(&window) - .expect("Make OpenGL context current"), - window, - ) + if let Err(error) = surface.set_swap_interval( + &context, + glutin::surface::SwapInterval::Wait(ONE), + ) { + log::error!("set swap interval failed: {}", error); } + + (display, window, configuration.0, surface, context) }; #[allow(unsafe_code)] let (compositor, renderer) = unsafe { C::new(compositor_settings, |address| { - context.get_proc_address(address) + let address = CString::new(address).expect("address error"); + display.get_proc_address(address.as_c_str()) })? }; + let context = { context.make_not_current().expect("make context current") }; + let (mut sender, receiver) = mpsc::unbounded(); let mut instance = Box::pin(run_instance::( @@ -143,8 +296,11 @@ where proxy, debug, receiver, - context, + display, window, + configuration, + surface, + context, init_command, settings.exit_on_close_request, )); @@ -152,25 +308,25 @@ where let mut context = task::Context::from_waker(task::noop_waker_ref()); let _ = event_loop.run_return(move |event, event_loop, control_flow| { - use glutin::event_loop::ControlFlow; + use winit::event_loop::ControlFlow; if let ControlFlow::ExitWithCode(_) = control_flow { return; } let event = match event { - glutin::event::Event::WindowEvent { + winit::event::Event::WindowEvent { event: - glutin::event::WindowEvent::ScaleFactorChanged { + winit::event::WindowEvent::ScaleFactorChanged { new_inner_size, .. }, window_id, - } => Some(glutin::event::Event::WindowEvent { - event: glutin::event::WindowEvent::Resized(*new_inner_size), + } => Some(winit::event::Event::WindowEvent { + event: winit::event::WindowEvent::Resized(*new_inner_size), window_id, }), - glutin::event::Event::UserEvent(Event::NewWindow(id, settings)) => { + winit::event::Event::UserEvent(Event::NewWindow(id, settings)) => { // TODO(derezzedex) let window = settings .into_builder( @@ -181,7 +337,7 @@ where .build(event_loop) .expect("Failed to build window"); - Some(glutin::event::Event::UserEvent(Event::WindowCreated( + Some(winit::event::Event::UserEvent(Event::WindowCreated( id, window, ))) } @@ -208,13 +364,16 @@ async fn run_instance( mut compositor: C, mut renderer: A::Renderer, mut runtime: Runtime>, Event>, - mut proxy: glutin::event_loop::EventLoopProxy>, + mut proxy: winit::event_loop::EventLoopProxy>, mut debug: Debug, mut receiver: mpsc::UnboundedReceiver< - glutin::event::Event<'_, Event>, + winit::event::Event<'_, Event>, >, - mut context: glutin::RawContext, - window: Window, + display: Display, + window: winit::window::Window, + configuration: Config, + surface: Surface, + context: NotCurrentContext, init_command: Command, _exit_on_close_request: bool, ) where @@ -223,8 +382,14 @@ async fn run_instance( C: iced_graphics::window::GLCompositor + 'static, ::Theme: StyleSheet, { - use glutin::event; use iced_winit::futures::stream::StreamExt; + use winit::event; + + let context = { + context + .make_current(&surface) + .expect("make context current") + }; let mut clipboard = Clipboard::connect(&window); let mut cache = user_interface::Cache::default(); @@ -241,6 +406,7 @@ async fn run_instance( let mut current_context_window = window.id(); let mut window_ids = HashMap::from([(window.id(), window::Id::MAIN)]); let mut windows = HashMap::from([(window::Id::MAIN, window)]); + let mut surfaces = HashMap::from([(window::Id::MAIN, surface)]); let mut states = HashMap::from([(window::Id::MAIN, state)]); let mut interfaces = ManuallyDrop::new(HashMap::from([(window::Id::MAIN, user_interface)])); @@ -419,10 +585,32 @@ async fn run_instance( id, ); + let window_handle = window.raw_window_handle(); + let (width, height) = window.inner_size().into(); + let surface_attributes = + SurfaceAttributesBuilder::::new() + .with_srgb(Some(true)) + .build( + window_handle, + NonZeroU32::new(width).unwrap_or(ONE), + NonZeroU32::new(height).unwrap_or(ONE), + ); + + #[allow(unsafe_code)] + let surface = unsafe { + display + .create_window_surface( + &configuration, + &surface_attributes, + ) + .expect("failed to create surface") + }; + let _ = states.insert(id, state); let _ = interfaces.insert(id, user_interface); let _ = window_ids.insert(window.id(), id); let _ = windows.insert(id, window); + let _ = surfaces.insert(id, surface); } Event::CloseWindow(id) => { // TODO(derezzedex): log errors @@ -437,6 +625,9 @@ async fn run_instance( if interfaces.remove(&id).is_none() { println!("Failed to remove from `interfaces`!"); } + if surfaces.remove(&id).is_none() { + println!("Failed to remove from `surfaces`!") + } if windows.remove(&id).is_none() { println!("Failed to remove from `windows`!") } @@ -455,17 +646,19 @@ async fn run_instance( let window = window_ids.get(&id).and_then(|id| windows.get(id)).unwrap(); + let surface = window_ids + .get(&id) + .and_then(|id| surfaces.get(id)) + .unwrap(); + debug.render_started(); - #[allow(unsafe_code)] - unsafe { - if current_context_window != id { - context = context - .make_current(window) - .expect("Make OpenGL context current"); + if current_context_window != id { + context + .make_current(&surface) + .expect("Make OpenGL context current"); - current_context_window = id; - } + current_context_window = id; } if state.viewport_changed() { @@ -501,10 +694,11 @@ async fn run_instance( mouse_interaction = new_mouse_interaction; } - context.resize(glutin::dpi::PhysicalSize::new( - physical_size.width, - physical_size.height, - )); + surface.resize( + &context, + NonZeroU32::new(physical_size.width).unwrap_or(ONE), + NonZeroU32::new(physical_size.height).unwrap_or(ONE), + ); compositor.resize_viewport(physical_size); @@ -519,7 +713,7 @@ async fn run_instance( &debug.overlay(), ); - context.swap_buffers(window).expect("Swap buffers"); + surface.swap_buffers(&context).expect("Swap buffers"); debug.render_finished(); @@ -595,7 +789,7 @@ pub enum Event { /// TODO(derezzedex) CloseWindow(window::Id), /// TODO(derezzedex) - WindowCreated(window::Id, glutin::window::Window), + WindowCreated(window::Id, winit::window::Window), } /// Updates an [`Application`] by feeding it the provided messages, spawning any @@ -607,10 +801,10 @@ pub fn update( renderer: &mut A::Renderer, runtime: &mut Runtime>, Event>, clipboard: &mut Clipboard, - proxy: &mut glutin::event_loop::EventLoopProxy>, + proxy: &mut winit::event_loop::EventLoopProxy>, debug: &mut Debug, messages: &mut Vec, - windows: &HashMap, + windows: &HashMap, graphics_info: impl FnOnce() -> iced_graphics::compositor::Information + Copy, ) where ::Theme: StyleSheet, @@ -650,9 +844,9 @@ pub fn run_command( command: Command, runtime: &mut Runtime>, Event>, clipboard: &mut Clipboard, - proxy: &mut glutin::event_loop::EventLoopProxy>, + proxy: &mut winit::event_loop::EventLoopProxy>, debug: &mut Debug, - windows: &HashMap, + windows: &HashMap, _graphics_info: impl FnOnce() -> iced_graphics::compositor::Information + Copy, ) where A: Application, @@ -695,14 +889,14 @@ pub fn run_command( } window::Action::Resize { width, height } => { let window = windows.get(&id).expect("No window found"); - window.set_inner_size(glutin::dpi::LogicalSize { + window.set_inner_size(winit::dpi::LogicalSize { width, height, }); } window::Action::Move { x, y } => { let window = windows.get(&id).expect("No window found"); - window.set_outer_position(glutin::dpi::LogicalPosition { + window.set_outer_position(winit::dpi::LogicalPosition { x, y, }); diff --git a/glutin/src/multi_window/state.rs b/glutin/src/multi_window/state.rs index 163f46bd38..321fc4d16f 100644 --- a/glutin/src/multi_window/state.rs +++ b/glutin/src/multi_window/state.rs @@ -4,9 +4,11 @@ use crate::multi_window::{Application, Event}; use crate::window; use crate::{Color, Debug, Point, Size, Viewport}; -use glutin::event::{Touch, WindowEvent}; -use glutin::event_loop::EventLoopProxy; -use glutin::window::Window; +use iced_winit::winit; +use winit::event::{Touch, WindowEvent}; +use winit::event_loop::EventLoopProxy; +use winit::window::Window; + use std::collections::HashMap; use std::marker::PhantomData; @@ -20,8 +22,8 @@ where scale_factor: f64, viewport: Viewport, viewport_changed: bool, - cursor_position: glutin::dpi::PhysicalPosition, - modifiers: glutin::event::ModifiersState, + cursor_position: winit::dpi::PhysicalPosition, + modifiers: winit::event::ModifiersState, theme: ::Theme, appearance: iced_winit::application::Appearance, application: PhantomData, @@ -53,8 +55,8 @@ where viewport, viewport_changed: false, // TODO: Encode cursor availability in the type-system - cursor_position: glutin::dpi::PhysicalPosition::new(-1.0, -1.0), - modifiers: glutin::event::ModifiersState::default(), + cursor_position: winit::dpi::PhysicalPosition::new(-1.0, -1.0), + modifiers: winit::event::ModifiersState::default(), theme, appearance, application: PhantomData, @@ -95,7 +97,7 @@ where } /// Returns the current keyboard modifiers of the [`State`]. - pub fn modifiers(&self) -> glutin::event::ModifiersState { + pub fn modifiers(&self) -> winit::event::ModifiersState { self.modifiers } @@ -156,7 +158,7 @@ where WindowEvent::CursorLeft { .. } => { // TODO: Encode cursor availability in the type-system self.cursor_position = - glutin::dpi::PhysicalPosition::new(-1.0, -1.0); + winit::dpi::PhysicalPosition::new(-1.0, -1.0); } WindowEvent::ModifiersChanged(new_modifiers) => { self.modifiers = *new_modifiers; From 5e4e410b18eb744cf70ae1f18b9ef08611f59150 Mon Sep 17 00:00:00 2001 From: Richard Date: Thu, 3 Nov 2022 14:53:05 -0300 Subject: [PATCH 28/66] remove `windows` method (use commands instead) --- examples/multi_window/src/main.rs | 13 ++++--------- glutin/src/multi_window.rs | 2 +- glutin/src/multi_window/state.rs | 24 +----------------------- src/multi_window/application.rs | 13 ------------- winit/src/multi_window.rs | 5 +---- winit/src/multi_window/state.rs | 24 +----------------------- 6 files changed, 8 insertions(+), 73 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 0dda1804a1..2771d7283e 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -131,6 +131,7 @@ impl Application for Example { } WindowMessage::CloseWindow => { let _ = self.windows.remove(&id); + return window::close(id); } WindowMessage::Resized(pane_grid::ResizeEvent { split, ratio }) => { let window = self.windows.get_mut(&id).unwrap(); @@ -173,8 +174,9 @@ impl Application for Example { title: format!("New window ({})", self.windows.len()), }; - self.windows - .insert(window::Id::new(self.windows.len()), window); + let window_id = window::Id::new(self.windows.len()); + self.windows.insert(window_id, window); + return window::spawn(window_id, Default::default()); } } WindowMessage::Dragged(pane_grid::DragEvent::Dropped { @@ -243,13 +245,6 @@ impl Application for Example { }) } - fn windows(&self) -> Vec<(window::Id, iced::window::Settings)> { - self.windows - .iter() - .map(|(&id, _window)| (id, iced::window::Settings::default())) - .collect() - } - fn close_requested(&self, window: window::Id) -> Self::Message { Message::Window(window, WindowMessage::CloseWindow) } diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index 095e0e2cee..2ac7f63626 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -515,7 +515,7 @@ async fn run_instance( ); // Update window - state.synchronize(&application, &windows, &proxy); + state.synchronize(&application, &windows); let should_exit = application.should_exit(); diff --git a/glutin/src/multi_window/state.rs b/glutin/src/multi_window/state.rs index 321fc4d16f..28f4a895f9 100644 --- a/glutin/src/multi_window/state.rs +++ b/glutin/src/multi_window/state.rs @@ -1,12 +1,11 @@ use crate::application::{self, StyleSheet as _}; use crate::conversion; -use crate::multi_window::{Application, Event}; +use crate::multi_window::Application; use crate::window; use crate::{Color, Debug, Point, Size, Viewport}; use iced_winit::winit; use winit::event::{Touch, WindowEvent}; -use winit::event_loop::EventLoopProxy; use winit::window::Window; use std::collections::HashMap; @@ -189,28 +188,7 @@ where &mut self, application: &A, windows: &HashMap, - proxy: &EventLoopProxy>, ) { - let new_windows = application.windows(); - - // Check for windows to close - for window_id in windows.keys() { - if !new_windows.iter().any(|(id, _)| id == window_id) { - proxy - .send_event(Event::CloseWindow(*window_id)) - .expect("Failed to send message"); - } - } - - // Check for windows to spawn - for (id, settings) in new_windows { - if !windows.contains_key(&id) { - proxy - .send_event(Event::NewWindow(id, settings)) - .expect("Failed to send message"); - } - } - let window = windows.values().next().expect("No window found"); // Update window title diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index df45ca1eff..7d55939749 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -46,9 +46,6 @@ pub trait Application: Sized { /// title of your application when necessary. fn title(&self) -> String; - /// TODO(derezzedex) - fn windows(&self) -> Vec<(window::Id, window::Settings)>; - /// Handles a __message__ and updates the state of the [`Application`]. /// /// This is where you define your __update logic__. All the __messages__, @@ -170,16 +167,6 @@ where self.0.title() } - fn windows(&self) -> Vec<(window::Id, iced_winit::settings::Window)> { - self.0 - .windows() - .into_iter() - .map(|(id, settings)| { - (id, iced_winit::settings::Window::from(settings)) - }) - .collect() - } - fn update(&mut self, message: Self::Message) -> Command { self.0.update(message) } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 1d71d801fe..c0c233c5a2 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -68,9 +68,6 @@ where /// The type of __messages__ your [`Program`] will produce. type Message: std::fmt::Debug + Send; - /// TODO(derezzedex) - fn windows(&self) -> Vec<(window::Id, settings::Window)>; - /// Handles a __message__ and updates the state of the [`Program`]. /// /// This is where you define your __update logic__. All the __messages__, @@ -459,7 +456,7 @@ async fn run_instance( ); // Update window - state.synchronize(&application, &windows, &proxy); + state.synchronize(&application, &windows); let should_exit = application.should_exit(); diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index ae353e3bb4..a7d51df4e1 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -1,13 +1,12 @@ use crate::application::{self, StyleSheet as _}; use crate::conversion; -use crate::multi_window::{Application, Event}; +use crate::multi_window::Application; use crate::window; use crate::{Color, Debug, Point, Size, Viewport}; use std::collections::HashMap; use std::marker::PhantomData; use winit::event::{Touch, WindowEvent}; -use winit::event_loop::EventLoopProxy; use winit::window::Window; /// The state of a windowed [`Application`]. @@ -186,28 +185,7 @@ where &mut self, application: &A, windows: &HashMap, - proxy: &EventLoopProxy>, ) { - let new_windows = application.windows(); - - // Check for windows to close - for window_id in windows.keys() { - if !new_windows.iter().any(|(id, _)| id == window_id) { - proxy - .send_event(Event::CloseWindow(*window_id)) - .expect("Failed to send message"); - } - } - - // Check for windows to spawn - for (id, settings) in new_windows { - if !windows.contains_key(&id) { - proxy - .send_event(Event::NewWindow(id, settings)) - .expect("Failed to send message"); - } - } - let window = windows.values().next().expect("No window found"); // Update window title From 942f1c91afb8257e289af8d0c229f74819f68361 Mon Sep 17 00:00:00 2001 From: bungoboingo Date: Mon, 2 Jan 2023 10:58:07 -0800 Subject: [PATCH 29/66] merged in iced master --- examples/multi_window/src/main.rs | 2 +- glutin/src/multi_window.rs | 20 ++++++++++++++++++++ glutin/src/multi_window/state.rs | 4 ++-- winit/src/multi_window.rs | 20 ++++++++++++++++++++ winit/src/multi_window/state.rs | 4 ++-- 5 files changed, 45 insertions(+), 5 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 2771d7283e..9b93eea6c2 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -268,7 +268,7 @@ impl Application for Example { .spacing(5) .align_items(Alignment::Center); - let pane_grid = PaneGrid::new(&window.panes, |id, pane| { + let pane_grid = PaneGrid::new(&window.panes, |id, pane, _| { let is_focused = focus == Some(id); let pin_button = button( diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index 2ac7f63626..746da159d1 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -887,6 +887,10 @@ pub fn run_command( .send_event(Event::CloseWindow(id)) .expect("Send message to event loop"); } + window::Action::Drag => { + let window = windows.get(&id).expect("No window found"); + let _res = window.drag_window(); + } window::Action::Resize { width, height } => { let window = windows.get(&id).expect("No window found"); window.set_inner_size(winit::dpi::LogicalSize { @@ -921,6 +925,22 @@ pub fn run_command( .send_event(Event::Application(tag(mode))) .expect("Send message to event loop"); } + window::Action::Maximize(value) => { + let window = windows.get(&id).expect("No window found!"); + window.set_maximized(value); + } + window::Action::Minimize(value) => { + let window = windows.get(&id).expect("No window found!"); + window.set_minimized(value); + } + window::Action::ToggleMaximize => { + let window = windows.get(&id).expect("No window found!"); + window.set_maximized(!window.is_maximized()); + } + window::Action::ToggleDecorations => { + let window = windows.get(&id).expect("No window found!"); + window.set_decorations(!window.is_decorated()); + } }, command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { diff --git a/glutin/src/multi_window/state.rs b/glutin/src/multi_window/state.rs index 28f4a895f9..e7e8287642 100644 --- a/glutin/src/multi_window/state.rs +++ b/glutin/src/multi_window/state.rs @@ -37,7 +37,7 @@ where let title = application.title(); let scale_factor = application.scale_factor(); let theme = application.theme(); - let appearance = theme.appearance(application.style()); + let appearance = theme.appearance(&application.style()); let viewport = { let physical_size = window.inner_size(); @@ -216,6 +216,6 @@ where // Update theme and appearance self.theme = application.theme(); - self.appearance = self.theme.appearance(application.style()); + self.appearance = self.theme.appearance(&application.style()); } } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index c0c233c5a2..0a2f71ad2c 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -863,6 +863,10 @@ pub fn run_command( .send_event(Event::CloseWindow(id)) .expect("Send message to event loop"); } + window::Action::Drag => { + let window = windows.get(&id).expect("No window found"); + let _res = window.drag_window(); + } window::Action::Resize { width, height } => { let window = windows.get(&id).expect("No window found"); window.set_inner_size(winit::dpi::LogicalSize { @@ -897,6 +901,22 @@ pub fn run_command( .send_event(Event::Application(tag(mode))) .expect("Send message to event loop"); } + window::Action::Maximize(value) => { + let window = windows.get(&id).expect("No window found!"); + window.set_maximized(value); + } + window::Action::Minimize(value) => { + let window = windows.get(&id).expect("No window found!"); + window.set_minimized(value); + } + window::Action::ToggleMaximize => { + let window = windows.get(&id).expect("No window found!"); + window.set_maximized(!window.is_maximized()); + } + window::Action::ToggleDecorations => { + let window = windows.get(&id).expect("No window found!"); + window.set_decorations(!window.is_decorated()); + } }, command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index a7d51df4e1..eebdcdf15e 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -35,7 +35,7 @@ where let title = application.title(); let scale_factor = application.scale_factor(); let theme = application.theme(); - let appearance = theme.appearance(application.style()); + let appearance = theme.appearance(&application.style()); let viewport = { let physical_size = window.inner_size(); @@ -213,6 +213,6 @@ where // Update theme and appearance self.theme = application.theme(); - self.appearance = self.theme.appearance(application.style()); + self.appearance = self.theme.appearance(&application.style()); } } From f43419d4752fe18065c0e1b7c2a26e65b9d6e253 Mon Sep 17 00:00:00 2001 From: bungoboingo Date: Mon, 2 Jan 2023 18:14:31 -0800 Subject: [PATCH 30/66] Fixed issue with window ID on winit --- examples/multi_window/Cargo.toml | 1 + examples/multi_window/src/main.rs | 2 + winit/src/multi_window.rs | 110 ++++++++++++++++-------------- 3 files changed, 62 insertions(+), 51 deletions(-) diff --git a/examples/multi_window/Cargo.toml b/examples/multi_window/Cargo.toml index 9c3d0f2107..6de895d74e 100644 --- a/examples/multi_window/Cargo.toml +++ b/examples/multi_window/Cargo.toml @@ -8,5 +8,6 @@ publish = false [dependencies] iced = { path = "../..", features = ["debug", "multi_window"] } +env_logger = "0.10.0" iced_native = { path = "../../native" } iced_lazy = { path = "../../lazy" } \ No newline at end of file diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 9b93eea6c2..9fe6b481b0 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -15,6 +15,8 @@ use iced_native::{event, subscription, Event}; use std::collections::HashMap; pub fn main() -> iced::Result { + env_logger::init(); + Example::run(Settings::default()) } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 0a2f71ad2c..7d8bbc398b 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -33,7 +33,6 @@ use std::mem::ManuallyDrop; pub enum Event { /// An [`Application`] generated message Application(Message), - /// TODO(derezzedex) // Create a wrapper variant of `window::Event` type instead // (maybe we should also allow users to listen/react to those internal messages?) @@ -197,7 +196,8 @@ where .map_err(Error::WindowCreationFailed)?; let windows: HashMap = - HashMap::from([(window::Id::new(0usize), window)]); + HashMap::from([(window::Id::MAIN, window)]); + let window = windows.values().next().expect("No window found"); #[cfg(target_arch = "wasm32")] @@ -515,64 +515,72 @@ async fn run_instance( ), )); } - event::Event::UserEvent(event) => match event { - Event::Application(message) => { - messages.push(message); - } - Event::WindowCreated(id, window) => { - let mut surface = compositor.create_surface(&window); + event::Event::UserEvent(event) => { + match event { + Event::Application(message) => { + messages.push(message); + } + Event::WindowCreated(id, window) => { + let mut surface = compositor.create_surface(&window); - let state = State::new(&application, &window); + let state = State::new(&application, &window); - let physical_size = state.physical_size(); + let physical_size = state.physical_size(); - compositor.configure_surface( - &mut surface, - physical_size.width, - physical_size.height, - ); + compositor.configure_surface( + &mut surface, + physical_size.width, + physical_size.height, + ); - let user_interface = build_user_interface( - &application, - user_interface::Cache::default(), - &mut renderer, - state.logical_size(), - &mut debug, - id, - ); + let user_interface = build_user_interface( + &application, + user_interface::Cache::default(), + &mut renderer, + state.logical_size(), + &mut debug, + id, + ); - let _ = states.insert(id, state); - let _ = surfaces.insert(id, surface); - let _ = interfaces.insert(id, user_interface); - let _ = window_ids.insert(window.id(), id); - let _ = windows.insert(id, window); - } - Event::CloseWindow(id) => { - // TODO(derezzedex): log errors - if let Some(window) = windows.get(&id) { - if window_ids.remove(&window.id()).is_none() { - println!("Failed to remove from `window_ids`!"); - } - } - if states.remove(&id).is_none() { - println!("Failed to remove from `states`!") - } - if interfaces.remove(&id).is_none() { - println!("Failed to remove from `interfaces`!"); - } - if windows.remove(&id).is_none() { - println!("Failed to remove from `windows`!") - } - if surfaces.remove(&id).is_none() { - println!("Failed to remove from `surfaces`!") + let _ = states.insert(id, state); + let _ = surfaces.insert(id, surface); + let _ = interfaces.insert(id, user_interface); + let _ = window_ids.insert(window.id(), id); + let _ = windows.insert(id, window); } + Event::CloseWindow(id) => { + println!("Closing window {:?}. Total: {}", id, windows.len()); - if windows.is_empty() { - break 'main; + if let Some(window) = windows.get(&id) { + if window_ids.remove(&window.id()).is_none() { + log::error!("Failed to remove window with id {:?} from window_ids.", window.id()); + } + } else { + log::error!("Could not find window with id {:?} in windows.", id); + } + if states.remove(&id).is_none() { + log::error!("Failed to remove window {:?} from states.", id); + } + if interfaces.remove(&id).is_none() { + log::error!("Failed to remove window {:?} from interfaces.", id); + } + if windows.remove(&id).is_none() { + log::error!("Failed to remove window {:?} from windows.", id); + } + if surfaces.remove(&id).is_none() { + log::error!("Failed to remove window {:?} from surfaces.", id); + } + + if windows.is_empty() { + log::info!("All windows are closed. Terminating program."); + break 'main; + } else { + log::info!("Remaining windows: {:?}", windows.len()); + } } + Event::NewWindow(_, _) => unreachable!(), } - Event::NewWindow(_, _) => unreachable!(), - }, + } event::Event::RedrawRequested(id) => { let state = window_ids .get(&id) From 1944e98f82b7efd5b268e04ba5ced065e55a218e Mon Sep 17 00:00:00 2001 From: Bingus Date: Mon, 2 Jan 2023 21:06:59 -0800 Subject: [PATCH 31/66] Fix multi-window example for Glutin on MacOS --- glutin/Cargo.toml | 2 - glutin/src/multi_window.rs | 162 ++++++++++++++++++++----------------- winit/src/multi_window.rs | 1 + 3 files changed, 90 insertions(+), 75 deletions(-) diff --git a/glutin/Cargo.toml b/glutin/Cargo.toml index 708207804f..3f902d204e 100644 --- a/glutin/Cargo.toml +++ b/glutin/Cargo.toml @@ -24,8 +24,6 @@ version = "0.4" [dependencies.glutin] version = "0.30" -git = "https://github.com/derezzedex/glutin" -rev = "2a2a97209c49929027beced68e1989b8486bdec9" [dependencies.iced_native] version = "0.7" diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index 746da159d1..35eeeb36c8 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -23,12 +23,11 @@ use glutin::config::{ }; use glutin::context::{ ContextApi, ContextAttributesBuilder, NotCurrentContext, - NotCurrentGlContextSurfaceAccessor, - PossiblyCurrentContextGlSurfaceAccessor, PossiblyCurrentGlContext, + NotCurrentGlContextSurfaceAccessor, PossiblyCurrentGlContext, }; use glutin::display::{Display, DisplayApiPreference, GlDisplay}; use glutin::surface::{ - GlSurface, Surface, SurfaceAttributesBuilder, WindowSurface, + GlSurface, Surface, SurfaceAttributesBuilder, SwapInterval, WindowSurface, }; use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; @@ -240,42 +239,19 @@ where ) })?; - let (width, height) = window.inner_size().into(); - let surface_attributes = - SurfaceAttributesBuilder::::new() - .with_srgb(Some(true)) - .build( - window_handle, - NonZeroU32::new(width).unwrap_or(ONE), - NonZeroU32::new(height).unwrap_or(ONE), - ); - - let surface = display - .create_window_surface(configuration.as_ref(), &surface_attributes) - .map_err(|error| { - Error::GraphicsCreationFailed( - iced_graphics::Error::BackendError(format!( - "failed to create surface: {error}" - )), - ) - })?; - - let context = { - context - .make_current(&surface) - .expect("make context current") - }; - - if let Err(error) = surface.set_swap_interval( - &context, - glutin::surface::SwapInterval::Wait(ONE), - ) { - log::error!("set swap interval failed: {}", error); - } + let surface = gl_surface(&display, configuration.as_ref(), &window); (display, window, configuration.0, surface, context) }; + let windows: HashMap = + HashMap::from([(window::Id::MAIN, window)]); + + // need to make context current before trying to load GL functions + let context = context + .make_current(&surface) + .expect("Make context current."); + #[allow(unsafe_code)] let (compositor, renderer) = unsafe { C::new(compositor_settings, |address| { @@ -284,7 +260,7 @@ where })? }; - let context = { context.make_not_current().expect("make context current") }; + let context = context.make_not_current().expect("Make not current."); let (mut sender, receiver) = mpsc::unbounded(); @@ -297,9 +273,8 @@ where debug, receiver, display, - window, + windows, configuration, - surface, context, init_command, settings.exit_on_close_request, @@ -370,10 +345,9 @@ async fn run_instance( winit::event::Event<'_, Event>, >, display: Display, - window: winit::window::Window, + mut windows: HashMap, configuration: Config, - surface: Surface, - context: NotCurrentContext, + mut context: NotCurrentContext, init_command: Command, _exit_on_close_request: bool, ) where @@ -385,34 +359,48 @@ async fn run_instance( use iced_winit::futures::stream::StreamExt; use winit::event; - let context = { - context - .make_current(&surface) - .expect("make context current") - }; - - let mut clipboard = Clipboard::connect(&window); + let mut clipboard = + Clipboard::connect(windows.values().next().expect("No window found")); let mut cache = user_interface::Cache::default(); - let state = State::new(&application, &window); - let user_interface = multi_window::build_user_interface( - &application, - user_interface::Cache::default(), - &mut renderer, - state.logical_size(), - &mut debug, - window::Id::MAIN, - ); + let mut current_context_window = None; + let mut window_ids: HashMap<_, _> = windows + .iter() + .map(|(&id, window)| (window.id(), id)) + .collect(); + let mut states = HashMap::new(); + let mut surfaces = HashMap::new(); + let mut interfaces = ManuallyDrop::new(HashMap::new()); + + for (&id, window) in windows.keys().zip(windows.values()) { + let surface = gl_surface(&display, &configuration, &window); + let current_context = context.make_current(&surface).expect("Make current."); + let state = State::new(&application, &window); + let physical_size = state.physical_size(); + + surface.resize( + ¤t_context, + NonZeroU32::new(physical_size.width).unwrap_or(ONE), + NonZeroU32::new(physical_size.height).unwrap_or(ONE), + ); - let mut current_context_window = window.id(); - let mut window_ids = HashMap::from([(window.id(), window::Id::MAIN)]); - let mut windows = HashMap::from([(window::Id::MAIN, window)]); - let mut surfaces = HashMap::from([(window::Id::MAIN, surface)]); - let mut states = HashMap::from([(window::Id::MAIN, state)]); - let mut interfaces = - ManuallyDrop::new(HashMap::from([(window::Id::MAIN, user_interface)])); + let user_interface = multi_window::build_user_interface( + &application, + user_interface::Cache::default(), + &mut renderer, + state.logical_size(), + &mut debug, + id, + ); + + context = current_context.make_not_current().expect("Make not current."); + + let _ = states.insert(id, state); + let _ = surfaces.insert(id, surface); + let _ = interfaces.insert(id, user_interface); + } { - let state = states.get(&window::Id::MAIN).unwrap(); + let state = states.values().next().expect("No state found."); run_command( &application, @@ -653,12 +641,11 @@ async fn run_instance( debug.render_started(); - if current_context_window != id { - context - .make_current(&surface) - .expect("Make OpenGL context current"); + let current_context = + context.make_current(&surface).expect("Make current."); - current_context_window = id; + if current_context_window != Some(id) { + current_context_window = Some(id); } if state.viewport_changed() { @@ -695,11 +682,17 @@ async fn run_instance( } surface.resize( - &context, + ¤t_context, NonZeroU32::new(physical_size.width).unwrap_or(ONE), NonZeroU32::new(physical_size.height).unwrap_or(ONE), ); + if let Err(error) = + surface.set_swap_interval(¤t_context, SwapInterval::Wait(ONE)) + { + log::error!("Could not set swap interval for surface attached to window id: {:?}", id); + } + compositor.resize_viewport(physical_size); let _ = interfaces @@ -713,10 +706,10 @@ async fn run_instance( &debug.overlay(), ); - surface.swap_buffers(&context).expect("Swap buffers"); + surface.swap_buffers(¤t_context).expect("Swap buffers"); + context = current_context.make_not_current().expect("Make not current."); debug.render_finished(); - // TODO: Handle animations! // Maybe we can use `ControlFlow::WaitUntil` for this. } @@ -1038,3 +1031,26 @@ where interfaces } + +#[allow(unsafe_code)] +fn gl_surface( + display: &Display, + gl_config: &Config, + window: &winit::window::Window, +) -> Surface { + let (width, height) = window.inner_size().into(); + + let surface_attributes = SurfaceAttributesBuilder::::new() + .with_srgb(Some(true)) + .build( + window.raw_window_handle(), + NonZeroU32::new(width).unwrap_or(ONE), + NonZeroU32::new(height).unwrap_or(ONE), + ); + + unsafe { + display + .create_window_surface(gl_config, &surface_attributes) + .expect("failed to create surface") + } +} diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 7d8bbc398b..43455148d2 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -320,6 +320,7 @@ async fn run_instance( for (&id, window) in windows.keys().zip(windows.values()) { let mut surface = compositor.create_surface(window); + println!("Creating surface for window: {:?}", window); let state = State::new(&application, window); From ec41918ec40bddaba81235372f1566da59fd09f2 Mon Sep 17 00:00:00 2001 From: bungoboingo Date: Thu, 5 Jan 2023 15:26:28 -0800 Subject: [PATCH 32/66] Implemented window title update functionality for multiwindow. --- examples/multi_window/Cargo.toml | 2 +- examples/multi_window/src/main.rs | 10 +- glutin/src/application.rs | 33 ++++-- glutin/src/multi_window.rs | 156 ++++++++++-------------- glutin/src/multi_window/state.rs | 14 +-- native/src/window.rs | 4 +- native/src/window/action.rs | 8 +- native/src/window/icon.rs | 6 +- native/src/window/id.rs | 13 +- src/multi_window/application.rs | 8 +- winit/src/application.rs | 2 +- winit/src/multi_window.rs | 190 ++++++++++++++++++------------ winit/src/multi_window/state.rs | 14 +-- winit/src/window.rs | 37 +++--- 14 files changed, 262 insertions(+), 235 deletions(-) diff --git a/examples/multi_window/Cargo.toml b/examples/multi_window/Cargo.toml index 6de895d74e..621985950f 100644 --- a/examples/multi_window/Cargo.toml +++ b/examples/multi_window/Cargo.toml @@ -10,4 +10,4 @@ publish = false iced = { path = "../..", features = ["debug", "multi_window"] } env_logger = "0.10.0" iced_native = { path = "../../native" } -iced_lazy = { path = "../../lazy" } \ No newline at end of file +iced_lazy = { path = "../../lazy" } diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 9fe6b481b0..b9f0514c67 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -26,6 +26,7 @@ struct Example { _focused: window::Id, } +#[derive(Debug)] struct Window { title: String, panes: pane_grid::State, @@ -80,8 +81,11 @@ impl Application for Example { ) } - fn title(&self) -> String { - String::from("Multi windowed pane grid - Iced") + fn title(&self, window: window::Id) -> String { + self.windows + .get(&window) + .map(|w| w.title.clone()) + .unwrap_or(String::from("New Window")) } fn update(&mut self, message: Message) -> Command { @@ -262,7 +266,6 @@ impl Application for Example { &window.title, WindowMessage::TitleChanged, ), - button(text("Apply")).style(theme::Button::Primary), button(text("Close")) .on_press(WindowMessage::CloseWindow) .style(theme::Button::Destructive), @@ -389,6 +392,7 @@ impl std::fmt::Display for SelectableWindow { } } +#[derive(Debug)] struct Pane { id: usize, pub axis: pane_grid::Axis, diff --git a/glutin/src/application.rs b/glutin/src/application.rs index 45ff37f009..f43a47b927 100644 --- a/glutin/src/application.rs +++ b/glutin/src/application.rs @@ -245,18 +245,7 @@ where ) })?; - let (width, height) = window.inner_size().into(); - let surface_attributes = - SurfaceAttributesBuilder::::new() - .with_srgb(Some(true)) - .build( - window_handle, - NonZeroU32::new(width).unwrap_or(ONE), - NonZeroU32::new(height).unwrap_or(ONE), - ); - - let surface = display - .create_window_surface(configuration.as_ref(), &surface_attributes) + let surface = gl_surface(&display, configuration.as_ref(), &window) .map_err(|error| { Error::GraphicsCreationFailed( iced_graphics::Error::BackendError(format!( @@ -616,3 +605,23 @@ async fn run_instance( // Manually drop the user interface drop(ManuallyDrop::into_inner(user_interface)); } + +#[allow(unsafe_code)] +/// Creates a new [`glutin::Surface`]. +pub fn gl_surface( + display: &Display, + gl_config: &Config, + window: &winit::window::Window, +) -> Result, glutin::error::Error> { + let (width, height) = window.inner_size().into(); + + let surface_attributes = SurfaceAttributesBuilder::::new() + .with_srgb(Some(true)) + .build( + window.raw_window_handle(), + NonZeroU32::new(width).unwrap_or(ONE), + NonZeroU32::new(height).unwrap_or(ONE), + ); + + unsafe { display.create_window_surface(gl_config, &surface_attributes) } +} diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index 35eeeb36c8..e79ec77d38 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -12,7 +12,6 @@ use iced_winit::conversion; use iced_winit::futures; use iced_winit::futures::channel::mpsc; use iced_winit::renderer; -use iced_winit::settings; use iced_winit::user_interface; use iced_winit::window; use iced_winit::winit; @@ -26,11 +25,12 @@ use glutin::context::{ NotCurrentGlContextSurfaceAccessor, PossiblyCurrentGlContext, }; use glutin::display::{Display, DisplayApiPreference, GlDisplay}; -use glutin::surface::{ - GlSurface, Surface, SurfaceAttributesBuilder, SwapInterval, WindowSurface, -}; +use glutin::surface::{GlSurface, SwapInterval}; use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; +use crate::application::gl_surface; +use iced_native::window::Action; +use iced_winit::multi_window::Event; use std::collections::HashMap; use std::ffi::CString; use std::mem::ManuallyDrop; @@ -76,7 +76,7 @@ where }; let builder = settings.window.into_builder( - &application.title(), + &application.title(window::Id::MAIN), event_loop.primary_monitor(), settings.id, ); @@ -239,7 +239,14 @@ where ) })?; - let surface = gl_surface(&display, configuration.as_ref(), &window); + let surface = gl_surface(&display, configuration.as_ref(), &window) + .map_err(|error| { + Error::GraphicsCreationFailed( + iced_graphics::Error::BackendError(format!( + "failed to create surface: {error}" + )), + ) + })?; (display, window, configuration.0, surface, context) }; @@ -301,14 +308,13 @@ where event: winit::event::WindowEvent::Resized(*new_inner_size), window_id, }), - winit::event::Event::UserEvent(Event::NewWindow(id, settings)) => { - // TODO(derezzedex) + winit::event::Event::UserEvent(Event::NewWindow { + id, + settings, + title, + }) => { let window = settings - .into_builder( - "fix window title", - event_loop.primary_monitor(), - None, - ) + .into_builder(&title, event_loop.primary_monitor(), None) .build(event_loop) .expect("Failed to build window"); @@ -372,9 +378,11 @@ async fn run_instance( let mut interfaces = ManuallyDrop::new(HashMap::new()); for (&id, window) in windows.keys().zip(windows.values()) { - let surface = gl_surface(&display, &configuration, &window); - let current_context = context.make_current(&surface).expect("Make current."); - let state = State::new(&application, &window); + let surface = gl_surface(&display, &configuration, &window) + .expect("Create surface."); + let current_context = + context.make_current(&surface).expect("Make current."); + let state = State::new(&application, id, &window); let physical_size = state.physical_size(); surface.resize( @@ -392,7 +400,9 @@ async fn run_instance( id, ); - context = current_context.make_not_current().expect("Make not current."); + context = current_context + .make_not_current() + .expect("Make not current."); let _ = states.insert(id, state); let _ = surfaces.insert(id, surface); @@ -431,7 +441,7 @@ async fn run_instance( let (filtered, remaining): (Vec<_>, Vec<_>) = events.iter().cloned().partition( |(window_id, _event): &( - Option, + Option, iced_native::event::Event, )| { *window_id == Some(id) || *window_id == None @@ -503,7 +513,11 @@ async fn run_instance( ); // Update window - state.synchronize(&application, &windows); + state.synchronize( + &application, + id, + windows.get(&id).expect("No window found with ID."), + ); let should_exit = application.should_exit(); @@ -563,7 +577,7 @@ async fn run_instance( event::Event::UserEvent(event) => match event { Event::Application(message) => messages.push(message), Event::WindowCreated(id, window) => { - let state = State::new(&application, &window); + let state = State::new(&application, id, &window); let user_interface = multi_window::build_user_interface( &application, user_interface::Cache::default(), @@ -573,26 +587,8 @@ async fn run_instance( id, ); - let window_handle = window.raw_window_handle(); - let (width, height) = window.inner_size().into(); - let surface_attributes = - SurfaceAttributesBuilder::::new() - .with_srgb(Some(true)) - .build( - window_handle, - NonZeroU32::new(width).unwrap_or(ONE), - NonZeroU32::new(height).unwrap_or(ONE), - ); - - #[allow(unsafe_code)] - let surface = unsafe { - display - .create_window_surface( - &configuration, - &surface_attributes, - ) - .expect("failed to create surface") - }; + let surface = gl_surface(&display, &configuration, &window) + .expect("Create surface."); let _ = states.insert(id, state); let _ = interfaces.insert(id, user_interface); @@ -624,7 +620,7 @@ async fn run_instance( break 'main; } } - Event::NewWindow(_, _) => unreachable!(), + Event::NewWindow { .. } => unreachable!(), }, event::Event::RedrawRequested(id) => { let state = window_ids @@ -687,9 +683,10 @@ async fn run_instance( NonZeroU32::new(physical_size.height).unwrap_or(ONE), ); - if let Err(error) = - surface.set_swap_interval(¤t_context, SwapInterval::Wait(ONE)) - { + if let Err(_) = surface.set_swap_interval( + ¤t_context, + SwapInterval::Wait(ONE), + ) { log::error!("Could not set swap interval for surface attached to window id: {:?}", id); } @@ -706,9 +703,13 @@ async fn run_instance( &debug.overlay(), ); - surface.swap_buffers(¤t_context).expect("Swap buffers"); + surface + .swap_buffers(¤t_context) + .expect("Swap buffers"); - context = current_context.make_not_current().expect("Make not current."); + context = current_context + .make_not_current() + .expect("Make not current."); debug.render_finished(); // TODO: Handle animations! // Maybe we can use `ControlFlow::WaitUntil` for this. @@ -751,11 +752,10 @@ async fn run_instance( )); } } else { - // TODO(derezzedex): log error + log::error!("Window state not found for id: {:?}", window_id); } } else { - // TODO(derezzedex): log error - // println!("{:?}: {:?}", window_id, window_event); + log::error!("Window not found for id: {:?}", window_id); } } _ => {} @@ -766,25 +766,6 @@ async fn run_instance( // drop(ManuallyDrop::into_inner(user_interface)); } -/// TODO(derezzedex): -// This is the an wrapper around the `Application::Message` associate type -// to allows the `shell` to create internal messages, while still having -// the current user specified custom messages. -#[derive(Debug)] -pub enum Event { - /// An [`Application`] generated message - Application(Message), - - /// TODO(derezzedex) - // Create a wrapper variant of `window::Event` type instead - // (maybe we should also allow users to listen/react to those internal messages?) - NewWindow(window::Id, settings::Window), - /// TODO(derezzedex) - CloseWindow(window::Id), - /// TODO(derezzedex) - WindowCreated(window::Id, winit::window::Window), -} - /// Updates an [`Application`] by feeding it the provided messages, spawning any /// resulting [`Command`], and tracking its [`Subscription`]. pub fn update( @@ -872,7 +853,11 @@ pub fn run_command( command::Action::Window(id, action) => match action { window::Action::Spawn { settings } => { proxy - .send_event(Event::NewWindow(id, settings.into())) + .send_event(Event::NewWindow { + id, + settings: settings.into(), + title: application.title(id), + }) .expect("Send message to event loop"); } window::Action::Close => { @@ -934,6 +919,16 @@ pub fn run_command( let window = windows.get(&id).expect("No window found!"); window.set_decorations(!window.is_decorated()); } + Action::RequestUserAttention(attention_type) => { + let window = windows.get(&id).expect("No window found!"); + window.request_user_attention( + attention_type.map(conversion::user_attention), + ); + } + Action::GainFocus => { + let window = windows.get(&id).expect("No window found!"); + window.focus_window(); + } }, command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { @@ -1031,26 +1026,3 @@ where interfaces } - -#[allow(unsafe_code)] -fn gl_surface( - display: &Display, - gl_config: &Config, - window: &winit::window::Window, -) -> Surface { - let (width, height) = window.inner_size().into(); - - let surface_attributes = SurfaceAttributesBuilder::::new() - .with_srgb(Some(true)) - .build( - window.raw_window_handle(), - NonZeroU32::new(width).unwrap_or(ONE), - NonZeroU32::new(height).unwrap_or(ONE), - ); - - unsafe { - display - .create_window_surface(gl_config, &surface_attributes) - .expect("failed to create surface") - } -} diff --git a/glutin/src/multi_window/state.rs b/glutin/src/multi_window/state.rs index e7e8287642..04ec508352 100644 --- a/glutin/src/multi_window/state.rs +++ b/glutin/src/multi_window/state.rs @@ -8,7 +8,6 @@ use iced_winit::winit; use winit::event::{Touch, WindowEvent}; use winit::window::Window; -use std::collections::HashMap; use std::marker::PhantomData; /// The state of a windowed [`Application`]. @@ -33,8 +32,8 @@ where ::Theme: application::StyleSheet, { /// Creates a new [`State`] for the provided [`Application`] and window. - pub fn new(application: &A, window: &Window) -> Self { - let title = application.title(); + pub fn new(application: &A, window_id: window::Id, window: &Window) -> Self { + let title = application.title(window_id); let scale_factor = application.scale_factor(); let theme = application.theme(); let appearance = theme.appearance(&application.style()); @@ -67,7 +66,7 @@ where &self.viewport } - /// TODO(derezzedex) + /// Returns whether or not the current [`Viewport`] has changed. pub fn viewport_changed(&self) -> bool { self.viewport_changed } @@ -187,12 +186,11 @@ where pub fn synchronize( &mut self, application: &A, - windows: &HashMap, + window_id: window::Id, + window: &Window, ) { - let window = windows.values().next().expect("No window found"); - // Update window title - let new_title = application.title(); + let new_title = application.title(window_id); if self.title != new_title { window.set_title(&new_title); diff --git a/native/src/window.rs b/native/src/window.rs index 1c03fcdff0..96a5fe61cb 100644 --- a/native/src/window.rs +++ b/native/src/window.rs @@ -4,6 +4,8 @@ mod event; mod icon; mod id; mod mode; +mod position; +mod settings; mod user_attention; pub use action::Action; @@ -11,6 +13,6 @@ pub use event::Event; pub use icon::Icon; pub use id::Id; pub use mode::Mode; -pub use user_attention::UserAttention; pub use position::Position; pub use settings::Settings; +pub use user_attention::UserAttention; diff --git a/native/src/window/action.rs b/native/src/window/action.rs index 0587f25c33..929663ec56 100644 --- a/native/src/window/action.rs +++ b/native/src/window/action.rs @@ -1,4 +1,4 @@ -use crate::window::{self, Mode, UserAttention}; +use crate::window; use iced_futures::MaybeSend; use std::fmt; @@ -13,9 +13,9 @@ pub enum Action { /// There’s no guarantee that this will work unless the left mouse /// button was pressed immediately before this function is called. Drag, - /// TODO(derezzedex) + /// Spawns a new window with the provided [`window::Settings`]. Spawn { - /// TODO(derezzedex) + /// The settings of the [`Window`]. settings: window::Settings, }, /// Resize the window. @@ -62,7 +62,7 @@ pub enum Action { /// - **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(Option), + RequestUserAttention(Option), /// Brings the window to the front and sets input focus. Has no effect if the window is /// already in focus, minimized, or not visible. /// diff --git a/native/src/window/icon.rs b/native/src/window/icon.rs index e89baf03eb..08a6acfd86 100644 --- a/native/src/window/icon.rs +++ b/native/src/window/icon.rs @@ -3,10 +3,10 @@ /// The icon of a window. #[derive(Debug, Clone)] pub struct Icon { - /// TODO(derezzedex) + /// The __rgba__ color data of the window [`Icon`]. pub rgba: Vec, - /// TODO(derezzedex) + /// The width of the window [`Icon`]. pub width: u32, - /// TODO(derezzedex) + /// The height of the window [`Icon`]. pub height: u32, } diff --git a/native/src/window/id.rs b/native/src/window/id.rs index 5060e162af..fa9761f586 100644 --- a/native/src/window/id.rs +++ b/native/src/window/id.rs @@ -1,15 +1,18 @@ use std::collections::hash_map::DefaultHasher; +use std::fmt::{Display, Formatter}; use std::hash::{Hash, Hasher}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -/// TODO(derezzedex) +/// The ID of the window. +/// +/// This is not necessarily the same as the window ID fetched from `winit::window::Window`. pub struct Id(u64); impl Id { /// TODO(derezzedex): maybe change `u64` to an enum `Type::{Single, Multi(u64)}` pub const MAIN: Self = Id(0); - /// TODO(derezzedex) + /// Creates a new unique window ID. pub fn new(id: impl Hash) -> Id { let mut hasher = DefaultHasher::new(); id.hash(&mut hasher); @@ -17,3 +20,9 @@ impl Id { Id(hasher.finish()) } } + +impl Display for Id { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "Id({})", self.0) + } +} diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index 7d55939749..dc1ac5b041 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -44,7 +44,7 @@ pub trait Application: Sized { /// /// This title can be dynamic! The runtime will automatically update the /// title of your application when necessary. - fn title(&self) -> String; + fn title(&self, window: window::Id) -> String; /// Handles a __message__ and updates the state of the [`Application`]. /// @@ -110,7 +110,7 @@ pub trait Application: Sized { false } - /// TODO(derezzedex) + /// Requests that the [`window`] be closed. fn close_requested(&self, window: window::Id) -> Self::Message; /// Runs the [`Application`]. @@ -163,8 +163,8 @@ where (Instance(app), command) } - fn title(&self) -> String { - self.0.title() + fn title(&self, window: window::Id) -> String { + self.0.title(window) } fn update(&mut self, message: Self::Message) -> Command { diff --git a/winit/src/application.rs b/winit/src/application.rs index 910f3d94ff..eef6833cf5 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -675,7 +675,7 @@ pub fn run_command( window::Action::Drag => { let _res = window.drag_window(); } - window::Action::Spawn { .. } | window::Action::Close => { + window::Action::Spawn { .. } => { log::info!( "This is only available on `multi_window::Application`" ) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 43455148d2..6a2bdca92a 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -22,6 +22,7 @@ use iced_native::user_interface::{self, UserInterface}; pub use iced_native::application::{Appearance, StyleSheet}; +use iced_native::window::Action; use std::collections::HashMap; use std::mem::ManuallyDrop; @@ -36,7 +37,14 @@ pub enum Event { /// TODO(derezzedex) // Create a wrapper variant of `window::Event` type instead // (maybe we should also allow users to listen/react to those internal messages?) - NewWindow(window::Id, settings::Window), + NewWindow { + /// The [window::Id] of the newly spawned [`Window`]. + id: window::Id, + /// The [settings::Window] of the newly spawned [`Window`]. + settings: settings::Window, + /// The title of the newly spawned [`Window`]. + title: String, + }, /// TODO(derezzedex) CloseWindow(window::Id), /// TODO(derezzedex) @@ -95,11 +103,11 @@ where /// load state from a file, perform an initial HTTP request, etc. fn new(flags: Self::Flags) -> (Self, Command); - /// Returns the current title of the [`Application`]. + /// Returns the current title of the current [`Application`] window. /// /// This title can be dynamic! The runtime will automatically update the /// title of your application when necessary. - fn title(&self) -> String; + fn title(&self, window_id: window::Id) -> String; /// Returns the current [`Theme`] of the [`Application`]. fn theme(&self) -> ::Theme; @@ -144,7 +152,7 @@ where false } - /// TODO(derezzedex) + /// Requests that the [`window`] be closed. fn close_requested(&self, window: window::Id) -> Self::Message; } @@ -184,7 +192,7 @@ where }; let builder = settings.window.into_builder( - &application.title(), + &application.title(window::Id::MAIN), event_loop.primary_monitor(), settings.id, ); @@ -253,14 +261,13 @@ where event: winit::event::WindowEvent::Resized(*new_inner_size), window_id, }), - winit::event::Event::UserEvent(Event::NewWindow(id, settings)) => { - // TODO(derezzedex) + winit::event::Event::UserEvent(Event::NewWindow { + id, + settings, + title, + }) => { let window = settings - .into_builder( - "fix window title", - event_loop.primary_monitor(), - None, - ) + .into_builder(&title, event_loop.primary_monitor(), None) .build(event_loop) .expect("Failed to build window"); @@ -320,10 +327,7 @@ async fn run_instance( for (&id, window) in windows.keys().zip(windows.values()) { let mut surface = compositor.create_surface(window); - println!("Creating surface for window: {:?}", window); - - let state = State::new(&application, window); - + let state = State::new(&application, id, window); let physical_size = state.physical_size(); compositor.configure_surface( @@ -457,7 +461,11 @@ async fn run_instance( ); // Update window - state.synchronize(&application, &windows); + state.synchronize( + &application, + id, + windows.get(&id).expect("No window found with ID."), + ); let should_exit = application.should_exit(); @@ -516,72 +524,85 @@ async fn run_instance( ), )); } - event::Event::UserEvent(event) => { - match event { - Event::Application(message) => { - messages.push(message); - } - Event::WindowCreated(id, window) => { - let mut surface = compositor.create_surface(&window); - - let state = State::new(&application, &window); + event::Event::UserEvent(event) => match event { + Event::Application(message) => { + messages.push(message); + } + Event::WindowCreated(id, window) => { + let mut surface = compositor.create_surface(&window); - let physical_size = state.physical_size(); + let state = State::new(&application, id, &window); - compositor.configure_surface( - &mut surface, - physical_size.width, - physical_size.height, - ); + let physical_size = state.physical_size(); - let user_interface = build_user_interface( - &application, - user_interface::Cache::default(), - &mut renderer, - state.logical_size(), - &mut debug, - id, - ); + compositor.configure_surface( + &mut surface, + physical_size.width, + physical_size.height, + ); - let _ = states.insert(id, state); - let _ = surfaces.insert(id, surface); - let _ = interfaces.insert(id, user_interface); - let _ = window_ids.insert(window.id(), id); - let _ = windows.insert(id, window); - } - Event::CloseWindow(id) => { - println!("Closing window {:?}. Total: {}", id, windows.len()); + let user_interface = build_user_interface( + &application, + user_interface::Cache::default(), + &mut renderer, + state.logical_size(), + &mut debug, + id, + ); - if let Some(window) = windows.get(&id) { - if window_ids.remove(&window.id()).is_none() { - log::error!("Failed to remove window with id {:?} from window_ids.", window.id()); - } - } else { - log::error!("Could not find window with id {:?} in windows.", id); - } - if states.remove(&id).is_none() { - log::error!("Failed to remove window {:?} from states.", id); - } - if interfaces.remove(&id).is_none() { - log::error!("Failed to remove window {:?} from interfaces.", id); - } - if windows.remove(&id).is_none() { - log::error!("Failed to remove window {:?} from windows.", id); - } - if surfaces.remove(&id).is_none() { - log::error!("Failed to remove window {:?} from surfaces.", id); + let _ = states.insert(id, state); + let _ = surfaces.insert(id, surface); + let _ = interfaces.insert(id, user_interface); + let _ = window_ids.insert(window.id(), id); + let _ = windows.insert(id, window); + } + Event::CloseWindow(id) => { + if let Some(window) = windows.get(&id) { + if window_ids.remove(&window.id()).is_none() { + log::error!("Failed to remove window with id {:?} from window_ids.", window.id()); } + } else { + log::error!( + "Could not find window with id {:?} in windows.", + id + ); + } + if states.remove(&id).is_none() { + log::error!( + "Failed to remove window {:?} from states.", + id + ); + } + if interfaces.remove(&id).is_none() { + log::error!( + "Failed to remove window {:?} from interfaces.", + id + ); + } + if windows.remove(&id).is_none() { + log::error!( + "Failed to remove window {:?} from windows.", + id + ); + } + if surfaces.remove(&id).is_none() { + log::error!( + "Failed to remove window {:?} from surfaces.", + id + ); + } - if windows.is_empty() { - log::info!("All windows are closed. Terminating program."); - break 'main; - } else { - log::info!("Remaining windows: {:?}", windows.len()); - } + if windows.is_empty() { + log::info!( + "All windows are closed. Terminating program." + ); + break 'main; + } else { + log::info!("Remaining windows: {:?}", windows.len()); } - Event::NewWindow(_, _) => unreachable!(), } - } + Event::NewWindow { .. } => unreachable!(), + }, event::Event::RedrawRequested(id) => { let state = window_ids .get(&id) @@ -716,11 +737,10 @@ async fn run_instance( )); } } else { - // TODO(derezzedex): log error + log::error!("No window state found for id: {:?}", window_id); } } else { - // TODO(derezzedex): log error - // println!("{:?}: {:?}", window_id, window_event); + log::error!("No window found with id: {:?}", window_id); } } _ => {} @@ -864,7 +884,11 @@ pub fn run_command( command::Action::Window(id, action) => match action { window::Action::Spawn { settings } => { proxy - .send_event(Event::NewWindow(id, settings.into())) + .send_event(Event::NewWindow { + id, + settings: settings.into(), + title: application.title(id), + }) .expect("Send message to event loop"); } window::Action::Close => { @@ -926,6 +950,16 @@ pub fn run_command( let window = windows.get(&id).expect("No window found!"); window.set_decorations(!window.is_decorated()); } + window::Action::RequestUserAttention(attention_type) => { + let window = windows.get(&id).expect("No window found!"); + window.request_user_attention( + attention_type.map(conversion::user_attention), + ); + } + Action::GainFocus => { + let window = windows.get(&id).expect("No window found!"); + window.focus_window(); + } }, command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index eebdcdf15e..7a598b9863 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -4,7 +4,6 @@ use crate::multi_window::Application; use crate::window; use crate::{Color, Debug, Point, Size, Viewport}; -use std::collections::HashMap; use std::marker::PhantomData; use winit::event::{Touch, WindowEvent}; use winit::window::Window; @@ -31,8 +30,8 @@ where ::Theme: application::StyleSheet, { /// Creates a new [`State`] for the provided [`Application`] and window. - pub fn new(application: &A, window: &Window) -> Self { - let title = application.title(); + pub fn new(application: &A, window_id: window::Id, window: &Window) -> Self { + let title = application.title(window_id); let scale_factor = application.scale_factor(); let theme = application.theme(); let appearance = theme.appearance(&application.style()); @@ -65,7 +64,7 @@ where &self.viewport } - /// TODO(derezzedex) + /// Returns whether or not the viewport changed. pub fn viewport_changed(&self) -> bool { self.viewport_changed } @@ -184,12 +183,11 @@ where pub fn synchronize( &mut self, application: &A, - windows: &HashMap, + window_id: window::Id, + window: &Window, ) { - let window = windows.values().next().expect("No window found"); - // Update window title - let new_title = application.title(); + let new_title = application.title(window_id); if self.title != new_title { window.set_title(&new_title); diff --git a/winit/src/window.rs b/winit/src/window.rs index fba863ef6c..5a8ff6df0f 100644 --- a/winit/src/window.rs +++ b/winit/src/window.rs @@ -2,19 +2,19 @@ use crate::command::{self, Command}; use iced_native::window; -pub use window::{Id, Event, Mode, UserAttention}; +pub use window::{Event, Id, Mode, UserAttention}; -/// Closes the current window and exits the application. -pub fn close() -> Command { - Command::single(command::Action::Window(window::Action::Close)) +/// Closes the window. +pub fn close(id: window::Id) -> Command { + Command::single(command::Action::Window(id, window::Action::Close)) } /// Begins dragging the window while the left mouse button is held. -pub fn drag() -> Command { - Command::single(command::Action::Window(window::Action::Drag)) +pub fn drag(id: window::Id) -> Command { + Command::single(command::Action::Window(id, window::Action::Drag)) } -/// TODO(derezzedex) +/// Spawns a new window. pub fn spawn( id: window::Id, settings: window::Settings, @@ -25,11 +25,6 @@ pub fn spawn( )) } -/// TODO(derezzedex) -pub fn close(id: window::Id) -> Command { - Command::single(command::Action::Window(id, window::Action::Close)) -} - /// Resizes the window to the given logical dimensions. pub fn resize( id: window::Id, @@ -43,13 +38,19 @@ pub fn resize( } /// Sets the window to maximized or back. -pub fn maximize(value: bool) -> Command { - Command::single(command::Action::Window(window::Action::Maximize(value))) +pub fn maximize(id: window::Id, value: bool) -> Command { + Command::single(command::Action::Window( + id, + window::Action::Maximize(value), + )) } /// Set the window to minimized or back. -pub fn minimize(value: bool) -> Command { - Command::single(command::Action::Window(window::Action::Minimize(value))) +pub fn minimize(id: window::Id, value: bool) -> Command { + Command::single(command::Action::Window( + id, + window::Action::Minimize(value), + )) } /// Moves a window to the given logical coordinates. @@ -63,8 +64,8 @@ pub fn set_mode(id: window::Id, mode: Mode) -> Command { } /// Sets the window to maximized or back. -pub fn toggle_maximize() -> Command { - Command::single(command::Action::Window(window::Action::ToggleMaximize)) +pub fn toggle_maximize(id: window::Id) -> Command { + Command::single(command::Action::Window(id, window::Action::ToggleMaximize)) } /// Fetches the current [`Mode`] of the window. From 3e5d34f25fa07fa99f57b686bbde87d73b8ed548 Mon Sep 17 00:00:00 2001 From: bungoboingo Date: Mon, 9 Jan 2023 10:19:12 -0800 Subject: [PATCH 33/66] Formatting --- examples/multi_window/src/main.rs | 10 ++-- glutin/src/multi_window/state.rs | 8 +++- src/multi_window/application.rs | 79 +++++++++++++++++++++++++------ winit/src/multi_window/state.rs | 9 ++-- 4 files changed, 81 insertions(+), 25 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index b9f0514c67..18536bdf36 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -57,9 +57,9 @@ enum WindowMessage { } impl Application for Example { + type Executor = executor::Default; type Message = Message; type Theme = Theme; - type Executor = executor::Default; type Flags = (); fn new(_flags: ()) -> (Self, Command) { @@ -251,10 +251,6 @@ impl Application for Example { }) } - fn close_requested(&self, window: window::Id) -> Self::Message { - Message::Window(window, WindowMessage::CloseWindow) - } - fn view(&self, window_id: window::Id) -> Element { if let Some(window) = self.windows.get(&window_id) { let focus = window.focus; @@ -342,6 +338,10 @@ impl Application for Example { .center_y() .into() } + + fn close_requested(&self, window: window::Id) -> Self::Message { + Message::Window(window, WindowMessage::CloseWindow) + } } const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb( diff --git a/glutin/src/multi_window/state.rs b/glutin/src/multi_window/state.rs index 04ec508352..8ed134b2f6 100644 --- a/glutin/src/multi_window/state.rs +++ b/glutin/src/multi_window/state.rs @@ -31,8 +31,12 @@ impl State where ::Theme: application::StyleSheet, { - /// Creates a new [`State`] for the provided [`Application`] and window. - pub fn new(application: &A, window_id: window::Id, window: &Window) -> Self { + /// Creates a new [`State`] for the provided [`Application`]'s window. + pub fn new( + application: &A, + window_id: window::Id, + window: &Window, + ) -> Self { let title = application.title(window_id); let scale_factor = application.scale_factor(); let theme = application.theme(); diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index dc1ac5b041..3f20382cd0 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -3,13 +3,62 @@ use crate::{Command, Element, Executor, Settings, Subscription}; pub use iced_native::application::{Appearance, StyleSheet}; -/// A pure version of [`Application`]. +/// An interactive cross-platform multi-window application. /// -/// Unlike the impure version, the `view` method of this trait takes an -/// immutable reference to `self` and returns a pure [`Element`]. +/// This trait is the main entrypoint of Iced. Once implemented, you can run +/// your GUI application by simply calling [`run`](#method.run). /// -/// [`Application`]: crate::Application -/// [`Element`]: pure::Element +/// An [`Application`] can execute asynchronous actions by returning a +/// [`Command`] in some of its methods. For example, to spawn a new window, you +/// can use the `iced_winit::window::spawn()` [`Command`]. +/// +/// When using an [`Application`] with the `debug` feature enabled, a debug view +/// can be toggled by pressing `F12`. +/// +/// ## A simple "Hello, world!" +/// +/// If you just want to get started, here is a simple [`Application`] that +/// says "Hello, world!": +/// +/// ```no_run +/// use iced::executor; +/// use iced::multi_window::Application; +/// use iced::window; +/// use iced::{Command, Element, Settings, Theme}; +/// +/// pub fn main() -> iced::Result { +/// Hello::run(Settings::default()) +/// } +/// +/// struct Hello; +/// +/// impl Application for Hello { +/// type Executor = executor::Default; +/// type Message = (); +/// type Theme = Theme; +/// type Flags = (); +/// +/// fn new(_flags: ()) -> (Hello, Command) { +/// (Hello, Command::none()) +/// } +/// +/// fn title(&self, window: window::Id) -> String { +/// String::from("A cool application") +/// } +/// +/// fn update(&mut self, _message: Self::Message) -> Command { +/// Command::none() +/// } +/// +/// fn view(&self, window: window::Id) -> Element { +/// "Hello, world!".into() +/// } +/// +/// fn close_requested(&self, window: window::Id) -> Self::Message { +/// () +/// } +/// } +/// ``` pub trait Application: Sized { /// The [`Executor`] that will run commands and subscriptions. /// @@ -157,16 +206,6 @@ where type Renderer = crate::Renderer; type Message = A::Message; - fn new(flags: Self::Flags) -> (Self, Command) { - let (app, command) = A::new(flags); - - (Instance(app), command) - } - - fn title(&self, window: window::Id) -> String { - self.0.title(window) - } - fn update(&mut self, message: Self::Message) -> Command { self.0.update(message) } @@ -178,6 +217,16 @@ where self.0.view(window) } + fn new(flags: Self::Flags) -> (Self, Command) { + let (app, command) = A::new(flags); + + (Instance(app), command) + } + + fn title(&self, window: window::Id) -> String { + self.0.title(window) + } + fn theme(&self) -> A::Theme { self.0.theme() } diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index 7a598b9863..2c2a4693b9 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -29,8 +29,12 @@ impl State where ::Theme: application::StyleSheet, { - /// Creates a new [`State`] for the provided [`Application`] and window. - pub fn new(application: &A, window_id: window::Id, window: &Window) -> Self { + /// Creates a new [`State`] for the provided [`Application`]'s window. + pub fn new( + application: &A, + window_id: window::Id, + window: &Window, + ) -> Self { let title = application.title(window_id); let scale_factor = application.scale_factor(); let theme = application.theme(); @@ -191,7 +195,6 @@ where if self.title != new_title { window.set_title(&new_title); - self.title = new_title; } From f78ccd9af9ced4c18ed4b56cbf838c6c5a5119ad Mon Sep 17 00:00:00 2001 From: bungoboingo Date: Mon, 9 Jan 2023 11:48:34 -0800 Subject: [PATCH 34/66] Removed glutin's individual multi_window state since 0.30+ doesn't have its own event crate anymore --- glutin/src/multi_window.rs | 14 +- glutin/src/multi_window/state.rs | 223 ------------------------------- 2 files changed, 5 insertions(+), 232 deletions(-) delete mode 100644 glutin/src/multi_window/state.rs diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index e79ec77d38..2b45654312 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -1,8 +1,4 @@ //! Create interactive, native cross-platform applications. -mod state; - -pub use state::State; - use crate::mouse; use crate::{Error, Executor, Runtime}; @@ -382,7 +378,7 @@ async fn run_instance( .expect("Create surface."); let current_context = context.make_current(&surface).expect("Make current."); - let state = State::new(&application, id, &window); + let state = multi_window::State::new(&application, id, &window); let physical_size = state.physical_size(); surface.resize( @@ -577,7 +573,7 @@ async fn run_instance( event::Event::UserEvent(event) => match event { Event::Application(message) => messages.push(message), Event::WindowCreated(id, window) => { - let state = State::new(&application, id, &window); + let state = multi_window::State::new(&application, id, &window); let user_interface = multi_window::build_user_interface( &application, user_interface::Cache::default(), @@ -771,7 +767,7 @@ async fn run_instance( pub fn update( application: &mut A, cache: &mut user_interface::Cache, - state: &State, + state: &multi_window::State, renderer: &mut A::Renderer, runtime: &mut Runtime>, Event>, clipboard: &mut Clipboard, @@ -813,7 +809,7 @@ pub fn update( pub fn run_command( application: &A, cache: &mut user_interface::Cache, - state: &State, + state: &multi_window::State, renderer: &mut A::Renderer, command: Command, runtime: &mut Runtime>, Event>, @@ -993,7 +989,7 @@ pub fn build_user_interfaces<'a, A>( application: &'a A, renderer: &mut A::Renderer, debug: &mut Debug, - states: &HashMap>, + states: &HashMap>, mut pure_states: HashMap, ) -> HashMap< window::Id, diff --git a/glutin/src/multi_window/state.rs b/glutin/src/multi_window/state.rs deleted file mode 100644 index 8ed134b2f6..0000000000 --- a/glutin/src/multi_window/state.rs +++ /dev/null @@ -1,223 +0,0 @@ -use crate::application::{self, StyleSheet as _}; -use crate::conversion; -use crate::multi_window::Application; -use crate::window; -use crate::{Color, Debug, Point, Size, Viewport}; - -use iced_winit::winit; -use winit::event::{Touch, WindowEvent}; -use winit::window::Window; - -use std::marker::PhantomData; - -/// The state of a windowed [`Application`]. -#[allow(missing_debug_implementations)] -pub struct State -where - ::Theme: application::StyleSheet, -{ - title: String, - scale_factor: f64, - viewport: Viewport, - viewport_changed: bool, - cursor_position: winit::dpi::PhysicalPosition, - modifiers: winit::event::ModifiersState, - theme: ::Theme, - appearance: iced_winit::application::Appearance, - application: PhantomData, -} - -impl State -where - ::Theme: application::StyleSheet, -{ - /// Creates a new [`State`] for the provided [`Application`]'s window. - pub fn new( - application: &A, - window_id: window::Id, - window: &Window, - ) -> Self { - let title = application.title(window_id); - let scale_factor = application.scale_factor(); - let theme = application.theme(); - let appearance = theme.appearance(&application.style()); - - let viewport = { - let physical_size = window.inner_size(); - - Viewport::with_physical_size( - Size::new(physical_size.width, physical_size.height), - window.scale_factor() * scale_factor, - ) - }; - - Self { - title, - scale_factor, - viewport, - viewport_changed: false, - // TODO: Encode cursor availability in the type-system - cursor_position: winit::dpi::PhysicalPosition::new(-1.0, -1.0), - modifiers: winit::event::ModifiersState::default(), - theme, - appearance, - application: PhantomData, - } - } - - /// Returns the current [`Viewport`] of the [`State`]. - pub fn viewport(&self) -> &Viewport { - &self.viewport - } - - /// Returns whether or not the current [`Viewport`] has changed. - pub fn viewport_changed(&self) -> bool { - self.viewport_changed - } - - /// Returns the physical [`Size`] of the [`Viewport`] of the [`State`]. - pub fn physical_size(&self) -> Size { - self.viewport.physical_size() - } - - /// Returns the logical [`Size`] of the [`Viewport`] of the [`State`]. - pub fn logical_size(&self) -> Size { - self.viewport.logical_size() - } - - /// Returns the current scale factor of the [`Viewport`] of the [`State`]. - pub fn scale_factor(&self) -> f64 { - self.viewport.scale_factor() - } - - /// Returns the current cursor position of the [`State`]. - pub fn cursor_position(&self) -> Point { - conversion::cursor_position( - self.cursor_position, - self.viewport.scale_factor(), - ) - } - - /// Returns the current keyboard modifiers of the [`State`]. - pub fn modifiers(&self) -> winit::event::ModifiersState { - self.modifiers - } - - /// Returns the current theme of the [`State`]. - pub fn theme(&self) -> &::Theme { - &self.theme - } - - /// Returns the current background [`Color`] of the [`State`]. - pub fn background_color(&self) -> Color { - self.appearance.background_color - } - - /// Returns the current text [`Color`] of the [`State`]. - pub fn text_color(&self) -> Color { - self.appearance.text_color - } - - /// Processes the provided window event and updates the [`State`] - /// accordingly. - pub fn update( - &mut self, - window: &Window, - event: &WindowEvent<'_>, - _debug: &mut Debug, - ) { - match event { - WindowEvent::Resized(new_size) => { - let size = Size::new(new_size.width, new_size.height); - - self.viewport = Viewport::with_physical_size( - size, - window.scale_factor() * self.scale_factor, - ); - - self.viewport_changed = true; - } - WindowEvent::ScaleFactorChanged { - scale_factor: new_scale_factor, - new_inner_size, - } => { - let size = - Size::new(new_inner_size.width, new_inner_size.height); - - self.viewport = Viewport::with_physical_size( - size, - new_scale_factor * self.scale_factor, - ); - - self.viewport_changed = true; - } - WindowEvent::CursorMoved { position, .. } - | WindowEvent::Touch(Touch { - location: position, .. - }) => { - self.cursor_position = *position; - } - WindowEvent::CursorLeft { .. } => { - // TODO: Encode cursor availability in the type-system - self.cursor_position = - winit::dpi::PhysicalPosition::new(-1.0, -1.0); - } - WindowEvent::ModifiersChanged(new_modifiers) => { - self.modifiers = *new_modifiers; - } - #[cfg(feature = "debug")] - WindowEvent::KeyboardInput { - input: - glutin::event::KeyboardInput { - virtual_keycode: - Some(glutin::event::VirtualKeyCode::F12), - state: glutin::event::ElementState::Pressed, - .. - }, - .. - } => _debug.toggle(), - _ => {} - } - } - - /// Synchronizes the [`State`] with its [`Application`] and its respective - /// window. - /// - /// Normally an [`Application`] should be synchronized with its [`State`] - /// and window after calling [`Application::update`]. - /// - /// [`Application::update`]: crate::Program::update - pub fn synchronize( - &mut self, - application: &A, - window_id: window::Id, - window: &Window, - ) { - // Update window title - let new_title = application.title(window_id); - - if self.title != new_title { - window.set_title(&new_title); - - self.title = new_title; - } - - // Update scale factor - let new_scale_factor = application.scale_factor(); - - if self.scale_factor != new_scale_factor { - let size = window.inner_size(); - - self.viewport = Viewport::with_physical_size( - Size::new(size.width, size.height), - window.scale_factor() * new_scale_factor, - ); - - self.scale_factor = new_scale_factor; - } - - // Update theme and appearance - self.theme = application.theme(); - self.appearance = self.theme.appearance(&application.style()); - } -} From 790fa3e7a01a790aa3f07083fe9abf6b68fa7ba1 Mon Sep 17 00:00:00 2001 From: Bingus Date: Fri, 13 Jan 2023 11:56:28 -0800 Subject: [PATCH 35/66] Added tracing to multi_window applications --- glutin/Cargo.toml | 2 +- glutin/src/application.rs | 8 ++-- glutin/src/multi_window.rs | 50 ++++++++++++++------ winit/src/application.rs | 4 +- winit/src/lib.rs | 4 +- winit/src/multi_window.rs | 61 ++++++++++++++++++++----- winit/src/{application => }/profiler.rs | 1 + 7 files changed, 94 insertions(+), 36 deletions(-) rename winit/src/{application => }/profiler.rs (98%) diff --git a/glutin/Cargo.toml b/glutin/Cargo.toml index 3f902d204e..5197b07610 100644 --- a/glutin/Cargo.toml +++ b/glutin/Cargo.toml @@ -11,7 +11,7 @@ keywords = ["gui", "ui", "graphics", "interface", "widgets"] categories = ["gui"] [features] -trace = ["iced_winit/trace"] +trace = ["iced_winit/trace", "tracing"] debug = ["iced_winit/debug"] system = ["iced_winit/system"] multi_window = ["iced_winit/multi_window"] diff --git a/glutin/src/application.rs b/glutin/src/application.rs index f43a47b927..a6479597c2 100644 --- a/glutin/src/application.rs +++ b/glutin/src/application.rs @@ -33,7 +33,7 @@ use std::ffi::CString; use std::mem::ManuallyDrop; use std::num::NonZeroU32; -#[cfg(feature = "tracing")] +#[cfg(feature = "trace")] use tracing::{info_span, instrument::Instrument}; #[allow(unsafe_code)] @@ -62,7 +62,7 @@ where let mut debug = Debug::new(); debug.startup_started(); - #[cfg(feature = "tracing")] + #[cfg(feature = "trace")] let _ = info_span!("Application::Glutin", "RUN").entered(); let mut event_loop = EventLoopBuilder::with_user_event().build(); @@ -298,7 +298,7 @@ where settings.exit_on_close_request, ); - #[cfg(feature = "tracing")] + #[cfg(feature = "trace")] let run_instance = run_instance.instrument(info_span!("Application", "LOOP")); @@ -509,7 +509,7 @@ async fn run_instance( messages.push(message); } event::Event::RedrawRequested(_) => { - #[cfg(feature = "tracing")] + #[cfg(feature = "trace")] let _ = info_span!("Application", "FRAME").entered(); debug.render_started(); diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index 2b45654312..a2e0581a09 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -32,6 +32,9 @@ use std::ffi::CString; use std::mem::ManuallyDrop; use std::num::NonZeroU32; +#[cfg(feature = "tracing")] +use tracing::{info_span, instrument::Instrument}; + #[allow(unsafe_code)] const ONE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1) }; @@ -52,9 +55,15 @@ where use winit::event_loop::EventLoopBuilder; use winit::platform::run_return::EventLoopExtRunReturn; + #[cfg(feature = "trace")] + let _guard = iced_winit::Profiler::init(); + let mut debug = Debug::new(); debug.startup_started(); + #[cfg(feature = "tracing")] + let _ = info_span!("Application::Glutin", "RUN").entered(); + let mut event_loop = EventLoopBuilder::with_user_event().build(); let proxy = event_loop.create_proxy(); @@ -267,21 +276,29 @@ where let (mut sender, receiver) = mpsc::unbounded(); - let mut instance = Box::pin(run_instance::( - application, - compositor, - renderer, - runtime, - proxy, - debug, - receiver, - display, - windows, - configuration, - context, - init_command, - settings.exit_on_close_request, - )); + let mut instance = Box::pin({ + let run_instance = run_instance::( + application, + compositor, + renderer, + runtime, + proxy, + debug, + receiver, + display, + windows, + configuration, + context, + init_command, + settings.exit_on_close_request, + ); + + #[cfg(feature = "tracing")] + let run_instance = + run_instance.instrument(info_span!("Application", "LOOP")); + + run_instance + }); let mut context = task::Context::from_waker(task::noop_waker_ref()); @@ -619,6 +636,9 @@ async fn run_instance( Event::NewWindow { .. } => unreachable!(), }, event::Event::RedrawRequested(id) => { + #[cfg(feature = "tracing")] + let _ = info_span!("Application", "FRAME").entered(); + let state = window_ids .get(&id) .and_then(|id| states.get_mut(id)) diff --git a/winit/src/application.rs b/winit/src/application.rs index eef6833cf5..76553988d7 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -1,6 +1,4 @@ //! Create interactive, native cross-platform applications. -#[cfg(feature = "trace")] -mod profiler; mod state; pub use state::State; @@ -27,7 +25,7 @@ pub use iced_native::application::{Appearance, StyleSheet}; use std::mem::ManuallyDrop; #[cfg(feature = "trace")] -pub use profiler::Profiler; +pub use crate::Profiler; #[cfg(feature = "trace")] use tracing::{info_span, instrument::Instrument}; diff --git a/winit/src/lib.rs b/winit/src/lib.rs index eb58482bc4..99a468503a 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -51,11 +51,13 @@ pub mod system; mod error; mod icon; mod proxy; +#[cfg(feature = "trace")] +mod profiler; #[cfg(feature = "application")] pub use application::Application; #[cfg(feature = "trace")] -pub use application::Profiler; +pub use profiler::Profiler; pub use clipboard::Clipboard; pub use error::Error; pub use icon::Icon; diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 6a2bdca92a..d7378a1ded 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -26,6 +26,11 @@ use iced_native::window::Action; use std::collections::HashMap; use std::mem::ManuallyDrop; +#[cfg(feature = "trace")] +pub use crate::Profiler; +#[cfg(feature = "trace")] +use tracing::{info_span, instrument::Instrument}; + /// TODO(derezzedex) // This is the an wrapper around the `Application::Message` associate type // to allows the `shell` to create internal messages, while still having @@ -172,9 +177,15 @@ where use futures::Future; use winit::event_loop::EventLoopBuilder; + #[cfg(feature = "trace")] + let _guard = Profiler::init(); + let mut debug = Debug::new(); debug.startup_started(); + #[cfg(feature = "trace")] + let _ = info_span!("Application", "RUN").entered(); + let event_loop = EventLoopBuilder::with_user_event().build(); let proxy = event_loop.create_proxy(); @@ -227,18 +238,26 @@ where let (mut sender, receiver) = mpsc::unbounded(); - let mut instance = Box::pin(run_instance::( - application, - compositor, - renderer, - runtime, - proxy, - debug, - receiver, - init_command, - windows, - settings.exit_on_close_request, - )); + let mut instance = Box::pin({ + let run_instance = run_instance::( + application, + compositor, + renderer, + runtime, + proxy, + debug, + receiver, + init_command, + windows, + settings.exit_on_close_request, + ); + + #[cfg(feature = "trace")] + let run_instance = + run_instance.instrument(info_span!("Application", "LOOP")); + + run_instance + }); let mut context = task::Context::from_waker(task::noop_waker_ref()); @@ -604,6 +623,9 @@ async fn run_instance( Event::NewWindow { .. } => unreachable!(), }, event::Event::RedrawRequested(id) => { + #[cfg(feature = "trace")] + let _ = info_span!("Application", "FRAME").entered(); + let state = window_ids .get(&id) .and_then(|id| states.get_mut(id)) @@ -788,12 +810,22 @@ pub fn build_user_interface<'a, A: Application>( where ::Theme: StyleSheet, { + #[cfg(feature = "trace")] + let view_span = info_span!("Application", "VIEW").entered(); + debug.view_started(); let view = application.view(id); + + #[cfg(feature = "trace")] + let _ = view_span.exit(); debug.view_finished(); + #[cfg(feature = "trace")] + let layout_span = info_span!("Application", "LAYOUT").entered(); debug.layout_started(); let user_interface = UserInterface::build(view, size, cache, renderer); + #[cfg(feature = "trace")] + let _ = layout_span.exit(); debug.layout_finished(); user_interface @@ -817,10 +849,15 @@ pub fn update( ::Theme: StyleSheet, { for message in messages.drain(..) { + #[cfg(feature = "trace")] + let update_span = info_span!("Application", "UPDATE").entered(); + debug.log_message(&message); debug.update_started(); let command = runtime.enter(|| application.update(message)); + #[cfg(feature = "trace")] + let _ = update_span.exit(); debug.update_finished(); run_command( diff --git a/winit/src/application/profiler.rs b/winit/src/profiler.rs similarity index 98% rename from winit/src/application/profiler.rs rename to winit/src/profiler.rs index 23eaa390c1..1f638de813 100644 --- a/winit/src/application/profiler.rs +++ b/winit/src/profiler.rs @@ -21,6 +21,7 @@ pub struct Profiler { impl Profiler { /// Initializes the [`Profiler`]. pub fn init() -> Self { + log::info!("Capturing trace.."); // Registry stores the spans & generates unique span IDs let subscriber = Registry::default(); From 7e9a12a4aa64deda193dfc0f18c34f93e3adc852 Mon Sep 17 00:00:00 2001 From: Bingus Date: Wed, 18 Jan 2023 15:17:20 -0800 Subject: [PATCH 36/66] New iced changes --- native/src/subscription.rs | 2 +- native/src/widget/text_input.rs | 2 +- native/src/window.rs | 6 +++--- winit/src/application.rs | 1 + 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/native/src/subscription.rs b/native/src/subscription.rs index 8c92efad47..f517fc70a2 100644 --- a/native/src/subscription.rs +++ b/native/src/subscription.rs @@ -70,7 +70,7 @@ where events.filter_map(move |(event, status)| { future::ready(match event { - Event::Window(window::Event::RedrawRequested(_)) => None, + Event::Window(_, window::Event::RedrawRequested(_)) => None, _ => f(event, status), }) }) diff --git a/native/src/widget/text_input.rs b/native/src/widget/text_input.rs index 8755b85d81..a62d9f35ba 100644 --- a/native/src/widget/text_input.rs +++ b/native/src/widget/text_input.rs @@ -782,7 +782,7 @@ where state.keyboard_modifiers = modifiers; } - Event::Window(window::Event::RedrawRequested(now)) => { + Event::Window(_, window::Event::RedrawRequested(now)) => { let state = state(); if let Some(focus) = &mut state.is_focused { diff --git a/native/src/window.rs b/native/src/window.rs index d3c8c96f50..660cd54f3a 100644 --- a/native/src/window.rs +++ b/native/src/window.rs @@ -5,8 +5,8 @@ mod icon; mod id; mod mode; mod position; -mod settings; mod redraw_request; +mod settings; mod user_attention; pub use action::Action; @@ -15,8 +15,8 @@ pub use icon::Icon; pub use id::Id; pub use mode::Mode; pub use position::Position; -pub use settings::Settings; pub use redraw_request::RedrawRequest; +pub use settings::Settings; pub use user_attention::UserAttention; use crate::subscription::{self, Subscription}; @@ -32,7 +32,7 @@ use crate::time::Instant; /// animations without missing any frames. pub fn frames() -> Subscription { subscription::raw_events(|event, _status| match event { - crate::Event::Window(Event::RedrawRequested(at)) => Some(at), + crate::Event::Window(_, Event::RedrawRequested(at)) => Some(at), _ => None, }) } diff --git a/winit/src/application.rs b/winit/src/application.rs index c66e08b2aa..d586fd2178 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -402,6 +402,7 @@ async fn run_instance( // Then, we can use the `interface_state` here to decide if a redraw // is needed right away, or simply wait until a specific time. let redraw_event = Event::Window( + crate::window::Id::MAIN, crate::window::Event::RedrawRequested(Instant::now()), ); From 0a643287deece9234b64cc843a9f6ae3e6e4806e Mon Sep 17 00:00:00 2001 From: Bingus Date: Wed, 18 Jan 2023 17:04:11 -0800 Subject: [PATCH 37/66] Added window::Id to multi_window application's scale_factor --- examples/multi_window/src/main.rs | 8 ++++++++ src/multi_window/application.rs | 6 +++--- winit/src/multi_window.rs | 2 +- winit/src/multi_window/state.rs | 4 ++-- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 18536bdf36..0d0a809b47 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -12,6 +12,7 @@ use iced::{Color, Command, Element, Length, Settings, Size, Subscription}; use iced_lazy::responsive; use iced_native::{event, subscription, Event}; +use iced_native::window::Id; use std::collections::HashMap; pub fn main() -> iced::Result { @@ -29,6 +30,7 @@ struct Example { #[derive(Debug)] struct Window { title: String, + scale: f64, panes: pane_grid::State, focus: Option, } @@ -69,6 +71,7 @@ impl Application for Example { panes, focus: None, title: String::from("Default window"), + scale: 1.0, }; ( @@ -178,6 +181,7 @@ impl Application for Example { panes, focus: None, title: format!("New window ({})", self.windows.len()), + scale: 1.0 + (self.windows.len() as f64 / 10.0), }; let window_id = window::Id::new(self.windows.len()); @@ -342,6 +346,10 @@ impl Application for Example { fn close_requested(&self, window: window::Id) -> Self::Message { Message::Window(window, WindowMessage::CloseWindow) } + + fn scale_factor(&self, window: Id) -> f64 { + self.windows.get(&window).map(|w| w.scale).unwrap_or(1.0) + } } const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb( diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index 3f20382cd0..3af1d8d585 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -148,7 +148,7 @@ pub trait Application: Sized { /// while a scale factor of `0.5` will shrink them to half their size. /// /// By default, it returns `1.0`. - fn scale_factor(&self) -> f64 { + fn scale_factor(&self, window: window::Id) -> f64 { 1.0 } @@ -239,8 +239,8 @@ where self.0.subscription() } - fn scale_factor(&self) -> f64 { - self.0.scale_factor() + fn scale_factor(&self, window: window::Id) -> f64 { + self.0.scale_factor(window) } fn should_exit(&self) -> bool { diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index d7378a1ded..ad65e6a56e 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -146,7 +146,7 @@ where /// while a scale factor of `0.5` will shrink them to half their size. /// /// By default, it returns `1.0`. - fn scale_factor(&self) -> f64 { + fn scale_factor(&self, window: window::Id) -> f64 { 1.0 } diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index 2c2a4693b9..35c6992426 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -36,7 +36,7 @@ where window: &Window, ) -> Self { let title = application.title(window_id); - let scale_factor = application.scale_factor(); + let scale_factor = application.scale_factor(window_id); let theme = application.theme(); let appearance = theme.appearance(&application.style()); @@ -199,7 +199,7 @@ where } // Update scale factor - let new_scale_factor = application.scale_factor(); + let new_scale_factor = application.scale_factor(window_id); if self.scale_factor != new_scale_factor { let size = window.inner_size(); From 367fea5dc8e94584334e880970126b40a046bfa6 Mon Sep 17 00:00:00 2001 From: Bingus Date: Wed, 15 Feb 2023 11:28:36 -0800 Subject: [PATCH 38/66] Redraw request events for multiwindow. --- examples/solar_system/src/main.rs | 2 +- native/src/window.rs | 13 +++++++++++-- winit/src/multi_window.rs | 11 ++++++++--- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/examples/solar_system/src/main.rs b/examples/solar_system/src/main.rs index 9a4ee7549a..eb461bb090 100644 --- a/examples/solar_system/src/main.rs +++ b/examples/solar_system/src/main.rs @@ -89,7 +89,7 @@ impl Application for SolarSystem { } fn subscription(&self) -> Subscription { - window::frames().map(Message::Tick) + window::frames().map(|frame| Message::Tick(frame.at)) } } diff --git a/native/src/window.rs b/native/src/window.rs index 660cd54f3a..aa11756f4c 100644 --- a/native/src/window.rs +++ b/native/src/window.rs @@ -30,9 +30,18 @@ use crate::time::Instant; /// /// In any case, this [`Subscription`] is useful to smoothly draw application-driven /// animations without missing any frames. -pub fn frames() -> Subscription { +pub fn frames() -> Subscription { subscription::raw_events(|event, _status| match event { - crate::Event::Window(_, Event::RedrawRequested(at)) => Some(at), + crate::Event::Window(id, Event::RedrawRequested(at)) => { + Some(Frame { id, at }) + } _ => None, }) } + +/// The returned `Frame` for a framerate subscription. +#[derive(Debug)] +pub struct Frame { + pub id: Id, + pub at: Instant, +} diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index ad65e6a56e..430e670622 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -25,6 +25,7 @@ pub use iced_native::application::{Appearance, StyleSheet}; use iced_native::window::Action; use std::collections::HashMap; use std::mem::ManuallyDrop; +use std::time::Instant; #[cfg(feature = "trace")] pub use crate::Profiler; @@ -402,7 +403,7 @@ async fn run_instance( let (filtered, remaining): (Vec<_>, Vec<_>) = events.iter().cloned().partition( |(window_id, _event): &( - Option, + Option, iced_native::event::Event, )| { *window_id == Some(id) || *window_id == None @@ -410,10 +411,14 @@ async fn run_instance( ); events.retain(|el| remaining.contains(el)); - let filtered: Vec<_> = filtered + let mut filtered: Vec<_> = filtered .into_iter() .map(|(_id, event)| event) .collect(); + filtered.push(iced_native::Event::Window( + id, + window::Event::RedrawRequested(Instant::now()), + )); let cursor_position = states.get(&id).unwrap().cursor_position(); @@ -450,7 +455,7 @@ async fn run_instance( user_interface::State::Outdated, ) { - let state = &mut states.get_mut(&id).unwrap(); + let state = states.get_mut(&id).unwrap(); let pure_states: HashMap<_, _> = ManuallyDrop::into_inner(interfaces) .drain() From 64e0e817c27d720dc954ee94de58ded35b3f9f9a Mon Sep 17 00:00:00 2001 From: Bingus Date: Wed, 15 Feb 2023 14:31:16 -0800 Subject: [PATCH 39/66] Widget operations for multi-window. --- examples/multi_window/src/main.rs | 50 +++++++++++-- glutin/src/multi_window.rs | 116 +++++++++++++++-------------- native/src/window.rs | 3 + winit/src/multi_window.rs | 117 ++++++++++++++++-------------- 4 files changed, 171 insertions(+), 115 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 0d0a809b47..23f082174e 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -12,6 +12,7 @@ use iced::{Color, Command, Element, Length, Settings, Size, Subscription}; use iced_lazy::responsive; use iced_native::{event, subscription, Event}; +use iced_native::widget::scrollable::{Properties, RelativeOffset}; use iced_native::window::Id; use std::collections::HashMap; @@ -56,6 +57,7 @@ enum WindowMessage { CloseFocused, SelectedWindow(pane_grid::Pane, SelectableWindow), CloseWindow, + SnapToggle, } impl Application for Example { @@ -94,6 +96,25 @@ impl Application for Example { fn update(&mut self, message: Message) -> Command { let Message::Window(id, message) = message; match message { + WindowMessage::SnapToggle => { + let window = self.windows.get_mut(&id).unwrap(); + + if let Some(focused) = &window.focus { + let pane = window.panes.get_mut(focused).unwrap(); + + let cmd = scrollable::snap_to( + pane.scrollable_id.clone(), + if pane.snapped { + RelativeOffset::START + } else { + RelativeOffset::END + }, + ); + + pane.snapped = !pane.snapped; + return cmd; + } + } WindowMessage::Split(axis, pane) => { let window = self.windows.get_mut(&id).unwrap(); let result = window.panes.split( @@ -311,7 +332,13 @@ impl Application for Example { }); pane_grid::Content::new(responsive(move |size| { - view_content(id, total_panes, pane.is_pinned, size) + view_content( + id, + pane.scrollable_id.clone(), + total_panes, + pane.is_pinned, + size, + ) })) .title_bar(title_bar) .style(if is_focused { @@ -403,24 +430,29 @@ impl std::fmt::Display for SelectableWindow { #[derive(Debug)] struct Pane { id: usize, + pub scrollable_id: scrollable::Id, pub axis: pane_grid::Axis, pub is_pinned: bool, pub is_moving: bool, + pub snapped: bool, } impl Pane { fn new(id: usize, axis: pane_grid::Axis) -> Self { Self { id, + scrollable_id: scrollable::Id::new(format!("{:?}", id)), axis, is_pinned: false, is_moving: false, + snapped: false, } } } fn view_content<'a>( pane: pane_grid::Pane, + scrollable_id: scrollable::Id, total_panes: usize, is_pinned: bool, size: Size, @@ -445,7 +477,8 @@ fn view_content<'a>( button( "Split vertically", WindowMessage::Split(pane_grid::Axis::Vertical, pane), - ) + ), + button("Snap", WindowMessage::SnapToggle,) ] .spacing(5) .max_width(150); @@ -462,15 +495,22 @@ fn view_content<'a>( controls, ] .width(Length::Fill) + .height(Length::Units(800)) .spacing(10) .align_items(Alignment::Center); - container(scrollable(content)) + Element::from( + container( + scrollable(content) + .vertical_scroll(Properties::new()) + .id(scrollable_id), + ) .width(Length::Fill) .height(Length::Fill) .padding(5) - .center_y() - .into() + .center_y(), + ) + .explain(Color::default()) } fn view_controls<'a>( diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index a2e0581a09..33fe60ffd1 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -34,6 +34,7 @@ use std::num::NonZeroU32; #[cfg(feature = "tracing")] use tracing::{info_span, instrument::Instrument}; +use iced_native::widget::operation; #[allow(unsafe_code)] const ONE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1) }; @@ -294,7 +295,7 @@ where ); #[cfg(feature = "tracing")] - let run_instance = + let run_instance = run_instance.instrument(info_span!("Application", "LOOP")); run_instance @@ -380,7 +381,7 @@ async fn run_instance( let mut clipboard = Clipboard::connect(windows.values().next().expect("No window found")); - let mut cache = user_interface::Cache::default(); + let mut caches = HashMap::new(); let mut current_context_window = None; let mut window_ids: HashMap<_, _> = windows .iter() @@ -422,23 +423,20 @@ async fn run_instance( let _ = interfaces.insert(id, user_interface); } - { - let state = states.values().next().expect("No state found."); + run_command( + &application, + &mut caches, + &states, + &mut renderer, + init_command, + &mut runtime, + &mut clipboard, + &mut proxy, + &mut debug, + &windows, + || compositor.fetch_information(), + ); - run_command( - &application, - &mut cache, - state, - &mut renderer, - init_command, - &mut runtime, - &mut clipboard, - &mut proxy, - &mut debug, - &windows, - || compositor.fetch_information(), - ); - } runtime.track(application.subscription().map(Event::Application)); let mut mouse_interaction = mouse::Interaction::default(); @@ -501,8 +499,7 @@ async fn run_instance( user_interface::State::Outdated ) { - let state = &mut states.get_mut(&id).unwrap(); - let pure_states: HashMap<_, _> = + let user_interfaces: HashMap<_, _> = ManuallyDrop::into_inner(interfaces) .drain() .map(|(id, interface)| { @@ -513,8 +510,8 @@ async fn run_instance( // Update application update( &mut application, - &mut cache, - state, + &mut caches, + &states, &mut renderer, &mut runtime, &mut clipboard, @@ -526,7 +523,7 @@ async fn run_instance( ); // Update window - state.synchronize( + states.get_mut(&id).unwrap().synchronize( &application, id, windows.get(&id).expect("No window found with ID."), @@ -539,7 +536,7 @@ async fn run_instance( &mut renderer, &mut debug, &states, - pure_states, + user_interfaces, )); if should_exit { @@ -590,7 +587,8 @@ async fn run_instance( event::Event::UserEvent(event) => match event { Event::Application(message) => messages.push(message), Event::WindowCreated(id, window) => { - let state = multi_window::State::new(&application, id, &window); + let state = + multi_window::State::new(&application, id, &window); let user_interface = multi_window::build_user_interface( &application, user_interface::Cache::default(), @@ -768,7 +766,10 @@ async fn run_instance( )); } } else { - log::error!("Window state not found for id: {:?}", window_id); + log::error!( + "Window state not found for id: {:?}", + window_id + ); } } else { log::error!("Window not found for id: {:?}", window_id); @@ -786,8 +787,8 @@ async fn run_instance( /// resulting [`Command`], and tracking its [`Subscription`]. pub fn update( application: &mut A, - cache: &mut user_interface::Cache, - state: &multi_window::State, + caches: &mut HashMap, + states: &HashMap>, renderer: &mut A::Renderer, runtime: &mut Runtime>, Event>, clipboard: &mut Clipboard, @@ -797,6 +798,7 @@ pub fn update( windows: &HashMap, graphics_info: impl FnOnce() -> iced_graphics::compositor::Information + Copy, ) where + A: Application + 'static, ::Theme: StyleSheet, { for message in messages.drain(..) { @@ -808,8 +810,8 @@ pub fn update( run_command( application, - cache, - state, + caches, + &states, renderer, command, runtime, @@ -828,8 +830,8 @@ pub fn update( /// Runs the actions of a [`Command`]. pub fn run_command( application: &A, - cache: &mut user_interface::Cache, - state: &multi_window::State, + caches: &mut HashMap, + states: &HashMap>, renderer: &mut A::Renderer, command: Command, runtime: &mut Runtime>, Event>, @@ -839,7 +841,7 @@ pub fn run_command( windows: &HashMap, _graphics_info: impl FnOnce() -> iced_graphics::compositor::Information + Copy, ) where - A: Application, + A: Application + 'static, E: Executor, ::Theme: StyleSheet, { @@ -967,38 +969,42 @@ pub fn run_command( } }, command::Action::Widget(action) => { - use crate::widget::operation; - - let mut current_cache = std::mem::take(cache); + let mut current_caches = std::mem::take(caches); let mut current_operation = Some(action.into_operation()); - let mut user_interface = multi_window::build_user_interface( + let mut user_interfaces = multi_window::build_user_interfaces( application, - current_cache, renderer, - state.logical_size(), debug, - window::Id::MAIN, // TODO(derezzedex): run the operation on every widget tree + states, + current_caches, ); while let Some(mut operation) = current_operation.take() { - user_interface.operate(renderer, operation.as_mut()); - - match operation.finish() { - operation::Outcome::None => {} - operation::Outcome::Some(message) => { - proxy - .send_event(Event::Application(message)) - .expect("Send message to event loop"); - } - operation::Outcome::Chain(next) => { - current_operation = Some(next); + for user_interface in user_interfaces.values_mut() { + user_interface.operate(renderer, operation.as_mut()); + + match operation.finish() { + operation::Outcome::None => {} + operation::Outcome::Some(message) => { + proxy + .send_event(Event::Application(message)) + .expect("Send message to event loop"); + } + operation::Outcome::Chain(next) => { + current_operation = Some(next); + } } } } - current_cache = user_interface.into_cache(); - *cache = current_cache; + let user_interfaces: HashMap<_, _> = user_interfaces + .drain() + .map(|(id, interface)| (id, interface.into_cache())) + .collect(); + + current_caches = user_interfaces; + *caches = current_caches; } } } @@ -1010,7 +1016,7 @@ pub fn build_user_interfaces<'a, A>( renderer: &mut A::Renderer, debug: &mut Debug, states: &HashMap>, - mut pure_states: HashMap, + mut user_interfaces: HashMap, ) -> HashMap< window::Id, iced_winit::UserInterface< @@ -1025,7 +1031,7 @@ where { let mut interfaces = HashMap::new(); - for (id, pure_state) in pure_states.drain() { + for (id, pure_state) in user_interfaces.drain() { let state = &states.get(&id).unwrap(); let user_interface = multi_window::build_user_interface( diff --git a/native/src/window.rs b/native/src/window.rs index aa11756f4c..e768ed6d3a 100644 --- a/native/src/window.rs +++ b/native/src/window.rs @@ -21,6 +21,7 @@ pub use user_attention::UserAttention; use crate::subscription::{self, Subscription}; use crate::time::Instant; +use crate::window; /// Subscribes to the frames of the window of the running application. /// @@ -42,6 +43,8 @@ pub fn frames() -> Subscription { /// The returned `Frame` for a framerate subscription. #[derive(Debug)] pub struct Frame { + /// The `window::Id` that the `Frame` was produced in. pub id: Id, + /// The `Instant` at which the frame was produced. pub at: Instant, } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 430e670622..bd7e9d44dc 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -4,12 +4,12 @@ mod state; pub use state::State; use crate::clipboard::{self, Clipboard}; -use crate::conversion; use crate::mouse; use crate::renderer; use crate::settings; use crate::widget::operation; use crate::window; +use crate::{conversion, multi_window}; use crate::{ Command, Debug, Element, Error, Executor, Proxy, Renderer, Runtime, Settings, Size, Subscription, @@ -254,7 +254,7 @@ where ); #[cfg(feature = "trace")] - let run_instance = + let run_instance = run_instance.instrument(info_span!("Application", "LOOP")); run_instance @@ -335,7 +335,7 @@ async fn run_instance( let mut clipboard = Clipboard::connect(windows.values().next().expect("No window found")); - let mut cache = user_interface::Cache::default(); + let mut caches = HashMap::new(); let mut window_ids: HashMap<_, _> = windows .iter() .map(|(&id, window)| (window.id(), id)) @@ -368,26 +368,23 @@ async fn run_instance( let _ = states.insert(id, state); let _ = surfaces.insert(id, surface); let _ = interfaces.insert(id, user_interface); + let _ = caches.insert(id, user_interface::Cache::default()); } - { - // TODO(derezzedex) - let state = states.values().next().expect("No state found"); + run_command( + &application, + &mut caches, + &states, + &mut renderer, + init_command, + &mut runtime, + &mut clipboard, + &mut proxy, + &mut debug, + &windows, + || compositor.fetch_information(), + ); - run_command( - &application, - &mut cache, - state, - &mut renderer, - init_command, - &mut runtime, - &mut clipboard, - &mut proxy, - &mut debug, - &windows, - || compositor.fetch_information(), - ); - } runtime.track(application.subscription().map(Event::Application)); let mut mouse_interaction = mouse::Interaction::default(); @@ -455,8 +452,7 @@ async fn run_instance( user_interface::State::Outdated, ) { - let state = states.get_mut(&id).unwrap(); - let pure_states: HashMap<_, _> = + let user_interfaces: HashMap<_, _> = ManuallyDrop::into_inner(interfaces) .drain() .map( @@ -472,8 +468,8 @@ async fn run_instance( // Update application update( &mut application, - &mut cache, - state, + &mut caches, + &states, &mut renderer, &mut runtime, &mut clipboard, @@ -485,7 +481,7 @@ async fn run_instance( ); // Update window - state.synchronize( + states.get_mut(&id).unwrap().synchronize( &application, id, windows.get(&id).expect("No window found with ID."), @@ -498,7 +494,7 @@ async fn run_instance( &mut renderer, &mut debug, &states, - pure_states, + user_interfaces, )); if should_exit { @@ -579,6 +575,7 @@ async fn run_instance( let _ = interfaces.insert(id, user_interface); let _ = window_ids.insert(window.id(), id); let _ = windows.insert(id, window); + let _ = caches.insert(id, user_interface::Cache::default()); } Event::CloseWindow(id) => { if let Some(window) = windows.get(&id) { @@ -764,7 +761,10 @@ async fn run_instance( )); } } else { - log::error!("No window state found for id: {:?}", window_id); + log::error!( + "No window state found for id: {:?}", + window_id + ); } } else { log::error!("No window found with id: {:?}", window_id); @@ -840,8 +840,8 @@ where /// resulting [`Command`], and tracking its [`Subscription`]. pub fn update( application: &mut A, - cache: &mut user_interface::Cache, - state: &State, + caches: &mut HashMap, + states: &HashMap>, renderer: &mut A::Renderer, runtime: &mut Runtime>, Event>, clipboard: &mut Clipboard, @@ -851,6 +851,7 @@ pub fn update( windows: &HashMap, graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where + A: Application + 'static, ::Theme: StyleSheet, { for message in messages.drain(..) { @@ -867,8 +868,8 @@ pub fn update( run_command( application, - cache, - state, + caches, + states, renderer, command, runtime, @@ -887,8 +888,8 @@ pub fn update( /// Runs the actions of a [`Command`]. pub fn run_command( application: &A, - cache: &mut user_interface::Cache, - state: &State, + caches: &mut HashMap, + states: &HashMap>, renderer: &mut A::Renderer, command: Command, runtime: &mut Runtime>, Event>, @@ -898,7 +899,7 @@ pub fn run_command( windows: &HashMap, _graphics_info: impl FnOnce() -> compositor::Information + Copy, ) where - A: Application, + A: Application + 'static, E: Executor, ::Theme: StyleSheet, { @@ -1024,36 +1025,42 @@ pub fn run_command( } }, command::Action::Widget(action) => { - let mut current_cache = std::mem::take(cache); + let mut current_caches = std::mem::take(caches); let mut current_operation = Some(action.into_operation()); - let mut user_interface = build_user_interface( + let mut user_interfaces = build_user_interfaces( application, - current_cache, renderer, - state.logical_size(), debug, - window::Id::MAIN, // TODO(derezzedex): run the operation on every widget tree + states, + current_caches, ); while let Some(mut operation) = current_operation.take() { - user_interface.operate(renderer, operation.as_mut()); - - match operation.finish() { - operation::Outcome::None => {} - operation::Outcome::Some(message) => { - proxy - .send_event(Event::Application(message)) - .expect("Send message to event loop"); - } - operation::Outcome::Chain(next) => { - current_operation = Some(next); + for user_interface in user_interfaces.values_mut() { + user_interface.operate(renderer, operation.as_mut()); + + match operation.finish() { + operation::Outcome::None => {} + operation::Outcome::Some(message) => { + proxy + .send_event(Event::Application(message)) + .expect("Send message to event loop"); + } + operation::Outcome::Chain(next) => { + current_operation = Some(next); + } } } } - current_cache = user_interface.into_cache(); - *cache = current_cache; + let user_interfaces: HashMap<_, _> = user_interfaces + .drain() + .map(|(id, interface)| (id, interface.into_cache())) + .collect(); + + current_caches = user_interfaces; + *caches = current_caches; } } } @@ -1065,7 +1072,7 @@ pub fn build_user_interfaces<'a, A>( renderer: &mut A::Renderer, debug: &mut Debug, states: &HashMap>, - mut pure_states: HashMap, + mut cached_user_interfaces: HashMap, ) -> HashMap< window::Id, UserInterface< @@ -1080,12 +1087,12 @@ where { let mut interfaces = HashMap::new(); - for (id, pure_state) in pure_states.drain() { + for (id, cache) in cached_user_interfaces.drain() { let state = &states.get(&id).unwrap(); let user_interface = build_user_interface( application, - pure_state, + cache, renderer, state.logical_size(), debug, From 3c095aa3f09f28c6fd9d2a7ba220ced407693e0b Mon Sep 17 00:00:00 2001 From: Bingus Date: Wed, 15 Feb 2023 14:56:15 -0800 Subject: [PATCH 40/66] Merged in iced master --- glutin/src/multi_window.rs | 2 +- native/src/window/action.rs | 4 ++-- winit/src/multi_window.rs | 2 +- winit/src/window.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index 33fe60ffd1..da450dee68 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -901,7 +901,7 @@ pub fn run_command( y, }); } - window::Action::SetMode(mode) => { + window::Action::ChangeMode(mode) => { let window = windows.get(&id).expect("No window found"); window.set_visible(conversion::visible(mode)); window.set_fullscreen(conversion::fullscreen( diff --git a/native/src/window/action.rs b/native/src/window/action.rs index 63858bc845..e345cdfc55 100644 --- a/native/src/window/action.rs +++ b/native/src/window/action.rs @@ -1,4 +1,4 @@ -use crate::window::{Mode, UserAttention}; +use crate::window::{Mode, UserAttention, Settings}; use iced_futures::MaybeSend; use std::fmt; @@ -16,7 +16,7 @@ pub enum Action { /// Spawns a new window with the provided [`window::Settings`]. Spawn { /// The settings of the [`Window`]. - settings: window::Settings, + settings: Settings, }, /// Resize the window. Resize { diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index bd7e9d44dc..f846e124d6 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -957,7 +957,7 @@ pub fn run_command( y, }); } - window::Action::SetMode(mode) => { + window::Action::ChangeMode(mode) => { let window = windows.get(&id).expect("No window found"); window.set_visible(conversion::visible(mode)); window.set_fullscreen(conversion::fullscreen( diff --git a/winit/src/window.rs b/winit/src/window.rs index fa31dca13e..97d80c3821 100644 --- a/winit/src/window.rs +++ b/winit/src/window.rs @@ -60,7 +60,7 @@ pub fn move_to(id: window::Id, x: i32, y: i32) -> Command { /// Changes the [`Mode`] of the window. pub fn change_mode(id: window::Id, mode: Mode) -> Command { - Command::single(command::Action::Window(id, window::Action::SetMode(mode))) + Command::single(command::Action::Window(id, window::Action::ChangeMode(mode))) } /// Fetches the current [`Mode`] of the window. From 8da098330b58542cc929f4f24d02e26bd654bae4 Mon Sep 17 00:00:00 2001 From: Bingus Date: Fri, 17 Feb 2023 11:42:49 -0800 Subject: [PATCH 41/66] Fixed widget animations implementation --- examples/multi_window/src/main.rs | 21 +++--- native/src/widget/tree.rs | 2 +- native/src/window.rs | 1 - winit/src/multi_window.rs | 110 +++++++++++++++++++++++------- 4 files changed, 95 insertions(+), 39 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 23f082174e..17d662b426 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -499,18 +499,17 @@ fn view_content<'a>( .spacing(10) .align_items(Alignment::Center); - Element::from( - container( - scrollable(content) - .vertical_scroll(Properties::new()) - .id(scrollable_id), - ) - .width(Length::Fill) - .height(Length::Fill) - .padding(5) - .center_y(), + container( + scrollable(content) + .height(Length::Fill) + .vertical_scroll(Properties::new()) + .id(scrollable_id), ) - .explain(Color::default()) + .width(Length::Fill) + .height(Length::Fill) + .padding(5) + .center_y() + .into() } fn view_controls<'a>( diff --git a/native/src/widget/tree.rs b/native/src/widget/tree.rs index 0af40c33d9..da26963243 100644 --- a/native/src/widget/tree.rs +++ b/native/src/widget/tree.rs @@ -67,7 +67,7 @@ impl Tree { } } - /// Reconciliates the children of the tree with the provided list of widgets. + /// Reconciles the children of the tree with the provided list of widgets. pub fn diff_children<'a, Message, Renderer>( &mut self, new_children: &[impl Borrow + 'a>], diff --git a/native/src/window.rs b/native/src/window.rs index e768ed6d3a..a8f8b10f92 100644 --- a/native/src/window.rs +++ b/native/src/window.rs @@ -21,7 +21,6 @@ pub use user_attention::UserAttention; use crate::subscription::{self, Subscription}; use crate::time::Instant; -use crate::window; /// Subscribes to the frames of the window of the running application. /// diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index f846e124d6..17eaa6fec8 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -9,7 +9,7 @@ use crate::renderer; use crate::settings; use crate::widget::operation; use crate::window; -use crate::{conversion, multi_window}; +use crate::conversion; use crate::{ Command, Debug, Element, Error, Executor, Proxy, Renderer, Runtime, Settings, Size, Subscription, @@ -237,7 +237,8 @@ where let (compositor, renderer) = C::new(compositor_settings, Some(&window))?; - let (mut sender, receiver) = mpsc::unbounded(); + let (mut event_sender, event_receiver) = mpsc::unbounded(); + let (control_sender, mut control_receiver) = mpsc::unbounded(); let mut instance = Box::pin({ let run_instance = run_instance::( @@ -247,7 +248,8 @@ where runtime, proxy, debug, - receiver, + event_receiver, + control_sender, init_command, windows, settings.exit_on_close_request, @@ -299,13 +301,19 @@ where }; if let Some(event) = event { - sender.start_send(event).expect("Send 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, + match poll { + task::Poll::Pending => { + if let Ok(Some(flow)) = control_receiver.try_next() { + *control_flow = flow; + } + } + task::Poll::Ready(_) => { + *control_flow = ControlFlow::Exit; + } }; } }) @@ -318,9 +326,10 @@ async fn run_instance( mut runtime: Runtime>, Event>, mut proxy: winit::event_loop::EventLoopProxy>, mut debug: Debug, - mut receiver: mpsc::UnboundedReceiver< + mut event_receiver: mpsc::UnboundedReceiver< winit::event::Event<'_, Event>, >, + mut control_sender: mpsc::UnboundedSender, init_command: Command, mut windows: HashMap, _exit_on_close_request: bool, @@ -332,6 +341,7 @@ async fn run_instance( { use iced_futures::futures::stream::StreamExt; use winit::event; + use winit::event_loop::ControlFlow; let mut clipboard = Clipboard::connect(windows.values().next().expect("No window found")); @@ -390,11 +400,20 @@ async fn run_instance( let mut mouse_interaction = mouse::Interaction::default(); let mut events = Vec::new(); let mut messages = Vec::new(); + let mut redraw_pending = false; debug.startup_finished(); - 'main: while let Some(event) = receiver.next().await { + 'main: while let Some(event) = event_receiver.next().await { match event { + event::Event::NewEvents(start_cause) => { + redraw_pending = matches!( + start_cause, + event::StartCause::Init + | event::StartCause::Poll + | event::StartCause::ResumeTimeReached { .. } + ); + } event::Event::MainEventsCleared => { for id in states.keys().copied().collect::>() { let (filtered, remaining): (Vec<_>, Vec<_>) = @@ -408,29 +427,27 @@ async fn run_instance( ); events.retain(|el| remaining.contains(el)); - let mut filtered: Vec<_> = filtered + let window_events: Vec<_> = filtered .into_iter() .map(|(_id, event)| event) .collect(); - filtered.push(iced_native::Event::Window( - id, - window::Event::RedrawRequested(Instant::now()), - )); - let cursor_position = - states.get(&id).unwrap().cursor_position(); - let window = windows.get(&id).unwrap(); - - if filtered.is_empty() && messages.is_empty() { + if !redraw_pending + && window_events.is_empty() + && messages.is_empty() + { continue; } debug.event_processing_started(); + let cursor_position = + states.get(&id).unwrap().cursor_position(); + let (interface_state, statuses) = { let user_interface = interfaces.get_mut(&id).unwrap(); user_interface.update( - &filtered, + &window_events, cursor_position, &mut renderer, &mut clipboard, @@ -440,7 +457,8 @@ async fn run_instance( debug.event_processing_finished(); - for event in filtered.into_iter().zip(statuses.into_iter()) + for event in + window_events.into_iter().zip(statuses.into_iter()) { runtime.broadcast(event); } @@ -487,8 +505,6 @@ async fn run_instance( windows.get(&id).expect("No window found with ID."), ); - let should_exit = application.should_exit(); - interfaces = ManuallyDrop::new(build_user_interfaces( &application, &mut renderer, @@ -497,17 +513,35 @@ async fn run_instance( user_interfaces, )); - if should_exit { + if application.should_exit() { break 'main; } } + // TODO: Avoid redrawing all the time by forcing widgets to + // request redraws on state changes + // + // Then, we can use the `interface_state` here to decide if a redraw + // is needed right away, or simply wait until a specific time. + let redraw_event = iced_native::Event::Window( + id, + window::Event::RedrawRequested(Instant::now()), + ); + + let (interface_state, _) = + interfaces.get_mut(&id).unwrap().update( + &[redraw_event.clone()], + cursor_position, + &mut renderer, + &mut clipboard, + &mut messages, + ); + debug.draw_started(); let new_mouse_interaction = { - let user_interface = interfaces.get_mut(&id).unwrap(); let state = states.get(&id).unwrap(); - user_interface.draw( + interfaces.get_mut(&id).unwrap().draw( &mut renderer, state.theme(), &renderer::Style { @@ -518,6 +552,8 @@ async fn run_instance( }; debug.draw_finished(); + let window = windows.get(&id).unwrap(); + if new_mouse_interaction != mouse_interaction { window.set_cursor_icon(conversion::mouse_interaction( new_mouse_interaction, @@ -528,6 +564,28 @@ async fn run_instance( for window in windows.values() { window.request_redraw(); + + runtime.broadcast(( + redraw_event.clone(), + crate::event::Status::Ignored, + )); + + let _ = + control_sender.start_send(match interface_state { + user_interface::State::Updated { + redraw_request: Some(redraw_request), + } => match redraw_request { + window::RedrawRequest::NextFrame => { + ControlFlow::Poll + } + window::RedrawRequest::At(at) => { + ControlFlow::WaitUntil(at) + } + }, + _ => ControlFlow::Wait, + }); + + redraw_pending = false; } } } From 2d427455ce8f9627da7c09eb80f38a615f0ddcb7 Mon Sep 17 00:00:00 2001 From: Bingus Date: Fri, 17 Feb 2023 11:50:52 -0800 Subject: [PATCH 42/66] Iced master merge (again) --- examples/multi_window/src/main.rs | 4 ++-- glutin/src/multi_window.rs | 18 ++++++++++++++---- src/multi_window/application.rs | 1 + winit/src/multi_window.rs | 21 ++++++++++++++++----- winit/src/window.rs | 2 +- 5 files changed, 34 insertions(+), 12 deletions(-) diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 17d662b426..c2687ee6e3 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -441,7 +441,7 @@ impl Pane { fn new(id: usize, axis: pane_grid::Axis) -> Self { Self { id, - scrollable_id: scrollable::Id::new(format!("{:?}", id)), + scrollable_id: scrollable::Id::unique(), axis, is_pinned: false, is_moving: false, @@ -495,7 +495,7 @@ fn view_content<'a>( controls, ] .width(Length::Fill) - .height(Length::Units(800)) + .height(800) .spacing(10) .align_items(Alignment::Center); diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs index da450dee68..620d01d8e4 100644 --- a/glutin/src/multi_window.rs +++ b/glutin/src/multi_window.rs @@ -25,16 +25,15 @@ use glutin::surface::{GlSurface, SwapInterval}; use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; use crate::application::gl_surface; -use iced_native::window::Action; use iced_winit::multi_window::Event; use std::collections::HashMap; use std::ffi::CString; use std::mem::ManuallyDrop; use std::num::NonZeroU32; +use iced_native::widget::operation; #[cfg(feature = "tracing")] use tracing::{info_span, instrument::Instrument}; -use iced_native::widget::operation; #[allow(unsafe_code)] const ONE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1) }; @@ -937,16 +936,27 @@ pub fn run_command( let window = windows.get(&id).expect("No window found!"); window.set_decorations(!window.is_decorated()); } - Action::RequestUserAttention(attention_type) => { + window::Action::RequestUserAttention(attention_type) => { let window = windows.get(&id).expect("No window found!"); window.request_user_attention( attention_type.map(conversion::user_attention), ); } - Action::GainFocus => { + window::Action::GainFocus => { let window = windows.get(&id).expect("No window found!"); window.focus_window(); } + window::Action::ChangeAlwaysOnTop(on_top) => { + let window = windows.get(&id).expect("No window found!"); + window.set_always_on_top(on_top); + } + window::Action::FetchId(tag) => { + let window = windows.get(&id).expect("No window found!"); + + proxy + .send_event(Event::Application(tag(window.id().into()))) + .expect("Send message to event loop.") + } }, command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index 3af1d8d585..d0b515ab13 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -148,6 +148,7 @@ pub trait Application: Sized { /// while a scale factor of `0.5` will shrink them to half their size. /// /// By default, it returns `1.0`. + #[allow(unused_variables)] fn scale_factor(&self, window: window::Id) -> f64 { 1.0 } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 17eaa6fec8..96dd1c8b4a 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -4,12 +4,12 @@ mod state; pub use state::State; use crate::clipboard::{self, Clipboard}; +use crate::conversion; use crate::mouse; use crate::renderer; use crate::settings; use crate::widget::operation; use crate::window; -use crate::conversion; use crate::{ Command, Debug, Element, Error, Executor, Proxy, Renderer, Runtime, Settings, Size, Subscription, @@ -22,7 +22,6 @@ use iced_native::user_interface::{self, UserInterface}; pub use iced_native::application::{Appearance, StyleSheet}; -use iced_native::window::Action; use std::collections::HashMap; use std::mem::ManuallyDrop; use std::time::Instant; @@ -147,6 +146,7 @@ where /// while a scale factor of `0.5` will shrink them to half their size. /// /// By default, it returns `1.0`. + #[allow(unused_variables)] fn scale_factor(&self, window: window::Id) -> f64 { 1.0 } @@ -470,7 +470,7 @@ async fn run_instance( user_interface::State::Outdated, ) { - let user_interfaces: HashMap<_, _> = + let cached_interfaces: HashMap<_, _> = ManuallyDrop::into_inner(interfaces) .drain() .map( @@ -510,7 +510,7 @@ async fn run_instance( &mut renderer, &mut debug, &states, - user_interfaces, + cached_interfaces, )); if application.should_exit() { @@ -1057,10 +1057,21 @@ pub fn run_command( attention_type.map(conversion::user_attention), ); } - Action::GainFocus => { + window::Action::GainFocus => { let window = windows.get(&id).expect("No window found!"); window.focus_window(); } + window::Action::ChangeAlwaysOnTop(on_top) => { + let window = windows.get(&id).expect("No window found!"); + window.set_always_on_top(on_top); + } + window::Action::FetchId(tag) => { + let window = windows.get(&id).expect("No window found!"); + + proxy + .send_event(Event::Application(tag(window.id().into()))) + .expect("Send message to event loop.") + } }, command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { diff --git a/winit/src/window.rs b/winit/src/window.rs index 88cd3f145f..8fd415efb9 100644 --- a/winit/src/window.rs +++ b/winit/src/window.rs @@ -122,7 +122,7 @@ pub fn fetch_id( id: window::Id, f: impl FnOnce(u64) -> Message + 'static, ) -> Command { - Command::single(command::Action::Window(id: window::Id, window::Action::FetchId(Box::new( + Command::single(command::Action::Window(id, window::Action::FetchId(Box::new( f, )))) } From 3aaf5d8873b16302badb14dc5508329c943862fb Mon Sep 17 00:00:00 2001 From: Bingus Date: Fri, 17 Feb 2023 13:26:31 -0800 Subject: [PATCH 43/66] Fixed widget operations --- winit/src/multi_window.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 96dd1c8b4a..fc91f41b83 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -470,7 +470,7 @@ async fn run_instance( user_interface::State::Outdated, ) { - let cached_interfaces: HashMap<_, _> = + let mut cached_interfaces: HashMap<_, _> = ManuallyDrop::into_inner(interfaces) .drain() .map( @@ -486,7 +486,7 @@ async fn run_instance( // Update application update( &mut application, - &mut caches, + &mut cached_interfaces, &states, &mut renderer, &mut runtime, From bd58d5fe25182908e99fdb0ced07b86666e45081 Mon Sep 17 00:00:00 2001 From: Bingus Date: Mon, 20 Feb 2023 12:34:04 -0800 Subject: [PATCH 44/66] Cargo fix --- Cargo.toml | 2 +- examples/multi_window/Cargo.toml | 2 +- examples/multi_window/src/main.rs | 304 ++++++++++++++++-------------- winit/src/multi_window.rs | 56 +++--- 4 files changed, 191 insertions(+), 173 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e4da8b2cc4..1a615da21d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,7 @@ chrome-trace = [ "iced_glow?/tracing", ] # Enables experimental multi-window support -multi_window = ["iced_winit/multi_window", "iced_glutin/multi_window"] +multi_window = ["iced_winit/multi_window", "iced_glutin?/multi_window"] [badges] maintenance = { status = "actively-developed" } diff --git a/examples/multi_window/Cargo.toml b/examples/multi_window/Cargo.toml index 621985950f..0bb83f37ae 100644 --- a/examples/multi_window/Cargo.toml +++ b/examples/multi_window/Cargo.toml @@ -7,7 +7,7 @@ publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -iced = { path = "../..", features = ["debug", "multi_window"] } +iced = { path = "../..", features = ["debug", "multi_window", "tokio"] } env_logger = "0.10.0" iced_native = { path = "../../native" } iced_lazy = { path = "../../lazy" } diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index c2687ee6e3..60f32a7d0e 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -1,5 +1,5 @@ use iced::alignment::{self, Alignment}; -use iced::executor; +use iced::{executor, time}; use iced::keyboard; use iced::multi_window::Application; use iced::theme::{self, Theme}; @@ -15,6 +15,7 @@ use iced_native::{event, subscription, Event}; use iced_native::widget::scrollable::{Properties, RelativeOffset}; use iced_native::window::Id; use std::collections::HashMap; +use std::time::{Duration, Instant}; pub fn main() -> iced::Result { env_logger::init(); @@ -25,6 +26,7 @@ pub fn main() -> iced::Result { struct Example { windows: HashMap, panes_created: usize, + count: usize, _focused: window::Id, } @@ -39,6 +41,7 @@ struct Window { #[derive(Debug, Clone)] enum Message { Window(window::Id, WindowMessage), + CountIncremented(Instant), } #[derive(Debug, Clone)] @@ -80,6 +83,7 @@ impl Application for Example { Example { windows: HashMap::from([(window::Id::MAIN, window)]), panes_created: 1, + count: 0, _focused: window::Id::MAIN, }, Command::none(), @@ -94,44 +98,29 @@ impl Application for Example { } fn update(&mut self, message: Message) -> Command { - let Message::Window(id, message) = message; match message { - WindowMessage::SnapToggle => { - let window = self.windows.get_mut(&id).unwrap(); - - if let Some(focused) = &window.focus { - let pane = window.panes.get_mut(focused).unwrap(); - - let cmd = scrollable::snap_to( - pane.scrollable_id.clone(), - if pane.snapped { - RelativeOffset::START - } else { - RelativeOffset::END - }, - ); - - pane.snapped = !pane.snapped; - return cmd; - } - } - WindowMessage::Split(axis, pane) => { - let window = self.windows.get_mut(&id).unwrap(); - let result = window.panes.split( - axis, - &pane, - Pane::new(self.panes_created, axis), - ); - - if let Some((pane, _)) = result { - window.focus = Some(pane); + Message::Window(id, message) => match message { + WindowMessage::SnapToggle => { + let window = self.windows.get_mut(&id).unwrap(); + + if let Some(focused) = &window.focus { + let pane = window.panes.get_mut(focused).unwrap(); + + let cmd = scrollable::snap_to( + pane.scrollable_id.clone(), + if pane.snapped { + RelativeOffset::START + } else { + RelativeOffset::END + }, + ); + + pane.snapped = !pane.snapped; + return cmd; + } } - - self.panes_created += 1; - } - WindowMessage::SplitFocused(axis) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.focus { + WindowMessage::Split(axis, pane) => { + let window = self.windows.get_mut(&id).unwrap(); let result = window.panes.split( axis, &pane, @@ -144,112 +133,131 @@ impl Application for Example { self.panes_created += 1; } - } - WindowMessage::FocusAdjacent(direction) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.focus { - if let Some(adjacent) = - window.panes.adjacent(&pane, direction) - { - window.focus = Some(adjacent); + WindowMessage::SplitFocused(axis) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.focus { + let result = window.panes.split( + axis, + &pane, + Pane::new(self.panes_created, axis), + ); + + if let Some((pane, _)) = result { + window.focus = Some(pane); + } + + self.panes_created += 1; } } - } - WindowMessage::Clicked(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - window.focus = Some(pane); - } - WindowMessage::CloseWindow => { - let _ = self.windows.remove(&id); - return window::close(id); - } - WindowMessage::Resized(pane_grid::ResizeEvent { split, ratio }) => { - let window = self.windows.get_mut(&id).unwrap(); - window.panes.resize(&split, ratio); - } - WindowMessage::SelectedWindow(pane, selected) => { - let window = self.windows.get_mut(&id).unwrap(); - let (mut pane, _) = window.panes.close(&pane).unwrap(); - pane.is_moving = false; - - if let Some(window) = self.windows.get_mut(&selected.0) { - let (&first_pane, _) = window.panes.iter().next().unwrap(); - let result = - window.panes.split(pane.axis, &first_pane, pane); - - if let Some((pane, _)) = result { - window.focus = Some(pane); + WindowMessage::FocusAdjacent(direction) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.focus { + if let Some(adjacent) = + window.panes.adjacent(&pane, direction) + { + window.focus = Some(adjacent); + } } } - } - WindowMessage::ToggleMoving(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.panes.get_mut(&pane) { - pane.is_moving = !pane.is_moving; + WindowMessage::Clicked(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + window.focus = Some(pane); } - } - WindowMessage::TitleChanged(title) => { - let window = self.windows.get_mut(&id).unwrap(); - window.title = title; - } - WindowMessage::PopOut(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some((popped, sibling)) = window.panes.close(&pane) { - window.focus = Some(sibling); - - let (panes, _) = pane_grid::State::new(popped); - let window = Window { - panes, - focus: None, - title: format!("New window ({})", self.windows.len()), - scale: 1.0 + (self.windows.len() as f64 / 10.0), - }; - - let window_id = window::Id::new(self.windows.len()); - self.windows.insert(window_id, window); - return window::spawn(window_id, Default::default()); + WindowMessage::CloseWindow => { + let _ = self.windows.remove(&id); + return window::close(id); } - } - WindowMessage::Dragged(pane_grid::DragEvent::Dropped { - pane, - target, - }) => { - let window = self.windows.get_mut(&id).unwrap(); - window.panes.swap(&pane, &target); - } - // WindowMessage::Dragged(pane_grid::DragEvent::Picked { pane }) => { - // println!("Picked {pane:?}"); - // } - WindowMessage::Dragged(_) => {} - WindowMessage::TogglePin(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(Pane { is_pinned, .. }) = - window.panes.get_mut(&pane) - { - *is_pinned = !*is_pinned; + WindowMessage::Resized(pane_grid::ResizeEvent { split, ratio }) => { + let window = self.windows.get_mut(&id).unwrap(); + window.panes.resize(&split, ratio); } - } - WindowMessage::Close(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some((_, sibling)) = window.panes.close(&pane) { - window.focus = Some(sibling); + WindowMessage::SelectedWindow(pane, selected) => { + let window = self.windows.get_mut(&id).unwrap(); + let (mut pane, _) = window.panes.close(&pane).unwrap(); + pane.is_moving = false; + + if let Some(window) = self.windows.get_mut(&selected.0) { + let (&first_pane, _) = window.panes.iter().next().unwrap(); + let result = + window.panes.split(pane.axis, &first_pane, pane); + + if let Some((pane, _)) = result { + window.focus = Some(pane); + } + } } - } - WindowMessage::CloseFocused => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.focus { + WindowMessage::ToggleMoving(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.panes.get_mut(&pane) { + pane.is_moving = !pane.is_moving; + } + } + WindowMessage::TitleChanged(title) => { + let window = self.windows.get_mut(&id).unwrap(); + window.title = title; + } + WindowMessage::PopOut(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some((popped, sibling)) = window.panes.close(&pane) { + window.focus = Some(sibling); + + let (panes, _) = pane_grid::State::new(popped); + let window = Window { + panes, + focus: None, + title: format!("New window ({})", self.windows.len()), + scale: 1.0 + (self.windows.len() as f64 / 10.0), + }; + + let window_id = window::Id::new(self.windows.len()); + self.windows.insert(window_id, window); + return window::spawn(window_id, Default::default()); + } + } + WindowMessage::Dragged(pane_grid::DragEvent::Dropped { + pane, + target, + }) => { + let window = self.windows.get_mut(&id).unwrap(); + window.panes.swap(&pane, &target); + } + // WindowMessage::Dragged(pane_grid::DragEvent::Picked { pane }) => { + // println!("Picked {pane:?}"); + // } + WindowMessage::Dragged(_) => {} + WindowMessage::TogglePin(pane) => { + let window = self.windows.get_mut(&id).unwrap(); if let Some(Pane { is_pinned, .. }) = - window.panes.get(&pane) + window.panes.get_mut(&pane) { - if !is_pinned { - if let Some((_, sibling)) = - window.panes.close(&pane) - { - window.focus = Some(sibling); + *is_pinned = !*is_pinned; + } + } + WindowMessage::Close(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some((_, sibling)) = window.panes.close(&pane) { + window.focus = Some(sibling); + } + } + WindowMessage::CloseFocused => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.focus { + if let Some(Pane { is_pinned, .. }) = + window.panes.get(&pane) + { + if !is_pinned { + if let Some((_, sibling)) = + window.panes.close(&pane) + { + window.focus = Some(sibling); + } } } } } + }, + Message::CountIncremented(_) => { + self.count += 1; } } @@ -257,23 +265,26 @@ impl Application for Example { } fn subscription(&self) -> Subscription { - subscription::events_with(|event, status| { - if let event::Status::Captured = status { - return None; - } + Subscription::batch(vec![ + subscription::events_with(|event, status| { + if let event::Status::Captured = status { + return None; + } - match event { - Event::Keyboard(keyboard::Event::KeyPressed { - modifiers, - key_code, - }) if modifiers.command() => { - handle_hotkey(key_code).map(|message| { - Message::Window(window::Id::new(0usize), message) - }) - } // TODO(derezzedex) - _ => None, - } - }) + match event { + Event::Keyboard(keyboard::Event::KeyPressed { + modifiers, + key_code, + }) if modifiers.command() => { + handle_hotkey(key_code).map(|message| { + Message::Window(window::Id::new(0usize), message) + }) + } // TODO(derezzedex) + _ => None, + } + }), + time::every(Duration::from_secs(1)).map(Message::CountIncremented), + ]) } fn view(&self, window_id: window::Id) -> Element { @@ -335,6 +346,7 @@ impl Application for Example { view_content( id, pane.scrollable_id.clone(), + self.count, total_panes, pane.is_pinned, size, @@ -453,6 +465,7 @@ impl Pane { fn view_content<'a>( pane: pane_grid::Pane, scrollable_id: scrollable::Id, + count: usize, total_panes: usize, is_pinned: bool, size: Size, @@ -493,6 +506,7 @@ fn view_content<'a>( let content = column![ text(format!("{}x{}", size.width, size.height)).size(24), controls, + text(format!("{count}")).size(48), ] .width(Length::Fill) .height(800) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index fc91f41b83..788f39f725 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -416,6 +416,7 @@ async fn run_instance( } event::Event::MainEventsCleared => { for id in states.keys().copied().collect::>() { + // Partition events into only events for this window let (filtered, remaining): (Vec<_>, Vec<_>) = events.iter().cloned().partition( |(window_id, _event): &( @@ -426,7 +427,9 @@ async fn run_instance( }, ); + // Only retain events which have not been processed for next iteration events.retain(|el| remaining.contains(el)); + let window_events: Vec<_> = filtered .into_iter() .map(|(_id, event)| event) @@ -439,8 +442,8 @@ async fn run_instance( continue; } + // Process winit events for window debug.event_processing_started(); - let cursor_position = states.get(&id).unwrap().cursor_position(); @@ -455,15 +458,16 @@ async fn run_instance( ) }; - debug.event_processing_finished(); - for event in window_events.into_iter().zip(statuses.into_iter()) { runtime.broadcast(event); } + debug.event_processing_finished(); - // TODO(derezzedex): Should we redraw every window? We can't know what changed. + // Update application with app message(s) + // Note: without tying an app message to a window ID, we must redraw all windows + // as we cannot know what changed without some kind of damage tracking. if !messages.is_empty() || matches!( interface_state, @@ -498,7 +502,7 @@ async fn run_instance( || compositor.fetch_information(), ); - // Update window + // synchronize window state with application state. states.get_mut(&id).unwrap().synchronize( &application, id, @@ -564,29 +568,29 @@ async fn run_instance( for window in windows.values() { window.request_redraw(); + } - runtime.broadcast(( - redraw_event.clone(), - crate::event::Status::Ignored, - )); + runtime.broadcast(( + redraw_event.clone(), + crate::event::Status::Ignored, + )); - let _ = - control_sender.start_send(match interface_state { - user_interface::State::Updated { - redraw_request: Some(redraw_request), - } => match redraw_request { - window::RedrawRequest::NextFrame => { - ControlFlow::Poll - } - window::RedrawRequest::At(at) => { - ControlFlow::WaitUntil(at) - } - }, - _ => ControlFlow::Wait, - }); - - redraw_pending = false; - } + let _ = + control_sender.start_send(match interface_state { + user_interface::State::Updated { + redraw_request: Some(redraw_request), + } => match redraw_request { + window::RedrawRequest::NextFrame => { + ControlFlow::Poll + } + window::RedrawRequest::At(at) => { + ControlFlow::WaitUntil(at) + } + }, + _ => ControlFlow::Wait, + }); + + redraw_pending = false; } } event::Event::PlatformSpecific(event::PlatformSpecific::MacOS( From 50b9c778b1e49fc83f827a340dce36a09bb291d6 Mon Sep 17 00:00:00 2001 From: Bingus Date: Tue, 21 Feb 2023 16:46:32 -0800 Subject: [PATCH 45/66] Fixed state syncing issue with MW. --- winit/src/multi_window.rs | 43 +++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 788f39f725..1a9d4a1ccd 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -502,12 +502,16 @@ async fn run_instance( || compositor.fetch_information(), ); - // synchronize window state with application state. - states.get_mut(&id).unwrap().synchronize( - &application, - id, - windows.get(&id).expect("No window found with ID."), - ); + // synchronize window states with application states. + for (id, state) in states.iter_mut() { + state.synchronize( + &application, + *id, + windows + .get(id) + .expect("No window found with ID."), + ); + } interfaces = ManuallyDrop::new(build_user_interfaces( &application, @@ -575,20 +579,19 @@ async fn run_instance( crate::event::Status::Ignored, )); - let _ = - control_sender.start_send(match interface_state { - user_interface::State::Updated { - redraw_request: Some(redraw_request), - } => match redraw_request { - window::RedrawRequest::NextFrame => { - ControlFlow::Poll - } - window::RedrawRequest::At(at) => { - ControlFlow::WaitUntil(at) - } - }, - _ => ControlFlow::Wait, - }); + let _ = control_sender.start_send(match interface_state { + user_interface::State::Updated { + redraw_request: Some(redraw_request), + } => match redraw_request { + window::RedrawRequest::NextFrame => { + ControlFlow::Poll + } + window::RedrawRequest::At(at) => { + ControlFlow::WaitUntil(at) + } + }, + _ => ControlFlow::Wait, + }); redraw_pending = false; } From e36daa6f937abd7cb2071fd8852a3c12263944ea Mon Sep 17 00:00:00 2001 From: bungoboingo Date: Tue, 28 Feb 2023 13:44:36 -0800 Subject: [PATCH 46/66] Removed glutin MW support and reverted glutin changes back to Iced master since it's being axed as we speak. --- Cargo.toml | 4 +- examples/integration_opengl/src/main.rs | 8 +- glutin/Cargo.toml | 10 +- glutin/src/application.rs | 364 ++------ glutin/src/lib.rs | 3 - glutin/src/multi_window.rs | 1060 ----------------------- graphics/src/window/gl_compositor.rs | 2 +- native/src/window/id.rs | 4 +- src/lib.rs | 2 +- winit/src/application.rs | 2 +- winit/src/multi_window.rs | 25 +- winit/src/multi_window/state.rs | 7 +- winit/src/profiler.rs | 1 - winit/src/settings.rs | 8 +- winit/src/settings/windows.rs | 4 +- 15 files changed, 129 insertions(+), 1375 deletions(-) delete mode 100644 glutin/src/multi_window.rs diff --git a/Cargo.toml b/Cargo.toml index 1a615da21d..5276d92187 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,8 +46,8 @@ chrome-trace = [ "iced_wgpu?/tracing", "iced_glow?/tracing", ] -# Enables experimental multi-window support -multi_window = ["iced_winit/multi_window", "iced_glutin?/multi_window"] +# Enables experimental multi-window support for iced_winit +multi_window = ["iced_winit/multi_window"] [badges] maintenance = { status = "actively-developed" } diff --git a/examples/integration_opengl/src/main.rs b/examples/integration_opengl/src/main.rs index fdbd736907..4dd3a4a950 100644 --- a/examples/integration_opengl/src/main.rs +++ b/examples/integration_opengl/src/main.rs @@ -13,7 +13,6 @@ use iced_glow::{Backend, Renderer, Settings, Viewport}; use iced_glutin::conversion; use iced_glutin::glutin; use iced_glutin::renderer; -use iced_glutin::window; use iced_glutin::{program, Clipboard, Color, Debug, Size}; pub fn main() { @@ -31,8 +30,7 @@ pub fn main() { .unwrap(); unsafe { - let windowed_context = - windowed_context.make_current(todo!("derezzedex")).unwrap(); + let windowed_context = windowed_context.make_current().unwrap(); let gl = glow::Context::from_loader_function(|s| { windowed_context.get_proc_address(s) as *const _ @@ -109,7 +107,7 @@ pub fn main() { // Map window event to iced event if let Some(event) = iced_winit::conversion::window_event( - window::Id::MAIN, + iced_winit::window::Id::MAIN, &event, windowed_context.window().scale_factor(), modifiers, @@ -182,7 +180,7 @@ pub fn main() { ), ); - windowed_context.swap_buffers(todo!("derezzedex")).unwrap(); + windowed_context.swap_buffers().unwrap(); } _ => (), } diff --git a/glutin/Cargo.toml b/glutin/Cargo.toml index 01dd3748b8..10d3778be9 100644 --- a/glutin/Cargo.toml +++ b/glutin/Cargo.toml @@ -11,19 +11,17 @@ keywords = ["gui", "ui", "graphics", "interface", "widgets"] categories = ["gui"] [features] -trace = ["iced_winit/trace", "tracing"] +trace = ["iced_winit/trace"] debug = ["iced_winit/debug"] system = ["iced_winit/system"] -multi_window = ["iced_winit/multi_window"] - -[dependencies.raw-window-handle] -version = "0.5.0" [dependencies] log = "0.4" [dependencies.glutin] -version = "0.30" +version = "0.29" +git = "https://github.com/iced-rs/glutin" +rev = "da8d291486b4c9bec12487a46c119c4b1d386abf" [dependencies.iced_native] version = "0.9" diff --git a/glutin/src/application.rs b/glutin/src/application.rs index c0a8cda40f..24f38e7b20 100644 --- a/glutin/src/application.rs +++ b/glutin/src/application.rs @@ -13,33 +13,14 @@ use iced_winit::futures::channel::mpsc; use iced_winit::renderer; use iced_winit::time::Instant; use iced_winit::user_interface; -use iced_winit::winit; use iced_winit::{Clipboard, Command, Debug, Event, Proxy, Settings}; -use glutin::config::{ - Config, ConfigSurfaceTypes, ConfigTemplateBuilder, GlConfig, -}; -use glutin::context::{ - ContextApi, ContextAttributesBuilder, NotCurrentContext, - NotCurrentGlContextSurfaceAccessor, - PossiblyCurrentContextGlSurfaceAccessor, PossiblyCurrentGlContext, -}; -use glutin::display::{Display, DisplayApiPreference, GlDisplay}; -use glutin::surface::{ - GlSurface, Surface, SurfaceAttributesBuilder, WindowSurface, -}; -use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; - -use std::ffi::CString; +use glutin::window::Window; use std::mem::ManuallyDrop; -use std::num::NonZeroU32; -#[cfg(feature = "trace")] +#[cfg(feature = "tracing")] use tracing::{info_span, instrument::Instrument}; -#[allow(unsafe_code)] -const ONE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1) }; - /// Runs an [`Application`] with an executor, compositor, and the provided /// settings. pub fn run( @@ -54,8 +35,9 @@ where { use futures::task; use futures::Future; - use winit::event_loop::EventLoopBuilder; - use winit::platform::run_return::EventLoopExtRunReturn; + use glutin::event_loop::EventLoopBuilder; + use glutin::platform::run_return::EventLoopExtRunReturn; + use glutin::ContextBuilder; #[cfg(feature = "trace")] let _guard = iced_winit::Profiler::init(); @@ -63,7 +45,7 @@ where let mut debug = Debug::new(); debug.startup_started(); - #[cfg(feature = "trace")] + #[cfg(feature = "tracing")] let _ = info_span!("Application::Glutin", "RUN").entered(); let mut event_loop = EventLoopBuilder::with_user_event().build(); @@ -82,205 +64,74 @@ where runtime.enter(|| A::new(flags)) }; - let builder = settings.window.into_builder( - &application.title(), - event_loop.primary_monitor(), - settings.id, - ); - - log::debug!("Window builder: {:#?}", builder); - - #[allow(unsafe_code)] - let (display, window, surface, context) = unsafe { - struct Configuration(Config); - use std::fmt; - impl fmt::Debug for Configuration { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let config = &self.0; - - f.debug_struct("Configuration") - .field("raw", &config) - .field("samples", &config.num_samples()) - .field("buffer_type", &config.color_buffer_type()) - .field("surface_type", &config.config_surface_types()) - .field("depth", &config.depth_size()) - .field("alpha", &config.alpha_size()) - .field("stencil", &config.stencil_size()) - .field("float_pixels", &config.float_pixels()) - .field("srgb", &config.srgb_capable()) - .field("api", &config.api()) - .finish() - } - } - - impl AsRef for Configuration { - fn as_ref(&self) -> &Config { - &self.0 - } - } - - let display_handle = event_loop.raw_display_handle(); - - #[cfg(all( - any(windows, target_os = "macos"), - not(target_arch = "wasm32") - ))] - let (window, window_handle) = { - let window = builder - .build(&event_loop) - .map_err(Error::WindowCreationFailed)?; - - let handle = window.raw_window_handle(); - - (window, handle) - }; - - #[cfg(target_arch = "wasm32")] - let preference = Err(Error::GraphicsCreationFailed( - iced_graphics::Error::BackendError(format!( - "target not supported by backend" - )), - ))?; - - #[cfg(all(windows, not(target_arch = "wasm32")))] - let preference = DisplayApiPreference::WglThenEgl(Some(window_handle)); - - #[cfg(all(target_os = "macos", not(target_arch = "wasm32")))] - let preference = DisplayApiPreference::Cgl; - - #[cfg(all( - unix, - not(target_os = "macos"), - not(target_arch = "wasm32") - ))] - let preference = DisplayApiPreference::GlxThenEgl(Box::new( - winit::platform::unix::register_xlib_error_hook, - )); - - let display = - Display::new(display_handle, preference).map_err(|error| { - Error::GraphicsCreationFailed( - iced_graphics::Error::BackendError(format!( - "failed to create display: {error}" - )), - ) - })?; + let context = { + let builder = settings.window.into_builder( + &application.title(), + event_loop.primary_monitor(), + settings.id, + ); - log::debug!("Display: {}", display.version_string()); + log::debug!("Window builder: {:#?}", builder); - let samples = C::sample_count(&compositor_settings) as u8; - let mut template = ConfigTemplateBuilder::new() - .with_surface_type(ConfigSurfaceTypes::WINDOW); + let opengl_builder = ContextBuilder::new() + .with_vsync(true) + .with_multisampling(C::sample_count(&compositor_settings) as u16); - if samples != 0 { - template = template.with_multisampling(samples); - } + let opengles_builder = opengl_builder.clone().with_gl( + glutin::GlRequest::Specific(glutin::Api::OpenGlEs, (2, 0)), + ); - #[cfg(all(windows, not(target_arch = "wasm32")))] - let template = template.compatible_with_native_window(window_handle); - - log::debug!("Searching for display configurations"); - let configuration = display - .find_configs(template.build()) - .map_err(|_| { - Error::GraphicsCreationFailed( - iced_graphics::Error::NoAvailablePixelFormat, - ) - })? - .map(Configuration) - .inspect(|config| { - log::trace!("{config:#?}"); - }) - .min_by_key(|config| { - config.as_ref().num_samples().saturating_sub(samples) - }) - .ok_or(Error::GraphicsCreationFailed( - iced_graphics::Error::NoAvailablePixelFormat, - ))?; - - log::debug!("Selected: {configuration:#?}"); - - #[cfg(all( - unix, - not(target_os = "macos"), - not(target_arch = "wasm32") - ))] - let (window, window_handle) = { - use glutin::platform::x11::X11GlConfigExt; - let builder = - if let Some(visual) = configuration.as_ref().x11_visual() { - use winit::platform::unix::WindowBuilderExtUnix; - builder.with_x11_visual(visual.into_raw()) - } else { - builder - }; - - let window = builder - .build(&event_loop) - .map_err(Error::WindowCreationFailed)?; - - let handle = window.raw_window_handle(); - - (window, handle) + let (first_builder, second_builder) = if settings.try_opengles_first { + (opengles_builder, opengl_builder) + } else { + (opengl_builder, opengles_builder) }; - let attributes = - ContextAttributesBuilder::new().build(Some(window_handle)); - let fallback_attributes = ContextAttributesBuilder::new() - .with_context_api(ContextApi::Gles(None)) - .build(Some(window_handle)); + log::info!("Trying first builder: {:#?}", first_builder); - let context = display - .create_context(configuration.as_ref(), &attributes) + let context = first_builder + .build_windowed(builder.clone(), &event_loop) .or_else(|_| { - display.create_context( - configuration.as_ref(), - &fallback_attributes, - ) + log::info!("Trying second builder: {:#?}", second_builder); + second_builder.build_windowed(builder, &event_loop) }) .map_err(|error| { - Error::GraphicsCreationFailed( - iced_graphics::Error::BackendError(format!( - "failed to create context: {error}" - )), - ) - })?; + use glutin::CreationError; + use iced_graphics::Error as ContextError; - let surface = gl_surface(&display, configuration.as_ref(), &window) - .map_err(|error| { - Error::GraphicsCreationFailed( - iced_graphics::Error::BackendError(format!( - "failed to create surface: {error}" - )), - ) + match error { + CreationError::Window(error) => { + Error::WindowCreationFailed(error) + } + CreationError::OpenGlVersionNotSupported => { + Error::GraphicsCreationFailed( + ContextError::VersionNotSupported, + ) + } + CreationError::NoAvailablePixelFormat => { + Error::GraphicsCreationFailed( + ContextError::NoAvailablePixelFormat, + ) + } + error => Error::GraphicsCreationFailed( + ContextError::BackendError(error.to_string()), + ), + } })?; - let context = { - context - .make_current(&surface) - .expect("make context current") - }; - - if let Err(error) = surface.set_swap_interval( - &context, - glutin::surface::SwapInterval::Wait(ONE), - ) { - log::error!("set swap interval failed: {}", error); + #[allow(unsafe_code)] + unsafe { + context.make_current().expect("Make OpenGL context current") } - - (display, window, surface, context) }; #[allow(unsafe_code)] let (compositor, renderer) = unsafe { C::new(compositor_settings, |address| { - let address = CString::new(address).expect("address error"); - display.get_proc_address(address.as_c_str()) + context.get_proc_address(address) })? }; - let context = { context.make_not_current().expect("make context current") }; - let (mut event_sender, event_receiver) = mpsc::unbounded(); let (control_sender, mut control_receiver) = mpsc::unbounded(); @@ -294,14 +145,12 @@ where debug, event_receiver, control_sender, - window, - surface, context, init_command, settings.exit_on_close_request, ); - #[cfg(feature = "trace")] + #[cfg(feature = "tracing")] let run_instance = run_instance.instrument(info_span!("Application", "LOOP")); @@ -311,22 +160,22 @@ where let mut context = task::Context::from_waker(task::noop_waker_ref()); let _ = event_loop.run_return(move |event, _, control_flow| { - use winit::event_loop::ControlFlow; + use glutin::event_loop::ControlFlow; if let ControlFlow::ExitWithCode(_) = control_flow { return; } let event = match event { - winit::event::Event::WindowEvent { + glutin::event::Event::WindowEvent { event: - winit::event::WindowEvent::ScaleFactorChanged { + glutin::event::WindowEvent::ScaleFactorChanged { new_inner_size, .. }, window_id, - } => Some(winit::event::Event::WindowEvent { - event: winit::event::WindowEvent::Resized(*new_inner_size), + } => Some(glutin::event::Event::WindowEvent { + event: glutin::event::WindowEvent::Resized(*new_inner_size), window_id, }), _ => event.to_static(), @@ -358,13 +207,13 @@ async fn run_instance( mut compositor: C, mut renderer: A::Renderer, mut runtime: Runtime, A::Message>, - mut proxy: winit::event_loop::EventLoopProxy, + mut proxy: glutin::event_loop::EventLoopProxy, mut debug: Debug, - mut event_receiver: mpsc::UnboundedReceiver, >, - mut control_sender: mpsc::UnboundedSender, - window: winit::window::Window, - surface: Surface, - context: NotCurrentContext, + mut event_receiver: mpsc::UnboundedReceiver< + glutin::event::Event<'_, A::Message>, + >, + mut control_sender: mpsc::UnboundedSender, + mut context: glutin::ContextWrapper, init_command: Command, exit_on_close_request: bool, ) where @@ -373,19 +222,13 @@ async fn run_instance( C: window::GLCompositor + 'static, ::Theme: StyleSheet, { + use glutin::event; + use glutin::event_loop::ControlFlow; use iced_winit::futures::stream::StreamExt; - use winit::event_loop::ControlFlow; - use winit::event; - let context = { - context - .make_current(&surface) - .expect("make context current") - }; - - let mut clipboard = Clipboard::connect(&window); + let mut clipboard = Clipboard::connect(context.window()); let mut cache = user_interface::Cache::default(); - let mut state = application::State::new(&application, &window); + let mut state = application::State::new(&application, context.window()); let mut viewport_version = state.viewport_version(); let mut should_exit = false; @@ -400,7 +243,7 @@ async fn run_instance( &mut should_exit, &mut proxy, &mut debug, - &window, + context.window(), || compositor.fetch_information(), ); runtime.track(application.subscription()); @@ -473,12 +316,12 @@ async fn run_instance( &mut proxy, &mut debug, &mut messages, - &window, + context.window(), || compositor.fetch_information(), ); // Update window - state.synchronize(&application, &window); + state.synchronize(&application, context.window()); user_interface = ManuallyDrop::new(application::build_user_interface( @@ -524,15 +367,16 @@ async fn run_instance( debug.draw_finished(); if new_mouse_interaction != mouse_interaction { - window.set_cursor_icon(conversion::mouse_interaction( - new_mouse_interaction, - )); + context.window().set_cursor_icon( + conversion::mouse_interaction(new_mouse_interaction), + ); mouse_interaction = new_mouse_interaction; } - window.request_redraw(); - runtime.broadcast((redraw_event, crate::event::Status::Ignored)); + context.window().request_redraw(); + runtime + .broadcast((redraw_event, crate::event::Status::Ignored)); let _ = control_sender.start_send(match interface_state { user_interface::State::Updated { @@ -564,15 +408,18 @@ async fn run_instance( messages.push(message); } event::Event::RedrawRequested(_) => { - #[cfg(feature = "trace")] + #[cfg(feature = "tracing")] let _ = info_span!("Application", "FRAME").entered(); debug.render_started(); - if !context.is_current() { - context - .make_current(&surface) - .expect("Make OpenGL context current"); + #[allow(unsafe_code)] + unsafe { + if !context.is_current() { + context = context + .make_current() + .expect("Make OpenGL context current"); + } } let current_viewport_version = state.viewport_version(); @@ -600,18 +447,19 @@ async fn run_instance( debug.draw_finished(); if new_mouse_interaction != mouse_interaction { - window.set_cursor_icon(conversion::mouse_interaction( - new_mouse_interaction, - )); + context.window().set_cursor_icon( + conversion::mouse_interaction( + new_mouse_interaction, + ), + ); mouse_interaction = new_mouse_interaction; } - surface.resize( - &context, - NonZeroU32::new(physical_size.width).unwrap_or(ONE), - NonZeroU32::new(physical_size.height).unwrap_or(ONE), - ); + context.resize(glutin::dpi::PhysicalSize::new( + physical_size.width, + physical_size.height, + )); compositor.resize_viewport(physical_size); @@ -625,7 +473,7 @@ async fn run_instance( &debug.overlay(), ); - surface.swap_buffers(&context).expect("Swap buffers"); + context.swap_buffers().expect("Swap buffers"); debug.render_finished(); @@ -642,7 +490,7 @@ async fn run_instance( break; } - state.update(&window, &window_event, &mut debug); + state.update(context.window(), &window_event, &mut debug); if let Some(event) = conversion::window_event( crate::window::Id::MAIN, @@ -660,23 +508,3 @@ async fn run_instance( // Manually drop the user interface drop(ManuallyDrop::into_inner(user_interface)); } - -#[allow(unsafe_code)] -/// Creates a new [`glutin::Surface`]. -pub fn gl_surface( - display: &Display, - gl_config: &Config, - window: &winit::window::Window, -) -> Result, glutin::error::Error> { - let (width, height) = window.inner_size().into(); - - let surface_attributes = SurfaceAttributesBuilder::::new() - .with_srgb(Some(true)) - .build( - window.raw_window_handle(), - NonZeroU32::new(width).unwrap_or(ONE), - NonZeroU32::new(height).unwrap_or(ONE), - ); - - unsafe { display.create_window_surface(gl_config, &surface_attributes) } -} diff --git a/glutin/src/lib.rs b/glutin/src/lib.rs index 45d6cb5b41..33afd66435 100644 --- a/glutin/src/lib.rs +++ b/glutin/src/lib.rs @@ -29,8 +29,5 @@ pub use iced_winit::*; pub mod application; -#[cfg(feature = "multi_window")] -pub mod multi_window; - #[doc(no_inline)] pub use application::Application; diff --git a/glutin/src/multi_window.rs b/glutin/src/multi_window.rs deleted file mode 100644 index 620d01d8e4..0000000000 --- a/glutin/src/multi_window.rs +++ /dev/null @@ -1,1060 +0,0 @@ -//! Create interactive, native cross-platform applications. -use crate::mouse; -use crate::{Error, Executor, Runtime}; - -pub use iced_winit::multi_window::{self, Application, StyleSheet}; - -use iced_winit::conversion; -use iced_winit::futures; -use iced_winit::futures::channel::mpsc; -use iced_winit::renderer; -use iced_winit::user_interface; -use iced_winit::window; -use iced_winit::winit; -use iced_winit::{Clipboard, Command, Debug, Proxy, Settings}; - -use glutin::config::{ - Config, ConfigSurfaceTypes, ConfigTemplateBuilder, GlConfig, -}; -use glutin::context::{ - ContextApi, ContextAttributesBuilder, NotCurrentContext, - NotCurrentGlContextSurfaceAccessor, PossiblyCurrentGlContext, -}; -use glutin::display::{Display, DisplayApiPreference, GlDisplay}; -use glutin::surface::{GlSurface, SwapInterval}; -use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; - -use crate::application::gl_surface; -use iced_winit::multi_window::Event; -use std::collections::HashMap; -use std::ffi::CString; -use std::mem::ManuallyDrop; -use std::num::NonZeroU32; - -use iced_native::widget::operation; -#[cfg(feature = "tracing")] -use tracing::{info_span, instrument::Instrument}; - -#[allow(unsafe_code)] -const ONE: NonZeroU32 = unsafe { NonZeroU32::new_unchecked(1) }; - -/// Runs an [`Application`] with an executor, compositor, and the provided -/// settings. -pub fn run( - settings: Settings, - compositor_settings: C::Settings, -) -> Result<(), Error> -where - A: Application + 'static, - E: Executor + 'static, - C: iced_graphics::window::GLCompositor + 'static, - ::Theme: StyleSheet, -{ - use futures::task; - use futures::Future; - use winit::event_loop::EventLoopBuilder; - use winit::platform::run_return::EventLoopExtRunReturn; - - #[cfg(feature = "trace")] - let _guard = iced_winit::Profiler::init(); - - let mut debug = Debug::new(); - debug.startup_started(); - - #[cfg(feature = "tracing")] - let _ = info_span!("Application::Glutin", "RUN").entered(); - - let mut event_loop = EventLoopBuilder::with_user_event().build(); - let proxy = event_loop.create_proxy(); - - let runtime = { - let executor = E::new().map_err(Error::ExecutorCreationFailed)?; - let proxy = Proxy::new(event_loop.create_proxy()); - - Runtime::new(executor, proxy) - }; - - let (application, init_command) = { - let flags = settings.flags; - - runtime.enter(|| A::new(flags)) - }; - - let builder = settings.window.into_builder( - &application.title(window::Id::MAIN), - event_loop.primary_monitor(), - settings.id, - ); - - log::info!("Window builder: {:#?}", builder); - - #[allow(unsafe_code)] - let (display, window, configuration, surface, context) = unsafe { - struct Configuration(Config); - use std::fmt; - impl fmt::Debug for Configuration { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let config = &self.0; - - f.debug_struct("Configuration") - .field("raw", &config) - .field("samples", &config.num_samples()) - .field("buffer_type", &config.color_buffer_type()) - .field("surface_type", &config.config_surface_types()) - .field("depth", &config.depth_size()) - .field("alpha", &config.alpha_size()) - .field("stencil", &config.stencil_size()) - .field("float_pixels", &config.float_pixels()) - .field("srgb", &config.srgb_capable()) - .field("api", &config.api()) - .finish() - } - } - - impl AsRef for Configuration { - fn as_ref(&self) -> &Config { - &self.0 - } - } - - let display_handle = event_loop.raw_display_handle(); - - #[cfg(all( - any(windows, target_os = "macos"), - not(target_arch = "wasm32") - ))] - let (window, window_handle) = { - let window = builder - .build(&event_loop) - .map_err(Error::WindowCreationFailed)?; - - let handle = window.raw_window_handle(); - - (window, handle) - }; - - #[cfg(target_arch = "wasm32")] - let preference = Err(Error::GraphicsCreationFailed( - iced_graphics::Error::BackendError(format!( - "target not supported by backend" - )), - ))?; - - #[cfg(all(windows, not(target_arch = "wasm32")))] - let preference = DisplayApiPreference::WglThenEgl(Some(window_handle)); - - #[cfg(all(target_os = "macos", not(target_arch = "wasm32")))] - let preference = DisplayApiPreference::Cgl; - - #[cfg(all( - unix, - not(target_os = "macos"), - not(target_arch = "wasm32") - ))] - let preference = DisplayApiPreference::GlxThenEgl(Box::new( - winit::platform::unix::register_xlib_error_hook, - )); - - let display = - Display::new(display_handle, preference).map_err(|error| { - Error::GraphicsCreationFailed( - iced_graphics::Error::BackendError(format!( - "failed to create display: {error}" - )), - ) - })?; - - log::debug!("Display: {}", display.version_string()); - - let samples = C::sample_count(&compositor_settings) as u8; - let mut template = ConfigTemplateBuilder::new() - .with_surface_type(ConfigSurfaceTypes::WINDOW); - - if samples != 0 { - template = template.with_multisampling(samples); - } - - #[cfg(all(windows, not(target_arch = "wasm32")))] - let template = template.compatible_with_native_window(window_handle); - - log::debug!("Searching for display configurations"); - let configuration = display - .find_configs(template.build()) - .map_err(|_| { - Error::GraphicsCreationFailed( - iced_graphics::Error::NoAvailablePixelFormat, - ) - })? - .map(Configuration) - .inspect(|config| { - log::trace!("{config:#?}"); - }) - .min_by_key(|config| { - config.as_ref().num_samples().saturating_sub(samples) - }) - .ok_or(Error::GraphicsCreationFailed( - iced_graphics::Error::NoAvailablePixelFormat, - ))?; - - log::debug!("Selected: {configuration:#?}"); - - #[cfg(all( - unix, - not(target_os = "macos"), - not(target_arch = "wasm32") - ))] - let (window, window_handle) = { - use glutin::platform::x11::X11GlConfigExt; - let builder = - if let Some(visual) = configuration.as_ref().x11_visual() { - use winit::platform::unix::WindowBuilderExtUnix; - builder.with_x11_visual(visual.into_raw()) - } else { - builder - }; - - let window = builder - .build(&event_loop) - .map_err(Error::WindowCreationFailed)?; - - let handle = window.raw_window_handle(); - - (window, handle) - }; - - let attributes = - ContextAttributesBuilder::new().build(Some(window_handle)); - let fallback_attributes = ContextAttributesBuilder::new() - .with_context_api(ContextApi::Gles(None)) - .build(Some(window_handle)); - - let context = display - .create_context(configuration.as_ref(), &attributes) - .or_else(|_| { - display.create_context( - configuration.as_ref(), - &fallback_attributes, - ) - }) - .map_err(|error| { - Error::GraphicsCreationFailed( - iced_graphics::Error::BackendError(format!( - "failed to create context: {error}" - )), - ) - })?; - - let surface = gl_surface(&display, configuration.as_ref(), &window) - .map_err(|error| { - Error::GraphicsCreationFailed( - iced_graphics::Error::BackendError(format!( - "failed to create surface: {error}" - )), - ) - })?; - - (display, window, configuration.0, surface, context) - }; - - let windows: HashMap = - HashMap::from([(window::Id::MAIN, window)]); - - // need to make context current before trying to load GL functions - let context = context - .make_current(&surface) - .expect("Make context current."); - - #[allow(unsafe_code)] - let (compositor, renderer) = unsafe { - C::new(compositor_settings, |address| { - let address = CString::new(address).expect("address error"); - display.get_proc_address(address.as_c_str()) - })? - }; - - let context = context.make_not_current().expect("Make not current."); - - let (mut sender, receiver) = mpsc::unbounded(); - - let mut instance = Box::pin({ - let run_instance = run_instance::( - application, - compositor, - renderer, - runtime, - proxy, - debug, - receiver, - display, - windows, - configuration, - context, - init_command, - settings.exit_on_close_request, - ); - - #[cfg(feature = "tracing")] - let run_instance = - run_instance.instrument(info_span!("Application", "LOOP")); - - run_instance - }); - - let mut context = task::Context::from_waker(task::noop_waker_ref()); - - let _ = event_loop.run_return(move |event, event_loop, control_flow| { - use winit::event_loop::ControlFlow; - - if let ControlFlow::ExitWithCode(_) = control_flow { - 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, - }), - winit::event::Event::UserEvent(Event::NewWindow { - id, - settings, - title, - }) => { - let window = settings - .into_builder(&title, event_loop.primary_monitor(), None) - .build(event_loop) - .expect("Failed to build window"); - - Some(winit::event::Event::UserEvent(Event::WindowCreated( - id, window, - ))) - } - _ => 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, - }; - } - }); - - Ok(()) -} - -async fn run_instance( - mut application: A, - mut compositor: C, - mut renderer: A::Renderer, - mut runtime: Runtime>, Event>, - mut proxy: winit::event_loop::EventLoopProxy>, - mut debug: Debug, - mut receiver: mpsc::UnboundedReceiver< - winit::event::Event<'_, Event>, - >, - display: Display, - mut windows: HashMap, - configuration: Config, - mut context: NotCurrentContext, - init_command: Command, - _exit_on_close_request: bool, -) where - A: Application + 'static, - E: Executor + 'static, - C: iced_graphics::window::GLCompositor + 'static, - ::Theme: StyleSheet, -{ - use iced_winit::futures::stream::StreamExt; - use winit::event; - - let mut clipboard = - Clipboard::connect(windows.values().next().expect("No window found")); - let mut caches = HashMap::new(); - let mut current_context_window = None; - let mut window_ids: HashMap<_, _> = windows - .iter() - .map(|(&id, window)| (window.id(), id)) - .collect(); - let mut states = HashMap::new(); - let mut surfaces = HashMap::new(); - let mut interfaces = ManuallyDrop::new(HashMap::new()); - - for (&id, window) in windows.keys().zip(windows.values()) { - let surface = gl_surface(&display, &configuration, &window) - .expect("Create surface."); - let current_context = - context.make_current(&surface).expect("Make current."); - let state = multi_window::State::new(&application, id, &window); - let physical_size = state.physical_size(); - - surface.resize( - ¤t_context, - NonZeroU32::new(physical_size.width).unwrap_or(ONE), - NonZeroU32::new(physical_size.height).unwrap_or(ONE), - ); - - let user_interface = multi_window::build_user_interface( - &application, - user_interface::Cache::default(), - &mut renderer, - state.logical_size(), - &mut debug, - id, - ); - - context = current_context - .make_not_current() - .expect("Make not current."); - - let _ = states.insert(id, state); - let _ = surfaces.insert(id, surface); - let _ = interfaces.insert(id, user_interface); - } - - run_command( - &application, - &mut caches, - &states, - &mut renderer, - init_command, - &mut runtime, - &mut clipboard, - &mut proxy, - &mut debug, - &windows, - || compositor.fetch_information(), - ); - - runtime.track(application.subscription().map(Event::Application)); - - let mut mouse_interaction = mouse::Interaction::default(); - let mut events = Vec::new(); - let mut messages = Vec::new(); - - debug.startup_finished(); - - 'main: while let Some(event) = receiver.next().await { - match event { - event::Event::MainEventsCleared => { - for id in windows.keys().copied() { - let (filtered, remaining): (Vec<_>, Vec<_>) = - events.iter().cloned().partition( - |(window_id, _event): &( - Option, - iced_native::event::Event, - )| { - *window_id == Some(id) || *window_id == None - }, - ); - - events.retain(|el| remaining.contains(el)); - let filtered: Vec<_> = filtered - .into_iter() - .map(|(_id, event)| event) - .collect(); - - let cursor_position = - states.get(&id).unwrap().cursor_position(); - let window = windows.get(&id).unwrap(); - - if filtered.is_empty() && messages.is_empty() { - continue; - } - - debug.event_processing_started(); - - let (interface_state, statuses) = { - let user_interface = interfaces.get_mut(&id).unwrap(); - user_interface.update( - &filtered, - cursor_position, - &mut renderer, - &mut clipboard, - &mut messages, - ) - }; - - debug.event_processing_finished(); - - for event in filtered.into_iter().zip(statuses.into_iter()) - { - runtime.broadcast(event); - } - - if !messages.is_empty() - || matches!( - interface_state, - user_interface::State::Outdated - ) - { - let user_interfaces: HashMap<_, _> = - ManuallyDrop::into_inner(interfaces) - .drain() - .map(|(id, interface)| { - (id, interface.into_cache()) - }) - .collect(); - - // Update application - update( - &mut application, - &mut caches, - &states, - &mut renderer, - &mut runtime, - &mut clipboard, - &mut proxy, - &mut debug, - &mut messages, - &windows, - || compositor.fetch_information(), - ); - - // Update window - states.get_mut(&id).unwrap().synchronize( - &application, - id, - windows.get(&id).expect("No window found with ID."), - ); - - let should_exit = application.should_exit(); - - interfaces = ManuallyDrop::new(build_user_interfaces( - &application, - &mut renderer, - &mut debug, - &states, - user_interfaces, - )); - - if should_exit { - break 'main; - } - } - - debug.draw_started(); - let new_mouse_interaction = { - let user_interface = interfaces.get_mut(&id).unwrap(); - let state = states.get(&id).unwrap(); - - user_interface.draw( - &mut renderer, - state.theme(), - &renderer::Style { - text_color: state.text_color(), - }, - state.cursor_position(), - ) - }; - debug.draw_finished(); - - if new_mouse_interaction != mouse_interaction { - window.set_cursor_icon(conversion::mouse_interaction( - new_mouse_interaction, - )); - - mouse_interaction = new_mouse_interaction; - } - - window.request_redraw(); - } - } - event::Event::PlatformSpecific(event::PlatformSpecific::MacOS( - event::MacOS::ReceivedUrl(url), - )) => { - use iced_native::event; - events.push(( - None, - iced_native::Event::PlatformSpecific( - event::PlatformSpecific::MacOS( - event::MacOS::ReceivedUrl(url), - ), - ), - )); - } - event::Event::UserEvent(event) => match event { - Event::Application(message) => messages.push(message), - Event::WindowCreated(id, window) => { - let state = - multi_window::State::new(&application, id, &window); - let user_interface = multi_window::build_user_interface( - &application, - user_interface::Cache::default(), - &mut renderer, - state.logical_size(), - &mut debug, - id, - ); - - let surface = gl_surface(&display, &configuration, &window) - .expect("Create surface."); - - let _ = states.insert(id, state); - let _ = interfaces.insert(id, user_interface); - let _ = window_ids.insert(window.id(), id); - let _ = windows.insert(id, window); - let _ = surfaces.insert(id, surface); - } - Event::CloseWindow(id) => { - // TODO(derezzedex): log errors - if let Some(window) = windows.get(&id) { - if window_ids.remove(&window.id()).is_none() { - println!("Failed to remove from `window_ids`!"); - } - } - if states.remove(&id).is_none() { - println!("Failed to remove from `states`!") - } - if interfaces.remove(&id).is_none() { - println!("Failed to remove from `interfaces`!"); - } - if surfaces.remove(&id).is_none() { - println!("Failed to remove from `surfaces`!") - } - if windows.remove(&id).is_none() { - println!("Failed to remove from `windows`!") - } - - if windows.is_empty() { - break 'main; - } - } - Event::NewWindow { .. } => unreachable!(), - }, - event::Event::RedrawRequested(id) => { - #[cfg(feature = "tracing")] - let _ = info_span!("Application", "FRAME").entered(); - - let state = window_ids - .get(&id) - .and_then(|id| states.get_mut(id)) - .unwrap(); - let window = - window_ids.get(&id).and_then(|id| windows.get(id)).unwrap(); - - let surface = window_ids - .get(&id) - .and_then(|id| surfaces.get(id)) - .unwrap(); - - debug.render_started(); - - let current_context = - context.make_current(&surface).expect("Make current."); - - if current_context_window != Some(id) { - current_context_window = Some(id); - } - - if state.viewport_changed() { - let physical_size = state.physical_size(); - let logical_size = state.logical_size(); - - let mut user_interface = window_ids - .get(&id) - .and_then(|id| interfaces.remove(id)) - .unwrap(); - - debug.layout_started(); - user_interface = - user_interface.relayout(logical_size, &mut renderer); - debug.layout_finished(); - - debug.draw_started(); - let new_mouse_interaction = user_interface.draw( - &mut renderer, - state.theme(), - &renderer::Style { - text_color: state.text_color(), - }, - state.cursor_position(), - ); - debug.draw_finished(); - - if new_mouse_interaction != mouse_interaction { - window.set_cursor_icon(conversion::mouse_interaction( - new_mouse_interaction, - )); - - mouse_interaction = new_mouse_interaction; - } - - surface.resize( - ¤t_context, - NonZeroU32::new(physical_size.width).unwrap_or(ONE), - NonZeroU32::new(physical_size.height).unwrap_or(ONE), - ); - - if let Err(_) = surface.set_swap_interval( - ¤t_context, - SwapInterval::Wait(ONE), - ) { - log::error!("Could not set swap interval for surface attached to window id: {:?}", id); - } - - compositor.resize_viewport(physical_size); - - let _ = interfaces - .insert(*window_ids.get(&id).unwrap(), user_interface); - } - - compositor.present( - &mut renderer, - state.viewport(), - state.background_color(), - &debug.overlay(), - ); - - surface - .swap_buffers(¤t_context) - .expect("Swap buffers"); - - context = current_context - .make_not_current() - .expect("Make not current."); - debug.render_finished(); - // TODO: Handle animations! - // Maybe we can use `ControlFlow::WaitUntil` for this. - } - event::Event::WindowEvent { - event: window_event, - window_id, - } => { - // dbg!(window_id); - if let Some(window) = - window_ids.get(&window_id).and_then(|id| windows.get(id)) - { - if let Some(state) = window_ids - .get(&window_id) - .and_then(|id| states.get_mut(id)) - { - if multi_window::requests_exit( - &window_event, - state.modifiers(), - ) { - if let Some(id) = - window_ids.get(&window_id).cloned() - { - let message = application.close_requested(id); - messages.push(message); - } - } - - state.update(window, &window_event, &mut debug); - - if let Some(event) = conversion::window_event( - *window_ids.get(&window_id).unwrap(), - &window_event, - state.scale_factor(), - state.modifiers(), - ) { - events.push(( - window_ids.get(&window_id).cloned(), - event, - )); - } - } else { - log::error!( - "Window state not found for id: {:?}", - window_id - ); - } - } else { - log::error!("Window not found for id: {:?}", window_id); - } - } - _ => {} - } - } - - // Manually drop the user interface - // drop(ManuallyDrop::into_inner(user_interface)); -} - -/// Updates an [`Application`] by feeding it the provided messages, spawning any -/// resulting [`Command`], and tracking its [`Subscription`]. -pub fn update( - application: &mut A, - caches: &mut HashMap, - states: &HashMap>, - renderer: &mut A::Renderer, - runtime: &mut Runtime>, Event>, - clipboard: &mut Clipboard, - proxy: &mut winit::event_loop::EventLoopProxy>, - debug: &mut Debug, - messages: &mut Vec, - windows: &HashMap, - graphics_info: impl FnOnce() -> iced_graphics::compositor::Information + Copy, -) where - A: Application + 'static, - ::Theme: StyleSheet, -{ - for message in messages.drain(..) { - debug.log_message(&message); - - debug.update_started(); - let command = runtime.enter(|| application.update(message)); - debug.update_finished(); - - run_command( - application, - caches, - &states, - renderer, - command, - runtime, - clipboard, - proxy, - debug, - windows, - graphics_info, - ); - } - - let subscription = application.subscription().map(Event::Application); - runtime.track(subscription); -} - -/// Runs the actions of a [`Command`]. -pub fn run_command( - application: &A, - caches: &mut HashMap, - states: &HashMap>, - renderer: &mut A::Renderer, - command: Command, - runtime: &mut Runtime>, Event>, - clipboard: &mut Clipboard, - proxy: &mut winit::event_loop::EventLoopProxy>, - debug: &mut Debug, - windows: &HashMap, - _graphics_info: impl FnOnce() -> iced_graphics::compositor::Information + Copy, -) where - A: Application + 'static, - E: Executor, - ::Theme: StyleSheet, -{ - use iced_native::command; - use iced_native::system; - use iced_native::window; - use iced_winit::clipboard; - use iced_winit::futures::FutureExt; - - for action in command.actions() { - match action { - command::Action::Future(future) => { - runtime.spawn(Box::pin(future.map(Event::Application))); - } - command::Action::Clipboard(action) => match action { - clipboard::Action::Read(tag) => { - let message = tag(clipboard.read()); - - proxy - .send_event(Event::Application(message)) - .expect("Send message to event loop"); - } - clipboard::Action::Write(contents) => { - clipboard.write(contents); - } - }, - command::Action::Window(id, action) => match action { - window::Action::Spawn { settings } => { - proxy - .send_event(Event::NewWindow { - id, - settings: settings.into(), - title: application.title(id), - }) - .expect("Send message to event loop"); - } - window::Action::Close => { - proxy - .send_event(Event::CloseWindow(id)) - .expect("Send message to event loop"); - } - window::Action::Drag => { - let window = windows.get(&id).expect("No window found"); - let _res = window.drag_window(); - } - window::Action::Resize { width, height } => { - let window = windows.get(&id).expect("No window found"); - window.set_inner_size(winit::dpi::LogicalSize { - width, - height, - }); - } - window::Action::Move { x, y } => { - let window = windows.get(&id).expect("No window found"); - window.set_outer_position(winit::dpi::LogicalPosition { - x, - y, - }); - } - window::Action::ChangeMode(mode) => { - let window = windows.get(&id).expect("No window found"); - window.set_visible(conversion::visible(mode)); - window.set_fullscreen(conversion::fullscreen( - window.primary_monitor(), - mode, - )); - } - window::Action::FetchMode(tag) => { - let window = windows.get(&id).expect("No window found"); - let mode = if window.is_visible().unwrap_or(true) { - conversion::mode(window.fullscreen()) - } else { - window::Mode::Hidden - }; - - proxy - .send_event(Event::Application(tag(mode))) - .expect("Send message to event loop"); - } - window::Action::Maximize(value) => { - let window = windows.get(&id).expect("No window found!"); - window.set_maximized(value); - } - window::Action::Minimize(value) => { - let window = windows.get(&id).expect("No window found!"); - window.set_minimized(value); - } - window::Action::ToggleMaximize => { - let window = windows.get(&id).expect("No window found!"); - window.set_maximized(!window.is_maximized()); - } - window::Action::ToggleDecorations => { - let window = windows.get(&id).expect("No window found!"); - window.set_decorations(!window.is_decorated()); - } - window::Action::RequestUserAttention(attention_type) => { - let window = windows.get(&id).expect("No window found!"); - window.request_user_attention( - attention_type.map(conversion::user_attention), - ); - } - window::Action::GainFocus => { - let window = windows.get(&id).expect("No window found!"); - window.focus_window(); - } - window::Action::ChangeAlwaysOnTop(on_top) => { - let window = windows.get(&id).expect("No window found!"); - window.set_always_on_top(on_top); - } - window::Action::FetchId(tag) => { - let window = windows.get(&id).expect("No window found!"); - - proxy - .send_event(Event::Application(tag(window.id().into()))) - .expect("Send message to event loop.") - } - }, - command::Action::System(action) => match action { - system::Action::QueryInformation(_tag) => { - #[cfg(feature = "iced_winit/system")] - { - let graphics_info = _graphics_info(); - let proxy = proxy.clone(); - - let _ = std::thread::spawn(move || { - let information = - crate::system::information(graphics_info); - - let message = _tag(information); - - proxy - .send_event(Event::Application(message)) - .expect("Send message to event loop") - }); - } - } - }, - command::Action::Widget(action) => { - let mut current_caches = std::mem::take(caches); - let mut current_operation = Some(action.into_operation()); - - let mut user_interfaces = multi_window::build_user_interfaces( - application, - renderer, - debug, - states, - current_caches, - ); - - while let Some(mut operation) = current_operation.take() { - for user_interface in user_interfaces.values_mut() { - user_interface.operate(renderer, operation.as_mut()); - - match operation.finish() { - operation::Outcome::None => {} - operation::Outcome::Some(message) => { - proxy - .send_event(Event::Application(message)) - .expect("Send message to event loop"); - } - operation::Outcome::Chain(next) => { - current_operation = Some(next); - } - } - } - } - - let user_interfaces: HashMap<_, _> = user_interfaces - .drain() - .map(|(id, interface)| (id, interface.into_cache())) - .collect(); - - current_caches = user_interfaces; - *caches = current_caches; - } - } - } -} - -/// TODO(derezzedex) -pub fn build_user_interfaces<'a, A>( - application: &'a A, - renderer: &mut A::Renderer, - debug: &mut Debug, - states: &HashMap>, - mut user_interfaces: HashMap, -) -> HashMap< - window::Id, - iced_winit::UserInterface< - 'a, - ::Message, - ::Renderer, - >, -> -where - A: Application + 'static, - ::Theme: StyleSheet, -{ - let mut interfaces = HashMap::new(); - - for (id, pure_state) in user_interfaces.drain() { - let state = &states.get(&id).unwrap(); - - let user_interface = multi_window::build_user_interface( - application, - pure_state, - renderer, - state.logical_size(), - debug, - id, - ); - - let _ = interfaces.insert(id, user_interface); - } - - interfaces -} diff --git a/graphics/src/window/gl_compositor.rs b/graphics/src/window/gl_compositor.rs index e6ae2364f9..a45a7ca114 100644 --- a/graphics/src/window/gl_compositor.rs +++ b/graphics/src/window/gl_compositor.rs @@ -30,7 +30,7 @@ pub trait GLCompositor: Sized { /// The settings of the [`GLCompositor`]. /// /// It's up to you to decide the configuration supported by your renderer! - type Settings: Default + Clone; + type Settings: Default; /// Creates a new [`GLCompositor`] and [`Renderer`] with the given /// [`Settings`] and an OpenGL address loader function. diff --git a/native/src/window/id.rs b/native/src/window/id.rs index fa9761f586..0c3e52728c 100644 --- a/native/src/window/id.rs +++ b/native/src/window/id.rs @@ -4,12 +4,10 @@ use std::hash::{Hash, Hasher}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] /// The ID of the window. -/// -/// This is not necessarily the same as the window ID fetched from `winit::window::Window`. pub struct Id(u64); impl Id { - /// TODO(derezzedex): maybe change `u64` to an enum `Type::{Single, Multi(u64)}` + /// The reserved window ID for the primary window in an Iced application. pub const MAIN: Self = Id(0); /// Creates a new unique window ID. diff --git a/src/lib.rs b/src/lib.rs index 993e94b19d..65fe3b93f8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -182,7 +182,7 @@ pub mod touch; pub mod widget; pub mod window; -#[cfg(feature = "multi_window")] +#[cfg(all(not(feature = "glow"), feature = "multi_window"))] pub mod multi_window; #[cfg(all(not(feature = "glow"), feature = "wgpu"))] diff --git a/winit/src/application.rs b/winit/src/application.rs index 58556da46b..1310ba1ca8 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -734,7 +734,7 @@ pub fn run_command( clipboard.write(contents); } }, - command::Action::Window(_id, action) => match action { + command::Action::Window(_, action) => match action { window::Action::Close => { *should_exit = true; } diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 1a9d4a1ccd..eac8b26078 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -1,4 +1,4 @@ -//! Create interactive, native cross-platform applications. +//! Create interactive, native cross-platform applications for WGPU. mod state; pub use state::State; @@ -31,17 +31,14 @@ pub use crate::Profiler; #[cfg(feature = "trace")] use tracing::{info_span, instrument::Instrument}; -/// TODO(derezzedex) -// This is the an wrapper around the `Application::Message` associate type -// to allows the `shell` to create internal messages, while still having -// the current user specified custom messages. +/// This is a wrapper around the `Application::Message` associate type +/// to allows the `shell` to create internal messages, while still having +/// the current user specified custom messages. #[derive(Debug)] pub enum Event { /// An [`Application`] generated message Application(Message), - /// TODO(derezzedex) - // Create a wrapper variant of `window::Event` type instead - // (maybe we should also allow users to listen/react to those internal messages?) + /// A message which spawns a new window. NewWindow { /// The [window::Id] of the newly spawned [`Window`]. id: window::Id, @@ -50,9 +47,9 @@ pub enum Event { /// The title of the newly spawned [`Window`]. title: String, }, - /// TODO(derezzedex) + /// Close a window. CloseWindow(window::Id), - /// TODO(derezzedex) + /// A message for when the window has finished being created. WindowCreated(window::Id, winit::window::Window), } @@ -90,7 +87,7 @@ where /// background by shells. fn update(&mut self, message: Self::Message) -> Command; - /// Returns the widgets to display in the [`Program`]. + /// Returns the widgets to display for the `window` in the [`Program`]. /// /// These widgets can produce __messages__ based on user interaction. fn view( @@ -108,7 +105,7 @@ where /// load state from a file, perform an initial HTTP request, etc. fn new(flags: Self::Flags) -> (Self, Command); - /// Returns the current title of the current [`Application`] window. + /// Returns the current title of each [`Application`] window. /// /// This title can be dynamic! The runtime will automatically update the /// title of your application when necessary. @@ -137,7 +134,7 @@ where Subscription::none() } - /// Returns the scale factor of the [`Application`]. + /// Returns the scale factor of the window of the [`Application`]. /// /// It can be used to dynamically control the size of the UI at runtime /// (i.e. zooming). @@ -1142,7 +1139,7 @@ pub fn run_command( } } -/// TODO(derezzedex) +/// Build the user interfaces for every window. pub fn build_user_interfaces<'a, A>( application: &'a A, renderer: &mut A::Renderer, diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index 35c6992426..a7e65de769 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -8,7 +8,7 @@ use std::marker::PhantomData; use winit::event::{Touch, WindowEvent}; use winit::window::Window; -/// The state of a windowed [`Application`]. +/// The state of a multi-windowed [`Application`]. #[allow(missing_debug_implementations)] pub struct State where @@ -29,7 +29,7 @@ impl State where ::Theme: application::StyleSheet, { - /// Creates a new [`State`] for the provided [`Application`]'s window. + /// Creates a new [`State`] for the provided [`Application`]'s `window`. pub fn new( application: &A, window_id: window::Id, @@ -116,8 +116,7 @@ where self.appearance.text_color } - /// Processes the provided window event and updates the [`State`] - /// accordingly. + /// Processes the provided window event and updates the [`State`] accordingly. pub fn update( &mut self, window: &Window, diff --git a/winit/src/profiler.rs b/winit/src/profiler.rs index ff9bbdc0fa..7031507a21 100644 --- a/winit/src/profiler.rs +++ b/winit/src/profiler.rs @@ -21,7 +21,6 @@ pub struct Profiler { impl Profiler { /// Initializes the [`Profiler`]. pub fn init() -> Self { - log::info!("Capturing trace.."); // Registry stores the spans & generates unique span IDs let subscriber = Registry::default(); diff --git a/winit/src/settings.rs b/winit/src/settings.rs index b26de54238..88d7c1deab 100644 --- a/winit/src/settings.rs +++ b/winit/src/settings.rs @@ -179,9 +179,9 @@ impl Window { { use winit::platform::windows::WindowBuilderExtWindows; - // if let Some(parent) = self.platform_specific.parent { - // window_builder = window_builder.with_parent_window(parent); - // } + if let Some(parent) = self.platform_specific.parent { + window_builder = window_builder.with_parent_window(parent); + } window_builder = window_builder .with_drag_and_drop(self.platform_specific.drag_and_drop); @@ -227,7 +227,7 @@ impl From for Window { fn from(settings: iced_native::window::Settings) -> Self { Self { size: settings.size, - position: Position::from(settings.position), + position: settings.position, min_size: settings.min_size, max_size: settings.max_size, visible: settings.visible, diff --git a/winit/src/settings/windows.rs b/winit/src/settings/windows.rs index 0891ec2c94..ff03a9c51e 100644 --- a/winit/src/settings/windows.rs +++ b/winit/src/settings/windows.rs @@ -4,7 +4,7 @@ #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PlatformSpecific { /// Parent window - // pub parent: Option, + pub parent: Option, /// Drag and drop support pub drag_and_drop: bool, @@ -13,7 +13,7 @@ pub struct PlatformSpecific { impl Default for PlatformSpecific { fn default() -> Self { Self { - // parent: None, + parent: None, drag_and_drop: true, } } From 8ba18430800142965549077373e2a45d0a3429a1 Mon Sep 17 00:00:00 2001 From: Bingus Date: Mon, 13 Mar 2023 14:16:45 -0700 Subject: [PATCH 47/66] Code cleanup, clearer comments + removed some unnecessary dupe; Removed `Frames` struct return for `window::frames()` since we are just redrawing every window anyways; Interface dropping; --- Cargo.toml | 4 +- examples/multi_window/Cargo.toml | 2 +- examples/solar_system/src/main.rs | 2 +- native/src/window.rs | 15 +--- src/lib.rs | 2 +- src/multi_window/application.rs | 5 +- winit/Cargo.toml | 2 +- winit/src/application.rs | 2 +- winit/src/lib.rs | 2 +- winit/src/multi_window.rs | 126 +++++++++++------------------- winit/src/multi_window/state.rs | 2 +- 11 files changed, 60 insertions(+), 104 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5276d92187..7f89b05e49 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,8 +46,8 @@ chrome-trace = [ "iced_wgpu?/tracing", "iced_glow?/tracing", ] -# Enables experimental multi-window support for iced_winit -multi_window = ["iced_winit/multi_window"] +# Enables experimental multi-window support for iced_winit + wgpu. +multi-window = ["iced_winit/multi-window"] [badges] maintenance = { status = "actively-developed" } diff --git a/examples/multi_window/Cargo.toml b/examples/multi_window/Cargo.toml index 0bb83f37ae..a59a0e6873 100644 --- a/examples/multi_window/Cargo.toml +++ b/examples/multi_window/Cargo.toml @@ -7,7 +7,7 @@ publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -iced = { path = "../..", features = ["debug", "multi_window", "tokio"] } +iced = { path = "../..", features = ["debug", "multi-window", "tokio"] } env_logger = "0.10.0" iced_native = { path = "../../native" } iced_lazy = { path = "../../lazy" } diff --git a/examples/solar_system/src/main.rs b/examples/solar_system/src/main.rs index eb461bb090..9a4ee7549a 100644 --- a/examples/solar_system/src/main.rs +++ b/examples/solar_system/src/main.rs @@ -89,7 +89,7 @@ impl Application for SolarSystem { } fn subscription(&self) -> Subscription { - window::frames().map(|frame| Message::Tick(frame.at)) + window::frames().map(Message::Tick) } } diff --git a/native/src/window.rs b/native/src/window.rs index a8f8b10f92..660cd54f3a 100644 --- a/native/src/window.rs +++ b/native/src/window.rs @@ -30,20 +30,9 @@ use crate::time::Instant; /// /// In any case, this [`Subscription`] is useful to smoothly draw application-driven /// animations without missing any frames. -pub fn frames() -> Subscription { +pub fn frames() -> Subscription { subscription::raw_events(|event, _status| match event { - crate::Event::Window(id, Event::RedrawRequested(at)) => { - Some(Frame { id, at }) - } + crate::Event::Window(_, Event::RedrawRequested(at)) => Some(at), _ => None, }) } - -/// The returned `Frame` for a framerate subscription. -#[derive(Debug)] -pub struct Frame { - /// The `window::Id` that the `Frame` was produced in. - pub id: Id, - /// The `Instant` at which the frame was produced. - pub at: Instant, -} diff --git a/src/lib.rs b/src/lib.rs index 65fe3b93f8..e7481c7751 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -182,7 +182,7 @@ pub mod touch; pub mod widget; pub mod window; -#[cfg(all(not(feature = "glow"), feature = "multi_window"))] +#[cfg(all(not(feature = "glow"), feature = "multi-window"))] pub mod multi_window; #[cfg(all(not(feature = "glow"), feature = "wgpu"))] diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index d0b515ab13..1fb4bcd415 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -139,7 +139,7 @@ pub trait Application: Sized { window: window::Id, ) -> Element<'_, Self::Message, crate::Renderer>; - /// Returns the scale factor of the [`Application`]. + /// Returns the scale factor of the `window` of the [`Application`]. /// /// It can be used to dynamically control the size of the UI at runtime /// (i.e. zooming). @@ -160,7 +160,8 @@ pub trait Application: Sized { false } - /// Requests that the [`window`] be closed. + /// Returns the `Self::Message` that should be processed when a `window` is requested to + /// be closed. fn close_requested(&self, window: window::Id) -> Self::Message; /// Runs the [`Application`]. diff --git a/winit/Cargo.toml b/winit/Cargo.toml index 7de6952812..9efd18901a 100644 --- a/winit/Cargo.toml +++ b/winit/Cargo.toml @@ -16,7 +16,7 @@ chrome-trace = ["trace", "tracing-chrome"] debug = ["iced_native/debug"] system = ["sysinfo"] application = [] -multi_window = [] +multi-window = [] [dependencies] window_clipboard = "0.2" diff --git a/winit/src/application.rs b/winit/src/application.rs index 906da3c613..fe97486f3b 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -743,7 +743,7 @@ pub fn run_command( } window::Action::Spawn { .. } => { log::info!( - "This is only available on `multi_window::Application`" + "Spawning a window is only available with `multi_window::Application`s." ) } window::Action::Resize { width, height } => { diff --git a/winit/src/lib.rs b/winit/src/lib.rs index fe5768dfb9..54b9c31f4a 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -35,7 +35,7 @@ pub use iced_native::*; pub use winit; -#[cfg(feature = "multi_window")] +#[cfg(feature = "multi-window")] pub mod multi_window; #[cfg(feature = "application")] diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index eac8b26078..d5da406ca8 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -33,7 +33,7 @@ use tracing::{info_span, instrument::Instrument}; /// This is a wrapper around the `Application::Message` associate type /// to allows the `shell` to create internal messages, while still having -/// the current user specified custom messages. +/// the current user-specified custom messages. #[derive(Debug)] pub enum Event { /// An [`Application`] generated message @@ -53,9 +53,9 @@ pub enum Event { WindowCreated(window::Id, winit::window::Window), } -/// An interactive, native cross-platform application. +/// An interactive, native, cross-platform, multi-windowed application. /// -/// This trait is the main entrypoint of Iced. Once implemented, you can run +/// This trait is the main entrypoint of multi-window Iced. Once implemented, you can run /// your GUI application by simply calling [`run`]. It will run in /// its own window. /// @@ -105,7 +105,7 @@ where /// load state from a file, perform an initial HTTP request, etc. fn new(flags: Self::Flags) -> (Self, Command); - /// Returns the current title of each [`Application`] window. + /// Returns the current title of each window of the [`Application`]. /// /// This title can be dynamic! The runtime will automatically update the /// title of your application when necessary. @@ -155,7 +155,8 @@ where false } - /// Requests that the [`window`] be closed. + /// Returns the `Self::Message` that should be processed when a `window` is requested to + /// be closed. fn close_requested(&self, window: window::Id) -> Self::Message; } @@ -462,9 +463,9 @@ async fn run_instance( } debug.event_processing_finished(); - // Update application with app message(s) - // Note: without tying an app message to a window ID, we must redraw all windows - // as we cannot know what changed without some kind of damage tracking. + // Update application with app messages + // Unless we implement some kind of diffing, we must redraw all windows as we + // cannot know what changed. if !messages.is_empty() || matches!( interface_state, @@ -612,9 +613,7 @@ async fn run_instance( } Event::WindowCreated(id, window) => { let mut surface = compositor.create_surface(&window); - let state = State::new(&application, id, &window); - let physical_size = state.physical_size(); compositor.configure_surface( @@ -776,14 +775,12 @@ async fn run_instance( } _ => { debug.render_finished(); + log::error!("Error {error:?} when presenting surface."); - // Try rendering again next frame. - // TODO(derezzedex) - windows - .values() - .next() - .expect("No window found") - .request_redraw(); + // Try rendering windows again next frame. + for window in windows.values() { + window.request_redraw(); + } } }, } @@ -792,80 +789,45 @@ async fn run_instance( event: window_event, window_id, } => { - // dbg!(window_id); - if let Some(window) = - window_ids.get(&window_id).and_then(|id| windows.get(id)) - { - if let Some(state) = window_ids + if let (Some(window), Some(state)) = ( + window_ids.get(&window_id).and_then(|id| windows.get(id)), + window_ids .get(&window_id) - .and_then(|id| states.get_mut(id)) - { - if requests_exit(&window_event, state.modifiers()) { - if let Some(id) = - window_ids.get(&window_id).cloned() - { - let message = application.close_requested(id); - messages.push(message); - } + .and_then(|id| states.get_mut(id)), + ) { + if crate::application::requests_exit(&window_event, state.modifiers()) { + if let Some(id) = window_ids.get(&window_id).cloned() { + let message = application.close_requested(id); + messages.push(message); } + } - state.update(window, &window_event, &mut debug); - - if let Some(event) = conversion::window_event( - *window_ids.get(&window_id).unwrap(), - &window_event, - state.scale_factor(), - state.modifiers(), - ) { - events.push(( - window_ids.get(&window_id).cloned(), - event, - )); - } - } else { - log::error!( - "No window state found for id: {:?}", - window_id - ); + state.update(window, &window_event, &mut debug); + + if let Some(event) = conversion::window_event( + *window_ids.get(&window_id).unwrap(), + &window_event, + state.scale_factor(), + state.modifiers(), + ) { + events + .push((window_ids.get(&window_id).cloned(), event)); } } else { - log::error!("No window found with id: {:?}", window_id); + log::error!( + "Could not find window or state for id: {window_id:?}" + ); } } _ => {} } } - // Manually drop the user interface - // drop(ManuallyDrop::into_inner(user_interface)); -} - -/// Returns true if the provided event should cause an [`Application`] to -/// exit. -pub fn requests_exit( - event: &winit::event::WindowEvent<'_>, - _modifiers: winit::event::ModifiersState, -) -> bool { - use winit::event::WindowEvent; - - match event { - WindowEvent::CloseRequested => true, - #[cfg(target_os = "macos")] - WindowEvent::KeyboardInput { - input: - winit::event::KeyboardInput { - virtual_keycode: Some(winit::event::VirtualKeyCode::Q), - state: winit::event::ElementState::Pressed, - .. - }, - .. - } if _modifiers.logo() => true, - _ => false, - } + // Manually drop the user interfaces + drop(ManuallyDrop::into_inner(interfaces)); } -/// Builds a [`UserInterface`] for the provided [`Application`], logging -/// [`struct@Debug`] information accordingly. +/// Builds a window's [`UserInterface`] for the [`Application`]. pub fn build_user_interface<'a, A: Application>( application: &'a A, cache: user_interface::Cache, @@ -890,7 +852,9 @@ where #[cfg(feature = "trace")] let layout_span = info_span!("Application", "LAYOUT").entered(); debug.layout_started(); + let user_interface = UserInterface::build(view, size, cache, renderer); + #[cfg(feature = "trace")] let _ = layout_span.exit(); debug.layout_finished(); @@ -898,7 +862,7 @@ where user_interface } -/// Updates an [`Application`] by feeding it the provided messages, spawning any +/// Updates an [`Application`] by feeding it messages, spawning any /// resulting [`Command`], and tracking its [`Subscription`]. pub fn update( application: &mut A, @@ -923,7 +887,9 @@ pub fn update( debug.log_message(&message); debug.update_started(); + let command = runtime.enter(|| application.update(message)); + #[cfg(feature = "trace")] let _ = update_span.exit(); debug.update_finished(); @@ -1023,7 +989,7 @@ pub fn run_command( let window = windows.get(&id).expect("No window found"); window.set_visible(conversion::visible(mode)); window.set_fullscreen(conversion::fullscreen( - window.primary_monitor(), + window.current_monitor(), mode, )); } diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index a7e65de769..d0e442d043 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -179,7 +179,7 @@ where /// Synchronizes the [`State`] with its [`Application`] and its respective /// window. /// - /// Normally an [`Application`] should be synchronized with its [`State`] + /// Normally, an [`Application`] should be synchronized with its [`State`] /// and window after calling [`Application::update`]. /// /// [`Application::update`]: crate::Program::update From ce4b2c93d9802dfb8cd3fc9033d76651d4bbc75b Mon Sep 17 00:00:00 2001 From: Bingus Date: Mon, 13 Mar 2023 18:19:16 -0700 Subject: [PATCH 48/66] Added simpler MW example --- examples/multi_window/Cargo.toml | 8 +- examples/multi_window/src/main.rs | 654 ++++-------------------- examples/multi_window_panes/Cargo.toml | 12 + examples/multi_window_panes/src/main.rs | 624 ++++++++++++++++++++++ native/src/window/id.rs | 2 + winit/src/multi_window.rs | 2 +- 6 files changed, 742 insertions(+), 560 deletions(-) create mode 100644 examples/multi_window_panes/Cargo.toml create mode 100644 examples/multi_window_panes/src/main.rs diff --git a/examples/multi_window/Cargo.toml b/examples/multi_window/Cargo.toml index a59a0e6873..0cb5d5469d 100644 --- a/examples/multi_window/Cargo.toml +++ b/examples/multi_window/Cargo.toml @@ -1,13 +1,9 @@ [package] name = "multi_window" version = "0.1.0" -authors = ["Richard Custodio "] +authors = ["Bingus "] edition = "2021" publish = false -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -iced = { path = "../..", features = ["debug", "multi-window", "tokio"] } -env_logger = "0.10.0" -iced_native = { path = "../../native" } -iced_lazy = { path = "../../lazy" } +iced = { path = "../..", features = ["debug", "multi-window"] } \ No newline at end of file diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 60f32a7d0e..5699ece03d 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -1,90 +1,50 @@ -use iced::alignment::{self, Alignment}; -use iced::{executor, time}; -use iced::keyboard; -use iced::multi_window::Application; -use iced::theme::{self, Theme}; -use iced::widget::pane_grid::{self, PaneGrid}; -use iced::widget::{ - button, column, container, pick_list, row, scrollable, text, text_input, +use iced::multi_window::{self, Application}; +use iced::widget::{button, column, container, scrollable, text, text_input}; +use iced::{ + executor, window, Alignment, Command, Element, Length, Settings, Theme, }; -use iced::window; -use iced::{Color, Command, Element, Length, Settings, Size, Subscription}; -use iced_lazy::responsive; -use iced_native::{event, subscription, Event}; - -use iced_native::widget::scrollable::{Properties, RelativeOffset}; -use iced_native::window::Id; use std::collections::HashMap; -use std::time::{Duration, Instant}; - -pub fn main() -> iced::Result { - env_logger::init(); +fn main() -> iced::Result { Example::run(Settings::default()) } +#[derive(Default)] struct Example { + windows_count: usize, windows: HashMap, - panes_created: usize, - count: usize, - _focused: window::Id, } -#[derive(Debug)] struct Window { + id: window::Id, title: String, - scale: f64, - panes: pane_grid::State, - focus: Option, + scale_input: String, + current_scale: f64, } #[derive(Debug, Clone)] enum Message { - Window(window::Id, WindowMessage), - CountIncremented(Instant), -} - -#[derive(Debug, Clone)] -enum WindowMessage { - Split(pane_grid::Axis, pane_grid::Pane), - SplitFocused(pane_grid::Axis), - FocusAdjacent(pane_grid::Direction), - Clicked(pane_grid::Pane), - Dragged(pane_grid::DragEvent), - PopOut(pane_grid::Pane), - Resized(pane_grid::ResizeEvent), - TitleChanged(String), - ToggleMoving(pane_grid::Pane), - TogglePin(pane_grid::Pane), - Close(pane_grid::Pane), - CloseFocused, - SelectedWindow(pane_grid::Pane, SelectableWindow), - CloseWindow, - SnapToggle, + ScaleInputChanged(window::Id, String), + ScaleChanged(window::Id, String), + TitleChanged(window::Id, String), + CloseWindow(window::Id), + NewWindow, } -impl Application for Example { +impl multi_window::Application for Example { type Executor = executor::Default; type Message = Message; type Theme = Theme; type Flags = (); fn new(_flags: ()) -> (Self, Command) { - let (panes, _) = - pane_grid::State::new(Pane::new(0, pane_grid::Axis::Horizontal)); - let window = Window { - panes, - focus: None, - title: String::from("Default window"), - scale: 1.0, - }; - ( Example { - windows: HashMap::from([(window::Id::MAIN, window)]), - panes_created: 1, - count: 0, - _focused: window::Id::MAIN, + windows_count: 0, + windows: HashMap::from([( + window::Id::MAIN, + Window::new(window::Id::MAIN), + )]), }, Command::none(), ) @@ -93,530 +53,118 @@ impl Application for Example { fn title(&self, window: window::Id) -> String { self.windows .get(&window) - .map(|w| w.title.clone()) - .unwrap_or(String::from("New Window")) + .map(|window| window.title.clone()) + .unwrap_or("Example".to_string()) } fn update(&mut self, message: Message) -> Command { match message { - Message::Window(id, message) => match message { - WindowMessage::SnapToggle => { - let window = self.windows.get_mut(&id).unwrap(); - - if let Some(focused) = &window.focus { - let pane = window.panes.get_mut(focused).unwrap(); - - let cmd = scrollable::snap_to( - pane.scrollable_id.clone(), - if pane.snapped { - RelativeOffset::START - } else { - RelativeOffset::END - }, - ); - - pane.snapped = !pane.snapped; - return cmd; - } - } - WindowMessage::Split(axis, pane) => { - let window = self.windows.get_mut(&id).unwrap(); - let result = window.panes.split( - axis, - &pane, - Pane::new(self.panes_created, axis), - ); - - if let Some((pane, _)) = result { - window.focus = Some(pane); - } - - self.panes_created += 1; - } - WindowMessage::SplitFocused(axis) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.focus { - let result = window.panes.split( - axis, - &pane, - Pane::new(self.panes_created, axis), - ); - - if let Some((pane, _)) = result { - window.focus = Some(pane); - } - - self.panes_created += 1; - } - } - WindowMessage::FocusAdjacent(direction) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.focus { - if let Some(adjacent) = - window.panes.adjacent(&pane, direction) - { - window.focus = Some(adjacent); - } - } - } - WindowMessage::Clicked(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - window.focus = Some(pane); - } - WindowMessage::CloseWindow => { - let _ = self.windows.remove(&id); - return window::close(id); - } - WindowMessage::Resized(pane_grid::ResizeEvent { split, ratio }) => { - let window = self.windows.get_mut(&id).unwrap(); - window.panes.resize(&split, ratio); - } - WindowMessage::SelectedWindow(pane, selected) => { - let window = self.windows.get_mut(&id).unwrap(); - let (mut pane, _) = window.panes.close(&pane).unwrap(); - pane.is_moving = false; - - if let Some(window) = self.windows.get_mut(&selected.0) { - let (&first_pane, _) = window.panes.iter().next().unwrap(); - let result = - window.panes.split(pane.axis, &first_pane, pane); - - if let Some((pane, _)) = result { - window.focus = Some(pane); - } - } - } - WindowMessage::ToggleMoving(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.panes.get_mut(&pane) { - pane.is_moving = !pane.is_moving; - } - } - WindowMessage::TitleChanged(title) => { - let window = self.windows.get_mut(&id).unwrap(); - window.title = title; - } - WindowMessage::PopOut(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some((popped, sibling)) = window.panes.close(&pane) { - window.focus = Some(sibling); + Message::ScaleInputChanged(id, scale) => { + let window = + self.windows.get_mut(&id).expect("Window not found!"); + window.scale_input = scale; + } + Message::ScaleChanged(id, scale) => { + let window = + self.windows.get_mut(&id).expect("Window not found!"); + + window.current_scale = scale + .parse::() + .unwrap_or(window.current_scale) + .clamp(0.5, 5.0); + } + Message::TitleChanged(id, title) => { + let window = + self.windows.get_mut(&id).expect("Window not found."); - let (panes, _) = pane_grid::State::new(popped); - let window = Window { - panes, - focus: None, - title: format!("New window ({})", self.windows.len()), - scale: 1.0 + (self.windows.len() as f64 / 10.0), - }; + window.title = title; + } + Message::CloseWindow(id) => { + return window::close(id); + } + Message::NewWindow => { + self.windows_count += 1; + let id = window::Id::new(self.windows_count); + self.windows.insert(id, Window::new(id)); - let window_id = window::Id::new(self.windows.len()); - self.windows.insert(window_id, window); - return window::spawn(window_id, Default::default()); - } - } - WindowMessage::Dragged(pane_grid::DragEvent::Dropped { - pane, - target, - }) => { - let window = self.windows.get_mut(&id).unwrap(); - window.panes.swap(&pane, &target); - } - // WindowMessage::Dragged(pane_grid::DragEvent::Picked { pane }) => { - // println!("Picked {pane:?}"); - // } - WindowMessage::Dragged(_) => {} - WindowMessage::TogglePin(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(Pane { is_pinned, .. }) = - window.panes.get_mut(&pane) - { - *is_pinned = !*is_pinned; - } - } - WindowMessage::Close(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some((_, sibling)) = window.panes.close(&pane) { - window.focus = Some(sibling); - } - } - WindowMessage::CloseFocused => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.focus { - if let Some(Pane { is_pinned, .. }) = - window.panes.get(&pane) - { - if !is_pinned { - if let Some((_, sibling)) = - window.panes.close(&pane) - { - window.focus = Some(sibling); - } - } - } - } - } - }, - Message::CountIncremented(_) => { - self.count += 1; + return window::spawn(id, window::Settings::default()); } } Command::none() } - fn subscription(&self) -> Subscription { - Subscription::batch(vec![ - subscription::events_with(|event, status| { - if let event::Status::Captured = status { - return None; - } - - match event { - Event::Keyboard(keyboard::Event::KeyPressed { - modifiers, - key_code, - }) if modifiers.command() => { - handle_hotkey(key_code).map(|message| { - Message::Window(window::Id::new(0usize), message) - }) - } // TODO(derezzedex) - _ => None, - } - }), - time::every(Duration::from_secs(1)).map(Message::CountIncremented), - ]) - } - - fn view(&self, window_id: window::Id) -> Element { - if let Some(window) = self.windows.get(&window_id) { - let focus = window.focus; - let total_panes = window.panes.len(); - - let window_controls = row![ - text_input( - "Window title", - &window.title, - WindowMessage::TitleChanged, - ), - button(text("Close")) - .on_press(WindowMessage::CloseWindow) - .style(theme::Button::Destructive), - ] - .spacing(5) - .align_items(Alignment::Center); - - let pane_grid = PaneGrid::new(&window.panes, |id, pane, _| { - let is_focused = focus == Some(id); - - let pin_button = button( - text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14), - ) - .on_press(WindowMessage::TogglePin(id)) - .padding(3); - - let title = row![ - pin_button, - "Pane", - text(pane.id.to_string()).style(if is_focused { - PANE_ID_COLOR_FOCUSED - } else { - PANE_ID_COLOR_UNFOCUSED - }), - ] - .spacing(5); - - let title_bar = pane_grid::TitleBar::new(title) - .controls(view_controls( - id, - total_panes, - pane.is_pinned, - pane.is_moving, - &window.title, - window_id, - &self.windows, - )) - .padding(10) - .style(if is_focused { - style::title_bar_focused - } else { - style::title_bar_active - }); + fn view(&self, window: window::Id) -> Element { + let window = self + .windows + .get(&window) + .map(|window| window.view()) + .unwrap(); - pane_grid::Content::new(responsive(move |size| { - view_content( - id, - pane.scrollable_id.clone(), - self.count, - total_panes, - pane.is_pinned, - size, - ) - })) - .title_bar(title_bar) - .style(if is_focused { - style::pane_focused - } else { - style::pane_active - }) - }) + container(window) .width(Length::Fill) .height(Length::Fill) - .spacing(10) - .on_click(WindowMessage::Clicked) - .on_drag(WindowMessage::Dragged) - .on_resize(10, WindowMessage::Resized); - - let content: Element<_> = column![window_controls, pane_grid] - .width(Length::Fill) - .height(Length::Fill) - .padding(10) - .into(); - - return content - .map(move |message| Message::Window(window_id, message)); - } - - container(text("This shouldn't be possible!").size(20)) .center_x() .center_y() .into() } - fn close_requested(&self, window: window::Id) -> Self::Message { - Message::Window(window, WindowMessage::CloseWindow) - } - - fn scale_factor(&self, window: Id) -> f64 { - self.windows.get(&window).map(|w| w.scale).unwrap_or(1.0) - } -} - -const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb( - 0xFF as f32 / 255.0, - 0xC7 as f32 / 255.0, - 0xC7 as f32 / 255.0, -); -const PANE_ID_COLOR_FOCUSED: Color = Color::from_rgb( - 0xFF as f32 / 255.0, - 0x47 as f32 / 255.0, - 0x47 as f32 / 255.0, -); - -fn handle_hotkey(key_code: keyboard::KeyCode) -> Option { - use keyboard::KeyCode; - use pane_grid::{Axis, Direction}; - - let direction = match key_code { - KeyCode::Up => Some(Direction::Up), - KeyCode::Down => Some(Direction::Down), - KeyCode::Left => Some(Direction::Left), - KeyCode::Right => Some(Direction::Right), - _ => None, - }; - - match key_code { - KeyCode::V => Some(WindowMessage::SplitFocused(Axis::Vertical)), - KeyCode::H => Some(WindowMessage::SplitFocused(Axis::Horizontal)), - KeyCode::W => Some(WindowMessage::CloseFocused), - _ => direction.map(WindowMessage::FocusAdjacent), - } -} - -#[derive(Debug, Clone)] -struct SelectableWindow(window::Id, String); - -impl PartialEq for SelectableWindow { - fn eq(&self, other: &Self) -> bool { - self.0 == other.0 + fn scale_factor(&self, window: window::Id) -> f64 { + self.windows + .get(&window) + .map(|window| window.current_scale) + .unwrap_or(1.0) } -} - -impl Eq for SelectableWindow {} -impl std::fmt::Display for SelectableWindow { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.1.fmt(f) + fn close_requested(&self, window: window::Id) -> Self::Message { + Message::CloseWindow(window) } } -#[derive(Debug)] -struct Pane { - id: usize, - pub scrollable_id: scrollable::Id, - pub axis: pane_grid::Axis, - pub is_pinned: bool, - pub is_moving: bool, - pub snapped: bool, -} - -impl Pane { - fn new(id: usize, axis: pane_grid::Axis) -> Self { +impl Window { + fn new(id: window::Id) -> Self { Self { id, - scrollable_id: scrollable::Id::unique(), - axis, - is_pinned: false, - is_moving: false, - snapped: false, + title: "Window".to_string(), + scale_input: "1.0".to_string(), + current_scale: 1.0, } } -} - -fn view_content<'a>( - pane: pane_grid::Pane, - scrollable_id: scrollable::Id, - count: usize, - total_panes: usize, - is_pinned: bool, - size: Size, -) -> Element<'a, WindowMessage> { - let button = |label, message| { - button( - text(label) - .width(Length::Fill) - .horizontal_alignment(alignment::Horizontal::Center) - .size(16), - ) - .width(Length::Fill) - .padding(8) - .on_press(message) - }; - let mut controls = column![ - button( - "Split horizontally", - WindowMessage::Split(pane_grid::Axis::Horizontal, pane), - ), - button( - "Split vertically", - WindowMessage::Split(pane_grid::Axis::Vertical, pane), - ), - button("Snap", WindowMessage::SnapToggle,) - ] - .spacing(5) - .max_width(150); - - if total_panes > 1 && !is_pinned { - controls = controls.push( - button("Close", WindowMessage::Close(pane)) - .style(theme::Button::Destructive), - ); + fn view(&self) -> Element { + window_view(self.id, &self.scale_input, &self.title) } - - let content = column![ - text(format!("{}x{}", size.width, size.height)).size(24), - controls, - text(format!("{count}")).size(48), - ] - .width(Length::Fill) - .height(800) - .spacing(10) - .align_items(Alignment::Center); - - container( - scrollable(content) - .height(Length::Fill) - .vertical_scroll(Properties::new()) - .id(scrollable_id), - ) - .width(Length::Fill) - .height(Length::Fill) - .padding(5) - .center_y() - .into() } -fn view_controls<'a>( - pane: pane_grid::Pane, - total_panes: usize, - is_pinned: bool, - is_moving: bool, - window_title: &'a str, - window_id: window::Id, - windows: &HashMap, -) -> Element<'a, WindowMessage> { - let window_selector = { - let options: Vec<_> = windows - .iter() - .map(|(id, window)| SelectableWindow(*id, window.title.clone())) - .collect(); - pick_list( - options, - Some(SelectableWindow(window_id, window_title.to_string())), - move |window| WindowMessage::SelectedWindow(pane, window), - ) - }; - - let mut move_to = button(text("Move to").size(14)).padding(3); - - let mut pop_out = button(text("Pop Out").size(14)).padding(3); - - let mut close = button(text("Close").size(14)) - .style(theme::Button::Destructive) - .padding(3); - - if total_panes > 1 && !is_pinned { - close = close.on_press(WindowMessage::Close(pane)); - pop_out = pop_out.on_press(WindowMessage::PopOut(pane)); - } - - if windows.len() > 1 && total_panes > 1 && !is_pinned { - move_to = move_to.on_press(WindowMessage::ToggleMoving(pane)); - } - - let mut content = row![].spacing(10); - if is_moving { - content = content.push(pop_out).push(window_selector).push(close); - } else { - content = content.push(pop_out).push(move_to).push(close); - } - - content.into() -} - -mod style { - use iced::widget::container; - use iced::Theme; - - pub fn title_bar_active(theme: &Theme) -> container::Appearance { - let palette = theme.extended_palette(); - - container::Appearance { - text_color: Some(palette.background.strong.text), - background: Some(palette.background.strong.color.into()), - ..Default::default() - } - } - - pub fn title_bar_focused(theme: &Theme) -> container::Appearance { - let palette = theme.extended_palette(); - - container::Appearance { - text_color: Some(palette.primary.strong.text), - background: Some(palette.primary.strong.color.into()), - ..Default::default() - } - } - - pub fn pane_active(theme: &Theme) -> container::Appearance { - let palette = theme.extended_palette(); - - container::Appearance { - background: Some(palette.background.weak.color.into()), - border_width: 2.0, - border_color: palette.background.strong.color, - ..Default::default() - } - } - - pub fn pane_focused(theme: &Theme) -> container::Appearance { - let palette = theme.extended_palette(); +fn window_view<'a>( + id: window::Id, + scale_input: &'a str, + title: &'a str, +) -> Element<'a, Message> { + let scale_input = column![ + text("Window scale factor:"), + text_input("Window Scale", scale_input, move |msg| { + Message::ScaleInputChanged(id, msg) + }) + .on_submit(Message::ScaleChanged(id, scale_input.to_string())) + ]; + + let title_input = column![ + text("Window title:"), + text_input("Window Title", title, move |msg| { + Message::TitleChanged(id, msg) + }) + ]; + + let new_window_button = + button(text("New Window")).on_press(Message::NewWindow); + + let content = scrollable( + column![scale_input, title_input, new_window_button] + .spacing(50) + .width(Length::Fill) + .align_items(Alignment::Center), + ); - container::Appearance { - background: Some(palette.background.weak.color.into()), - border_width: 2.0, - border_color: palette.primary.strong.color, - ..Default::default() - } - } + container(content).width(200).center_x().into() } diff --git a/examples/multi_window_panes/Cargo.toml b/examples/multi_window_panes/Cargo.toml new file mode 100644 index 0000000000..1b3f3ec65d --- /dev/null +++ b/examples/multi_window_panes/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "multi_window_panes" +version = "0.1.0" +authors = ["Richard Custodio "] +edition = "2021" +publish = false + +[dependencies] +iced = { path = "../..", features = ["debug", "multi-window", "tokio"] } +env_logger = "0.10.0" +iced_native = { path = "../../native" } +iced_lazy = { path = "../../lazy" } diff --git a/examples/multi_window_panes/src/main.rs b/examples/multi_window_panes/src/main.rs new file mode 100644 index 0000000000..b8b63769c0 --- /dev/null +++ b/examples/multi_window_panes/src/main.rs @@ -0,0 +1,624 @@ +use iced::alignment::{self, Alignment}; +use iced::{executor, time}; +use iced::keyboard; +use iced::multi_window::Application; +use iced::theme::{self, Theme}; +use iced::widget::pane_grid::{self, PaneGrid}; +use iced::widget::{ + button, column, container, pick_list, row, scrollable, text, text_input, +}; +use iced::window; +use iced::{Color, Command, Element, Length, Settings, Size, Subscription}; +use iced_lazy::responsive; +use iced_native::{event, subscription, Event}; + +use iced_native::widget::scrollable::{Properties, RelativeOffset}; +use iced_native::window::Id; +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +pub fn main() -> iced::Result { + env_logger::init(); + + Example::run(Settings::default()) +} + +struct Example { + windows: HashMap, + panes_created: usize, + count: usize, + _focused: window::Id, +} + +#[derive(Debug)] +struct Window { + title: String, + scale: f64, + panes: pane_grid::State, + focus: Option, +} + +#[derive(Debug, Clone)] +enum Message { + Window(window::Id, WindowMessage), + CountIncremented(Instant), +} + +#[derive(Debug, Clone)] +enum WindowMessage { + Split(pane_grid::Axis, pane_grid::Pane), + SplitFocused(pane_grid::Axis), + FocusAdjacent(pane_grid::Direction), + Clicked(pane_grid::Pane), + Dragged(pane_grid::DragEvent), + PopOut(pane_grid::Pane), + Resized(pane_grid::ResizeEvent), + TitleChanged(String), + ToggleMoving(pane_grid::Pane), + TogglePin(pane_grid::Pane), + Close(pane_grid::Pane), + CloseFocused, + SelectedWindow(pane_grid::Pane, SelectableWindow), + CloseWindow, + SnapToggle, +} + +impl Application for Example { + type Executor = executor::Default; + type Message = Message; + type Theme = Theme; + type Flags = (); + + fn new(_flags: ()) -> (Self, Command) { + let (panes, _) = + pane_grid::State::new(Pane::new(0, pane_grid::Axis::Horizontal)); + let window = Window { + panes, + focus: None, + title: String::from("Default window"), + scale: 1.0, + }; + + ( + Example { + windows: HashMap::from([(window::Id::MAIN, window)]), + panes_created: 1, + count: 0, + _focused: window::Id::MAIN, + }, + Command::none(), + ) + } + + fn title(&self, window: window::Id) -> String { + self.windows + .get(&window) + .map(|w| w.title.clone()) + .unwrap_or(String::from("New Window")) + } + + fn update(&mut self, message: Message) -> Command { + match message { + Message::Window(id, message) => match message { + WindowMessage::SnapToggle => { + let window = self.windows.get_mut(&id).unwrap(); + + if let Some(focused) = &window.focus { + let pane = window.panes.get_mut(focused).unwrap(); + + let cmd = scrollable::snap_to( + pane.scrollable_id.clone(), + if pane.snapped { + RelativeOffset::START + } else { + RelativeOffset::END + }, + ); + + pane.snapped = !pane.snapped; + return cmd; + } + } + WindowMessage::Split(axis, pane) => { + let window = self.windows.get_mut(&id).unwrap(); + let result = window.panes.split( + axis, + &pane, + Pane::new(self.panes_created, axis), + ); + + if let Some((pane, _)) = result { + window.focus = Some(pane); + } + + self.panes_created += 1; + } + WindowMessage::SplitFocused(axis) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.focus { + let result = window.panes.split( + axis, + &pane, + Pane::new(self.panes_created, axis), + ); + + if let Some((pane, _)) = result { + window.focus = Some(pane); + } + + self.panes_created += 1; + } + } + WindowMessage::FocusAdjacent(direction) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.focus { + if let Some(adjacent) = + window.panes.adjacent(&pane, direction) + { + window.focus = Some(adjacent); + } + } + } + WindowMessage::Clicked(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + window.focus = Some(pane); + } + WindowMessage::CloseWindow => { + let _ = self.windows.remove(&id); + return window::close(id); + } + WindowMessage::Resized(pane_grid::ResizeEvent { split, ratio }) => { + let window = self.windows.get_mut(&id).unwrap(); + window.panes.resize(&split, ratio); + } + WindowMessage::SelectedWindow(pane, selected) => { + let window = self.windows.get_mut(&id).unwrap(); + let (mut pane, _) = window.panes.close(&pane).unwrap(); + pane.is_moving = false; + + if let Some(window) = self.windows.get_mut(&selected.0) { + let (&first_pane, _) = window.panes.iter().next().unwrap(); + let result = + window.panes.split(pane.axis, &first_pane, pane); + + if let Some((pane, _)) = result { + window.focus = Some(pane); + } + } + } + WindowMessage::ToggleMoving(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.panes.get_mut(&pane) { + pane.is_moving = !pane.is_moving; + } + } + WindowMessage::TitleChanged(title) => { + let window = self.windows.get_mut(&id).unwrap(); + window.title = title; + } + WindowMessage::PopOut(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some((popped, sibling)) = window.panes.close(&pane) { + window.focus = Some(sibling); + + let (panes, _) = pane_grid::State::new(popped); + let window = Window { + panes, + focus: None, + title: format!("New window ({})", self.windows.len()), + scale: 1.0 + (self.windows.len() as f64 / 10.0), + }; + + let window_id = window::Id::new(self.windows.len()); + self.windows.insert(window_id, window); + return window::spawn(window_id, Default::default()); + } + } + WindowMessage::Dragged(pane_grid::DragEvent::Dropped { + pane, + target, + }) => { + let window = self.windows.get_mut(&id).unwrap(); + window.panes.swap(&pane, &target); + } + // WindowMessage::Dragged(pane_grid::DragEvent::Picked { pane }) => { + // println!("Picked {pane:?}"); + // } + WindowMessage::Dragged(_) => {} + WindowMessage::TogglePin(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(Pane { is_pinned, .. }) = + window.panes.get_mut(&pane) + { + *is_pinned = !*is_pinned; + } + } + WindowMessage::Close(pane) => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some((_, sibling)) = window.panes.close(&pane) { + window.focus = Some(sibling); + } + } + WindowMessage::CloseFocused => { + let window = self.windows.get_mut(&id).unwrap(); + if let Some(pane) = window.focus { + if let Some(Pane { is_pinned, .. }) = + window.panes.get(&pane) + { + if !is_pinned { + if let Some((_, sibling)) = + window.panes.close(&pane) + { + window.focus = Some(sibling); + } + } + } + } + } + }, + Message::CountIncremented(_) => { + self.count += 1; + } + } + + Command::none() + } + + fn subscription(&self) -> Subscription { + Subscription::batch(vec![ + subscription::events_with(|event, status| { + if let event::Status::Captured = status { + return None; + } + + match event { + Event::Keyboard(keyboard::Event::KeyPressed { + modifiers, + key_code, + }) if modifiers.command() => { + handle_hotkey(key_code).map(|message| { + Message::Window(window::Id::new(0usize), message) + }) + } // TODO(derezzedex) + _ => None, + } + }), + time::every(Duration::from_secs(1)).map(Message::CountIncremented), + ]) + } + + fn view(&self, window: window::Id) -> Element { + let window_id = window; + + if let Some(window) = self.windows.get(&window) { + let focus = window.focus; + let total_panes = window.panes.len(); + + let window_controls = row![ + text_input( + "Window title", + &window.title, + WindowMessage::TitleChanged, + ), + button(text("Close")) + .on_press(WindowMessage::CloseWindow) + .style(theme::Button::Destructive), + ] + .spacing(5) + .align_items(Alignment::Center); + + let pane_grid = PaneGrid::new(&window.panes, |id, pane, _| { + let is_focused = focus == Some(id); + + let pin_button = button( + text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14), + ) + .on_press(WindowMessage::TogglePin(id)) + .padding(3); + + let title = row![ + pin_button, + "Pane", + text(pane.id.to_string()).style(if is_focused { + PANE_ID_COLOR_FOCUSED + } else { + PANE_ID_COLOR_UNFOCUSED + }), + ] + .spacing(5); + + let title_bar = pane_grid::TitleBar::new(title) + .controls(view_controls( + id, + total_panes, + pane.is_pinned, + pane.is_moving, + &window.title, + window_id, + &self.windows, + )) + .padding(10) + .style(if is_focused { + style::title_bar_focused + } else { + style::title_bar_active + }); + + pane_grid::Content::new(responsive(move |size| { + view_content( + id, + pane.scrollable_id.clone(), + self.count, + total_panes, + pane.is_pinned, + size, + ) + })) + .title_bar(title_bar) + .style(if is_focused { + style::pane_focused + } else { + style::pane_active + }) + }) + .width(Length::Fill) + .height(Length::Fill) + .spacing(10) + .on_click(WindowMessage::Clicked) + .on_drag(WindowMessage::Dragged) + .on_resize(10, WindowMessage::Resized); + + let content: Element<_> = column![window_controls, pane_grid] + .width(Length::Fill) + .height(Length::Fill) + .padding(10) + .into(); + + return content + .map(move |message| Message::Window(window_id, message)); + } + + container(text("This shouldn't be possible!").size(20)) + .center_x() + .center_y() + .into() + } + + fn close_requested(&self, window: window::Id) -> Self::Message { + Message::Window(window, WindowMessage::CloseWindow) + } + + fn scale_factor(&self, window: Id) -> f64 { + self.windows.get(&window).map(|w| w.scale).unwrap_or(1.0) + } +} + +const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb( + 0xFF as f32 / 255.0, + 0xC7 as f32 / 255.0, + 0xC7 as f32 / 255.0, +); +const PANE_ID_COLOR_FOCUSED: Color = Color::from_rgb( + 0xFF as f32 / 255.0, + 0x47 as f32 / 255.0, + 0x47 as f32 / 255.0, +); + +fn handle_hotkey(key_code: keyboard::KeyCode) -> Option { + use keyboard::KeyCode; + use pane_grid::{Axis, Direction}; + + let direction = match key_code { + KeyCode::Up => Some(Direction::Up), + KeyCode::Down => Some(Direction::Down), + KeyCode::Left => Some(Direction::Left), + KeyCode::Right => Some(Direction::Right), + _ => None, + }; + + match key_code { + KeyCode::V => Some(WindowMessage::SplitFocused(Axis::Vertical)), + KeyCode::H => Some(WindowMessage::SplitFocused(Axis::Horizontal)), + KeyCode::W => Some(WindowMessage::CloseFocused), + _ => direction.map(WindowMessage::FocusAdjacent), + } +} + +#[derive(Debug, Clone)] +struct SelectableWindow(window::Id, String); + +impl PartialEq for SelectableWindow { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } +} + +impl Eq for SelectableWindow {} + +impl std::fmt::Display for SelectableWindow { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.1.fmt(f) + } +} + +#[derive(Debug)] +struct Pane { + id: usize, + pub scrollable_id: scrollable::Id, + pub axis: pane_grid::Axis, + pub is_pinned: bool, + pub is_moving: bool, + pub snapped: bool, +} + +impl Pane { + fn new(id: usize, axis: pane_grid::Axis) -> Self { + Self { + id, + scrollable_id: scrollable::Id::unique(), + axis, + is_pinned: false, + is_moving: false, + snapped: false, + } + } +} + +fn view_content<'a>( + pane: pane_grid::Pane, + scrollable_id: scrollable::Id, + count: usize, + total_panes: usize, + is_pinned: bool, + size: Size, +) -> Element<'a, WindowMessage> { + let button = |label, message| { + button( + text(label) + .width(Length::Fill) + .horizontal_alignment(alignment::Horizontal::Center) + .size(16), + ) + .width(Length::Fill) + .padding(8) + .on_press(message) + }; + + let mut controls = column![ + button( + "Split horizontally", + WindowMessage::Split(pane_grid::Axis::Horizontal, pane), + ), + button( + "Split vertically", + WindowMessage::Split(pane_grid::Axis::Vertical, pane), + ), + button("Snap", WindowMessage::SnapToggle,) + ] + .spacing(5) + .max_width(150); + + if total_panes > 1 && !is_pinned { + controls = controls.push( + button("Close", WindowMessage::Close(pane)) + .style(theme::Button::Destructive), + ); + } + + let content = column![ + text(format!("{}x{}", size.width, size.height)).size(24), + controls, + text(format!("{count}")).size(48), + ] + .width(Length::Fill) + .height(800) + .spacing(10) + .align_items(Alignment::Center); + + container( + scrollable(content) + .height(Length::Fill) + .vertical_scroll(Properties::new()) + .id(scrollable_id), + ) + .width(Length::Fill) + .height(Length::Fill) + .padding(5) + .center_y() + .into() +} + +fn view_controls<'a>( + pane: pane_grid::Pane, + total_panes: usize, + is_pinned: bool, + is_moving: bool, + window_title: &'a str, + window_id: window::Id, + windows: &HashMap, +) -> Element<'a, WindowMessage> { + let window_selector = { + let options: Vec<_> = windows + .iter() + .map(|(id, window)| SelectableWindow(*id, window.title.clone())) + .collect(); + pick_list( + options, + Some(SelectableWindow(window_id, window_title.to_string())), + move |window| WindowMessage::SelectedWindow(pane, window), + ) + }; + + let mut move_to = button(text("Move to").size(14)).padding(3); + + let mut pop_out = button(text("Pop Out").size(14)).padding(3); + + let mut close = button(text("Close").size(14)) + .style(theme::Button::Destructive) + .padding(3); + + if total_panes > 1 && !is_pinned { + close = close.on_press(WindowMessage::Close(pane)); + pop_out = pop_out.on_press(WindowMessage::PopOut(pane)); + } + + if windows.len() > 1 && total_panes > 1 && !is_pinned { + move_to = move_to.on_press(WindowMessage::ToggleMoving(pane)); + } + + let mut content = row![].spacing(10); + if is_moving { + content = content.push(pop_out).push(window_selector).push(close); + } else { + content = content.push(pop_out).push(move_to).push(close); + } + + content.into() +} + +mod style { + use iced::widget::container; + use iced::Theme; + + pub fn title_bar_active(theme: &Theme) -> container::Appearance { + let palette = theme.extended_palette(); + + container::Appearance { + text_color: Some(palette.background.strong.text), + background: Some(palette.background.strong.color.into()), + ..Default::default() + } + } + + pub fn title_bar_focused(theme: &Theme) -> container::Appearance { + let palette = theme.extended_palette(); + + container::Appearance { + text_color: Some(palette.primary.strong.text), + background: Some(palette.primary.strong.color.into()), + ..Default::default() + } + } + + pub fn pane_active(theme: &Theme) -> container::Appearance { + let palette = theme.extended_palette(); + + container::Appearance { + background: Some(palette.background.weak.color.into()), + border_width: 2.0, + border_color: palette.background.strong.color, + ..Default::default() + } + } + + pub fn pane_focused(theme: &Theme) -> container::Appearance { + let palette = theme.extended_palette(); + + container::Appearance { + background: Some(palette.background.weak.color.into()), + border_width: 2.0, + border_color: palette.primary.strong.color, + ..Default::default() + } + } +} diff --git a/native/src/window/id.rs b/native/src/window/id.rs index 0c3e52728c..0a11b1aaa1 100644 --- a/native/src/window/id.rs +++ b/native/src/window/id.rs @@ -4,6 +4,8 @@ use std::hash::{Hash, Hasher}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] /// The ID of the window. +/// +/// Internally Iced uses `window::Id::MAIN` as the first window spawned. pub struct Id(u64); impl Id { diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index d5da406ca8..6e28f1fa0c 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -109,7 +109,7 @@ where /// /// This title can be dynamic! The runtime will automatically update the /// title of your application when necessary. - fn title(&self, window_id: window::Id) -> String; + fn title(&self, window: window::Id) -> String; /// Returns the current [`Theme`] of the [`Application`]. fn theme(&self) -> ::Theme; From 41836dd80d0534608e7aedfbf2319c540a23de1a Mon Sep 17 00:00:00 2001 From: Bingus Date: Wed, 15 Mar 2023 18:20:38 -0700 Subject: [PATCH 49/66] Added per-window theme support. --- examples/multi_window_panes/src/main.rs | 41 +++++++++++++++++-------- src/multi_window/application.rs | 7 +++-- winit/src/multi_window.rs | 2 +- winit/src/multi_window/state.rs | 4 +-- 4 files changed, 35 insertions(+), 19 deletions(-) diff --git a/examples/multi_window_panes/src/main.rs b/examples/multi_window_panes/src/main.rs index b8b63769c0..b1d0a3bcb1 100644 --- a/examples/multi_window_panes/src/main.rs +++ b/examples/multi_window_panes/src/main.rs @@ -1,5 +1,4 @@ use iced::alignment::{self, Alignment}; -use iced::{executor, time}; use iced::keyboard; use iced::multi_window::Application; use iced::theme::{self, Theme}; @@ -8,6 +7,7 @@ use iced::widget::{ button, column, container, pick_list, row, scrollable, text, text_input, }; use iced::window; +use iced::{executor, time}; use iced::{Color, Command, Element, Length, Settings, Size, Subscription}; use iced_lazy::responsive; use iced_native::{event, subscription, Event}; @@ -34,6 +34,7 @@ struct Example { struct Window { title: String, scale: f64, + theme: Theme, panes: pane_grid::State, focus: Option, } @@ -77,6 +78,7 @@ impl Application for Example { focus: None, title: String::from("Default window"), scale: 1.0, + theme: Theme::default(), }; ( @@ -167,7 +169,10 @@ impl Application for Example { let _ = self.windows.remove(&id); return window::close(id); } - WindowMessage::Resized(pane_grid::ResizeEvent { split, ratio }) => { + WindowMessage::Resized(pane_grid::ResizeEvent { + split, + ratio, + }) => { let window = self.windows.get_mut(&id).unwrap(); window.panes.resize(&split, ratio); } @@ -177,7 +182,8 @@ impl Application for Example { pane.is_moving = false; if let Some(window) = self.windows.get_mut(&selected.0) { - let (&first_pane, _) = window.panes.iter().next().unwrap(); + let (&first_pane, _) = + window.panes.iter().next().unwrap(); let result = window.panes.split(pane.axis, &first_pane, pane); @@ -205,8 +211,16 @@ impl Application for Example { let window = Window { panes, focus: None, - title: format!("New window ({})", self.windows.len()), + title: format!( + "New window ({})", + self.windows.len() + ), scale: 1.0 + (self.windows.len() as f64 / 10.0), + theme: if self.windows.len() % 2 == 0 { + Theme::Light + } else { + Theme::Dark + }, }; let window_id = window::Id::new(self.windows.len()); @@ -215,15 +229,12 @@ impl Application for Example { } } WindowMessage::Dragged(pane_grid::DragEvent::Dropped { - pane, - target, - }) => { + pane, + target, + }) => { let window = self.windows.get_mut(&id).unwrap(); window.panes.swap(&pane, &target); } - // WindowMessage::Dragged(pane_grid::DragEvent::Picked { pane }) => { - // println!("Picked {pane:?}"); - // } WindowMessage::Dragged(_) => {} WindowMessage::TogglePin(pane) => { let window = self.windows.get_mut(&id).unwrap(); @@ -273,9 +284,9 @@ impl Application for Example { match event { Event::Keyboard(keyboard::Event::KeyPressed { - modifiers, - key_code, - }) if modifiers.command() => { + modifiers, + key_code, + }) if modifiers.command() => { handle_hotkey(key_code).map(|message| { Message::Window(window::Id::new(0usize), message) }) @@ -391,6 +402,10 @@ impl Application for Example { fn scale_factor(&self, window: Id) -> f64 { self.windows.get(&window).map(|w| w.scale).unwrap_or(1.0) } + + fn theme(&self, window: Id) -> Theme { + self.windows.get(&window).expect("Window not found!").theme.clone() + } } const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb( diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index 1fb4bcd415..9974128cdf 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -107,7 +107,8 @@ pub trait Application: Sized { /// Returns the current [`Theme`] of the [`Application`]. /// /// [`Theme`]: Self::Theme - fn theme(&self) -> Self::Theme { + #[allow(unused_variables)] + fn theme(&self, window: window::Id) -> Self::Theme { Self::Theme::default() } @@ -229,8 +230,8 @@ where self.0.title(window) } - fn theme(&self) -> A::Theme { - self.0.theme() + fn theme(&self, window: window::Id) -> A::Theme { + self.0.theme(window) } fn style(&self) -> ::Style { diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 6e28f1fa0c..9b395c1d74 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -112,7 +112,7 @@ where fn title(&self, window: window::Id) -> String; /// Returns the current [`Theme`] of the [`Application`]. - fn theme(&self) -> ::Theme; + fn theme(&self, window: window::Id) -> ::Theme; /// Returns the [`Style`] variation of the [`Theme`]. fn style( diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index d0e442d043..54a114ad4f 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -37,7 +37,7 @@ where ) -> Self { let title = application.title(window_id); let scale_factor = application.scale_factor(window_id); - let theme = application.theme(); + let theme = application.theme(window_id); let appearance = theme.appearance(&application.style()); let viewport = { @@ -212,7 +212,7 @@ where } // Update theme and appearance - self.theme = application.theme(); + self.theme = application.theme(window_id); self.appearance = self.theme.appearance(&application.style()); } } From d53ccc857da4d4cda769904342aeb5a82a64f146 Mon Sep 17 00:00:00 2001 From: Bingus Date: Wed, 12 Jul 2023 19:21:05 -0700 Subject: [PATCH 50/66] refactored window storage; new helper window events (Destroyed, Created); clippy + fmt; --- .github/ISSUE_TEMPLATE/BUG-REPORT.yml | 1 - Cargo.toml | 2 +- ECOSYSTEM.md | 8 +- core/Cargo.toml | 3 + core/src/window.rs | 6 + core/src/window/event.rs | 17 + core/src/window/id.rs | 15 +- core/src/window/position.rs | 22 + core/src/window/settings.rs | 40 +- .../src => core/src/window}/settings/macos.rs | 0 .../src => core/src/window}/settings/other.rs | 0 .../src => core/src/window}/settings/wasm.rs | 0 .../src/window}/settings/windows.rs | 0 examples/events/src/main.rs | 7 +- examples/exit/src/main.rs | 2 +- examples/integration/src/main.rs | 2 +- examples/integration_opengl/src/main.rs | 0 examples/loading_spinners/src/circular.rs | 2 +- examples/loading_spinners/src/linear.rs | 2 +- examples/multi_window/Cargo.toml | 2 +- examples/multi_window/src/main.rs | 162 ++- examples/multi_window_panes/Cargo.toml | 12 - examples/multi_window_panes/src/main.rs | 639 ---------- examples/screenshot/src/main.rs | 7 +- examples/toast/src/main.rs | 4 +- examples/todos/src/main.rs | 2 +- futures/src/subscription.rs | 2 +- glutin/src/application.rs | 0 graphics/Cargo.toml | 1 - graphics/src/compositor.rs | 3 + native/src/subscription.rs | 0 native/src/window.rs | 0 renderer/src/compositor.rs | 16 + runtime/Cargo.toml | 1 + runtime/src/lib.rs | 3 + runtime/src/multi_window.rs | 6 + runtime/src/multi_window/program.rs | 32 + runtime/src/multi_window/state.rs | 280 +++++ runtime/src/window.rs | 102 +- runtime/src/window/action.rs | 4 +- src/multi_window/application.rs | 96 +- src/settings.rs | 2 +- src/window.rs | 4 - {winit/src => src/window}/icon.rs | 0 tiny_skia/src/window/compositor.rs | 6 + wgpu/src/window/compositor.rs | 4 + winit/Cargo.toml | 22 +- winit/src/application.rs | 86 +- winit/src/conversion.rs | 9 +- winit/src/lib.rs | 8 +- winit/src/multi_window.rs | 1078 ++++++++--------- winit/src/multi_window/state.rs | 96 +- winit/src/multi_window/windows.rs | 170 +++ winit/src/profiler.rs | 101 -- winit/src/settings.rs | 246 ++-- winit/src/window.rs | 0 56 files changed, 1512 insertions(+), 1823 deletions(-) rename {winit/src => core/src/window}/settings/macos.rs (100%) rename {winit/src => core/src/window}/settings/other.rs (100%) rename {winit/src => core/src/window}/settings/wasm.rs (100%) rename {winit/src => core/src/window}/settings/windows.rs (100%) delete mode 100644 examples/integration_opengl/src/main.rs delete mode 100644 examples/multi_window_panes/Cargo.toml delete mode 100644 examples/multi_window_panes/src/main.rs delete mode 100644 glutin/src/application.rs delete mode 100644 native/src/subscription.rs delete mode 100644 native/src/window.rs create mode 100644 runtime/src/multi_window.rs create mode 100644 runtime/src/multi_window/program.rs create mode 100644 runtime/src/multi_window/state.rs rename {winit/src => src/window}/icon.rs (100%) create mode 100644 winit/src/multi_window/windows.rs delete mode 100644 winit/src/profiler.rs delete mode 100644 winit/src/window.rs diff --git a/.github/ISSUE_TEMPLATE/BUG-REPORT.yml b/.github/ISSUE_TEMPLATE/BUG-REPORT.yml index d4c94fcd20..09b3169791 100644 --- a/.github/ISSUE_TEMPLATE/BUG-REPORT.yml +++ b/.github/ISSUE_TEMPLATE/BUG-REPORT.yml @@ -25,7 +25,6 @@ body: Before filing an issue... - If you are using `wgpu`, you need an environment that supports Vulkan, Metal, or DirectX 12. Please, make sure you can run [the `wgpu` examples]. - - If you are using `glow`, you need support for OpenGL 2.1+. Please, make sure you can run [the `glow` examples]. If you have any issues running any of the examples, make sure your graphics drivers are up-to-date. If the issues persist, please report them to the authors of the libraries directly! diff --git a/Cargo.toml b/Cargo.toml index 4a82c92380..a7f02055ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,7 @@ system = ["iced_winit/system"] web-colors = ["iced_renderer/web-colors"] # Enables the advanced module advanced = [] -# Enables experimental multi-window support for iced_winit + wgpu. +# Enables experimental multi-window support. multi-window = ["iced_winit/multi-window"] [badges] diff --git a/ECOSYSTEM.md b/ECOSYSTEM.md index 86581e4a18..da3066d8be 100644 --- a/ECOSYSTEM.md +++ b/ECOSYSTEM.md @@ -45,7 +45,7 @@ The widgets of a _graphical_ user interface produce some primitives that eventua Currently, there are two different official renderers: - [`iced_wgpu`] is powered by [`wgpu`] and supports Vulkan, DirectX 12, and Metal. -- [`iced_glow`] is powered by [`glow`] and supports OpenGL 2.1+ and OpenGL ES 2.0+. +- [`tiny-skia`] is used as a fallback software renderer when `wgpu` is not supported. Additionally, the [`iced_graphics`] subcrate contains a bunch of backend-agnostic types that can be leveraged to build renderers. Both of the renderers rely on the graphical foundations provided by this crate. @@ -54,10 +54,7 @@ The widgets of a graphical user _interface_ are interactive. __Shells__ gather a Normally, a shell will be responsible of creating a window and managing the lifecycle of a user interface, implementing a runtime of [The Elm Architecture]. -As of now, there are two official shells: - -- [`iced_winit`] implements a shell runtime on top of [`winit`]. -- [`iced_glutin`] is similar to [`iced_winit`], but it also deals with [OpenGL context creation]. +As of now, there is one official shell: [`iced_winit`] implements a shell runtime on top of [`winit`]. ## The web target The Web platform provides all the abstractions necessary to draw widgets and gather users interactions. @@ -91,5 +88,4 @@ Finally, [`iced`] unifies everything into a simple abstraction to create cross-p [`winit`]: https://github.com/rust-windowing/winit [`glutin`]: https://github.com/rust-windowing/glutin [`dodrio`]: https://github.com/fitzgen/dodrio -[OpenGL context creation]: https://www.khronos.org/opengl/wiki/Creating_an_OpenGL_Context [The Elm Architecture]: https://guide.elm-lang.org/architecture/ diff --git a/core/Cargo.toml b/core/Cargo.toml index 55f2e85f16..edf9e7c819 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -20,5 +20,8 @@ optional = true [target.'cfg(target_arch = "wasm32")'.dependencies] instant = "0.1" +[target.'cfg(windows)'.dependencies.raw-window-handle] +version = "0.5.2" + [dev-dependencies] approx = "0.5" diff --git a/core/src/window.rs b/core/src/window.rs index a6dbdfb446..10db31b6f4 100644 --- a/core/src/window.rs +++ b/core/src/window.rs @@ -2,14 +2,20 @@ pub mod icon; mod event; +mod id; mod level; mod mode; +mod position; mod redraw_request; +mod settings; mod user_attention; pub use event::Event; pub use icon::Icon; +pub use id::Id; pub use level::Level; pub use mode::Mode; +pub use position::Position; pub use redraw_request::RedrawRequest; +pub use settings::Settings; pub use user_attention::UserAttention; diff --git a/core/src/window/event.rs b/core/src/window/event.rs index e2fb5e665b..3efce05ef8 100644 --- a/core/src/window/event.rs +++ b/core/src/window/event.rs @@ -1,4 +1,5 @@ use crate::time::Instant; +use crate::Size; use std::path::PathBuf; @@ -32,6 +33,22 @@ pub enum Event { /// occurs. CloseRequested, + /// A window was destroyed by the runtime. + Destroyed, + + /// A window was created. + /// + /// **Note:** this event is not supported on Wayland. + Created { + /// The position of the created window. This is relative to the top-left corner of the desktop + /// the window is on, including virtual desktops. Refers to window's "inner" position, + /// or the client area, in logical pixels. + position: (i32, i32), + /// The size of the created window. This is its "inner" size, or the size of the + /// client area, in logical pixels. + size: Size, + }, + /// A window was focused. Focused, diff --git a/core/src/window/id.rs b/core/src/window/id.rs index 0a11b1aaa1..65002d437b 100644 --- a/core/src/window/id.rs +++ b/core/src/window/id.rs @@ -1,18 +1,17 @@ use std::collections::hash_map::DefaultHasher; -use std::fmt::{Display, Formatter}; use std::hash::{Hash, Hasher}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -/// The ID of the window. +/// The id of the window. /// -/// Internally Iced uses `window::Id::MAIN` as the first window spawned. +/// Internally Iced reserves `window::Id::MAIN` for the first window spawned. pub struct Id(u64); impl Id { - /// The reserved window ID for the primary window in an Iced application. + /// The reserved window [`Id`] for the first window in an Iced application. pub const MAIN: Self = Id(0); - /// Creates a new unique window ID. + /// Creates a new unique window [`Id`]. pub fn new(id: impl Hash) -> Id { let mut hasher = DefaultHasher::new(); id.hash(&mut hasher); @@ -20,9 +19,3 @@ impl Id { Id(hasher.finish()) } } - -impl Display for Id { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "Id({})", self.0) - } -} diff --git a/core/src/window/position.rs b/core/src/window/position.rs index e69de29bb2..c260c29eb1 100644 --- a/core/src/window/position.rs +++ b/core/src/window/position.rs @@ -0,0 +1,22 @@ +/// The position of a window in a given screen. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Position { + /// The platform-specific default position for a new window. + Default, + /// The window is completely centered on the screen. + Centered, + /// The window is positioned with specific coordinates: `(X, Y)`. + /// + /// When the decorations of the window are enabled, Windows 10 will add some + /// invisible padding to the window. This padding gets included in the + /// position. So if you have decorations enabled and want the window to be + /// at (0, 0) you would have to set the position to + /// `(PADDING_X, PADDING_Y)`. + Specific(i32, i32), +} + +impl Default for Position { + fn default() -> Self { + Self::Default + } +} diff --git a/core/src/window/settings.rs b/core/src/window/settings.rs index 458b9232c1..20811e8393 100644 --- a/core/src/window/settings.rs +++ b/core/src/window/settings.rs @@ -1,6 +1,26 @@ use crate::window::{Icon, Level, Position}; -pub use iced_winit::settings::PlatformSpecific; +#[cfg(target_os = "windows")] +#[path = "settings/windows.rs"] +mod platform; + +#[cfg(target_os = "macos")] +#[path = "settings/macos.rs"] +mod platform; + +#[cfg(target_arch = "wasm32")] +#[path = "settings/wasm.rs"] +mod platform; + +#[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_arch = "wasm32" +)))] +#[path = "settings/other.rs"] +mod platform; + +pub use platform::PlatformSpecific; /// The window settings of an application. #[derive(Debug, Clone)] @@ -56,21 +76,3 @@ impl Default for Settings { } } } - -impl From for iced_winit::settings::Window { - fn from(settings: Settings) -> Self { - Self { - size: settings.size, - position: iced_winit::Position::from(settings.position), - min_size: settings.min_size, - max_size: settings.max_size, - visible: settings.visible, - resizable: settings.resizable, - decorations: settings.decorations, - transparent: settings.transparent, - level: settings.level, - icon: settings.icon.map(Icon::into), - platform_specific: settings.platform_specific, - } - } -} diff --git a/winit/src/settings/macos.rs b/core/src/window/settings/macos.rs similarity index 100% rename from winit/src/settings/macos.rs rename to core/src/window/settings/macos.rs diff --git a/winit/src/settings/other.rs b/core/src/window/settings/other.rs similarity index 100% rename from winit/src/settings/other.rs rename to core/src/window/settings/other.rs diff --git a/winit/src/settings/wasm.rs b/core/src/window/settings/wasm.rs similarity index 100% rename from winit/src/settings/wasm.rs rename to core/src/window/settings/wasm.rs diff --git a/winit/src/settings/windows.rs b/core/src/window/settings/windows.rs similarity index 100% rename from winit/src/settings/windows.rs rename to core/src/window/settings/windows.rs diff --git a/examples/events/src/main.rs b/examples/events/src/main.rs index 70659f52c2..c3ac6fd11a 100644 --- a/examples/events/src/main.rs +++ b/examples/events/src/main.rs @@ -26,7 +26,7 @@ struct Events { enum Message { EventOccurred(Event), Toggled(bool), - Exit(window::Id), + Exit, } impl Application for Events { @@ -55,7 +55,8 @@ impl Application for Events { Command::none() } Message::EventOccurred(event) => { - if let Event::Window(id, window::Event::CloseRequested) = event { + if let Event::Window(id, window::Event::CloseRequested) = event + { window::close(id) } else { Command::none() @@ -66,7 +67,7 @@ impl Application for Events { Command::none() } - Message::Exit(id) => window::close(id), + Message::Exit => window::close(window::Id::MAIN), } } diff --git a/examples/exit/src/main.rs b/examples/exit/src/main.rs index 6152f62706..ec618dc140 100644 --- a/examples/exit/src/main.rs +++ b/examples/exit/src/main.rs @@ -34,7 +34,7 @@ impl Application for Exit { fn update(&mut self, message: Message) -> Command { match message { - Message::Confirm => window::close(), + Message::Confirm => window::close(window::Id::MAIN), Message::Exit => { self.show_confirm = true; diff --git a/examples/integration/src/main.rs b/examples/integration/src/main.rs index a560959abf..90beb097b5 100644 --- a/examples/integration/src/main.rs +++ b/examples/integration/src/main.rs @@ -6,8 +6,8 @@ use scene::Scene; use iced_wgpu::graphics::Viewport; use iced_wgpu::{wgpu, Backend, Renderer, Settings}; -use iced_winit::core::mouse; use iced_winit::core::renderer; +use iced_winit::core::{mouse, window}; use iced_winit::core::{Color, Size}; use iced_winit::runtime::program; use iced_winit::runtime::Debug; diff --git a/examples/integration_opengl/src/main.rs b/examples/integration_opengl/src/main.rs deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/examples/loading_spinners/src/circular.rs b/examples/loading_spinners/src/circular.rs index 3a35e029e1..ff599231da 100644 --- a/examples/loading_spinners/src/circular.rs +++ b/examples/loading_spinners/src/circular.rs @@ -277,7 +277,7 @@ where let state = tree.state.downcast_mut::(); - if let Event::Window(window::Event::RedrawRequested(now)) = event { + if let Event::Window(_, window::Event::RedrawRequested(now)) = event { state.animation = state.animation.timed_transition( self.cycle_duration, self.rotation_duration, diff --git a/examples/loading_spinners/src/linear.rs b/examples/loading_spinners/src/linear.rs index 3d95729bf2..8e07c12b44 100644 --- a/examples/loading_spinners/src/linear.rs +++ b/examples/loading_spinners/src/linear.rs @@ -198,7 +198,7 @@ where let state = tree.state.downcast_mut::(); - if let Event::Window(window::Event::RedrawRequested(now)) = event { + if let Event::Window(_, window::Event::RedrawRequested(now)) = event { *state = state.timed_transition(self.cycle_duration, now); shell.request_redraw(RedrawRequest::At( diff --git a/examples/multi_window/Cargo.toml b/examples/multi_window/Cargo.toml index 0cb5d5469d..2e222dfbb1 100644 --- a/examples/multi_window/Cargo.toml +++ b/examples/multi_window/Cargo.toml @@ -6,4 +6,4 @@ edition = "2021" publish = false [dependencies] -iced = { path = "../..", features = ["debug", "multi-window"] } \ No newline at end of file +iced = { path = "../..", features = ["debug", "multi-window"] } diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 5699ece03d..58604702a2 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -1,25 +1,32 @@ use iced::multi_window::{self, Application}; use iced::widget::{button, column, container, scrollable, text, text_input}; +use iced::window::{Id, Position}; use iced::{ - executor, window, Alignment, Command, Element, Length, Settings, Theme, + executor, subscription, window, Alignment, Command, Element, Length, + Settings, Subscription, Theme, }; use std::collections::HashMap; fn main() -> iced::Result { - Example::run(Settings::default()) + Example::run(Settings { + exit_on_close_request: false, + ..Default::default() + }) } #[derive(Default)] struct Example { - windows_count: usize, windows: HashMap, + next_window_pos: window::Position, } +#[derive(Debug)] struct Window { - id: window::Id, title: String, scale_input: String, current_scale: f64, + theme: Theme, + input_id: iced::widget::text_input::Id, } #[derive(Debug, Clone)] @@ -28,6 +35,8 @@ enum Message { ScaleChanged(window::Id, String), TitleChanged(window::Id, String), CloseWindow(window::Id), + WindowDestroyed(window::Id), + WindowCreated(window::Id, (i32, i32)), NewWindow, } @@ -40,11 +49,8 @@ impl multi_window::Application for Example { fn new(_flags: ()) -> (Self, Command) { ( Example { - windows_count: 0, - windows: HashMap::from([( - window::Id::MAIN, - Window::new(window::Id::MAIN), - )]), + windows: HashMap::from([(window::Id::MAIN, Window::new(1))]), + next_window_pos: Position::Default, }, Command::none(), ) @@ -82,12 +88,32 @@ impl multi_window::Application for Example { Message::CloseWindow(id) => { return window::close(id); } + Message::WindowDestroyed(id) => { + self.windows.remove(&id); + } + Message::WindowCreated(id, position) => { + self.next_window_pos = window::Position::Specific( + position.0 + 20, + position.1 + 20, + ); + + if let Some(window) = self.windows.get(&id) { + return text_input::focus(window.input_id.clone()); + } + } Message::NewWindow => { - self.windows_count += 1; - let id = window::Id::new(self.windows_count); - self.windows.insert(id, Window::new(id)); - - return window::spawn(id, window::Settings::default()); + let count = self.windows.len() + 1; + let id = window::Id::new(count); + + self.windows.insert(id, Window::new(count)); + + return window::spawn( + id, + window::Settings { + position: self.next_window_pos, + ..Default::default() + }, + ); } } @@ -95,13 +121,9 @@ impl multi_window::Application for Example { } fn view(&self, window: window::Id) -> Element { - let window = self - .windows - .get(&window) - .map(|window| window.view()) - .unwrap(); + let content = self.windows.get(&window).unwrap().view(window); - container(window) + container(content) .width(Length::Fill) .height(Length::Fill) .center_x() @@ -109,6 +131,10 @@ impl multi_window::Application for Example { .into() } + fn theme(&self, window: Id) -> Self::Theme { + self.windows.get(&window).unwrap().theme.clone() + } + fn scale_factor(&self, window: window::Id) -> f64 { self.windows .get(&window) @@ -116,55 +142,71 @@ impl multi_window::Application for Example { .unwrap_or(1.0) } - fn close_requested(&self, window: window::Id) -> Self::Message { - Message::CloseWindow(window) + fn subscription(&self) -> Subscription { + subscription::events_with(|event, _| { + if let iced::Event::Window(id, window_event) = event { + match window_event { + window::Event::CloseRequested => { + Some(Message::CloseWindow(id)) + } + window::Event::Destroyed => { + Some(Message::WindowDestroyed(id)) + } + window::Event::Created { position, .. } => { + Some(Message::WindowCreated(id, position)) + } + _ => None, + } + } else { + None + } + }) } } impl Window { - fn new(id: window::Id) -> Self { + fn new(count: usize) -> Self { Self { - id, - title: "Window".to_string(), + title: format!("Window_{}", count), scale_input: "1.0".to_string(), current_scale: 1.0, + theme: if count % 2 == 0 { + Theme::Light + } else { + Theme::Dark + }, + input_id: text_input::Id::unique(), } } - fn view(&self) -> Element { - window_view(self.id, &self.scale_input, &self.title) + fn view(&self, id: window::Id) -> Element { + let scale_input = column![ + text("Window scale factor:"), + text_input("Window Scale", &self.scale_input) + .on_input(move |msg| { Message::ScaleInputChanged(id, msg) }) + .on_submit(Message::ScaleChanged( + id, + self.scale_input.to_string() + )) + ]; + + let title_input = column![ + text("Window title:"), + text_input("Window Title", &self.title) + .on_input(move |msg| { Message::TitleChanged(id, msg) }) + .id(self.input_id.clone()) + ]; + + let new_window_button = + button(text("New Window")).on_press(Message::NewWindow); + + let content = scrollable( + column![scale_input, title_input, new_window_button] + .spacing(50) + .width(Length::Fill) + .align_items(Alignment::Center), + ); + + container(content).width(200).center_x().into() } } - -fn window_view<'a>( - id: window::Id, - scale_input: &'a str, - title: &'a str, -) -> Element<'a, Message> { - let scale_input = column![ - text("Window scale factor:"), - text_input("Window Scale", scale_input, move |msg| { - Message::ScaleInputChanged(id, msg) - }) - .on_submit(Message::ScaleChanged(id, scale_input.to_string())) - ]; - - let title_input = column![ - text("Window title:"), - text_input("Window Title", title, move |msg| { - Message::TitleChanged(id, msg) - }) - ]; - - let new_window_button = - button(text("New Window")).on_press(Message::NewWindow); - - let content = scrollable( - column![scale_input, title_input, new_window_button] - .spacing(50) - .width(Length::Fill) - .align_items(Alignment::Center), - ); - - container(content).width(200).center_x().into() -} diff --git a/examples/multi_window_panes/Cargo.toml b/examples/multi_window_panes/Cargo.toml deleted file mode 100644 index 1b3f3ec65d..0000000000 --- a/examples/multi_window_panes/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "multi_window_panes" -version = "0.1.0" -authors = ["Richard Custodio "] -edition = "2021" -publish = false - -[dependencies] -iced = { path = "../..", features = ["debug", "multi-window", "tokio"] } -env_logger = "0.10.0" -iced_native = { path = "../../native" } -iced_lazy = { path = "../../lazy" } diff --git a/examples/multi_window_panes/src/main.rs b/examples/multi_window_panes/src/main.rs deleted file mode 100644 index b1d0a3bcb1..0000000000 --- a/examples/multi_window_panes/src/main.rs +++ /dev/null @@ -1,639 +0,0 @@ -use iced::alignment::{self, Alignment}; -use iced::keyboard; -use iced::multi_window::Application; -use iced::theme::{self, Theme}; -use iced::widget::pane_grid::{self, PaneGrid}; -use iced::widget::{ - button, column, container, pick_list, row, scrollable, text, text_input, -}; -use iced::window; -use iced::{executor, time}; -use iced::{Color, Command, Element, Length, Settings, Size, Subscription}; -use iced_lazy::responsive; -use iced_native::{event, subscription, Event}; - -use iced_native::widget::scrollable::{Properties, RelativeOffset}; -use iced_native::window::Id; -use std::collections::HashMap; -use std::time::{Duration, Instant}; - -pub fn main() -> iced::Result { - env_logger::init(); - - Example::run(Settings::default()) -} - -struct Example { - windows: HashMap, - panes_created: usize, - count: usize, - _focused: window::Id, -} - -#[derive(Debug)] -struct Window { - title: String, - scale: f64, - theme: Theme, - panes: pane_grid::State, - focus: Option, -} - -#[derive(Debug, Clone)] -enum Message { - Window(window::Id, WindowMessage), - CountIncremented(Instant), -} - -#[derive(Debug, Clone)] -enum WindowMessage { - Split(pane_grid::Axis, pane_grid::Pane), - SplitFocused(pane_grid::Axis), - FocusAdjacent(pane_grid::Direction), - Clicked(pane_grid::Pane), - Dragged(pane_grid::DragEvent), - PopOut(pane_grid::Pane), - Resized(pane_grid::ResizeEvent), - TitleChanged(String), - ToggleMoving(pane_grid::Pane), - TogglePin(pane_grid::Pane), - Close(pane_grid::Pane), - CloseFocused, - SelectedWindow(pane_grid::Pane, SelectableWindow), - CloseWindow, - SnapToggle, -} - -impl Application for Example { - type Executor = executor::Default; - type Message = Message; - type Theme = Theme; - type Flags = (); - - fn new(_flags: ()) -> (Self, Command) { - let (panes, _) = - pane_grid::State::new(Pane::new(0, pane_grid::Axis::Horizontal)); - let window = Window { - panes, - focus: None, - title: String::from("Default window"), - scale: 1.0, - theme: Theme::default(), - }; - - ( - Example { - windows: HashMap::from([(window::Id::MAIN, window)]), - panes_created: 1, - count: 0, - _focused: window::Id::MAIN, - }, - Command::none(), - ) - } - - fn title(&self, window: window::Id) -> String { - self.windows - .get(&window) - .map(|w| w.title.clone()) - .unwrap_or(String::from("New Window")) - } - - fn update(&mut self, message: Message) -> Command { - match message { - Message::Window(id, message) => match message { - WindowMessage::SnapToggle => { - let window = self.windows.get_mut(&id).unwrap(); - - if let Some(focused) = &window.focus { - let pane = window.panes.get_mut(focused).unwrap(); - - let cmd = scrollable::snap_to( - pane.scrollable_id.clone(), - if pane.snapped { - RelativeOffset::START - } else { - RelativeOffset::END - }, - ); - - pane.snapped = !pane.snapped; - return cmd; - } - } - WindowMessage::Split(axis, pane) => { - let window = self.windows.get_mut(&id).unwrap(); - let result = window.panes.split( - axis, - &pane, - Pane::new(self.panes_created, axis), - ); - - if let Some((pane, _)) = result { - window.focus = Some(pane); - } - - self.panes_created += 1; - } - WindowMessage::SplitFocused(axis) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.focus { - let result = window.panes.split( - axis, - &pane, - Pane::new(self.panes_created, axis), - ); - - if let Some((pane, _)) = result { - window.focus = Some(pane); - } - - self.panes_created += 1; - } - } - WindowMessage::FocusAdjacent(direction) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.focus { - if let Some(adjacent) = - window.panes.adjacent(&pane, direction) - { - window.focus = Some(adjacent); - } - } - } - WindowMessage::Clicked(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - window.focus = Some(pane); - } - WindowMessage::CloseWindow => { - let _ = self.windows.remove(&id); - return window::close(id); - } - WindowMessage::Resized(pane_grid::ResizeEvent { - split, - ratio, - }) => { - let window = self.windows.get_mut(&id).unwrap(); - window.panes.resize(&split, ratio); - } - WindowMessage::SelectedWindow(pane, selected) => { - let window = self.windows.get_mut(&id).unwrap(); - let (mut pane, _) = window.panes.close(&pane).unwrap(); - pane.is_moving = false; - - if let Some(window) = self.windows.get_mut(&selected.0) { - let (&first_pane, _) = - window.panes.iter().next().unwrap(); - let result = - window.panes.split(pane.axis, &first_pane, pane); - - if let Some((pane, _)) = result { - window.focus = Some(pane); - } - } - } - WindowMessage::ToggleMoving(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.panes.get_mut(&pane) { - pane.is_moving = !pane.is_moving; - } - } - WindowMessage::TitleChanged(title) => { - let window = self.windows.get_mut(&id).unwrap(); - window.title = title; - } - WindowMessage::PopOut(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some((popped, sibling)) = window.panes.close(&pane) { - window.focus = Some(sibling); - - let (panes, _) = pane_grid::State::new(popped); - let window = Window { - panes, - focus: None, - title: format!( - "New window ({})", - self.windows.len() - ), - scale: 1.0 + (self.windows.len() as f64 / 10.0), - theme: if self.windows.len() % 2 == 0 { - Theme::Light - } else { - Theme::Dark - }, - }; - - let window_id = window::Id::new(self.windows.len()); - self.windows.insert(window_id, window); - return window::spawn(window_id, Default::default()); - } - } - WindowMessage::Dragged(pane_grid::DragEvent::Dropped { - pane, - target, - }) => { - let window = self.windows.get_mut(&id).unwrap(); - window.panes.swap(&pane, &target); - } - WindowMessage::Dragged(_) => {} - WindowMessage::TogglePin(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(Pane { is_pinned, .. }) = - window.panes.get_mut(&pane) - { - *is_pinned = !*is_pinned; - } - } - WindowMessage::Close(pane) => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some((_, sibling)) = window.panes.close(&pane) { - window.focus = Some(sibling); - } - } - WindowMessage::CloseFocused => { - let window = self.windows.get_mut(&id).unwrap(); - if let Some(pane) = window.focus { - if let Some(Pane { is_pinned, .. }) = - window.panes.get(&pane) - { - if !is_pinned { - if let Some((_, sibling)) = - window.panes.close(&pane) - { - window.focus = Some(sibling); - } - } - } - } - } - }, - Message::CountIncremented(_) => { - self.count += 1; - } - } - - Command::none() - } - - fn subscription(&self) -> Subscription { - Subscription::batch(vec![ - subscription::events_with(|event, status| { - if let event::Status::Captured = status { - return None; - } - - match event { - Event::Keyboard(keyboard::Event::KeyPressed { - modifiers, - key_code, - }) if modifiers.command() => { - handle_hotkey(key_code).map(|message| { - Message::Window(window::Id::new(0usize), message) - }) - } // TODO(derezzedex) - _ => None, - } - }), - time::every(Duration::from_secs(1)).map(Message::CountIncremented), - ]) - } - - fn view(&self, window: window::Id) -> Element { - let window_id = window; - - if let Some(window) = self.windows.get(&window) { - let focus = window.focus; - let total_panes = window.panes.len(); - - let window_controls = row![ - text_input( - "Window title", - &window.title, - WindowMessage::TitleChanged, - ), - button(text("Close")) - .on_press(WindowMessage::CloseWindow) - .style(theme::Button::Destructive), - ] - .spacing(5) - .align_items(Alignment::Center); - - let pane_grid = PaneGrid::new(&window.panes, |id, pane, _| { - let is_focused = focus == Some(id); - - let pin_button = button( - text(if pane.is_pinned { "Unpin" } else { "Pin" }).size(14), - ) - .on_press(WindowMessage::TogglePin(id)) - .padding(3); - - let title = row![ - pin_button, - "Pane", - text(pane.id.to_string()).style(if is_focused { - PANE_ID_COLOR_FOCUSED - } else { - PANE_ID_COLOR_UNFOCUSED - }), - ] - .spacing(5); - - let title_bar = pane_grid::TitleBar::new(title) - .controls(view_controls( - id, - total_panes, - pane.is_pinned, - pane.is_moving, - &window.title, - window_id, - &self.windows, - )) - .padding(10) - .style(if is_focused { - style::title_bar_focused - } else { - style::title_bar_active - }); - - pane_grid::Content::new(responsive(move |size| { - view_content( - id, - pane.scrollable_id.clone(), - self.count, - total_panes, - pane.is_pinned, - size, - ) - })) - .title_bar(title_bar) - .style(if is_focused { - style::pane_focused - } else { - style::pane_active - }) - }) - .width(Length::Fill) - .height(Length::Fill) - .spacing(10) - .on_click(WindowMessage::Clicked) - .on_drag(WindowMessage::Dragged) - .on_resize(10, WindowMessage::Resized); - - let content: Element<_> = column![window_controls, pane_grid] - .width(Length::Fill) - .height(Length::Fill) - .padding(10) - .into(); - - return content - .map(move |message| Message::Window(window_id, message)); - } - - container(text("This shouldn't be possible!").size(20)) - .center_x() - .center_y() - .into() - } - - fn close_requested(&self, window: window::Id) -> Self::Message { - Message::Window(window, WindowMessage::CloseWindow) - } - - fn scale_factor(&self, window: Id) -> f64 { - self.windows.get(&window).map(|w| w.scale).unwrap_or(1.0) - } - - fn theme(&self, window: Id) -> Theme { - self.windows.get(&window).expect("Window not found!").theme.clone() - } -} - -const PANE_ID_COLOR_UNFOCUSED: Color = Color::from_rgb( - 0xFF as f32 / 255.0, - 0xC7 as f32 / 255.0, - 0xC7 as f32 / 255.0, -); -const PANE_ID_COLOR_FOCUSED: Color = Color::from_rgb( - 0xFF as f32 / 255.0, - 0x47 as f32 / 255.0, - 0x47 as f32 / 255.0, -); - -fn handle_hotkey(key_code: keyboard::KeyCode) -> Option { - use keyboard::KeyCode; - use pane_grid::{Axis, Direction}; - - let direction = match key_code { - KeyCode::Up => Some(Direction::Up), - KeyCode::Down => Some(Direction::Down), - KeyCode::Left => Some(Direction::Left), - KeyCode::Right => Some(Direction::Right), - _ => None, - }; - - match key_code { - KeyCode::V => Some(WindowMessage::SplitFocused(Axis::Vertical)), - KeyCode::H => Some(WindowMessage::SplitFocused(Axis::Horizontal)), - KeyCode::W => Some(WindowMessage::CloseFocused), - _ => direction.map(WindowMessage::FocusAdjacent), - } -} - -#[derive(Debug, Clone)] -struct SelectableWindow(window::Id, String); - -impl PartialEq for SelectableWindow { - fn eq(&self, other: &Self) -> bool { - self.0 == other.0 - } -} - -impl Eq for SelectableWindow {} - -impl std::fmt::Display for SelectableWindow { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.1.fmt(f) - } -} - -#[derive(Debug)] -struct Pane { - id: usize, - pub scrollable_id: scrollable::Id, - pub axis: pane_grid::Axis, - pub is_pinned: bool, - pub is_moving: bool, - pub snapped: bool, -} - -impl Pane { - fn new(id: usize, axis: pane_grid::Axis) -> Self { - Self { - id, - scrollable_id: scrollable::Id::unique(), - axis, - is_pinned: false, - is_moving: false, - snapped: false, - } - } -} - -fn view_content<'a>( - pane: pane_grid::Pane, - scrollable_id: scrollable::Id, - count: usize, - total_panes: usize, - is_pinned: bool, - size: Size, -) -> Element<'a, WindowMessage> { - let button = |label, message| { - button( - text(label) - .width(Length::Fill) - .horizontal_alignment(alignment::Horizontal::Center) - .size(16), - ) - .width(Length::Fill) - .padding(8) - .on_press(message) - }; - - let mut controls = column![ - button( - "Split horizontally", - WindowMessage::Split(pane_grid::Axis::Horizontal, pane), - ), - button( - "Split vertically", - WindowMessage::Split(pane_grid::Axis::Vertical, pane), - ), - button("Snap", WindowMessage::SnapToggle,) - ] - .spacing(5) - .max_width(150); - - if total_panes > 1 && !is_pinned { - controls = controls.push( - button("Close", WindowMessage::Close(pane)) - .style(theme::Button::Destructive), - ); - } - - let content = column![ - text(format!("{}x{}", size.width, size.height)).size(24), - controls, - text(format!("{count}")).size(48), - ] - .width(Length::Fill) - .height(800) - .spacing(10) - .align_items(Alignment::Center); - - container( - scrollable(content) - .height(Length::Fill) - .vertical_scroll(Properties::new()) - .id(scrollable_id), - ) - .width(Length::Fill) - .height(Length::Fill) - .padding(5) - .center_y() - .into() -} - -fn view_controls<'a>( - pane: pane_grid::Pane, - total_panes: usize, - is_pinned: bool, - is_moving: bool, - window_title: &'a str, - window_id: window::Id, - windows: &HashMap, -) -> Element<'a, WindowMessage> { - let window_selector = { - let options: Vec<_> = windows - .iter() - .map(|(id, window)| SelectableWindow(*id, window.title.clone())) - .collect(); - pick_list( - options, - Some(SelectableWindow(window_id, window_title.to_string())), - move |window| WindowMessage::SelectedWindow(pane, window), - ) - }; - - let mut move_to = button(text("Move to").size(14)).padding(3); - - let mut pop_out = button(text("Pop Out").size(14)).padding(3); - - let mut close = button(text("Close").size(14)) - .style(theme::Button::Destructive) - .padding(3); - - if total_panes > 1 && !is_pinned { - close = close.on_press(WindowMessage::Close(pane)); - pop_out = pop_out.on_press(WindowMessage::PopOut(pane)); - } - - if windows.len() > 1 && total_panes > 1 && !is_pinned { - move_to = move_to.on_press(WindowMessage::ToggleMoving(pane)); - } - - let mut content = row![].spacing(10); - if is_moving { - content = content.push(pop_out).push(window_selector).push(close); - } else { - content = content.push(pop_out).push(move_to).push(close); - } - - content.into() -} - -mod style { - use iced::widget::container; - use iced::Theme; - - pub fn title_bar_active(theme: &Theme) -> container::Appearance { - let palette = theme.extended_palette(); - - container::Appearance { - text_color: Some(palette.background.strong.text), - background: Some(palette.background.strong.color.into()), - ..Default::default() - } - } - - pub fn title_bar_focused(theme: &Theme) -> container::Appearance { - let palette = theme.extended_palette(); - - container::Appearance { - text_color: Some(palette.primary.strong.text), - background: Some(palette.primary.strong.color.into()), - ..Default::default() - } - } - - pub fn pane_active(theme: &Theme) -> container::Appearance { - let palette = theme.extended_palette(); - - container::Appearance { - background: Some(palette.background.weak.color.into()), - border_width: 2.0, - border_color: palette.background.strong.color, - ..Default::default() - } - } - - pub fn pane_focused(theme: &Theme) -> container::Appearance { - let palette = theme.extended_palette(); - - container::Appearance { - background: Some(palette.background.weak.color.into()), - border_width: 2.0, - border_color: palette.primary.strong.color, - ..Default::default() - } - } -} diff --git a/examples/screenshot/src/main.rs b/examples/screenshot/src/main.rs index 838245350e..7658384bec 100644 --- a/examples/screenshot/src/main.rs +++ b/examples/screenshot/src/main.rs @@ -1,8 +1,8 @@ -use iced::alignment; use iced::keyboard::KeyCode; use iced::theme::{Button, Container}; use iced::widget::{button, column, container, image, row, text, text_input}; use iced::window::screenshot::{self, Screenshot}; +use iced::{alignment, window}; use iced::{ event, executor, keyboard, subscription, Alignment, Application, Command, ContentFit, Element, Event, Length, Rectangle, Renderer, Subscription, @@ -71,7 +71,10 @@ impl Application for Example { fn update(&mut self, message: Self::Message) -> Command { match message { Message::Screenshot => { - return iced::window::screenshot(Message::ScreenshotData); + return iced::window::screenshot( + window::Id::MAIN, + Message::ScreenshotData, + ); } Message::ScreenshotData(screenshot) => { self.screenshot = Some(screenshot); diff --git a/examples/toast/src/main.rs b/examples/toast/src/main.rs index 4282ddcf61..e28c4236f6 100644 --- a/examples/toast/src/main.rs +++ b/examples/toast/src/main.rs @@ -528,7 +528,9 @@ mod toast { clipboard: &mut dyn Clipboard, shell: &mut Shell<'_, Message>, ) -> event::Status { - if let Event::Window(window::Event::RedrawRequested(now)) = &event { + if let Event::Window(_, window::Event::RedrawRequested(now)) = + &event + { let mut next_redraw: Option = None; self.instants.iter_mut().enumerate().for_each( diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index 6ad7b4fbd3..04c8f618f1 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -164,7 +164,7 @@ impl Application for Todos { } } Message::ToggleFullscreen(mode) => { - window::change_mode(mode) + window::change_mode(window::Id::MAIN, mode) } _ => Command::none(), }; diff --git a/futures/src/subscription.rs b/futures/src/subscription.rs index 0642a92473..c087fdabc3 100644 --- a/futures/src/subscription.rs +++ b/futures/src/subscription.rs @@ -251,7 +251,7 @@ where events.filter_map(move |(event, status)| { future::ready(match event { - Event::Window(window::Event::RedrawRequested(_)) => None, + Event::Window(_, window::Event::RedrawRequested(_)) => None, _ => f(event, status), }) }) diff --git a/glutin/src/application.rs b/glutin/src/application.rs deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/graphics/Cargo.toml b/graphics/Cargo.toml index 7a9e6aee9d..15d263466b 100644 --- a/graphics/Cargo.toml +++ b/graphics/Cargo.toml @@ -12,7 +12,6 @@ categories = ["gui"] [features] geometry = ["lyon_path"] -opengl = [] image = ["dep:image", "kamadak-exif"] web-colors = [] diff --git a/graphics/src/compositor.rs b/graphics/src/compositor.rs index f7b8604581..321110087d 100644 --- a/graphics/src/compositor.rs +++ b/graphics/src/compositor.rs @@ -24,6 +24,9 @@ pub trait Compositor: Sized { compatible_window: Option<&W>, ) -> Result<(Self, Self::Renderer), Error>; + /// Creates a [`Renderer`] for the [`Compositor`]. + fn renderer(&self) -> Self::Renderer; + /// Crates a new [`Surface`] for the given window. /// /// [`Surface`]: Self::Surface diff --git a/native/src/subscription.rs b/native/src/subscription.rs deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/native/src/window.rs b/native/src/window.rs deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/renderer/src/compositor.rs b/renderer/src/compositor.rs index 8b17a4b0c7..b5da31bfe5 100644 --- a/renderer/src/compositor.rs +++ b/renderer/src/compositor.rs @@ -46,6 +46,22 @@ impl crate::graphics::Compositor for Compositor { Err(error) } + fn renderer(&self) -> Self::Renderer { + match self { + Compositor::TinySkia(compositor) => { + Renderer::TinySkia(compositor.renderer()) + } + #[cfg(feature = "wgpu")] + Compositor::Wgpu(compositor) => { + Renderer::Wgpu(compositor.renderer()) + } + #[cfg(not(feature = "wgpu"))] + Self::Wgpu => { + panic!("`wgpu` feature was not enabled in `iced_renderer`") + } + } + } + fn create_surface( &mut self, window: &W, diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index a65f07f26a..3d2976a7ac 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -9,6 +9,7 @@ repository = "https://github.com/iced-rs/iced" [features] debug = [] +multi-window = [] [dependencies] thiserror = "1" diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 4bbf9687bc..4c39f80f07 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -53,6 +53,9 @@ pub mod system; pub mod user_interface; pub mod window; +#[cfg(feature = "multi-window")] +pub mod multi_window; + // We disable debug capabilities on release builds unless the `debug` feature // is explicitly enabled. #[cfg(feature = "debug")] diff --git a/runtime/src/multi_window.rs b/runtime/src/multi_window.rs new file mode 100644 index 0000000000..cf778a2075 --- /dev/null +++ b/runtime/src/multi_window.rs @@ -0,0 +1,6 @@ +//! A multi-window application. +pub mod program; +pub mod state; + +pub use program::Program; +pub use state::State; diff --git a/runtime/src/multi_window/program.rs b/runtime/src/multi_window/program.rs new file mode 100644 index 0000000000..c3989d0d01 --- /dev/null +++ b/runtime/src/multi_window/program.rs @@ -0,0 +1,32 @@ +//! Build interactive programs using The Elm Architecture. +use crate::{window, Command}; + +use crate::core::text; +use crate::core::{Element, Renderer}; + +/// The core of a user interface for a multi-window application following The Elm Architecture. +pub trait Program: Sized { + /// The graphics backend to use to draw the [`Program`]. + type Renderer: Renderer + text::Renderer; + + /// The type of __messages__ your [`Program`] will produce. + 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. + fn update(&mut self, message: Self::Message) -> Command; + + /// Returns the widgets to display in the [`Program`] for the `window`. + /// + /// These widgets can produce __messages__ based on user interaction. + fn view( + &self, + window: window::Id, + ) -> Element<'_, Self::Message, Self::Renderer>; +} diff --git a/runtime/src/multi_window/state.rs b/runtime/src/multi_window/state.rs new file mode 100644 index 0000000000..78c35e6cc4 --- /dev/null +++ b/runtime/src/multi_window/state.rs @@ -0,0 +1,280 @@ +//! The internal state of a multi-window [`Program`]. +use crate::core::event::{self, Event}; +use crate::core::mouse; +use crate::core::renderer; +use crate::core::widget::operation::{self, Operation}; +use crate::core::{Clipboard, Size}; +use crate::user_interface::{self, UserInterface}; +use crate::{Command, Debug, Program}; + +/// The execution state of a multi-window [`Program`]. It leverages caching, event +/// processing, and rendering primitive storage. +#[allow(missing_debug_implementations)] +pub struct State

+where + P: Program + 'static, +{ + program: P, + caches: Option>, + queued_events: Vec, + queued_messages: Vec, + mouse_interaction: mouse::Interaction, +} + +impl

State

+where + P: Program + 'static, +{ + /// Creates a new [`State`] with the provided [`Program`], initializing its + /// primitive with the given logical bounds and renderer. + pub fn new( + program: P, + bounds: Size, + renderer: &mut P::Renderer, + debug: &mut Debug, + ) -> Self { + let user_interface = build_user_interface( + &program, + user_interface::Cache::default(), + renderer, + bounds, + debug, + ); + + let caches = Some(vec![user_interface.into_cache()]); + + State { + program, + caches, + queued_events: Vec::new(), + queued_messages: Vec::new(), + mouse_interaction: mouse::Interaction::Idle, + } + } + + /// Returns a reference to the [`Program`] of the [`State`]. + pub fn program(&self) -> &P { + &self.program + } + + /// Queues an event in the [`State`] for processing during an [`update`]. + /// + /// [`update`]: Self::update + pub fn queue_event(&mut self, event: Event) { + self.queued_events.push(event); + } + + /// Queues a message in the [`State`] for processing during an [`update`]. + /// + /// [`update`]: Self::update + pub fn queue_message(&mut self, message: P::Message) { + self.queued_messages.push(message); + } + + /// Returns whether the event queue of the [`State`] is empty or not. + pub fn is_queue_empty(&self) -> bool { + self.queued_events.is_empty() && self.queued_messages.is_empty() + } + + /// Returns the current [`mouse::Interaction`] of the [`State`]. + pub fn mouse_interaction(&self) -> mouse::Interaction { + self.mouse_interaction + } + + /// Processes all the queued events and messages, rebuilding and redrawing + /// the widgets of the linked [`Program`] if necessary. + /// + /// Returns a list containing the instances of [`Event`] that were not + /// captured by any widget, and the [`Command`] obtained from [`Program`] + /// after updating it, only if an update was necessary. + pub fn update( + &mut self, + bounds: Size, + cursor: mouse::Cursor, + renderer: &mut P::Renderer, + theme: &::Theme, + style: &renderer::Style, + clipboard: &mut dyn Clipboard, + debug: &mut Debug, + ) -> (Vec, Option>) { + let mut user_interfaces = build_user_interfaces( + &self.program, + self.caches.take().unwrap(), + renderer, + bounds, + debug, + ); + + debug.event_processing_started(); + let mut messages = Vec::new(); + + let uncaptured_events = user_interfaces.iter_mut().fold( + vec![], + |mut uncaptured_events, ui| { + let (_, event_statuses) = ui.update( + &self.queued_events, + cursor, + renderer, + clipboard, + &mut messages, + ); + + uncaptured_events.extend( + self.queued_events + .iter() + .zip(event_statuses) + .filter_map(|(event, status)| { + matches!(status, event::Status::Ignored) + .then_some(event) + }) + .cloned(), + ); + uncaptured_events + }, + ); + + self.queued_events.clear(); + messages.append(&mut self.queued_messages); + debug.event_processing_finished(); + + let commands = if messages.is_empty() { + debug.draw_started(); + + for ui in &mut user_interfaces { + self.mouse_interaction = + ui.draw(renderer, theme, style, cursor); + } + + debug.draw_finished(); + + self.caches = Some( + user_interfaces + .drain(..) + .map(UserInterface::into_cache) + .collect(), + ); + + None + } else { + let temp_caches = user_interfaces + .drain(..) + .map(UserInterface::into_cache) + .collect(); + + drop(user_interfaces); + + let commands = Command::batch(messages.into_iter().map(|msg| { + debug.log_message(&msg); + + debug.update_started(); + let command = self.program.update(msg); + debug.update_finished(); + + command + })); + + let mut user_interfaces = build_user_interfaces( + &self.program, + temp_caches, + renderer, + bounds, + debug, + ); + + debug.draw_started(); + for ui in &mut user_interfaces { + self.mouse_interaction = + ui.draw(renderer, theme, style, cursor); + } + debug.draw_finished(); + + self.caches = Some( + user_interfaces + .drain(..) + .map(UserInterface::into_cache) + .collect(), + ); + + Some(commands) + }; + + (uncaptured_events, commands) + } + + /// Applies [`widget::Operation`]s to the [`State`] + pub fn operate( + &mut self, + renderer: &mut P::Renderer, + operations: impl Iterator>>, + bounds: Size, + debug: &mut Debug, + ) { + let mut user_interfaces = build_user_interfaces( + &self.program, + self.caches.take().unwrap(), + renderer, + bounds, + debug, + ); + + for operation in operations { + let mut current_operation = Some(operation); + + while let Some(mut operation) = current_operation.take() { + for ui in &mut user_interfaces { + ui.operate(renderer, operation.as_mut()); + } + + match operation.finish() { + operation::Outcome::None => {} + operation::Outcome::Some(message) => { + self.queued_messages.push(message) + } + operation::Outcome::Chain(next) => { + current_operation = Some(next); + } + }; + } + } + + self.caches = Some( + user_interfaces + .drain(..) + .map(UserInterface::into_cache) + .collect(), + ); + } +} + +fn build_user_interfaces<'a, P: Program>( + program: &'a P, + mut caches: Vec, + renderer: &mut P::Renderer, + size: Size, + debug: &mut Debug, +) -> Vec> { + caches + .drain(..) + .map(|cache| { + build_user_interface(program, cache, renderer, size, debug) + }) + .collect() +} + +fn build_user_interface<'a, P: Program>( + program: &'a P, + cache: user_interface::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 +} diff --git a/runtime/src/window.rs b/runtime/src/window.rs index 5219fbfdec..4737dcdde4 100644 --- a/runtime/src/window.rs +++ b/runtime/src/window.rs @@ -3,101 +3,117 @@ mod action; pub mod screenshot; +pub use crate::core::window::Id; pub use action::Action; pub use screenshot::Screenshot; use crate::command::{self, Command}; use crate::core::time::Instant; -use crate::core::window::{Event, Icon, Level, Mode, UserAttention}; +use crate::core::window::{self, Event, Icon, Level, Mode, UserAttention}; use crate::core::Size; use crate::futures::subscription::{self, Subscription}; /// Subscribes to the frames of the window of the running application. /// /// The resulting [`Subscription`] will produce items at a rate equal to the -/// refresh rate of the window. Note that this rate may be variable, as it is +/// refresh rate of the first application window. Note that this rate may be variable, as it is /// normally managed by the graphics driver and/or the OS. /// /// In any case, this [`Subscription`] is useful to smoothly draw application-driven /// animations without missing any frames. pub fn frames() -> Subscription { subscription::raw_events(|event, _status| match event { - iced_core::Event::Window(Event::RedrawRequested(at)) => Some(at), + iced_core::Event::Window(_, Event::RedrawRequested(at)) => Some(at), _ => None, }) } -/// Closes the current window and exits the application. -pub fn close() -> Command { - Command::single(command::Action::Window(Action::Close)) +/// Spawns a new window with the given `id` and `settings`. +pub fn spawn( + id: window::Id, + settings: window::Settings, +) -> Command { + Command::single(command::Action::Window(id, Action::Spawn { settings })) +} + +/// Closes the window with `id`. +pub fn close(id: window::Id) -> Command { + Command::single(command::Action::Window(id, Action::Close)) } /// Begins dragging the window while the left mouse button is held. -pub fn drag() -> Command { - Command::single(command::Action::Window(Action::Drag)) +pub fn drag(id: window::Id) -> Command { + Command::single(command::Action::Window(id, Action::Drag)) } /// Resizes the window to the given logical dimensions. -pub fn resize(new_size: Size) -> Command { - Command::single(command::Action::Window(Action::Resize(new_size))) +pub fn resize( + id: window::Id, + new_size: Size, +) -> Command { + Command::single(command::Action::Window(id, Action::Resize(new_size))) } -/// Fetches the current window size in logical dimensions. +/// Fetches the window's size in logical dimensions. pub fn fetch_size( + id: window::Id, f: impl FnOnce(Size) -> Message + 'static, ) -> Command { - Command::single(command::Action::Window(Action::FetchSize(Box::new(f)))) + Command::single(command::Action::Window(id, Action::FetchSize(Box::new(f)))) } /// Maximizes the window. -pub fn maximize(maximized: bool) -> Command { - Command::single(command::Action::Window(Action::Maximize(maximized))) +pub fn maximize(id: window::Id, maximized: bool) -> Command { + Command::single(command::Action::Window(id, Action::Maximize(maximized))) } -/// Minimes the window. -pub fn minimize(minimized: bool) -> Command { - Command::single(command::Action::Window(Action::Minimize(minimized))) +/// Minimizes the window. +pub fn minimize(id: window::Id, minimized: bool) -> Command { + Command::single(command::Action::Window(id, Action::Minimize(minimized))) } -/// Moves a window to the given logical coordinates. -pub fn move_to(x: i32, y: i32) -> Command { - Command::single(command::Action::Window(Action::Move { x, y })) +/// Moves the window to the given logical coordinates. +pub fn move_to(id: window::Id, x: i32, y: i32) -> Command { + Command::single(command::Action::Window(id, Action::Move { x, y })) } /// Changes the [`Mode`] of the window. -pub fn change_mode(mode: Mode) -> Command { - Command::single(command::Action::Window(Action::ChangeMode(mode))) +pub fn change_mode(id: window::Id, mode: Mode) -> Command { + Command::single(command::Action::Window(id, Action::ChangeMode(mode))) } /// Fetches the current [`Mode`] of the window. pub fn fetch_mode( + id: window::Id, f: impl FnOnce(Mode) -> Message + 'static, ) -> Command { - Command::single(command::Action::Window(Action::FetchMode(Box::new(f)))) + Command::single(command::Action::Window(id, Action::FetchMode(Box::new(f)))) } /// Toggles the window to maximized or back. -pub fn toggle_maximize() -> Command { - Command::single(command::Action::Window(Action::ToggleMaximize)) +pub fn toggle_maximize(id: window::Id) -> Command { + Command::single(command::Action::Window(id, Action::ToggleMaximize)) } /// Toggles the window decorations. -pub fn toggle_decorations() -> Command { - Command::single(command::Action::Window(Action::ToggleDecorations)) +pub fn toggle_decorations(id: window::Id) -> Command { + Command::single(command::Action::Window(id, Action::ToggleDecorations)) } -/// 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 /// 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. pub fn request_user_attention( + id: window::Id, user_attention: Option, ) -> Command { - Command::single(command::Action::Window(Action::RequestUserAttention( - user_attention, - ))) + Command::single(command::Action::Window( + id, + Action::RequestUserAttention(user_attention), + )) } /// Brings the window to the front and sets input focus. Has no effect if the window is @@ -106,30 +122,36 @@ pub fn request_user_attention( /// This [`Command`] 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. -pub fn gain_focus() -> Command { - Command::single(command::Action::Window(Action::GainFocus)) +pub fn gain_focus(id: window::Id) -> Command { + Command::single(command::Action::Window(id, Action::GainFocus)) } /// Changes the window [`Level`]. -pub fn change_level(level: Level) -> Command { - Command::single(command::Action::Window(Action::ChangeLevel(level))) +pub fn change_level(id: window::Id, level: Level) -> Command { + Command::single(command::Action::Window(id, Action::ChangeLevel(level))) } -/// Fetches an identifier unique to the window. +/// Fetches an identifier unique to the window, provided by the underlying windowing system. This is +/// not to be confused with [`window::Id`]. pub fn fetch_id( + id: window::Id, f: impl FnOnce(u64) -> Message + 'static, ) -> Command { - Command::single(command::Action::Window(Action::FetchId(Box::new(f)))) + Command::single(command::Action::Window(id, Action::FetchId(Box::new(f)))) } /// Changes the [`Icon`] of the window. -pub fn change_icon(icon: Icon) -> Command { - Command::single(command::Action::Window(Action::ChangeIcon(icon))) +pub fn change_icon(id: window::Id, icon: Icon) -> Command { + Command::single(command::Action::Window(id, Action::ChangeIcon(icon))) } /// Captures a [`Screenshot`] from the window. pub fn screenshot( + id: window::Id, f: impl FnOnce(Screenshot) -> Message + Send + 'static, ) -> Command { - Command::single(command::Action::Window(Action::Screenshot(Box::new(f)))) + Command::single(command::Action::Window( + id, + Action::Screenshot(Box::new(f)), + )) } diff --git a/runtime/src/window/action.rs b/runtime/src/window/action.rs index cebec4ae8a..d631cee108 100644 --- a/runtime/src/window/action.rs +++ b/runtime/src/window/action.rs @@ -1,4 +1,4 @@ -use crate::core::window::{Icon, Level, Mode, UserAttention, Settings}; +use crate::core::window::{Icon, Level, Mode, Settings, UserAttention}; use crate::core::Size; use crate::futures::MaybeSend; use crate::window::Screenshot; @@ -15,7 +15,7 @@ pub enum Action { /// There’s no guarantee that this will work unless the left mouse /// button was pressed immediately before this function is called. Drag, - /// Spawns a new window with the provided [`window::Settings`]. + /// Spawns a new window. Spawn { /// The settings of the [`Window`]. settings: Settings, diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index 9974128cdf..0486159e6f 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -1,30 +1,37 @@ use crate::window; use crate::{Command, Element, Executor, Settings, Subscription}; -pub use iced_native::application::{Appearance, StyleSheet}; +pub use crate::style::application::{Appearance, StyleSheet}; /// An interactive cross-platform multi-window application. /// /// This trait is the main entrypoint of Iced. Once implemented, you can run /// your GUI application by simply calling [`run`](#method.run). /// +/// - On native platforms, it will run in its own windows. +/// - On the web, it will take control of the `` and the `<body>` of the +/// document and display only the contents of the `window::Id::MAIN` window. +/// /// An [`Application`] can execute asynchronous actions by returning a -/// [`Command`] in some of its methods. For example, to spawn a new window, you -/// can use the `iced_winit::window::spawn()` [`Command`]. +/// [`Command`] in some of its methods. If you do not intend to perform any +/// background work in your program, the [`Sandbox`] trait offers a simplified +/// interface. /// /// When using an [`Application`] with the `debug` feature enabled, a debug view /// can be toggled by pressing `F12`. /// +/// # Examples +/// See the `examples/multi-window` example to see this multi-window `Application` trait in action. +/// /// ## A simple "Hello, world!" /// /// If you just want to get started, here is a simple [`Application`] that /// says "Hello, world!": /// /// ```no_run -/// use iced::executor; -/// use iced::multi_window::Application; -/// use iced::window; +/// use iced::{executor, window}; /// use iced::{Command, Element, Settings, Theme}; +/// use iced::multi_window::{self, Application}; /// /// pub fn main() -> iced::Result { /// Hello::run(Settings::default()) @@ -32,17 +39,17 @@ pub use iced_native::application::{Appearance, StyleSheet}; /// /// struct Hello; /// -/// impl Application for Hello { +/// impl multi_window::Application for Hello { /// type Executor = executor::Default; +/// type Flags = (); /// type Message = (); /// type Theme = Theme; -/// type Flags = (); /// /// fn new(_flags: ()) -> (Hello, Command<Self::Message>) { /// (Hello, Command::none()) /// } /// -/// fn title(&self, window: window::Id) -> String { +/// fn title(&self, _window: window::Id) -> String { /// String::from("A cool application") /// } /// @@ -50,13 +57,9 @@ pub use iced_native::application::{Appearance, StyleSheet}; /// Command::none() /// } /// -/// fn view(&self, window: window::Id) -> Element<Self::Message> { +/// fn view(&self, _window: window::Id) -> Element<Self::Message> { /// "Hello, world!".into() /// } -/// -/// fn close_requested(&self, window: window::Id) -> Self::Message { -/// () -/// } /// } /// ``` pub trait Application: Sized { @@ -89,10 +92,10 @@ pub trait Application: Sized { /// [`run`]: Self::run fn new(flags: Self::Flags) -> (Self, Command<Self::Message>); - /// Returns the current title of the [`Application`]. + /// Returns the current title of the `window` of the [`Application`]. /// /// This title can be dynamic! The runtime will automatically update the - /// title of your application when necessary. + /// title of your window when necessary. fn title(&self, window: window::Id) -> String; /// Handles a __message__ and updates the state of the [`Application`]. @@ -104,7 +107,15 @@ pub trait Application: Sized { /// Any [`Command`] returned will be executed immediately in the background. fn update(&mut self, message: Self::Message) -> Command<Self::Message>; - /// Returns the current [`Theme`] of the [`Application`]. + /// Returns the widgets to display in the `window` of the [`Application`]. + /// + /// These widgets can produce __messages__ based on user interaction. + fn view( + &self, + window: window::Id, + ) -> Element<'_, Self::Message, crate::Renderer<Self::Theme>>; + + /// Returns the current [`Theme`] of the `window` of the [`Application`]. /// /// [`Theme`]: Self::Theme #[allow(unused_variables)] @@ -112,9 +123,8 @@ pub trait Application: Sized { Self::Theme::default() } - /// Returns the current [`Style`] of the [`Theme`]. + /// Returns the current `Style` of the [`Theme`]. /// - /// [`Style`]: <Self::Theme as StyleSheet>::Style /// [`Theme`]: Self::Theme fn style(&self) -> <Self::Theme as StyleSheet>::Style { <Self::Theme as StyleSheet>::Style::default() @@ -132,14 +142,6 @@ pub trait Application: Sized { Subscription::none() } - /// Returns the widgets to display in the [`Application`]. - /// - /// These widgets can produce __messages__ based on user interaction. - fn view( - &self, - window: window::Id, - ) -> Element<'_, Self::Message, crate::Renderer<Self::Theme>>; - /// Returns the scale factor of the `window` of the [`Application`]. /// /// It can be used to dynamically control the size of the UI at runtime @@ -154,18 +156,7 @@ pub trait Application: Sized { 1.0 } - /// Returns whether the [`Application`] should be terminated. - /// - /// By default, it returns `false`. - fn should_exit(&self) -> bool { - false - } - - /// Returns the `Self::Message` that should be processed when a `window` is requested to - /// be closed. - fn close_requested(&self, window: window::Id) -> Self::Message; - - /// Runs the [`Application`]. + /// Runs the multi-window [`Application`]. /// /// On native platforms, this method will take control of the current thread /// until the [`Application`] exits. @@ -182,30 +173,28 @@ pub trait Application: Sized { let renderer_settings = crate::renderer::Settings { default_font: settings.default_font, default_text_size: settings.default_text_size, - text_multithreading: settings.text_multithreading, antialiasing: if settings.antialiasing { - Some(crate::renderer::settings::Antialiasing::MSAAx4) + Some(crate::graphics::Antialiasing::MSAAx4) } else { None }, - ..crate::renderer::Settings::from_env() + ..crate::renderer::Settings::default() }; - Ok(crate::runtime::multi_window::run::< + Ok(crate::shell::multi_window::run::< Instance<Self>, Self::Executor, - crate::renderer::window::Compositor<Self::Theme>, + crate::renderer::Compositor<Self::Theme>, >(settings.into(), renderer_settings)?) } } struct Instance<A: Application>(A); -impl<A> crate::runtime::multi_window::Application for Instance<A> +impl<A> crate::runtime::multi_window::Program for Instance<A> where A: Application, { - type Flags = A::Flags; type Renderer = crate::Renderer<A::Theme>; type Message = A::Message; @@ -219,6 +208,13 @@ where ) -> Element<'_, Self::Message, Self::Renderer> { self.0.view(window) } +} + +impl<A> crate::shell::multi_window::Application for Instance<A> +where + A: Application, +{ + type Flags = A::Flags; fn new(flags: Self::Flags) -> (Self, Command<A::Message>) { let (app, command) = A::new(flags); @@ -245,12 +241,4 @@ where fn scale_factor(&self, window: window::Id) -> f64 { self.0.scale_factor(window) } - - fn should_exit(&self) -> bool { - self.0.should_exit() - } - - fn close_requested(&self, window: window::Id) -> Self::Message { - self.0.close_requested(window) - } } diff --git a/src/settings.rs b/src/settings.rs index 0dd465849a..4ce2d135ef 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -91,7 +91,7 @@ impl<Flags> From<Settings<Flags>> for iced_winit::Settings<Flags> { fn from(settings: Settings<Flags>) -> iced_winit::Settings<Flags> { iced_winit::Settings { id: settings.id, - window: settings.window.into(), + window: settings.window, flags: settings.flags, exit_on_close_request: settings.exit_on_close_request, } diff --git a/src/window.rs b/src/window.rs index e46015750c..9f96da5245 100644 --- a/src/window.rs +++ b/src/window.rs @@ -1,12 +1,8 @@ //! Configure the window of your application in native platforms. -mod position; -mod settings; pub mod icon; pub use icon::Icon; -pub use position::Position; -pub use settings::{PlatformSpecific, Settings}; pub use crate::core::window::*; pub use crate::runtime::window::*; diff --git a/winit/src/icon.rs b/src/window/icon.rs similarity index 100% rename from winit/src/icon.rs rename to src/window/icon.rs diff --git a/tiny_skia/src/window/compositor.rs b/tiny_skia/src/window/compositor.rs index 775cf9e5b8..1aaba2c938 100644 --- a/tiny_skia/src/window/compositor.rs +++ b/tiny_skia/src/window/compositor.rs @@ -8,6 +8,7 @@ use raw_window_handle::{HasRawDisplayHandle, HasRawWindowHandle}; use std::marker::PhantomData; pub struct Compositor<Theme> { + settings: Settings, _theme: PhantomData<Theme>, } @@ -33,6 +34,10 @@ impl<Theme> crate::graphics::Compositor for Compositor<Theme> { Ok((compositor, Renderer::new(backend))) } + fn renderer(&self) -> Self::Renderer { + Renderer::new(Backend::new(self.settings)) + } + fn create_surface<W: HasRawWindowHandle + HasRawDisplayHandle>( &mut self, window: &W, @@ -116,6 +121,7 @@ impl<Theme> crate::graphics::Compositor for Compositor<Theme> { pub fn new<Theme>(settings: Settings) -> (Compositor<Theme>, Backend) { ( Compositor { + settings, _theme: PhantomData, }, Backend::new(settings), diff --git a/wgpu/src/window/compositor.rs b/wgpu/src/window/compositor.rs index cd5b20cc3b..814269f3ad 100644 --- a/wgpu/src/window/compositor.rs +++ b/wgpu/src/window/compositor.rs @@ -219,6 +219,10 @@ impl<Theme> graphics::Compositor for Compositor<Theme> { Ok((compositor, Renderer::new(backend))) } + fn renderer(&self) -> Self::Renderer { + Renderer::new(self.create_backend()) + } + fn create_surface<W: HasRawWindowHandle + HasRawDisplayHandle>( &mut self, window: &W, diff --git a/winit/Cargo.toml b/winit/Cargo.toml index a4c0a402fe..30cec0b8c6 100644 --- a/winit/Cargo.toml +++ b/winit/Cargo.toml @@ -12,8 +12,6 @@ categories = ["gui"] [features] default = ["x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"] -trace = ["tracing", "tracing-core", "tracing-subscriber"] -chrome-trace = ["trace", "tracing-chrome"] debug = ["iced_runtime/debug"] system = ["sysinfo"] application = [] @@ -21,7 +19,7 @@ x11 = ["winit/x11"] wayland = ["winit/wayland"] wayland-dlopen = ["winit/wayland-dlopen"] wayland-csd-adwaita = ["winit/wayland-csd-adwaita"] -multi-window = [] +multi-window = ["iced_runtime/multi-window"] [dependencies] window_clipboard = "0.3" @@ -47,24 +45,6 @@ path = "../graphics" version = "0.8" path = "../style" -[dependencies.tracing] -version = "0.1.37" -optional = true -features = ["std"] - -[dependencies.tracing-core] -version = "0.1.30" -optional = true - -[dependencies.tracing-subscriber] -version = "0.3.16" -optional = true -features = ["registry"] - -[dependencies.tracing-chrome] -version = "0.7.0" -optional = true - [target.'cfg(target_os = "windows")'.dependencies.winapi] version = "0.3.6" diff --git a/winit/src/application.rs b/winit/src/application.rs index ab7b249571..5c45bbdacb 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -18,6 +18,7 @@ use crate::runtime::clipboard; use crate::runtime::program::Program; use crate::runtime::user_interface::{self, UserInterface}; use crate::runtime::{Command, Debug}; +use crate::settings; use crate::style::application::{Appearance, StyleSheet}; use crate::{Clipboard, Error, Proxy, Settings}; @@ -25,11 +26,6 @@ use futures::channel::mpsc; use std::mem::ManuallyDrop; -#[cfg(feature = "trace")] -pub use crate::Profiler; -#[cfg(feature = "trace")] -use tracing::{info_span, instrument::Instrument}; - /// An interactive, native cross-platform application. /// /// This trait is the main entrypoint of Iced. Once implemented, you can run @@ -117,15 +113,9 @@ where use futures::Future; use winit::event_loop::EventLoopBuilder; - #[cfg(feature = "trace")] - let _guard = Profiler::init(); - let mut debug = Debug::new(); debug.startup_started(); - #[cfg(feature = "trace")] - let _ = info_span!("Application", "RUN").entered(); - let event_loop = EventLoopBuilder::with_user_event().build(); let proxy = event_loop.create_proxy(); @@ -146,14 +136,13 @@ where let target = settings.window.platform_specific.target.clone(); let should_be_visible = settings.window.visible; - let builder = settings - .window - .into_builder( - &application.title(), - event_loop.primary_monitor(), - settings.id, - ) - .with_visible(false); + let builder = settings::window_builder( + settings.window, + &application.title(), + event_loop.primary_monitor(), + settings.id, + ) + .with_visible(false); log::debug!("Window builder: {:#?}", builder); @@ -196,28 +185,20 @@ where let (mut event_sender, event_receiver) = mpsc::unbounded(); let (control_sender, mut control_receiver) = mpsc::unbounded(); - let mut instance = Box::pin({ - let run_instance = run_instance::<A, E, C>( - application, - compositor, - renderer, - runtime, - proxy, - debug, - event_receiver, - control_sender, - init_command, - window, - should_be_visible, - settings.exit_on_close_request, - ); - - #[cfg(feature = "trace")] - let run_instance = - run_instance.instrument(info_span!("Application", "LOOP")); - - run_instance - }); + let mut instance = Box::pin(run_instance::<A, E, C>( + application, + compositor, + renderer, + runtime, + proxy, + debug, + event_receiver, + control_sender, + init_command, + window, + should_be_visible, + settings.exit_on_close_request, + )); let mut context = task::Context::from_waker(task::noop_waker_ref()); @@ -480,9 +461,6 @@ async fn run_instance<A, E, C>( messages.push(message); } event::Event::RedrawRequested(_) => { - #[cfg(feature = "trace")] - let _ = info_span!("Application", "FRAME").entered(); - let physical_size = state.physical_size(); if physical_size.width == 0 || physical_size.height == 0 { @@ -622,24 +600,12 @@ pub fn build_user_interface<'a, A: Application>( where <A::Renderer as core::Renderer>::Theme: StyleSheet, { - #[cfg(feature = "trace")] - let view_span = info_span!("Application", "VIEW").entered(); - debug.view_started(); let view = application.view(); - - #[cfg(feature = "trace")] - let _ = view_span.exit(); debug.view_finished(); - #[cfg(feature = "trace")] - let layout_span = info_span!("Application", "LAYOUT").entered(); - debug.layout_started(); let user_interface = UserInterface::build(view, size, cache, renderer); - - #[cfg(feature = "trace")] - let _ = layout_span.exit(); debug.layout_finished(); user_interface @@ -666,16 +632,10 @@ pub fn update<A: Application, C, E: Executor>( <A::Renderer as core::Renderer>::Theme: StyleSheet, { for message in messages.drain(..) { - #[cfg(feature = "trace")] - let update_span = info_span!("Application", "UPDATE").entered(); - debug.log_message(&message); debug.update_started(); let command = runtime.enter(|| application.update(message)); - - #[cfg(feature = "trace")] - let _ = update_span.exit(); debug.update_finished(); run_command( @@ -750,7 +710,7 @@ pub fn run_command<A, C, E>( } window::Action::Spawn { .. } => { log::info!( - "Spawning a window is only available with `multi_window::Application`s." + "Spawning a window is only available with multi-window applications." ) } window::Action::Resize(size) => { diff --git a/winit/src/conversion.rs b/winit/src/conversion.rs index fe0fce197c..0625e74bf5 100644 --- a/winit/src/conversion.rs +++ b/winit/src/conversion.rs @@ -7,7 +7,6 @@ use crate::core::mouse; use crate::core::touch; use crate::core::window; use crate::core::{Event, Point}; -use crate::Position; /// Converts a winit window event into an iced event. pub fn window_event( @@ -169,17 +168,17 @@ pub fn window_level(level: window::Level) -> winit::window::WindowLevel { pub fn position( monitor: Option<&winit::monitor::MonitorHandle>, (width, height): (u32, u32), - position: Position, + position: window::Position, ) -> Option<winit::dpi::Position> { match position { - Position::Default => None, - Position::Specific(x, y) => { + window::Position::Default => None, + window::Position::Specific(x, y) => { Some(winit::dpi::Position::Logical(winit::dpi::LogicalPosition { x: f64::from(x), y: f64::from(y), })) } - Position::Centered => { + window::Position::Centered => { if let Some(monitor) = monitor { let start = monitor.position(); diff --git a/winit/src/lib.rs b/winit/src/lib.rs index dc163430a1..31002f5183 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -51,20 +51,14 @@ pub mod settings; pub mod system; mod error; -mod icon; mod proxy; -#[cfg(feature = "trace")] -mod profiler; #[cfg(feature = "application")] pub use application::Application; -#[cfg(feature = "trace")] -pub use profiler::Profiler; pub use clipboard::Clipboard; pub use error::Error; -pub use icon::Icon; pub use proxy::Proxy; pub use settings::Settings; +pub use crate::core::window::*; pub use iced_graphics::Viewport; -pub use iced_native::window::Position; diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 9b395c1d74..e6f440bce0 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -1,58 +1,57 @@ //! Create interactive, native cross-platform applications for WGPU. mod state; +mod windows; pub use state::State; -use crate::clipboard::{self, Clipboard}; -use crate::conversion; -use crate::mouse; -use crate::renderer; -use crate::settings; -use crate::widget::operation; -use crate::window; -use crate::{ - Command, Debug, Element, Error, Executor, Proxy, Renderer, Runtime, - Settings, Size, Subscription, -}; - -use iced_futures::futures::channel::mpsc; -use iced_futures::futures::{self, FutureExt}; -use iced_graphics::compositor; -use iced_native::user_interface::{self, UserInterface}; - -pub use iced_native::application::{Appearance, StyleSheet}; - -use std::collections::HashMap; +use crate::core::widget::operation; +use crate::core::{self, mouse, renderer, window, Size}; +use crate::futures::futures::channel::mpsc; +use crate::futures::futures::{task, Future, FutureExt, StreamExt}; +use crate::futures::{Executor, Runtime, Subscription}; +use crate::graphics::{compositor, Compositor}; +use crate::multi_window::windows::Windows; +use crate::runtime::command::{self, Command}; +use crate::runtime::multi_window::Program; +use crate::runtime::user_interface::{self, UserInterface}; +use crate::runtime::Debug; +use crate::settings::window_builder; +use crate::style::application::StyleSheet; +use crate::{conversion, settings, Clipboard, Error, Proxy, Settings}; + +use iced_runtime::user_interface::Cache; use std::mem::ManuallyDrop; use std::time::Instant; - -#[cfg(feature = "trace")] -pub use crate::Profiler; -#[cfg(feature = "trace")] -use tracing::{info_span, instrument::Instrument}; +use winit::monitor::MonitorHandle; /// This is a wrapper around the `Application::Message` associate type /// to allows the `shell` to create internal messages, while still having /// the current user-specified custom messages. #[derive(Debug)] pub enum Event<Message> { - /// An [`Application`] generated message + /// An internal event which contains an [`Application`] generated message. Application(Message), - /// A message which spawns a new window. + /// An internal event which spawns a new window. NewWindow { /// The [window::Id] of the newly spawned [`Window`]. id: window::Id, /// The [settings::Window] of the newly spawned [`Window`]. - settings: settings::Window, + settings: window::Settings, /// The title of the newly spawned [`Window`]. title: String, + /// The monitor on which to spawn the window. If `None`, will use monitor of the last window + /// spawned. + monitor: Option<MonitorHandle>, }, - /// Close a window. + /// An internal event for closing a window. CloseWindow(window::Id), - /// A message for when the window has finished being created. + /// An internal event for when the window has finished being created. WindowCreated(window::Id, winit::window::Window), } +#[allow(unsafe_code)] +unsafe impl<Message> std::marker::Send for Event<Message> {} + /// An interactive, native, cross-platform, multi-windowed application. /// /// This trait is the main entrypoint of multi-window Iced. Once implemented, you can run @@ -64,37 +63,13 @@ pub enum Event<Message> { /// /// When using an [`Application`] with the `debug` feature enabled, a debug view /// can be toggled by pressing `F12`. -pub trait Application: Sized +pub trait Application: Program where - <Self::Renderer as crate::Renderer>::Theme: StyleSheet, + <Self::Renderer as core::Renderer>::Theme: StyleSheet, { /// The data needed to initialize your [`Application`]. type Flags; - /// The graphics backend to use to draw the [`Program`]. - type Renderer: Renderer; - - /// The type of __messages__ your [`Program`] will produce. - 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. - fn update(&mut self, message: Self::Message) -> Command<Self::Message>; - - /// Returns the widgets to display for the `window` in the [`Program`]. - /// - /// These widgets can produce __messages__ based on user interaction. - fn view( - &self, - window: window::Id, - ) -> Element<'_, Self::Message, Self::Renderer>; - /// Initializes the [`Application`] with the flags provided to /// [`run`] as part of the [`Settings`]. /// @@ -105,19 +80,22 @@ where /// 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 each window of the [`Application`]. + /// Returns the current title of the [`Application`]. /// /// This title can be dynamic! The runtime will automatically update the /// title of your application when necessary. fn title(&self, window: window::Id) -> String; - /// Returns the current [`Theme`] of the [`Application`]. - fn theme(&self, window: window::Id) -> <Self::Renderer as crate::Renderer>::Theme; + /// Returns the current `Theme` of the [`Application`]. + fn theme( + &self, + window: window::Id, + ) -> <Self::Renderer as core::Renderer>::Theme; - /// Returns the [`Style`] variation of the [`Theme`]. + /// Returns the `Style` variation of the `Theme`. fn style( &self, - ) -> <<Self::Renderer as crate::Renderer>::Theme as StyleSheet>::Style { + ) -> <<Self::Renderer as core::Renderer>::Theme as StyleSheet>::Style { Default::default() } @@ -147,17 +125,6 @@ where fn scale_factor(&self, window: window::Id) -> f64 { 1.0 } - - /// Returns whether the [`Application`] should be terminated. - /// - /// By default, it returns `false`. - fn should_exit(&self) -> bool { - false - } - - /// Returns the `Self::Message` that should be processed when a `window` is requested to - /// be closed. - fn close_requested(&self, window: window::Id) -> Self::Message; } /// Runs an [`Application`] with an executor, compositor, and the provided @@ -169,22 +136,14 @@ pub fn run<A, E, C>( where A: Application + 'static, E: Executor + 'static, - C: iced_graphics::window::Compositor<Renderer = A::Renderer> + 'static, - <A::Renderer as crate::Renderer>::Theme: StyleSheet, + C: Compositor<Renderer = A::Renderer> + 'static, + <A::Renderer as core::Renderer>::Theme: StyleSheet, { - use futures::task; - use futures::Future; use winit::event_loop::EventLoopBuilder; - #[cfg(feature = "trace")] - let _guard = Profiler::init(); - let mut debug = Debug::new(); debug.startup_started(); - #[cfg(feature = "trace")] - let _ = info_span!("Application", "RUN").entered(); - let event_loop = EventLoopBuilder::with_user_event().build(); let proxy = event_loop.create_proxy(); @@ -201,68 +160,77 @@ where runtime.enter(|| A::new(flags)) }; - let builder = settings.window.into_builder( + let should_main_be_visible = settings.window.visible; + let builder = window_builder( + settings.window, &application.title(window::Id::MAIN), event_loop.primary_monitor(), settings.id, - ); + ) + .with_visible(false); log::info!("Window builder: {:#?}", builder); - let window = builder + let main_window = builder .build(&event_loop) .map_err(Error::WindowCreationFailed)?; - let windows: HashMap<window::Id, winit::window::Window> = - HashMap::from([(window::Id::MAIN, window)]); - - let window = windows.values().next().expect("No window found"); - #[cfg(target_arch = "wasm32")] { use winit::platform::web::WindowExtWebSys; - let canvas = window.canvas(); + let canvas = main_window.canvas(); let window = web_sys::window().unwrap(); let document = window.document().unwrap(); let body = document.body().unwrap(); - let _ = body - .append_child(&canvas) - .expect("Append canvas to HTML body"); + let target = target.and_then(|target| { + body.query_selector(&format!("#{}", target)) + .ok() + .unwrap_or(None) + }); + + match target { + Some(node) => { + let _ = node + .replace_with_with_node_1(&canvas) + .expect(&format!("Could not replace #{}", node.id())); + } + None => { + let _ = body + .append_child(&canvas) + .expect("Append canvas to HTML body"); + } + }; } - let (compositor, renderer) = C::new(compositor_settings, Some(&window))?; + let (mut compositor, renderer) = + C::new(compositor_settings, Some(&main_window))?; + + let windows = + Windows::new(&application, &mut compositor, renderer, main_window); let (mut event_sender, event_receiver) = mpsc::unbounded(); let (control_sender, mut control_receiver) = mpsc::unbounded(); - let mut instance = Box::pin({ - let run_instance = run_instance::<A, E, C>( - application, - compositor, - renderer, - runtime, - proxy, - debug, - event_receiver, - control_sender, - init_command, - windows, - settings.exit_on_close_request, - ); - - #[cfg(feature = "trace")] - let run_instance = - run_instance.instrument(info_span!("Application", "LOOP")); - - run_instance - }); + let mut instance = Box::pin(run_instance::<A, E, C>( + application, + compositor, + runtime, + proxy, + debug, + event_receiver, + control_sender, + init_command, + windows, + should_main_be_visible, + settings.exit_on_close_request, + )); let mut context = task::Context::from_waker(task::noop_waker_ref()); - platform::run(event_loop, move |event, event_loop, control_flow| { + platform::run(event_loop, move |event, window_target, control_flow| { use winit::event_loop::ControlFlow; if let ControlFlow::ExitWithCode(_) = control_flow { @@ -285,11 +253,12 @@ where id, settings, title, + monitor, }) => { - let window = settings - .into_builder(&title, event_loop.primary_monitor(), None) - .build(event_loop) - .expect("Failed to build window"); + let window = + settings::window_builder(settings, &title, monitor, None) + .build(window_target) + .expect("Failed to build window"); Some(winit::event::Event::UserEvent(Event::WindowCreated( id, window, @@ -320,7 +289,6 @@ where async fn run_instance<A, E, C>( mut application: A, mut compositor: C, - mut renderer: A::Renderer, mut runtime: Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>, mut proxy: winit::event_loop::EventLoopProxy<Event<A::Message>>, mut debug: Debug, @@ -329,74 +297,65 @@ async fn run_instance<A, E, C>( >, mut control_sender: mpsc::UnboundedSender<winit::event_loop::ControlFlow>, init_command: Command<A::Message>, - mut windows: HashMap<window::Id, winit::window::Window>, - _exit_on_close_request: bool, + mut windows: Windows<A, C>, + should_main_window_be_visible: bool, + exit_on_main_closed: bool, ) where A: Application + 'static, E: Executor + 'static, - C: iced_graphics::window::Compositor<Renderer = A::Renderer> + 'static, - <A::Renderer as crate::Renderer>::Theme: StyleSheet, + C: Compositor<Renderer = A::Renderer> + 'static, + <A::Renderer as core::Renderer>::Theme: StyleSheet, { - use iced_futures::futures::stream::StreamExt; use winit::event; use winit::event_loop::ControlFlow; - let mut clipboard = - Clipboard::connect(windows.values().next().expect("No window found")); - let mut caches = HashMap::new(); - let mut window_ids: HashMap<_, _> = windows - .iter() - .map(|(&id, window)| (window.id(), id)) - .collect(); - - let mut states = HashMap::new(); - let mut surfaces = HashMap::new(); - let mut interfaces = ManuallyDrop::new(HashMap::new()); - - for (&id, window) in windows.keys().zip(windows.values()) { - let mut surface = compositor.create_surface(window); - let state = State::new(&application, id, window); - let physical_size = state.physical_size(); - - compositor.configure_surface( - &mut surface, - physical_size.width, - physical_size.height, - ); + let mut clipboard = Clipboard::connect(windows.main()); - let user_interface = build_user_interface( - &application, - user_interface::Cache::default(), - &mut renderer, - state.logical_size(), - &mut debug, - id, - ); + let mut ui_caches = vec![user_interface::Cache::default()]; + let mut user_interfaces = ManuallyDrop::new(build_user_interfaces( + &application, + &mut debug, + &mut windows, + vec![user_interface::Cache::default()], + )); - let _ = states.insert(id, state); - let _ = surfaces.insert(id, surface); - let _ = interfaces.insert(id, user_interface); - let _ = caches.insert(id, user_interface::Cache::default()); + if should_main_window_be_visible { + windows.main().set_visible(true); } run_command( &application, - &mut caches, - &states, - &mut renderer, + &mut compositor, init_command, &mut runtime, &mut clipboard, &mut proxy, &mut debug, - &windows, - || compositor.fetch_information(), + &mut windows, + &mut ui_caches, ); - runtime.track(application.subscription().map(Event::Application)); + runtime.track( + application + .subscription() + .map(Event::Application) + .into_recipes(), + ); let mut mouse_interaction = mouse::Interaction::default(); - let mut events = Vec::new(); + + let mut events = + if let Some((position, size)) = logical_bounds_of(windows.main()) { + vec![( + Some(window::Id::MAIN), + core::Event::Window( + window::Id::MAIN, + window::Event::Created { position, size }, + ), + )] + } else { + Vec::new() + }; let mut messages = Vec::new(); let mut redraw_pending = false; @@ -413,25 +372,20 @@ async fn run_instance<A, E, C>( ); } event::Event::MainEventsCleared => { - for id in states.keys().copied().collect::<Vec<_>>() { - // Partition events into only events for this window - let (filtered, remaining): (Vec<_>, Vec<_>) = - events.iter().cloned().partition( - |(window_id, _event): &( - Option<window::Id>, - iced_native::event::Event, - )| { - *window_id == Some(id) || *window_id == None - }, - ); - - // Only retain events which have not been processed for next iteration - events.retain(|el| remaining.contains(el)); - - let window_events: Vec<_> = filtered - .into_iter() - .map(|(_id, event)| event) - .collect(); + debug.event_processing_started(); + let mut uis_stale = false; + + for (i, id) in windows.ids.iter().enumerate() { + let mut window_events = vec![]; + + events.retain(|(window_id, event)| { + if *window_id == Some(*id) || window_id.is_none() { + window_events.push(event.clone()); + false + } else { + true + } + }); if !redraw_pending && window_events.is_empty() @@ -440,144 +394,124 @@ async fn run_instance<A, E, C>( continue; } - // Process winit events for window - debug.event_processing_started(); - let cursor_position = - states.get(&id).unwrap().cursor_position(); - - let (interface_state, statuses) = { - let user_interface = interfaces.get_mut(&id).unwrap(); - user_interface.update( - &window_events, - cursor_position, - &mut renderer, - &mut clipboard, - &mut messages, - ) - }; + let (ui_state, statuses) = user_interfaces[i].update( + &window_events, + windows.states[i].cursor(), + &mut windows.renderers[i], + &mut clipboard, + &mut messages, + ); + + if !uis_stale { + uis_stale = + matches!(ui_state, user_interface::State::Outdated); + } - for event in + for (event, status) in window_events.into_iter().zip(statuses.into_iter()) { - runtime.broadcast(event); + runtime.broadcast(event, status); } - debug.event_processing_finished(); - - // Update application with app messages - // Unless we implement some kind of diffing, we must redraw all windows as we - // cannot know what changed. - if !messages.is_empty() - || matches!( - interface_state, - user_interface::State::Outdated, - ) - { - let mut cached_interfaces: HashMap<_, _> = - ManuallyDrop::into_inner(interfaces) - .drain() - .map( - |(id, interface): ( - window::Id, - UserInterface<'_, _, _>, - )| { - (id, interface.into_cache()) - }, - ) - .collect(); - - // Update application - update( - &mut application, - &mut cached_interfaces, - &states, - &mut renderer, - &mut runtime, - &mut clipboard, - &mut proxy, - &mut debug, - &mut messages, - &windows, - || compositor.fetch_information(), - ); - - // synchronize window states with application states. - for (id, state) in states.iter_mut() { - state.synchronize( - &application, - *id, - windows - .get(id) - .expect("No window found with ID."), - ); - } + } - interfaces = ManuallyDrop::new(build_user_interfaces( - &application, - &mut renderer, - &mut debug, - &states, - cached_interfaces, - )); + debug.event_processing_finished(); + + // TODO mw application update returns which window IDs to update + if !messages.is_empty() || uis_stale { + let mut cached_interfaces: Vec<Cache> = + ManuallyDrop::into_inner(user_interfaces) + .drain(..) + .map(UserInterface::into_cache) + .collect(); + + // Update application + update( + &mut application, + &mut compositor, + &mut runtime, + &mut clipboard, + &mut proxy, + &mut debug, + &mut messages, + &mut windows, + &mut cached_interfaces, + ); - if application.should_exit() { - break 'main; - } + // we must synchronize all window states with application state after an + // application update since we don't know what changed + for (state, (id, window)) in windows + .states + .iter_mut() + .zip(windows.ids.iter().zip(windows.raw.iter())) + { + state.synchronize(&application, *id, window); } + // rebuild UIs with the synchronized states + user_interfaces = ManuallyDrop::new(build_user_interfaces( + &application, + &mut debug, + &mut windows, + cached_interfaces, + )); + } + + debug.draw_started(); + + for (i, id) in windows.ids.iter().enumerate() { // TODO: Avoid redrawing all the time by forcing widgets to - // request redraws on state changes + // request redraws on state changes // // Then, we can use the `interface_state` here to decide if a redraw // is needed right away, or simply wait until a specific time. - let redraw_event = iced_native::Event::Window( - id, + let redraw_event = core::Event::Window( + *id, window::Event::RedrawRequested(Instant::now()), ); - let (interface_state, _) = - interfaces.get_mut(&id).unwrap().update( - &[redraw_event.clone()], - cursor_position, - &mut renderer, - &mut clipboard, - &mut messages, - ); + let cursor = windows.states[i].cursor(); + + let (ui_state, _) = user_interfaces[i].update( + &[redraw_event.clone()], + cursor, + &mut windows.renderers[i], + &mut clipboard, + &mut messages, + ); - debug.draw_started(); let new_mouse_interaction = { - let state = states.get(&id).unwrap(); + let state = &windows.states[i]; - interfaces.get_mut(&id).unwrap().draw( - &mut renderer, + user_interfaces[i].draw( + &mut windows.renderers[i], state.theme(), &renderer::Style { text_color: state.text_color(), }, - state.cursor_position(), + cursor, ) }; - debug.draw_finished(); - - let window = windows.get(&id).unwrap(); if new_mouse_interaction != mouse_interaction { - window.set_cursor_icon(conversion::mouse_interaction( - new_mouse_interaction, - )); + windows.raw[i].set_cursor_icon( + conversion::mouse_interaction( + new_mouse_interaction, + ), + ); mouse_interaction = new_mouse_interaction; } - for window in windows.values() { - window.request_redraw(); - } + // TODO once widgets can request to be redrawn, we can avoid always requesting a + // redraw + windows.raw[i].request_redraw(); - runtime.broadcast(( + runtime.broadcast( redraw_event.clone(), - crate::event::Status::Ignored, - )); + core::event::Status::Ignored, + ); - let _ = control_sender.start_send(match interface_state { + let _ = control_sender.start_send(match ui_state { user_interface::State::Updated { redraw_request: Some(redraw_request), } => match redraw_request { @@ -590,17 +524,20 @@ async fn run_instance<A, E, C>( }, _ => ControlFlow::Wait, }); - - redraw_pending = false; } + + redraw_pending = false; + + debug.draw_finished(); } event::Event::PlatformSpecific(event::PlatformSpecific::MacOS( event::MacOS::ReceivedUrl(url), )) => { - use iced_native::event; + use crate::core::event; + events.push(( None, - iced_native::Event::PlatformSpecific( + event::Event::PlatformSpecific( event::PlatformSpecific::MacOS( event::MacOS::ReceivedUrl(url), ), @@ -612,91 +549,48 @@ async fn run_instance<A, E, C>( messages.push(message); } Event::WindowCreated(id, window) => { - let mut surface = compositor.create_surface(&window); - let state = State::new(&application, id, &window); - let physical_size = state.physical_size(); + let bounds = logical_bounds_of(&window); - compositor.configure_surface( - &mut surface, - physical_size.width, - physical_size.height, - ); + let (inner_size, i) = + windows.add(&application, &mut compositor, id, window); - let user_interface = build_user_interface( + user_interfaces.push(build_user_interface( &application, user_interface::Cache::default(), - &mut renderer, - state.logical_size(), + &mut windows.renderers[i], + inner_size, &mut debug, id, - ); - - let _ = states.insert(id, state); - let _ = surfaces.insert(id, surface); - let _ = interfaces.insert(id, user_interface); - let _ = window_ids.insert(window.id(), id); - let _ = windows.insert(id, window); - let _ = caches.insert(id, user_interface::Cache::default()); + )); + ui_caches.push(user_interface::Cache::default()); + + if let Some(bounds) = bounds { + events.push(( + Some(id), + core::Event::Window( + id, + window::Event::Created { + position: bounds.0, + size: bounds.1, + }, + ), + )); + } } Event::CloseWindow(id) => { - if let Some(window) = windows.get(&id) { - if window_ids.remove(&window.id()).is_none() { - log::error!("Failed to remove window with id {:?} from window_ids.", window.id()); - } - } else { - log::error!( - "Could not find window with id {:?} in windows.", - id - ); - } - if states.remove(&id).is_none() { - log::error!( - "Failed to remove window {:?} from states.", - id - ); - } - if interfaces.remove(&id).is_none() { - log::error!( - "Failed to remove window {:?} from interfaces.", - id - ); - } - if windows.remove(&id).is_none() { - log::error!( - "Failed to remove window {:?} from windows.", - id - ); - } - if surfaces.remove(&id).is_none() { - log::error!( - "Failed to remove window {:?} from surfaces.", - id - ); - } + let i = windows.delete(id); + let _ = user_interfaces.remove(i); + let _ = ui_caches.remove(i); if windows.is_empty() { - log::info!( - "All windows are closed. Terminating program." - ); break 'main; - } else { - log::info!("Remaining windows: {:?}", windows.len()); } } Event::NewWindow { .. } => unreachable!(), }, event::Event::RedrawRequested(id) => { - #[cfg(feature = "trace")] - let _ = info_span!("Application", "FRAME").entered(); - - let state = window_ids - .get(&id) - .and_then(|id| states.get_mut(id)) - .unwrap(); - let surface = window_ids - .get(&id) - .and_then(|id| surfaces.get_mut(id)) - .unwrap(); + let i = windows.index_from_raw(id); + let state = &windows.states[i]; let physical_size = state.physical_size(); if physical_size.width == 0 || physical_size.height == 0 { @@ -704,60 +598,55 @@ async fn run_instance<A, E, C>( } debug.render_started(); + let current_viewport_version = state.viewport_version(); + let window_viewport_version = windows.viewport_versions[i]; - if state.viewport_changed() { - let mut user_interface = window_ids - .get(&id) - .and_then(|id| interfaces.remove(id)) - .unwrap(); - + if window_viewport_version != current_viewport_version { let logical_size = state.logical_size(); debug.layout_started(); - user_interface = - user_interface.relayout(logical_size, &mut renderer); + + let renderer = &mut windows.renderers[i]; + let ui = user_interfaces.remove(i); + + user_interfaces + .insert(i, ui.relayout(logical_size, renderer)); + debug.layout_finished(); debug.draw_started(); - let new_mouse_interaction = { - let state = &state; - - user_interface.draw( - &mut renderer, - state.theme(), - &renderer::Style { - text_color: state.text_color(), - }, - state.cursor_position(), - ) - }; + let new_mouse_interaction = user_interfaces[i].draw( + renderer, + state.theme(), + &renderer::Style { + text_color: state.text_color(), + }, + state.cursor(), + ); - let window = window_ids - .get(&id) - .and_then(|id| windows.get(id)) - .unwrap(); if new_mouse_interaction != mouse_interaction { - window.set_cursor_icon(conversion::mouse_interaction( - new_mouse_interaction, - )); + windows.raw[i].set_cursor_icon( + conversion::mouse_interaction( + new_mouse_interaction, + ), + ); mouse_interaction = new_mouse_interaction; } debug.draw_finished(); - let _ = interfaces - .insert(*window_ids.get(&id).unwrap(), user_interface); - compositor.configure_surface( - surface, + &mut windows.surfaces[i], physical_size.width, physical_size.height, ); + + windows.viewport_versions[i] = current_viewport_version; } match compositor.present( - &mut renderer, - surface, + &mut windows.renderers[i], + &mut windows.surfaces[i], state.viewport(), state.background_color(), &debug.overlay(), @@ -775,10 +664,12 @@ async fn run_instance<A, E, C>( } _ => { debug.render_finished(); - log::error!("Error {error:?} when presenting surface."); + log::error!( + "Error {error:?} when presenting surface." + ); - // Try rendering windows again next frame. - for window in windows.values() { + // Try rendering all windows again next frame. + for window in &windows.raw { window.request_redraw(); } } @@ -789,42 +680,58 @@ async fn run_instance<A, E, C>( event: window_event, window_id, } => { - if let (Some(window), Some(state)) = ( - window_ids.get(&window_id).and_then(|id| windows.get(id)), - window_ids - .get(&window_id) - .and_then(|id| states.get_mut(id)), - ) { - if crate::application::requests_exit(&window_event, state.modifiers()) { - if let Some(id) = window_ids.get(&window_id).cloned() { - let message = application.close_requested(id); - messages.push(message); - } + let window_deleted = windows + .pending_destroy + .iter() + .any(|(_, w_id)| window_id == *w_id); + + if matches!(window_event, winit::event::WindowEvent::Destroyed) + { + // This is the only special case, since in order trigger the Destroyed event the + // window reference from winit must be dropped, but we still want to inform the + // user that the window was destroyed so they can clean up any specific window + // code for this window + let id = windows.get_pending_destroy(window_id); + + events.push(( + None, + core::Event::Window(id, window::Event::Destroyed), + )); + } else if !window_deleted { + let i = windows.index_from_raw(window_id); + let id = windows.ids[i]; + let raw = &windows.raw[i]; + let state = &mut windows.states[i]; + + // first check if we need to just break the entire application + // e.g. a user does a force quit on MacOS, or if a user has set "exit on main closed" + // as an option in window settings and wants to close the main window + if requests_exit( + i, + exit_on_main_closed, + &window_event, + state.modifiers(), + ) { + break 'main; } - state.update(window, &window_event, &mut debug); + state.update(raw, &window_event, &mut debug); if let Some(event) = conversion::window_event( - *window_ids.get(&window_id).unwrap(), + id, &window_event, state.scale_factor(), state.modifiers(), ) { - events - .push((window_ids.get(&window_id).cloned(), event)); + events.push((Some(id), event)); } - } else { - log::error!( - "Could not find window or state for id: {window_id:?}" - ); } } _ => {} } } - // Manually drop the user interfaces - drop(ManuallyDrop::into_inner(interfaces)); + let _ = ManuallyDrop::into_inner(user_interfaces); } /// Builds a window's [`UserInterface`] for the [`Application`]. @@ -837,103 +744,79 @@ pub fn build_user_interface<'a, A: Application>( id: window::Id, ) -> UserInterface<'a, A::Message, A::Renderer> where - <A::Renderer as crate::Renderer>::Theme: StyleSheet, + <A::Renderer as core::Renderer>::Theme: StyleSheet, { - #[cfg(feature = "trace")] - let view_span = info_span!("Application", "VIEW").entered(); - debug.view_started(); let view = application.view(id); - - #[cfg(feature = "trace")] - let _ = view_span.exit(); debug.view_finished(); - #[cfg(feature = "trace")] - let layout_span = info_span!("Application", "LAYOUT").entered(); debug.layout_started(); - let user_interface = UserInterface::build(view, size, cache, renderer); - - #[cfg(feature = "trace")] - let _ = layout_span.exit(); debug.layout_finished(); user_interface } -/// Updates an [`Application`] by feeding it messages, spawning any +/// Updates a multi-window [`Application`] by feeding it messages, spawning any /// resulting [`Command`], and tracking its [`Subscription`]. -pub fn update<A: Application, E: Executor>( +pub fn update<A: Application, C, E: Executor>( application: &mut A, - caches: &mut HashMap<window::Id, user_interface::Cache>, - states: &HashMap<window::Id, State<A>>, - renderer: &mut A::Renderer, + compositor: &mut C, runtime: &mut Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>, clipboard: &mut Clipboard, proxy: &mut winit::event_loop::EventLoopProxy<Event<A::Message>>, debug: &mut Debug, messages: &mut Vec<A::Message>, - windows: &HashMap<window::Id, winit::window::Window>, - graphics_info: impl FnOnce() -> compositor::Information + Copy, + windows: &mut Windows<A, C>, + ui_caches: &mut Vec<user_interface::Cache>, ) where - A: Application + 'static, - <A::Renderer as crate::Renderer>::Theme: StyleSheet, + C: Compositor<Renderer = A::Renderer> + 'static, + <A::Renderer as core::Renderer>::Theme: StyleSheet, { for message in messages.drain(..) { - #[cfg(feature = "trace")] - let update_span = info_span!("Application", "UPDATE").entered(); - debug.log_message(&message); - debug.update_started(); let command = runtime.enter(|| application.update(message)); - - #[cfg(feature = "trace")] - let _ = update_span.exit(); debug.update_finished(); run_command( application, - caches, - states, - renderer, + compositor, command, runtime, clipboard, proxy, debug, windows, - graphics_info, + ui_caches, ); } let subscription = application.subscription().map(Event::Application); - runtime.track(subscription); + runtime.track(subscription.into_recipes()); } /// Runs the actions of a [`Command`]. -pub fn run_command<A, E>( +pub fn run_command<A, C, E>( application: &A, - caches: &mut HashMap<window::Id, user_interface::Cache>, - states: &HashMap<window::Id, State<A>>, - renderer: &mut A::Renderer, + compositor: &mut C, command: Command<A::Message>, runtime: &mut Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>, clipboard: &mut Clipboard, proxy: &mut winit::event_loop::EventLoopProxy<Event<A::Message>>, debug: &mut Debug, - windows: &HashMap<window::Id, winit::window::Window>, - _graphics_info: impl FnOnce() -> compositor::Information + Copy, + windows: &mut Windows<A, C>, + ui_caches: &mut Vec<user_interface::Cache>, ) where - A: Application + 'static, + A: Application, E: Executor, - <A::Renderer as crate::Renderer>::Theme: StyleSheet, + C: Compositor<Renderer = A::Renderer> + 'static, + <A::Renderer as core::Renderer>::Theme: StyleSheet, { - use iced_native::command; - use iced_native::system; - use iced_native::window; + use crate::runtime::clipboard; + use crate::runtime::system; + use crate::runtime::window; for action in command.actions() { match action { @@ -954,11 +837,14 @@ pub fn run_command<A, E>( }, command::Action::Window(id, action) => match action { window::Action::Spawn { settings } => { + let monitor = windows.last_monitor(); + proxy .send_event(Event::NewWindow { id, - settings: settings.into(), + settings, title: application.title(id), + monitor, }) .expect("Send message to event loop"); } @@ -968,86 +854,117 @@ pub fn run_command<A, E>( .expect("Send message to event loop"); } window::Action::Drag => { - let window = windows.get(&id).expect("No window found"); - let _res = window.drag_window(); + let _ = windows.with_raw(id).drag_window(); } - window::Action::Resize { width, height } => { - let window = windows.get(&id).expect("No window found"); - window.set_inner_size(winit::dpi::LogicalSize { - width, - height, - }); + window::Action::Resize(size) => { + windows.with_raw(id).set_inner_size( + winit::dpi::LogicalSize { + width: size.width, + height: size.height, + }, + ); + } + window::Action::FetchSize(callback) => { + let window = windows.with_raw(id); + let size = window.inner_size(); + + proxy + .send_event(Event::Application(callback(Size::new( + size.width, + size.height, + )))) + .expect("Send message to event loop") + } + window::Action::Maximize(maximized) => { + windows.with_raw(id).set_maximized(maximized); + } + window::Action::Minimize(minimized) => { + windows.with_raw(id).set_minimized(minimized); } window::Action::Move { x, y } => { - let window = windows.get(&id).expect("No window found"); - window.set_outer_position(winit::dpi::LogicalPosition { - x, - y, - }); + windows.with_raw(id).set_outer_position( + winit::dpi::LogicalPosition { x, y }, + ); } window::Action::ChangeMode(mode) => { - let window = windows.get(&id).expect("No window found"); + let window = windows.with_raw(id); window.set_visible(conversion::visible(mode)); window.set_fullscreen(conversion::fullscreen( window.current_monitor(), mode, )); } + window::Action::ChangeIcon(icon) => { + windows.with_raw(id).set_window_icon(conversion::icon(icon)) + } window::Action::FetchMode(tag) => { - let window = windows.get(&id).expect("No window found"); + let window = windows.with_raw(id); let mode = if window.is_visible().unwrap_or(true) { conversion::mode(window.fullscreen()) } else { - window::Mode::Hidden + core::window::Mode::Hidden }; proxy .send_event(Event::Application(tag(mode))) - .expect("Send message to event loop"); - } - window::Action::Maximize(value) => { - let window = windows.get(&id).expect("No window found!"); - window.set_maximized(value); - } - window::Action::Minimize(value) => { - let window = windows.get(&id).expect("No window found!"); - window.set_minimized(value); + .expect("Event loop doesn't exist."); } window::Action::ToggleMaximize => { - let window = windows.get(&id).expect("No window found!"); + let window = windows.with_raw(id); window.set_maximized(!window.is_maximized()); } window::Action::ToggleDecorations => { - let window = windows.get(&id).expect("No window found!"); + let window = windows.with_raw(id); window.set_decorations(!window.is_decorated()); } window::Action::RequestUserAttention(attention_type) => { - let window = windows.get(&id).expect("No window found!"); - window.request_user_attention( + windows.with_raw(id).request_user_attention( attention_type.map(conversion::user_attention), ); } window::Action::GainFocus => { - let window = windows.get(&id).expect("No window found!"); - window.focus_window(); + windows.with_raw(id).focus_window(); } - window::Action::ChangeAlwaysOnTop(on_top) => { - let window = windows.get(&id).expect("No window found!"); - window.set_always_on_top(on_top); + window::Action::ChangeLevel(level) => { + windows + .with_raw(id) + .set_window_level(conversion::window_level(level)); } - window::Action::FetchId(tag) => { - let window = windows.get(&id).expect("No window found!"); + window::Action::FetchId(tag) => proxy + .send_event(Event::Application(tag(windows + .with_raw(id) + .id() + .into()))) + .expect("Event loop doesn't exist."), + window::Action::Screenshot(tag) => { + let i = windows.index_from_id(id); + let state = &windows.states[i]; + let surface = &mut windows.surfaces[i]; + let renderer = &mut windows.renderers[i]; + + let bytes = compositor.screenshot( + renderer, + surface, + state.viewport(), + state.background_color(), + &debug.overlay(), + ); proxy - .send_event(Event::Application(tag(window.id().into()))) - .expect("Send message to event loop.") + .send_event(Event::Application(tag( + window::Screenshot::new( + bytes, + state.physical_size(), + ), + ))) + .expect("Event loop doesn't exist.") } }, command::Action::System(action) => match action { system::Action::QueryInformation(_tag) => { #[cfg(feature = "system")] { - let graphics_info = _graphics_info(); + let graphics_info = compositor.fetch_information(); let proxy = proxy.clone(); let _ = std::thread::spawn(move || { @@ -1058,33 +975,36 @@ pub fn run_command<A, E>( proxy .send_event(Event::Application(message)) - .expect("Send message to event loop") + .expect("Event loop doesn't exist.") }); } } }, command::Action::Widget(action) => { - let mut current_caches = std::mem::take(caches); - let mut current_operation = Some(action.into_operation()); + let mut current_operation = Some(action); - let mut user_interfaces = build_user_interfaces( + let mut uis = build_user_interfaces( application, - renderer, debug, - states, - current_caches, + windows, + std::mem::take(ui_caches), ); - while let Some(mut operation) = current_operation.take() { - for user_interface in user_interfaces.values_mut() { - user_interface.operate(renderer, operation.as_mut()); + 'operate: while let Some(mut operation) = + current_operation.take() + { + for (i, ui) in uis.iter_mut().enumerate() { + ui.operate(&windows.renderers[i], operation.as_mut()); match operation.finish() { operation::Outcome::None => {} operation::Outcome::Some(message) => { proxy .send_event(Event::Application(message)) - .expect("Send message to event loop"); + .expect("Event loop doesn't exist."); + + // operation completed, don't need to try to operate on rest of UIs + break 'operate; } operation::Outcome::Chain(next) => { current_operation = Some(next); @@ -1093,55 +1013,105 @@ pub fn run_command<A, E>( } } - let user_interfaces: HashMap<_, _> = user_interfaces - .drain() - .map(|(id, interface)| (id, interface.into_cache())) - .collect(); + *ui_caches = + uis.drain(..).map(UserInterface::into_cache).collect(); + } + command::Action::LoadFont { bytes, tagger } => { + use crate::core::text::Renderer; + + // TODO change this once we change each renderer to having a single backend reference.. :pain: + // TODO: Error handling (?) + for renderer in &mut windows.renderers { + renderer.load_font(bytes.clone()); + } - current_caches = user_interfaces; - *caches = current_caches; + proxy + .send_event(Event::Application(tagger(Ok(())))) + .expect("Send message to event loop"); } } } } -/// Build the user interfaces for every window. -pub fn build_user_interfaces<'a, A>( +/// Build the user interface for every window. +pub fn build_user_interfaces<'a, A: Application, C: Compositor>( application: &'a A, - renderer: &mut A::Renderer, debug: &mut Debug, - states: &HashMap<window::Id, State<A>>, - mut cached_user_interfaces: HashMap<window::Id, user_interface::Cache>, -) -> HashMap< - window::Id, - UserInterface< - 'a, - <A as Application>::Message, - <A as Application>::Renderer, - >, -> + windows: &mut Windows<A, C>, + mut cached_user_interfaces: Vec<user_interface::Cache>, +) -> Vec<UserInterface<'a, A::Message, A::Renderer>> where - A: Application + 'static, - <A::Renderer as crate::Renderer>::Theme: StyleSheet, + <A::Renderer as core::Renderer>::Theme: StyleSheet, + C: Compositor<Renderer = A::Renderer>, { - let mut interfaces = HashMap::new(); - - for (id, cache) in cached_user_interfaces.drain() { - let state = &states.get(&id).unwrap(); - - let user_interface = build_user_interface( - application, - cache, - renderer, - state.logical_size(), - debug, - id, - ); + cached_user_interfaces + .drain(..) + .zip( + windows + .ids + .iter() + .zip(windows.states.iter().zip(windows.renderers.iter_mut())), + ) + .fold(vec![], |mut uis, (cache, (id, (state, renderer)))| { + uis.push(build_user_interface( + application, + cache, + renderer, + state.logical_size(), + debug, + *id, + )); + + uis + }) +} - let _ = interfaces.insert(id, user_interface); +/// Returns true if the provided event should cause an [`Application`] to +/// exit. +pub fn requests_exit( + window: usize, + exit_on_main_closed: bool, + event: &winit::event::WindowEvent<'_>, + _modifiers: winit::event::ModifiersState, +) -> bool { + use winit::event::WindowEvent; + + //TODO alt f4..? + match event { + WindowEvent::CloseRequested => exit_on_main_closed && window == 0, + #[cfg(target_os = "macos")] + WindowEvent::KeyboardInput { + input: + winit::event::KeyboardInput { + virtual_keycode: Some(winit::event::VirtualKeyCode::Q), + state: winit::event::ElementState::Pressed, + .. + }, + .. + } if _modifiers.logo() => true, + _ => false, } +} + +fn logical_bounds_of( + window: &winit::window::Window, +) -> Option<((i32, i32), Size<u32>)> { + let scale = window.scale_factor(); + let pos = window + .inner_position() + .map(|pos| { + ((pos.x as f64 / scale) as i32, (pos.y as f64 / scale) as i32) + }) + .ok()?; + let size = { + let size = window.inner_size(); + Size::new( + (size.width as f64 / scale) as u32, + (size.height as f64 / scale) as u32, + ) + }; - interfaces + Some((pos, size)) } #[cfg(not(target_arch = "wasm32"))] diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index 54a114ad4f..f2741c3c12 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -1,33 +1,50 @@ -use crate::application::{self, StyleSheet as _}; use crate::conversion; +use crate::core; +use crate::core::{mouse, window}; +use crate::core::{Color, Size}; +use crate::graphics::Viewport; use crate::multi_window::Application; -use crate::window; -use crate::{Color, Debug, Point, Size, Viewport}; +use crate::style::application; +use std::fmt::{Debug, Formatter}; -use std::marker::PhantomData; +use iced_style::application::StyleSheet; use winit::event::{Touch, WindowEvent}; use winit::window::Window; /// The state of a multi-windowed [`Application`]. -#[allow(missing_debug_implementations)] pub struct State<A: Application> where - <A::Renderer as crate::Renderer>::Theme: application::StyleSheet, + <A::Renderer as core::Renderer>::Theme: application::StyleSheet, { title: String, scale_factor: f64, viewport: Viewport, - viewport_changed: bool, - cursor_position: winit::dpi::PhysicalPosition<f64>, + viewport_version: usize, + cursor_position: Option<winit::dpi::PhysicalPosition<f64>>, modifiers: winit::event::ModifiersState, - theme: <A::Renderer as crate::Renderer>::Theme, + theme: <A::Renderer as core::Renderer>::Theme, appearance: application::Appearance, - application: PhantomData<A>, +} + +impl<A: Application> Debug for State<A> +where + <A::Renderer as core::Renderer>::Theme: application::StyleSheet, +{ + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("multi_window::State") + .field("title", &self.title) + .field("scale_factor", &self.scale_factor) + .field("viewport", &self.viewport) + .field("viewport_version", &self.viewport_version) + .field("cursor_position", &self.cursor_position) + .field("appearance", &self.appearance) + .finish() + } } impl<A: Application> State<A> where - <A::Renderer as crate::Renderer>::Theme: application::StyleSheet, + <A::Renderer as core::Renderer>::Theme: application::StyleSheet, { /// Creates a new [`State`] for the provided [`Application`]'s `window`. pub fn new( @@ -53,13 +70,11 @@ where title, scale_factor, viewport, - viewport_changed: false, - // TODO: Encode cursor availability in the type-system - cursor_position: winit::dpi::PhysicalPosition::new(-1.0, -1.0), + viewport_version: 0, + cursor_position: None, modifiers: winit::event::ModifiersState::default(), theme, appearance, - application: PhantomData, } } @@ -68,9 +83,11 @@ where &self.viewport } - /// Returns whether or not the viewport changed. - pub fn viewport_changed(&self) -> bool { - self.viewport_changed + /// Returns the version of the [`Viewport`] of the [`State`]. + /// + /// The version is incremented every time the [`Viewport`] changes. + pub fn viewport_version(&self) -> usize { + self.viewport_version } /// Returns the physical [`Size`] of the [`Viewport`] of the [`State`]. @@ -89,11 +106,16 @@ where } /// Returns the current cursor position of the [`State`]. - pub fn cursor_position(&self) -> Point { - conversion::cursor_position( - self.cursor_position, - self.viewport.scale_factor(), - ) + pub fn cursor(&self) -> mouse::Cursor { + self.cursor_position + .map(|cursor_position| { + conversion::cursor_position( + cursor_position, + self.viewport.scale_factor(), + ) + }) + .map(mouse::Cursor::Available) + .unwrap_or(mouse::Cursor::Unavailable) } /// Returns the current keyboard modifiers of the [`State`]. @@ -102,7 +124,7 @@ where } /// Returns the current theme of the [`State`]. - pub fn theme(&self) -> &<A::Renderer as crate::Renderer>::Theme { + pub fn theme(&self) -> &<A::Renderer as core::Renderer>::Theme { &self.theme } @@ -121,7 +143,7 @@ where &mut self, window: &Window, event: &WindowEvent<'_>, - _debug: &mut Debug, + _debug: &mut crate::runtime::Debug, ) { match event { WindowEvent::Resized(new_size) => { @@ -132,7 +154,7 @@ where window.scale_factor() * self.scale_factor, ); - self.viewport_changed = true; + self.viewport_version = self.viewport_version.wrapping_add(1); } WindowEvent::ScaleFactorChanged { scale_factor: new_scale_factor, @@ -146,18 +168,16 @@ where new_scale_factor * self.scale_factor, ); - self.viewport_changed = true; + self.viewport_version = self.viewport_version.wrapping_add(1); } WindowEvent::CursorMoved { position, .. } | WindowEvent::Touch(Touch { location: position, .. }) => { - self.cursor_position = *position; + self.cursor_position = Some(*position); } WindowEvent::CursorLeft { .. } => { - // TODO: Encode cursor availability in the type-system - self.cursor_position = - winit::dpi::PhysicalPosition::new(-1.0, -1.0); + self.cursor_position = None; } WindowEvent::ModifiersChanged(new_modifiers) => { self.modifiers = *new_modifiers; @@ -197,16 +217,20 @@ where self.title = new_title; } - // Update scale factor + // Update scale factor and size let new_scale_factor = application.scale_factor(window_id); + let new_size = window.inner_size(); + let current_size = self.viewport.physical_size(); - if self.scale_factor != new_scale_factor { - let size = window.inner_size(); - + if self.scale_factor != new_scale_factor + || (current_size.width, current_size.height) + != (new_size.width, new_size.height) + { self.viewport = Viewport::with_physical_size( - Size::new(size.width, size.height), + Size::new(new_size.width, new_size.height), window.scale_factor() * new_scale_factor, ); + self.viewport_version = self.viewport_version.wrapping_add(1); self.scale_factor = new_scale_factor; } diff --git a/winit/src/multi_window/windows.rs b/winit/src/multi_window/windows.rs new file mode 100644 index 0000000000..7b63defaf9 --- /dev/null +++ b/winit/src/multi_window/windows.rs @@ -0,0 +1,170 @@ +use crate::core::{window, Size}; +use crate::multi_window::{Application, State}; +use iced_graphics::Compositor; +use iced_style::application::StyleSheet; +use std::fmt::{Debug, Formatter}; +use winit::monitor::MonitorHandle; + +pub struct Windows<A: Application, C: Compositor> +where + <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, + C: Compositor<Renderer = A::Renderer>, +{ + pub ids: Vec<window::Id>, + pub raw: Vec<winit::window::Window>, + pub states: Vec<State<A>>, + pub viewport_versions: Vec<usize>, + pub surfaces: Vec<C::Surface>, + pub renderers: Vec<A::Renderer>, + pub pending_destroy: Vec<(window::Id, winit::window::WindowId)>, +} + +impl<A: Application, C: Compositor> Debug for Windows<A, C> +where + <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, + C: Compositor<Renderer = A::Renderer>, +{ + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Windows") + .field("ids", &self.ids) + .field( + "raw", + &self + .raw + .iter() + .map(|raw| raw.id()) + .collect::<Vec<winit::window::WindowId>>(), + ) + .field("states", &self.states) + .field("viewport_versions", &self.viewport_versions) + .finish() + } +} + +impl<A: Application, C: Compositor> Windows<A, C> +where + <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, + C: Compositor<Renderer = A::Renderer>, +{ + /// Creates a new [`Windows`] with a single `window::Id::MAIN` window. + pub fn new( + application: &A, + compositor: &mut C, + renderer: A::Renderer, + main: winit::window::Window, + ) -> Self { + let state = State::new(application, window::Id::MAIN, &main); + let viewport_version = state.viewport_version(); + let physical_size = state.physical_size(); + let surface = compositor.create_surface( + &main, + physical_size.width, + physical_size.height, + ); + + Self { + ids: vec![window::Id::MAIN], + raw: vec![main], + states: vec![state], + viewport_versions: vec![viewport_version], + surfaces: vec![surface], + renderers: vec![renderer], + pending_destroy: vec![], + } + } + + /// Adds a new window to [`Windows`]. Returns the size of the newly created window in logical + /// pixels & the index of the window within [`Windows`]. + pub fn add( + &mut self, + application: &A, + compositor: &mut C, + id: window::Id, + window: winit::window::Window, + ) -> (Size, usize) { + let state = State::new(application, id, &window); + let window_size = state.logical_size(); + let viewport_version = state.viewport_version(); + let physical_size = state.physical_size(); + let surface = compositor.create_surface( + &window, + physical_size.width, + physical_size.height, + ); + let renderer = compositor.renderer(); + + self.ids.push(id); + self.raw.push(window); + self.states.push(state); + self.viewport_versions.push(viewport_version); + self.surfaces.push(surface); + self.renderers.push(renderer); + + (window_size, self.ids.len() - 1) + } + + pub fn is_empty(&self) -> bool { + self.ids.is_empty() + } + + pub fn main(&self) -> &winit::window::Window { + &self.raw[0] + } + + pub fn index_from_raw(&self, id: winit::window::WindowId) -> usize { + self.raw + .iter() + .position(|window| window.id() == id) + .expect("No raw window in multi_window::Windows") + } + + pub fn index_from_id(&self, id: window::Id) -> usize { + self.ids + .iter() + .position(|window_id| *window_id == id) + .expect("No window in multi_window::Windows") + } + + pub fn last_monitor(&self) -> Option<MonitorHandle> { + self.raw.last().and_then(|w| w.current_monitor()) + } + + pub fn last(&self) -> usize { + self.ids.len() - 1 + } + + pub fn with_raw(&self, id: window::Id) -> &winit::window::Window { + let i = self.index_from_id(id); + &self.raw[i] + } + + /// Deletes the window with `id` from [`Windows`]. Returns the index that the window had. + pub fn delete(&mut self, id: window::Id) -> usize { + let i = self.index_from_id(id); + + let id = self.ids.remove(i); + let window = self.raw.remove(i); + let _ = self.states.remove(i); + let _ = self.viewport_versions.remove(i); + let _ = self.surfaces.remove(i); + + self.pending_destroy.push((id, window.id())); + + i + } + + /// Gets the winit `window` that is pending to be destroyed if it exists. + pub fn get_pending_destroy( + &mut self, + window: winit::window::WindowId, + ) -> window::Id { + let i = self + .pending_destroy + .iter() + .position(|(_, window_id)| window == *window_id) + .unwrap(); + + let (id, _) = self.pending_destroy.remove(i); + id + } +} diff --git a/winit/src/profiler.rs b/winit/src/profiler.rs deleted file mode 100644 index 7031507a21..0000000000 --- a/winit/src/profiler.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! A simple profiler for Iced. -use std::ffi::OsStr; -use std::path::Path; -use std::time::Duration; -use tracing_subscriber::prelude::*; -use tracing_subscriber::Registry; -#[cfg(feature = "chrome-trace")] -use { - tracing_chrome::FlushGuard, - tracing_subscriber::fmt::{format::DefaultFields, FormattedFields}, -}; - -/// Profiler state. This will likely need to be updated or reworked when adding new tracing backends. -#[allow(missing_debug_implementations)] -pub struct Profiler { - #[cfg(feature = "chrome-trace")] - /// [`FlushGuard`] must not be dropped until the application scope is dropped for accurate tracing. - _guard: FlushGuard, -} - -impl Profiler { - /// Initializes the [`Profiler`]. - pub fn init() -> Self { - // Registry stores the spans & generates unique span IDs - let subscriber = Registry::default(); - - let default_path = Path::new(env!("CARGO_MANIFEST_DIR")); - let curr_exe = std::env::current_exe() - .unwrap_or_else(|_| default_path.to_path_buf()); - let out_dir = curr_exe.parent().unwrap_or(default_path).join("traces"); - - #[cfg(feature = "chrome-trace")] - let (chrome_layer, guard) = { - let mut layer = tracing_chrome::ChromeLayerBuilder::new(); - - // Optional configurable env var: CHROME_TRACE_FILE=/path/to/trace_file/file.json, - // for uploading to chrome://tracing (old) or ui.perfetto.dev (new). - if let Ok(path) = std::env::var("CHROME_TRACE_FILE") { - layer = layer.file(path); - } else if std::fs::create_dir_all(&out_dir).is_ok() { - let time = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or(Duration::from_millis(0)) - .as_millis(); - - let curr_exe_name = curr_exe - .file_name() - .unwrap_or_else(|| OsStr::new("trace")) - .to_str() - .unwrap_or("trace"); - - let path = - out_dir.join(format!("{curr_exe_name}_trace_{time}.json")); - - layer = layer.file(path); - } else { - layer = layer.file(env!("CARGO_MANIFEST_DIR")) - } - - let (chrome_layer, guard) = layer - .name_fn(Box::new(|event_or_span| match event_or_span { - tracing_chrome::EventOrSpan::Event(event) => { - event.metadata().name().into() - } - tracing_chrome::EventOrSpan::Span(span) => { - if let Some(fields) = span - .extensions() - .get::<FormattedFields<DefaultFields>>() - { - format!( - "{}: {}", - span.metadata().name(), - fields.fields.as_str() - ) - } else { - span.metadata().name().into() - } - } - })) - .build(); - - (chrome_layer, guard) - }; - - let fmt_layer = tracing_subscriber::fmt::Layer::default(); - let subscriber = subscriber.with(fmt_layer); - - #[cfg(feature = "chrome-trace")] - let subscriber = subscriber.with(chrome_layer); - - // create dispatcher which will forward span events to the subscriber - // this can only be set once or will panic - tracing::subscriber::set_global_default(subscriber) - .expect("Tracer could not set the global default subscriber."); - - Profiler { - #[cfg(feature = "chrome-trace")] - _guard: guard, - } - } -} diff --git a/winit/src/settings.rs b/winit/src/settings.rs index 40b3d487d1..2b846fbd6f 100644 --- a/winit/src/settings.rs +++ b/winit/src/settings.rs @@ -1,35 +1,10 @@ //! Configure your application. -#[cfg(target_os = "windows")] -#[path = "settings/windows.rs"] -mod platform; - -#[cfg(target_os = "macos")] -#[path = "settings/macos.rs"] -mod platform; - -#[cfg(target_arch = "wasm32")] -#[path = "settings/wasm.rs"] -mod platform; - -#[cfg(not(any( - target_os = "windows", - target_os = "macos", - target_arch = "wasm32" -)))] -#[path = "settings/other.rs"] -mod platform; - -pub use platform::PlatformSpecific; - use crate::conversion; -use crate::core::window::{Icon, Level}; -use crate::Position; +use crate::core::window; use winit::monitor::MonitorHandle; use winit::window::WindowBuilder; -use std::fmt; - /// The settings of an application. #[derive(Debug, Clone, Default)] pub struct Settings<Flags> { @@ -40,7 +15,7 @@ pub struct Settings<Flags> { pub id: Option<String>, /// The [`Window`] settings. - pub window: Window, + pub window: window::Settings, /// The data needed to initialize an [`Application`]. /// @@ -50,166 +25,93 @@ pub struct Settings<Flags> { /// Whether the [`Application`] should exit when the user requests the /// window to close (e.g. the user presses the close button). /// + /// With a [`multi_window::Application`] this will instead be used to determine whether the + /// application should exit when the "main"" window is closed, i.e. the first window created on + /// app launch. + /// /// [`Application`]: crate::Application pub exit_on_close_request: bool, } -/// The window settings of an application. -#[derive(Clone)] -pub struct Window { - /// The size of the window. - pub size: (u32, u32), - - /// The position of the window. - pub position: Position, - - /// The minimum size of the window. - pub min_size: Option<(u32, u32)>, - - /// The maximum size of the window. - pub max_size: Option<(u32, u32)>, - - /// Whether the window should be visible or not. - pub visible: bool, - - /// Whether the window should be resizable or not. - pub resizable: bool, - - /// Whether the window should have a border, a title bar, etc. - pub decorations: bool, - - /// Whether the window should be transparent. - pub transparent: bool, - - /// The window [`Level`]. - pub level: Level, - - /// The window icon, which is also usually used in the taskbar - pub icon: Option<Icon>, - - /// Platform specific settings. - pub platform_specific: platform::PlatformSpecific, -} - -impl fmt::Debug for Window { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Window") - .field("size", &self.size) - .field("position", &self.position) - .field("min_size", &self.min_size) - .field("max_size", &self.max_size) - .field("visible", &self.visible) - .field("resizable", &self.resizable) - .field("decorations", &self.decorations) - .field("transparent", &self.transparent) - .field("level", &self.level) - .field("icon", &self.icon.is_some()) - .field("platform_specific", &self.platform_specific) - .finish() +/// Converts the window settings into a `WindowBuilder` from `winit`. +pub fn window_builder( + settings: window::Settings, + title: &str, + monitor: Option<MonitorHandle>, + _id: Option<String>, +) -> WindowBuilder { + let mut window_builder = WindowBuilder::new(); + + let (width, height) = settings.size; + + window_builder = window_builder + .with_title(title) + .with_inner_size(winit::dpi::LogicalSize { width, height }) + .with_resizable(settings.resizable) + .with_decorations(settings.decorations) + .with_transparent(settings.transparent) + .with_window_icon(settings.icon.and_then(conversion::icon)) + .with_window_level(conversion::window_level(settings.level)) + .with_visible(settings.visible); + + if let Some(position) = + conversion::position(monitor.as_ref(), settings.size, settings.position) + { + window_builder = window_builder.with_position(position); } -} - -impl Window { - /// Converts the window settings into a `WindowBuilder` from `winit`. - pub fn into_builder( - self, - title: &str, - primary_monitor: Option<MonitorHandle>, - _id: Option<String>, - ) -> WindowBuilder { - let mut window_builder = WindowBuilder::new(); - - let (width, height) = self.size; + if let Some((width, height)) = settings.min_size { window_builder = window_builder - .with_title(title) - .with_inner_size(winit::dpi::LogicalSize { width, height }) - .with_resizable(self.resizable) - .with_decorations(self.decorations) - .with_transparent(self.transparent) - .with_window_icon(self.icon.and_then(conversion::icon)) - .with_window_level(conversion::window_level(self.level)) - .with_visible(self.visible); - - if let Some(position) = conversion::position( - primary_monitor.as_ref(), - self.size, - self.position, - ) { - window_builder = window_builder.with_position(position); - } - - if let Some((width, height)) = self.min_size { - window_builder = window_builder - .with_min_inner_size(winit::dpi::LogicalSize { width, height }); - } + .with_min_inner_size(winit::dpi::LogicalSize { width, height }); + } - if let Some((width, height)) = self.max_size { - window_builder = window_builder - .with_max_inner_size(winit::dpi::LogicalSize { width, height }); - } + if let Some((width, height)) = settings.max_size { + window_builder = window_builder + .with_max_inner_size(winit::dpi::LogicalSize { width, height }); + } - #[cfg(any( - target_os = "linux", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd" - ))] - { - // `with_name` is available on both `WindowBuilderExtWayland` and `WindowBuilderExtX11` and they do - // exactly the same thing. We arbitrarily choose `WindowBuilderExtWayland` here. - use ::winit::platform::wayland::WindowBuilderExtWayland; - - if let Some(id) = _id { - window_builder = window_builder.with_name(id.clone(), id); - } + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + { + // `with_name` is available on both `WindowBuilderExtWayland` and `WindowBuilderExtX11` and they do + // exactly the same thing. We arbitrarily choose `WindowBuilderExtWayland` here. + use ::winit::platform::wayland::WindowBuilderExtWayland; + + if let Some(id) = _id { + window_builder = window_builder.with_name(id.clone(), id); } + } - #[cfg(target_os = "windows")] - { - use winit::platform::windows::WindowBuilderExtWindows; - #[allow(unsafe_code)] - unsafe { - window_builder = window_builder - .with_parent_window(self.platform_specific.parent); - } + #[cfg(target_os = "windows")] + { + use winit::platform::windows::WindowBuilderExtWindows; + #[allow(unsafe_code)] + unsafe { window_builder = window_builder - .with_drag_and_drop(self.platform_specific.drag_and_drop); + .with_parent_window(settings.platform_specific.parent); } + window_builder = window_builder + .with_drag_and_drop(settings.platform_specific.drag_and_drop); + } - #[cfg(target_os = "macos")] - { - use winit::platform::macos::WindowBuilderExtMacOS; - - window_builder = window_builder - .with_title_hidden(self.platform_specific.title_hidden) - .with_titlebar_transparent( - self.platform_specific.titlebar_transparent, - ) - .with_fullsize_content_view( - self.platform_specific.fullsize_content_view, - ); - } + #[cfg(target_os = "macos")] + { + use winit::platform::macos::WindowBuilderExtMacOS; - window_builder + window_builder = window_builder + .with_title_hidden(settings.platform_specific.title_hidden) + .with_titlebar_transparent( + settings.platform_specific.titlebar_transparent, + ) + .with_fullsize_content_view( + settings.platform_specific.fullsize_content_view, + ); } -} -impl Default for Window { - fn default() -> Window { - Window { - size: (1024, 768), - position: Position::default(), - min_size: None, - max_size: None, - visible: true, - resizable: true, - decorations: true, - transparent: false, - level: Level::default(), - icon: None, - platform_specific: Default::default(), - } - } + window_builder } diff --git a/winit/src/window.rs b/winit/src/window.rs deleted file mode 100644 index e69de29bb2..0000000000 From 83c7870c569a2976923ee6243a19813094d44673 Mon Sep 17 00:00:00 2001 From: Bingus <shankern@protonmail.com> Date: Mon, 24 Jul 2023 14:32:59 -0700 Subject: [PATCH 51/66] Moved `exit_on_close_request` to window settings. This now controls whether each INDIVIDUAL window should close on CloseRequested events. --- core/src/window/event.rs | 3 - core/src/window/settings.rs | 11 +++ examples/multi_window/src/main.rs | 6 +- src/settings.rs | 11 --- winit/src/application.rs | 4 +- winit/src/multi_window.rs | 148 ++++++++++++++++++------------ winit/src/multi_window/windows.rs | 26 ++++++ winit/src/settings.rs | 12 +-- 8 files changed, 133 insertions(+), 88 deletions(-) diff --git a/core/src/window/event.rs b/core/src/window/event.rs index 3efce05ef8..f7759435f1 100644 --- a/core/src/window/event.rs +++ b/core/src/window/event.rs @@ -28,9 +28,6 @@ pub enum Event { RedrawRequested(Instant), /// The user has requested for the window to close. - /// - /// Usually, you will want to terminate the execution whenever this event - /// occurs. CloseRequested, /// A window was destroyed by the runtime. diff --git a/core/src/window/settings.rs b/core/src/window/settings.rs index 20811e8393..eba27914e2 100644 --- a/core/src/window/settings.rs +++ b/core/src/window/settings.rs @@ -57,6 +57,16 @@ pub struct Settings { /// Platform specific settings. pub platform_specific: PlatformSpecific, + + /// Whether the window will close when the user requests it, e.g. when a user presses the + /// close button. + /// + /// This can be useful if you want to have some behavior that executes before the window is + /// actually destroyed. If you disable this, you must manually close the window with the + /// `window::close` command. + /// + /// By default this is enabled. + pub exit_on_close_request: bool, } impl Default for Settings { @@ -73,6 +83,7 @@ impl Default for Settings { level: Level::default(), icon: None, platform_specific: Default::default(), + exit_on_close_request: true, } } } diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 58604702a2..51ec3595d3 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -8,10 +8,7 @@ use iced::{ use std::collections::HashMap; fn main() -> iced::Result { - Example::run(Settings { - exit_on_close_request: false, - ..Default::default() - }) + Example::run(Settings::default()) } #[derive(Default)] @@ -111,6 +108,7 @@ impl multi_window::Application for Example { id, window::Settings { position: self.next_window_pos, + exit_on_close_request: count % 2 == 0, ..Default::default() }, ); diff --git a/src/settings.rs b/src/settings.rs index 4ce2d135ef..e2a435810f 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -41,14 +41,6 @@ pub struct Settings<Flags> { /// /// [`Canvas`]: crate::widget::Canvas pub antialiasing: bool, - - /// Whether the [`Application`] should exit when the user requests the - /// window to close (e.g. the user presses the close button). - /// - /// By default, it is enabled. - /// - /// [`Application`]: crate::Application - pub exit_on_close_request: bool, } impl<Flags> Settings<Flags> { @@ -65,7 +57,6 @@ impl<Flags> Settings<Flags> { default_font: default_settings.default_font, default_text_size: default_settings.default_text_size, antialiasing: default_settings.antialiasing, - exit_on_close_request: default_settings.exit_on_close_request, } } } @@ -82,7 +73,6 @@ where default_font: Default::default(), default_text_size: 16.0, antialiasing: false, - exit_on_close_request: true, } } } @@ -93,7 +83,6 @@ impl<Flags> From<Settings<Flags>> for iced_winit::Settings<Flags> { id: settings.id, window: settings.window, flags: settings.flags, - exit_on_close_request: settings.exit_on_close_request, } } } diff --git a/winit/src/application.rs b/winit/src/application.rs index 5c45bbdacb..cffcb8848c 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -136,6 +136,8 @@ where let target = settings.window.platform_specific.target.clone(); let should_be_visible = settings.window.visible; + let exit_on_close_request = settings.window.exit_on_close_request; + let builder = settings::window_builder( settings.window, &application.title(), @@ -197,7 +199,7 @@ where init_command, window, should_be_visible, - settings.exit_on_close_request, + exit_on_close_request, )); let mut context = task::Context::from_waker(task::noop_waker_ref()); diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index e6f440bce0..b67c0a489e 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -46,7 +46,14 @@ pub enum Event<Message> { /// An internal event for closing a window. CloseWindow(window::Id), /// An internal event for when the window has finished being created. - WindowCreated(window::Id, winit::window::Window), + WindowCreated { + /// The internal ID of the window. + id: window::Id, + /// The raw window. + window: winit::window::Window, + /// Whether or not the window should close when a user requests it does. + exit_on_close_request: bool, + }, } #[allow(unsafe_code)] @@ -161,6 +168,8 @@ where }; let should_main_be_visible = settings.window.visible; + let exit_on_close_request = settings.window.exit_on_close_request; + let builder = window_builder( settings.window, &application.title(window::Id::MAIN), @@ -208,8 +217,13 @@ where let (mut compositor, renderer) = C::new(compositor_settings, Some(&main_window))?; - let windows = - Windows::new(&application, &mut compositor, renderer, main_window); + let windows = Windows::new( + &application, + &mut compositor, + renderer, + main_window, + exit_on_close_request, + ); let (mut event_sender, event_receiver) = mpsc::unbounded(); let (control_sender, mut control_receiver) = mpsc::unbounded(); @@ -225,7 +239,6 @@ where init_command, windows, should_main_be_visible, - settings.exit_on_close_request, )); let mut context = task::Context::from_waker(task::noop_waker_ref()); @@ -255,14 +268,18 @@ where title, monitor, }) => { + let exit_on_close_request = settings.exit_on_close_request; + let window = settings::window_builder(settings, &title, monitor, None) .build(window_target) .expect("Failed to build window"); - Some(winit::event::Event::UserEvent(Event::WindowCreated( - id, window, - ))) + Some(winit::event::Event::UserEvent(Event::WindowCreated { + id, + window, + exit_on_close_request, + })) } _ => event.to_static(), }; @@ -299,7 +316,6 @@ async fn run_instance<A, E, C>( init_command: Command<A::Message>, mut windows: Windows<A, C>, should_main_window_be_visible: bool, - exit_on_main_closed: bool, ) where A: Application + 'static, E: Executor + 'static, @@ -548,11 +564,20 @@ async fn run_instance<A, E, C>( Event::Application(message) => { messages.push(message); } - Event::WindowCreated(id, window) => { + Event::WindowCreated { + id, + window, + exit_on_close_request, + } => { let bounds = logical_bounds_of(&window); - let (inner_size, i) = - windows.add(&application, &mut compositor, id, window); + let (inner_size, i) = windows.add( + &application, + &mut compositor, + id, + window, + exit_on_close_request, + ); user_interfaces.push(build_user_interface( &application, @@ -680,50 +705,61 @@ async fn run_instance<A, E, C>( event: window_event, window_id, } => { - let window_deleted = windows - .pending_destroy - .iter() - .any(|(_, w_id)| window_id == *w_id); + let window_index = + windows.raw.iter().position(|w| w.id() == window_id); + + match window_index { + Some(i) => { + let id = windows.ids[i]; + let raw = &windows.raw[i]; + let exit_on_close_request = + windows.exit_on_close_requested[i]; + + if matches!( + window_event, + winit::event::WindowEvent::CloseRequested + ) && exit_on_close_request + { + let i = windows.delete(id); + let _ = user_interfaces.remove(i); + let _ = ui_caches.remove(i); + + if windows.is_empty() { + break 'main; + } + } else { + let state = &mut windows.states[i]; + state.update(raw, &window_event, &mut debug); - if matches!(window_event, winit::event::WindowEvent::Destroyed) - { - // This is the only special case, since in order trigger the Destroyed event the - // window reference from winit must be dropped, but we still want to inform the - // user that the window was destroyed so they can clean up any specific window - // code for this window - let id = windows.get_pending_destroy(window_id); - - events.push(( - None, - core::Event::Window(id, window::Event::Destroyed), - )); - } else if !window_deleted { - let i = windows.index_from_raw(window_id); - let id = windows.ids[i]; - let raw = &windows.raw[i]; - let state = &mut windows.states[i]; - - // first check if we need to just break the entire application - // e.g. a user does a force quit on MacOS, or if a user has set "exit on main closed" - // as an option in window settings and wants to close the main window - if requests_exit( - i, - exit_on_main_closed, - &window_event, - state.modifiers(), - ) { - break 'main; + if let Some(event) = conversion::window_event( + id, + &window_event, + state.scale_factor(), + state.modifiers(), + ) { + events.push((Some(id), event)); + } + } } - - state.update(raw, &window_event, &mut debug); - - if let Some(event) = conversion::window_event( - id, - &window_event, - state.scale_factor(), - state.modifiers(), - ) { - events.push((Some(id), event)); + None => { + // This is the only special case, since in order to trigger the Destroyed event the + // window reference from winit must be dropped, but we still want to inform the + // user that the window was destroyed so they can clean up any specific window + // code for this window + if matches!( + window_event, + winit::event::WindowEvent::Destroyed + ) { + let id = windows.get_pending_destroy(window_id); + + events.push(( + None, + core::Event::Window( + id, + window::Event::Destroyed, + ), + )); + } } } } @@ -1068,17 +1104,13 @@ where /// Returns true if the provided event should cause an [`Application`] to /// exit. -pub fn requests_exit( - window: usize, - exit_on_main_closed: bool, +pub fn user_force_quit( event: &winit::event::WindowEvent<'_>, _modifiers: winit::event::ModifiersState, ) -> bool { use winit::event::WindowEvent; - //TODO alt f4..? match event { - WindowEvent::CloseRequested => exit_on_main_closed && window == 0, #[cfg(target_os = "macos")] WindowEvent::KeyboardInput { input: diff --git a/winit/src/multi_window/windows.rs b/winit/src/multi_window/windows.rs index 7b63defaf9..1f606b3163 100644 --- a/winit/src/multi_window/windows.rs +++ b/winit/src/multi_window/windows.rs @@ -14,6 +14,7 @@ where pub raw: Vec<winit::window::Window>, pub states: Vec<State<A>>, pub viewport_versions: Vec<usize>, + pub exit_on_close_requested: Vec<bool>, pub surfaces: Vec<C::Surface>, pub renderers: Vec<A::Renderer>, pub pending_destroy: Vec<(window::Id, winit::window::WindowId)>, @@ -52,6 +53,7 @@ where compositor: &mut C, renderer: A::Renderer, main: winit::window::Window, + exit_on_close_requested: bool, ) -> Self { let state = State::new(application, window::Id::MAIN, &main); let viewport_version = state.viewport_version(); @@ -67,6 +69,7 @@ where raw: vec![main], states: vec![state], viewport_versions: vec![viewport_version], + exit_on_close_requested: vec![exit_on_close_requested], surfaces: vec![surface], renderers: vec![renderer], pending_destroy: vec![], @@ -81,6 +84,7 @@ where compositor: &mut C, id: window::Id, window: winit::window::Window, + exit_on_close_requested: bool, ) -> (Size, usize) { let state = State::new(application, id, &window); let window_size = state.logical_size(); @@ -96,6 +100,7 @@ where self.ids.push(id); self.raw.push(window); self.states.push(state); + self.exit_on_close_requested.push(exit_on_close_requested); self.viewport_versions.push(viewport_version); self.surfaces.push(surface); self.renderers.push(renderer); @@ -145,6 +150,7 @@ where let id = self.ids.remove(i); let window = self.raw.remove(i); let _ = self.states.remove(i); + let _ = self.exit_on_close_requested.remove(i); let _ = self.viewport_versions.remove(i); let _ = self.surfaces.remove(i); @@ -167,4 +173,24 @@ where let (id, _) = self.pending_destroy.remove(i); id } + + /// Returns the windows that need to be requested to closed, and also the windows that can be + /// closed immediately. + pub fn partition_close_requests(&self) -> (Vec<window::Id>, Vec<window::Id>) { + self.exit_on_close_requested.iter().enumerate().fold( + (vec![], vec![]), + |(mut close_immediately, mut needs_request_closed), + (i, close)| { + let id = self.ids[i]; + + if *close { + close_immediately.push(id); + } else { + needs_request_closed.push(id); + } + + (close_immediately, needs_request_closed) + }, + ) + } } diff --git a/winit/src/settings.rs b/winit/src/settings.rs index 2b846fbd6f..c0b3b047c3 100644 --- a/winit/src/settings.rs +++ b/winit/src/settings.rs @@ -1,6 +1,6 @@ //! Configure your application. -use crate::conversion; use crate::core::window; +use crate::conversion; use winit::monitor::MonitorHandle; use winit::window::WindowBuilder; @@ -21,16 +21,6 @@ pub struct Settings<Flags> { /// /// [`Application`]: crate::Application pub flags: Flags, - - /// Whether the [`Application`] should exit when the user requests the - /// window to close (e.g. the user presses the close button). - /// - /// With a [`multi_window::Application`] this will instead be used to determine whether the - /// application should exit when the "main"" window is closed, i.e. the first window created on - /// app launch. - /// - /// [`Application`]: crate::Application - pub exit_on_close_request: bool, } /// Converts the window settings into a `WindowBuilder` from `winit`. From 6dca076c8b18c3cdb702fa55045866cbd413cc55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Wed, 29 Nov 2023 22:32:41 +0100 Subject: [PATCH 52/66] Use `workspace` dependency for `raw-window-handle` --- core/Cargo.toml | 4 ++-- winit/Cargo.toml | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/core/Cargo.toml b/core/Cargo.toml index 7db4fa536b..4672c754ac 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -23,8 +23,8 @@ palette.optional = true [target.'cfg(target_arch = "wasm32")'.dependencies] instant.workspace = true -[target.'cfg(windows)'.dependencies.raw-window-handle] -version = "0.5.2" +[target.'cfg(windows)'.dependencies] +raw-window-handle.workspace = true [dev-dependencies] approx = "0.5" diff --git a/winit/Cargo.toml b/winit/Cargo.toml index bab05b916b..87e600aeba 100644 --- a/winit/Cargo.toml +++ b/winit/Cargo.toml @@ -27,7 +27,6 @@ iced_runtime.workspace = true iced_style.workspace = true log.workspace = true -raw-window-handle.workspace = true thiserror.workspace = true tracing.workspace = true window_clipboard.workspace = true From abe13b530514c8ce63a0ef90172082258e35a43d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Wed, 29 Nov 2023 22:33:20 +0100 Subject: [PATCH 53/66] Move `multi-window` feature before the `advanced` one --- Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index aba66f39eb..0afbcd513d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,10 +49,10 @@ web-colors = ["iced_renderer/web-colors"] webgl = ["iced_renderer/webgl"] # Enables the syntax `highlighter` module highlighter = ["iced_highlighter"] -# Enables the advanced module -advanced = [] # Enables experimental multi-window support. multi-window = ["iced_winit/multi-window"] +# Enables the advanced module +advanced = [] [dependencies] iced_core.workspace = true From 9b34b2ac19a8fdd424581d160bc702e096a2b46a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Wed, 29 Nov 2023 22:33:41 +0100 Subject: [PATCH 54/66] Run `cargo fmt` --- winit/src/multi_window/windows.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/winit/src/multi_window/windows.rs b/winit/src/multi_window/windows.rs index 1f606b3163..6846abb364 100644 --- a/winit/src/multi_window/windows.rs +++ b/winit/src/multi_window/windows.rs @@ -176,11 +176,12 @@ where /// Returns the windows that need to be requested to closed, and also the windows that can be /// closed immediately. - pub fn partition_close_requests(&self) -> (Vec<window::Id>, Vec<window::Id>) { + pub fn partition_close_requests( + &self, + ) -> (Vec<window::Id>, Vec<window::Id>) { self.exit_on_close_requested.iter().enumerate().fold( (vec![], vec![]), - |(mut close_immediately, mut needs_request_closed), - (i, close)| { + |(mut close_immediately, mut needs_request_closed), (i, close)| { let id = self.ids[i]; if *close { From 7def3ee38a3f0f24a331d722b09f325fc9584625 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Wed, 29 Nov 2023 22:37:54 +0100 Subject: [PATCH 55/66] Fix `clippy` lints --- runtime/src/multi_window/state.rs | 2 +- winit/src/application.rs | 7 ++++--- winit/src/multi_window.rs | 24 ++++++++++++++---------- winit/src/multi_window/windows.rs | 14 +++++++++----- 4 files changed, 28 insertions(+), 19 deletions(-) diff --git a/runtime/src/multi_window/state.rs b/runtime/src/multi_window/state.rs index 78c35e6cc4..05036a0711 100644 --- a/runtime/src/multi_window/state.rs +++ b/runtime/src/multi_window/state.rs @@ -228,7 +228,7 @@ where match operation.finish() { operation::Outcome::None => {} operation::Outcome::Some(message) => { - self.queued_messages.push(message) + self.queued_messages.push(message); } operation::Outcome::Chain(next) => { current_operation = Some(next); diff --git a/winit/src/application.rs b/winit/src/application.rs index 8457fd92f6..b197c4ed78 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -720,9 +720,10 @@ pub fn run_command<A, C, E>( let _res = window.drag_window(); } window::Action::Spawn { .. } => { - log::info!( - "Spawning a window is only available with multi-window applications." - ) + log::warn!( + "Spawning a window is only available with \ + multi-window applications." + ); } window::Action::Resize(size) => { window.set_inner_size(winit::dpi::LogicalSize { diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index f2452eb3c6..b233564abc 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -912,7 +912,7 @@ pub fn run_command<A, C, E>( size.width, size.height, )))) - .expect("Send message to event loop") + .expect("Send message to event loop"); } window::Action::Maximize(maximized) => { windows.with_raw(id).set_maximized(maximized); @@ -934,7 +934,9 @@ pub fn run_command<A, C, E>( )); } window::Action::ChangeIcon(icon) => { - windows.with_raw(id).set_window_icon(conversion::icon(icon)) + windows + .with_raw(id) + .set_window_icon(conversion::icon(icon)); } window::Action::FetchMode(tag) => { let window = windows.with_raw(id); @@ -969,12 +971,14 @@ pub fn run_command<A, C, E>( .with_raw(id) .set_window_level(conversion::window_level(level)); } - window::Action::FetchId(tag) => proxy - .send_event(Event::Application(tag(windows - .with_raw(id) - .id() - .into()))) - .expect("Event loop doesn't exist."), + window::Action::FetchId(tag) => { + proxy + .send_event(Event::Application(tag(windows + .with_raw(id) + .id() + .into()))) + .expect("Event loop doesn't exist."); + } window::Action::Screenshot(tag) => { let i = windows.index_from_id(id); let state = &windows.states[i]; @@ -996,7 +1000,7 @@ pub fn run_command<A, C, E>( state.physical_size(), ), ))) - .expect("Event loop doesn't exist.") + .expect("Event loop doesn't exist."); } }, command::Action::System(action) => match action { @@ -1014,7 +1018,7 @@ pub fn run_command<A, C, E>( proxy .send_event(Event::Application(message)) - .expect("Event loop doesn't exist.") + .expect("Event loop doesn't exist."); }); } } diff --git a/winit/src/multi_window/windows.rs b/winit/src/multi_window/windows.rs index 6846abb364..a4841a4510 100644 --- a/winit/src/multi_window/windows.rs +++ b/winit/src/multi_window/windows.rs @@ -1,10 +1,12 @@ use crate::core::{window, Size}; +use crate::graphics::Compositor; use crate::multi_window::{Application, State}; -use iced_graphics::Compositor; -use iced_style::application::StyleSheet; -use std::fmt::{Debug, Formatter}; +use crate::style::application::StyleSheet; + use winit::monitor::MonitorHandle; +use std::fmt::{Debug, Formatter}; + pub struct Windows<A: Application, C: Compositor> where <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, @@ -33,7 +35,7 @@ where &self .raw .iter() - .map(|raw| raw.id()) + .map(winit::window::Window::id) .collect::<Vec<winit::window::WindowId>>(), ) .field("states", &self.states) @@ -131,7 +133,9 @@ where } pub fn last_monitor(&self) -> Option<MonitorHandle> { - self.raw.last().and_then(|w| w.current_monitor()) + self.raw + .last() + .and_then(winit::window::Window::current_monitor) } pub fn last(&self) -> usize { From 6740c2c5d6b24399dab1343abdfec5daf4b03c98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Wed, 29 Nov 2023 22:46:47 +0100 Subject: [PATCH 56/66] Fix broken intra-doc links --- graphics/src/compositor.rs | 2 +- runtime/src/multi_window/state.rs | 2 +- runtime/src/window/action.rs | 2 +- src/multi_window/application.rs | 2 ++ winit/src/conversion.rs | 2 +- winit/src/multi_window.rs | 23 ++++------------------- winit/src/multi_window/state.rs | 4 +--- winit/src/settings.rs | 2 +- 8 files changed, 12 insertions(+), 27 deletions(-) diff --git a/graphics/src/compositor.rs b/graphics/src/compositor.rs index e0b1e20f1b..78731a982b 100644 --- a/graphics/src/compositor.rs +++ b/graphics/src/compositor.rs @@ -24,7 +24,7 @@ pub trait Compositor: Sized { compatible_window: Option<&W>, ) -> Result<(Self, Self::Renderer), Error>; - /// Creates a [`Renderer`] for the [`Compositor`]. + /// Creates a [`Self::Renderer`] for the [`Compositor`]. fn renderer(&self) -> Self::Renderer; /// Crates a new [`Surface`] for the given window. diff --git a/runtime/src/multi_window/state.rs b/runtime/src/multi_window/state.rs index 05036a0711..49f72c3971 100644 --- a/runtime/src/multi_window/state.rs +++ b/runtime/src/multi_window/state.rs @@ -201,7 +201,7 @@ where (uncaptured_events, commands) } - /// Applies [`widget::Operation`]s to the [`State`] + /// Applies widget [`Operation`]s to the [`State`]. pub fn operate( &mut self, renderer: &mut P::Renderer, diff --git a/runtime/src/window/action.rs b/runtime/src/window/action.rs index d631cee108..2a31bbd617 100644 --- a/runtime/src/window/action.rs +++ b/runtime/src/window/action.rs @@ -17,7 +17,7 @@ pub enum Action<T> { Drag, /// Spawns a new window. Spawn { - /// The settings of the [`Window`]. + /// The settings of the window. settings: Settings, }, /// Resize the window. diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index 0486159e6f..b6f151491e 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -62,6 +62,8 @@ pub use crate::style::application::{Appearance, StyleSheet}; /// } /// } /// ``` +/// +/// [`Sandbox`]: crate::Sandbox pub trait Application: Sized { /// The [`Executor`] that will run commands and subscriptions. /// diff --git a/winit/src/conversion.rs b/winit/src/conversion.rs index 22e6b9be51..68c2b905ae 100644 --- a/winit/src/conversion.rs +++ b/winit/src/conversion.rs @@ -272,7 +272,7 @@ pub fn window_level(level: window::Level) -> winit::window::WindowLevel { } } -/// Converts a [`Position`] to a [`winit`] logical position for a given monitor. +/// Converts a [`window::Position`] to a [`winit`] logical position for a given monitor. /// /// [`winit`]: https://github.com/rust-windowing/winit pub fn position( diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index b233564abc..0e08a081b7 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -23,34 +23,19 @@ use std::mem::ManuallyDrop; use std::time::Instant; use winit::monitor::MonitorHandle; -/// This is a wrapper around the `Application::Message` associate type -/// to allows the `shell` to create internal messages, while still having -/// the current user-specified custom messages. #[derive(Debug)] -pub enum Event<Message> { - /// An internal event which contains an [`Application`] generated message. +enum Event<Message> { Application(Message), - /// An internal event which spawns a new window. NewWindow { - /// The [window::Id] of the newly spawned [`Window`]. id: window::Id, - /// The [settings::Window] of the newly spawned [`Window`]. settings: window::Settings, - /// The title of the newly spawned [`Window`]. title: String, - /// The monitor on which to spawn the window. If `None`, will use monitor of the last window - /// spawned. monitor: Option<MonitorHandle>, }, - /// An internal event for closing a window. CloseWindow(window::Id), - /// An internal event for when the window has finished being created. WindowCreated { - /// The internal ID of the window. id: window::Id, - /// The raw window. window: winit::window::Window, - /// Whether or not the window should close when a user requests it does. exit_on_close_request: bool, }, } @@ -771,7 +756,7 @@ async fn run_instance<A, E, C>( } /// Builds a window's [`UserInterface`] for the [`Application`]. -pub fn build_user_interface<'a, A: Application>( +fn build_user_interface<'a, A: Application>( application: &'a A, cache: user_interface::Cache, renderer: &mut A::Renderer, @@ -795,7 +780,7 @@ where /// Updates a multi-window [`Application`] by feeding it messages, spawning any /// resulting [`Command`], and tracking its [`Subscription`]. -pub fn update<A: Application, C, E: Executor>( +fn update<A: Application, C, E: Executor>( application: &mut A, compositor: &mut C, runtime: &mut Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>, @@ -834,7 +819,7 @@ pub fn update<A: Application, C, E: Executor>( } /// Runs the actions of a [`Command`]. -pub fn run_command<A, C, E>( +fn run_command<A, C, E>( application: &A, compositor: &mut C, command: Command<A::Message>, diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index f2741c3c12..e9a9f91a62 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -200,9 +200,7 @@ where /// window. /// /// Normally, an [`Application`] should be synchronized with its [`State`] - /// and window after calling [`Application::update`]. - /// - /// [`Application::update`]: crate::Program::update + /// and window after calling [`State::update`]. pub fn synchronize( &mut self, application: &A, diff --git a/winit/src/settings.rs b/winit/src/settings.rs index dc0f65a50b..2e541128b5 100644 --- a/winit/src/settings.rs +++ b/winit/src/settings.rs @@ -12,7 +12,7 @@ pub struct Settings<Flags> { /// communicate with it through the windowing system. pub id: Option<String>, - /// The [`Window`] settings. + /// The [`window::Settings`]. pub window: window::Settings, /// The data needed to initialize an [`Application`]. From 8c4e7d80a1ba128864ee82770a4670b8dbba619a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Wed, 29 Nov 2023 22:47:46 +0100 Subject: [PATCH 57/66] Fix `renderer` method in `iced_renderer::Compositor` --- renderer/src/compositor.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/renderer/src/compositor.rs b/renderer/src/compositor.rs index 5fc5a45965..5bec1639f7 100644 --- a/renderer/src/compositor.rs +++ b/renderer/src/compositor.rs @@ -55,10 +55,6 @@ impl<Theme> crate::graphics::Compositor for Compositor<Theme> { Compositor::Wgpu(compositor) => { Renderer::Wgpu(compositor.renderer()) } - #[cfg(not(feature = "wgpu"))] - Self::Wgpu => { - panic!("`wgpu` feature was not enabled in `iced_renderer`") - } } } From ac12d2d099d9ae996d0ccfdc7e5b82d9cef990ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Wed, 29 Nov 2023 22:50:35 +0100 Subject: [PATCH 58/66] Remove unnecessary unsafe `Send` marker in `iced_winit` --- winit/src/multi_window.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 0e08a081b7..ef142c771d 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -40,9 +40,6 @@ enum Event<Message> { }, } -#[allow(unsafe_code)] -unsafe impl<Message> std::marker::Send for Event<Message> {} - /// An interactive, native, cross-platform, multi-windowed application. /// /// This trait is the main entrypoint of multi-window Iced. Once implemented, you can run From 3b39ba7029832cab5235fb5538b46148d599daa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Wed, 29 Nov 2023 22:52:46 +0100 Subject: [PATCH 59/66] Fix unused import in `multi_window::application` --- src/multi_window/application.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/multi_window/application.rs b/src/multi_window/application.rs index b6f151491e..4a91bdf4f1 100644 --- a/src/multi_window/application.rs +++ b/src/multi_window/application.rs @@ -1,8 +1,7 @@ +use crate::style::application::StyleSheet; use crate::window; use crate::{Command, Element, Executor, Settings, Subscription}; -pub use crate::style::application::{Appearance, StyleSheet}; - /// An interactive cross-platform multi-window application. /// /// This trait is the main entrypoint of Iced. Once implemented, you can run From d34bc4e4a251bb28854770575d379d4a53f2db12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Wed, 29 Nov 2023 23:55:17 +0100 Subject: [PATCH 60/66] Refactor event loop <-> instance communication in `multi_window` --- winit/src/multi_window.rs | 871 ++++++++++++++++++++------------------ 1 file changed, 452 insertions(+), 419 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index ef142c771d..f4ebbe091a 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -8,7 +8,7 @@ use crate::conversion; use crate::core::widget::operation; use crate::core::{self, mouse, renderer, window, Size}; use crate::futures::futures::channel::mpsc; -use crate::futures::futures::{task, Future, FutureExt, StreamExt}; +use crate::futures::futures::{task, Future, StreamExt}; use crate::futures::{Executor, Runtime, Subscription}; use crate::graphics::{compositor, Compositor}; use crate::multi_window::windows::Windows; @@ -21,23 +21,24 @@ use crate::{Clipboard, Error, Proxy, Settings}; use std::mem::ManuallyDrop; use std::time::Instant; -use winit::monitor::MonitorHandle; -#[derive(Debug)] -enum Event<Message> { - Application(Message), - NewWindow { - id: window::Id, - settings: window::Settings, - title: String, - monitor: Option<MonitorHandle>, - }, - CloseWindow(window::Id), +enum Event<Message: 'static> { WindowCreated { id: window::Id, window: winit::window::Window, exit_on_close_request: bool, }, + EventLoopAwakened(winit::event::Event<'static, Message>), +} + +enum Control { + ChangeFlow(winit::event_loop::ControlFlow), + CreateWindow { + id: window::Id, + settings: window::Settings, + title: String, + monitor: Option<winit::monitor::MonitorHandle>, + }, } /// An interactive, native, cross-platform, multi-windowed application. @@ -243,44 +244,57 @@ where event: winit::event::WindowEvent::Resized(*new_inner_size), window_id, }), - winit::event::Event::UserEvent(Event::NewWindow { - id, - settings, - title, - monitor, - }) => { - let exit_on_close_request = settings.exit_on_close_request; - - let window = conversion::window_settings( - settings, &title, monitor, None, - ) - .build(window_target) - .expect("Failed to build window"); - - Some(winit::event::Event::UserEvent(Event::WindowCreated { - id, - window, - exit_on_close_request, - })) - } _ => event.to_static(), }; if let Some(event) = event { - event_sender.start_send(event).expect("Send event"); - - let poll = instance.as_mut().poll(&mut context); - - match poll { - task::Poll::Pending => { - if let Ok(Some(flow)) = control_receiver.try_next() { - *control_flow = flow; + event_sender + .start_send(Event::EventLoopAwakened(event)) + .expect("Send event"); + + loop { + let poll = instance.as_mut().poll(&mut context); + + match poll { + task::Poll::Pending => match control_receiver.try_next() { + Ok(Some(control)) => match control { + Control::ChangeFlow(flow) => { + *control_flow = flow; + } + Control::CreateWindow { + id, + settings, + title, + monitor, + } => { + let exit_on_close_request = + settings.exit_on_close_request; + + let window = conversion::window_settings( + settings, &title, monitor, None, + ) + .build(window_target) + .expect("Failed to build window"); + + event_sender + .start_send(Event::WindowCreated { + id, + window, + exit_on_close_request, + }) + .expect("Send event"); + } + }, + _ => { + break; + } + }, + task::Poll::Ready(_) => { + *control_flow = ControlFlow::Exit; + break; } - } - task::Poll::Ready(_) => { - *control_flow = ControlFlow::Exit; - } - }; + }; + } } }) } @@ -288,13 +302,11 @@ where async fn run_instance<A, E, C>( mut application: A, mut compositor: C, - mut runtime: Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>, - mut proxy: winit::event_loop::EventLoopProxy<Event<A::Message>>, + mut runtime: Runtime<E, Proxy<A::Message>, A::Message>, + mut proxy: winit::event_loop::EventLoopProxy<A::Message>, mut debug: Debug, - mut event_receiver: mpsc::UnboundedReceiver< - winit::event::Event<'_, Event<A::Message>>, - >, - mut control_sender: mpsc::UnboundedSender<winit::event_loop::ControlFlow>, + mut event_receiver: mpsc::UnboundedReceiver<Event<A::Message>>, + mut control_sender: mpsc::UnboundedSender<Control>, init_command: Command<A::Message>, mut windows: Windows<A, C>, should_main_window_be_visible: bool, @@ -327,18 +339,14 @@ async fn run_instance<A, E, C>( init_command, &mut runtime, &mut clipboard, + &mut control_sender, &mut proxy, &mut debug, &mut windows, &mut ui_caches, ); - runtime.track( - application - .subscription() - .map(Event::Application) - .into_recipes(), - ); + runtime.track(application.subscription().into_recipes()); let mut mouse_interaction = mouse::Interaction::default(); @@ -361,391 +369,409 @@ async fn run_instance<A, E, C>( 'main: while let Some(event) = event_receiver.next().await { match event { - event::Event::NewEvents(start_cause) => { - redraw_pending = matches!( - start_cause, - event::StartCause::Init - | event::StartCause::Poll - | event::StartCause::ResumeTimeReached { .. } - ); - } - event::Event::MainEventsCleared => { - debug.event_processing_started(); - let mut uis_stale = false; - - for (i, id) in windows.ids.iter().enumerate() { - let mut window_events = vec![]; - - events.retain(|(window_id, event)| { - if *window_id == Some(*id) || window_id.is_none() { - window_events.push(event.clone()); - false - } else { - true - } - }); - - if !redraw_pending - && window_events.is_empty() - && messages.is_empty() - { - continue; - } + Event::WindowCreated { + id, + window, + exit_on_close_request, + } => { + let bounds = logical_bounds_of(&window); - let (ui_state, statuses) = user_interfaces[i].update( - &window_events, - windows.states[i].cursor(), - &mut windows.renderers[i], - &mut clipboard, - &mut messages, - ); + let (inner_size, i) = windows.add( + &application, + &mut compositor, + id, + window, + exit_on_close_request, + ); - if !uis_stale { - uis_stale = - matches!(ui_state, user_interface::State::Outdated); - } + user_interfaces.push(build_user_interface( + &application, + user_interface::Cache::default(), + &mut windows.renderers[i], + inner_size, + &mut debug, + id, + )); + ui_caches.push(user_interface::Cache::default()); - for (event, status) in - window_events.into_iter().zip(statuses.into_iter()) - { - runtime.broadcast(event, status); - } + if let Some(bounds) = bounds { + events.push(( + Some(id), + core::Event::Window( + id, + window::Event::Created { + position: bounds.0, + size: bounds.1, + }, + ), + )); } - - debug.event_processing_finished(); - - // TODO mw application update returns which window IDs to update - if !messages.is_empty() || uis_stale { - let mut cached_interfaces: Vec<user_interface::Cache> = - ManuallyDrop::into_inner(user_interfaces) - .drain(..) - .map(UserInterface::into_cache) - .collect(); - - // Update application - update( - &mut application, - &mut compositor, - &mut runtime, - &mut clipboard, - &mut proxy, - &mut debug, - &mut messages, - &mut windows, - &mut cached_interfaces, - ); - - // we must synchronize all window states with application state after an - // application update since we don't know what changed - for (state, (id, window)) in windows - .states - .iter_mut() - .zip(windows.ids.iter().zip(windows.raw.iter())) - { - state.synchronize(&application, *id, window); + } + Event::EventLoopAwakened(event) => { + match event { + event::Event::NewEvents(start_cause) => { + redraw_pending = matches!( + start_cause, + event::StartCause::Init + | event::StartCause::Poll + | event::StartCause::ResumeTimeReached { .. } + ); } + event::Event::MainEventsCleared => { + debug.event_processing_started(); + let mut uis_stale = false; + + for (i, id) in windows.ids.iter().enumerate() { + let mut window_events = vec![]; + + events.retain(|(window_id, event)| { + if *window_id == Some(*id) + || window_id.is_none() + { + window_events.push(event.clone()); + false + } else { + true + } + }); + + if !redraw_pending + && window_events.is_empty() + && messages.is_empty() + { + continue; + } - // rebuild UIs with the synchronized states - user_interfaces = ManuallyDrop::new(build_user_interfaces( - &application, - &mut debug, - &mut windows, - cached_interfaces, - )); - } + let (ui_state, statuses) = user_interfaces[i] + .update( + &window_events, + windows.states[i].cursor(), + &mut windows.renderers[i], + &mut clipboard, + &mut messages, + ); + + if !uis_stale { + uis_stale = matches!( + ui_state, + user_interface::State::Outdated + ); + } - debug.draw_started(); - - for (i, id) in windows.ids.iter().enumerate() { - // TODO: Avoid redrawing all the time by forcing widgets to - // request redraws on state changes - // - // Then, we can use the `interface_state` here to decide if a redraw - // is needed right away, or simply wait until a specific time. - let redraw_event = core::Event::Window( - *id, - window::Event::RedrawRequested(Instant::now()), - ); + for (event, status) in window_events + .into_iter() + .zip(statuses.into_iter()) + { + runtime.broadcast(event, status); + } + } - let cursor = windows.states[i].cursor(); + debug.event_processing_finished(); + + // TODO mw application update returns which window IDs to update + if !messages.is_empty() || uis_stale { + let mut cached_interfaces: Vec< + user_interface::Cache, + > = ManuallyDrop::into_inner(user_interfaces) + .drain(..) + .map(UserInterface::into_cache) + .collect(); + + // Update application + update( + &mut application, + &mut compositor, + &mut runtime, + &mut clipboard, + &mut control_sender, + &mut proxy, + &mut debug, + &mut messages, + &mut windows, + &mut cached_interfaces, + ); - let (ui_state, _) = user_interfaces[i].update( - &[redraw_event.clone()], - cursor, - &mut windows.renderers[i], - &mut clipboard, - &mut messages, - ); + // we must synchronize all window states with application state after an + // application update since we don't know what changed + for (state, (id, window)) in windows + .states + .iter_mut() + .zip(windows.ids.iter().zip(windows.raw.iter())) + { + state.synchronize(&application, *id, window); + } - let new_mouse_interaction = { - let state = &windows.states[i]; + // rebuild UIs with the synchronized states + user_interfaces = + ManuallyDrop::new(build_user_interfaces( + &application, + &mut debug, + &mut windows, + cached_interfaces, + )); + } - user_interfaces[i].draw( - &mut windows.renderers[i], - state.theme(), - &renderer::Style { - text_color: state.text_color(), - }, - cursor, - ) - }; + debug.draw_started(); + + for (i, id) in windows.ids.iter().enumerate() { + // TODO: Avoid redrawing all the time by forcing widgets to + // request redraws on state changes + // + // Then, we can use the `interface_state` here to decide if a redraw + // is needed right away, or simply wait until a specific time. + let redraw_event = core::Event::Window( + *id, + window::Event::RedrawRequested(Instant::now()), + ); - if new_mouse_interaction != mouse_interaction { - windows.raw[i].set_cursor_icon( - conversion::mouse_interaction( - new_mouse_interaction, - ), - ); + let cursor = windows.states[i].cursor(); - mouse_interaction = new_mouse_interaction; - } + let (ui_state, _) = user_interfaces[i].update( + &[redraw_event.clone()], + cursor, + &mut windows.renderers[i], + &mut clipboard, + &mut messages, + ); - // TODO once widgets can request to be redrawn, we can avoid always requesting a - // redraw - windows.raw[i].request_redraw(); + let new_mouse_interaction = { + let state = &windows.states[i]; + + user_interfaces[i].draw( + &mut windows.renderers[i], + state.theme(), + &renderer::Style { + text_color: state.text_color(), + }, + cursor, + ) + }; + + if new_mouse_interaction != mouse_interaction { + windows.raw[i].set_cursor_icon( + conversion::mouse_interaction( + new_mouse_interaction, + ), + ); + + mouse_interaction = new_mouse_interaction; + } - runtime.broadcast( - redraw_event.clone(), - core::event::Status::Ignored, - ); + // TODO once widgets can request to be redrawn, we can avoid always requesting a + // redraw + windows.raw[i].request_redraw(); - let _ = control_sender.start_send(match ui_state { - user_interface::State::Updated { - redraw_request: Some(redraw_request), - } => match redraw_request { - window::RedrawRequest::NextFrame => { - ControlFlow::Poll - } - window::RedrawRequest::At(at) => { - ControlFlow::WaitUntil(at) - } - }, - _ => ControlFlow::Wait, - }); - } + runtime.broadcast( + redraw_event.clone(), + core::event::Status::Ignored, + ); - redraw_pending = false; + let _ = control_sender.start_send( + Control::ChangeFlow(match ui_state { + user_interface::State::Updated { + redraw_request: Some(redraw_request), + } => match redraw_request { + window::RedrawRequest::NextFrame => { + ControlFlow::Poll + } + window::RedrawRequest::At(at) => { + ControlFlow::WaitUntil(at) + } + }, + _ => ControlFlow::Wait, + }), + ); + } - debug.draw_finished(); - } - event::Event::PlatformSpecific(event::PlatformSpecific::MacOS( - event::MacOS::ReceivedUrl(url), - )) => { - use crate::core::event; + redraw_pending = false; - events.push(( - None, + debug.draw_finished(); + } event::Event::PlatformSpecific( event::PlatformSpecific::MacOS( event::MacOS::ReceivedUrl(url), ), - ), - )); - } - event::Event::UserEvent(event) => match event { - Event::Application(message) => { - messages.push(message); - } - Event::WindowCreated { - id, - window, - exit_on_close_request, - } => { - let bounds = logical_bounds_of(&window); - - let (inner_size, i) = windows.add( - &application, - &mut compositor, - id, - window, - exit_on_close_request, - ); + ) => { + use crate::core::event; - user_interfaces.push(build_user_interface( - &application, - user_interface::Cache::default(), - &mut windows.renderers[i], - inner_size, - &mut debug, - id, - )); - ui_caches.push(user_interface::Cache::default()); - - if let Some(bounds) = bounds { events.push(( - Some(id), - core::Event::Window( - id, - window::Event::Created { - position: bounds.0, - size: bounds.1, - }, + None, + event::Event::PlatformSpecific( + event::PlatformSpecific::MacOS( + event::MacOS::ReceivedUrl(url), + ), ), )); } - } - Event::CloseWindow(id) => { - let i = windows.delete(id); - let _ = user_interfaces.remove(i); - let _ = ui_caches.remove(i); - - if windows.is_empty() { - break 'main; + event::Event::UserEvent(message) => { + messages.push(message); } - } - Event::NewWindow { .. } => unreachable!(), - }, - event::Event::RedrawRequested(id) => { - let i = windows.index_from_raw(id); - let state = &windows.states[i]; - let physical_size = state.physical_size(); - - if physical_size.width == 0 || physical_size.height == 0 { - continue; - } - - debug.render_started(); - let current_viewport_version = state.viewport_version(); - let window_viewport_version = windows.viewport_versions[i]; + event::Event::RedrawRequested(id) => { + let i = windows.index_from_raw(id); + let state = &windows.states[i]; + let physical_size = state.physical_size(); - if window_viewport_version != current_viewport_version { - let logical_size = state.logical_size(); + if physical_size.width == 0 || physical_size.height == 0 + { + continue; + } - debug.layout_started(); + debug.render_started(); + let current_viewport_version = state.viewport_version(); + let window_viewport_version = + windows.viewport_versions[i]; - let renderer = &mut windows.renderers[i]; - let ui = user_interfaces.remove(i); + if window_viewport_version != current_viewport_version { + let logical_size = state.logical_size(); - user_interfaces - .insert(i, ui.relayout(logical_size, renderer)); + debug.layout_started(); - debug.layout_finished(); + let renderer = &mut windows.renderers[i]; + let ui = user_interfaces.remove(i); - debug.draw_started(); - let new_mouse_interaction = user_interfaces[i].draw( - renderer, - state.theme(), - &renderer::Style { - text_color: state.text_color(), - }, - state.cursor(), - ); + user_interfaces + .insert(i, ui.relayout(logical_size, renderer)); - if new_mouse_interaction != mouse_interaction { - windows.raw[i].set_cursor_icon( - conversion::mouse_interaction( - new_mouse_interaction, - ), - ); + debug.layout_finished(); - mouse_interaction = new_mouse_interaction; - } - debug.draw_finished(); + debug.draw_started(); + let new_mouse_interaction = user_interfaces[i] + .draw( + renderer, + state.theme(), + &renderer::Style { + text_color: state.text_color(), + }, + state.cursor(), + ); - compositor.configure_surface( - &mut windows.surfaces[i], - physical_size.width, - physical_size.height, - ); + if new_mouse_interaction != mouse_interaction { + windows.raw[i].set_cursor_icon( + conversion::mouse_interaction( + new_mouse_interaction, + ), + ); - windows.viewport_versions[i] = current_viewport_version; - } + mouse_interaction = new_mouse_interaction; + } + debug.draw_finished(); - match compositor.present( - &mut windows.renderers[i], - &mut windows.surfaces[i], - state.viewport(), - state.background_color(), - &debug.overlay(), - ) { - Ok(()) => { - debug.render_finished(); - - // TODO: Handle animations! - // Maybe we can use `ControlFlow::WaitUntil` for this. - } - Err(error) => match error { - // This is an unrecoverable error. - compositor::SurfaceError::OutOfMemory => { - panic!("{:?}", error); - } - _ => { - debug.render_finished(); - log::error!( - "Error {error:?} when presenting surface." + compositor.configure_surface( + &mut windows.surfaces[i], + physical_size.width, + physical_size.height, ); - // Try rendering all windows again next frame. - for window in &windows.raw { - window.request_redraw(); - } + windows.viewport_versions[i] = + current_viewport_version; } - }, - } - } - event::Event::WindowEvent { - event: window_event, - window_id, - } => { - let window_index = - windows.raw.iter().position(|w| w.id() == window_id); - - match window_index { - Some(i) => { - let id = windows.ids[i]; - let raw = &windows.raw[i]; - let exit_on_close_request = - windows.exit_on_close_requested[i]; - - if matches!( - window_event, - winit::event::WindowEvent::CloseRequested - ) && exit_on_close_request - { - let i = windows.delete(id); - let _ = user_interfaces.remove(i); - let _ = ui_caches.remove(i); - if windows.is_empty() { - break 'main; - } - } else { - let state = &mut windows.states[i]; - state.update(raw, &window_event, &mut debug); + match compositor.present( + &mut windows.renderers[i], + &mut windows.surfaces[i], + state.viewport(), + state.background_color(), + &debug.overlay(), + ) { + Ok(()) => { + debug.render_finished(); - if let Some(event) = conversion::window_event( - id, - &window_event, - state.scale_factor(), - state.modifiers(), - ) { - events.push((Some(id), event)); + // TODO: Handle animations! + // Maybe we can use `ControlFlow::WaitUntil` for this. } + Err(error) => match error { + // This is an unrecoverable error. + compositor::SurfaceError::OutOfMemory => { + panic!("{:?}", error); + } + _ => { + debug.render_finished(); + log::error!( + "Error {error:?} when presenting surface." + ); + + // Try rendering all windows again next frame. + for window in &windows.raw { + window.request_redraw(); + } + } + }, } } - None => { - // This is the only special case, since in order to trigger the Destroyed event the - // window reference from winit must be dropped, but we still want to inform the - // user that the window was destroyed so they can clean up any specific window - // code for this window - if matches!( - window_event, - winit::event::WindowEvent::Destroyed - ) { - let id = windows.get_pending_destroy(window_id); - - events.push(( - None, - core::Event::Window( - id, - window::Event::Destroyed, - ), - )); + event::Event::WindowEvent { + event: window_event, + window_id, + } => { + let window_index = windows + .raw + .iter() + .position(|w| w.id() == window_id); + + match window_index { + Some(i) => { + let id = windows.ids[i]; + let raw = &windows.raw[i]; + let exit_on_close_request = + windows.exit_on_close_requested[i]; + + if matches!( + window_event, + winit::event::WindowEvent::CloseRequested + ) && exit_on_close_request + { + let i = windows.delete(id); + let _ = user_interfaces.remove(i); + let _ = ui_caches.remove(i); + + if windows.is_empty() { + break 'main; + } + } else { + let state = &mut windows.states[i]; + state.update( + raw, + &window_event, + &mut debug, + ); + + if let Some(event) = + conversion::window_event( + id, + &window_event, + state.scale_factor(), + state.modifiers(), + ) + { + events.push((Some(id), event)); + } + } + } + None => { + // This is the only special case, since in order to trigger the Destroyed event the + // window reference from winit must be dropped, but we still want to inform the + // user that the window was destroyed so they can clean up any specific window + // code for this window + if matches!( + window_event, + winit::event::WindowEvent::Destroyed + ) { + let id = + windows.get_pending_destroy(window_id); + + events.push(( + None, + core::Event::Window( + id, + window::Event::Destroyed, + ), + )); + } + } } } + _ => {} } } - _ => {} } } @@ -780,9 +806,10 @@ where fn update<A: Application, C, E: Executor>( application: &mut A, compositor: &mut C, - runtime: &mut Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>, + runtime: &mut Runtime<E, Proxy<A::Message>, A::Message>, clipboard: &mut Clipboard, - proxy: &mut winit::event_loop::EventLoopProxy<Event<A::Message>>, + control_sender: &mut mpsc::UnboundedSender<Control>, + proxy: &mut winit::event_loop::EventLoopProxy<A::Message>, debug: &mut Debug, messages: &mut Vec<A::Message>, windows: &mut Windows<A, C>, @@ -804,6 +831,7 @@ fn update<A: Application, C, E: Executor>( command, runtime, clipboard, + control_sender, proxy, debug, windows, @@ -811,7 +839,7 @@ fn update<A: Application, C, E: Executor>( ); } - let subscription = application.subscription().map(Event::Application); + let subscription = application.subscription(); runtime.track(subscription.into_recipes()); } @@ -820,9 +848,10 @@ fn run_command<A, C, E>( application: &A, compositor: &mut C, command: Command<A::Message>, - runtime: &mut Runtime<E, Proxy<Event<A::Message>>, Event<A::Message>>, + runtime: &mut Runtime<E, Proxy<A::Message>, A::Message>, clipboard: &mut Clipboard, - proxy: &mut winit::event_loop::EventLoopProxy<Event<A::Message>>, + control_sender: &mut mpsc::UnboundedSender<Control>, + proxy: &mut winit::event_loop::EventLoopProxy<A::Message>, debug: &mut Debug, windows: &mut Windows<A, C>, ui_caches: &mut Vec<user_interface::Cache>, @@ -839,17 +868,17 @@ fn run_command<A, C, E>( for action in command.actions() { match action { command::Action::Future(future) => { - runtime.spawn(Box::pin(future.map(Event::Application))); + runtime.spawn(Box::pin(future)); } command::Action::Stream(stream) => { - runtime.run(Box::pin(stream.map(Event::Application))); + runtime.run(Box::pin(stream)); } command::Action::Clipboard(action) => match action { clipboard::Action::Read(tag) => { let message = tag(clipboard.read()); proxy - .send_event(Event::Application(message)) + .send_event(message) .expect("Send message to event loop"); } clipboard::Action::Write(contents) => { @@ -860,19 +889,28 @@ fn run_command<A, C, E>( window::Action::Spawn { settings } => { let monitor = windows.last_monitor(); - proxy - .send_event(Event::NewWindow { + control_sender + .start_send(Control::CreateWindow { id, settings, title: application.title(id), monitor, }) - .expect("Send message to event loop"); + .expect("Send control action"); } window::Action::Close => { - proxy - .send_event(Event::CloseWindow(id)) - .expect("Send message to event loop"); + use winit::event_loop::ControlFlow; + + let i = windows.delete(id); + let _ = ui_caches.remove(i); + + if windows.is_empty() { + control_sender + .start_send(Control::ChangeFlow( + ControlFlow::ExitWithCode(0), + )) + .expect("Send control action"); + } } window::Action::Drag => { let _ = windows.with_raw(id).drag_window(); @@ -890,10 +928,10 @@ fn run_command<A, C, E>( let size = window.inner_size(); proxy - .send_event(Event::Application(callback(Size::new( + .send_event(callback(Size::new( size.width, size.height, - )))) + ))) .expect("Send message to event loop"); } window::Action::Maximize(maximized) => { @@ -929,7 +967,7 @@ fn run_command<A, C, E>( }; proxy - .send_event(Event::Application(tag(mode))) + .send_event(tag(mode)) .expect("Event loop doesn't exist."); } window::Action::ToggleMaximize => { @@ -955,10 +993,7 @@ fn run_command<A, C, E>( } window::Action::FetchId(tag) => { proxy - .send_event(Event::Application(tag(windows - .with_raw(id) - .id() - .into()))) + .send_event(tag(windows.with_raw(id).id().into())) .expect("Event loop doesn't exist."); } window::Action::Screenshot(tag) => { @@ -976,11 +1011,9 @@ fn run_command<A, C, E>( ); proxy - .send_event(Event::Application(tag( - window::Screenshot::new( - bytes, - state.physical_size(), - ), + .send_event(tag(window::Screenshot::new( + bytes, + state.physical_size(), ))) .expect("Event loop doesn't exist."); } @@ -999,7 +1032,7 @@ fn run_command<A, C, E>( let message = _tag(information); proxy - .send_event(Event::Application(message)) + .send_event(message) .expect("Event loop doesn't exist."); }); } @@ -1025,7 +1058,7 @@ fn run_command<A, C, E>( operation::Outcome::None => {} operation::Outcome::Some(message) => { proxy - .send_event(Event::Application(message)) + .send_event(message) .expect("Event loop doesn't exist."); // operation completed, don't need to try to operate on rest of UIs @@ -1051,7 +1084,7 @@ fn run_command<A, C, E>( } proxy - .send_event(Event::Application(tagger(Ok(())))) + .send_event(tagger(Ok(()))) .expect("Send message to event loop"); } } From 9f29aec128ccf51c620a8b69a9fbd64186ab8c65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Thu, 30 Nov 2023 00:01:32 +0100 Subject: [PATCH 61/66] Move `Event` and `Control` types after `multi_window::run` --- winit/src/multi_window.rs | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index f4ebbe091a..f8cedcb831 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -22,25 +22,6 @@ use crate::{Clipboard, Error, Proxy, Settings}; use std::mem::ManuallyDrop; use std::time::Instant; -enum Event<Message: 'static> { - WindowCreated { - id: window::Id, - window: winit::window::Window, - exit_on_close_request: bool, - }, - EventLoopAwakened(winit::event::Event<'static, Message>), -} - -enum Control { - ChangeFlow(winit::event_loop::ControlFlow), - CreateWindow { - id: window::Id, - settings: window::Settings, - title: String, - monitor: Option<winit::monitor::MonitorHandle>, - }, -} - /// An interactive, native, cross-platform, multi-windowed application. /// /// This trait is the main entrypoint of multi-window Iced. Once implemented, you can run @@ -299,6 +280,25 @@ where }) } +enum Event<Message: 'static> { + WindowCreated { + id: window::Id, + window: winit::window::Window, + exit_on_close_request: bool, + }, + EventLoopAwakened(winit::event::Event<'static, Message>), +} + +enum Control { + ChangeFlow(winit::event_loop::ControlFlow), + CreateWindow { + id: window::Id, + settings: window::Settings, + title: String, + monitor: Option<winit::monitor::MonitorHandle>, + }, +} + async fn run_instance<A, E, C>( mut application: A, mut compositor: C, From 67408311f45d341509538f8cc185978da66b6ace Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Thu, 30 Nov 2023 23:40:33 +0100 Subject: [PATCH 62/66] Use actual floats for logical coordinates --- core/src/point.rs | 58 ++++++++++++++------ core/src/window/event.rs | 18 +++---- core/src/window/position.rs | 6 ++- core/src/window/settings.rs | 11 ++-- examples/multi_window/src/main.rs | 15 +++--- examples/solar_system/src/main.rs | 14 ++--- examples/todos/src/main.rs | 4 +- runtime/src/window.rs | 13 ++--- runtime/src/window/action.rs | 25 ++++----- winit/src/application.rs | 9 ++-- winit/src/conversion.rs | 39 ++++++++------ winit/src/multi_window.rs | 89 ++++++++++++++++--------------- 12 files changed, 165 insertions(+), 136 deletions(-) diff --git a/core/src/point.rs b/core/src/point.rs index 9bf7726b8e..ef42852f1b 100644 --- a/core/src/point.rs +++ b/core/src/point.rs @@ -1,26 +1,34 @@ use crate::Vector; +use num_traits::{Float, Num}; +use std::fmt; + /// A 2D point. -#[derive(Debug, Clone, Copy, PartialEq, Default)] -pub struct Point { +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Point<T = f32> { /// The X coordinate. - pub x: f32, + pub x: T, /// The Y coordinate. - pub y: f32, + pub y: T, } impl Point { /// The origin (i.e. a [`Point`] at (0, 0)). - pub const ORIGIN: Point = Point::new(0.0, 0.0); + pub const ORIGIN: Self = Self::new(0.0, 0.0); +} +impl<T: Num> Point<T> { /// Creates a new [`Point`] with the given coordinates. - pub const fn new(x: f32, y: f32) -> Self { + pub const fn new(x: T, y: T) -> Self { Self { x, y } } /// Computes the distance to another [`Point`]. - pub fn distance(&self, to: Point) -> f32 { + pub fn distance(&self, to: Self) -> T + where + T: Float, + { let a = self.x - to.x; let b = self.y - to.y; @@ -34,9 +42,9 @@ impl From<[f32; 2]> for Point { } } -impl From<[u16; 2]> for Point { +impl From<[u16; 2]> for Point<u16> { fn from([x, y]: [u16; 2]) -> Self { - Point::new(x.into(), y.into()) + Point::new(x, y) } } @@ -46,10 +54,13 @@ impl From<Point> for [f32; 2] { } } -impl std::ops::Add<Vector> for Point { +impl<T> std::ops::Add<Vector<T>> for Point<T> +where + T: std::ops::Add<Output = T>, +{ type Output = Self; - fn add(self, vector: Vector) -> Self { + fn add(self, vector: Vector<T>) -> Self { Self { x: self.x + vector.x, y: self.y + vector.y, @@ -57,10 +68,13 @@ impl std::ops::Add<Vector> for Point { } } -impl std::ops::Sub<Vector> for Point { +impl<T> std::ops::Sub<Vector<T>> for Point<T> +where + T: std::ops::Sub<Output = T>, +{ type Output = Self; - fn sub(self, vector: Vector) -> Self { + fn sub(self, vector: Vector<T>) -> Self { Self { x: self.x - vector.x, y: self.y - vector.y, @@ -68,10 +82,22 @@ impl std::ops::Sub<Vector> for Point { } } -impl std::ops::Sub<Point> for Point { - type Output = Vector; +impl<T> std::ops::Sub<Point<T>> for Point<T> +where + T: std::ops::Sub<Output = T>, +{ + type Output = Vector<T>; - fn sub(self, point: Point) -> Vector { + fn sub(self, point: Self) -> Vector<T> { Vector::new(self.x - point.x, self.y - point.y) } } + +impl<T> fmt::Display for Point<T> +where + T: fmt::Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y) + } +} diff --git a/core/src/window/event.rs b/core/src/window/event.rs index f7759435f1..3ab7cd810a 100644 --- a/core/src/window/event.rs +++ b/core/src/window/event.rs @@ -1,10 +1,10 @@ use crate::time::Instant; -use crate::Size; +use crate::{Point, Size}; use std::path::PathBuf; /// A window-related event. -#[derive(PartialEq, Eq, Clone, Debug)] +#[derive(PartialEq, Clone, Debug)] pub enum Event { /// A window was moved. Moved { @@ -30,22 +30,22 @@ pub enum Event { /// The user has requested for the window to close. CloseRequested, - /// A window was destroyed by the runtime. - Destroyed, - /// A window was created. - /// - /// **Note:** this event is not supported on Wayland. Created { /// The position of the created window. This is relative to the top-left corner of the desktop /// the window is on, including virtual desktops. Refers to window's "inner" position, /// or the client area, in logical pixels. - position: (i32, i32), + /// + /// **Note**: Not available in Wayland. + position: Option<Point>, /// The size of the created window. This is its "inner" size, or the size of the /// client area, in logical pixels. - size: Size<u32>, + size: Size, }, + /// A window was destroyed by the runtime. + Destroyed, + /// A window was focused. Focused, diff --git a/core/src/window/position.rs b/core/src/window/position.rs index c260c29eb1..73391e75eb 100644 --- a/core/src/window/position.rs +++ b/core/src/window/position.rs @@ -1,5 +1,7 @@ +use crate::Point; + /// The position of a window in a given screen. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq)] pub enum Position { /// The platform-specific default position for a new window. Default, @@ -12,7 +14,7 @@ pub enum Position { /// position. So if you have decorations enabled and want the window to be /// at (0, 0) you would have to set the position to /// `(PADDING_X, PADDING_Y)`. - Specific(i32, i32), + Specific(Point), } impl Default for Position { diff --git a/core/src/window/settings.rs b/core/src/window/settings.rs index 25df815908..fbbf86abd8 100644 --- a/core/src/window/settings.rs +++ b/core/src/window/settings.rs @@ -25,22 +25,23 @@ mod platform; mod platform; use crate::window::{Icon, Level, Position}; +use crate::Size; pub use platform::PlatformSpecific; /// The window settings of an application. #[derive(Debug, Clone)] pub struct Settings { - /// The initial size of the window. - pub size: (u32, u32), + /// The initial logical dimensions of the window. + pub size: Size, /// The initial position of the window. pub position: Position, /// The minimum size of the window. - pub min_size: Option<(u32, u32)>, + pub min_size: Option<Size>, /// The maximum size of the window. - pub max_size: Option<(u32, u32)>, + pub max_size: Option<Size>, /// Whether the window should be visible or not. pub visible: bool, @@ -77,7 +78,7 @@ pub struct Settings { impl Default for Settings { fn default() -> Self { Self { - size: (1024, 768), + size: Size::new(1024.0, 768.0), position: Position::default(), min_size: None, max_size: None, diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 7d1f1e9134..16beb46e24 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -4,8 +4,10 @@ use iced::multi_window::{self, Application}; use iced::widget::{button, column, container, scrollable, text, text_input}; use iced::window; use iced::{ - Alignment, Command, Element, Length, Settings, Subscription, Theme, + Alignment, Command, Element, Length, Point, Settings, Subscription, Theme, + Vector, }; + use std::collections::HashMap; fn main() -> iced::Result { @@ -33,8 +35,8 @@ enum Message { ScaleChanged(window::Id, String), TitleChanged(window::Id, String), CloseWindow(window::Id), + WindowCreated(window::Id, Option<Point>), WindowDestroyed(window::Id), - WindowCreated(window::Id, (i32, i32)), NewWindow, } @@ -90,10 +92,11 @@ impl multi_window::Application for Example { self.windows.remove(&id); } Message::WindowCreated(id, position) => { - self.next_window_pos = window::Position::Specific( - position.0 + 20, - position.1 + 20, - ); + if let Some(position) = position { + self.next_window_pos = window::Position::Specific( + position + Vector::new(20.0, 20.0), + ); + } if let Some(window) = self.windows.get(&id) { return text_input::focus(window.input_id.clone()); diff --git a/examples/solar_system/src/main.rs b/examples/solar_system/src/main.rs index 8295ddeded..82421a8684 100644 --- a/examples/solar_system/src/main.rs +++ b/examples/solar_system/src/main.rs @@ -114,14 +114,14 @@ impl State { pub fn new() -> State { let now = Instant::now(); - let (width, height) = window::Settings::default().size; + let size = window::Settings::default().size; State { space_cache: canvas::Cache::default(), system_cache: canvas::Cache::default(), start: now, now, - stars: Self::generate_stars(width, height), + stars: Self::generate_stars(size.width, size.height), } } @@ -130,7 +130,7 @@ impl State { self.system_cache.clear(); } - fn generate_stars(width: u32, height: u32) -> Vec<(Point, f32)> { + fn generate_stars(width: f32, height: f32) -> Vec<(Point, f32)> { use rand::Rng; let mut rng = rand::thread_rng(); @@ -139,12 +139,8 @@ impl State { .map(|_| { ( Point::new( - rng.gen_range( - (-(width as f32) / 2.0)..(width as f32 / 2.0), - ), - rng.gen_range( - (-(height as f32) / 2.0)..(height as f32 / 2.0), - ), + rng.gen_range((-width / 2.0)..(width / 2.0)), + rng.gen_range((-height / 2.0)..(height / 2.0)), ), rng.gen_range(0.5..1.0), ) diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index a7ba69b93e..4dac032c83 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -8,7 +8,7 @@ use iced::widget::{ }; use iced::window; use iced::{Application, Element}; -use iced::{Color, Command, Length, Settings, Subscription}; +use iced::{Color, Command, Length, Settings, Size, Subscription}; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; @@ -22,7 +22,7 @@ pub fn main() -> iced::Result { Todos::run(Settings { window: window::Settings { - size: (500, 800), + size: Size::new(500.0, 800.0), ..window::Settings::default() }, ..Settings::default() diff --git a/runtime/src/window.rs b/runtime/src/window.rs index 375ce8896e..f46ac1b80e 100644 --- a/runtime/src/window.rs +++ b/runtime/src/window.rs @@ -10,7 +10,7 @@ pub use screenshot::Screenshot; use crate::command::{self, Command}; use crate::core::time::Instant; use crate::core::window::{self, Event, Icon, Level, Mode, UserAttention}; -use crate::core::Size; +use crate::core::{Point, Size}; use crate::futures::event; use crate::futures::Subscription; @@ -48,17 +48,14 @@ pub fn drag<Message>(id: window::Id) -> Command<Message> { } /// Resizes the window to the given logical dimensions. -pub fn resize<Message>( - id: window::Id, - new_size: Size<u32>, -) -> Command<Message> { +pub fn resize<Message>(id: window::Id, new_size: Size) -> Command<Message> { Command::single(command::Action::Window(id, Action::Resize(new_size))) } /// Fetches the window's size in logical dimensions. pub fn fetch_size<Message>( id: window::Id, - f: impl FnOnce(Size<u32>) -> Message + 'static, + f: impl FnOnce(Size) -> Message + 'static, ) -> Command<Message> { Command::single(command::Action::Window(id, Action::FetchSize(Box::new(f)))) } @@ -74,8 +71,8 @@ pub fn minimize<Message>(id: window::Id, minimized: bool) -> Command<Message> { } /// Moves the window to the given logical coordinates. -pub fn move_to<Message>(id: window::Id, x: i32, y: i32) -> Command<Message> { - Command::single(command::Action::Window(id, Action::Move { x, y })) +pub fn move_to<Message>(id: window::Id, position: Point) -> Command<Message> { + Command::single(command::Action::Window(id, Action::Move(position))) } /// Changes the [`Mode`] of the window. diff --git a/runtime/src/window/action.rs b/runtime/src/window/action.rs index 2a31bbd617..5afe038983 100644 --- a/runtime/src/window/action.rs +++ b/runtime/src/window/action.rs @@ -1,5 +1,5 @@ use crate::core::window::{Icon, Level, Mode, Settings, UserAttention}; -use crate::core::Size; +use crate::core::{Point, Size}; use crate::futures::MaybeSend; use crate::window::Screenshot; @@ -20,23 +20,18 @@ pub enum Action<T> { /// The settings of the window. settings: Settings, }, - /// Resize the window. - Resize(Size<u32>), - /// Fetch the current size of the window. - FetchSize(Box<dyn FnOnce(Size<u32>) -> T + 'static>), + /// Resize the window to the given logical dimensions. + Resize(Size), + /// Fetch the current logical dimensions of the window. + FetchSize(Box<dyn FnOnce(Size) -> T + 'static>), /// Set the window to maximized or back Maximize(bool), /// Set the window to minimized or back Minimize(bool), - /// Move the window. + /// Move the window to the given logical coordinates. /// /// Unsupported on Wayland. - Move { - /// The new logical x location of the window - x: i32, - /// The new logical y location of the window - y: i32, - }, + Move(Point), /// Change the [`Mode`] of the window. ChangeMode(Mode), /// Fetch the current [`Mode`] of the window. @@ -114,7 +109,7 @@ impl<T> Action<T> { Self::FetchSize(o) => Action::FetchSize(Box::new(move |s| f(o(s)))), Self::Maximize(maximized) => Action::Maximize(maximized), Self::Minimize(minimized) => Action::Minimize(minimized), - Self::Move { x, y } => Action::Move { x, y }, + Self::Move(position) => Action::Move(position), Self::ChangeMode(mode) => Action::ChangeMode(mode), Self::FetchMode(o) => Action::FetchMode(Box::new(move |s| f(o(s)))), Self::ToggleMaximize => Action::ToggleMaximize, @@ -151,8 +146,8 @@ impl<T> fmt::Debug for Action<T> { Self::Minimize(minimized) => { write!(f, "Action::Minimize({minimized}") } - Self::Move { x, y } => { - write!(f, "Action::Move {{ x: {x}, y: {y} }}") + Self::Move(position) => { + write!(f, "Action::Move({position})") } Self::ChangeMode(mode) => write!(f, "Action::SetMode({mode:?})"), Self::FetchMode(_) => write!(f, "Action::FetchMode"), diff --git a/winit/src/application.rs b/winit/src/application.rs index b197c4ed78..4e6a879fc1 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -732,7 +732,8 @@ pub fn run_command<A, C, E>( }); } window::Action::FetchSize(callback) => { - let size = window.inner_size(); + let size = + window.inner_size().to_logical(window.scale_factor()); proxy .send_event(callback(Size::new( @@ -747,10 +748,10 @@ pub fn run_command<A, C, E>( window::Action::Minimize(minimized) => { window.set_minimized(minimized); } - window::Action::Move { x, y } => { + window::Action::Move(position) => { window.set_outer_position(winit::dpi::LogicalPosition { - x, - y, + x: position.x, + y: position.y, }); } window::Action::ChangeMode(mode) => { diff --git a/winit/src/conversion.rs b/winit/src/conversion.rs index 68c2b905ae..7e51a2d400 100644 --- a/winit/src/conversion.rs +++ b/winit/src/conversion.rs @@ -6,7 +6,7 @@ use crate::core::keyboard; use crate::core::mouse; use crate::core::touch; use crate::core::window; -use crate::core::{Event, Point}; +use crate::core::{Event, Point, Size}; /// Converts some [`window::Settings`] into a `WindowBuilder` from `winit`. pub fn window_settings( @@ -17,11 +17,12 @@ pub fn window_settings( ) -> winit::window::WindowBuilder { let mut window_builder = winit::window::WindowBuilder::new(); - let (width, height) = settings.size; - window_builder = window_builder .with_title(title) - .with_inner_size(winit::dpi::LogicalSize { width, height }) + .with_inner_size(winit::dpi::LogicalSize { + width: settings.size.width, + height: settings.size.height, + }) .with_resizable(settings.resizable) .with_enabled_buttons(if settings.resizable { winit::window::WindowButtons::all() @@ -41,14 +42,20 @@ pub fn window_settings( window_builder = window_builder.with_position(position); } - if let Some((width, height)) = settings.min_size { - window_builder = window_builder - .with_min_inner_size(winit::dpi::LogicalSize { width, height }); + if let Some(min_size) = settings.min_size { + window_builder = + window_builder.with_min_inner_size(winit::dpi::LogicalSize { + width: min_size.width, + height: min_size.height, + }); } - if let Some((width, height)) = settings.max_size { - window_builder = window_builder - .with_max_inner_size(winit::dpi::LogicalSize { width, height }); + if let Some(max_size) = settings.max_size { + window_builder = + window_builder.with_max_inner_size(winit::dpi::LogicalSize { + width: max_size.width, + height: max_size.height, + }); } #[cfg(any( @@ -277,15 +284,15 @@ pub fn window_level(level: window::Level) -> winit::window::WindowLevel { /// [`winit`]: https://github.com/rust-windowing/winit pub fn position( monitor: Option<&winit::monitor::MonitorHandle>, - (width, height): (u32, u32), + size: Size, position: window::Position, ) -> Option<winit::dpi::Position> { match position { window::Position::Default => None, - window::Position::Specific(x, y) => { + window::Position::Specific(position) => { Some(winit::dpi::Position::Logical(winit::dpi::LogicalPosition { - x: f64::from(x), - y: f64::from(y), + x: f64::from(position.x), + y: f64::from(position.y), })) } window::Position::Centered => { @@ -297,8 +304,8 @@ pub fn position( let centered: winit::dpi::PhysicalPosition<i32> = winit::dpi::LogicalPosition { - x: (resolution.width - f64::from(width)) / 2.0, - y: (resolution.height - f64::from(height)) / 2.0, + x: (resolution.width - f64::from(size.width)) / 2.0, + y: (resolution.height - f64::from(size.height)) / 2.0, } .to_physical(monitor.scale_factor()); diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index f8cedcb831..7347645227 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -5,8 +5,12 @@ mod windows; pub use state::State; use crate::conversion; +use crate::core; +use crate::core::mouse; +use crate::core::renderer; use crate::core::widget::operation; -use crate::core::{self, mouse, renderer, window, Size}; +use crate::core::window; +use crate::core::{Point, Size}; use crate::futures::futures::channel::mpsc; use crate::futures::futures::{task, Future, StreamExt}; use crate::futures::{Executor, Runtime, Subscription}; @@ -350,18 +354,18 @@ async fn run_instance<A, E, C>( let mut mouse_interaction = mouse::Interaction::default(); - let mut events = - if let Some((position, size)) = logical_bounds_of(windows.main()) { - vec![( - Some(window::Id::MAIN), - core::Event::Window( - window::Id::MAIN, - window::Event::Created { position, size }, - ), - )] - } else { - Vec::new() - }; + let mut events = { + let (position, size) = logical_bounds_of(windows.main()); + + vec![( + Some(window::Id::MAIN), + core::Event::Window( + window::Id::MAIN, + window::Event::Created { position, size }, + ), + )] + }; + let mut messages = Vec::new(); let mut redraw_pending = false; @@ -374,7 +378,7 @@ async fn run_instance<A, E, C>( window, exit_on_close_request, } => { - let bounds = logical_bounds_of(&window); + let (position, size) = logical_bounds_of(&window); let (inner_size, i) = windows.add( &application, @@ -394,18 +398,13 @@ async fn run_instance<A, E, C>( )); ui_caches.push(user_interface::Cache::default()); - if let Some(bounds) = bounds { - events.push(( - Some(id), - core::Event::Window( - id, - window::Event::Created { - position: bounds.0, - size: bounds.1, - }, - ), - )); - } + events.push(( + Some(id), + core::Event::Window( + id, + window::Event::Created { position, size }, + ), + )); } Event::EventLoopAwakened(event) => { match event { @@ -925,7 +924,8 @@ fn run_command<A, C, E>( } window::Action::FetchSize(callback) => { let window = windows.with_raw(id); - let size = window.inner_size(); + let size = + window.inner_size().to_logical(window.scale_factor()); proxy .send_event(callback(Size::new( @@ -940,9 +940,12 @@ fn run_command<A, C, E>( window::Action::Minimize(minimized) => { windows.with_raw(id).set_minimized(minimized); } - window::Action::Move { x, y } => { + window::Action::Move(position) => { windows.with_raw(id).set_outer_position( - winit::dpi::LogicalPosition { x, y }, + winit::dpi::LogicalPosition { + x: position.x, + y: position.y, + }, ); } window::Action::ChangeMode(mode) => { @@ -1145,25 +1148,23 @@ pub fn user_force_quit( } } -fn logical_bounds_of( - window: &winit::window::Window, -) -> Option<((i32, i32), Size<u32>)> { - let scale = window.scale_factor(); - let pos = window +fn logical_bounds_of(window: &winit::window::Window) -> (Option<Point>, Size) { + let position = window .inner_position() - .map(|pos| { - ((pos.x as f64 / scale) as i32, (pos.y as f64 / scale) as i32) - }) - .ok()?; + .ok() + .map(|position| position.to_logical(window.scale_factor())) + .map(|position| Point { + x: position.x, + y: position.y, + }); + let size = { - let size = window.inner_size(); - Size::new( - (size.width as f64 / scale) as u32, - (size.height as f64 / scale) as u32, - ) + let size = window.inner_size().to_logical(window.scale_factor()); + + Size::new(size.width, size.height) }; - Some((pos, size)) + (position, size) } #[cfg(not(target_arch = "wasm32"))] From ea42af766f345715ff7a7168182d3896ee79cfbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Sat, 2 Dec 2023 20:41:58 +0100 Subject: [PATCH 63/66] Use `AtomicU64` for `window::Id` --- core/src/window/event.rs | 32 +++--- core/src/window/id.rs | 14 +-- examples/multi_window/src/main.rs | 49 ++++----- runtime/src/command/action.rs | 8 +- runtime/src/multi_window/program.rs | 4 +- runtime/src/window.rs | 99 +++++++++--------- runtime/src/window/action.rs | 154 +++++++++++++++------------- winit/src/application.rs | 36 +++---- winit/src/multi_window.rs | 44 ++++---- 9 files changed, 228 insertions(+), 212 deletions(-) diff --git a/core/src/window/event.rs b/core/src/window/event.rs index 3ab7cd810a..b9ee7aca78 100644 --- a/core/src/window/event.rs +++ b/core/src/window/event.rs @@ -6,6 +6,22 @@ use std::path::PathBuf; /// A window-related event. #[derive(PartialEq, Clone, Debug)] pub enum Event { + /// A window was opened. + Opened { + /// The position of the opened window. This is relative to the top-left corner of the desktop + /// the window is on, including virtual desktops. Refers to window's "inner" position, + /// or the client area, in logical pixels. + /// + /// **Note**: Not available in Wayland. + position: Option<Point>, + /// The size of the created window. This is its "inner" size, or the size of the + /// client area, in logical pixels. + size: Size, + }, + + /// A window was closed. + Closed, + /// A window was moved. Moved { /// The new logical x location of the window @@ -30,22 +46,6 @@ pub enum Event { /// The user has requested for the window to close. CloseRequested, - /// A window was created. - Created { - /// The position of the created window. This is relative to the top-left corner of the desktop - /// the window is on, including virtual desktops. Refers to window's "inner" position, - /// or the client area, in logical pixels. - /// - /// **Note**: Not available in Wayland. - position: Option<Point>, - /// The size of the created window. This is its "inner" size, or the size of the - /// client area, in logical pixels. - size: Size, - }, - - /// A window was destroyed by the runtime. - Destroyed, - /// A window was focused. Focused, diff --git a/core/src/window/id.rs b/core/src/window/id.rs index 65002d437b..20474c8f31 100644 --- a/core/src/window/id.rs +++ b/core/src/window/id.rs @@ -1,5 +1,6 @@ -use std::collections::hash_map::DefaultHasher; -use std::hash::{Hash, Hasher}; +use std::hash::Hash; + +use std::sync::atomic::{self, AtomicU64}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] /// The id of the window. @@ -7,15 +8,14 @@ use std::hash::{Hash, Hasher}; /// Internally Iced reserves `window::Id::MAIN` for the first window spawned. pub struct Id(u64); +static COUNT: AtomicU64 = AtomicU64::new(1); + impl Id { /// The reserved window [`Id`] for the first window in an Iced application. pub const MAIN: Self = Id(0); /// Creates a new unique window [`Id`]. - pub fn new(id: impl Hash) -> Id { - let mut hasher = DefaultHasher::new(); - id.hash(&mut hasher); - - Id(hasher.finish()) + pub fn unique() -> Id { + Id(COUNT.fetch_add(1, atomic::Ordering::Relaxed)) } } diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index 16beb46e24..5a5e70c16c 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -35,8 +35,8 @@ enum Message { ScaleChanged(window::Id, String), TitleChanged(window::Id, String), CloseWindow(window::Id), - WindowCreated(window::Id, Option<Point>), - WindowDestroyed(window::Id), + WindowOpened(window::Id, Option<Point>), + WindowClosed(window::Id), NewWindow, } @@ -69,6 +69,8 @@ impl multi_window::Application for Example { let window = self.windows.get_mut(&id).expect("Window not found!"); window.scale_input = scale; + + Command::none() } Message::ScaleChanged(id, scale) => { let window = @@ -78,20 +80,23 @@ impl multi_window::Application for Example { .parse::<f64>() .unwrap_or(window.current_scale) .clamp(0.5, 5.0); + + Command::none() } Message::TitleChanged(id, title) => { let window = self.windows.get_mut(&id).expect("Window not found."); window.title = title; + + Command::none() } - Message::CloseWindow(id) => { - return window::close(id); - } - Message::WindowDestroyed(id) => { + Message::CloseWindow(id) => window::close(id), + Message::WindowClosed(id) => { self.windows.remove(&id); + Command::none() } - Message::WindowCreated(id, position) => { + Message::WindowOpened(id, position) => { if let Some(position) = position { self.next_window_pos = window::Position::Specific( position + Vector::new(20.0, 20.0), @@ -99,27 +104,25 @@ impl multi_window::Application for Example { } if let Some(window) = self.windows.get(&id) { - return text_input::focus(window.input_id.clone()); + text_input::focus(window.input_id.clone()) + } else { + Command::none() } } Message::NewWindow => { let count = self.windows.len() + 1; - let id = window::Id::new(count); + + let (id, spawn_window) = window::spawn(window::Settings { + position: self.next_window_pos, + exit_on_close_request: count % 2 == 0, + ..Default::default() + }); self.windows.insert(id, Window::new(count)); - return window::spawn( - id, - window::Settings { - position: self.next_window_pos, - exit_on_close_request: count % 2 == 0, - ..Default::default() - }, - ); + spawn_window } } - - Command::none() } fn view(&self, window: window::Id) -> Element<Message> { @@ -151,12 +154,10 @@ impl multi_window::Application for Example { window::Event::CloseRequested => { Some(Message::CloseWindow(id)) } - window::Event::Destroyed => { - Some(Message::WindowDestroyed(id)) - } - window::Event::Created { position, .. } => { - Some(Message::WindowCreated(id, position)) + window::Event::Opened { position, .. } => { + Some(Message::WindowOpened(id, position)) } + window::Event::Closed => Some(Message::WindowClosed(id)), _ => None, } } else { diff --git a/runtime/src/command/action.rs b/runtime/src/command/action.rs index 7a70920ed6..cb0936df74 100644 --- a/runtime/src/command/action.rs +++ b/runtime/src/command/action.rs @@ -27,7 +27,7 @@ pub enum Action<T> { Clipboard(clipboard::Action<T>), /// Run a window action. - Window(window::Id, window::Action<T>), + Window(window::Action<T>), /// Run a system action. System(system::Action<T>), @@ -63,7 +63,7 @@ impl<T> Action<T> { 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(id, window) => Action::Window(id, window.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))) @@ -84,8 +84,8 @@ impl<T> fmt::Debug for Action<T> { Self::Clipboard(action) => { write!(f, "Action::Clipboard({action:?})") } - Self::Window(id, action) => { - write!(f, "Action::Window({id:?}, {action:?})") + Self::Window(action) => { + write!(f, "Action::Window({action:?})") } Self::System(action) => write!(f, "Action::System({action:?})"), Self::Widget(_action) => write!(f, "Action::Widget"), diff --git a/runtime/src/multi_window/program.rs b/runtime/src/multi_window/program.rs index c3989d0d01..591b3e9a7b 100644 --- a/runtime/src/multi_window/program.rs +++ b/runtime/src/multi_window/program.rs @@ -1,8 +1,8 @@ //! Build interactive programs using The Elm Architecture. -use crate::{window, Command}; - use crate::core::text; +use crate::core::window; use crate::core::{Element, Renderer}; +use crate::Command; /// The core of a user interface for a multi-window application following The Elm Architecture. pub trait Program: Sized { diff --git a/runtime/src/window.rs b/runtime/src/window.rs index f46ac1b80e..f9d943f6aa 100644 --- a/runtime/src/window.rs +++ b/runtime/src/window.rs @@ -3,13 +3,14 @@ mod action; pub mod screenshot; -pub use crate::core::window::Id; pub use action::Action; pub use screenshot::Screenshot; use crate::command::{self, Command}; use crate::core::time::Instant; -use crate::core::window::{self, Event, Icon, Level, Mode, UserAttention}; +use crate::core::window::{ + Event, Icon, Id, Level, Mode, Settings, UserAttention, +}; use crate::core::{Point, Size}; use crate::futures::event; use crate::futures::Subscription; @@ -29,73 +30,77 @@ pub fn frames() -> Subscription<Instant> { }) } -/// Spawns a new window with the given `id` and `settings`. -pub fn spawn<Message>( - id: window::Id, - settings: window::Settings, -) -> Command<Message> { - Command::single(command::Action::Window(id, Action::Spawn { settings })) +/// Spawns a new window with the given `settings`. +/// +/// Returns the new window [`Id`] alongside the [`Command`]. +pub fn spawn<Message>(settings: Settings) -> (Id, Command<Message>) { + let id = Id::unique(); + + ( + id, + Command::single(command::Action::Window(Action::Spawn(id, settings))), + ) } /// Closes the window with `id`. -pub fn close<Message>(id: window::Id) -> Command<Message> { - Command::single(command::Action::Window(id, Action::Close)) +pub fn close<Message>(id: Id) -> Command<Message> { + Command::single(command::Action::Window(Action::Close(id))) } /// Begins dragging the window while the left mouse button is held. -pub fn drag<Message>(id: window::Id) -> Command<Message> { - Command::single(command::Action::Window(id, Action::Drag)) +pub fn drag<Message>(id: Id) -> Command<Message> { + Command::single(command::Action::Window(Action::Drag(id))) } /// Resizes the window to the given logical dimensions. -pub fn resize<Message>(id: window::Id, new_size: Size) -> Command<Message> { - Command::single(command::Action::Window(id, Action::Resize(new_size))) +pub fn resize<Message>(id: Id, new_size: Size) -> Command<Message> { + Command::single(command::Action::Window(Action::Resize(id, new_size))) } /// Fetches the window's size in logical dimensions. pub fn fetch_size<Message>( - id: window::Id, + id: Id, f: impl FnOnce(Size) -> Message + 'static, ) -> Command<Message> { - Command::single(command::Action::Window(id, Action::FetchSize(Box::new(f)))) + Command::single(command::Action::Window(Action::FetchSize(id, Box::new(f)))) } /// Maximizes the window. -pub fn maximize<Message>(id: window::Id, maximized: bool) -> Command<Message> { - Command::single(command::Action::Window(id, Action::Maximize(maximized))) +pub fn maximize<Message>(id: Id, maximized: bool) -> Command<Message> { + Command::single(command::Action::Window(Action::Maximize(id, maximized))) } /// Minimizes the window. -pub fn minimize<Message>(id: window::Id, minimized: bool) -> Command<Message> { - Command::single(command::Action::Window(id, Action::Minimize(minimized))) +pub fn minimize<Message>(id: Id, minimized: bool) -> Command<Message> { + Command::single(command::Action::Window(Action::Minimize(id, minimized))) } /// Moves the window to the given logical coordinates. -pub fn move_to<Message>(id: window::Id, position: Point) -> Command<Message> { - Command::single(command::Action::Window(id, Action::Move(position))) +pub fn move_to<Message>(id: Id, position: Point) -> Command<Message> { + Command::single(command::Action::Window(Action::Move(id, position))) } /// Changes the [`Mode`] of the window. -pub fn change_mode<Message>(id: window::Id, mode: Mode) -> Command<Message> { - Command::single(command::Action::Window(id, Action::ChangeMode(mode))) +pub fn change_mode<Message>(id: Id, mode: Mode) -> Command<Message> { + Command::single(command::Action::Window(Action::ChangeMode(id, mode))) } /// Fetches the current [`Mode`] of the window. pub fn fetch_mode<Message>( - id: window::Id, + id: Id, f: impl FnOnce(Mode) -> Message + 'static, ) -> Command<Message> { - Command::single(command::Action::Window(id, Action::FetchMode(Box::new(f)))) + Command::single(command::Action::Window(Action::FetchMode(id, Box::new(f)))) } /// Toggles the window to maximized or back. -pub fn toggle_maximize<Message>(id: window::Id) -> Command<Message> { - Command::single(command::Action::Window(id, Action::ToggleMaximize)) +pub fn toggle_maximize<Message>(id: Id) -> Command<Message> { + Command::single(command::Action::Window(Action::ToggleMaximize(id))) } /// Toggles the window decorations. -pub fn toggle_decorations<Message>(id: window::Id) -> Command<Message> { - Command::single(command::Action::Window(id, Action::ToggleDecorations)) +pub fn toggle_decorations<Message>(id: Id) -> Command<Message> { + Command::single(command::Action::Window(Action::ToggleDecorations(id))) } /// Request user attention to the window. This has no effect if the application @@ -105,13 +110,13 @@ pub fn toggle_decorations<Message>(id: window::Id) -> Command<Message> { /// 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. pub fn request_user_attention<Message>( - id: window::Id, + id: Id, user_attention: Option<UserAttention>, ) -> Command<Message> { - Command::single(command::Action::Window( + Command::single(command::Action::Window(Action::RequestUserAttention( id, - Action::RequestUserAttention(user_attention), - )) + user_attention, + ))) } /// Brings the window to the front and sets input focus. Has no effect if the window is @@ -120,36 +125,36 @@ pub fn request_user_attention<Message>( /// This [`Command`] 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. -pub fn gain_focus<Message>(id: window::Id) -> Command<Message> { - Command::single(command::Action::Window(id, Action::GainFocus)) +pub fn gain_focus<Message>(id: Id) -> Command<Message> { + Command::single(command::Action::Window(Action::GainFocus(id))) } /// Changes the window [`Level`]. -pub fn change_level<Message>(id: window::Id, level: Level) -> Command<Message> { - Command::single(command::Action::Window(id, Action::ChangeLevel(level))) +pub fn change_level<Message>(id: Id, level: Level) -> Command<Message> { + Command::single(command::Action::Window(Action::ChangeLevel(id, level))) } /// Fetches an identifier unique to the window, provided by the underlying windowing system. This is -/// not to be confused with [`window::Id`]. +/// not to be confused with [`Id`]. pub fn fetch_id<Message>( - id: window::Id, + id: Id, f: impl FnOnce(u64) -> Message + 'static, ) -> Command<Message> { - Command::single(command::Action::Window(id, Action::FetchId(Box::new(f)))) + Command::single(command::Action::Window(Action::FetchId(id, Box::new(f)))) } /// Changes the [`Icon`] of the window. -pub fn change_icon<Message>(id: window::Id, icon: Icon) -> Command<Message> { - Command::single(command::Action::Window(id, Action::ChangeIcon(icon))) +pub fn change_icon<Message>(id: Id, icon: Icon) -> Command<Message> { + Command::single(command::Action::Window(Action::ChangeIcon(id, icon))) } /// Captures a [`Screenshot`] from the window. pub fn screenshot<Message>( - id: window::Id, + id: Id, f: impl FnOnce(Screenshot) -> Message + Send + 'static, ) -> Command<Message> { - Command::single(command::Action::Window( + Command::single(command::Action::Window(Action::Screenshot( id, - Action::Screenshot(Box::new(f)), - )) + Box::new(f), + ))) } diff --git a/runtime/src/window/action.rs b/runtime/src/window/action.rs index 5afe038983..2d98b60766 100644 --- a/runtime/src/window/action.rs +++ b/runtime/src/window/action.rs @@ -1,4 +1,4 @@ -use crate::core::window::{Icon, Level, Mode, Settings, UserAttention}; +use crate::core::window::{Icon, Id, Level, Mode, Settings, UserAttention}; use crate::core::{Point, Size}; use crate::futures::MaybeSend; use crate::window::Screenshot; @@ -7,43 +7,40 @@ use std::fmt; /// An operation to be performed on some window. pub enum Action<T> { - /// Close the current window and exits the application. - Close, + /// 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. /// /// There’s no guarantee that this will work unless the left mouse /// button was pressed immediately before this function is called. - Drag, - /// Spawns a new window. - Spawn { - /// The settings of the window. - settings: Settings, - }, + Drag(Id), /// Resize the window to the given logical dimensions. - Resize(Size), + Resize(Id, Size), /// Fetch the current logical dimensions of the window. - FetchSize(Box<dyn FnOnce(Size) -> T + 'static>), + FetchSize(Id, Box<dyn FnOnce(Size) -> T + 'static>), /// Set the window to maximized or back - Maximize(bool), + Maximize(Id, bool), /// Set the window to minimized or back - Minimize(bool), + Minimize(Id, bool), /// Move the window to the given logical coordinates. /// /// Unsupported on Wayland. - Move(Point), + Move(Id, Point), /// Change the [`Mode`] of the window. - ChangeMode(Mode), + ChangeMode(Id, Mode), /// Fetch the current [`Mode`] of the window. - FetchMode(Box<dyn FnOnce(Mode) -> T + 'static>), + FetchMode(Id, Box<dyn FnOnce(Mode) -> T + 'static>), /// Toggle the window to maximized or back - ToggleMaximize, + ToggleMaximize(Id), /// Toggle whether window has decorations. /// /// ## Platform-specific /// - **X11:** Not implemented. /// - **Web:** Unsupported. - ToggleDecorations, + 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. @@ -57,7 +54,7 @@ pub enum Action<T> { /// - **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(Option<UserAttention>), + 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. /// @@ -68,11 +65,11 @@ pub enum Action<T> { /// ## Platform-specific /// /// - **Web / Wayland:** Unsupported. - GainFocus, + GainFocus(Id), /// Change the window [`Level`]. - ChangeLevel(Level), - /// Fetch an identifier unique to the window. - FetchId(Box<dyn FnOnce(u64) -> T + 'static>), + ChangeLevel(Id, Level), + /// 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 @@ -87,9 +84,9 @@ pub enum Action<T> { /// /// - **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(Icon), + ChangeIcon(Id, Icon), /// Screenshot the viewport of the window. - Screenshot(Box<dyn FnOnce(Screenshot) -> T + 'static>), + Screenshot(Id, Box<dyn FnOnce(Screenshot) -> T + 'static>), } impl<T> Action<T> { @@ -102,30 +99,35 @@ impl<T> Action<T> { T: 'static, { match self { - Self::Close => Action::Close, - Self::Drag => Action::Drag, - Self::Spawn { settings } => Action::Spawn { settings }, - Self::Resize(size) => Action::Resize(size), - Self::FetchSize(o) => Action::FetchSize(Box::new(move |s| f(o(s)))), - Self::Maximize(maximized) => Action::Maximize(maximized), - Self::Minimize(minimized) => Action::Minimize(minimized), - Self::Move(position) => Action::Move(position), - Self::ChangeMode(mode) => Action::ChangeMode(mode), - Self::FetchMode(o) => Action::FetchMode(Box::new(move |s| f(o(s)))), - Self::ToggleMaximize => Action::ToggleMaximize, - Self::ToggleDecorations => Action::ToggleDecorations, - Self::RequestUserAttention(attention_type) => { - Action::RequestUserAttention(attention_type) + 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::GainFocus => Action::GainFocus, - Self::ChangeLevel(level) => Action::ChangeLevel(level), - Self::FetchId(o) => Action::FetchId(Box::new(move |s| f(o(s)))), - Self::ChangeIcon(icon) => Action::ChangeIcon(icon), - Self::Screenshot(tag) => { - Action::Screenshot(Box::new(move |screenshot| { - f(tag(screenshot)) - })) + Self::Maximize(id, maximized) => Action::Maximize(id, maximized), + Self::Minimize(id, minimized) => Action::Minimize(id, minimized), + 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::FetchId(id, o) => { + Action::FetchId(id, Box::new(move |s| f(o(s)))) + } + Self::ChangeIcon(id, icon) => Action::ChangeIcon(id, icon), + Self::Screenshot(id, tag) => Action::Screenshot( + id, + Box::new(move |screenshot| f(tag(screenshot))), + ), } } } @@ -133,38 +135,46 @@ impl<T> Action<T> { impl<T> fmt::Debug for Action<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Close => write!(f, "Action::Close"), - Self::Drag => write!(f, "Action::Drag"), - Self::Spawn { settings } => { - write!(f, "Action::Spawn {{ settings: {:?} }}", settings) + 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::Maximize(id, maximized) => { + write!(f, "Action::Maximize({id:?}, {maximized})") + } + Self::Minimize(id, minimized) => { + write!(f, "Action::Minimize({id:?}, {minimized}") + } + Self::Move(id, position) => { + write!(f, "Action::Move({id:?}, {position})") } - Self::Resize(size) => write!(f, "Action::Resize({size:?})"), - Self::FetchSize(_) => write!(f, "Action::FetchSize"), - Self::Maximize(maximized) => { - write!(f, "Action::Maximize({maximized})") + Self::ChangeMode(id, mode) => { + write!(f, "Action::SetMode({id:?}, {mode:?})") } - Self::Minimize(minimized) => { - write!(f, "Action::Minimize({minimized}") + Self::FetchMode(id, _) => write!(f, "Action::FetchMode({id:?})"), + Self::ToggleMaximize(id) => { + write!(f, "Action::ToggleMaximize({id:?})") } - Self::Move(position) => { - write!(f, "Action::Move({position})") + Self::ToggleDecorations(id) => { + write!(f, "Action::ToggleDecorations({id:?})") } - Self::ChangeMode(mode) => write!(f, "Action::SetMode({mode:?})"), - Self::FetchMode(_) => write!(f, "Action::FetchMode"), - Self::ToggleMaximize => write!(f, "Action::ToggleMaximize"), - Self::ToggleDecorations => write!(f, "Action::ToggleDecorations"), - Self::RequestUserAttention(_) => { - write!(f, "Action::RequestUserAttention") + Self::RequestUserAttention(id, _) => { + write!(f, "Action::RequestUserAttention({id:?})") } - Self::GainFocus => write!(f, "Action::GainFocus"), - Self::ChangeLevel(level) => { - write!(f, "Action::ChangeLevel({level:?})") + Self::GainFocus(id) => write!(f, "Action::GainFocus({id:?})"), + Self::ChangeLevel(id, level) => { + write!(f, "Action::ChangeLevel({id:?}, {level:?})") } - Self::FetchId(_) => write!(f, "Action::FetchId"), - Self::ChangeIcon(_icon) => { - write!(f, "Action::ChangeIcon(icon)") + Self::FetchId(id, _) => write!(f, "Action::FetchId({id:?})"), + Self::ChangeIcon(id, _icon) => { + write!(f, "Action::ChangeIcon({id:?})") } - Self::Screenshot(_) => write!(f, "Action::Screenshot"), + Self::Screenshot(id, _) => write!(f, "Action::Screenshot({id:?})"), } } } diff --git a/winit/src/application.rs b/winit/src/application.rs index 4e6a879fc1..cc1db8cb78 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -712,11 +712,11 @@ pub fn run_command<A, C, E>( clipboard.write(contents); } }, - command::Action::Window(_, action) => match action { - window::Action::Close => { + command::Action::Window(action) => match action { + window::Action::Close(_id) => { *should_exit = true; } - window::Action::Drag => { + window::Action::Drag(_id) => { let _res = window.drag_window(); } window::Action::Spawn { .. } => { @@ -725,13 +725,13 @@ pub fn run_command<A, C, E>( multi-window applications." ); } - window::Action::Resize(size) => { + window::Action::Resize(_id, size) => { window.set_inner_size(winit::dpi::LogicalSize { width: size.width, height: size.height, }); } - window::Action::FetchSize(callback) => { + window::Action::FetchSize(_id, callback) => { let size = window.inner_size().to_logical(window.scale_factor()); @@ -742,29 +742,29 @@ pub fn run_command<A, C, E>( ))) .expect("Send message to event loop"); } - window::Action::Maximize(maximized) => { + window::Action::Maximize(_id, maximized) => { window.set_maximized(maximized); } - window::Action::Minimize(minimized) => { + window::Action::Minimize(_id, minimized) => { window.set_minimized(minimized); } - window::Action::Move(position) => { + window::Action::Move(_id, position) => { window.set_outer_position(winit::dpi::LogicalPosition { x: position.x, y: position.y, }); } - window::Action::ChangeMode(mode) => { + window::Action::ChangeMode(_id, mode) => { window.set_visible(conversion::visible(mode)); window.set_fullscreen(conversion::fullscreen( window.current_monitor(), mode, )); } - window::Action::ChangeIcon(icon) => { + window::Action::ChangeIcon(_id, icon) => { window.set_window_icon(conversion::icon(icon)); } - window::Action::FetchMode(tag) => { + window::Action::FetchMode(_id, tag) => { let mode = if window.is_visible().unwrap_or(true) { conversion::mode(window.fullscreen()) } else { @@ -775,29 +775,29 @@ pub fn run_command<A, C, E>( .send_event(tag(mode)) .expect("Send message to event loop"); } - window::Action::ToggleMaximize => { + window::Action::ToggleMaximize(_id) => { window.set_maximized(!window.is_maximized()); } - window::Action::ToggleDecorations => { + window::Action::ToggleDecorations(_id) => { window.set_decorations(!window.is_decorated()); } - window::Action::RequestUserAttention(user_attention) => { + window::Action::RequestUserAttention(_id, user_attention) => { window.request_user_attention( user_attention.map(conversion::user_attention), ); } - window::Action::GainFocus => { + window::Action::GainFocus(_id) => { window.focus_window(); } - window::Action::ChangeLevel(level) => { + window::Action::ChangeLevel(_id, level) => { window.set_window_level(conversion::window_level(level)); } - window::Action::FetchId(tag) => { + window::Action::FetchId(_id, tag) => { proxy .send_event(tag(window.id().into())) .expect("Send message to event loop"); } - window::Action::Screenshot(tag) => { + window::Action::Screenshot(_id, tag) => { let bytes = compositor.screenshot( renderer, surface, diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 7347645227..aeb2c5e11c 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -361,7 +361,7 @@ async fn run_instance<A, E, C>( Some(window::Id::MAIN), core::Event::Window( window::Id::MAIN, - window::Event::Created { position, size }, + window::Event::Opened { position, size }, ), )] }; @@ -402,7 +402,7 @@ async fn run_instance<A, E, C>( Some(id), core::Event::Window( id, - window::Event::Created { position, size }, + window::Event::Opened { position, size }, ), )); } @@ -761,7 +761,7 @@ async fn run_instance<A, E, C>( None, core::Event::Window( id, - window::Event::Destroyed, + window::Event::Closed, ), )); } @@ -884,8 +884,8 @@ fn run_command<A, C, E>( clipboard.write(contents); } }, - command::Action::Window(id, action) => match action { - window::Action::Spawn { settings } => { + command::Action::Window(action) => match action { + window::Action::Spawn(id, settings) => { let monitor = windows.last_monitor(); control_sender @@ -897,7 +897,7 @@ fn run_command<A, C, E>( }) .expect("Send control action"); } - window::Action::Close => { + window::Action::Close(id) => { use winit::event_loop::ControlFlow; let i = windows.delete(id); @@ -911,10 +911,10 @@ fn run_command<A, C, E>( .expect("Send control action"); } } - window::Action::Drag => { + window::Action::Drag(id) => { let _ = windows.with_raw(id).drag_window(); } - window::Action::Resize(size) => { + window::Action::Resize(id, size) => { windows.with_raw(id).set_inner_size( winit::dpi::LogicalSize { width: size.width, @@ -922,7 +922,7 @@ fn run_command<A, C, E>( }, ); } - window::Action::FetchSize(callback) => { + window::Action::FetchSize(id, callback) => { let window = windows.with_raw(id); let size = window.inner_size().to_logical(window.scale_factor()); @@ -934,13 +934,13 @@ fn run_command<A, C, E>( ))) .expect("Send message to event loop"); } - window::Action::Maximize(maximized) => { + window::Action::Maximize(id, maximized) => { windows.with_raw(id).set_maximized(maximized); } - window::Action::Minimize(minimized) => { + window::Action::Minimize(id, minimized) => { windows.with_raw(id).set_minimized(minimized); } - window::Action::Move(position) => { + window::Action::Move(id, position) => { windows.with_raw(id).set_outer_position( winit::dpi::LogicalPosition { x: position.x, @@ -948,7 +948,7 @@ fn run_command<A, C, E>( }, ); } - window::Action::ChangeMode(mode) => { + window::Action::ChangeMode(id, mode) => { let window = windows.with_raw(id); window.set_visible(conversion::visible(mode)); window.set_fullscreen(conversion::fullscreen( @@ -956,12 +956,12 @@ fn run_command<A, C, E>( mode, )); } - window::Action::ChangeIcon(icon) => { + window::Action::ChangeIcon(id, icon) => { windows .with_raw(id) .set_window_icon(conversion::icon(icon)); } - window::Action::FetchMode(tag) => { + window::Action::FetchMode(id, tag) => { let window = windows.with_raw(id); let mode = if window.is_visible().unwrap_or(true) { conversion::mode(window.fullscreen()) @@ -973,33 +973,33 @@ fn run_command<A, C, E>( .send_event(tag(mode)) .expect("Event loop doesn't exist."); } - window::Action::ToggleMaximize => { + window::Action::ToggleMaximize(id) => { let window = windows.with_raw(id); window.set_maximized(!window.is_maximized()); } - window::Action::ToggleDecorations => { + window::Action::ToggleDecorations(id) => { let window = windows.with_raw(id); window.set_decorations(!window.is_decorated()); } - window::Action::RequestUserAttention(attention_type) => { + window::Action::RequestUserAttention(id, attention_type) => { windows.with_raw(id).request_user_attention( attention_type.map(conversion::user_attention), ); } - window::Action::GainFocus => { + window::Action::GainFocus(id) => { windows.with_raw(id).focus_window(); } - window::Action::ChangeLevel(level) => { + window::Action::ChangeLevel(id, level) => { windows .with_raw(id) .set_window_level(conversion::window_level(level)); } - window::Action::FetchId(tag) => { + window::Action::FetchId(id, tag) => { proxy .send_event(tag(windows.with_raw(id).id().into())) .expect("Event loop doesn't exist."); } - window::Action::Screenshot(tag) => { + window::Action::Screenshot(id, tag) => { let i = windows.index_from_id(id); let state = &windows.states[i]; let surface = &mut windows.surfaces[i]; From b152ecda63238136f77b6eda3c582fa1eff99737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Sat, 2 Dec 2023 20:49:47 +0100 Subject: [PATCH 64/66] Separate `Compositor::new` from `Compositor::create_renderer` --- graphics/src/compositor.rs | 4 +-- renderer/src/compositor.rs | 47 ++++++++++-------------------- tiny_skia/src/window/compositor.rs | 28 +++++------------- wgpu/src/window/compositor.rs | 21 ++++--------- winit/src/application.rs | 4 +-- winit/src/multi_window.rs | 4 +-- winit/src/multi_window/windows.rs | 2 +- 7 files changed, 35 insertions(+), 75 deletions(-) diff --git a/graphics/src/compositor.rs b/graphics/src/compositor.rs index 78731a982b..b8b575b41c 100644 --- a/graphics/src/compositor.rs +++ b/graphics/src/compositor.rs @@ -22,10 +22,10 @@ pub trait Compositor: Sized { fn new<W: HasRawWindowHandle + HasRawDisplayHandle>( settings: Self::Settings, compatible_window: Option<&W>, - ) -> Result<(Self, Self::Renderer), Error>; + ) -> Result<Self, Error>; /// Creates a [`Self::Renderer`] for the [`Compositor`]. - fn renderer(&self) -> Self::Renderer; + fn create_renderer(&self) -> Self::Renderer; /// Crates a new [`Surface`] for the given window. /// diff --git a/renderer/src/compositor.rs b/renderer/src/compositor.rs index 5bec1639f7..9d0ff9ab3c 100644 --- a/renderer/src/compositor.rs +++ b/renderer/src/compositor.rs @@ -26,7 +26,7 @@ impl<Theme> crate::graphics::Compositor for Compositor<Theme> { fn new<W: HasRawWindowHandle + HasRawDisplayHandle>( settings: Self::Settings, compatible_window: Option<&W>, - ) -> Result<(Self, Self::Renderer), Error> { + ) -> Result<Self, Error> { let candidates = Candidate::list_from_env().unwrap_or(Candidate::default_list()); @@ -34,9 +34,7 @@ impl<Theme> crate::graphics::Compositor for Compositor<Theme> { for candidate in candidates { match candidate.build(settings, compatible_window) { - Ok((compositor, renderer)) => { - return Ok((compositor, renderer)) - } + Ok(compositor) => return Ok(compositor), Err(new_error) => { error = new_error; } @@ -46,14 +44,14 @@ impl<Theme> crate::graphics::Compositor for Compositor<Theme> { Err(error) } - fn renderer(&self) -> Self::Renderer { + fn create_renderer(&self) -> Self::Renderer { match self { Compositor::TinySkia(compositor) => { - Renderer::TinySkia(compositor.renderer()) + Renderer::TinySkia(compositor.create_renderer()) } #[cfg(feature = "wgpu")] Compositor::Wgpu(compositor) => { - Renderer::Wgpu(compositor.renderer()) + Renderer::Wgpu(compositor.create_renderer()) } } } @@ -232,29 +230,21 @@ impl Candidate { self, settings: Settings, _compatible_window: Option<&W>, - ) -> Result<(Compositor<Theme>, Renderer<Theme>), Error> { + ) -> Result<Compositor<Theme>, Error> { match self { Self::TinySkia => { - let (compositor, backend) = - iced_tiny_skia::window::compositor::new( - iced_tiny_skia::Settings { - default_font: settings.default_font, - default_text_size: settings.default_text_size, - }, - ); + let compositor = iced_tiny_skia::window::compositor::new( + iced_tiny_skia::Settings { + default_font: settings.default_font, + default_text_size: settings.default_text_size, + }, + ); - Ok(( - Compositor::TinySkia(compositor), - Renderer::TinySkia(iced_tiny_skia::Renderer::new( - backend, - settings.default_font, - settings.default_text_size, - )), - )) + Ok(Compositor::TinySkia(compositor)) } #[cfg(feature = "wgpu")] Self::Wgpu => { - let (compositor, backend) = iced_wgpu::window::compositor::new( + let compositor = iced_wgpu::window::compositor::new( iced_wgpu::Settings { default_font: settings.default_font, default_text_size: settings.default_text_size, @@ -264,14 +254,7 @@ impl Candidate { _compatible_window, )?; - Ok(( - Compositor::Wgpu(compositor), - Renderer::Wgpu(iced_wgpu::Renderer::new( - backend, - settings.default_font, - settings.default_text_size, - )), - )) + Ok(Compositor::Wgpu(compositor)) } #[cfg(not(feature = "wgpu"))] Self::Wgpu => { diff --git a/tiny_skia/src/window/compositor.rs b/tiny_skia/src/window/compositor.rs index 32095e2396..87ded74640 100644 --- a/tiny_skia/src/window/compositor.rs +++ b/tiny_skia/src/window/compositor.rs @@ -28,20 +28,11 @@ impl<Theme> crate::graphics::Compositor for Compositor<Theme> { fn new<W: HasRawWindowHandle + HasRawDisplayHandle>( settings: Self::Settings, _compatible_window: Option<&W>, - ) -> Result<(Self, Self::Renderer), Error> { - let (compositor, backend) = new(settings); - - Ok(( - compositor, - Renderer::new( - backend, - settings.default_font, - settings.default_text_size, - ), - )) + ) -> Result<Self, Error> { + Ok(new(settings)) } - fn renderer(&self) -> Self::Renderer { + fn create_renderer(&self) -> Self::Renderer { Renderer::new( Backend::new(), self.settings.default_font, @@ -130,14 +121,11 @@ impl<Theme> crate::graphics::Compositor for Compositor<Theme> { } } -pub fn new<Theme>(settings: Settings) -> (Compositor<Theme>, Backend) { - ( - Compositor { - settings, - _theme: PhantomData, - }, - Backend::new(), - ) +pub fn new<Theme>(settings: Settings) -> Compositor<Theme> { + Compositor { + settings, + _theme: PhantomData, + } } pub fn present<T: AsRef<str>>( diff --git a/wgpu/src/window/compositor.rs b/wgpu/src/window/compositor.rs index 21406134a5..090e0e9f40 100644 --- a/wgpu/src/window/compositor.rs +++ b/wgpu/src/window/compositor.rs @@ -139,16 +139,14 @@ impl<Theme> Compositor<Theme> { pub fn new<Theme, W: HasRawWindowHandle + HasRawDisplayHandle>( settings: Settings, compatible_window: Option<&W>, -) -> Result<(Compositor<Theme>, Backend), Error> { +) -> Result<Compositor<Theme>, Error> { let compositor = futures::executor::block_on(Compositor::request( settings, compatible_window, )) .ok_or(Error::GraphicsAdapterNotFound)?; - let backend = compositor.create_backend(); - - Ok((compositor, backend)) + Ok(compositor) } /// Presents the given primitives with the given [`Compositor`] and [`Backend`]. @@ -214,20 +212,11 @@ impl<Theme> graphics::Compositor for Compositor<Theme> { fn new<W: HasRawWindowHandle + HasRawDisplayHandle>( settings: Self::Settings, compatible_window: Option<&W>, - ) -> Result<(Self, Self::Renderer), Error> { - let (compositor, backend) = new(settings, compatible_window)?; - - Ok(( - compositor, - Renderer::new( - backend, - settings.default_font, - settings.default_text_size, - ), - )) + ) -> Result<Self, Error> { + new(settings, compatible_window) } - fn renderer(&self) -> Self::Renderer { + fn create_renderer(&self) -> Self::Renderer { Renderer::new( self.create_backend(), self.settings.default_font, diff --git a/winit/src/application.rs b/winit/src/application.rs index cc1db8cb78..d970007573 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -181,8 +181,8 @@ where }; } - let (compositor, mut renderer) = - C::new(compositor_settings, Some(&window))?; + let compositor = C::new(compositor_settings, Some(&window))?; + let mut renderer = compositor.create_renderer(); for font in settings.fonts { use crate::core::text::Renderer; diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index aeb2c5e11c..31c27a6d97 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -181,8 +181,8 @@ where }; } - let (mut compositor, renderer) = - C::new(compositor_settings, Some(&main_window))?; + let mut compositor = C::new(compositor_settings, Some(&main_window))?; + let renderer = compositor.create_renderer(); let windows = Windows::new( &application, diff --git a/winit/src/multi_window/windows.rs b/winit/src/multi_window/windows.rs index a4841a4510..5a33b7b493 100644 --- a/winit/src/multi_window/windows.rs +++ b/winit/src/multi_window/windows.rs @@ -97,7 +97,7 @@ where physical_size.width, physical_size.height, ); - let renderer = compositor.renderer(); + let renderer = compositor.create_renderer(); self.ids.push(id); self.raw.push(window); From 31cccd8f7b9b92d486cdcbf39ede112652c9dafa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Sat, 2 Dec 2023 20:56:55 +0100 Subject: [PATCH 65/66] Remove unnecessary re-exports in `iced_winit` --- winit/src/lib.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/winit/src/lib.rs b/winit/src/lib.rs index cc88635456..948576a28a 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -54,6 +54,3 @@ pub use clipboard::Clipboard; pub use error::Error; pub use proxy::Proxy; pub use settings::Settings; - -pub use crate::core::window::*; -pub use iced_graphics::Viewport; From 5c5e7653bed248ba63faa6563e4d673e4441415e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= <hector@hecrj.dev> Date: Sat, 2 Dec 2023 22:26:01 +0100 Subject: [PATCH 66/66] Refactor `Windows` abstraction into `WindowManager` --- winit/src/multi_window.rs | 620 ++++++++++++----------- winit/src/multi_window/state.rs | 4 +- winit/src/multi_window/window_manager.rs | 156 ++++++ winit/src/multi_window/windows.rs | 201 -------- 4 files changed, 470 insertions(+), 511 deletions(-) create mode 100644 winit/src/multi_window/window_manager.rs delete mode 100644 winit/src/multi_window/windows.rs diff --git a/winit/src/multi_window.rs b/winit/src/multi_window.rs index 31c27a6d97..84651d40de 100644 --- a/winit/src/multi_window.rs +++ b/winit/src/multi_window.rs @@ -1,21 +1,20 @@ //! Create interactive, native cross-platform applications for WGPU. mod state; -mod windows; +mod window_manager; pub use state::State; use crate::conversion; use crate::core; -use crate::core::mouse; use crate::core::renderer; use crate::core::widget::operation; use crate::core::window; -use crate::core::{Point, Size}; +use crate::core::Size; use crate::futures::futures::channel::mpsc; use crate::futures::futures::{task, Future, StreamExt}; use crate::futures::{Executor, Runtime, Subscription}; use crate::graphics::{compositor, Compositor}; -use crate::multi_window::windows::Windows; +use crate::multi_window::window_manager::WindowManager; use crate::runtime::command::{self, Command}; use crate::runtime::multi_window::Program; use crate::runtime::user_interface::{self, UserInterface}; @@ -23,6 +22,7 @@ use crate::runtime::Debug; use crate::style::application::StyleSheet; use crate::{Clipboard, Error, Proxy, Settings}; +use std::collections::HashMap; use std::mem::ManuallyDrop; use std::time::Instant; @@ -182,13 +182,13 @@ where } let mut compositor = C::new(compositor_settings, Some(&main_window))?; - let renderer = compositor.create_renderer(); - let windows = Windows::new( + let mut window_manager = WindowManager::new(); + let _ = window_manager.insert( + window::Id::MAIN, + main_window, &application, &mut compositor, - renderer, - main_window, exit_on_close_request, ); @@ -204,7 +204,7 @@ where event_receiver, control_sender, init_command, - windows, + window_manager, should_main_be_visible, )); @@ -312,7 +312,7 @@ async fn run_instance<A, E, C>( mut event_receiver: mpsc::UnboundedReceiver<Event<A::Message>>, mut control_sender: mpsc::UnboundedSender<Control>, init_command: Command<A::Message>, - mut windows: Windows<A, C>, + mut window_manager: WindowManager<A, C>, should_main_window_be_visible: bool, ) where A: Application + 'static, @@ -323,20 +323,39 @@ async fn run_instance<A, E, C>( use winit::event; use winit::event_loop::ControlFlow; - let mut clipboard = Clipboard::connect(windows.main()); + let main_window = window_manager + .get_mut(window::Id::MAIN) + .expect("Get main window"); + + if should_main_window_be_visible { + main_window.raw.set_visible(true); + } + + let mut clipboard = Clipboard::connect(&main_window.raw); + let mut events = { + vec![( + Some(window::Id::MAIN), + core::Event::Window( + window::Id::MAIN, + window::Event::Opened { + position: main_window.position(), + size: main_window.size(), + }, + ), + )] + }; - let mut ui_caches = vec![user_interface::Cache::default()]; + let mut ui_caches = HashMap::new(); let mut user_interfaces = ManuallyDrop::new(build_user_interfaces( &application, &mut debug, - &mut windows, - vec![user_interface::Cache::default()], + &mut window_manager, + HashMap::from_iter([( + window::Id::MAIN, + user_interface::Cache::default(), + )]), )); - if should_main_window_be_visible { - windows.main().set_visible(true); - } - run_command( &application, &mut compositor, @@ -346,26 +365,12 @@ async fn run_instance<A, E, C>( &mut control_sender, &mut proxy, &mut debug, - &mut windows, + &mut window_manager, &mut ui_caches, ); runtime.track(application.subscription().into_recipes()); - let mut mouse_interaction = mouse::Interaction::default(); - - let mut events = { - let (position, size) = logical_bounds_of(windows.main()); - - vec![( - Some(window::Id::MAIN), - core::Event::Window( - window::Id::MAIN, - window::Event::Opened { position, size }, - ), - )] - }; - let mut messages = Vec::new(); let mut redraw_pending = false; @@ -378,31 +383,37 @@ async fn run_instance<A, E, C>( window, exit_on_close_request, } => { - let (position, size) = logical_bounds_of(&window); - - let (inner_size, i) = windows.add( - &application, - &mut compositor, + let window = window_manager.insert( id, window, + &application, + &mut compositor, exit_on_close_request, ); - user_interfaces.push(build_user_interface( - &application, - user_interface::Cache::default(), - &mut windows.renderers[i], - inner_size, - &mut debug, + let logical_size = window.state.logical_size(); + + let _ = user_interfaces.insert( id, - )); - ui_caches.push(user_interface::Cache::default()); + build_user_interface( + &application, + user_interface::Cache::default(), + &mut window.renderer, + logical_size, + &mut debug, + id, + ), + ); + let _ = ui_caches.insert(id, user_interface::Cache::default()); events.push(( Some(id), core::Event::Window( id, - window::Event::Opened { position, size }, + window::Event::Opened { + position: window.position(), + size: window.size(), + }, ), )); } @@ -420,12 +431,11 @@ async fn run_instance<A, E, C>( debug.event_processing_started(); let mut uis_stale = false; - for (i, id) in windows.ids.iter().enumerate() { + for (id, window) in window_manager.iter_mut() { let mut window_events = vec![]; events.retain(|(window_id, event)| { - if *window_id == Some(*id) - || window_id.is_none() + if *window_id == Some(id) || window_id.is_none() { window_events.push(event.clone()); false @@ -441,11 +451,13 @@ async fn run_instance<A, E, C>( continue; } - let (ui_state, statuses) = user_interfaces[i] + let (ui_state, statuses) = user_interfaces + .get_mut(&id) + .expect("Get user interface") .update( &window_events, - windows.states[i].cursor(), - &mut windows.renderers[i], + window.state.cursor(), + &mut window.renderer, &mut clipboard, &mut messages, ); @@ -469,11 +481,12 @@ async fn run_instance<A, E, C>( // TODO mw application update returns which window IDs to update if !messages.is_empty() || uis_stale { - let mut cached_interfaces: Vec< + let mut cached_interfaces: HashMap< + window::Id, user_interface::Cache, > = ManuallyDrop::into_inner(user_interfaces) - .drain(..) - .map(UserInterface::into_cache) + .drain() + .map(|(id, ui)| (id, ui.into_cache())) .collect(); // Update application @@ -486,18 +499,18 @@ async fn run_instance<A, E, C>( &mut proxy, &mut debug, &mut messages, - &mut windows, + &mut window_manager, &mut cached_interfaces, ); // we must synchronize all window states with application state after an // application update since we don't know what changed - for (state, (id, window)) in windows - .states - .iter_mut() - .zip(windows.ids.iter().zip(windows.raw.iter())) - { - state.synchronize(&application, *id, window); + for (id, window) in window_manager.iter_mut() { + window.state.synchronize( + &application, + id, + &window.raw, + ); } // rebuild UIs with the synchronized states @@ -505,39 +518,43 @@ async fn run_instance<A, E, C>( ManuallyDrop::new(build_user_interfaces( &application, &mut debug, - &mut windows, + &mut window_manager, cached_interfaces, )); } debug.draw_started(); - for (i, id) in windows.ids.iter().enumerate() { + for (id, window) in window_manager.iter_mut() { // TODO: Avoid redrawing all the time by forcing widgets to // request redraws on state changes // // Then, we can use the `interface_state` here to decide if a redraw // is needed right away, or simply wait until a specific time. let redraw_event = core::Event::Window( - *id, + id, window::Event::RedrawRequested(Instant::now()), ); - let cursor = windows.states[i].cursor(); + let cursor = window.state.cursor(); + + let ui = user_interfaces + .get_mut(&id) + .expect("Get user interface"); - let (ui_state, _) = user_interfaces[i].update( + let (ui_state, _) = ui.update( &[redraw_event.clone()], cursor, - &mut windows.renderers[i], + &mut window.renderer, &mut clipboard, &mut messages, ); let new_mouse_interaction = { - let state = &windows.states[i]; + let state = &window.state; - user_interfaces[i].draw( - &mut windows.renderers[i], + ui.draw( + &mut window.renderer, state.theme(), &renderer::Style { text_color: state.text_color(), @@ -546,19 +563,21 @@ async fn run_instance<A, E, C>( ) }; - if new_mouse_interaction != mouse_interaction { - windows.raw[i].set_cursor_icon( + if new_mouse_interaction != window.mouse_interaction + { + window.raw.set_cursor_icon( conversion::mouse_interaction( new_mouse_interaction, ), ); - mouse_interaction = new_mouse_interaction; + window.mouse_interaction = + new_mouse_interaction; } // TODO once widgets can request to be redrawn, we can avoid always requesting a // redraw - windows.raw[i].request_redraw(); + window.raw.request_redraw(); runtime.broadcast( redraw_event.clone(), @@ -606,9 +625,13 @@ async fn run_instance<A, E, C>( messages.push(message); } event::Event::RedrawRequested(id) => { - let i = windows.index_from_raw(id); - let state = &windows.states[i]; - let physical_size = state.physical_size(); + let Some((id, window)) = + window_manager.get_mut_alias(id) + else { + continue; + }; + + let physical_size = window.state.physical_size(); if physical_size.width == 0 || physical_size.height == 0 { @@ -616,60 +639,65 @@ async fn run_instance<A, E, C>( } debug.render_started(); - let current_viewport_version = state.viewport_version(); - let window_viewport_version = - windows.viewport_versions[i]; - - if window_viewport_version != current_viewport_version { - let logical_size = state.logical_size(); + if window.viewport_version + != window.state.viewport_version() + { + let logical_size = window.state.logical_size(); debug.layout_started(); - let renderer = &mut windows.renderers[i]; - let ui = user_interfaces.remove(i); + let ui = user_interfaces + .remove(&id) + .expect("Remove user interface"); - user_interfaces - .insert(i, ui.relayout(logical_size, renderer)); + let _ = user_interfaces.insert( + id, + ui.relayout(logical_size, &mut window.renderer), + ); debug.layout_finished(); debug.draw_started(); - let new_mouse_interaction = user_interfaces[i] + let new_mouse_interaction = user_interfaces + .get_mut(&id) + .expect("Get user interface") .draw( - renderer, - state.theme(), + &mut window.renderer, + window.state.theme(), &renderer::Style { - text_color: state.text_color(), + text_color: window.state.text_color(), }, - state.cursor(), + window.state.cursor(), ); - if new_mouse_interaction != mouse_interaction { - windows.raw[i].set_cursor_icon( + if new_mouse_interaction != window.mouse_interaction + { + window.raw.set_cursor_icon( conversion::mouse_interaction( new_mouse_interaction, ), ); - mouse_interaction = new_mouse_interaction; + window.mouse_interaction = + new_mouse_interaction; } debug.draw_finished(); compositor.configure_surface( - &mut windows.surfaces[i], + &mut window.surface, physical_size.width, physical_size.height, ); - windows.viewport_versions[i] = - current_viewport_version; + window.viewport_version = + window.state.viewport_version(); } match compositor.present( - &mut windows.renderers[i], - &mut windows.surfaces[i], - state.viewport(), - state.background_color(), + &mut window.renderer, + &mut window.surface, + window.state.viewport(), + window.state.background_color(), &debug.overlay(), ) { Ok(()) => { @@ -690,8 +718,10 @@ async fn run_instance<A, E, C>( ); // Try rendering all windows again next frame. - for window in &windows.raw { - window.request_redraw(); + for (_id, window) in + window_manager.iter_mut() + { + window.raw.request_redraw(); } } }, @@ -701,70 +731,43 @@ async fn run_instance<A, E, C>( event: window_event, window_id, } => { - let window_index = windows - .raw - .iter() - .position(|w| w.id() == window_id); + let Some((id, window)) = + window_manager.get_mut_alias(window_id) + else { + continue; + }; - match window_index { - Some(i) => { - let id = windows.ids[i]; - let raw = &windows.raw[i]; - let exit_on_close_request = - windows.exit_on_close_requested[i]; + if matches!( + window_event, + winit::event::WindowEvent::CloseRequested + ) && window.exit_on_close_request + { + let _ = window_manager.remove(id); + let _ = user_interfaces.remove(&id); + let _ = ui_caches.remove(&id); - if matches!( - window_event, - winit::event::WindowEvent::CloseRequested - ) && exit_on_close_request - { - let i = windows.delete(id); - let _ = user_interfaces.remove(i); - let _ = ui_caches.remove(i); + events.push(( + None, + core::Event::Window(id, window::Event::Closed), + )); - if windows.is_empty() { - break 'main; - } - } else { - let state = &mut windows.states[i]; - state.update( - raw, - &window_event, - &mut debug, - ); - - if let Some(event) = - conversion::window_event( - id, - &window_event, - state.scale_factor(), - state.modifiers(), - ) - { - events.push((Some(id), event)); - } - } + if window_manager.is_empty() { + break 'main; } - None => { - // This is the only special case, since in order to trigger the Destroyed event the - // window reference from winit must be dropped, but we still want to inform the - // user that the window was destroyed so they can clean up any specific window - // code for this window - if matches!( - window_event, - winit::event::WindowEvent::Destroyed - ) { - let id = - windows.get_pending_destroy(window_id); - - events.push(( - None, - core::Event::Window( - id, - window::Event::Closed, - ), - )); - } + } else { + window.state.update( + &window.raw, + &window_event, + &mut debug, + ); + + if let Some(event) = conversion::window_event( + id, + &window_event, + window.state.scale_factor(), + window.state.modifiers(), + ) { + events.push((Some(id), event)); } } } @@ -811,8 +814,8 @@ fn update<A: Application, C, E: Executor>( proxy: &mut winit::event_loop::EventLoopProxy<A::Message>, debug: &mut Debug, messages: &mut Vec<A::Message>, - windows: &mut Windows<A, C>, - ui_caches: &mut Vec<user_interface::Cache>, + window_manager: &mut WindowManager<A, C>, + ui_caches: &mut HashMap<window::Id, user_interface::Cache>, ) where C: Compositor<Renderer = A::Renderer> + 'static, <A::Renderer as core::Renderer>::Theme: StyleSheet, @@ -833,7 +836,7 @@ fn update<A: Application, C, E: Executor>( control_sender, proxy, debug, - windows, + window_manager, ui_caches, ); } @@ -852,8 +855,8 @@ fn run_command<A, C, E>( control_sender: &mut mpsc::UnboundedSender<Control>, proxy: &mut winit::event_loop::EventLoopProxy<A::Message>, debug: &mut Debug, - windows: &mut Windows<A, C>, - ui_caches: &mut Vec<user_interface::Cache>, + window_manager: &mut WindowManager<A, C>, + ui_caches: &mut HashMap<window::Id, user_interface::Cache>, ) where A: Application, E: Executor, @@ -886,7 +889,7 @@ fn run_command<A, C, E>( }, command::Action::Window(action) => match action { window::Action::Spawn(id, settings) => { - let monitor = windows.last_monitor(); + let monitor = window_manager.last_monitor(); control_sender .start_send(Control::CreateWindow { @@ -900,10 +903,10 @@ fn run_command<A, C, E>( window::Action::Close(id) => { use winit::event_loop::ControlFlow; - let i = windows.delete(id); - let _ = ui_caches.remove(i); + let _ = window_manager.remove(id); + let _ = ui_caches.remove(&id); - if windows.is_empty() { + if window_manager.is_empty() { control_sender .start_send(Control::ChangeFlow( ControlFlow::ExitWithCode(0), @@ -912,113 +915,133 @@ fn run_command<A, C, E>( } } window::Action::Drag(id) => { - let _ = windows.with_raw(id).drag_window(); + if let Some(window) = window_manager.get_mut(id) { + let _ = window.raw.drag_window(); + } } window::Action::Resize(id, size) => { - windows.with_raw(id).set_inner_size( - winit::dpi::LogicalSize { + if let Some(window) = window_manager.get_mut(id) { + window.raw.set_inner_size(winit::dpi::LogicalSize { width: size.width, height: size.height, - }, - ); + }); + } } window::Action::FetchSize(id, callback) => { - let window = windows.with_raw(id); - let size = - window.inner_size().to_logical(window.scale_factor()); - - proxy - .send_event(callback(Size::new( - size.width, - size.height, - ))) - .expect("Send message to event loop"); + if let Some(window) = window_manager.get_mut(id) { + let size = window + .raw + .inner_size() + .to_logical(window.raw.scale_factor()); + + proxy + .send_event(callback(Size::new( + size.width, + size.height, + ))) + .expect("Send message to event loop"); + } } window::Action::Maximize(id, maximized) => { - windows.with_raw(id).set_maximized(maximized); + if let Some(window) = window_manager.get_mut(id) { + window.raw.set_maximized(maximized); + } } window::Action::Minimize(id, minimized) => { - windows.with_raw(id).set_minimized(minimized); + if let Some(window) = window_manager.get_mut(id) { + window.raw.set_minimized(minimized); + } } window::Action::Move(id, position) => { - windows.with_raw(id).set_outer_position( - winit::dpi::LogicalPosition { - x: position.x, - y: position.y, - }, - ); + if let Some(window) = window_manager.get_mut(id) { + window.raw.set_outer_position( + winit::dpi::LogicalPosition { + x: position.x, + y: position.y, + }, + ); + } } window::Action::ChangeMode(id, mode) => { - let window = windows.with_raw(id); - window.set_visible(conversion::visible(mode)); - window.set_fullscreen(conversion::fullscreen( - window.current_monitor(), - mode, - )); + if let Some(window) = window_manager.get_mut(id) { + window.raw.set_visible(conversion::visible(mode)); + window.raw.set_fullscreen(conversion::fullscreen( + window.raw.current_monitor(), + mode, + )); + } } window::Action::ChangeIcon(id, icon) => { - windows - .with_raw(id) - .set_window_icon(conversion::icon(icon)); + if let Some(window) = window_manager.get_mut(id) { + window.raw.set_window_icon(conversion::icon(icon)); + } } window::Action::FetchMode(id, tag) => { - let window = windows.with_raw(id); - let mode = if window.is_visible().unwrap_or(true) { - conversion::mode(window.fullscreen()) - } else { - core::window::Mode::Hidden - }; - - proxy - .send_event(tag(mode)) - .expect("Event loop doesn't exist."); + if let Some(window) = window_manager.get_mut(id) { + let mode = if window.raw.is_visible().unwrap_or(true) { + conversion::mode(window.raw.fullscreen()) + } else { + core::window::Mode::Hidden + }; + + proxy + .send_event(tag(mode)) + .expect("Event loop doesn't exist."); + } } window::Action::ToggleMaximize(id) => { - let window = windows.with_raw(id); - window.set_maximized(!window.is_maximized()); + if let Some(window) = window_manager.get_mut(id) { + window.raw.set_maximized(!window.raw.is_maximized()); + } } window::Action::ToggleDecorations(id) => { - let window = windows.with_raw(id); - window.set_decorations(!window.is_decorated()); + if let Some(window) = window_manager.get_mut(id) { + window.raw.set_decorations(!window.raw.is_decorated()); + } } window::Action::RequestUserAttention(id, attention_type) => { - windows.with_raw(id).request_user_attention( - attention_type.map(conversion::user_attention), - ); + if let Some(window) = window_manager.get_mut(id) { + window.raw.request_user_attention( + attention_type.map(conversion::user_attention), + ); + } } window::Action::GainFocus(id) => { - windows.with_raw(id).focus_window(); + if let Some(window) = window_manager.get_mut(id) { + window.raw.focus_window(); + } } window::Action::ChangeLevel(id, level) => { - windows - .with_raw(id) - .set_window_level(conversion::window_level(level)); + if let Some(window) = window_manager.get_mut(id) { + window + .raw + .set_window_level(conversion::window_level(level)); + } } window::Action::FetchId(id, tag) => { - proxy - .send_event(tag(windows.with_raw(id).id().into())) - .expect("Event loop doesn't exist."); + if let Some(window) = window_manager.get_mut(id) { + proxy + .send_event(tag(window.raw.id().into())) + .expect("Event loop doesn't exist."); + } } window::Action::Screenshot(id, tag) => { - let i = windows.index_from_id(id); - let state = &windows.states[i]; - let surface = &mut windows.surfaces[i]; - let renderer = &mut windows.renderers[i]; - - let bytes = compositor.screenshot( - renderer, - surface, - state.viewport(), - state.background_color(), - &debug.overlay(), - ); + if let Some(window) = window_manager.get_mut(id) { + let bytes = compositor.screenshot( + &mut window.renderer, + &mut window.surface, + window.state.viewport(), + window.state.background_color(), + &debug.overlay(), + ); - proxy - .send_event(tag(window::Screenshot::new( - bytes, - state.physical_size(), - ))) - .expect("Event loop doesn't exist."); + proxy + .send_event(tag(window::Screenshot::new( + bytes, + window.state.physical_size(), + ))) + .expect("Event loop doesn't exist."); + } } }, command::Action::System(action) => match action { @@ -1047,43 +1070,45 @@ fn run_command<A, C, E>( let mut uis = build_user_interfaces( application, debug, - windows, + window_manager, std::mem::take(ui_caches), ); 'operate: while let Some(mut operation) = current_operation.take() { - for (i, ui) in uis.iter_mut().enumerate() { - ui.operate(&windows.renderers[i], operation.as_mut()); - - match operation.finish() { - operation::Outcome::None => {} - operation::Outcome::Some(message) => { - proxy - .send_event(message) - .expect("Event loop doesn't exist."); - - // operation completed, don't need to try to operate on rest of UIs - break 'operate; - } - operation::Outcome::Chain(next) => { - current_operation = Some(next); + for (id, ui) in uis.iter_mut() { + if let Some(window) = window_manager.get_mut(*id) { + ui.operate(&window.renderer, operation.as_mut()); + + match operation.finish() { + operation::Outcome::None => {} + operation::Outcome::Some(message) => { + proxy + .send_event(message) + .expect("Event loop doesn't exist."); + + // operation completed, don't need to try to operate on rest of UIs + break 'operate; + } + operation::Outcome::Chain(next) => { + current_operation = Some(next); + } } } } } *ui_caches = - uis.drain(..).map(UserInterface::into_cache).collect(); + uis.drain().map(|(id, ui)| (id, ui.into_cache())).collect(); } command::Action::LoadFont { bytes, tagger } => { use crate::core::text::Renderer; // TODO change this once we change each renderer to having a single backend reference.. :pain: // TODO: Error handling (?) - for renderer in &mut windows.renderers { - renderer.load_font(bytes.clone()); + for (_, window) in window_manager.iter_mut() { + window.renderer.load_font(bytes.clone()); } proxy @@ -1098,33 +1123,31 @@ fn run_command<A, C, E>( pub fn build_user_interfaces<'a, A: Application, C: Compositor>( application: &'a A, debug: &mut Debug, - windows: &mut Windows<A, C>, - mut cached_user_interfaces: Vec<user_interface::Cache>, -) -> Vec<UserInterface<'a, A::Message, A::Renderer>> + window_manager: &mut WindowManager<A, C>, + mut cached_user_interfaces: HashMap<window::Id, user_interface::Cache>, +) -> HashMap<window::Id, UserInterface<'a, A::Message, A::Renderer>> where <A::Renderer as core::Renderer>::Theme: StyleSheet, C: Compositor<Renderer = A::Renderer>, { cached_user_interfaces - .drain(..) - .zip( - windows - .ids - .iter() - .zip(windows.states.iter().zip(windows.renderers.iter_mut())), - ) - .fold(vec![], |mut uis, (cache, (id, (state, renderer)))| { - uis.push(build_user_interface( - application, - cache, - renderer, - state.logical_size(), - debug, - *id, - )); - - uis + .drain() + .filter_map(|(id, cache)| { + let window = window_manager.get_mut(id)?; + + Some(( + id, + build_user_interface( + application, + cache, + &mut window.renderer, + window.state.logical_size(), + debug, + id, + ), + )) }) + .collect() } /// Returns true if the provided event should cause an [`Application`] to @@ -1148,25 +1171,6 @@ pub fn user_force_quit( } } -fn logical_bounds_of(window: &winit::window::Window) -> (Option<Point>, Size) { - let position = window - .inner_position() - .ok() - .map(|position| position.to_logical(window.scale_factor())) - .map(|position| Point { - x: position.x, - y: position.y, - }); - - let size = { - let size = window.inner_size().to_logical(window.scale_factor()); - - Size::new(size.width, size.height) - }; - - (position, size) -} - #[cfg(not(target_arch = "wasm32"))] mod platform { pub fn run<T, F>( diff --git a/winit/src/multi_window/state.rs b/winit/src/multi_window/state.rs index e9a9f91a62..03da5ad751 100644 --- a/winit/src/multi_window/state.rs +++ b/winit/src/multi_window/state.rs @@ -19,7 +19,7 @@ where title: String, scale_factor: f64, viewport: Viewport, - viewport_version: usize, + viewport_version: u64, cursor_position: Option<winit::dpi::PhysicalPosition<f64>>, modifiers: winit::event::ModifiersState, theme: <A::Renderer as core::Renderer>::Theme, @@ -86,7 +86,7 @@ where /// Returns the version of the [`Viewport`] of the [`State`]. /// /// The version is incremented every time the [`Viewport`] changes. - pub fn viewport_version(&self) -> usize { + pub fn viewport_version(&self) -> u64 { self.viewport_version } diff --git a/winit/src/multi_window/window_manager.rs b/winit/src/multi_window/window_manager.rs new file mode 100644 index 0000000000..d54156e767 --- /dev/null +++ b/winit/src/multi_window/window_manager.rs @@ -0,0 +1,156 @@ +use crate::core::mouse; +use crate::core::window::Id; +use crate::core::{Point, Size}; +use crate::graphics::Compositor; +use crate::multi_window::{Application, State}; +use crate::style::application::StyleSheet; + +use std::collections::BTreeMap; +use winit::monitor::MonitorHandle; + +#[allow(missing_debug_implementations)] +pub struct WindowManager<A: Application, C: Compositor> +where + <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, + C: Compositor<Renderer = A::Renderer>, +{ + aliases: BTreeMap<winit::window::WindowId, Id>, + entries: BTreeMap<Id, Window<A, C>>, +} + +impl<A, C> WindowManager<A, C> +where + A: Application, + C: Compositor<Renderer = A::Renderer>, + <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, +{ + pub fn new() -> Self { + Self { + aliases: BTreeMap::new(), + entries: BTreeMap::new(), + } + } + + pub fn insert( + &mut self, + id: Id, + window: winit::window::Window, + application: &A, + compositor: &mut C, + exit_on_close_request: bool, + ) -> &mut Window<A, C> { + let state = State::new(application, id, &window); + let viewport_version = state.viewport_version(); + let physical_size = state.physical_size(); + let surface = compositor.create_surface( + &window, + physical_size.width, + physical_size.height, + ); + let renderer = compositor.create_renderer(); + + let _ = self.aliases.insert(window.id(), id); + + let _ = self.entries.insert( + id, + Window { + raw: window, + state, + viewport_version, + exit_on_close_request, + surface, + renderer, + mouse_interaction: mouse::Interaction::Idle, + }, + ); + + self.entries + .get_mut(&id) + .expect("Get window that was just inserted") + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn iter_mut( + &mut self, + ) -> impl Iterator<Item = (Id, &mut Window<A, C>)> { + self.entries.iter_mut().map(|(k, v)| (*k, v)) + } + + pub fn get_mut(&mut self, id: Id) -> Option<&mut Window<A, C>> { + self.entries.get_mut(&id) + } + + pub fn get_mut_alias( + &mut self, + id: winit::window::WindowId, + ) -> Option<(Id, &mut Window<A, C>)> { + let id = self.aliases.get(&id).copied()?; + + Some((id, self.get_mut(id)?)) + } + + pub fn last_monitor(&self) -> Option<MonitorHandle> { + self.entries.values().last()?.raw.current_monitor() + } + + pub fn remove(&mut self, id: Id) -> Option<Window<A, C>> { + let window = self.entries.remove(&id)?; + let _ = self.aliases.remove(&window.raw.id()); + + Some(window) + } +} + +impl<A, C> Default for WindowManager<A, C> +where + A: Application, + C: Compositor<Renderer = A::Renderer>, + <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, +{ + fn default() -> Self { + Self::new() + } +} + +#[allow(missing_debug_implementations)] +pub struct Window<A, C> +where + A: Application, + C: Compositor<Renderer = A::Renderer>, + <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, +{ + pub raw: winit::window::Window, + pub state: State<A>, + pub viewport_version: u64, + pub exit_on_close_request: bool, + pub mouse_interaction: mouse::Interaction, + pub surface: C::Surface, + pub renderer: A::Renderer, +} + +impl<A, C> Window<A, C> +where + A: Application, + C: Compositor<Renderer = A::Renderer>, + <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, +{ + pub fn position(&self) -> Option<Point> { + self.raw + .inner_position() + .ok() + .map(|position| position.to_logical(self.raw.scale_factor())) + .map(|position| Point { + x: position.x, + y: position.y, + }) + } + + pub fn size(&self) -> Size { + let size = self.raw.inner_size().to_logical(self.raw.scale_factor()); + + Size::new(size.width, size.height) + } +} diff --git a/winit/src/multi_window/windows.rs b/winit/src/multi_window/windows.rs deleted file mode 100644 index 5a33b7b493..0000000000 --- a/winit/src/multi_window/windows.rs +++ /dev/null @@ -1,201 +0,0 @@ -use crate::core::{window, Size}; -use crate::graphics::Compositor; -use crate::multi_window::{Application, State}; -use crate::style::application::StyleSheet; - -use winit::monitor::MonitorHandle; - -use std::fmt::{Debug, Formatter}; - -pub struct Windows<A: Application, C: Compositor> -where - <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, - C: Compositor<Renderer = A::Renderer>, -{ - pub ids: Vec<window::Id>, - pub raw: Vec<winit::window::Window>, - pub states: Vec<State<A>>, - pub viewport_versions: Vec<usize>, - pub exit_on_close_requested: Vec<bool>, - pub surfaces: Vec<C::Surface>, - pub renderers: Vec<A::Renderer>, - pub pending_destroy: Vec<(window::Id, winit::window::WindowId)>, -} - -impl<A: Application, C: Compositor> Debug for Windows<A, C> -where - <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, - C: Compositor<Renderer = A::Renderer>, -{ - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Windows") - .field("ids", &self.ids) - .field( - "raw", - &self - .raw - .iter() - .map(winit::window::Window::id) - .collect::<Vec<winit::window::WindowId>>(), - ) - .field("states", &self.states) - .field("viewport_versions", &self.viewport_versions) - .finish() - } -} - -impl<A: Application, C: Compositor> Windows<A, C> -where - <A::Renderer as crate::core::Renderer>::Theme: StyleSheet, - C: Compositor<Renderer = A::Renderer>, -{ - /// Creates a new [`Windows`] with a single `window::Id::MAIN` window. - pub fn new( - application: &A, - compositor: &mut C, - renderer: A::Renderer, - main: winit::window::Window, - exit_on_close_requested: bool, - ) -> Self { - let state = State::new(application, window::Id::MAIN, &main); - let viewport_version = state.viewport_version(); - let physical_size = state.physical_size(); - let surface = compositor.create_surface( - &main, - physical_size.width, - physical_size.height, - ); - - Self { - ids: vec![window::Id::MAIN], - raw: vec![main], - states: vec![state], - viewport_versions: vec![viewport_version], - exit_on_close_requested: vec![exit_on_close_requested], - surfaces: vec![surface], - renderers: vec![renderer], - pending_destroy: vec![], - } - } - - /// Adds a new window to [`Windows`]. Returns the size of the newly created window in logical - /// pixels & the index of the window within [`Windows`]. - pub fn add( - &mut self, - application: &A, - compositor: &mut C, - id: window::Id, - window: winit::window::Window, - exit_on_close_requested: bool, - ) -> (Size, usize) { - let state = State::new(application, id, &window); - let window_size = state.logical_size(); - let viewport_version = state.viewport_version(); - let physical_size = state.physical_size(); - let surface = compositor.create_surface( - &window, - physical_size.width, - physical_size.height, - ); - let renderer = compositor.create_renderer(); - - self.ids.push(id); - self.raw.push(window); - self.states.push(state); - self.exit_on_close_requested.push(exit_on_close_requested); - self.viewport_versions.push(viewport_version); - self.surfaces.push(surface); - self.renderers.push(renderer); - - (window_size, self.ids.len() - 1) - } - - pub fn is_empty(&self) -> bool { - self.ids.is_empty() - } - - pub fn main(&self) -> &winit::window::Window { - &self.raw[0] - } - - pub fn index_from_raw(&self, id: winit::window::WindowId) -> usize { - self.raw - .iter() - .position(|window| window.id() == id) - .expect("No raw window in multi_window::Windows") - } - - pub fn index_from_id(&self, id: window::Id) -> usize { - self.ids - .iter() - .position(|window_id| *window_id == id) - .expect("No window in multi_window::Windows") - } - - pub fn last_monitor(&self) -> Option<MonitorHandle> { - self.raw - .last() - .and_then(winit::window::Window::current_monitor) - } - - pub fn last(&self) -> usize { - self.ids.len() - 1 - } - - pub fn with_raw(&self, id: window::Id) -> &winit::window::Window { - let i = self.index_from_id(id); - &self.raw[i] - } - - /// Deletes the window with `id` from [`Windows`]. Returns the index that the window had. - pub fn delete(&mut self, id: window::Id) -> usize { - let i = self.index_from_id(id); - - let id = self.ids.remove(i); - let window = self.raw.remove(i); - let _ = self.states.remove(i); - let _ = self.exit_on_close_requested.remove(i); - let _ = self.viewport_versions.remove(i); - let _ = self.surfaces.remove(i); - - self.pending_destroy.push((id, window.id())); - - i - } - - /// Gets the winit `window` that is pending to be destroyed if it exists. - pub fn get_pending_destroy( - &mut self, - window: winit::window::WindowId, - ) -> window::Id { - let i = self - .pending_destroy - .iter() - .position(|(_, window_id)| window == *window_id) - .unwrap(); - - let (id, _) = self.pending_destroy.remove(i); - id - } - - /// Returns the windows that need to be requested to closed, and also the windows that can be - /// closed immediately. - pub fn partition_close_requests( - &self, - ) -> (Vec<window::Id>, Vec<window::Id>) { - self.exit_on_close_requested.iter().enumerate().fold( - (vec![], vec![]), - |(mut close_immediately, mut needs_request_closed), (i, close)| { - let id = self.ids[i]; - - if *close { - close_immediately.push(id); - } else { - needs_request_closed.push(id); - } - - (close_immediately, needs_request_closed) - }, - ) - } -}