diff options
31 files changed, 713 insertions, 177 deletions
diff --git a/core/src/rectangle.rs b/core/src/rectangle.rs index cff33991..14d2a2e8 100644 --- a/core/src/rectangle.rs +++ b/core/src/rectangle.rs @@ -143,6 +143,20 @@ impl Rectangle<f32> { && point.y < self.y + self.height } + /// Returns the minimum distance from the given [`Point`] to any of the edges + /// of the [`Rectangle`]. + pub fn distance(&self, point: Point) -> f32 { + let center = self.center(); + + let distance_x = + ((point.x - center.x).abs() - self.width / 2.0).max(0.0); + + let distance_y = + ((point.y - center.y).abs() - self.height / 2.0).max(0.0); + + distance_x.hypot(distance_y) + } + /// Returns true if the current [`Rectangle`] is completely within the given /// `container`. pub fn is_within(&self, container: &Rectangle) -> bool { diff --git a/core/src/time.rs b/core/src/time.rs index dcfe4e41..c6e30444 100644 --- a/core/src/time.rs +++ b/core/src/time.rs @@ -2,3 +2,28 @@ pub use web_time::Duration; pub use web_time::Instant; + +/// Creates a [`Duration`] representing the given amount of milliseconds. +pub fn milliseconds(milliseconds: u64) -> Duration { + Duration::from_millis(milliseconds) +} + +/// Creates a [`Duration`] representing the given amount of seconds. +pub fn seconds(seconds: u64) -> Duration { + Duration::from_secs(seconds) +} + +/// Creates a [`Duration`] representing the given amount of minutes. +pub fn minutes(minutes: u64) -> Duration { + seconds(minutes * 60) +} + +/// Creates a [`Duration`] representing the given amount of hours. +pub fn hours(hours: u64) -> Duration { + minutes(hours * 60) +} + +/// Creates a [`Duration`] representing the given amount of days. +pub fn days(days: u64) -> Duration { + hours(days * 24) +} diff --git a/examples/arc/src/main.rs b/examples/arc/src/main.rs index 18873259..88544caa 100644 --- a/examples/arc/src/main.rs +++ b/examples/arc/src/main.rs @@ -4,6 +4,7 @@ use iced::mouse; use iced::widget::canvas::{ self, stroke, Cache, Canvas, Geometry, Path, Stroke, }; +use iced::window; use iced::{Element, Fill, Point, Rectangle, Renderer, Subscription, Theme}; pub fn main() -> iced::Result { @@ -34,8 +35,7 @@ impl Arc { } fn subscription(&self) -> Subscription<Message> { - iced::time::every(std::time::Duration::from_millis(10)) - .map(|_| Message::Tick) + window::frames().map(|_| Message::Tick) } } diff --git a/examples/bezier_tool/src/main.rs b/examples/bezier_tool/src/main.rs index e8f0efc9..4d438bd9 100644 --- a/examples/bezier_tool/src/main.rs +++ b/examples/bezier_tool/src/main.rs @@ -1,6 +1,6 @@ //! This example showcases an interactive `Canvas` for drawing Bézier curves. -use iced::widget::{button, container, horizontal_space, hover}; -use iced::{Element, Fill, Theme}; +use iced::widget::{button, container, horizontal_space, hover, right}; +use iced::{Element, Theme}; pub fn main() -> iced::Result { iced::application("Bezier Tool - Iced", Example::update, Example::view) @@ -41,13 +41,12 @@ impl Example { if self.curves.is_empty() { container(horizontal_space()) } else { - container( + right( button("Clear") .style(button::danger) .on_press(Message::Clear), ) .padding(10) - .align_right(Fill) }, )) .padding(20) diff --git a/examples/clock/src/main.rs b/examples/clock/src/main.rs index 7d11a3b5..0810594f 100644 --- a/examples/clock/src/main.rs +++ b/examples/clock/src/main.rs @@ -1,5 +1,5 @@ use iced::mouse; -use iced::time; +use iced::time::{self, milliseconds}; use iced::widget::canvas::{stroke, Cache, Geometry, LineCap, Path, Stroke}; use iced::widget::{canvas, container}; use iced::{alignment, Radians}; @@ -49,7 +49,7 @@ impl Clock { } fn subscription(&self) -> Subscription<Message> { - time::every(time::Duration::from_millis(500)) + time::every(milliseconds(500)) .map(|_| Message::Tick(chrono::offset::Local::now())) } diff --git a/examples/editor/src/main.rs b/examples/editor/src/main.rs index d55f9bdf..7032324a 100644 --- a/examples/editor/src/main.rs +++ b/examples/editor/src/main.rs @@ -1,8 +1,8 @@ use iced::highlighter; use iced::keyboard; use iced::widget::{ - self, button, column, container, horizontal_space, pick_list, row, text, - text_editor, toggler, tooltip, + self, button, center_x, column, container, horizontal_space, pick_list, + row, text, text_editor, toggler, tooltip, }; use iced::{Center, Element, Fill, Font, Task, Theme}; @@ -288,7 +288,7 @@ fn action<'a, Message: Clone + 'a>( label: &'a str, on_press: Option<Message>, ) -> Element<'a, Message> { - let action = button(container(content).center_x(30)); + let action = button(center_x(content).width(30)); if let Some(on_press) = on_press { tooltip( diff --git a/examples/game_of_life/src/main.rs b/examples/game_of_life/src/main.rs index 7a7224d5..1008e477 100644 --- a/examples/game_of_life/src/main.rs +++ b/examples/game_of_life/src/main.rs @@ -5,12 +5,11 @@ mod preset; use grid::Grid; use preset::Preset; -use iced::time; +use iced::time::{self, milliseconds}; use iced::widget::{ button, checkbox, column, container, pick_list, row, slider, text, }; use iced::{Center, Element, Fill, Subscription, Task, Theme}; -use std::time::Duration; pub fn main() -> iced::Result { tracing_subscriber::fmt::init(); @@ -112,7 +111,7 @@ impl GameOfLife { fn subscription(&self) -> Subscription<Message> { if self.is_playing { - time::every(Duration::from_millis(1000 / self.speed as u64)) + time::every(milliseconds(1000 / self.speed as u64)) .map(|_| Message::Tick) } else { Subscription::none() @@ -191,6 +190,7 @@ mod grid { use crate::Preset; use iced::alignment; use iced::mouse; + use iced::time::{Duration, Instant}; use iced::touch; use iced::widget::canvas; use iced::widget::canvas::{ @@ -202,7 +202,6 @@ mod grid { use rustc_hash::{FxHashMap, FxHashSet}; use std::future::Future; use std::ops::RangeInclusive; - use std::time::{Duration, Instant}; pub struct Grid { state: State, diff --git a/examples/geometry/src/main.rs b/examples/geometry/src/main.rs index d53ae6a5..44214c63 100644 --- a/examples/geometry/src/main.rs +++ b/examples/geometry/src/main.rs @@ -152,8 +152,8 @@ mod rainbow { } } -use iced::widget::{column, container, scrollable}; -use iced::{Element, Length}; +use iced::widget::{center_x, center_y, column, scrollable}; +use iced::Element; use rainbow::rainbow; pub fn main() -> iced::Result { @@ -176,7 +176,7 @@ fn view(_state: &()) -> Element<'_, ()> { .spacing(20) .max_width(500); - let scrollable = scrollable(container(content).center_x(Length::Fill)); + let scrollable = scrollable(center_x(content)); - container(scrollable).center_y(Length::Fill).into() + center_y(scrollable).into() } diff --git a/examples/integration/src/controls.rs b/examples/integration/src/controls.rs index 0b11a323..b92e4987 100644 --- a/examples/integration/src/controls.rs +++ b/examples/integration/src/controls.rs @@ -1,6 +1,6 @@ use iced_wgpu::Renderer; -use iced_widget::{column, container, row, slider, text, text_input}; -use iced_winit::core::{Color, Element, Length::*, Theme}; +use iced_widget::{bottom, column, row, slider, text, text_input}; +use iced_winit::core::{Color, Element, Theme}; use iced_winit::runtime::{Program, Task}; pub struct Controls { @@ -74,18 +74,17 @@ impl Program for Controls { .width(500) .spacing(20); - container( + bottom( column![ text("Background color").color(Color::WHITE), text!("{background_color:?}").size(14).color(Color::WHITE), - text_input("Placeholder", &self.input) - .on_input(Message::InputChanged), sliders, + text_input("Type something...", &self.input) + .on_input(Message::InputChanged), ] .spacing(10), ) .padding(10) - .align_bottom(Fill) .into() } } diff --git a/examples/layout/src/main.rs b/examples/layout/src/main.rs index e83a1f7d..b298dce4 100644 --- a/examples/layout/src/main.rs +++ b/examples/layout/src/main.rs @@ -2,9 +2,9 @@ use iced::border; use iced::keyboard; use iced::mouse; use iced::widget::{ - button, canvas, center, checkbox, column, container, horizontal_rule, - horizontal_space, pick_list, pin, row, scrollable, stack, text, - vertical_rule, + button, canvas, center, center_y, checkbox, column, container, + horizontal_rule, horizontal_space, pick_list, pin, row, scrollable, stack, + text, vertical_rule, }; use iced::{ color, Center, Element, Fill, Font, Length, Point, Rectangle, Renderer, @@ -253,15 +253,14 @@ fn application<'a>() -> Element<'a, Message> { .border(border::color(palette.background.strong.color).width(1)) }); - let sidebar = container( + let sidebar = center_y( column!["Sidebar!", square(50), square(50)] .spacing(40) .padding(10) .width(200) .align_x(Center), ) - .style(container::rounded_box) - .center_y(Fill); + .style(container::rounded_box); let content = container( scrollable( diff --git a/examples/multi_window/src/main.rs b/examples/multi_window/src/main.rs index b43a627a..f9021c8d 100644 --- a/examples/multi_window/src/main.rs +++ b/examples/multi_window/src/main.rs @@ -1,5 +1,5 @@ use iced::widget::{ - button, center, column, container, horizontal_space, scrollable, text, + button, center, center_x, column, horizontal_space, scrollable, text, text_input, }; use iced::window; @@ -193,6 +193,6 @@ impl Window { .align_x(Center), ); - container(content).center_x(200).into() + center_x(content).width(200).into() } } diff --git a/examples/pane_grid/src/main.rs b/examples/pane_grid/src/main.rs index 67f4d27f..17ba5804 100644 --- a/examples/pane_grid/src/main.rs +++ b/examples/pane_grid/src/main.rs @@ -1,7 +1,7 @@ use iced::keyboard; use iced::widget::pane_grid::{self, PaneGrid}; use iced::widget::{ - button, column, container, responsive, row, scrollable, text, + button, center_y, column, container, responsive, row, scrollable, text, }; use iced::{Center, Color, Element, Fill, Size, Subscription}; @@ -196,11 +196,7 @@ impl Example { .on_drag(Message::Dragged) .on_resize(10, Message::Resized); - container(pane_grid) - .width(Fill) - .height(Fill) - .padding(10) - .into() + container(pane_grid).padding(10).into() } } @@ -295,10 +291,7 @@ fn view_content<'a>( .spacing(10) .align_x(Center); - container(scrollable(content)) - .center_y(Fill) - .padding(5) - .into() + center_y(scrollable(content)).padding(5).into() } fn view_controls<'a>( diff --git a/examples/progress_bar/src/main.rs b/examples/progress_bar/src/main.rs index 67da62f2..e431a404 100644 --- a/examples/progress_bar/src/main.rs +++ b/examples/progress_bar/src/main.rs @@ -1,4 +1,7 @@ -use iced::widget::{column, progress_bar, slider}; +use iced::widget::{ + center, center_x, checkbox, column, progress_bar, row, slider, + vertical_slider, +}; use iced::Element; pub fn main() -> iced::Result { @@ -8,25 +11,58 @@ pub fn main() -> iced::Result { #[derive(Default)] struct Progress { value: f32, + is_vertical: bool, } #[derive(Debug, Clone, Copy)] enum Message { SliderChanged(f32), + ToggleVertical(bool), } impl Progress { fn update(&mut self, message: Message) { match message { Message::SliderChanged(x) => self.value = x, + Message::ToggleVertical(is_vertical) => { + self.is_vertical = is_vertical + } } } fn view(&self) -> Element<Message> { + let bar = progress_bar(0.0..=100.0, self.value); + column![ - progress_bar(0.0..=100.0, self.value), - slider(0.0..=100.0, self.value, Message::SliderChanged).step(0.01) + if self.is_vertical { + center( + row![ + bar.vertical(), + vertical_slider( + 0.0..=100.0, + self.value, + Message::SliderChanged + ) + .step(0.01) + ] + .spacing(20), + ) + } else { + center( + column![ + bar, + slider(0.0..=100.0, self.value, Message::SliderChanged) + .step(0.01) + ] + .spacing(20), + ) + }, + center_x( + checkbox("Vertical", self.is_vertical) + .on_toggle(Message::ToggleVertical) + ), ] + .spacing(20) .padding(20) .into() } diff --git a/examples/screenshot/src/main.rs b/examples/screenshot/src/main.rs index 5c105f6c..7766542d 100644 --- a/examples/screenshot/src/main.rs +++ b/examples/screenshot/src/main.rs @@ -1,5 +1,7 @@ use iced::keyboard; -use iced::widget::{button, column, container, image, row, text, text_input}; +use iced::widget::{ + button, center_y, column, container, image, row, text, text_input, +}; use iced::window; use iced::window::screenshot::{self, Screenshot}; use iced::{ @@ -131,8 +133,8 @@ impl Example { text("Press the button to take a screenshot!").into() }; - let image = container(image) - .center_y(FillPortion(2)) + let image = center_y(image) + .height(FillPortion(2)) .padding(10) .style(container::rounded_box); @@ -211,7 +213,7 @@ impl Example { .spacing(40) }; - let side_content = container(controls).center_y(Fill); + let side_content = center_y(controls); let content = row![side_content, image] .spacing(10) diff --git a/examples/stopwatch/src/main.rs b/examples/stopwatch/src/main.rs index 0d824d36..a814da55 100644 --- a/examples/stopwatch/src/main.rs +++ b/examples/stopwatch/src/main.rs @@ -1,10 +1,8 @@ use iced::keyboard; -use iced::time; +use iced::time::{self, milliseconds, Duration, Instant}; use iced::widget::{button, center, column, row, text}; use iced::{Center, Element, Subscription, Theme}; -use std::time::{Duration, Instant}; - pub fn main() -> iced::Result { iced::application("Stopwatch - Iced", Stopwatch::update, Stopwatch::view) .subscription(Stopwatch::subscription) @@ -63,7 +61,7 @@ impl Stopwatch { let tick = match self.state { State::Idle => Subscription::none(), State::Ticking { .. } => { - time::every(Duration::from_millis(10)).map(Message::Tick) + time::every(milliseconds(10)).map(Message::Tick) } }; diff --git a/examples/svg/src/main.rs b/examples/svg/src/main.rs index 02cb85cc..c4be8fb8 100644 --- a/examples/svg/src/main.rs +++ b/examples/svg/src/main.rs @@ -1,4 +1,4 @@ -use iced::widget::{center, checkbox, column, container, svg}; +use iced::widget::{center, center_x, checkbox, column, svg}; use iced::{color, Element, Fill}; pub fn main() -> iced::Result { @@ -46,12 +46,8 @@ impl Tiger { checkbox("Apply a color filter", self.apply_color_filter) .on_toggle(Message::ToggleColorFilter); - center( - column![svg, container(apply_color_filter).center_x(Fill)] - .spacing(20) - .height(Fill), - ) - .padding(20) - .into() + center(column![svg, center_x(apply_color_filter)].spacing(20)) + .padding(20) + .into() } } diff --git a/examples/the_matrix/src/main.rs b/examples/the_matrix/src/main.rs index c6b20ece..315e9ee5 100644 --- a/examples/the_matrix/src/main.rs +++ b/examples/the_matrix/src/main.rs @@ -1,5 +1,5 @@ use iced::mouse; -use iced::time::{self, Instant}; +use iced::time::{self, milliseconds, Instant}; use iced::widget::canvas; use iced::{ Color, Element, Fill, Font, Point, Rectangle, Renderer, Subscription, Theme, @@ -40,7 +40,7 @@ impl TheMatrix { } fn subscription(&self) -> Subscription<Message> { - time::every(std::time::Duration::from_millis(50)).map(Message::Tick) + time::every(milliseconds(50)).map(Message::Tick) } } diff --git a/examples/toast/src/main.rs b/examples/toast/src/main.rs index a1b5886f..2ae9bfe2 100644 --- a/examples/toast/src/main.rs +++ b/examples/toast/src/main.rs @@ -162,7 +162,6 @@ impl Default for App { mod toast { use std::fmt; - use std::time::{Duration, Instant}; use iced::advanced::layout::{self, Layout}; use iced::advanced::overlay; @@ -171,6 +170,7 @@ mod toast { use iced::advanced::{Clipboard, Shell, Widget}; use iced::mouse; use iced::theme; + use iced::time::{self, Duration, Instant}; use iced::widget::{ button, column, container, horizontal_rule, horizontal_space, row, text, }; @@ -502,9 +502,8 @@ mod toast { self.instants.iter_mut().enumerate().for_each( |(index, maybe_instant)| { if let Some(instant) = maybe_instant.as_mut() { - let remaining = - Duration::from_secs(self.timeout_secs) - .saturating_sub(instant.elapsed()); + let remaining = time::seconds(self.timeout_secs) + .saturating_sub(instant.elapsed()); if remaining == Duration::ZERO { maybe_instant.take(); diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index e86e23b5..7759552c 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -1,6 +1,6 @@ use iced::keyboard; use iced::widget::{ - self, button, center, checkbox, column, container, keyed_column, row, + self, button, center, center_x, checkbox, column, keyed_column, row, scrollable, text, text_input, Text, }; use iced::window; @@ -237,7 +237,7 @@ impl Todos { .spacing(20) .max_width(800); - scrollable(container(content).center_x(Fill).padding(40)).into() + scrollable(center_x(content).padding(40)).into() } } } diff --git a/examples/tour/src/main.rs b/examples/tour/src/main.rs index d8c0b29a..32720c47 100644 --- a/examples/tour/src/main.rs +++ b/examples/tour/src/main.rs @@ -1,6 +1,6 @@ use iced::widget::{ - button, checkbox, column, container, horizontal_space, image, radio, row, - scrollable, slider, text, text_input, toggler, vertical_space, + button, center_x, center_y, checkbox, column, horizontal_space, image, + radio, row, scrollable, slider, text, text_input, toggler, vertical_space, }; use iced::widget::{Button, Column, Container, Slider}; use iced::{Center, Color, Element, Fill, Font, Pixels}; @@ -166,16 +166,13 @@ impl Tour { .padding(20) .into(); - let scrollable = scrollable( - container(if self.debug { - content.explain(Color::BLACK) - } else { - content - }) - .center_x(Fill), - ); + let scrollable = scrollable(center_x(if self.debug { + content.explain(Color::BLACK) + } else { + content + })); - container(scrollable).center_y(Fill).into() + center_y(scrollable).into() } fn can_continue(&self) -> bool { @@ -543,7 +540,7 @@ fn ferris<'a>( width: u16, filter_method: image::FilterMethod, ) -> Container<'a, Message> { - container( + center_x( // This should go away once we unify resource loading on native // platforms if cfg!(target_arch = "wasm32") { @@ -554,7 +551,6 @@ fn ferris<'a>( .filter_method(filter_method) .width(width), ) - .center_x(Fill) } fn padded_button<Message: Clone>(label: &str) -> Button<'_, Message> { diff --git a/futures/src/backend/native/tokio.rs b/futures/src/backend/native/tokio.rs index 9dc3593d..e0be83a6 100644 --- a/futures/src/backend/native/tokio.rs +++ b/futures/src/backend/native/tokio.rs @@ -22,40 +22,25 @@ impl crate::Executor for Executor { pub mod time { //! Listen and react to time. - use crate::subscription::{self, Hasher, Subscription}; + use crate::core::time::{Duration, Instant}; + use crate::stream; + use crate::subscription::Subscription; + use crate::MaybeSend; + + use futures::SinkExt; + use std::future::Future; /// Returns a [`Subscription`] that produces messages at a set interval. /// /// The first message is produced after a `duration`, and then continues to /// produce more messages every `duration` after that. - pub fn every( - duration: std::time::Duration, - ) -> Subscription<std::time::Instant> { - subscription::from_recipe(Every(duration)) - } - - #[derive(Debug)] - struct Every(std::time::Duration); - - impl subscription::Recipe for Every { - type Output = std::time::Instant; - - fn hash(&self, state: &mut Hasher) { - use std::hash::Hash; - - std::any::TypeId::of::<Self>().hash(state); - self.0.hash(state); - } - - fn stream( - self: Box<Self>, - _input: subscription::EventStream, - ) -> futures::stream::BoxStream<'static, Self::Output> { + pub fn every(duration: Duration) -> Subscription<Instant> { + Subscription::run_with(duration, |duration| { use futures::stream::StreamExt; - let start = tokio::time::Instant::now() + self.0; + let start = tokio::time::Instant::now() + *duration; - let mut interval = tokio::time::interval_at(start, self.0); + let mut interval = tokio::time::interval_at(start, *duration); interval.set_missed_tick_behavior( tokio::time::MissedTickBehavior::Skip, ); @@ -67,6 +52,27 @@ pub mod time { }; stream.map(tokio::time::Instant::into_std).boxed() - } + }) + } + + /// Returns a [`Subscription`] that runs the given async function at a + /// set interval; producing the result of the function as output. + pub fn repeat<F, T>(f: fn() -> F, interval: Duration) -> Subscription<T> + where + F: Future<Output = T> + MaybeSend + 'static, + T: MaybeSend + 'static, + { + Subscription::run_with((f, interval), |(f, interval)| { + let f = *f; + let interval = *interval; + + stream::channel(1, move |mut output| async move { + loop { + let _ = output.send(f().await).await; + + tokio::time::sleep(interval).await; + } + }) + }) } } diff --git a/futures/src/subscription.rs b/futures/src/subscription.rs index eaea1a1f..82cba9a1 100644 --- a/futures/src/subscription.rs +++ b/futures/src/subscription.rs @@ -202,8 +202,8 @@ impl<T> Subscription<T> { T: 'static, { from_recipe(Runner { - id: builder, - spawn: move |_| builder(), + data: builder, + spawn: |builder, _| builder(), }) } @@ -211,15 +211,15 @@ impl<T> Subscription<T> { /// given [`Stream`]. /// /// The `id` will be used to uniquely identify the [`Subscription`]. - pub fn run_with_id<I, S>(id: I, stream: S) -> Subscription<T> + pub fn run_with<D, S>(data: D, builder: fn(&D) -> S) -> Self where - I: Hash + 'static, + D: Hash + 'static, S: Stream<Item = T> + MaybeSend + 'static, T: 'static, { from_recipe(Runner { - id, - spawn: move |_| stream, + data: (data, builder), + spawn: |(data, builder), _| builder(data), }) } @@ -423,8 +423,8 @@ where T: 'static + MaybeSend, { from_recipe(Runner { - id, - spawn: |events| { + data: id, + spawn: |_, events| { use futures::future; use futures::stream::StreamExt; @@ -435,27 +435,27 @@ where struct Runner<I, F, S, T> where - F: FnOnce(EventStream) -> S, + F: FnOnce(&I, EventStream) -> S, S: Stream<Item = T>, { - id: I, + data: I, spawn: F, } impl<I, F, S, T> Recipe for Runner<I, F, S, T> where I: Hash + 'static, - F: FnOnce(EventStream) -> S, + F: FnOnce(&I, EventStream) -> S, S: Stream<Item = T> + MaybeSend + 'static, { type Output = T; fn hash(&self, state: &mut Hasher) { std::any::TypeId::of::<I>().hash(state); - self.id.hash(state); + self.data.hash(state); } fn stream(self: Box<Self>, input: EventStream) -> BoxStream<Self::Output> { - crate::boxed_stream((self.spawn)(input)) + crate::boxed_stream((self.spawn)(&self.data, input)) } } @@ -365,9 +365,9 @@ //! //! As with tasks, some modules expose convenient functions that build a [`Subscription`] for you—like //! [`time::every`] which can be used to listen to time, or [`keyboard::on_key_press`] which will notify you -//! of any key presses. But you can also create your own with [`Subscription::run`] and [`run_with_id`]. +//! of any key presses. But you can also create your own with [`Subscription::run`] and [`run_with`]. //! -//! [`run_with_id`]: Subscription::run_with_id +//! [`run_with`]: Subscription::run_with //! //! ## Scaling Applications //! The `update`, `view`, and `Message` triplet composes very nicely. diff --git a/src/time.rs b/src/time.rs index 26d31c0a..98a800ac 100644 --- a/src/time.rs +++ b/src/time.rs @@ -1,5 +1,5 @@ //! Listen and react to time. -pub use crate::core::time::{Duration, Instant}; +pub use crate::core::time::*; #[allow(unused_imports)] #[cfg_attr( diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index d79f0dc8..8e099af1 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -145,7 +145,19 @@ impl Renderer { self.text_viewport.update(queue, viewport.physical_size()); + let physical_bounds = Rectangle::<f32>::from(Rectangle::with_size( + viewport.physical_size(), + )); + for layer in self.layers.iter_mut() { + if physical_bounds + .intersection(&(layer.bounds * scale_factor)) + .and_then(Rectangle::snap) + .is_none() + { + continue; + } + if !layer.quads.is_empty() { engine.quad_pipeline.prepare( device, @@ -268,16 +280,13 @@ impl Renderer { let scale = Transformation::scale(scale_factor); for layer in self.layers.iter() { - let Some(physical_bounds) = - physical_bounds.intersection(&(layer.bounds * scale)) + let Some(scissor_rect) = physical_bounds + .intersection(&(layer.bounds * scale_factor)) + .and_then(Rectangle::snap) else { continue; }; - let Some(scissor_rect) = physical_bounds.snap() else { - continue; - }; - if !layer.quads.is_empty() { engine.quad_pipeline.render( quad_layer, diff --git a/widget/src/helpers.rs b/widget/src/helpers.rs index 5a0f8107..17cf94cc 100644 --- a/widget/src/helpers.rs +++ b/widget/src/helpers.rs @@ -24,7 +24,7 @@ use crate::text_input::{self, TextInput}; use crate::toggler::{self, Toggler}; use crate::tooltip::{self, Tooltip}; use crate::vertical_slider::{self, VerticalSlider}; -use crate::{Column, MouseArea, Pin, Row, Space, Stack, Themer}; +use crate::{Column, MouseArea, Pin, Pop, Row, Space, Stack, Themer}; use std::borrow::Borrow; use std::ops::RangeInclusive; @@ -232,10 +232,10 @@ where /// /// This is equivalent to: /// ```rust,no_run -/// # use iced_widget::core::Length; +/// # use iced_widget::core::Length::Fill; /// # use iced_widget::Container; /// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } -/// let centered = container("Centered!").center(Length::Fill); +/// let center = container("Center!").center(Fill); /// ``` /// /// [`Container`]: crate::Container @@ -249,6 +249,166 @@ where container(content).center(Length::Fill) } +/// Creates a new [`Container`] that fills all the available space +/// horizontally and centers its contents inside. +/// +/// This is equivalent to: +/// ```rust,no_run +/// # use iced_widget::core::Length::Fill; +/// # use iced_widget::Container; +/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } +/// let center_x = container("Horizontal Center!").center_x(Fill); +/// ``` +/// +/// [`Container`]: crate::Container +pub fn center_x<'a, Message, Theme, Renderer>( + content: impl Into<Element<'a, Message, Theme, Renderer>>, +) -> Container<'a, Message, Theme, Renderer> +where + Theme: container::Catalog + 'a, + Renderer: core::Renderer, +{ + container(content).center_x(Length::Fill) +} + +/// Creates a new [`Container`] that fills all the available space +/// vertically and centers its contents inside. +/// +/// This is equivalent to: +/// ```rust,no_run +/// # use iced_widget::core::Length::Fill; +/// # use iced_widget::Container; +/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } +/// let center_y = container("Vertical Center!").center_y(Fill); +/// ``` +/// +/// [`Container`]: crate::Container +pub fn center_y<'a, Message, Theme, Renderer>( + content: impl Into<Element<'a, Message, Theme, Renderer>>, +) -> Container<'a, Message, Theme, Renderer> +where + Theme: container::Catalog + 'a, + Renderer: core::Renderer, +{ + container(content).center_y(Length::Fill) +} + +/// Creates a new [`Container`] that fills all the available space +/// horizontally and right-aligns its contents inside. +/// +/// This is equivalent to: +/// ```rust,no_run +/// # use iced_widget::core::Length::Fill; +/// # use iced_widget::Container; +/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } +/// let right = container("Right!").align_right(Fill); +/// ``` +/// +/// [`Container`]: crate::Container +pub fn right<'a, Message, Theme, Renderer>( + content: impl Into<Element<'a, Message, Theme, Renderer>>, +) -> Container<'a, Message, Theme, Renderer> +where + Theme: container::Catalog + 'a, + Renderer: core::Renderer, +{ + container(content).align_right(Length::Fill) +} + +/// Creates a new [`Container`] that fills all the available space +/// and aligns its contents inside to the right center. +/// +/// This is equivalent to: +/// ```rust,no_run +/// # use iced_widget::core::Length::Fill; +/// # use iced_widget::Container; +/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } +/// let right_center = container("Bottom Center!").align_right(Fill).center_y(Fill); +/// ``` +/// +/// [`Container`]: crate::Container +pub fn right_center<'a, Message, Theme, Renderer>( + content: impl Into<Element<'a, Message, Theme, Renderer>>, +) -> Container<'a, Message, Theme, Renderer> +where + Theme: container::Catalog + 'a, + Renderer: core::Renderer, +{ + container(content) + .align_right(Length::Fill) + .center_y(Length::Fill) +} + +/// Creates a new [`Container`] that fills all the available space +/// vertically and bottom-aligns its contents inside. +/// +/// This is equivalent to: +/// ```rust,no_run +/// # use iced_widget::core::Length::Fill; +/// # use iced_widget::Container; +/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } +/// let bottom = container("Bottom!").align_bottom(Fill); +/// ``` +/// +/// [`Container`]: crate::Container +pub fn bottom<'a, Message, Theme, Renderer>( + content: impl Into<Element<'a, Message, Theme, Renderer>>, +) -> Container<'a, Message, Theme, Renderer> +where + Theme: container::Catalog + 'a, + Renderer: core::Renderer, +{ + container(content).align_bottom(Length::Fill) +} + +/// Creates a new [`Container`] that fills all the available space +/// and aligns its contents inside to the bottom center. +/// +/// This is equivalent to: +/// ```rust,no_run +/// # use iced_widget::core::Length::Fill; +/// # use iced_widget::Container; +/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } +/// let bottom_center = container("Bottom Center!").center_x(Fill).align_bottom(Fill); +/// ``` +/// +/// [`Container`]: crate::Container +pub fn bottom_center<'a, Message, Theme, Renderer>( + content: impl Into<Element<'a, Message, Theme, Renderer>>, +) -> Container<'a, Message, Theme, Renderer> +where + Theme: container::Catalog + 'a, + Renderer: core::Renderer, +{ + container(content) + .center_x(Length::Fill) + .align_bottom(Length::Fill) +} + +/// Creates a new [`Container`] that fills all the available space +/// and aligns its contents inside to the bottom right corner. +/// +/// This is equivalent to: +/// ```rust,no_run +/// # use iced_widget::core::Length::Fill; +/// # use iced_widget::Container; +/// # fn container<A>(x: A) -> Container<'static, ()> { unreachable!() } +/// let bottom_right = container("Bottom!").align_right(Fill).align_bottom(Fill); +/// ``` +/// +/// [`Container`]: crate::Container +pub fn bottom_right<'a, Message, Theme, Renderer>( + content: impl Into<Element<'a, Message, Theme, Renderer>>, +) -> Container<'a, Message, Theme, Renderer> +where + Theme: container::Catalog + 'a, + Renderer: core::Renderer, +{ + container(content) + .align_right(Length::Fill) + .align_bottom(Length::Fill) +} + /// Creates a new [`Pin`] widget with the given content. /// /// A [`Pin`] widget positions its contents at some fixed coordinates inside of its boundaries. @@ -810,6 +970,20 @@ where }) } +/// Creates a new [`Pop`] widget. +/// +/// A [`Pop`] widget can generate messages when it pops in and out of view. +/// It can even notify you with anticipation at a given distance! +pub fn pop<'a, Message, Theme, Renderer>( + content: impl Into<Element<'a, Message, Theme, Renderer>>, +) -> Pop<'a, Message, Theme, Renderer> +where + Renderer: core::Renderer, + Message: Clone, +{ + Pop::new(content) +} + /// Creates a new [`Scrollable`] with the provided content. /// /// Scrollables let users navigate an endless amount of content with a scrollbar. diff --git a/widget/src/image.rs b/widget/src/image.rs index c8f2a620..f5a9c7f3 100644 --- a/widget/src/image.rs +++ b/widget/src/image.rs @@ -167,6 +167,7 @@ where pub fn draw<Renderer, Handle>( renderer: &mut Renderer, layout: Layout<'_>, + viewport: &Rectangle, handle: &Handle, content_fit: ContentFit, filter_method: FilterMethod, @@ -218,7 +219,9 @@ pub fn draw<Renderer, Handle>( if adjusted_fit.width > bounds.width || adjusted_fit.height > bounds.height { - renderer.with_layer(bounds, render); + if let Some(bounds) = bounds.intersection(viewport) { + renderer.with_layer(bounds, render); + } } else { render(renderer); } @@ -262,11 +265,12 @@ where _style: &renderer::Style, layout: Layout<'_>, _cursor: mouse::Cursor, - _viewport: &Rectangle, + viewport: &Rectangle, ) { draw( renderer, layout, + viewport, &self.handle, self.content_fit, self.filter_method, diff --git a/widget/src/lib.rs b/widget/src/lib.rs index 38c9929a..b8cfa98f 100644 --- a/widget/src/lib.rs +++ b/widget/src/lib.rs @@ -25,6 +25,7 @@ pub mod keyed; pub mod overlay; pub mod pane_grid; pub mod pick_list; +pub mod pop; pub mod progress_bar; pub mod radio; pub mod rule; @@ -66,6 +67,8 @@ pub use pick_list::PickList; #[doc(no_inline)] pub use pin::Pin; #[doc(no_inline)] +pub use pop::Pop; +#[doc(no_inline)] pub use progress_bar::ProgressBar; #[doc(no_inline)] pub use radio::Radio; diff --git a/widget/src/pop.rs b/widget/src/pop.rs new file mode 100644 index 00000000..051fa76a --- /dev/null +++ b/widget/src/pop.rs @@ -0,0 +1,232 @@ +//! Generate messages when content pops in and out of view. +use crate::core::layout; +use crate::core::mouse; +use crate::core::overlay; +use crate::core::renderer; +use crate::core::widget; +use crate::core::widget::tree::{self, Tree}; +use crate::core::window; +use crate::core::{ + self, Clipboard, Element, Event, Layout, Length, Pixels, Rectangle, Shell, + Size, Vector, Widget, +}; + +/// A widget that can generate messages when its content pops in and out of view. +/// +/// It can even notify you with anticipation at a given distance! +#[allow(missing_debug_implementations)] +pub struct Pop<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> { + content: Element<'a, Message, Theme, Renderer>, + on_show: Option<Message>, + on_hide: Option<Message>, + anticipate: Pixels, +} + +impl<'a, Message, Theme, Renderer> Pop<'a, Message, Theme, Renderer> +where + Renderer: core::Renderer, + Message: Clone, +{ + /// Creates a new [`Pop`] widget with the given content. + pub fn new( + content: impl Into<Element<'a, Message, Theme, Renderer>>, + ) -> Self { + Self { + content: content.into(), + on_show: None, + on_hide: None, + anticipate: Pixels::ZERO, + } + } + + /// Sets the message to be produced when the content pops into view. + pub fn on_show(mut self, on_show: Message) -> Self { + self.on_show = Some(on_show); + self + } + + /// Sets the message to be produced when the content pops out of view. + pub fn on_hide(mut self, on_hide: Message) -> Self { + self.on_hide = Some(on_hide); + self + } + + /// Sets the distance in [`Pixels`] to use in anticipation of the + /// content popping into view. + /// + /// This can be quite useful to lazily load items in a long scrollable + /// behind the scenes before the user can notice it! + pub fn anticipate(mut self, distance: impl Into<Pixels>) -> Self { + self.anticipate = distance.into(); + self + } +} + +#[derive(Debug, Clone, Copy, Default)] +struct State { + has_popped_in: bool, +} + +impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> + for Pop<'_, Message, Theme, Renderer> +where + Message: Clone, + Renderer: core::Renderer, +{ + fn tag(&self) -> tree::Tag { + tree::Tag::of::<State>() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn children(&self) -> Vec<Tree> { + vec![Tree::new(&self.content)] + } + + fn diff(&self, tree: &mut Tree) { + tree.diff_children(&[&self.content]); + } + + fn update( + &mut self, + tree: &mut Tree, + event: Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + if let Event::Window(window::Event::RedrawRequested(_)) = &event { + let state = tree.state.downcast_mut::<State>(); + let bounds = layout.bounds(); + + let top_left_distance = viewport.distance(bounds.position()); + + let bottom_right_distance = viewport + .distance(bounds.position() + Vector::from(bounds.size())); + + let distance = top_left_distance.min(bottom_right_distance); + + if state.has_popped_in { + if let Some(on_hide) = &self.on_hide { + if distance > self.anticipate.0 { + state.has_popped_in = false; + shell.publish(on_hide.clone()); + } + } + } else if let Some(on_show) = &self.on_show { + if distance <= self.anticipate.0 { + state.has_popped_in = true; + shell.publish(on_show.clone()); + } + } + } + + self.content.as_widget_mut().update( + tree, event, layout, cursor, renderer, clipboard, shell, viewport, + ); + } + + fn size(&self) -> Size<Length> { + self.content.as_widget().size() + } + + fn size_hint(&self) -> Size<Length> { + self.content.as_widget().size_hint() + } + + fn layout( + &self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + self.content + .as_widget() + .layout(&mut tree.children[0], renderer, limits) + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: layout::Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + self.content.as_widget().draw( + &tree.children[0], + renderer, + theme, + style, + layout, + cursor, + viewport, + ); + } + + fn operate( + &self, + tree: &mut Tree, + layout: core::Layout<'_>, + renderer: &Renderer, + operation: &mut dyn widget::Operation, + ) { + self.content.as_widget().operate( + &mut tree.children[0], + layout, + renderer, + operation, + ); + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: core::Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + self.content.as_widget().mouse_interaction( + &tree.children[0], + layout, + cursor, + viewport, + renderer, + ) + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut Tree, + layout: core::Layout<'_>, + renderer: &Renderer, + translation: core::Vector, + ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { + self.content.as_widget_mut().overlay( + &mut tree.children[0], + layout, + renderer, + translation, + ) + } +} + +impl<'a, Message, Theme, Renderer> From<Pop<'a, Message, Theme, Renderer>> + for Element<'a, Message, Theme, Renderer> +where + Renderer: core::Renderer + 'a, + Theme: 'a, + Message: Clone + 'a, +{ + fn from(pop: Pop<'a, Message, Theme, Renderer>) -> Self { + Element::new(pop) + } +} diff --git a/widget/src/progress_bar.rs b/widget/src/progress_bar.rs index 8f85dcf3..554e8a44 100644 --- a/widget/src/progress_bar.rs +++ b/widget/src/progress_bar.rs @@ -59,8 +59,9 @@ where { range: RangeInclusive<f32>, value: f32, - width: Length, - height: Option<Length>, + length: Length, + girth: Length, + is_vertical: bool, class: Theme::Class<'a>, } @@ -68,8 +69,8 @@ impl<'a, Theme> ProgressBar<'a, Theme> where Theme: Catalog, { - /// The default height of a [`ProgressBar`]. - pub const DEFAULT_HEIGHT: f32 = 30.0; + /// The default girth of a [`ProgressBar`]. + pub const DEFAULT_GIRTH: f32 = 30.0; /// Creates a new [`ProgressBar`]. /// @@ -80,21 +81,30 @@ where ProgressBar { value: value.clamp(*range.start(), *range.end()), range, - width: Length::Fill, - height: None, + length: Length::Fill, + girth: Length::from(Self::DEFAULT_GIRTH), + is_vertical: false, class: Theme::default(), } } /// Sets the width of the [`ProgressBar`]. - pub fn width(mut self, width: impl Into<Length>) -> Self { - self.width = width.into(); + pub fn length(mut self, length: impl Into<Length>) -> Self { + self.length = length.into(); self } /// Sets the height of the [`ProgressBar`]. - pub fn height(mut self, height: impl Into<Length>) -> Self { - self.height = Some(height.into()); + pub fn girth(mut self, girth: impl Into<Length>) -> Self { + self.girth = girth.into(); + self + } + + /// Turns the [`ProgressBar`] into a vertical [`ProgressBar`]. + /// + /// By default, a [`ProgressBar`] is horizontal. + pub fn vertical(mut self) -> Self { + self.is_vertical = true; self } @@ -115,6 +125,22 @@ where self.class = class.into(); self } + + fn width(&self) -> Length { + if self.is_vertical { + self.girth + } else { + self.length + } + } + + fn height(&self) -> Length { + if self.is_vertical { + self.length + } else { + self.girth + } + } } impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> @@ -125,8 +151,8 @@ where { fn size(&self) -> Size<Length> { Size { - width: self.width, - height: self.height.unwrap_or(Length::Fixed(Self::DEFAULT_HEIGHT)), + width: self.width(), + height: self.height(), } } @@ -136,11 +162,7 @@ where _renderer: &Renderer, limits: &layout::Limits, ) -> layout::Node { - layout::atomic( - limits, - self.width, - self.height.unwrap_or(Length::Fixed(Self::DEFAULT_HEIGHT)), - ) + layout::atomic(limits, self.width(), self.height()) } fn draw( @@ -156,11 +178,16 @@ where let bounds = layout.bounds(); let (range_start, range_end) = self.range.clone().into_inner(); - let active_progress_width = if range_start >= range_end { + let length = if self.is_vertical { + bounds.height + } else { + bounds.width + }; + + let active_progress_length = if range_start >= range_end { 0.0 } else { - bounds.width * (self.value - range_start) - / (range_end - range_start) + length * (self.value - range_start) / (range_end - range_start) }; let style = theme.style(&self.class); @@ -174,13 +201,23 @@ where style.background, ); - if active_progress_width > 0.0 { + if active_progress_length > 0.0 { + let bounds = if self.is_vertical { + Rectangle { + y: bounds.y + bounds.height - active_progress_length, + height: active_progress_length, + ..bounds + } + } else { + Rectangle { + width: active_progress_length, + ..bounds + } + }; + renderer.fill_quad( renderer::Quad { - bounds: Rectangle { - width: active_progress_width, - ..bounds - }, + bounds, border: Border { color: Color::TRANSPARENT, ..style.border @@ -274,6 +311,13 @@ pub fn success(theme: &Theme) -> Style { styled(palette.background.strong.color, palette.success.base.color) } +/// The warning style of a [`ProgressBar`]. +pub fn warning(theme: &Theme) -> Style { + let palette = theme.extended_palette(); + + styled(palette.background.strong.color, palette.warning.base.color) +} + /// The danger style of a [`ProgressBar`]. pub fn danger(theme: &Theme) -> Style { let palette = theme.extended_palette(); diff --git a/widget/src/vertical_slider.rs b/widget/src/vertical_slider.rs index c1af142b..2ed9419a 100644 --- a/widget/src/vertical_slider.rs +++ b/widget/src/vertical_slider.rs @@ -42,6 +42,7 @@ use crate::core::mouse; use crate::core::renderer; use crate::core::touch; use crate::core::widget::tree::{self, Tree}; +use crate::core::window; use crate::core::{ self, Clipboard, Element, Event, Length, Pixels, Point, Rectangle, Shell, Size, Widget, @@ -98,6 +99,7 @@ where width: f32, height: Length, class: Theme::Class<'a>, + status: Option<Status>, } impl<'a, T, Message, Theme> VerticalSlider<'a, T, Message, Theme> @@ -144,6 +146,7 @@ where width: Self::DEFAULT_WIDTH, height: Length::Fill, class: Theme::default(), + status: None, } } @@ -390,7 +393,9 @@ where shell.capture_event(); } } - Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) => { + Event::Keyboard(keyboard::Event::KeyPressed { + ref key, .. + }) => { if cursor.is_over(layout.bounds()) { match key { Key::Named(key::Named::ArrowUp) => { @@ -410,32 +415,36 @@ where } _ => {} } + + let current_status = if state.is_dragging { + Status::Dragged + } else if cursor.is_over(layout.bounds()) { + Status::Hovered + } else { + Status::Active + }; + + if let Event::Window(window::Event::RedrawRequested(_now)) = event { + self.status = Some(current_status); + } else if self.status.is_some_and(|status| status != current_status) { + shell.request_redraw(); + } } fn draw( &self, - tree: &Tree, + _tree: &Tree, renderer: &mut Renderer, theme: &Theme, _style: &renderer::Style, layout: Layout<'_>, - cursor: mouse::Cursor, + _cursor: mouse::Cursor, _viewport: &Rectangle, ) { - let state = tree.state.downcast_ref::<State>(); let bounds = layout.bounds(); - let is_mouse_over = cursor.is_over(bounds); - let style = theme.style( - &self.class, - if state.is_dragging { - Status::Dragged - } else if is_mouse_over { - Status::Hovered - } else { - Status::Active - }, - ); + let style = + theme.style(&self.class, self.status.unwrap_or(Status::Active)); let (handle_width, handle_height, handle_border_radius) = match style.handle.shape { |