diff options
Diffstat (limited to 'winit')
-rw-r--r-- | winit/Cargo.toml | 6 | ||||
-rw-r--r-- | winit/src/application.rs | 615 | ||||
-rw-r--r-- | winit/src/conversion.rs | 88 | ||||
-rw-r--r-- | winit/src/debug/basic.rs | 211 | ||||
-rw-r--r-- | winit/src/debug/null.rs | 46 | ||||
-rw-r--r-- | winit/src/lib.rs | 16 | ||||
-rw-r--r-- | winit/src/proxy.rs | 5 | ||||
-rw-r--r-- | winit/src/settings.rs | 55 | ||||
-rw-r--r-- | winit/src/size.rs | 30 |
9 files changed, 411 insertions, 661 deletions
diff --git a/winit/Cargo.toml b/winit/Cargo.toml index b6662451..7fe83b96 100644 --- a/winit/Cargo.toml +++ b/winit/Cargo.toml @@ -11,7 +11,7 @@ keywords = ["gui", "ui", "graphics", "interface", "widgets"] categories = ["gui"] [features] -debug = [] +debug = ["iced_native/debug"] [dependencies] winit = "0.22" @@ -22,5 +22,9 @@ log = "0.4" version = "0.2" path = "../native" +[dependencies.iced_graphics] +version = "0.1" +path = "../graphics" + [target.'cfg(target_os = "windows")'.dependencies.winapi] version = "0.3.6" diff --git a/winit/src/application.rs b/winit/src/application.rs index b974711c..5b93c8af 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -1,8 +1,11 @@ +//! Create interactive, native cross-platform applications. use crate::{ - conversion, size::Size, window, Cache, Clipboard, Command, Debug, Element, - Executor, Mode, MouseCursor, Proxy, Runtime, Settings, Subscription, - UserInterface, + conversion, mouse, Clipboard, Color, Command, Debug, Executor, Mode, Proxy, + Runtime, Settings, Size, Subscription, }; +use iced_graphics::window; +use iced_graphics::Viewport; +use iced_native::program::{self, Program}; /// An interactive, native cross-platform application. /// @@ -15,22 +18,9 @@ use crate::{ /// /// When using an [`Application`] with the `debug` feature enabled, a debug view /// can be toggled by pressing `F12`. -pub trait Application: Sized { - /// The graphics backend to use to draw the [`Application`]. - /// - /// [`Application`]: trait.Application.html - type Backend: window::Backend; - - /// The [`Executor`] that will run commands and subscriptions. - /// - /// [`Executor`]: trait.Executor.html - type Executor: Executor; - - /// The type of __messages__ your [`Application`] will produce. - /// - /// [`Application`]: trait.Application.html - type Message: std::fmt::Debug + Send; - +/// +/// [`Application`]: trait.Application.html +pub trait Application: Program { /// The data needed to initialize your [`Application`]. /// /// [`Application`]: trait.Application.html @@ -48,7 +38,7 @@ pub trait Application: Sized { /// /// [`Application`]: trait.Application.html /// [`run`]: #method.run.html - /// [`Settings`]: struct.Settings.html + /// [`Settings`]: ../settings/struct.Settings.html fn new(flags: Self::Flags) -> (Self, Command<Self::Message>); /// Returns the current title of the [`Application`]. @@ -59,18 +49,6 @@ pub trait Application: Sized { /// [`Application`]: trait.Application.html fn title(&self) -> String; - /// Handles a __message__ and updates the state of the [`Application`]. - /// - /// This is where you define your __update logic__. All the __messages__, - /// produced by either user interactions or commands, will be handled by - /// this method. - /// - /// Any [`Command`] returned will be executed immediately in the background. - /// - /// [`Application`]: trait.Application.html - /// [`Command`]: struct.Command.html - fn update(&mut self, message: Self::Message) -> Command<Self::Message>; - /// Returns the event `Subscription` for the current state of the /// application. /// @@ -78,16 +56,11 @@ pub trait Application: Sized { /// [`update`](#tymethod.update). /// /// A `Subscription` will be kept alive as long as you keep returning it! - fn subscription(&self) -> Subscription<Self::Message>; - - /// Returns the widgets to display in the [`Application`]. - /// - /// These widgets can produce __messages__ based on user interaction. /// - /// [`Application`]: trait.Application.html - fn view( - &mut self, - ) -> Element<'_, Self::Message, <Self::Backend as window::Backend>::Renderer>; + /// By default, it returns an empty subscription. + fn subscription(&self) -> Subscription<Self::Message> { + Subscription::none() + } /// Returns the current [`Application`] mode. /// @@ -101,333 +74,323 @@ pub trait Application: Sized { Mode::Windowed } - /// Runs the [`Application`] with the provided [`Settings`]. + /// Returns the background [`Color`] of the [`Application`]. /// - /// On native platforms, this method will take control of the current thread - /// and __will NOT return__. - /// - /// It should probably be that last thing you call in your `main` function. + /// By default, it returns [`Color::WHITE`]. /// + /// [`Color`]: struct.Color.html /// [`Application`]: trait.Application.html - /// [`Settings`]: struct.Settings.html - fn run( - settings: Settings<Self::Flags>, - backend_settings: <Self::Backend as window::Backend>::Settings, - ) where - Self: 'static, - { - use window::Backend as _; - use winit::{ - event::{self, WindowEvent}, - event_loop::{ControlFlow, EventLoop}, - window::WindowBuilder, - }; - - let mut debug = Debug::new(); - - debug.startup_started(); - let event_loop = EventLoop::with_user_event(); - let mut external_messages = Vec::new(); - - let mut runtime = { - let executor = Self::Executor::new().expect("Create executor"); - - Runtime::new(executor, Proxy::new(event_loop.create_proxy())) - }; - - let flags = settings.flags; - let (mut application, init_command) = - runtime.enter(|| Self::new(flags)); - runtime.spawn(init_command); - - let subscription = application.subscription(); - runtime.track(subscription); - - let mut title = application.title(); - let mut mode = application.mode(); - - let window = { - let mut window_builder = WindowBuilder::new(); - - let (width, height) = settings.window.size; - - window_builder = window_builder - .with_title(&title) - .with_inner_size(winit::dpi::LogicalSize { width, height }) - .with_resizable(settings.window.resizable) - .with_decorations(settings.window.decorations) - .with_fullscreen(conversion::fullscreen( - event_loop.primary_monitor(), - mode, - )); - - #[cfg(target_os = "windows")] - { - use winit::platform::windows::WindowBuilderExtWindows; - - if let Some(parent) = settings.window.platform_specific.parent { - window_builder = window_builder.with_parent_window(parent); - } - } - - window_builder.build(&event_loop).expect("Open window") - }; - - let mut size = Size::new(window.inner_size(), window.scale_factor()); - let mut resized = false; - - let clipboard = Clipboard::new(&window); - let (mut backend, mut renderer) = Self::Backend::new(backend_settings); - - let surface = backend.create_surface(&window); + /// [`Color::WHITE`]: struct.Color.html#const.WHITE + fn background_color(&self) -> Color { + Color::WHITE + } - let mut swap_chain = { - let physical_size = size.physical(); + /// 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`. + /// + /// [`Application`]: trait.Application.html + fn scale_factor(&self) -> f64 { + 1.0 + } +} - backend.create_swap_chain( - &surface, - physical_size.width, - physical_size.height, - ) - }; +/// Runs an [`Application`] with an executor, compositor, and the provided +/// settings. +/// +/// [`Application`]: trait.Application.html +pub fn run<A, E, C>( + settings: Settings<A::Flags>, + compositor_settings: C::Settings, +) where + A: Application + 'static, + E: Executor + 'static, + C: window::Compositor<Renderer = A::Renderer> + 'static, +{ + use winit::{ + event, + event_loop::{ControlFlow, EventLoop}, + }; + + let mut debug = Debug::new(); + debug.startup_started(); + + let event_loop = EventLoop::with_user_event(); + let mut runtime = { + let executor = E::new().expect("Create executor"); + let proxy = Proxy::new(event_loop.create_proxy()); + + Runtime::new(executor, proxy) + }; + + let flags = settings.flags; + let (application, init_command) = runtime.enter(|| A::new(flags)); + runtime.spawn(init_command); + + let subscription = application.subscription(); + runtime.track(subscription); + + let mut title = application.title(); + let mut mode = application.mode(); + let mut background_color = application.background_color(); + let mut scale_factor = application.scale_factor(); + + let window = settings + .window + .into_builder(&title, mode, event_loop.primary_monitor()) + .build(&event_loop) + .expect("Open window"); + + let clipboard = Clipboard::new(&window); + let mut cursor_position = winit::dpi::PhysicalPosition::new(-1.0, -1.0); + let mut mouse_interaction = mouse::Interaction::default(); + let mut modifiers = winit::event::ModifiersState::default(); + + let physical_size = window.inner_size(); + let mut viewport = Viewport::with_physical_size( + Size::new(physical_size.width, physical_size.height), + window.scale_factor() * scale_factor, + ); + let mut resized = false; - let user_interface = build_user_interface( - &mut application, - Cache::default(), - &mut renderer, - size.logical(), - &mut debug, - ); + let (mut compositor, mut renderer) = C::new(compositor_settings); - debug.draw_started(); - let mut primitive = user_interface.draw(&mut renderer); - debug.draw_finished(); + let surface = compositor.create_surface(&window); - let mut cache = Some(user_interface.into_cache()); - let mut events = Vec::new(); - let mut mouse_cursor = MouseCursor::OutOfBounds; - let mut modifiers = winit::event::ModifiersState::default(); - debug.startup_finished(); + let mut swap_chain = compositor.create_swap_chain( + &surface, + physical_size.width, + physical_size.height, + ); - window.request_redraw(); + let mut state = program::State::new( + application, + viewport.logical_size(), + conversion::cursor_position(cursor_position, viewport.scale_factor()), + &mut renderer, + &mut debug, + ); + debug.startup_finished(); - event_loop.run(move |event, _, control_flow| match event { - event::Event::MainEventsCleared => { - if events.is_empty() && external_messages.is_empty() { - return; - } + event_loop.run(move |event, _, control_flow| match event { + event::Event::MainEventsCleared => { + if state.is_queue_empty() { + return; + } - // TODO: We should be able to keep a user interface alive - // between events once we remove state references. - // - // This will allow us to rebuild it only when a message is - // handled. - let mut user_interface = build_user_interface( - &mut application, - cache.take().unwrap(), + let command = runtime.enter(|| { + state.update( + viewport.logical_size(), + conversion::cursor_position( + cursor_position, + viewport.scale_factor(), + ), + clipboard.as_ref().map(|c| c as _), &mut renderer, - size.logical(), &mut debug, - ); + ) + }); - debug.event_processing_started(); - events - .iter() - .cloned() - .for_each(|event| runtime.broadcast(event)); - - let mut messages = user_interface.update( - events.drain(..), - clipboard - .as_ref() - .map(|c| c as &dyn iced_native::Clipboard), - &renderer, - ); - messages.extend(external_messages.drain(..)); - debug.event_processing_finished(); + // If the application was updated + if let Some(command) = command { + runtime.spawn(command); - if messages.is_empty() { - debug.draw_started(); - primitive = user_interface.draw(&mut renderer); - debug.draw_finished(); + let program = state.program(); - cache = Some(user_interface.into_cache()); - } else { - // When there are messages, we are forced to rebuild twice - // for now :^) - let temp_cache = user_interface.into_cache(); + // Update subscriptions + let subscription = program.subscription(); + runtime.track(subscription); - for message in messages { - log::debug!("Updating"); + // Update window title + let new_title = program.title(); - debug.log_message(&message); + if title != new_title { + window.set_title(&new_title); - debug.update_started(); - let command = - runtime.enter(|| application.update(message)); - runtime.spawn(command); - debug.update_finished(); - } + title = new_title; + } - let subscription = application.subscription(); - runtime.track(subscription); + // Update window mode + let new_mode = program.mode(); - // Update window title - let new_title = application.title(); + if mode != new_mode { + window.set_fullscreen(conversion::fullscreen( + window.current_monitor(), + new_mode, + )); - if title != new_title { - window.set_title(&new_title); + mode = new_mode; + } - title = new_title; - } + // Update background color + background_color = program.background_color(); - // Update window mode - let new_mode = application.mode(); + // Update scale factor + let new_scale_factor = program.scale_factor(); - if mode != new_mode { - window.set_fullscreen(conversion::fullscreen( - window.current_monitor(), - new_mode, - )); + if scale_factor != new_scale_factor { + let size = window.inner_size(); - mode = new_mode; - } + viewport = Viewport::with_physical_size( + Size::new(size.width, size.height), + window.scale_factor() * new_scale_factor, + ); - let user_interface = build_user_interface( - &mut application, - temp_cache, + // We relayout the UI with the new logical size. + // The queue is empty, therefore this will never produce + // a `Command`. + // + // TODO: Properly queue `WindowResized` + let _ = state.update( + viewport.logical_size(), + conversion::cursor_position( + cursor_position, + viewport.scale_factor(), + ), + clipboard.as_ref().map(|c| c as _), &mut renderer, - size.logical(), &mut debug, ); - debug.draw_started(); - primitive = user_interface.draw(&mut renderer); - debug.draw_finished(); - - cache = Some(user_interface.into_cache()); + scale_factor = new_scale_factor; } - - window.request_redraw(); } - event::Event::UserEvent(message) => { - external_messages.push(message); - } - event::Event::RedrawRequested(_) => { - debug.render_started(); - - if resized { - let physical_size = size.physical(); - swap_chain = backend.create_swap_chain( - &surface, - physical_size.width, - physical_size.height, - ); - - resized = false; - } - - let new_mouse_cursor = backend.draw( - &mut renderer, - &mut swap_chain, - &primitive, - size.scale_factor(), - &debug.overlay(), + window.request_redraw(); + } + event::Event::UserEvent(message) => { + state.queue_message(message); + } + event::Event::RedrawRequested(_) => { + debug.render_started(); + + if resized { + let physical_size = viewport.physical_size(); + + swap_chain = compositor.create_swap_chain( + &surface, + physical_size.width, + physical_size.height, ); - debug.render_finished(); + resized = false; + } - if new_mouse_cursor != mouse_cursor { - window.set_cursor_icon(conversion::mouse_cursor( - new_mouse_cursor, - )); + let new_mouse_interaction = compositor.draw( + &mut renderer, + &mut swap_chain, + &viewport, + background_color, + state.primitive(), + &debug.overlay(), + ); - mouse_cursor = new_mouse_cursor; - } + debug.render_finished(); - // TODO: Handle animations! - // Maybe we can use `ControlFlow::WaitUntil` for this. - } - event::Event::WindowEvent { - event: window_event, - .. - } => { - match window_event { - WindowEvent::Resized(new_size) => { - size = Size::new(new_size, window.scale_factor()); - resized = true; - } - WindowEvent::CloseRequested => { - *control_flow = ControlFlow::Exit; - } - WindowEvent::ModifiersChanged(new_modifiers) => { - modifiers = new_modifiers; - } - #[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() => { - *control_flow = ControlFlow::Exit; - } - #[cfg(feature = "debug")] - WindowEvent::KeyboardInput { - input: - winit::event::KeyboardInput { - virtual_keycode: - Some(winit::event::VirtualKeyCode::F12), - state: winit::event::ElementState::Pressed, - .. - }, - .. - } => debug.toggle(), - _ => {} - } + if new_mouse_interaction != mouse_interaction { + window.set_cursor_icon(conversion::mouse_interaction( + new_mouse_interaction, + )); - if let Some(event) = conversion::window_event( - &window_event, - size.scale_factor(), - modifiers, - ) { - events.push(event); - } + mouse_interaction = new_mouse_interaction; } - _ => { - *control_flow = ControlFlow::Wait; + + // TODO: Handle animations! + // Maybe we can use `ControlFlow::WaitUntil` for this. + } + event::Event::WindowEvent { + event: window_event, + .. + } => { + handle_window_event( + &window_event, + &window, + scale_factor, + control_flow, + &mut cursor_position, + &mut modifiers, + &mut viewport, + &mut resized, + &mut debug, + ); + + if let Some(event) = conversion::window_event( + &window_event, + viewport.scale_factor(), + modifiers, + ) { + state.queue_event(event.clone()); + runtime.broadcast(event); } - }) - } + } + _ => { + *control_flow = ControlFlow::Wait; + } + }) } -fn build_user_interface<'a, A: Application>( - application: &'a mut A, - cache: Cache, - renderer: &mut <A::Backend as window::Backend>::Renderer, - size: winit::dpi::LogicalSize<f64>, - debug: &mut Debug, -) -> UserInterface<'a, A::Message, <A::Backend as window::Backend>::Renderer> { - debug.view_started(); - let view = application.view(); - debug.view_finished(); - - debug.layout_started(); - let user_interface = UserInterface::build( - view, - iced_native::Size::new( - size.width.round() as f32, - size.height.round() as f32, - ), - cache, - renderer, - ); - debug.layout_finished(); - - user_interface +/// Handles a `WindowEvent` and mutates the provided control flow, keyboard +/// modifiers, viewport, and resized flag accordingly. +pub fn handle_window_event( + event: &winit::event::WindowEvent<'_>, + window: &winit::window::Window, + scale_factor: f64, + control_flow: &mut winit::event_loop::ControlFlow, + cursor_position: &mut winit::dpi::PhysicalPosition<f64>, + modifiers: &mut winit::event::ModifiersState, + viewport: &mut Viewport, + resized: &mut bool, + _debug: &mut Debug, +) { + use winit::{event::WindowEvent, event_loop::ControlFlow}; + + match event { + WindowEvent::Resized(new_size) => { + let size = Size::new(new_size.width, new_size.height); + + *viewport = Viewport::with_physical_size( + size, + window.scale_factor() * scale_factor, + ); + *resized = true; + } + WindowEvent::CloseRequested => { + *control_flow = ControlFlow::Exit; + } + WindowEvent::CursorMoved { position, .. } => { + *cursor_position = *position; + } + WindowEvent::ModifiersChanged(new_modifiers) => { + *modifiers = *new_modifiers; + } + #[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() => { + *control_flow = ControlFlow::Exit; + } + #[cfg(feature = "debug")] + WindowEvent::KeyboardInput { + input: + winit::event::KeyboardInput { + virtual_keycode: Some(winit::event::VirtualKeyCode::F12), + state: winit::event::ElementState::Pressed, + .. + }, + .. + } => _debug.toggle(), + _ => {} + } } diff --git a/winit/src/conversion.rs b/winit/src/conversion.rs index eaa26ace..80727bd8 100644 --- a/winit/src/conversion.rs +++ b/winit/src/conversion.rs @@ -3,11 +3,8 @@ //! [`winit`]: https://github.com/rust-windowing/winit //! [`iced_native`]: https://github.com/hecrj/iced/tree/master/native use crate::{ - input::{ - keyboard::{self, KeyCode, ModifiersState}, - mouse, ButtonState, - }, - window, Event, Mode, MouseCursor, + keyboard::{self, KeyCode, ModifiersState}, + mouse, window, Event, Mode, Point, }; /// Converts a winit window event into an iced event. @@ -36,9 +33,15 @@ pub fn window_event( })) } WindowEvent::MouseInput { button, state, .. } => { - Some(Event::Mouse(mouse::Event::Input { - button: mouse_button(*button), - state: button_state(*state), + let button = mouse_button(*button); + + Some(Event::Mouse(match state { + winit::event::ElementState::Pressed => { + mouse::Event::ButtonPressed(button) + } + winit::event::ElementState::Released => { + mouse::Event::ButtonReleased(button) + } })) } WindowEvent::MouseWheel { delta, .. } => match delta { @@ -70,10 +73,24 @@ pub fn window_event( .. }, .. - } => Some(Event::Keyboard(keyboard::Event::Input { - key_code: key_code(*virtual_keycode), - state: button_state(*state), - modifiers: modifiers_state(modifiers), + } => Some(Event::Keyboard({ + let key_code = key_code(*virtual_keycode); + let modifiers = modifiers_state(modifiers); + + match state { + winit::event::ElementState::Pressed => { + keyboard::Event::KeyPressed { + key_code, + modifiers, + } + } + winit::event::ElementState::Released => { + keyboard::Event::KeyReleased { + key_code, + modifiers, + } + } + } })), WindowEvent::HoveredFile(path) => { Some(Event::Window(window::Event::FileHovered(path.clone()))) @@ -108,19 +125,23 @@ pub fn fullscreen( /// /// [`winit`]: https://github.com/rust-windowing/winit /// [`iced_native`]: https://github.com/hecrj/iced/tree/master/native -pub fn mouse_cursor(mouse_cursor: MouseCursor) -> winit::window::CursorIcon { - match mouse_cursor { - MouseCursor::OutOfBounds => winit::window::CursorIcon::Default, - MouseCursor::Idle => winit::window::CursorIcon::Default, - MouseCursor::Pointer => winit::window::CursorIcon::Hand, - MouseCursor::Working => winit::window::CursorIcon::Progress, - MouseCursor::Grab => winit::window::CursorIcon::Grab, - MouseCursor::Grabbing => winit::window::CursorIcon::Grabbing, - MouseCursor::Text => winit::window::CursorIcon::Text, - MouseCursor::ResizingHorizontally => { +pub fn mouse_interaction( + interaction: mouse::Interaction, +) -> winit::window::CursorIcon { + use mouse::Interaction; + + match interaction { + Interaction::Idle => winit::window::CursorIcon::Default, + Interaction::Pointer => winit::window::CursorIcon::Hand, + Interaction::Working => winit::window::CursorIcon::Progress, + Interaction::Grab => winit::window::CursorIcon::Grab, + Interaction::Grabbing => winit::window::CursorIcon::Grabbing, + Interaction::Crosshair => winit::window::CursorIcon::Crosshair, + Interaction::Text => winit::window::CursorIcon::Text, + Interaction::ResizingHorizontally => { winit::window::CursorIcon::EwResize } - MouseCursor::ResizingVertically => winit::window::CursorIcon::NsResize, + Interaction::ResizingVertically => winit::window::CursorIcon::NsResize, } } @@ -137,17 +158,6 @@ pub fn mouse_button(mouse_button: winit::event::MouseButton) -> mouse::Button { } } -/// Converts an `ElementState` from [`winit`] to an [`iced_native`] button state. -/// -/// [`winit`]: https://github.com/rust-windowing/winit -/// [`iced_native`]: https://github.com/hecrj/iced/tree/master/native -pub fn button_state(element_state: winit::event::ElementState) -> ButtonState { - match element_state { - winit::event::ElementState::Pressed => ButtonState::Pressed, - winit::event::ElementState::Released => ButtonState::Released, - } -} - /// Converts some `ModifiersState` from [`winit`] to an [`iced_native`] /// modifiers state. /// @@ -164,6 +174,16 @@ pub fn modifiers_state( } } +/// Converts a physical cursor position to a logical `Point`. +pub fn cursor_position( + position: winit::dpi::PhysicalPosition<f64>, + scale_factor: f64, +) -> Point { + let logical_position = position.to_logical(scale_factor); + + Point::new(logical_position.x, logical_position.y) +} + /// Converts a `VirtualKeyCode` from [`winit`] to an [`iced_native`] key code. /// /// [`winit`]: https://github.com/rust-windowing/winit diff --git a/winit/src/debug/basic.rs b/winit/src/debug/basic.rs deleted file mode 100644 index d46edba6..00000000 --- a/winit/src/debug/basic.rs +++ /dev/null @@ -1,211 +0,0 @@ -use std::{collections::VecDeque, time}; - -#[derive(Debug)] -pub struct Debug { - is_enabled: bool, - - startup_start: time::Instant, - startup_duration: time::Duration, - - update_start: time::Instant, - update_durations: TimeBuffer, - - view_start: time::Instant, - view_durations: TimeBuffer, - - layout_start: time::Instant, - layout_durations: TimeBuffer, - - event_start: time::Instant, - event_durations: TimeBuffer, - - draw_start: time::Instant, - draw_durations: TimeBuffer, - - render_start: time::Instant, - render_durations: TimeBuffer, - - message_count: usize, - last_messages: VecDeque<String>, -} - -impl Debug { - pub fn new() -> Self { - let now = time::Instant::now(); - - Self { - is_enabled: false, - startup_start: now, - startup_duration: time::Duration::from_secs(0), - - update_start: now, - update_durations: TimeBuffer::new(200), - - view_start: now, - view_durations: TimeBuffer::new(200), - - layout_start: now, - layout_durations: TimeBuffer::new(200), - - event_start: now, - event_durations: TimeBuffer::new(200), - - draw_start: now, - draw_durations: TimeBuffer::new(200), - - render_start: now, - render_durations: TimeBuffer::new(50), - - message_count: 0, - last_messages: VecDeque::new(), - } - } - - pub fn toggle(&mut self) { - self.is_enabled = !self.is_enabled; - } - - pub fn startup_started(&mut self) { - self.startup_start = time::Instant::now(); - } - - pub fn startup_finished(&mut self) { - self.startup_duration = time::Instant::now() - self.startup_start; - } - - pub fn update_started(&mut self) { - self.update_start = time::Instant::now(); - } - - pub fn update_finished(&mut self) { - self.update_durations - .push(time::Instant::now() - self.update_start); - } - - pub fn view_started(&mut self) { - self.view_start = time::Instant::now(); - } - - pub fn view_finished(&mut self) { - self.view_durations - .push(time::Instant::now() - self.view_start); - } - - pub fn layout_started(&mut self) { - self.layout_start = time::Instant::now(); - } - - pub fn layout_finished(&mut self) { - self.layout_durations - .push(time::Instant::now() - self.layout_start); - } - - pub fn event_processing_started(&mut self) { - self.event_start = time::Instant::now(); - } - - pub fn event_processing_finished(&mut self) { - self.event_durations - .push(time::Instant::now() - self.event_start); - } - - pub fn draw_started(&mut self) { - self.draw_start = time::Instant::now(); - } - - pub fn draw_finished(&mut self) { - self.draw_durations - .push(time::Instant::now() - self.draw_start); - } - - pub fn render_started(&mut self) { - self.render_start = time::Instant::now(); - } - - pub fn render_finished(&mut self) { - self.render_durations - .push(time::Instant::now() - self.render_start); - } - - pub fn log_message<Message: std::fmt::Debug>(&mut self, message: &Message) { - self.last_messages.push_back(format!("{:?}", message)); - - if self.last_messages.len() > 10 { - let _ = self.last_messages.pop_front(); - } - - self.message_count += 1; - } - - pub fn overlay(&self) -> Vec<String> { - if !self.is_enabled { - return Vec::new(); - } - - let mut lines = Vec::new(); - - fn key_value<T: std::fmt::Debug>(key: &str, value: T) -> String { - format!("{} {:?}", key, value) - } - - lines.push(format!( - "{} {} - {}", - env!("CARGO_PKG_NAME"), - env!("CARGO_PKG_VERSION"), - env!("CARGO_PKG_REPOSITORY"), - )); - lines.push(key_value("Startup:", self.startup_duration)); - lines.push(key_value("Update:", self.update_durations.average())); - lines.push(key_value("View:", self.view_durations.average())); - lines.push(key_value("Layout:", self.layout_durations.average())); - lines.push(key_value( - "Event processing:", - self.event_durations.average(), - )); - lines.push(key_value( - "Primitive generation:", - self.draw_durations.average(), - )); - lines.push(key_value("Render:", self.render_durations.average())); - lines.push(key_value("Message count:", self.message_count)); - lines.push(String::from("Last messages:")); - lines.extend( - self.last_messages.iter().map(|msg| format!(" {}", msg)), - ); - - lines - } -} - -#[derive(Debug)] -struct TimeBuffer { - head: usize, - size: usize, - contents: Vec<time::Duration>, -} - -impl TimeBuffer { - fn new(capacity: usize) -> TimeBuffer { - TimeBuffer { - head: 0, - size: 0, - contents: vec![time::Duration::from_secs(0); capacity], - } - } - - fn push(&mut self, duration: time::Duration) { - self.head = (self.head + 1) % self.contents.len(); - self.contents[self.head] = duration; - self.size = (self.size + 1).min(self.contents.len()); - } - - fn average(&self) -> time::Duration { - let sum: time::Duration = if self.size == self.contents.len() { - self.contents[..].iter().sum() - } else { - self.contents[..self.size].iter().sum() - }; - - sum / self.size.max(1) as u32 - } -} diff --git a/winit/src/debug/null.rs b/winit/src/debug/null.rs deleted file mode 100644 index 2a9430cd..00000000 --- a/winit/src/debug/null.rs +++ /dev/null @@ -1,46 +0,0 @@ -#[derive(Debug)] -pub struct Debug; - -impl Debug { - pub fn new() -> Self { - Self - } - - pub fn startup_started(&mut self) {} - - pub fn startup_finished(&mut self) {} - - pub fn update_started(&mut self) {} - - pub fn update_finished(&mut self) {} - - pub fn view_started(&mut self) {} - - pub fn view_finished(&mut self) {} - - pub fn layout_started(&mut self) {} - - pub fn layout_finished(&mut self) {} - - pub fn event_processing_started(&mut self) {} - - pub fn event_processing_finished(&mut self) {} - - pub fn draw_started(&mut self) {} - - pub fn draw_finished(&mut self) {} - - pub fn render_started(&mut self) {} - - pub fn render_finished(&mut self) {} - - pub fn log_message<Message: std::fmt::Debug>( - &mut self, - _message: &Message, - ) { - } - - pub fn overlay(&self) -> Vec<String> { - Vec::new() - } -} diff --git a/winit/src/lib.rs b/winit/src/lib.rs index f99e1290..bdab3ed7 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -25,28 +25,18 @@ pub use iced_native::*; pub use winit; +pub mod application; pub mod conversion; pub mod settings; -mod application; mod clipboard; mod mode; mod proxy; -mod size; - -// We disable debug capabilities on release builds unless the `debug` feature -// is explicitly enabled. -#[cfg(feature = "debug")] -#[path = "debug/basic.rs"] -mod debug; -#[cfg(not(feature = "debug"))] -#[path = "debug/null.rs"] -mod debug; pub use application::Application; pub use clipboard::Clipboard; pub use mode::Mode; +pub use proxy::Proxy; pub use settings::Settings; -use debug::Debug; -use proxy::Proxy; +pub use iced_graphics::Viewport; diff --git a/winit/src/proxy.rs b/winit/src/proxy.rs index cff6ca72..532f8c56 100644 --- a/winit/src/proxy.rs +++ b/winit/src/proxy.rs @@ -5,6 +5,8 @@ use iced_native::futures::{ }; use std::pin::Pin; +/// An event loop proxy that implements `Sink`. +#[derive(Debug)] pub struct Proxy<Message: 'static> { raw: winit::event_loop::EventLoopProxy<Message>, } @@ -18,6 +20,9 @@ impl<Message: 'static> Clone for Proxy<Message> { } impl<Message: 'static> Proxy<Message> { + /// Creates a new [`Proxy`] from an `EventLoopProxy`. + /// + /// [`Proxy`]: struct.Proxy.html pub fn new(raw: winit::event_loop::EventLoopProxy<Message>) -> Self { Self { raw } } diff --git a/winit/src/settings.rs b/winit/src/settings.rs index d58c51f0..6799f23f 100644 --- a/winit/src/settings.rs +++ b/winit/src/settings.rs @@ -8,6 +8,11 @@ mod platform; pub use platform::PlatformSpecific; +use crate::conversion; +use crate::Mode; +use winit::monitor::MonitorHandle; +use winit::window::WindowBuilder; + /// The settings of an application. #[derive(Debug, Clone, Copy, PartialEq, Default)] pub struct Settings<Flags> { @@ -28,6 +33,12 @@ pub struct Window { /// The size of the window. pub size: (u32, u32), + /// 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 resizable or not. pub resizable: bool, @@ -38,10 +49,54 @@ pub struct Window { pub platform_specific: platform::PlatformSpecific, } +impl Window { + /// Converts the window settings into a `WindowBuilder` from `winit`. + pub fn into_builder( + self, + title: &str, + mode: Mode, + primary_monitor: MonitorHandle, + ) -> WindowBuilder { + let mut window_builder = WindowBuilder::new(); + + let (width, height) = self.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_fullscreen(conversion::fullscreen(primary_monitor, mode)); + + if let Some((width, height)) = self.min_size { + window_builder = window_builder + .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 }); + } + + #[cfg(target_os = "windows")] + { + use winit::platform::windows::WindowBuilderExtWindows; + + if let Some(parent) = self.platform_specific.parent { + window_builder = window_builder.with_parent_window(parent); + } + } + + window_builder + } +} + impl Default for Window { fn default() -> Window { Window { size: (1024, 768), + min_size: None, + max_size: None, resizable: true, decorations: true, platform_specific: Default::default(), diff --git a/winit/src/size.rs b/winit/src/size.rs deleted file mode 100644 index 7e3056d4..00000000 --- a/winit/src/size.rs +++ /dev/null @@ -1,30 +0,0 @@ -pub struct Size { - physical: winit::dpi::PhysicalSize<u32>, - logical: winit::dpi::LogicalSize<f64>, - scale_factor: f64, -} - -impl Size { - pub fn new( - physical: winit::dpi::PhysicalSize<u32>, - scale_factor: f64, - ) -> Size { - Size { - logical: physical.to_logical(scale_factor), - physical, - scale_factor, - } - } - - pub fn physical(&self) -> winit::dpi::PhysicalSize<u32> { - self.physical - } - - pub fn logical(&self) -> winit::dpi::LogicalSize<f64> { - self.logical - } - - pub fn scale_factor(&self) -> f64 { - self.scale_factor - } -} |