Added theme management, custom theme colors
This commit is contained in:
1 parent
da752bcfd7
commit
188e4f64d4
77 files changed
+40005
-104
No files matched your search
Vendored
+496
@@ -0,0 +1,496 @@
|
||||
//! Use a badge for color highlighting important information.
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: badge*
|
||||
|
||||
use iced_core::{
|
||||
Alignment, Border, Clipboard, Color, Element, Event, Layout, Length, Padding, Point, Rectangle,
|
||||
Shadow, Shell, Size, Widget,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
renderer,
|
||||
widget::{Operation, Tree},
|
||||
window,
|
||||
};
|
||||
|
||||
pub use crate::style::{
|
||||
badge::{Catalog, Style},
|
||||
status::{Status, StyleFn},
|
||||
};
|
||||
|
||||
/// The ratio of the border radius.
|
||||
const BORDER_RADIUS_RATIO: f32 = 34.0 / 15.0;
|
||||
|
||||
/// A badge for color highlighting small information.
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// # use iced_widget::Text;
|
||||
/// # use iced_aw::Badge;
|
||||
/// #
|
||||
/// #[derive(Debug, Clone)]
|
||||
/// enum Message {
|
||||
/// }
|
||||
///
|
||||
/// let badge = Badge::<Message>::new(Text::new("Text"));
|
||||
/// ```
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct Badge<'a, Message, Theme = iced_widget::Theme, Renderer = iced_widget::Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
Theme: Catalog,
|
||||
{
|
||||
/// The padding of the [`Badge`].
|
||||
padding: u16,
|
||||
/// The width of the [`Badge`].
|
||||
width: Length,
|
||||
/// The height of the [`Badge`].
|
||||
height: Length,
|
||||
/// The horizontal alignment of the [`Badge`].
|
||||
horizontal_alignment: Alignment,
|
||||
/// The vertical alignment of the [`Badge`].
|
||||
vertical_alignment: Alignment,
|
||||
/// The style of the [`Badge`].
|
||||
class: Theme::Class<'a>,
|
||||
/// The content [`Element`] of the [`Badge`].
|
||||
content: Element<'a, Message, Theme, Renderer>,
|
||||
/// The [`Status`] of the [`Badge`]
|
||||
status: Option<Status>,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> Badge<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
Theme: Catalog,
|
||||
{
|
||||
/// Creates a new [`Badge`] with the given content.
|
||||
///
|
||||
/// It expects:
|
||||
/// * the content [`Element`] to display in the [`Badge`].
|
||||
pub fn new<T>(content: T) -> Self
|
||||
where
|
||||
T: Into<Element<'a, Message, Theme, Renderer>>,
|
||||
{
|
||||
Badge {
|
||||
padding: 7,
|
||||
width: Length::Shrink,
|
||||
height: Length::Shrink,
|
||||
horizontal_alignment: Alignment::Center,
|
||||
vertical_alignment: Alignment::Center,
|
||||
class: Theme::default(),
|
||||
content: content.into(),
|
||||
status: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the horizontal alignment of the content of the [`Badge`].
|
||||
#[must_use]
|
||||
pub fn align_x(mut self, alignment: Alignment) -> Self {
|
||||
self.horizontal_alignment = alignment;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the vertical alignment of the content of the [`Badge`].
|
||||
#[must_use]
|
||||
pub fn align_y(mut self, alignment: Alignment) -> Self {
|
||||
self.vertical_alignment = alignment;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`Badge`].
|
||||
#[must_use]
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the padding of the [`Badge`].
|
||||
#[must_use]
|
||||
pub fn padding(mut self, units: u16) -> Self {
|
||||
self.padding = units;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the style of the [`Badge`].
|
||||
#[must_use]
|
||||
pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
|
||||
where
|
||||
Theme::Class<'a>: From<StyleFn<'a, Theme, Style>>,
|
||||
{
|
||||
self.class = (Box::new(style) as StyleFn<'a, Theme, Style>).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the class of the input of the [`Badge`].
|
||||
#[must_use]
|
||||
pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the width of the [`Badge`].
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for Badge<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
Theme: Catalog,
|
||||
{
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
vec![Tree::new(&self.content)]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(std::slice::from_ref(&self.content));
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
let padding: Padding = self.padding.into();
|
||||
let limits = limits
|
||||
.loose()
|
||||
.width(self.width)
|
||||
.height(self.height)
|
||||
.shrink(padding);
|
||||
|
||||
let mut content =
|
||||
self.content
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree.children[0], renderer, &limits.loose());
|
||||
let size = limits.resolve(self.width, self.height, content.size());
|
||||
|
||||
content = content
|
||||
.move_to(Point::new(padding.left, padding.top))
|
||||
.align(self.horizontal_alignment, self.vertical_alignment, size);
|
||||
|
||||
Node::with_children(size.expand(padding), vec![content])
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.content.as_widget_mut().update(
|
||||
&mut state.children[0],
|
||||
event,
|
||||
layout
|
||||
.children()
|
||||
.next()
|
||||
.expect("widget: Layout should have a children layout for a badge."),
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
|
||||
let current_status = 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 mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.content.as_widget().mouse_interaction(
|
||||
&state.children[0],
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
_style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let bounds = layout.bounds();
|
||||
let mut children = layout.children();
|
||||
|
||||
let style_sheet = theme.style(&self.class, self.status.unwrap_or(Status::Active));
|
||||
|
||||
let border_radius = style_sheet
|
||||
.border_radius
|
||||
.unwrap_or(bounds.height / BORDER_RADIUS_RATIO);
|
||||
|
||||
if bounds.intersects(viewport) {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds,
|
||||
border: Border {
|
||||
radius: border_radius.into(),
|
||||
width: style_sheet.border_width,
|
||||
color: style_sheet.border_color.unwrap_or(Color::BLACK),
|
||||
},
|
||||
shadow: Shadow::default(),
|
||||
..renderer::Quad::default()
|
||||
},
|
||||
style_sheet.background,
|
||||
);
|
||||
}
|
||||
|
||||
self.content.as_widget().draw(
|
||||
&tree.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
&renderer::Style {
|
||||
text_color: style_sheet.text_color,
|
||||
},
|
||||
children
|
||||
.next()
|
||||
.expect("Graphics: Layout should have a children layout for Badge"),
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation,
|
||||
) {
|
||||
operation.container(None, layout.bounds());
|
||||
operation.traverse(&mut |operation| {
|
||||
self.content.as_widget_mut().operate(
|
||||
&mut tree.children[0],
|
||||
layout
|
||||
.children()
|
||||
.next()
|
||||
.expect("Badge layout should have a content child"),
|
||||
renderer,
|
||||
operation,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> From<Badge<'a, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
Theme: 'a + Catalog,
|
||||
{
|
||||
fn from(badge: Badge<'a, Message, Theme, Renderer>) -> Self {
|
||||
Self::new(badge)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
enum TestMessage {}
|
||||
|
||||
type TestBadge<'a> = Badge<'a, TestMessage, iced_widget::Theme, iced_widget::Renderer>;
|
||||
|
||||
#[test]
|
||||
fn badge_new_has_default_values() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test"));
|
||||
|
||||
assert_eq!(badge.padding, 7);
|
||||
assert_eq!(badge.width, Length::Shrink);
|
||||
assert_eq!(badge.height, Length::Shrink);
|
||||
assert_eq!(badge.horizontal_alignment, Alignment::Center);
|
||||
assert_eq!(badge.vertical_alignment, Alignment::Center);
|
||||
assert!(badge.status.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_padding_sets_value() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test")).padding(15);
|
||||
assert_eq!(badge.padding, 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_width_sets_value() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test")).width(200);
|
||||
assert_eq!(badge.width, Length::Fixed(200.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_width_fill_sets_value() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test")).width(Length::Fill);
|
||||
assert_eq!(badge.width, Length::Fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_height_sets_value() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test")).height(50);
|
||||
assert_eq!(badge.height, Length::Fixed(50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_height_shrink_sets_value() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test")).height(Length::Shrink);
|
||||
assert_eq!(badge.height, Length::Shrink);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_align_x_sets_value() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test")).align_x(Alignment::Start);
|
||||
assert_eq!(badge.horizontal_alignment, Alignment::Start);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_align_y_sets_value() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test")).align_y(Alignment::End);
|
||||
assert_eq!(badge.vertical_alignment, Alignment::End);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_size_method_returns_correct_size() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test"))
|
||||
.width(100)
|
||||
.height(50);
|
||||
|
||||
let size = Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::size(&badge);
|
||||
assert_eq!(size.width, Length::Fixed(100.0));
|
||||
assert_eq!(size.height, Length::Fixed(50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_chaining_methods() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test"))
|
||||
.padding(10)
|
||||
.width(150)
|
||||
.height(40)
|
||||
.align_x(Alignment::Start)
|
||||
.align_y(Alignment::End);
|
||||
|
||||
assert_eq!(badge.padding, 10);
|
||||
assert_eq!(badge.width, Length::Fixed(150.0));
|
||||
assert_eq!(badge.height, Length::Fixed(40.0));
|
||||
assert_eq!(badge.horizontal_alignment, Alignment::Start);
|
||||
assert_eq!(badge.vertical_alignment, Alignment::End);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_default_padding_is_7() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test"));
|
||||
assert_eq!(badge.padding, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_padding_can_be_zero() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test")).padding(0);
|
||||
assert_eq!(badge.padding, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_padding_max_value() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test")).padding(u16::MAX);
|
||||
assert_eq!(badge.padding, u16::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_alignment_combinations() {
|
||||
let alignments = [Alignment::Start, Alignment::Center, Alignment::End];
|
||||
|
||||
for h_align in alignments {
|
||||
for v_align in alignments {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test"))
|
||||
.align_x(h_align)
|
||||
.align_y(v_align);
|
||||
|
||||
assert_eq!(badge.horizontal_alignment, h_align);
|
||||
assert_eq!(badge.vertical_alignment, v_align);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_length_fillportion() {
|
||||
let badge =
|
||||
TestBadge::new(iced_widget::text::Text::new("Test")).width(Length::FillPortion(3));
|
||||
|
||||
assert_eq!(badge.width, Length::FillPortion(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_widget_has_operate_method() {
|
||||
// Verify that Badge implements the operate method from Widget trait
|
||||
// This is a compile-time check to ensure the signature is correct
|
||||
fn assert_has_operate<W, M, T, R>(_widget: &W)
|
||||
where
|
||||
W: Widget<M, T, R>,
|
||||
R: renderer::Renderer,
|
||||
{
|
||||
}
|
||||
|
||||
// This is a compiler only test. not really a running test.
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test"));
|
||||
assert_has_operate(&badge);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_children_returns_single_content_tree() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Test"));
|
||||
let children =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::children(&badge);
|
||||
|
||||
// Badge should have exactly one child (the content element)
|
||||
assert_eq!(children.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn badge_diff_updates_content_tree() {
|
||||
let badge = TestBadge::new(iced_widget::text::Text::new("Original"));
|
||||
let content = Element::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::from(
|
||||
iced_widget::text::Text::new("Original"),
|
||||
);
|
||||
let mut tree = Tree {
|
||||
tag: iced_core::widget::tree::Tag::stateless(),
|
||||
state: iced_core::widget::tree::State::None,
|
||||
children: vec![Tree::new(&content)],
|
||||
};
|
||||
|
||||
// Verify diff doesn't panic and properly handles the tree
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::diff(&badge, &mut tree);
|
||||
|
||||
// Tree should still have one child after diff
|
||||
assert_eq!(tree.children.len(), 1);
|
||||
}
|
||||
}
|
||||
Vendored
+1406
File diff suppressed because it is too large.
Load diff
+421
@@ -0,0 +1,421 @@
|
||||
//! Use a color picker as an input element for picking colors.
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: `color_picker`*
|
||||
|
||||
use self::style::{Status, StyleFn};
|
||||
|
||||
use super::overlay::color_picker::{
|
||||
self, ColorBarDragged, ColorPickerOverlay, ColorPickerOverlayButtons,
|
||||
};
|
||||
|
||||
use iced_core::{
|
||||
Clipboard, Color, Element, Event, Layout, Length, Rectangle, Shell, Vector, Widget,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
overlay, renderer,
|
||||
widget::{
|
||||
Operation,
|
||||
tree::{self, Tag, Tree},
|
||||
},
|
||||
};
|
||||
use iced_widget::Renderer;
|
||||
|
||||
pub use crate::style::{self, color_picker::Style};
|
||||
|
||||
//TODO: Remove ignore when Null is updated. Temp fix for Test runs
|
||||
/// An input element for picking colors.
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// # use iced_aw::ColorPicker;
|
||||
/// # use iced::{Color, widget::{button, Button, Text}};
|
||||
/// #
|
||||
/// #[derive(Clone, Debug)]
|
||||
/// enum Message {
|
||||
/// Open,
|
||||
/// Cancel,
|
||||
/// Submit(Color),
|
||||
/// }
|
||||
///
|
||||
/// let color_picker = ColorPicker::new(
|
||||
/// true,
|
||||
/// Color::default(),
|
||||
/// Button::new(Text::new("Pick color"))
|
||||
/// .on_press(Message::Open),
|
||||
/// Message::Cancel,
|
||||
/// Message::Submit,
|
||||
/// );
|
||||
/// ```
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct ColorPicker<'a, Message, Theme = iced_widget::Theme>
|
||||
where
|
||||
Message: Clone,
|
||||
Theme: style::color_picker::Catalog + iced_widget::button::Catalog,
|
||||
{
|
||||
/// Show the picker.
|
||||
show_picker: bool,
|
||||
/// The color to show.
|
||||
color: Color,
|
||||
/// The underlying element.
|
||||
underlay: Element<'a, Message, Theme, Renderer>,
|
||||
/// The message that is sent if the cancel button of the [`ColorPickerOverlay`] is pressed.
|
||||
on_cancel: Message,
|
||||
/// The function that produces a message when the submit button of the [`ColorPickerOverlay`] is pressed.
|
||||
on_submit: Box<dyn Fn(Color) -> Message>,
|
||||
/// Optional function that produces a message when the color changes during selection (real-time updates).
|
||||
on_color_change: Option<Box<dyn Fn(Color) -> Message>>,
|
||||
/// The style of the [`ColorPickerOverlay`].
|
||||
class: <Theme as style::color_picker::Catalog>::Class<'a>,
|
||||
/// The buttons of the overlay.
|
||||
overlay_state: Element<'a, Message, Theme, Renderer>,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme> ColorPicker<'a, Message, Theme>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Theme: 'a
|
||||
+ style::color_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog,
|
||||
{
|
||||
/// Creates a new [`ColorPicker`] wrapping around the given underlay.
|
||||
///
|
||||
/// It expects:
|
||||
/// * if the overlay of the color picker is visible.
|
||||
/// * the initial color to show.
|
||||
/// * the underlay [`Element`] on which this [`ColorPicker`]
|
||||
/// will be wrapped around.
|
||||
/// * a message that will be send when the cancel button of the [`ColorPicker`]
|
||||
/// is pressed.
|
||||
/// * a function that will be called when the submit button of the [`ColorPicker`]
|
||||
/// is pressed, which takes the picked [`Color`] value.
|
||||
pub fn new<U, F>(
|
||||
show_picker: bool,
|
||||
color: Color,
|
||||
underlay: U,
|
||||
on_cancel: Message,
|
||||
on_submit: F,
|
||||
) -> Self
|
||||
where
|
||||
U: Into<Element<'a, Message, Theme, Renderer>>,
|
||||
F: 'static + Fn(Color) -> Message,
|
||||
{
|
||||
Self {
|
||||
show_picker,
|
||||
color,
|
||||
underlay: underlay.into(),
|
||||
on_cancel,
|
||||
on_submit: Box::new(on_submit),
|
||||
on_color_change: None,
|
||||
class: <Theme as style::color_picker::Catalog>::default(),
|
||||
overlay_state: ColorPickerOverlayButtons::default().into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets a callback that will be called whenever the color changes during selection (real-time updates).
|
||||
#[must_use]
|
||||
pub fn on_color_change<F>(mut self, on_color_change: F) -> Self
|
||||
where
|
||||
F: 'static + Fn(Color) -> Message,
|
||||
{
|
||||
self.on_color_change = Some(Box::new(on_color_change));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the style of the [`ColorPicker`].
|
||||
#[must_use]
|
||||
pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
|
||||
where
|
||||
<Theme as style::color_picker::Catalog>::Class<'a>: From<StyleFn<'a, Theme, Style>>,
|
||||
{
|
||||
self.class = (Box::new(style) as StyleFn<'a, Theme, Style>).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the class of the input of the [`ColorPicker`].
|
||||
#[must_use]
|
||||
pub fn class(
|
||||
mut self,
|
||||
class: impl Into<<Theme as style::color_picker::Catalog>::Class<'a>>,
|
||||
) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The state of the [`ColorPicker`].
|
||||
#[derive(Debug, Default)]
|
||||
pub struct State {
|
||||
/// The state of the overlay.
|
||||
pub(crate) overlay_state: color_picker::State,
|
||||
/// Was overlay shown during the previous render?
|
||||
pub(crate) old_show_picker: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Creates a new [`State`].
|
||||
#[must_use]
|
||||
pub fn new(color: Color) -> Self {
|
||||
Self {
|
||||
overlay_state: color_picker::State::new(color),
|
||||
old_show_picker: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the color of the state.
|
||||
pub fn reset(&mut self) {
|
||||
self.overlay_state.color = Color::from_rgb(0.5, 0.25, 0.25);
|
||||
self.overlay_state.color_bar_dragged = ColorBarDragged::None;
|
||||
}
|
||||
|
||||
/// Synchronize with the provided color if it was changed or picker was reopened
|
||||
///
|
||||
/// Keep the overlay state in sync. While overlay is open, it "owns" the value
|
||||
/// (there is no other way the user can update its value). When it is reopened,
|
||||
/// reset the color to the initial one.
|
||||
fn synchronize(&mut self, show_picker: bool, color: Color) {
|
||||
if show_picker && (!self.old_show_picker || self.overlay_state.initial_color != color) {
|
||||
self.overlay_state.force_synchronize(color);
|
||||
}
|
||||
self.old_show_picker = show_picker;
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme> Widget<Message, Theme, Renderer> for ColorPicker<'a, Message, Theme>
|
||||
where
|
||||
Message: 'static + Clone,
|
||||
Theme: 'a
|
||||
+ style::color_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog,
|
||||
{
|
||||
fn tag(&self) -> Tag {
|
||||
Tag::of::<State>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::new(State::new(self.color))
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
vec![Tree::new(&self.underlay), Tree::new(&self.overlay_state)]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
let color_picker_state = tree.state.downcast_mut::<State>();
|
||||
|
||||
color_picker_state.synchronize(self.show_picker, self.color);
|
||||
|
||||
tree.diff_children(&[&self.underlay, &self.overlay_state]);
|
||||
}
|
||||
|
||||
fn size(&self) -> iced_core::Size<Length> {
|
||||
self.underlay.as_widget().size()
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
self.underlay
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree.children[0], renderer, limits)
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.underlay.as_widget_mut().update(
|
||||
&mut state.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.underlay.as_widget().mouse_interaction(
|
||||
&state.children[0],
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.underlay.as_widget().draw(
|
||||
&state.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn operate<'b>(
|
||||
&'b mut self,
|
||||
state: &'b mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
self.underlay
|
||||
.as_widget_mut()
|
||||
.operate(&mut state.children[0], layout, renderer, operation);
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
tree: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
let picker_state: &mut State = tree.state.downcast_mut();
|
||||
|
||||
if !self.show_picker {
|
||||
return self.underlay.as_widget_mut().overlay(
|
||||
&mut tree.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
);
|
||||
}
|
||||
|
||||
let position = layout.position() + translation;
|
||||
|
||||
Some(
|
||||
ColorPickerOverlay::new(
|
||||
picker_state,
|
||||
self.on_cancel.clone(),
|
||||
&self.on_submit,
|
||||
self.on_color_change.as_deref(),
|
||||
position,
|
||||
&self.class,
|
||||
&mut tree.children[1],
|
||||
*viewport,
|
||||
)
|
||||
.overlay(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme> From<ColorPicker<'a, Message, Theme>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'static + Clone,
|
||||
Theme: 'a
|
||||
+ style::color_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog,
|
||||
{
|
||||
fn from(color_picker: ColorPicker<'a, Message, Theme>) -> Self {
|
||||
Element::new(color_picker)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum TestMessage {
|
||||
Cancel,
|
||||
Submit(Color),
|
||||
}
|
||||
|
||||
type TestColorPicker<'a> = ColorPicker<'a, TestMessage, iced_widget::Theme>;
|
||||
|
||||
fn create_test_button() -> iced_widget::Button<'static, TestMessage, iced_widget::Theme> {
|
||||
iced_widget::button(iced_widget::text::Text::new("Pick"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_picker_new_with_picker_hidden() {
|
||||
let color = Color::from_rgb(0.5, 0.5, 0.5);
|
||||
let button = create_test_button();
|
||||
|
||||
let picker = TestColorPicker::new(
|
||||
false,
|
||||
color,
|
||||
button,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
assert!(!picker.show_picker);
|
||||
assert_eq!(picker.color, color);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_picker_new_with_picker_shown() {
|
||||
let color = Color::from_rgb(0.3, 0.6, 0.9);
|
||||
let button = create_test_button();
|
||||
|
||||
let picker = TestColorPicker::new(
|
||||
true,
|
||||
color,
|
||||
button,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
assert!(picker.show_picker);
|
||||
assert_eq!(picker.color, color);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_picker_state_new() {
|
||||
let color = Color::from_rgb(0.5, 0.5, 0.5);
|
||||
let state = State::new(color);
|
||||
|
||||
assert!(!state.old_show_picker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_picker_state_default() {
|
||||
let state = State::default();
|
||||
|
||||
assert!(!state.old_show_picker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_picker_state_reset() {
|
||||
let color = Color::from_rgb(0.5, 0.5, 0.5);
|
||||
let mut state = State::new(color);
|
||||
|
||||
state.reset();
|
||||
// State should still be valid after reset
|
||||
assert!(!state.old_show_picker);
|
||||
}
|
||||
}
|
||||
Vendored
+63
@@ -0,0 +1,63 @@
|
||||
//! Common types for reuse.
|
||||
//!
|
||||
|
||||
use iced_core::{Padding, Rectangle};
|
||||
|
||||
/// Methods for creating inner bounds
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub enum InnerBounds {
|
||||
/// Create inner bounds ratio to the outer bounds
|
||||
Ratio(f32, f32),
|
||||
/// Create inner bounds by padding the outer bounds
|
||||
Padding(Padding),
|
||||
/// Create square inner bounds
|
||||
Square(f32),
|
||||
/// Create inner bounds with a custom function
|
||||
Custom(Box<dyn Fn(Rectangle) -> Rectangle>),
|
||||
}
|
||||
impl InnerBounds {
|
||||
/// Gets the inner bounds of the Set type.
|
||||
#[must_use]
|
||||
pub fn get_bounds(&self, outer_bounds: Rectangle) -> Rectangle {
|
||||
use InnerBounds::{Custom, Padding, Ratio, Square};
|
||||
match self {
|
||||
Ratio(w, h) => {
|
||||
let width = w * outer_bounds.width;
|
||||
let height = h * outer_bounds.height;
|
||||
let x = outer_bounds.x + (outer_bounds.width - width) * 0.5;
|
||||
let y = outer_bounds.y + (outer_bounds.height - height) * 0.5;
|
||||
Rectangle {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
Padding(p) => {
|
||||
let x = outer_bounds.x + p.left;
|
||||
let y = outer_bounds.y + p.top;
|
||||
let width = outer_bounds.width - p.x();
|
||||
let height = outer_bounds.width - p.y();
|
||||
Rectangle {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
Square(l) => {
|
||||
let width = *l;
|
||||
let height = *l;
|
||||
let x = outer_bounds.x + (outer_bounds.width - width) * 0.5;
|
||||
let y = outer_bounds.y + (outer_bounds.height - height) * 0.5;
|
||||
Rectangle {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
Custom(f) => f(outer_bounds),
|
||||
}
|
||||
}
|
||||
}
|
||||
+512
@@ -0,0 +1,512 @@
|
||||
//! A context menu for showing actions on right click.
|
||||
//!
|
||||
use iced_core::{
|
||||
Clipboard, Element, Event, Layout, Length, Point, Rectangle, Shell, Vector, Widget,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Button, Cursor},
|
||||
overlay, renderer,
|
||||
widget::{Operation, Tree, tree},
|
||||
};
|
||||
|
||||
pub use crate::style::{
|
||||
context_menu::{Catalog, Style},
|
||||
status::{Status, StyleFn},
|
||||
};
|
||||
|
||||
use crate::widget::overlay::ContextMenuOverlay;
|
||||
|
||||
/// A context menu
|
||||
///
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// # use iced_widget::{Text, Button};
|
||||
/// # use iced_aw::ContextMenu;
|
||||
/// #
|
||||
/// #[derive(Debug, Clone)]
|
||||
/// enum Message {
|
||||
/// Action1,
|
||||
/// }
|
||||
///
|
||||
/// let underlay = Text::new("right click me");
|
||||
///
|
||||
/// let cm = ContextMenu::new(
|
||||
/// underlay,
|
||||
/// || Button::new("action1").on_press(Message::Action1).into()
|
||||
/// );
|
||||
/// ```
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct ContextMenu<
|
||||
'a,
|
||||
Overlay,
|
||||
Message,
|
||||
Theme = iced_widget::Theme,
|
||||
Renderer = iced_widget::Renderer,
|
||||
> where
|
||||
Overlay: Fn() -> Element<'a, Message, Theme, Renderer>,
|
||||
Message: Clone,
|
||||
Renderer: renderer::Renderer,
|
||||
Theme: Catalog,
|
||||
{
|
||||
/// The underlying element.
|
||||
underlay: Element<'a, Message, Theme, Renderer>,
|
||||
/// The content of [`ContextMenuOverlay`].
|
||||
overlay: Overlay,
|
||||
overlay_instance: Option<Element<'a, Message, Theme, Renderer>>,
|
||||
/// The style of the [`ContextMenu`].
|
||||
class: Theme::Class<'a>,
|
||||
/// Force the menu to be shown (for testing purposes). If None, uses internal state.
|
||||
force_open: Option<bool>,
|
||||
}
|
||||
|
||||
impl<'a, Overlay, Message, Theme, Renderer> ContextMenu<'a, Overlay, Message, Theme, Renderer>
|
||||
where
|
||||
Overlay: Fn() -> Element<'a, Message, Theme, Renderer>,
|
||||
Message: Clone,
|
||||
Renderer: renderer::Renderer,
|
||||
Theme: Catalog,
|
||||
{
|
||||
/// Creates a new [`ContextMenu`]
|
||||
///
|
||||
/// `underlay`: The underlying element.
|
||||
///
|
||||
/// `overlay`: The content of [`ContextMenuOverlay`] which will be displayed when `underlay` is clicked.
|
||||
pub fn new<U>(underlay: U, overlay: Overlay) -> Self
|
||||
where
|
||||
U: Into<Element<'a, Message, Theme, Renderer>>,
|
||||
{
|
||||
ContextMenu {
|
||||
underlay: underlay.into(),
|
||||
overlay,
|
||||
overlay_instance: None,
|
||||
class: Theme::default(),
|
||||
force_open: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the style of the [`ContextMenu`].
|
||||
#[must_use]
|
||||
pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
|
||||
where
|
||||
Theme::Class<'a>: From<StyleFn<'a, Theme, Style>>,
|
||||
{
|
||||
self.class = (Box::new(style) as StyleFn<'a, Theme, Style>).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the class of the input of the [`ContextMenu`].
|
||||
#[must_use]
|
||||
pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Forces the menu to be open or closed, overriding the internal state.
|
||||
/// This is primarily useful for testing purposes.
|
||||
/// If `None`, the menu uses its internal state (toggled by right-click).
|
||||
#[must_use]
|
||||
pub fn open(mut self, open: bool) -> Self {
|
||||
self.force_open = Some(open);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Content, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for ContextMenu<'a, Content, Message, Theme, Renderer>
|
||||
where
|
||||
Content: 'a + Fn() -> Element<'a, Message, Theme, Renderer>,
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
Theme: Catalog,
|
||||
{
|
||||
fn size(&self) -> iced_core::Size<Length> {
|
||||
self.underlay.as_widget().size()
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
self.underlay
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree.children[0], renderer, limits)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.underlay.as_widget().draw(
|
||||
&state.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn tag(&self) -> tree::Tag {
|
||||
tree::Tag::of::<State>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::new(State::new())
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
let overlay_tree = self
|
||||
.overlay_instance
|
||||
.as_ref()
|
||||
.map_or_else(Tree::empty, Tree::new);
|
||||
vec![Tree::new(&self.underlay), overlay_tree]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.children[0].diff(&self.underlay);
|
||||
if let Some(overlay) = self.overlay_instance.as_ref() {
|
||||
tree.children[1].diff(overlay);
|
||||
}
|
||||
}
|
||||
|
||||
fn operate<'b>(
|
||||
&'b mut self,
|
||||
state: &'b mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
let s: &mut State = state.state.downcast_mut();
|
||||
let show = self.force_open.unwrap_or(s.show);
|
||||
|
||||
if show {
|
||||
let content = self.overlay_instance.get_or_insert_with(&self.overlay);
|
||||
state.children[1].diff(&*content);
|
||||
|
||||
content
|
||||
.as_widget_mut()
|
||||
.operate(&mut state.children[1], layout, renderer, operation);
|
||||
} else {
|
||||
self.overlay_instance = None;
|
||||
self.underlay.as_widget_mut().operate(
|
||||
&mut state.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
if *event == Event::Mouse(mouse::Event::ButtonPressed(Button::Right)) {
|
||||
let bounds = layout.bounds();
|
||||
|
||||
if cursor.is_over(bounds) {
|
||||
let s: &mut State = state.state.downcast_mut();
|
||||
s.cursor_position = cursor.position().unwrap_or_default();
|
||||
s.show = !s.show;
|
||||
|
||||
if !s.show {
|
||||
self.overlay_instance = None;
|
||||
}
|
||||
|
||||
shell.capture_event();
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
self.underlay.as_widget_mut().update(
|
||||
&mut state.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.underlay.as_widget().mouse_interaction(
|
||||
&state.children[0],
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
tree: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
let s: &mut State = tree.state.downcast_mut();
|
||||
let show = self.force_open.unwrap_or(s.show);
|
||||
|
||||
if !show {
|
||||
self.overlay_instance = None;
|
||||
return self.underlay.as_widget_mut().overlay(
|
||||
&mut tree.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
);
|
||||
}
|
||||
|
||||
let position = s.cursor_position;
|
||||
let content = self.overlay_instance.get_or_insert_with(&self.overlay);
|
||||
tree.children[1].diff(&*content);
|
||||
Some(
|
||||
ContextMenuOverlay::new(
|
||||
position + translation,
|
||||
&mut tree.children[1],
|
||||
content,
|
||||
&self.class,
|
||||
s,
|
||||
)
|
||||
.overlay(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Content, Message, Theme, Renderer> From<ContextMenu<'a, Content, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Content: 'a + Fn() -> Self,
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
Theme: 'a + Catalog,
|
||||
{
|
||||
fn from(modal: ContextMenu<'a, Content, Message, Theme, Renderer>) -> Self {
|
||||
Element::new(modal)
|
||||
}
|
||||
}
|
||||
|
||||
/// The state of the ``context_menu``.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct State {
|
||||
/// The visibility of the [`ContextMenu`] overlay.
|
||||
pub show: bool,
|
||||
/// Use for showing the overlay where the click was made.
|
||||
pub cursor_position: Point,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Creates a new [`State`] containing the given state data.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
show: false,
|
||||
cursor_position: Point::ORIGIN,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
enum TestMessage {}
|
||||
|
||||
type TestContextMenu<'a> = ContextMenu<
|
||||
'a,
|
||||
fn() -> Element<'a, TestMessage, iced_widget::Theme, iced_widget::Renderer>,
|
||||
TestMessage,
|
||||
iced_widget::Theme,
|
||||
iced_widget::Renderer,
|
||||
>;
|
||||
|
||||
fn create_overlay() -> Element<'static, TestMessage, iced_widget::Theme, iced_widget::Renderer>
|
||||
{
|
||||
iced_widget::text::Text::new("Overlay").into()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_new_has_default_values() {
|
||||
let state = State::new();
|
||||
assert!(!state.show);
|
||||
assert_eq!(state.cursor_position, Point::ORIGIN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_default_trait() {
|
||||
let state = State::default();
|
||||
assert!(!state.show);
|
||||
assert_eq!(state.cursor_position, Point::ORIGIN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_new_creates_instance() {
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay);
|
||||
|
||||
let size =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::size(&context_menu);
|
||||
assert_eq!(size.width, Length::Shrink);
|
||||
assert_eq!(size.height, Length::Shrink);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_tag_returns_state_tag() {
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay);
|
||||
|
||||
let tag =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::tag(&context_menu);
|
||||
assert_eq!(tag, tree::Tag::of::<State>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_has_two_children() {
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay);
|
||||
|
||||
let children = Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::children(
|
||||
&context_menu,
|
||||
);
|
||||
assert_eq!(children.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_size_matches_underlay() {
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay);
|
||||
|
||||
let size =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::size(&context_menu);
|
||||
assert_eq!(size.width, Length::Shrink);
|
||||
assert_eq!(size.height, Length::Shrink);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_cursor_position_can_be_set() {
|
||||
let mut state = State::new();
|
||||
state.cursor_position = Point::new(100.0, 200.0);
|
||||
assert_eq!(state.cursor_position.x, 100.0);
|
||||
assert_eq!(state.cursor_position.y, 200.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_show_can_be_toggled() {
|
||||
let mut state = State::new();
|
||||
assert!(!state.show);
|
||||
|
||||
state.show = true;
|
||||
assert!(state.show);
|
||||
|
||||
state.show = false;
|
||||
assert!(!state.show);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_allows_show_and_position_updates() {
|
||||
// Test that State can track show status and cursor position
|
||||
// This exercises the internal state logic used by update()
|
||||
let mut state = State::new();
|
||||
|
||||
// Initially not shown
|
||||
assert!(!state.show);
|
||||
assert_eq!(state.cursor_position, Point::ORIGIN);
|
||||
|
||||
// Simulate right-click at position
|
||||
state.show = !state.show;
|
||||
state.cursor_position = Point::new(10.0, 10.0);
|
||||
|
||||
assert!(state.show);
|
||||
assert_eq!(state.cursor_position, Point::new(10.0, 10.0));
|
||||
|
||||
// Simulate toggle off
|
||||
state.show = !state.show;
|
||||
assert!(!state.show);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widget_state_creates_correct_initial_state() {
|
||||
// Test that widget creates correct initial state
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay);
|
||||
|
||||
let state =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::state(&context_menu);
|
||||
|
||||
// Verify state is created with correct type
|
||||
let s: &State = state.downcast_ref();
|
||||
assert!(!s.show);
|
||||
assert_eq!(s.cursor_position, Point::ORIGIN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widget_children_returns_two_elements() {
|
||||
// Test that children() returns underlay and overlay
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay);
|
||||
|
||||
let children = Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::children(
|
||||
&context_menu,
|
||||
);
|
||||
|
||||
// Should have 2 children: underlay and overlay
|
||||
assert_eq!(children.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_method_sets_force_open_to_true() {
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay).open(true);
|
||||
|
||||
assert_eq!(context_menu.force_open, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_method_sets_force_open_to_false() {
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay).open(false);
|
||||
|
||||
assert_eq!(context_menu.force_open, Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_method_can_be_chained() {
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay)
|
||||
.open(true)
|
||||
.class(<iced_widget::Theme as crate::style::context_menu::Catalog>::default());
|
||||
|
||||
assert_eq!(context_menu.force_open, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_force_open_is_none() {
|
||||
let underlay = iced_widget::text::Text::new("Underlay");
|
||||
let context_menu = TestContextMenu::new(underlay, create_overlay);
|
||||
|
||||
assert_eq!(context_menu.force_open, None);
|
||||
}
|
||||
}
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
//! A container widget that allows you to specify the layout of its children.
|
||||
|
||||
use iced_core::{Length, Rectangle, Widget};
|
||||
|
||||
#[allow(unused_imports)]
|
||||
pub use iced_core::{
|
||||
Renderer,
|
||||
layout::{Limits, Node},
|
||||
widget::Tree,
|
||||
};
|
||||
|
||||
type LayoutFn<'a, Message, Theme, Renderer> = Box<
|
||||
dyn Fn(
|
||||
&mut Vec<iced_core::Element<'a, Message, Theme, Renderer>>,
|
||||
&mut Vec<Tree>,
|
||||
&Renderer,
|
||||
&Limits,
|
||||
) -> Node,
|
||||
>;
|
||||
|
||||
/// A container widget that allows you to specify the layout of its children.
|
||||
pub struct CustomLayout<'a, Message, Theme, Renderer> {
|
||||
elements: Vec<iced_core::Element<'a, Message, Theme, Renderer>>,
|
||||
width: Length,
|
||||
height: Length,
|
||||
layout: LayoutFn<'a, Message, Theme, Renderer>,
|
||||
}
|
||||
|
||||
impl<'b, Message, Theme, Renderer: iced_core::Renderer> CustomLayout<'b, Message, Theme, Renderer> {
|
||||
/// Creates a new [`CustomLayout`]
|
||||
pub fn new(
|
||||
elements: Vec<iced_core::Element<'b, Message, Theme, Renderer>>,
|
||||
layout: impl Fn(
|
||||
&mut Vec<iced_core::Element<'b, Message, Theme, Renderer>>,
|
||||
&mut Vec<Tree>,
|
||||
&Renderer,
|
||||
&Limits,
|
||||
) -> Node
|
||||
+ 'static,
|
||||
) -> Self {
|
||||
Self {
|
||||
elements,
|
||||
width: Length::Shrink,
|
||||
height: Length::Shrink,
|
||||
layout: Box::new(layout),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the width of the [`CustomLayout`]
|
||||
#[must_use]
|
||||
pub fn width(mut self, length: impl Into<Length>) -> Self {
|
||||
self.width = length.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`CustomLayout`]
|
||||
#[must_use]
|
||||
pub fn height(mut self, length: impl Into<Length>) -> Self {
|
||||
self.height = length.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme, Renderer: iced_core::Renderer> Widget<Message, Theme, Renderer>
|
||||
for CustomLayout<'_, Message, Theme, Renderer>
|
||||
{
|
||||
fn size(&self) -> iced_core::Size<Length> {
|
||||
iced_core::Size::new(self.width, self.height)
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
(self.layout)(&mut self.elements, &mut tree.children, renderer, limits)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &iced_core::renderer::Style,
|
||||
layout: iced_core::Layout<'_>,
|
||||
cursor: iced_core::mouse::Cursor,
|
||||
viewport: &iced_core::Rectangle,
|
||||
) {
|
||||
tree.children
|
||||
.iter()
|
||||
.zip(layout.children())
|
||||
.zip(self.elements.iter())
|
||||
.for_each(|((state, layout), element)| {
|
||||
element
|
||||
.as_widget()
|
||||
.draw(state, renderer, theme, style, layout, cursor, viewport);
|
||||
});
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
self.elements.iter().map(|x| Tree::new(x)).collect()
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(&self.elements);
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
layout: iced_core::Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn iced_core::widget::Operation,
|
||||
) {
|
||||
state
|
||||
.children
|
||||
.iter_mut()
|
||||
.zip(layout.children())
|
||||
.zip(self.elements.iter_mut())
|
||||
.for_each(|((state, layout), element)| {
|
||||
operation.container(None, layout.bounds());
|
||||
operation.traverse(&mut |operation| {
|
||||
element
|
||||
.as_widget_mut()
|
||||
.operate(state, layout, renderer, operation);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &iced_core::Event,
|
||||
layout: iced_core::Layout<'_>,
|
||||
cursor: iced_core::mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn iced_core::Clipboard,
|
||||
shell: &mut iced_core::Shell<'_, Message>,
|
||||
viewport: &iced_core::Rectangle,
|
||||
) {
|
||||
for ((state, layout), element) in state
|
||||
.children
|
||||
.iter_mut()
|
||||
.zip(layout.children())
|
||||
.zip(self.elements.iter_mut())
|
||||
{
|
||||
element.as_widget_mut().update(
|
||||
state, event, layout, cursor, renderer, clipboard, shell, viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> iced_core::Size<Length> {
|
||||
self.size()
|
||||
}
|
||||
|
||||
fn overlay<'a>(
|
||||
&'a mut self,
|
||||
state: &'a mut Tree,
|
||||
layout: iced_core::Layout<'a>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: iced_core::Vector,
|
||||
) -> Option<iced_core::overlay::Element<'a, Message, Theme, Renderer>> {
|
||||
iced_core::overlay::from_children(
|
||||
&mut self.elements,
|
||||
state,
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
)
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: iced_core::Layout<'_>,
|
||||
cursor: iced_core::mouse::Cursor,
|
||||
viewport: &iced_core::Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> iced_core::mouse::Interaction {
|
||||
self.elements
|
||||
.iter()
|
||||
.zip(&state.children)
|
||||
.zip(layout.children())
|
||||
.map(|((child, state), layout)| {
|
||||
child
|
||||
.as_widget()
|
||||
.mouse_interaction(state, layout, cursor, viewport, renderer)
|
||||
})
|
||||
.max()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'b, Message: 'b, Theme: 'b, Renderer: iced_core::Renderer + 'b>
|
||||
From<CustomLayout<'b, Message, Theme, Renderer>>
|
||||
for iced_core::Element<'b, Message, Theme, Renderer>
|
||||
{
|
||||
fn from(value: CustomLayout<'b, Message, Theme, Renderer>) -> Self {
|
||||
iced_core::Element::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use iced_core::{Size, layout::Node};
|
||||
|
||||
#[derive(Clone)]
|
||||
enum TestMessage {}
|
||||
|
||||
type TestCustomLayout<'a> =
|
||||
CustomLayout<'a, TestMessage, iced_widget::Theme, iced_widget::Renderer>;
|
||||
|
||||
fn simple_layout_fn(
|
||||
_elements: &mut Vec<
|
||||
iced_core::Element<'_, TestMessage, iced_widget::Theme, iced_widget::Renderer>,
|
||||
>,
|
||||
_trees: &mut Vec<Tree>,
|
||||
_renderer: &iced_widget::Renderer,
|
||||
limits: &Limits,
|
||||
) -> Node {
|
||||
Node::new(limits.resolve(Length::Shrink, Length::Shrink, Size::ZERO))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_new_has_default_values() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn);
|
||||
|
||||
assert_eq!(layout.width, Length::Shrink);
|
||||
assert_eq!(layout.height, Length::Shrink);
|
||||
assert_eq!(layout.elements.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_width_sets_value() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn).width(200);
|
||||
assert_eq!(layout.width, Length::Fixed(200.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_width_fill_sets_value() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn).width(Length::Fill);
|
||||
assert_eq!(layout.width, Length::Fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_height_sets_value() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn).height(100);
|
||||
assert_eq!(layout.height, Length::Fixed(100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_height_shrink_sets_value() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn).height(Length::Shrink);
|
||||
assert_eq!(layout.height, Length::Shrink);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_size_method_returns_correct_size() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn)
|
||||
.width(150)
|
||||
.height(75);
|
||||
|
||||
let size = Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::size(&layout);
|
||||
assert_eq!(size.width, Length::Fixed(150.0));
|
||||
assert_eq!(size.height, Length::Fixed(75.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_chaining_methods() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn)
|
||||
.width(200)
|
||||
.height(100);
|
||||
|
||||
assert_eq!(layout.width, Length::Fixed(200.0));
|
||||
assert_eq!(layout.height, Length::Fixed(100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_with_elements() {
|
||||
let elements = vec![
|
||||
iced_widget::text::Text::new("Element 1").into(),
|
||||
iced_widget::text::Text::new("Element 2").into(),
|
||||
];
|
||||
let layout = TestCustomLayout::new(elements, simple_layout_fn);
|
||||
|
||||
assert_eq!(layout.elements.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_children_count_matches_elements() {
|
||||
let elements = vec![
|
||||
iced_widget::text::Text::new("Element 1").into(),
|
||||
iced_widget::text::Text::new("Element 2").into(),
|
||||
iced_widget::text::Text::new("Element 3").into(),
|
||||
];
|
||||
let layout = TestCustomLayout::new(elements, simple_layout_fn);
|
||||
|
||||
let children =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::children(&layout);
|
||||
assert_eq!(children.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_empty_elements() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn);
|
||||
|
||||
let children =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::children(&layout);
|
||||
assert_eq!(children.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_length_fillportion() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn)
|
||||
.width(Length::FillPortion(2))
|
||||
.height(Length::FillPortion(3));
|
||||
|
||||
assert_eq!(layout.width, Length::FillPortion(2));
|
||||
assert_eq!(layout.height, Length::FillPortion(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_layout_size_hint_equals_size() {
|
||||
let layout = TestCustomLayout::new(vec![], simple_layout_fn)
|
||||
.width(100)
|
||||
.height(50);
|
||||
|
||||
let size = Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::size(&layout);
|
||||
let size_hint =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::size_hint(&layout);
|
||||
|
||||
assert_eq!(size.width, size_hint.width);
|
||||
assert_eq!(size.height, size_hint.height);
|
||||
}
|
||||
}
|
||||
+538
@@ -0,0 +1,538 @@
|
||||
//! Use a date picker as an input element for picking dates.
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: `date_picker`*
|
||||
|
||||
use super::overlay::date_picker::{self, DatePickerOverlay, DatePickerOverlayButtons};
|
||||
|
||||
use chrono::Local;
|
||||
use iced_core::{
|
||||
Clipboard, Element, Event, Layout, Length, Pixels, Point, Rectangle, Shell, Size, Vector,
|
||||
Widget,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
renderer,
|
||||
text::Renderer as _,
|
||||
widget::{
|
||||
self,
|
||||
tree::{Tag, Tree},
|
||||
},
|
||||
};
|
||||
use iced_widget::Renderer;
|
||||
|
||||
pub use crate::{
|
||||
core::date::Date,
|
||||
style::{Status, StyleFn, date_picker::Style},
|
||||
};
|
||||
|
||||
//TODO: Remove ignore when Null is updated. Temp fix for Test runs
|
||||
/// An input element for picking dates.
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// # use iced_aw::DatePicker;
|
||||
/// # use iced_widget::{button, Button, Text};
|
||||
/// #
|
||||
/// #[derive(Clone, Debug)]
|
||||
/// enum Message {
|
||||
/// Open,
|
||||
/// Cancel,
|
||||
/// Submit(date_picker::Date),
|
||||
/// }
|
||||
///
|
||||
/// let date_picker = DatePicker::new(
|
||||
/// true,
|
||||
/// date_picker::Date::today(),
|
||||
/// Button::new(Text::new("Pick date"))
|
||||
/// .on_press(Message::Open),
|
||||
/// Message::Cancel,
|
||||
/// Message::Submit,
|
||||
/// );
|
||||
/// ```
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct DatePicker<'a, Message, Theme>
|
||||
where
|
||||
Message: Clone,
|
||||
Theme: crate::style::date_picker::Catalog + iced_widget::button::Catalog,
|
||||
{
|
||||
/// Show the picker.
|
||||
show_picker: bool,
|
||||
/// The date to show.
|
||||
date: Date,
|
||||
/// The underlying element.
|
||||
underlay: Element<'a, Message, Theme, Renderer>,
|
||||
/// The message that is send if the cancel button of the [`DatePickerOverlay`] is pressed.
|
||||
on_cancel: Message,
|
||||
/// The function that produces a message when the submit button of the [`DatePickerOverlay`] is pressed.
|
||||
on_submit: Box<dyn Fn(Date) -> Message>,
|
||||
/// The style of the [`DatePickerOverlay`].
|
||||
class: <Theme as crate::style::date_picker::Catalog>::Class<'a>,
|
||||
/// The buttons of the overlay.
|
||||
overlay_state: Element<'a, Message, Theme, Renderer>,
|
||||
//button_style: <Renderer as button::Renderer>::Style, // clone not satisfied
|
||||
/// The font and icon size of the [`DatePickerOverlay`] or `None` for the default
|
||||
font_size: Option<Pixels>,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme> DatePicker<'a, Message, Theme>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Theme: 'a
|
||||
+ crate::style::date_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog
|
||||
+ iced_widget::container::Catalog,
|
||||
{
|
||||
/// Creates a new [`DatePicker`] wrapping around the given underlay.
|
||||
///
|
||||
/// It expects:
|
||||
/// * if the overlay of the date picker is visible.
|
||||
/// * the initial date to show.
|
||||
/// * the underlay [`Element`] on which this [`DatePicker`]
|
||||
/// will be wrapped around.
|
||||
/// * a message that will be send when the cancel button of the [`DatePicker`]
|
||||
/// is pressed.
|
||||
/// * a function that will be called when the submit button of the [`DatePicker`]
|
||||
/// is pressed, which takes the picked [`Date`] value.
|
||||
pub fn new<U, F>(
|
||||
show_picker: bool,
|
||||
date: impl Into<Date>,
|
||||
underlay: U,
|
||||
on_cancel: Message,
|
||||
on_submit: F,
|
||||
) -> Self
|
||||
where
|
||||
U: Into<Element<'a, Message, Theme, Renderer>>,
|
||||
F: 'static + Fn(Date) -> Message,
|
||||
{
|
||||
Self {
|
||||
show_picker,
|
||||
date: date.into(),
|
||||
underlay: underlay.into(),
|
||||
on_cancel,
|
||||
on_submit: Box::new(on_submit),
|
||||
class: <Theme as crate::style::date_picker::Catalog>::default(),
|
||||
overlay_state: DatePickerOverlayButtons::default().into(),
|
||||
//button_style: <Renderer as button::Renderer>::Style::default(),
|
||||
font_size: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the style of the [`DatePicker`].
|
||||
#[must_use]
|
||||
pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
|
||||
where
|
||||
<Theme as crate::style::date_picker::Catalog>::Class<'a>: From<StyleFn<'a, Theme, Style>>,
|
||||
{
|
||||
self.class = (Box::new(style) as StyleFn<'a, Theme, Style>).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the font and icon size of the [`DatePicker`].
|
||||
#[must_use]
|
||||
pub fn font_size<P: Into<Pixels>>(mut self, size: P) -> Self {
|
||||
self.font_size = Some(size.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the class of the input of the [`DatePicker`].
|
||||
#[must_use]
|
||||
pub fn class(
|
||||
mut self,
|
||||
class: impl Into<<Theme as crate::style::date_picker::Catalog>::Class<'a>>,
|
||||
) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The state of the [`DatePicker`] / [`DatePickerOverlay`].
|
||||
#[derive(Debug)]
|
||||
pub struct State {
|
||||
/// The state of the overlay.
|
||||
pub(crate) overlay_state: date_picker::State,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Creates a new [`State`] with the current date.
|
||||
#[must_use]
|
||||
pub fn now() -> Self {
|
||||
Self {
|
||||
overlay_state: date_picker::State::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new [`State`] with the given date.
|
||||
#[must_use]
|
||||
pub fn new(date: Date) -> Self {
|
||||
Self {
|
||||
overlay_state: date_picker::State::new(date.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the date of the state to the current date.
|
||||
pub fn reset(&mut self) {
|
||||
self.overlay_state.date = Local::now().naive_local().date();
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme> Widget<Message, Theme, Renderer> for DatePicker<'_, Message, Theme>
|
||||
where
|
||||
Message: 'static + Clone,
|
||||
Theme: crate::style::date_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog
|
||||
+ iced_widget::container::Catalog,
|
||||
{
|
||||
fn tag(&self) -> Tag {
|
||||
Tag::of::<State>()
|
||||
}
|
||||
|
||||
fn state(&self) -> widget::tree::State {
|
||||
widget::tree::State::new(State::new(self.date))
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
vec![Tree::new(&self.underlay), Tree::new(&self.overlay_state)]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(&[&self.underlay, &self.overlay_state]);
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
self.underlay.as_widget().size()
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
self.underlay
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree.children[0], renderer, limits)
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.underlay.as_widget_mut().update(
|
||||
&mut state.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.underlay.as_widget().mouse_interaction(
|
||||
&state.children[0],
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn widget::Operation<()>,
|
||||
) {
|
||||
self.underlay
|
||||
.as_widget_mut()
|
||||
.operate(&mut state.children[0], layout, renderer, operation);
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.underlay.as_widget().draw(
|
||||
&state.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
tree: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<iced_core::overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
let picker_state: &mut State = tree.state.downcast_mut();
|
||||
|
||||
if !self.show_picker {
|
||||
return self.underlay.as_widget_mut().overlay(
|
||||
&mut tree.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
);
|
||||
}
|
||||
|
||||
let bounds = layout.bounds();
|
||||
let position = Point::new(bounds.center_x(), bounds.center_y());
|
||||
|
||||
Some(
|
||||
DatePickerOverlay::new(
|
||||
picker_state,
|
||||
self.on_cancel.clone(),
|
||||
&self.on_submit,
|
||||
position,
|
||||
&self.class,
|
||||
&mut tree.children[1],
|
||||
self.font_size.unwrap_or_else(|| renderer.default_size()),
|
||||
*viewport,
|
||||
)
|
||||
.overlay(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme> From<DatePicker<'a, Message, Theme>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'static + Clone,
|
||||
Theme: 'a
|
||||
+ crate::style::date_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog
|
||||
+ iced_widget::container::Catalog,
|
||||
{
|
||||
fn from(date_picker: DatePicker<'a, Message, Theme>) -> Self {
|
||||
Element::new(date_picker)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::Datelike;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum TestMessage {
|
||||
Cancel,
|
||||
Submit(Date),
|
||||
}
|
||||
|
||||
type TestDatePicker<'a> = DatePicker<'a, TestMessage, iced_widget::Theme>;
|
||||
|
||||
#[test]
|
||||
fn state_new_creates_state_with_date() {
|
||||
let date = Date::from_ymd(2024, 6, 15);
|
||||
let state = State::new(date);
|
||||
|
||||
assert_eq!(state.overlay_state.date.year(), 2024);
|
||||
assert_eq!(state.overlay_state.date.month(), 6);
|
||||
assert_eq!(state.overlay_state.date.day(), 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_now_creates_state() {
|
||||
let state = State::now();
|
||||
// Just verify it was created successfully
|
||||
assert!(state.overlay_state.date.year() > 2020);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_reset_updates_to_current_date() {
|
||||
let old_date = Date::from_ymd(2020, 1, 1);
|
||||
let mut state = State::new(old_date);
|
||||
|
||||
state.reset();
|
||||
|
||||
// After reset, the date should be current (greater than 2020)
|
||||
assert!(state.overlay_state.date.year() >= 2024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_picker_new_creates_instance() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a date");
|
||||
let date = Date::from_ymd(2024, 6, 15);
|
||||
|
||||
let date_picker = TestDatePicker::new(
|
||||
false,
|
||||
date,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
assert!(!date_picker.show_picker);
|
||||
assert_eq!(date_picker.date.year, 2024);
|
||||
assert_eq!(date_picker.date.month, 6);
|
||||
assert_eq!(date_picker.date.day, 15);
|
||||
assert!(date_picker.font_size.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_picker_show_picker_true() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a date");
|
||||
let date = Date::from_ymd(2024, 1, 1);
|
||||
|
||||
let date_picker = TestDatePicker::new(
|
||||
true,
|
||||
date,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
assert!(date_picker.show_picker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_picker_font_size_sets_value() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a date");
|
||||
let date = Date::from_ymd(2024, 1, 1);
|
||||
|
||||
let date_picker = TestDatePicker::new(
|
||||
false,
|
||||
date,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
)
|
||||
.font_size(20.0);
|
||||
|
||||
assert_eq!(date_picker.font_size, Some(Pixels(20.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_picker_font_size_from_integer() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a date");
|
||||
let date = Date::from_ymd(2024, 1, 1);
|
||||
|
||||
let date_picker = TestDatePicker::new(
|
||||
false,
|
||||
date,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
)
|
||||
.font_size(16);
|
||||
|
||||
assert_eq!(date_picker.font_size, Some(Pixels(16.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_picker_tag_returns_state_tag() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a date");
|
||||
let date = Date::from_ymd(2024, 1, 1);
|
||||
|
||||
let date_picker = TestDatePicker::new(
|
||||
false,
|
||||
date,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
let tag = Widget::<TestMessage, iced_widget::Theme, Renderer>::tag(&date_picker);
|
||||
assert_eq!(tag, Tag::of::<State>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_picker_has_two_children() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a date");
|
||||
let date = Date::from_ymd(2024, 1, 1);
|
||||
|
||||
let date_picker = TestDatePicker::new(
|
||||
false,
|
||||
date,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
let children = Widget::<TestMessage, iced_widget::Theme, Renderer>::children(&date_picker);
|
||||
assert_eq!(children.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_picker_size_matches_underlay() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a date");
|
||||
let date = Date::from_ymd(2024, 1, 1);
|
||||
|
||||
let date_picker = TestDatePicker::new(
|
||||
false,
|
||||
date,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
let size = Widget::<TestMessage, iced_widget::Theme, Renderer>::size(&date_picker);
|
||||
assert_eq!(size.width, Length::Shrink);
|
||||
assert_eq!(size.height, Length::Shrink);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_picker_different_dates() {
|
||||
let test_dates = [
|
||||
(2024, 1, 1),
|
||||
(2024, 12, 31),
|
||||
(2025, 6, 15),
|
||||
(2020, 2, 29), // Leap year
|
||||
];
|
||||
|
||||
for (year, month, day) in test_dates {
|
||||
let date = Date::from_ymd(year, month, day);
|
||||
let underlay = iced_widget::text::Text::new("Pick a date");
|
||||
|
||||
let date_picker = TestDatePicker::new(
|
||||
false,
|
||||
date,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
assert_eq!(date_picker.date.year, year);
|
||||
assert_eq!(date_picker.date.month, month);
|
||||
assert_eq!(date_picker.date.day, day);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_from_ymd_creates_correct_date() {
|
||||
let date = Date::from_ymd(2024, 7, 20);
|
||||
|
||||
assert_eq!(date.year, 2024);
|
||||
assert_eq!(date.month, 7);
|
||||
assert_eq!(date.day, 20);
|
||||
}
|
||||
}
|
||||
+902
@@ -0,0 +1,902 @@
|
||||
//! Drop down menu widget
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: `drop_down`*
|
||||
|
||||
use iced_core::{
|
||||
Clipboard, Element, Event, Layout, Length, Point, Rectangle, Shell, Size, Vector, Widget,
|
||||
keyboard::{self, key::Named},
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
overlay, renderer, touch,
|
||||
widget::{self, Operation, Tree},
|
||||
};
|
||||
|
||||
pub use crate::core::{alignment::Alignment, offset::Offset};
|
||||
|
||||
/// Customizable drop down menu widget
|
||||
pub struct DropDown<'a, Message, Theme = iced_widget::Theme, Renderer = iced_widget::Renderer>
|
||||
where
|
||||
Message: Clone,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
underlay: Element<'a, Message, Theme, Renderer>,
|
||||
overlay: Element<'a, Message, Theme, Renderer>,
|
||||
on_dismiss: Option<Message>,
|
||||
width: Option<Length>,
|
||||
height: Length,
|
||||
alignment: Alignment,
|
||||
offset: Offset,
|
||||
expanded: bool,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> DropDown<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
/// Create a new [`DropDown`]
|
||||
pub fn new<U, B>(underlay: U, overlay: B, expanded: bool) -> Self
|
||||
where
|
||||
U: Into<Element<'a, Message, Theme, Renderer>>,
|
||||
B: Into<Element<'a, Message, Theme, Renderer>>,
|
||||
{
|
||||
DropDown {
|
||||
underlay: underlay.into(),
|
||||
overlay: overlay.into(),
|
||||
expanded,
|
||||
on_dismiss: None,
|
||||
width: None,
|
||||
height: Length::Shrink,
|
||||
alignment: Alignment::Bottom,
|
||||
offset: Offset::from(5.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The width of the overlay
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = Some(width.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// The height of the overlay
|
||||
#[must_use]
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// The alignment of the overlay relative to the underlay
|
||||
#[must_use]
|
||||
pub fn alignment(mut self, alignment: impl Into<Alignment>) -> Self {
|
||||
self.alignment = alignment.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// The offset of the overlay
|
||||
#[must_use]
|
||||
pub fn offset(mut self, offset: impl Into<Offset>) -> Self {
|
||||
self.offset = offset.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Send a message when a click occur outside of the overlay when expanded
|
||||
#[must_use]
|
||||
pub fn on_dismiss(mut self, message: Message) -> Self {
|
||||
self.on_dismiss = Some(message);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for DropDown<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
{
|
||||
fn size(&self) -> Size<Length> {
|
||||
self.underlay.as_widget().size()
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
self.underlay
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree.children[0], renderer, limits)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.underlay.as_widget().draw(
|
||||
&state.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
vec![Tree::new(&self.underlay), Tree::new(&self.overlay)]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(&[&self.underlay, &self.overlay]);
|
||||
}
|
||||
|
||||
fn operate<'b>(
|
||||
&'b mut self,
|
||||
state: &'b mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
self.underlay
|
||||
.as_widget_mut()
|
||||
.operate(&mut state.children[0], layout, renderer, operation);
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.underlay.as_widget_mut().update(
|
||||
&mut state.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.underlay.as_widget().mouse_interaction(
|
||||
&state.children[0],
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
state: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
if !self.expanded {
|
||||
return self.underlay.as_widget_mut().overlay(
|
||||
&mut state.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
);
|
||||
}
|
||||
|
||||
Some(overlay::Element::new(Box::new(DropDownOverlay::new(
|
||||
&mut state.children[1],
|
||||
&mut self.overlay,
|
||||
self.on_dismiss.as_ref(),
|
||||
self.width.as_ref(),
|
||||
&self.height,
|
||||
&self.alignment,
|
||||
&self.offset,
|
||||
layout.bounds(),
|
||||
layout.position() + translation,
|
||||
*viewport,
|
||||
))))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme: 'a, Renderer> From<DropDown<'a, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
{
|
||||
fn from(drop_down: DropDown<'a, Message, Theme, Renderer>) -> Self {
|
||||
Element::new(drop_down)
|
||||
}
|
||||
}
|
||||
|
||||
struct DropDownOverlay<
|
||||
'a,
|
||||
'b,
|
||||
Message,
|
||||
Theme = iced_widget::Theme,
|
||||
Renderer = iced_widget::Renderer,
|
||||
> where
|
||||
Message: Clone,
|
||||
{
|
||||
state: &'b mut Tree,
|
||||
element: &'b mut Element<'a, Message, Theme, Renderer>,
|
||||
on_dismiss: Option<&'b Message>,
|
||||
width: Option<&'b Length>,
|
||||
height: &'b Length,
|
||||
alignment: &'b Alignment,
|
||||
offset: &'b Offset,
|
||||
underlay_bounds: Rectangle,
|
||||
position: Point,
|
||||
viewport: Rectangle,
|
||||
}
|
||||
|
||||
impl<'a, 'b, Message, Theme, Renderer> DropDownOverlay<'a, 'b, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn new(
|
||||
state: &'b mut Tree,
|
||||
element: &'b mut Element<'a, Message, Theme, Renderer>,
|
||||
on_dismiss: Option<&'b Message>,
|
||||
width: Option<&'b Length>,
|
||||
height: &'b Length,
|
||||
alignment: &'b Alignment,
|
||||
offset: &'b Offset,
|
||||
underlay_bounds: Rectangle,
|
||||
position: Point,
|
||||
viewport: Rectangle,
|
||||
) -> Self {
|
||||
DropDownOverlay {
|
||||
state,
|
||||
element,
|
||||
on_dismiss,
|
||||
width,
|
||||
height,
|
||||
alignment,
|
||||
offset,
|
||||
underlay_bounds,
|
||||
position,
|
||||
viewport,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme, Renderer> overlay::Overlay<Message, Theme, Renderer>
|
||||
for DropDownOverlay<'_, '_, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
fn layout(&mut self, renderer: &Renderer, bounds: Size) -> Node {
|
||||
let limits = Limits::new(Size::ZERO, bounds)
|
||||
.width(
|
||||
*self
|
||||
.width
|
||||
.unwrap_or(&Length::Fixed(self.underlay_bounds.width)),
|
||||
)
|
||||
.height(*self.height);
|
||||
|
||||
let previous_position = self.position;
|
||||
let max = limits.max();
|
||||
|
||||
let height_above = (previous_position.y - self.offset.y).max(0.0);
|
||||
let height_below =
|
||||
(max.height - previous_position.y - self.underlay_bounds.height - self.offset.y)
|
||||
.max(0.0);
|
||||
|
||||
let ref_center_y = previous_position.y + self.underlay_bounds.height / 2.0;
|
||||
let max_height_symmetric = (ref_center_y.min(max.height - ref_center_y) * 2.0).max(0.0);
|
||||
|
||||
let limits = match self.alignment {
|
||||
Alignment::Top => limits.max_height(height_above),
|
||||
Alignment::TopStart | Alignment::TopEnd => {
|
||||
limits.max_height((height_above + self.underlay_bounds.height).max(0.0))
|
||||
}
|
||||
Alignment::Bottom => limits.max_height(height_below),
|
||||
Alignment::BottomEnd | Alignment::BottomStart => {
|
||||
limits.max_height((height_below + self.underlay_bounds.height).max(0.0))
|
||||
}
|
||||
Alignment::Start | Alignment::End => limits.max_height(max_height_symmetric),
|
||||
};
|
||||
|
||||
let node = self
|
||||
.element
|
||||
.as_widget_mut()
|
||||
.layout(self.state, renderer, &limits);
|
||||
|
||||
let mut new_position = match self.alignment {
|
||||
Alignment::TopStart => Point::new(
|
||||
previous_position.x - node.bounds().width - self.offset.x,
|
||||
previous_position.y - node.bounds().height + self.underlay_bounds.height
|
||||
- self.offset.y,
|
||||
),
|
||||
Alignment::Top => Point::new(
|
||||
previous_position.x + self.underlay_bounds.width / 2.0 - node.bounds().width / 2.0,
|
||||
previous_position.y - node.bounds().height - self.offset.y,
|
||||
),
|
||||
Alignment::TopEnd => Point::new(
|
||||
previous_position.x + self.underlay_bounds.width + self.offset.x,
|
||||
previous_position.y - node.bounds().height + self.underlay_bounds.height
|
||||
- self.offset.y,
|
||||
),
|
||||
Alignment::End => Point::new(
|
||||
previous_position.x + self.underlay_bounds.width + self.offset.x,
|
||||
previous_position.y + self.underlay_bounds.height / 2.0
|
||||
- node.bounds().height / 2.0,
|
||||
),
|
||||
Alignment::BottomEnd => Point::new(
|
||||
previous_position.x + self.underlay_bounds.width + self.offset.x,
|
||||
previous_position.y + self.offset.y,
|
||||
),
|
||||
Alignment::Bottom => Point::new(
|
||||
previous_position.x + self.underlay_bounds.width / 2.0 - node.bounds().width / 2.0,
|
||||
previous_position.y + self.underlay_bounds.height + self.offset.y,
|
||||
),
|
||||
Alignment::BottomStart => Point::new(
|
||||
previous_position.x - node.bounds().width - self.offset.x,
|
||||
previous_position.y + self.offset.y,
|
||||
),
|
||||
Alignment::Start => Point::new(
|
||||
previous_position.x - node.bounds().width - self.offset.x,
|
||||
previous_position.y + self.underlay_bounds.height / 2.0
|
||||
- node.bounds().height / 2.0,
|
||||
),
|
||||
};
|
||||
|
||||
if new_position.x + node.bounds().width > self.viewport.width {
|
||||
new_position.x -= node.bounds().width;
|
||||
}
|
||||
|
||||
if new_position.x < 0.0 {
|
||||
new_position.x = 0.0;
|
||||
}
|
||||
|
||||
if new_position.y + node.bounds().height > self.viewport.height {
|
||||
new_position.y -= node.bounds().height;
|
||||
}
|
||||
if new_position.y < 0.0 {
|
||||
new_position.y = 0.0;
|
||||
}
|
||||
|
||||
node.move_to(new_position)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
) {
|
||||
let bounds = layout.bounds();
|
||||
self.element
|
||||
.as_widget()
|
||||
.draw(self.state, renderer, theme, style, layout, cursor, &bounds);
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<Message>,
|
||||
) {
|
||||
self.underlay_bounds = Rectangle {
|
||||
x: self.position.x,
|
||||
y: self.position.y,
|
||||
width: self.underlay_bounds.width,
|
||||
height: self.underlay_bounds.height,
|
||||
};
|
||||
|
||||
if let Some(on_dismiss) = self.on_dismiss {
|
||||
match &event {
|
||||
Event::Keyboard(keyboard::Event::KeyPressed { key, .. })
|
||||
if key == &keyboard::Key::Named(Named::Escape) =>
|
||||
{
|
||||
shell.publish(on_dismiss.clone());
|
||||
}
|
||||
|
||||
Event::Mouse(mouse::Event::ButtonPressed(
|
||||
mouse::Button::Left | mouse::Button::Right,
|
||||
))
|
||||
| Event::Touch(touch::Event::FingerPressed { .. })
|
||||
if !cursor.is_over(layout.bounds())
|
||||
&& !cursor.is_over(self.underlay_bounds) =>
|
||||
{
|
||||
shell.publish(on_dismiss.clone());
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
self.element.as_widget_mut().update(
|
||||
self.state,
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
&layout.bounds(),
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.element.as_widget().mouse_interaction(
|
||||
self.state,
|
||||
layout,
|
||||
cursor,
|
||||
&self.viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn widget::Operation,
|
||||
) {
|
||||
// Operate on the overlay element to expose its children for testing
|
||||
self.element
|
||||
.as_widget_mut()
|
||||
.operate(self.state, layout, renderer, operation);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use iced_widget::text::Text;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum TestMessage {
|
||||
Dismiss,
|
||||
Select(usize),
|
||||
}
|
||||
|
||||
type TestDropDown<'a> = DropDown<'a, TestMessage, iced_widget::Theme, iced_widget::Renderer>;
|
||||
|
||||
// ============================================================================
|
||||
// Construction Tests
|
||||
// ============================================================================
|
||||
|
||||
#[test]
|
||||
fn drop_down_new_creates_instance() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false);
|
||||
|
||||
assert!(!dropdown.expanded, "Should not be expanded by default");
|
||||
assert!(
|
||||
dropdown.on_dismiss.is_none(),
|
||||
"Should have no dismiss message"
|
||||
);
|
||||
assert!(dropdown.width.is_none(), "Should have no custom width");
|
||||
assert_eq!(
|
||||
dropdown.height,
|
||||
Length::Shrink,
|
||||
"Default height should be Shrink"
|
||||
);
|
||||
assert_eq!(
|
||||
dropdown.alignment,
|
||||
Alignment::Bottom,
|
||||
"Default alignment should be Bottom"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_new_with_expanded_true() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, true);
|
||||
|
||||
assert!(dropdown.expanded, "Should be expanded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_new_with_expanded_false() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false);
|
||||
|
||||
assert!(!dropdown.expanded, "Should not be expanded");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Builder Method Tests
|
||||
// ============================================================================
|
||||
|
||||
#[test]
|
||||
fn drop_down_width_sets_value() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).width(Length::Fixed(200.0));
|
||||
|
||||
assert_eq!(dropdown.width, Some(Length::Fixed(200.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_width_fill() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).width(Length::Fill);
|
||||
|
||||
assert_eq!(dropdown.width, Some(Length::Fill));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_height_sets_value() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).height(Length::Fixed(150.0));
|
||||
|
||||
assert_eq!(dropdown.height, Length::Fixed(150.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_height_fill() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).height(Length::Fill);
|
||||
|
||||
assert_eq!(dropdown.height, Length::Fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_alignment_sets_value() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).alignment(Alignment::Top);
|
||||
|
||||
assert_eq!(dropdown.alignment, Alignment::Top);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_alignment_bottom_start() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown =
|
||||
TestDropDown::new(underlay, overlay, false).alignment(Alignment::BottomStart);
|
||||
|
||||
assert_eq!(dropdown.alignment, Alignment::BottomStart);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_alignment_top_end() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).alignment(Alignment::TopEnd);
|
||||
|
||||
assert_eq!(dropdown.alignment, Alignment::TopEnd);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_offset_sets_value() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).offset(Offset::from(10.0));
|
||||
|
||||
assert_eq!(dropdown.offset.x, 10.0);
|
||||
assert_eq!(dropdown.offset.y, 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_offset_different_x_y() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
let custom_offset = Offset { x: 5.0, y: 15.0 };
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).offset(custom_offset);
|
||||
|
||||
assert_eq!(dropdown.offset.x, 5.0);
|
||||
assert_eq!(dropdown.offset.y, 15.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_on_dismiss_sets_message() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).on_dismiss(TestMessage::Dismiss);
|
||||
|
||||
assert!(dropdown.on_dismiss.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_without_on_dismiss_is_none() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false);
|
||||
|
||||
assert!(dropdown.on_dismiss.is_none());
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Method Chaining Tests
|
||||
// ============================================================================
|
||||
|
||||
#[test]
|
||||
fn drop_down_chaining_methods() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, true)
|
||||
.width(Length::Fixed(300.0))
|
||||
.height(Length::Fixed(200.0))
|
||||
.alignment(Alignment::Top)
|
||||
.offset(Offset::from(15.0))
|
||||
.on_dismiss(TestMessage::Dismiss);
|
||||
|
||||
assert!(dropdown.expanded);
|
||||
assert_eq!(dropdown.width, Some(Length::Fixed(300.0)));
|
||||
assert_eq!(dropdown.height, Length::Fixed(200.0));
|
||||
assert_eq!(dropdown.alignment, Alignment::Top);
|
||||
assert_eq!(dropdown.offset.x, 15.0);
|
||||
assert_eq!(dropdown.offset.y, 15.0);
|
||||
assert!(dropdown.on_dismiss.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_partial_chaining() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false)
|
||||
.width(Length::Fill)
|
||||
.alignment(Alignment::BottomEnd);
|
||||
|
||||
assert_eq!(dropdown.width, Some(Length::Fill));
|
||||
assert_eq!(dropdown.alignment, Alignment::BottomEnd);
|
||||
assert_eq!(dropdown.height, Length::Shrink); // Default
|
||||
assert!(dropdown.on_dismiss.is_none()); // Not set
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Widget Trait Tests
|
||||
// ============================================================================
|
||||
|
||||
#[test]
|
||||
fn drop_down_has_two_children() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false);
|
||||
|
||||
let children =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::children(&dropdown);
|
||||
assert_eq!(
|
||||
children.len(),
|
||||
2,
|
||||
"DropDown should have 2 children (underlay and overlay)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_size_matches_underlay() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false);
|
||||
|
||||
let size =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::size(&dropdown);
|
||||
// Text widget has Shrink for both dimensions by default
|
||||
assert_eq!(size.width, Length::Shrink);
|
||||
assert_eq!(size.height, Length::Shrink);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Configuration Tests
|
||||
// ============================================================================
|
||||
|
||||
#[test]
|
||||
fn drop_down_alignment_bottom() {
|
||||
let dropdown =
|
||||
TestDropDown::new(Text::new("Click me"), Text::new("Dropdown content"), false)
|
||||
.alignment(Alignment::Bottom);
|
||||
|
||||
assert_eq!(dropdown.alignment, Alignment::Bottom);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_alignment_start() {
|
||||
let dropdown =
|
||||
TestDropDown::new(Text::new("Click me"), Text::new("Dropdown content"), false)
|
||||
.alignment(Alignment::Start);
|
||||
|
||||
assert_eq!(dropdown.alignment, Alignment::Start);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_alignment_end() {
|
||||
let dropdown =
|
||||
TestDropDown::new(Text::new("Click me"), Text::new("Dropdown content"), false)
|
||||
.alignment(Alignment::End);
|
||||
|
||||
assert_eq!(dropdown.alignment, Alignment::End);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_different_widths() {
|
||||
let widths = [
|
||||
Length::Fill,
|
||||
Length::Shrink,
|
||||
Length::Fixed(100.0),
|
||||
Length::Fixed(500.0),
|
||||
Length::FillPortion(2),
|
||||
];
|
||||
|
||||
for width in widths {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).width(width);
|
||||
|
||||
assert_eq!(dropdown.width, Some(width));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_different_heights() {
|
||||
let heights = [
|
||||
Length::Fill,
|
||||
Length::Shrink,
|
||||
Length::Fixed(100.0),
|
||||
Length::Fixed(500.0),
|
||||
Length::FillPortion(2),
|
||||
];
|
||||
|
||||
for height in heights {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).height(height);
|
||||
|
||||
assert_eq!(dropdown.height, height);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_zero_offset() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown =
|
||||
TestDropDown::new(underlay, overlay, false).offset(Offset { x: 0.0, y: 0.0 });
|
||||
|
||||
assert_eq!(dropdown.offset.x, 0.0);
|
||||
assert_eq!(dropdown.offset.y, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_negative_offset() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown =
|
||||
TestDropDown::new(underlay, overlay, false).offset(Offset { x: -5.0, y: -10.0 });
|
||||
|
||||
assert_eq!(dropdown.offset.x, -5.0);
|
||||
assert_eq!(dropdown.offset.y, -10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_large_offset() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false).offset(Offset {
|
||||
x: 1000.0,
|
||||
y: 500.0,
|
||||
});
|
||||
|
||||
assert_eq!(dropdown.offset.x, 1000.0);
|
||||
assert_eq!(dropdown.offset.y, 500.0);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Edge Case Tests
|
||||
// ============================================================================
|
||||
|
||||
#[test]
|
||||
fn drop_down_with_empty_text() {
|
||||
let underlay = Text::new("");
|
||||
let overlay = Text::new("");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false);
|
||||
|
||||
assert!(!dropdown.expanded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_multiple_instances() {
|
||||
let dropdown1 = TestDropDown::new(Text::new("First"), Text::new("Overlay 1"), false);
|
||||
|
||||
let dropdown2 = TestDropDown::new(Text::new("Second"), Text::new("Overlay 2"), true);
|
||||
|
||||
assert!(!dropdown1.expanded);
|
||||
assert!(dropdown2.expanded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_with_different_message_types() {
|
||||
let dropdown1 =
|
||||
TestDropDown::new(Text::new("Click me"), Text::new("Dropdown content"), false)
|
||||
.on_dismiss(TestMessage::Dismiss);
|
||||
|
||||
let dropdown2 =
|
||||
TestDropDown::new(Text::new("Click me"), Text::new("Dropdown content"), false)
|
||||
.on_dismiss(TestMessage::Select(42));
|
||||
|
||||
assert!(dropdown1.on_dismiss.is_some());
|
||||
assert!(dropdown2.on_dismiss.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_converts_to_element() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false);
|
||||
let _element: Element<'_, TestMessage, iced_widget::Theme, iced_widget::Renderer> =
|
||||
dropdown.into();
|
||||
// Just verify it compiles and converts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_down_default_offset_is_5() {
|
||||
let underlay = Text::new("Click me");
|
||||
let overlay = Text::new("Dropdown content");
|
||||
|
||||
let dropdown = TestDropDown::new(underlay, overlay, false);
|
||||
|
||||
// Default offset should be 5.0 (from Offset::from(5.0) in new())
|
||||
assert_eq!(dropdown.offset.x, 5.0);
|
||||
assert_eq!(dropdown.offset.y, 5.0);
|
||||
}
|
||||
}
|
||||
Vendored
+390
@@ -0,0 +1,390 @@
|
||||
//! widget Helpers.
|
||||
//!
|
||||
//!
|
||||
#[cfg(feature = "selection_list")]
|
||||
use crate::style::{Status, StyleFn};
|
||||
#[allow(unused_imports)]
|
||||
use iced_core::{self, Color, Element, Padding, renderer};
|
||||
|
||||
#[cfg(feature = "number_input")]
|
||||
use num_traits::bounds::Bounded;
|
||||
#[allow(unused_imports)]
|
||||
use std::{borrow::Cow, fmt::Display, hash::Hash, ops::RangeBounds};
|
||||
|
||||
/// Creates a horizontal [`Wrap`] with the given children.
|
||||
///
|
||||
/// [`Wrap`]: crate::Wrap
|
||||
#[cfg(feature = "wrap")]
|
||||
#[macro_export]
|
||||
macro_rules! wrap_horizontal {
|
||||
() => (
|
||||
$crate::Wrap::new()
|
||||
);
|
||||
($($x:expr),+ $(,)?) => (
|
||||
$crate::Wrap::with_elements(vec![$($crate::Element::from($x)),+])
|
||||
);
|
||||
}
|
||||
|
||||
/// Creates a vertical [`Wrap`] with the given children.
|
||||
///
|
||||
/// [`Wrap`]: crate::Wrap
|
||||
#[cfg(feature = "wrap")]
|
||||
#[macro_export]
|
||||
macro_rules! wrap_vertical {
|
||||
() => (
|
||||
$crate::Wrap::new_vertical()
|
||||
);
|
||||
($($x:expr),+ $(,)?) => (
|
||||
$crate::Wrap::with_elements_vertical(vec![$($crate::Element::from($x)),+])
|
||||
);
|
||||
}
|
||||
|
||||
/// Creates a vec of menu [`Item`]s
|
||||
///
|
||||
/// [`Item`]: crate::menu::Item
|
||||
///
|
||||
/// Syntax:
|
||||
/// ```ignore
|
||||
/// menu_items!(
|
||||
/// (widget),
|
||||
/// (widget, menu),
|
||||
/// expression,
|
||||
/// ...
|
||||
/// )
|
||||
/// ```
|
||||
#[cfg(feature = "menu")]
|
||||
#[macro_export]
|
||||
macro_rules! menu_items {
|
||||
// base case
|
||||
(@process [$($output:expr,)*]) => {
|
||||
vec![$($output),*]
|
||||
};
|
||||
|
||||
// rule for (widget, menu)
|
||||
(@process [$($output:expr,)*] ($i:expr, $m:expr) , $($rest:tt)*) => {
|
||||
$crate::menu_items!(@process [$($output,)* $crate::menu::Item::with_menu($i, $m),] $($rest)*)
|
||||
};
|
||||
(@process [$($output:expr,)*] ($i:expr, $m:expr)) => {
|
||||
$crate::menu_items!(@process [$($output,)* $crate::menu::Item::with_menu($i, $m),])
|
||||
};
|
||||
|
||||
// rule for (widget)
|
||||
(@process [$($output:expr,)*] ($i:expr) , $($rest:tt)*) => {
|
||||
$crate::menu_items!(@process [$($output,)* $crate::menu::Item::new($i),] $($rest)*)
|
||||
};
|
||||
(@process [$($output:expr,)*] ($i:expr)) => {
|
||||
$crate::menu_items!(@process [$($output,)* $crate::menu::Item::new($i),])
|
||||
};
|
||||
|
||||
// rule for expr
|
||||
(@process [$($output:expr,)*] $item:expr , $($rest:tt)*) => {
|
||||
$crate::menu_items!(@process [$($output,)* $item,] $($rest)*)
|
||||
};
|
||||
(@process [$($output:expr,)*] $item:expr) => {
|
||||
$crate::menu_items!(@process [$($output,)* $item,])
|
||||
};
|
||||
|
||||
// entry point
|
||||
($($input:tt)*) => {
|
||||
$crate::menu_items!(@process [] $($input)*)
|
||||
};
|
||||
}
|
||||
|
||||
/// Creates a [`Menu`] with the given items.
|
||||
///
|
||||
/// [`Menu`]: crate::menu::Menu
|
||||
///
|
||||
/// Syntax:
|
||||
/// ```ignore
|
||||
/// menu!(
|
||||
/// (widget),
|
||||
/// (widget, menu),
|
||||
/// expression,
|
||||
/// ...
|
||||
/// )
|
||||
/// ```
|
||||
#[cfg(feature = "menu")]
|
||||
#[macro_export]
|
||||
macro_rules! menu {
|
||||
($($x:tt)+) => {
|
||||
$crate::menu::Menu::new( $crate::menu_items!( $($x)+ ) )
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [`MenuBar`] with the given children.
|
||||
///
|
||||
/// [`MenuBar`]: crate::menu::MenuBar
|
||||
///
|
||||
/// Syntax:
|
||||
/// ```ignore
|
||||
/// menu_bar!(
|
||||
/// (widget),
|
||||
/// (widget, menu),
|
||||
/// expression,
|
||||
/// ...
|
||||
/// )
|
||||
/// ```
|
||||
#[cfg(feature = "menu")]
|
||||
#[macro_export]
|
||||
macro_rules! menu_bar {
|
||||
($($input:tt)+) => (
|
||||
$crate::menu::MenuBar::new($crate::menu_items!( $($input)+ ))
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "badge")]
|
||||
/// Shortcut helper to create a [`Badge`] Widget.
|
||||
///
|
||||
/// [`Badge`]: crate::Badge
|
||||
pub fn badge<'a, Message, Theme, Renderer>(
|
||||
content: impl Into<Element<'a, Message, Theme, Renderer>>,
|
||||
) -> crate::Badge<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
Theme: crate::style::badge::Catalog,
|
||||
{
|
||||
crate::Badge::new(content)
|
||||
}
|
||||
|
||||
#[cfg(feature = "card")]
|
||||
/// Shortcut helper to create a [`Card`] Widget.
|
||||
///
|
||||
/// [`Card`]: crate::Card
|
||||
pub fn card<'a, Message, Theme, Renderer>(
|
||||
head: impl Into<Element<'a, Message, Theme, Renderer>>,
|
||||
body: impl Into<Element<'a, Message, Theme, Renderer>>,
|
||||
) -> crate::Card<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
Theme: crate::style::card::Catalog,
|
||||
{
|
||||
crate::Card::new(head, body)
|
||||
}
|
||||
|
||||
#[cfg(feature = "color_picker")]
|
||||
/// Shortcut helper to create a [`ColorPicker`] Widget.
|
||||
///
|
||||
/// [`ColorPicker`]: crate::ColorPicker
|
||||
pub fn color_picker<'a, Message, Theme, F>(
|
||||
show_picker: bool,
|
||||
color: Color,
|
||||
underlay: impl Into<Element<'a, Message, Theme, iced_widget::Renderer>>,
|
||||
on_cancel: Message,
|
||||
on_submit: F,
|
||||
) -> crate::ColorPicker<'a, Message, Theme>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Theme: 'a
|
||||
+ crate::style::color_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog,
|
||||
F: 'static + Fn(Color) -> Message,
|
||||
{
|
||||
crate::ColorPicker::new(show_picker, color, underlay, on_cancel, on_submit)
|
||||
}
|
||||
|
||||
#[cfg(feature = "color_picker")]
|
||||
/// Shortcut helper to create a [`ColorPicker`] Widget with real-time color change callback.
|
||||
///
|
||||
/// [`ColorPicker`]: crate::ColorPicker
|
||||
pub fn color_picker_with_change<'a, Message, Theme, F, G>(
|
||||
show_picker: bool,
|
||||
color: Color,
|
||||
underlay: impl Into<Element<'a, Message, Theme, iced_widget::Renderer>>,
|
||||
on_cancel: Message,
|
||||
on_submit: F,
|
||||
on_color_change: G,
|
||||
) -> crate::ColorPicker<'a, Message, Theme>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Theme: 'a
|
||||
+ crate::style::color_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog,
|
||||
F: 'static + Fn(Color) -> Message,
|
||||
G: 'static + Fn(Color) -> Message,
|
||||
{
|
||||
crate::ColorPicker::new(show_picker, color, underlay, on_cancel, on_submit)
|
||||
.on_color_change(on_color_change)
|
||||
}
|
||||
|
||||
#[cfg(feature = "date_picker")]
|
||||
/// Shortcut helper to create a [`DatePicker`] Widget.
|
||||
///
|
||||
/// [`DatePicker`]: crate::DatePicker
|
||||
pub fn date_picker<'a, Message, Theme, F>(
|
||||
show_picker: bool,
|
||||
date: impl Into<crate::core::date::Date>,
|
||||
underlay: impl Into<Element<'a, Message, Theme, iced_widget::Renderer>>,
|
||||
on_cancel: Message,
|
||||
on_submit: F,
|
||||
) -> crate::DatePicker<'a, Message, Theme>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Theme: 'a
|
||||
+ crate::style::date_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog
|
||||
+ iced_widget::container::Catalog,
|
||||
F: 'static + Fn(crate::core::date::Date) -> Message,
|
||||
{
|
||||
crate::DatePicker::new(show_picker, date, underlay, on_cancel, on_submit)
|
||||
}
|
||||
|
||||
#[cfg(feature = "time_picker")]
|
||||
/// Shortcut helper to create a [`DatePicker`] Widget.
|
||||
///
|
||||
/// [`DatePicker`]: crate::DatePicker
|
||||
pub fn time_picker<'a, Message, Theme, U, F>(
|
||||
show_picker: bool,
|
||||
time: impl Into<crate::core::time::Time>,
|
||||
underlay: U,
|
||||
on_cancel: Message,
|
||||
on_submit: F,
|
||||
) -> crate::TimePicker<'a, Message, Theme>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Theme: 'a
|
||||
+ crate::style::time_picker::Catalog
|
||||
+ iced_widget::button::Catalog
|
||||
+ iced_widget::text::Catalog,
|
||||
U: Into<Element<'a, Message, Theme, iced_widget::Renderer>>,
|
||||
F: 'static + Fn(crate::core::time::Time) -> Message,
|
||||
{
|
||||
crate::TimePicker::new(show_picker, time, underlay, on_cancel, on_submit)
|
||||
}
|
||||
|
||||
#[cfg(feature = "wrap")]
|
||||
/// Shortcut helper to create a horizontal [`Wrap`] Widget.
|
||||
///
|
||||
/// [`Wrap`]: crate::Wrap
|
||||
#[must_use]
|
||||
pub fn wrap_horizontal<Message, Theme, Renderer>(
|
||||
children: Vec<Element<Message, Theme, Renderer>>,
|
||||
) -> crate::Wrap<Message, crate::direction::Horizontal, Theme, Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
crate::Wrap::with_elements(children)
|
||||
}
|
||||
|
||||
#[cfg(feature = "wrap")]
|
||||
/// Shortcut helper to create a vertical [`Wrap`] Widget.
|
||||
///
|
||||
/// [`Wrap`]: crate::Wrap
|
||||
#[must_use]
|
||||
pub fn wrap_vertical<Message, Theme, Renderer>(
|
||||
children: Vec<Element<Message, Theme, Renderer>>,
|
||||
) -> crate::Wrap<Message, crate::direction::Vertical, Theme, Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
crate::Wrap::with_elements_vertical(children)
|
||||
}
|
||||
|
||||
#[cfg(feature = "number_input")]
|
||||
/// Shortcut helper to create a [`NumberInput`] Widget.
|
||||
///
|
||||
/// [`NumberInput`]: crate::NumberInput
|
||||
#[must_use]
|
||||
pub fn number_input<'a, T, Message, Theme, Renderer, F>(
|
||||
value: &T,
|
||||
bounds: impl RangeBounds<T>,
|
||||
on_change: F,
|
||||
) -> crate::NumberInput<'a, T, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone + 'a,
|
||||
Renderer: iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: crate::style::number_input::ExtendedCatalog,
|
||||
F: 'a + Fn(T) -> Message + Copy,
|
||||
T: 'a
|
||||
+ num_traits::Num
|
||||
+ num_traits::NumAssignOps
|
||||
+ PartialOrd
|
||||
+ std::fmt::Display
|
||||
+ std::str::FromStr
|
||||
+ Copy
|
||||
+ Bounded,
|
||||
{
|
||||
crate::NumberInput::new(value, bounds, on_change)
|
||||
}
|
||||
|
||||
#[cfg(feature = "typed_input")]
|
||||
/// Shortcut helper to create a [`TypedInput`] Widget.
|
||||
///
|
||||
/// [`TypedInput`]: crate::TypedInput
|
||||
#[must_use]
|
||||
pub fn typed_input<'a, T, Message, Theme, Renderer, F>(
|
||||
value: &T,
|
||||
on_change: F,
|
||||
) -> crate::TypedInput<'a, T, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone,
|
||||
Renderer: iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: iced_widget::text_input::Catalog,
|
||||
F: 'static + Fn(T) -> Message + Copy,
|
||||
T: 'static + std::fmt::Display + std::str::FromStr + Clone,
|
||||
{
|
||||
crate::TypedInput::new("", value).on_input(on_change)
|
||||
}
|
||||
|
||||
#[cfg(feature = "selection_list")]
|
||||
/// Shortcut helper to create a [`SelectionList`] Widget.
|
||||
///
|
||||
/// [`SelectionList`]: crate::SelectionList
|
||||
#[must_use]
|
||||
pub fn selection_list_with<'a, T, Message, Theme, Renderer>(
|
||||
options: &'a [T],
|
||||
on_selected: impl Fn(usize, T) -> Message + 'static,
|
||||
text_size: f32,
|
||||
padding: impl Into<Padding>,
|
||||
style: impl Fn(&Theme, Status) -> crate::style::selection_list::Style + 'a + Clone,
|
||||
selected: Option<usize>,
|
||||
font: iced_core::Font,
|
||||
) -> crate::SelectionList<'a, T, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: 'a
|
||||
+ crate::style::selection_list::Catalog
|
||||
+ iced_widget::container::Catalog
|
||||
+ iced_widget::scrollable::Catalog
|
||||
+ iced_widget::text::Catalog,
|
||||
T: Clone + Display + Eq + Hash,
|
||||
[T]: ToOwned<Owned = Vec<T>>,
|
||||
<Theme as crate::style::selection_list::Catalog>::Class<'a>:
|
||||
From<StyleFn<'a, Theme, crate::style::selection_list::Style>>,
|
||||
{
|
||||
crate::SelectionList::new_with(
|
||||
options,
|
||||
on_selected,
|
||||
text_size,
|
||||
padding,
|
||||
style,
|
||||
selected,
|
||||
font,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "selection_list")]
|
||||
/// Shortcut helper to create a [`SelectionList`] Widget.
|
||||
///
|
||||
/// [`SelectionList`]: crate::SelectionList
|
||||
#[must_use]
|
||||
pub fn selection_list<'a, T, Message, Theme, Renderer>(
|
||||
options: &'a [T],
|
||||
on_selected: impl Fn(usize, T) -> Message + 'static,
|
||||
) -> crate::SelectionList<'a, T, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: 'a
|
||||
+ crate::style::selection_list::Catalog
|
||||
+ iced_widget::container::Catalog
|
||||
+ iced_widget::scrollable::Catalog
|
||||
+ iced_widget::text::Catalog,
|
||||
T: Clone + Display + Eq + Hash,
|
||||
[T]: ToOwned<Owned = Vec<T>>,
|
||||
{
|
||||
crate::SelectionList::new(options, on_selected)
|
||||
}
|
||||
+461
@@ -0,0 +1,461 @@
|
||||
//! This module provides a [`LabeledFrame`] widget which allows you to draw a border with a title around some content.
|
||||
|
||||
use iced_core::{Length, Pixels, Rectangle};
|
||||
|
||||
/// The style of a [`LabeledFrame`]
|
||||
pub struct Style {
|
||||
/// The color of the border/frame
|
||||
pub color: iced_core::Background,
|
||||
/// The border radius of the border/frame
|
||||
pub radius: iced_core::border::Radius,
|
||||
}
|
||||
|
||||
/// The theme catalog of a [`LabeledFrame`]
|
||||
pub trait Catalog {
|
||||
/// The item class of [`Catalog`]
|
||||
type Class<'a>;
|
||||
/// The default class produced by the [`Catalog`]
|
||||
fn default<'a>() -> Self::Class<'a>;
|
||||
/// The [`Style`] of a class
|
||||
fn style(&self, class: &Self::Class<'_>) -> Style;
|
||||
}
|
||||
|
||||
/// A styling function for a [`LabeledFrame`]
|
||||
pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>;
|
||||
|
||||
impl Catalog for iced_widget::Theme {
|
||||
type Class<'a> = StyleFn<'a, Self>;
|
||||
|
||||
fn default<'a>() -> Self::Class<'a> {
|
||||
Box::new(|theme| Style {
|
||||
color: iced_core::Background::Color(theme.extended_palette().secondary.weak.color),
|
||||
radius: iced_core::border::Radius::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn style(&self, class: &Self::Class<'_>) -> Style {
|
||||
(class)(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// A labeled frame widget
|
||||
pub struct LabeledFrame<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: Catalog,
|
||||
{
|
||||
title: iced_core::Element<'a, Message, Theme, Renderer>,
|
||||
content: iced_core::Element<'a, Message, Theme, Renderer>,
|
||||
width: Length,
|
||||
height: Length,
|
||||
class: Theme::Class<'a>,
|
||||
inset: f32,
|
||||
outset: f32,
|
||||
stroke_width: f32,
|
||||
horizontal_title_padding: f32,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> LabeledFrame<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: Catalog,
|
||||
{
|
||||
/// Creates a new [`LabeledFrame`]
|
||||
pub fn new(
|
||||
title: impl Into<iced_core::Element<'a, Message, Theme, Renderer>>,
|
||||
content: impl Into<iced_core::Element<'a, Message, Theme, Renderer>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
title: title.into(),
|
||||
content: content.into(),
|
||||
width: Length::Shrink,
|
||||
height: Length::Shrink,
|
||||
class: Theme::default(),
|
||||
inset: 5.0,
|
||||
outset: 5.0,
|
||||
stroke_width: 3.0,
|
||||
horizontal_title_padding: 5.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the width of the [`LabeledFrame`]
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`LabeledFrame`]
|
||||
#[must_use]
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the inset that is between the border and the inner content
|
||||
#[must_use]
|
||||
pub fn inset(mut self, inset: impl Into<Pixels>) -> Self {
|
||||
self.inset = inset.into().0;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the outset that is put around the border
|
||||
#[must_use]
|
||||
pub fn outset(mut self, outset: impl Into<Pixels>) -> Self {
|
||||
self.outset = outset.into().0;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the width of the stroke/border drawn around the content
|
||||
#[must_use]
|
||||
pub fn stroke_width(mut self, stroke_width: impl Into<Pixels>) -> Self {
|
||||
self.stroke_width = stroke_width.into().0;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the padding that the title gets on the horizontal axis
|
||||
#[must_use]
|
||||
pub fn horizontal_title_padding(mut self, padding: impl Into<Pixels>) -> Self {
|
||||
self.horizontal_title_padding = padding.into().0;
|
||||
self
|
||||
}
|
||||
|
||||
/// Changes the style of the [`LabeledFrame`]
|
||||
#[must_use]
|
||||
pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self
|
||||
where
|
||||
Theme::Class<'a>: From<StyleFn<'a, Theme>>,
|
||||
{
|
||||
self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme, Renderer> iced_core::Widget<Message, Theme, Renderer>
|
||||
for LabeledFrame<'_, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: iced_core::Renderer,
|
||||
Theme: Catalog,
|
||||
{
|
||||
fn size(&self) -> iced_core::Size<Length> {
|
||||
iced_core::Size::new(self.width, self.height)
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
tree: &mut iced_core::widget::Tree,
|
||||
renderer: &Renderer,
|
||||
limits: &iced_core::layout::Limits,
|
||||
) -> iced_core::layout::Node {
|
||||
let limits = (*limits).height(self.height).width(self.width).loose();
|
||||
let title_layout = self
|
||||
.title
|
||||
.as_widget_mut()
|
||||
.layout(
|
||||
&mut tree.children[0],
|
||||
renderer,
|
||||
&limits.shrink(
|
||||
iced_core::Padding::default()
|
||||
.left(
|
||||
(self.outset + self.inset + self.stroke_width) * 2.0
|
||||
+ self.horizontal_title_padding,
|
||||
)
|
||||
.right(
|
||||
(self.outset + self.inset + self.stroke_width) * 2.0
|
||||
+ self.horizontal_title_padding,
|
||||
),
|
||||
),
|
||||
)
|
||||
.translate([
|
||||
(self.outset + self.inset + self.stroke_width) * 2.0
|
||||
+ self.horizontal_title_padding,
|
||||
0.0,
|
||||
]);
|
||||
let content_layout = self
|
||||
.content
|
||||
.as_widget_mut()
|
||||
.layout(
|
||||
&mut tree.children[1],
|
||||
renderer,
|
||||
&limits.shrink(
|
||||
iced_core::Padding::default()
|
||||
.left(self.outset + self.inset + self.stroke_width)
|
||||
.right(self.outset + self.inset + self.stroke_width)
|
||||
.bottom(self.outset + self.inset + self.stroke_width)
|
||||
.top(
|
||||
(self.outset + self.inset + self.stroke_width)
|
||||
.max(title_layout.size().height),
|
||||
),
|
||||
),
|
||||
)
|
||||
.translate([
|
||||
self.outset + self.inset + self.stroke_width,
|
||||
(self.outset + self.inset + self.stroke_width).max(title_layout.bounds().height),
|
||||
]);
|
||||
|
||||
iced_core::layout::Node::with_children(
|
||||
limits.resolve(
|
||||
self.width,
|
||||
self.height,
|
||||
iced_core::Size::new(
|
||||
(content_layout.size().width
|
||||
+ (self.outset + self.inset + self.stroke_width) * 2.0)
|
||||
.max(
|
||||
title_layout.size().width
|
||||
+ (self.outset + self.inset + self.stroke_width) * 4.0,
|
||||
),
|
||||
content_layout.bounds().y
|
||||
+ content_layout.size().height
|
||||
+ (self.outset + self.inset + self.stroke_width),
|
||||
),
|
||||
),
|
||||
vec![title_layout, content_layout],
|
||||
)
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<iced_core::widget::Tree> {
|
||||
vec![
|
||||
iced_core::widget::Tree::new(&self.title),
|
||||
iced_core::widget::Tree::new(&self.content),
|
||||
]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut iced_core::widget::Tree) {
|
||||
tree.diff_children(&[&self.title, &self.content]);
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &iced_core::widget::Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &iced_core::renderer::Style,
|
||||
layout: iced_core::Layout<'_>,
|
||||
cursor: iced_core::mouse::Cursor,
|
||||
viewport: &iced_core::Rectangle,
|
||||
) {
|
||||
[&self.title, &self.content]
|
||||
.iter()
|
||||
.zip(&tree.children)
|
||||
.zip(layout.children())
|
||||
.for_each(|((child, state), layout)| {
|
||||
child
|
||||
.as_widget()
|
||||
.draw(state, renderer, theme, style, layout, cursor, viewport);
|
||||
});
|
||||
let style = theme.style(&self.class);
|
||||
let title_layout = layout.children().next().expect("missing title layout");
|
||||
let top_line_y =
|
||||
title_layout.position().y + (title_layout.bounds().height - self.stroke_width) / 2.0;
|
||||
// left line
|
||||
renderer.fill_quad(
|
||||
iced_core::renderer::Quad {
|
||||
bounds: iced_core::Rectangle {
|
||||
x: layout.position().x + self.outset,
|
||||
y: top_line_y,
|
||||
width: self.stroke_width,
|
||||
height: layout.bounds().height
|
||||
- self.outset
|
||||
- (top_line_y - layout.position().y),
|
||||
},
|
||||
border: iced_core::Border {
|
||||
radius: iced_core::border::Radius::default()
|
||||
.top_left(style.radius.top_left)
|
||||
.bottom_left(style.radius.bottom_left),
|
||||
..Default::default()
|
||||
},
|
||||
shadow: iced_core::Shadow::default(),
|
||||
..Default::default()
|
||||
},
|
||||
style.color,
|
||||
);
|
||||
// right line
|
||||
renderer.fill_quad(
|
||||
iced_core::renderer::Quad {
|
||||
bounds: iced_core::Rectangle {
|
||||
x: layout.position().x + layout.bounds().width
|
||||
- self.outset
|
||||
- self.stroke_width,
|
||||
y: top_line_y,
|
||||
width: self.stroke_width,
|
||||
height: layout.bounds().height
|
||||
- self.outset
|
||||
- (top_line_y - layout.position().y),
|
||||
},
|
||||
border: iced_core::Border {
|
||||
radius: iced_core::border::Radius::default()
|
||||
.top_right(style.radius.top_right)
|
||||
.bottom_right(style.radius.bottom_right),
|
||||
..Default::default()
|
||||
},
|
||||
shadow: iced_core::Shadow::default(),
|
||||
..Default::default()
|
||||
},
|
||||
style.color,
|
||||
);
|
||||
// bottom line
|
||||
renderer.fill_quad(
|
||||
iced_core::renderer::Quad {
|
||||
bounds: iced_core::Rectangle {
|
||||
x: layout.position().x + self.outset,
|
||||
y: layout.position().y + layout.bounds().height
|
||||
- self.outset
|
||||
- self.stroke_width,
|
||||
width: layout.bounds().width - self.outset * 2.0,
|
||||
height: self.stroke_width,
|
||||
},
|
||||
border: iced_core::Border {
|
||||
radius: iced_core::border::Radius::default()
|
||||
.bottom_right(style.radius.top_right)
|
||||
.bottom_left(style.radius.top_left),
|
||||
..Default::default()
|
||||
},
|
||||
shadow: iced_core::Shadow::default(),
|
||||
..Default::default()
|
||||
},
|
||||
style.color,
|
||||
);
|
||||
// top line left
|
||||
renderer.fill_quad(
|
||||
iced_core::renderer::Quad {
|
||||
bounds: iced_core::Rectangle {
|
||||
x: layout.position().x + self.outset,
|
||||
y: top_line_y,
|
||||
width: title_layout.position().x
|
||||
- (layout.position().x + self.outset)
|
||||
- self.horizontal_title_padding,
|
||||
height: self.stroke_width,
|
||||
},
|
||||
border: iced_core::Border {
|
||||
radius: iced_core::border::Radius::default().top_left(style.radius.top_left),
|
||||
..Default::default()
|
||||
},
|
||||
shadow: iced_core::Shadow::default(),
|
||||
..Default::default()
|
||||
},
|
||||
style.color,
|
||||
);
|
||||
// top line right
|
||||
renderer.fill_quad(
|
||||
iced_core::renderer::Quad {
|
||||
bounds: iced_core::Rectangle {
|
||||
x: title_layout.position().x
|
||||
+ title_layout.bounds().width
|
||||
+ self.horizontal_title_padding,
|
||||
y: top_line_y,
|
||||
width: (layout.position().x + layout.bounds().width - self.outset)
|
||||
- (title_layout.position().x + title_layout.bounds().width)
|
||||
- self.horizontal_title_padding,
|
||||
height: self.stroke_width,
|
||||
},
|
||||
border: iced_core::Border {
|
||||
radius: iced_core::border::Radius::default().top_right(style.radius.top_right),
|
||||
..Default::default()
|
||||
},
|
||||
shadow: iced_core::Shadow::default(),
|
||||
..Default::default()
|
||||
},
|
||||
style.color,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &iced_core::widget::Tree,
|
||||
layout: iced_core::Layout<'_>,
|
||||
cursor: iced_core::mouse::Cursor,
|
||||
viewport: &iced_core::Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> iced_core::mouse::Interaction {
|
||||
[&self.title, &self.content]
|
||||
.iter()
|
||||
.zip(&state.children)
|
||||
.zip(layout.children())
|
||||
.map(|((child, state), layout)| {
|
||||
child
|
||||
.as_widget()
|
||||
.mouse_interaction(state, layout, cursor, viewport, renderer)
|
||||
})
|
||||
.max()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut iced_core::widget::Tree,
|
||||
event: &iced_core::Event,
|
||||
layout: iced_core::Layout<'_>,
|
||||
cursor: iced_core::mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn iced_core::Clipboard,
|
||||
shell: &mut iced_core::Shell<'_, Message>,
|
||||
viewport: &iced_core::Rectangle,
|
||||
) {
|
||||
for ((child, state), layout) in [&mut self.title, &mut self.content]
|
||||
.iter_mut()
|
||||
.zip(&mut state.children)
|
||||
.zip(layout.children())
|
||||
{
|
||||
child.as_widget_mut().update(
|
||||
state, event, layout, cursor, renderer, clipboard, shell, viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
state: &mut iced_core::widget::Tree,
|
||||
layout: iced_core::Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn iced_core::widget::Operation,
|
||||
) {
|
||||
operation.container(None, layout.bounds());
|
||||
operation.traverse(&mut |operation| {
|
||||
[&mut self.title, &mut self.content]
|
||||
.iter_mut()
|
||||
.zip(&mut state.children)
|
||||
.zip(layout.children())
|
||||
.for_each(|((child, state), layout)| {
|
||||
child
|
||||
.as_widget_mut()
|
||||
.operate(state, layout, renderer, operation);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
state: &'b mut iced_core::widget::Tree,
|
||||
layout: iced_core::Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: iced_core::Vector,
|
||||
) -> Option<iced_core::overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
let children = vec![&mut self.title, &mut self.content]
|
||||
.into_iter()
|
||||
.zip(&mut state.children)
|
||||
.zip(layout.children())
|
||||
.filter_map(|((child, state), layout)| {
|
||||
child
|
||||
.as_widget_mut()
|
||||
.overlay(state, layout, renderer, viewport, translation)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
(!children.is_empty()).then(|| iced_core::overlay::Group::with_children(children).overlay())
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> iced_core::Size<Length> {
|
||||
self.size()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> From<LabeledFrame<'a, Message, Theme, Renderer>>
|
||||
for iced_core::Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a,
|
||||
Theme: 'a + Catalog,
|
||||
Renderer: iced_core::Renderer + 'a,
|
||||
{
|
||||
fn from(value: LabeledFrame<'a, Message, Theme, Renderer>) -> Self {
|
||||
iced_core::Element::new(value)
|
||||
}
|
||||
}
|
||||
Vendored
+159
@@ -0,0 +1,159 @@
|
||||
#![allow(clippy::doc_markdown)]
|
||||
|
||||
//! A [`MenuBar`] widget for displaying menu trees created with [`Item`]s and [`Menu`]s
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: `menu`*
|
||||
//!
|
||||
//! ## Example 1
|
||||
//!
|
||||
//! ```ignore
|
||||
//! use iced_widget::button;
|
||||
//! use iced_aw::menu::{Item, Menu, MenuBar};
|
||||
//!
|
||||
//! let sub_2 = Item::with_menu(
|
||||
//! button("Sub Menu 2"),
|
||||
//! Menu::new([
|
||||
//! Item::new(button("item_1")),
|
||||
//! Item::new(button("item_2")),
|
||||
//! Item::new(button("item_3")),
|
||||
//! ].into())
|
||||
//! );
|
||||
//!
|
||||
//! let sub_1 = Item::with_menu(
|
||||
//! button("Sub Menu 1"),
|
||||
//! Menu::new([
|
||||
//! Item::new(button("item_1")),
|
||||
//! sub_2,
|
||||
//! Item::new(button("item_2")),
|
||||
//! Item::new(button("item_3")),
|
||||
//! ].into())
|
||||
//! );
|
||||
//!
|
||||
//! let root_1 = Item::with_menu(
|
||||
//! button("Menu 1"),
|
||||
//! Menu::new([
|
||||
//! Item::new(button("item_1")),
|
||||
//! Item::new(button("item_2")),
|
||||
//! sub_1,
|
||||
//! Item::new(button("item_3")),
|
||||
//! ].into())
|
||||
//! );
|
||||
//!
|
||||
//! let root_2 = Item::with_menu(
|
||||
//! button("Menu 2"),
|
||||
//! Menu::new([
|
||||
//! Item::new(button("item_1")),
|
||||
//! Item::new(button("item_2")),
|
||||
//! Item::new(button("item_3")),
|
||||
//! ].into())
|
||||
//! );
|
||||
//!
|
||||
//! let menu_bar = MenuBar::new(vec![root_1, root_2]);
|
||||
//!
|
||||
//! ```
|
||||
//!
|
||||
//! Alternatively you can use the helper macros
|
||||
//!
|
||||
//! ## Example 2
|
||||
//! ```ignore
|
||||
//! use iced_widget::button;
|
||||
//! use iced_aw::menu::{Menu, Item, MenuBar};
|
||||
//! use iced_aw::{menu_bar, menu_items};
|
||||
//!
|
||||
//! let menu_template = |items| Menu::new(items).max_width(180.0).offset(6.0);
|
||||
//!
|
||||
//! let menu_bar: MenuBar<'_, (), iced_widget::Theme, iced::Renderer> = menu_bar!(
|
||||
//! (button("Menu 1"),menu_template(menu_items!(
|
||||
//! (button("item_1"))
|
||||
//! (button("item_2"))
|
||||
//! (button("Sub Menu 1"), menu_template(menu_items!(
|
||||
//! (button("item_1"))
|
||||
//! (button("Sub Menu 2"), menu_template(menu_items!(
|
||||
//! (button("item_1"))
|
||||
//! (button("item_2"))
|
||||
//! (button("item_3"))
|
||||
//! )))
|
||||
//! (button("item_2"))
|
||||
//! (button("item_3"))
|
||||
//! )))
|
||||
//! (button("item_3"))
|
||||
//! )))
|
||||
//! (button("Menu 2"), menu_template(menu_items!(
|
||||
//! (button("item_1"))
|
||||
//! (button("item_2"))
|
||||
//! (button("item_3"))
|
||||
//! )))
|
||||
//! );
|
||||
//! ```
|
||||
//!
|
||||
//! Here a menu_template function/closure is used in example 2,
|
||||
//! usually some properties are sync across all menus while others are not,
|
||||
//! using template functions can reduce the repeated code.
|
||||
//! If you find writing menu_template(menu_items!()) too cumbersome,
|
||||
//! there's a menu! macro you can use to create template macros
|
||||
//!
|
||||
//! ## Example 3
|
||||
//!
|
||||
//! ```ignore
|
||||
//! use iced_widget::button;
|
||||
//! use iced_aw::{menu, Menu};
|
||||
//!
|
||||
//! macro_rules! menu_template {
|
||||
//! ($($x:tt)+) => {
|
||||
//! menu!($($x)+).max_width(180.0).offset(6.0)
|
||||
//! };
|
||||
//! }
|
||||
//!
|
||||
//! // then you can just write
|
||||
//! let m: Menu<'_, (), iced_widget::Theme, iced::Renderer> = menu_template!(
|
||||
//! (button("item_1"))
|
||||
//! (button("item_2"))
|
||||
//! (button("sub menu"), menu_template!(
|
||||
//! (button("item_1"))
|
||||
//! (button("item_2"))
|
||||
//! ))
|
||||
//! (button("item_3"))
|
||||
//! );
|
||||
//! ```
|
||||
//!
|
||||
//! Technically you can create menu template functions with the menu! macro,
|
||||
//! but turns out closures can't infer the proper generic types in this case,
|
||||
//! and creating a function for it you have to write a bunch of generic annotations
|
||||
//!
|
||||
//! ## Example 4
|
||||
//!
|
||||
//! ```ignore
|
||||
//! use iced_aw::{menu, Menu};
|
||||
//! use iced_widget::button;
|
||||
//!
|
||||
//! fn menu_template<'a, Message, Theme, Renderer>(
|
||||
//! menu: Menu<'a, Message, Theme, Renderer>
|
||||
//! ) -> Menu<'a, Message, Theme, Renderer>
|
||||
//! where
|
||||
//! Theme: iced_aw::menu::Catalog,
|
||||
//! Renderer: iced_core::Renderer,
|
||||
//! {
|
||||
//! menu.max_width(180.0).offset(6.0)
|
||||
//! }
|
||||
//!
|
||||
//! let m: Menu<'_, (), iced_widget::Theme, iced::Renderer> = menu_template(menu!(
|
||||
//! (button("item_1"))
|
||||
//! (button("item_2"))
|
||||
//! (button("item_3"))
|
||||
//! ));
|
||||
//! ```
|
||||
//!
|
||||
//! For a more detailed example please
|
||||
//! take a look at the menu example in the iced_aw repo
|
||||
//!
|
||||
|
||||
mod common;
|
||||
mod flex;
|
||||
mod menu_bar;
|
||||
mod menu_bar_overlay;
|
||||
mod menu_tree;
|
||||
|
||||
pub use crate::style::menu_bar::{Catalog, Style, primary};
|
||||
pub use common::{DrawPath, ScrollSpeed};
|
||||
pub use menu_bar::MenuBar;
|
||||
pub use menu_tree::{Item, Menu};
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
|
||||
This is a guide on how to use the `MenuBar` widget.
|
||||
|
||||
This documentation and the `MenuBar` widget source code
|
||||
use the terms "parent menu" and "child menu".
|
||||
The term "submenu" is avoided,
|
||||
as it lacks a corresponding term for "parent menu",
|
||||
and the parent-child terminology
|
||||
can be more easily understood in a tree structure context.
|
||||
|
||||
# Overview
|
||||
|
||||
At its core, the menu system is a tree of widgets,
|
||||
the simplified version of the data structure looks like this:
|
||||
```rust
|
||||
MenuBar {
|
||||
roots: Vec<Item>,
|
||||
// ...
|
||||
}
|
||||
|
||||
Item {
|
||||
widget,
|
||||
menu: Option<Menu>,
|
||||
// ...
|
||||
}
|
||||
|
||||
Menu {
|
||||
items: Vec<Item>,
|
||||
// ...
|
||||
}
|
||||
```
|
||||
Note that `MenuBar` is the actual widget you add to your UI,
|
||||
`Item` and `Menu` are helper structures
|
||||
used to build the menu tree,
|
||||
they cannot function on their own
|
||||
and must be used within a `MenuBar`.
|
||||
|
||||
`MenuBar` is the "root menu"
|
||||
and the entry point of the tree
|
||||
as it owns and manages the global state.
|
||||
|
||||
Building this nested structure manually in Rust can be cumbersome,
|
||||
it is recommended to use macros to build menus,
|
||||
as they save you from the boilerplate of wrapping every widget with `Item::new()` and `Item::with_menu()`.
|
||||
|
||||
|
||||
# Macros
|
||||
|
||||
Three macros are provided:
|
||||
- `menu_items!`
|
||||
- `menu!`
|
||||
- `menu_bar!`
|
||||
|
||||
`menu_items!` is the core macro, it returns a `Vec<Item>`.
|
||||
|
||||
`menu!` and `menu_bar!` are convenient wrappers around `menu_items!`,
|
||||
equivalent to
|
||||
`Menu::new(menu_items!( ... ))` and `MenuBar::new(menu_items!( ... ))` respectively.
|
||||
|
||||
|
||||
Here is the `menu_items!` syntax:
|
||||
|
||||
```rust
|
||||
menu_items!(
|
||||
(widget), // creates an Item::new(widget)
|
||||
(widget, menu), // creates an Item::with_menu(widget, menu)
|
||||
expression, // any expression that returns an Item
|
||||
// ...
|
||||
)
|
||||
```
|
||||
|
||||
A nice thing about this syntax is that
|
||||
when you need to build `Item`s with additional settings,
|
||||
you can create a helper function/closure,
|
||||
and simply put it before the parentheses,
|
||||
it will be treated as a normal function call expression.
|
||||
```rust
|
||||
let hold_item = |widget| Item::new(widget).close_on_click(false);
|
||||
|
||||
menu_items!(
|
||||
hold_item(widget),
|
||||
// this is treated as an expression
|
||||
// and creates an Item::new(widget).close_on_click(false)
|
||||
// ...
|
||||
)
|
||||
```
|
||||
|
||||
If you run into a `recursion limit reached` error,
|
||||
it is very likely there is a syntax error in your macro invocation,
|
||||
e.g. a double comma `,,`,
|
||||
or any unexpected sequence of non-alphabetical symbols like `?.-=+`.
|
||||
|
||||
This is a limitation of `macro_rules!`,
|
||||
it doesn't always provide clear errors for unexpected syntax,
|
||||
and we don't have much control over how errors are handled.
|
||||
|
||||
# Parameters Explained
|
||||
|
||||

|
||||
|
||||
### Offset and Padding
|
||||
|
||||
The items bounds is the bounding rectangle of all items in a menu without the scroll offset.
|
||||
|
||||
The background bounds,
|
||||
which is the visual background of the menu,
|
||||
is a padded rectangle around the items bounds.
|
||||
You can change this padding by setting `Menu.padding`.
|
||||
|
||||
It's important to know that `Menu.padding` is not part of the layout calculation;
|
||||
it only affects appearance and the logic for closing menus.
|
||||
This simplifies layout calculations.
|
||||
|
||||
The trade-off is that,
|
||||
if you have a non-zero padding and `Menu.offset` is zero,
|
||||
the child menu will overlap the parent menu,
|
||||
which can be a bit confusing.
|
||||
|
||||
If tight alignment is the appearance you want,
|
||||
you can set the offset to match the padding.
|
||||
For example,
|
||||
if a parent menu has a left and right padding of 6.0,
|
||||
setting the child menu's offset to 6.0
|
||||
will ensure they are tightly aligned
|
||||
regarless of the open direction
|
||||
(NOTE: Tight alignment for asymmetric paddings is not currently supported,
|
||||
if you have a left padding 6.0 and a right padding 3.0,
|
||||
you can't get a tight alignment for both open directions at the same time).
|
||||
|
||||
|
||||
### Safe Bounds
|
||||
|
||||
The safe bounds is a padded rectangle around the background bounds.
|
||||
|
||||
It creates an invisible margin around each menu
|
||||
that prevents accidental closing.
|
||||
When the cursor moves from the menu background into this safe area,
|
||||
the menu remains open.
|
||||
|
||||
Here is a simplified version of the close logic:
|
||||
```
|
||||
if cursor is over background bounds {
|
||||
update the items
|
||||
} else if cursor is over parent bounds {
|
||||
let the parent menu process the event
|
||||
} else if cursor is over any background bounds of the ancestor menus {
|
||||
close the menu
|
||||
} else {
|
||||
if cursor is over safe bounds {
|
||||
keep the menu open
|
||||
} else {
|
||||
close the menu
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Close on Click
|
||||
|
||||
The close-on-click behavior follows an inheritance pattern:
|
||||
|
||||
Global <- MenuBar/Menu <- Item
|
||||
|
||||
A manu's setting (when it is `Some`) overrides the global settings.
|
||||
|
||||
An item's setting (when it is `Some`) overrides any ancestor settings.
|
||||
|
||||
Here is an overview of the data structure:
|
||||
```rust
|
||||
GlobalParameters {
|
||||
close_on_item_click: bool,
|
||||
close_on_background_click: bool,
|
||||
// ...
|
||||
}
|
||||
|
||||
MenuBar {
|
||||
close_on_item_click: Option<bool>,
|
||||
close_on_background_click: Option<bool>,
|
||||
global_parameters: GlobalParameters,
|
||||
// ...
|
||||
}
|
||||
|
||||
Menu {
|
||||
close_on_item_click: Option<bool>,
|
||||
close_on_background_click: Option<bool>,
|
||||
// ...
|
||||
}
|
||||
|
||||
Item {
|
||||
close_on_click: Option<bool>,
|
||||
// ...
|
||||
}
|
||||
```
|
||||
Here, "background" refers to
|
||||
the visual background plus the safe bounds for `Menu`s,
|
||||
but only the visual background area for `MenuBar`s
|
||||
(since menu bars don't have safe bounds).
|
||||
|
||||
By default,
|
||||
a menu closes when the cursor moves outside its safe bounds.
|
||||
|
||||
A common alternative is to have menus stay open
|
||||
until the user clicks an item or the empty space outside the menu.
|
||||
You can achieve this with:
|
||||
```rust
|
||||
let mb = menu_bar!(
|
||||
...
|
||||
)
|
||||
.close_on_item_click_global(true)
|
||||
.close_on_background_click_global(true)
|
||||
.safe_bounds_margin(f32::MAX);
|
||||
```
|
||||
By setting `safe_bounds_margin` to `f32::MAX`,
|
||||
the cursor effectively never leaves the safe bounds,
|
||||
and the menus will only close upon a click.
|
||||
|
||||
Be aware that with this setting,
|
||||
if no item or background is set to close on click
|
||||
(either directly or through inheritance),
|
||||
you can end up with menus that never close.
|
||||
|
||||
|
||||
# Nested Overlay
|
||||
|
||||
While `MenuBar` supports nested overlays,
|
||||
its interaction logic does not have special handling for
|
||||
complex, interactive overlays
|
||||
that can be created by the contained widgets.
|
||||
Using widgets like `PickList` within a menu
|
||||
can therefore lead to unexpected behavior.
|
||||
|
||||

|
||||
|
||||
Consider a `PickList` opened from a menu item.
|
||||
|
||||
Note that iced passes `Cursor::Unavailable` to lower overlays
|
||||
when an upper overlay calls `shell.capture_event()`,
|
||||
meaning an upper overlay has processed the event.
|
||||
|
||||
In the image above, a `PickList` is opened from a menu item.
|
||||
|
||||
1. If the cursor moves off the `PickList` overlay,
|
||||
`PickList` does not capture events that happen outside its bounds,
|
||||
the menu underneath is unaware of this overlay,
|
||||
and will process the `Cursor::Available(...)` it receives.
|
||||
This can result in multiple interactive overlays being visible at the same time.
|
||||
|
||||
2. If the cursor moves back over the `PickList`,
|
||||
the menu underneath receives a `Cursor::Unavailable`.
|
||||
the menu logic can't distinguish this from other cases,
|
||||
like the cursor leaving the window,
|
||||
and won't know to close the child menu.
|
||||
|
||||
The core issue is that
|
||||
managing interactions between multiple independent overlays
|
||||
is complex and highly use-case dependent,
|
||||
`MenuBar` cannot determine the intended interaction model
|
||||
of an arbitrary nested overlay
|
||||
|
||||
For example, a `Tooltip` is not expected to block menu interactions, whereas a `PickList` may.
|
||||
Since the `MenuBar` cannot know the difference,
|
||||
it defaults to blocking menu interaction
|
||||
upon receiving `Cursor::Unavailable`,
|
||||
which may not be ideal in all cases.
|
||||
|
||||
This complexity extends to other behaviors too,
|
||||
such as how close-on-click should be handled for nested overlays,
|
||||
or whether to perform out-of-safe-bounds checks
|
||||
when a nested overlay is active.
|
||||
|
||||
Therefore,
|
||||
the current implementation of the `MenuBar`'s interaction logic
|
||||
does not include mechanisms that
|
||||
specifically handle nested overlays.
|
||||
|
||||
If a nested overlay-like functionality is unavoidable,
|
||||
we recommend either thoroughly testing your setup,
|
||||
or building it using menus themselves.
|
||||
For example, a `PickList` can be easily replicated with a menu.
|
||||
Check out the [menu example](https://github.com/iced-rs/iced_aw/blob/main/examples/menu.rs).
|
||||
|
||||

|
||||
|
||||
|
||||
# Caveats
|
||||
|
||||
### Focus
|
||||
|
||||
Roughly speaking, a menu, and subsequently all of its items,
|
||||
is "in focus" ,
|
||||
when the cursor is within its safe bounds.
|
||||
When the cursor is hovering over an item that opens a child menu,
|
||||
the parent menu remains in focus.
|
||||
Once the cursor enters the child menu,
|
||||
the child menu gains focus.
|
||||
|
||||
### Performance
|
||||
|
||||
When a menu is in focus,
|
||||
`Widget::update()` is called on all visible widgets in the menu
|
||||
with the incoming event.
|
||||
|
||||
When a menu is not in focus,
|
||||
`Widget::update()` is called on all visible widgets in the menu
|
||||
with a `window::Event::RedrawRequested` event.
|
||||
|
||||
This is due to changes from iced 0.14,
|
||||
`Widget::update()` has to be called on widgets
|
||||
even when they aren't in focus,
|
||||
otherwise their appearance won't update properly.
|
||||
|
||||
Be aware of the potential performance cost.
|
||||
|
||||
### Panic
|
||||
|
||||
It is assumed that `Widget::update()` does not capture
|
||||
the `window::Event::RedrawRequested` event
|
||||
(i.e. it does not call `Shell::capture_event()`
|
||||
in response to a `window::Event::RedrawRequested` event).
|
||||
|
||||
A panic will occur when this assumption is violated.
|
||||
|
||||
# Debugging
|
||||
`MenuBar` is a complex widget,
|
||||
and bugs may exist.
|
||||
If you encounter unexpected behavior or crashes,
|
||||
please feel free to open an issue.
|
||||
|
||||
For contributors or if you'd like to debug it yourself,
|
||||
logs have been added throughout the `MenuBar` code using the `log` crate.
|
||||
|
||||
To enable them in your application, enable the `debug_log` feature:
|
||||
```
|
||||
iced_aw = {version = "0.14", features = ["menu", "debug_log"]}
|
||||
```
|
||||
Then, use a logger implementation like `env_logger` in your application:
|
||||
```rust
|
||||
fn main(){
|
||||
env_logger::init();
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
And set the `RUST_LOG` environment variable:
|
||||
|
||||
```
|
||||
RUST_LOG=menu=debug
|
||||
```
|
||||
|
||||
To run your application with logging enabled:
|
||||
```
|
||||
RUST_LOG=menu=debug cargo run
|
||||
```
|
||||
|
||||
If you need to log to a file, you can redirect stderr (where `env_logger` writes by default):
|
||||
|
||||
```
|
||||
RUST_LOG=menu=debug cargo run > path/to/your/log_file 2>&1
|
||||
```
|
||||
Alternatively,
|
||||
you can configure `env_logger` to write to stdout in your application:
|
||||
```rust
|
||||
fn main(){
|
||||
env_logger::builder()
|
||||
.target(env_logger::Target::Stdout)
|
||||
.init();
|
||||
// ...
|
||||
}
|
||||
```
|
||||
And then redirect stdout:
|
||||
```
|
||||
RUST_LOG=menu=debug cargo run > path/to/your/log_file
|
||||
```
|
||||
|
||||
To run the menu example with debug enabled:
|
||||
```
|
||||
RUST_LOG=menu=debug cargo run --example menu --features "debug_log"
|
||||
```
|
||||
+371
@@ -0,0 +1,371 @@
|
||||
use iced_core::{
|
||||
Padding, Rectangle, Shell, Size,
|
||||
layout::{Layout, Node},
|
||||
mouse, renderer,
|
||||
widget::Tree,
|
||||
};
|
||||
|
||||
use super::menu_bar::{GlobalState, MenuBarTask};
|
||||
use super::menu_tree::{Item, MenuState};
|
||||
use crate::style::menu_bar::Catalog;
|
||||
|
||||
///
|
||||
/// ## FakeHovering:
|
||||
///
|
||||
/// Places cursors at the path items,
|
||||
/// useful when you want to customize the styling of each item in the path,
|
||||
/// or you simple want the look of the items when they are hovered over.
|
||||
///
|
||||
/// The downside is when some widget in the path don't response to hovering,
|
||||
/// the path won't be fully drawn, and when you want uniform path styling
|
||||
/// but some widget response to hovering differently.
|
||||
///
|
||||
/// ## Backdrop:
|
||||
///
|
||||
/// Draws a rectangle behind each path item,
|
||||
/// requires path items to have transparent backgrounds,
|
||||
/// useful when you want uniform path styling.
|
||||
///
|
||||
/// The downside is,
|
||||
/// depending on the style you're going for,
|
||||
/// oftentimes manually syncing the path's styling to the path items' is necessary,
|
||||
/// the default styling simply can't cover most use cases.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum DrawPath {
|
||||
/// FakeHovering
|
||||
FakeHovering,
|
||||
/// Backdrop
|
||||
Backdrop,
|
||||
}
|
||||
|
||||
/// X+ goes right and Y+ goes down
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum Direction {
|
||||
Positive,
|
||||
Negative,
|
||||
}
|
||||
impl Direction {
|
||||
pub(super) fn flip(self) -> Self {
|
||||
match self {
|
||||
Self::Positive => Self::Negative,
|
||||
Self::Negative => Self::Positive,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Axis
|
||||
#[allow(missing_docs)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum Axis {
|
||||
Horizontal,
|
||||
Vertical,
|
||||
}
|
||||
|
||||
pub(super) type Index = Option<usize>;
|
||||
|
||||
/// Should be returned from the recursive event processing function,
|
||||
/// tells the caller which type of event has been processed
|
||||
///
|
||||
/// `Event`: The child event has been processed.
|
||||
/// The parent menu should not process the event.
|
||||
///
|
||||
/// `Close`: Either the child menu has decided to close itself,
|
||||
/// or that there is no child menu open,
|
||||
/// from the parent menu's perspective,
|
||||
/// there is no difference between the two.
|
||||
/// The parent menu should check if it should close itself,
|
||||
/// if not then it should process the event.
|
||||
///
|
||||
/// `None`: A child menu is open, but it did not process the event,
|
||||
/// this happens when the cursor hovers over the item that opens the child menu
|
||||
/// but has not entered the child menu yet,
|
||||
/// in this case the parent menu should process the event,
|
||||
/// but close check is not needed.
|
||||
///
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum RecEvent {
|
||||
Event,
|
||||
Close,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
/// Scroll speed
|
||||
pub struct ScrollSpeed {
|
||||
/// Speed of line-based scroll movement
|
||||
pub line: f32,
|
||||
/// Speed of Pixel scroll movement
|
||||
pub pixel: f32,
|
||||
}
|
||||
|
||||
pub fn pad_rectangle(rect: Rectangle, padding: Padding) -> Rectangle {
|
||||
Rectangle {
|
||||
x: rect.x - padding.left,
|
||||
y: rect.y - padding.top,
|
||||
width: rect.width + padding.x(),
|
||||
height: rect.height + padding.y(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) struct MenuSlice {
|
||||
pub(super) start_index: usize,
|
||||
pub(super) end_index: usize,
|
||||
pub(super) lower_bound_rel: f32,
|
||||
pub(super) upper_bound_rel: f32,
|
||||
}
|
||||
impl MenuSlice {
|
||||
pub(super) fn from_bounds_rel(
|
||||
lower_bound_rel: f32,
|
||||
upper_bound_rel: f32,
|
||||
items_node: &Node,
|
||||
get_position: fn(&Node) -> f32,
|
||||
) -> Self {
|
||||
let max_index = items_node.children().len().saturating_sub(1);
|
||||
let nodes = items_node.children();
|
||||
let start_index = search_bound(0, max_index, lower_bound_rel, nodes, get_position);
|
||||
let end_index = search_bound(start_index, max_index, upper_bound_rel, nodes, get_position);
|
||||
|
||||
Self {
|
||||
start_index,
|
||||
end_index,
|
||||
lower_bound_rel,
|
||||
upper_bound_rel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* fn search_bound_lin(
|
||||
bound: f32,
|
||||
nodes: &[Node],
|
||||
mut start_index: usize, // should be less than nodes.len()-1
|
||||
) -> usize{
|
||||
for (i, n) in nodes.iter().enumerate().skip(start_index){
|
||||
let b = n.bounds();
|
||||
if !(bound > b.y + b.height){
|
||||
start_index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
start_index
|
||||
} */
|
||||
|
||||
pub(super) fn search_bound(
|
||||
default_left: usize,
|
||||
default_right: usize,
|
||||
bound: f32,
|
||||
list: &[Node],
|
||||
get_position: fn(&Node) -> f32,
|
||||
) -> usize {
|
||||
// binary search
|
||||
let mut left = default_left;
|
||||
let mut right = default_right;
|
||||
|
||||
while left != right {
|
||||
let m = usize::midpoint(left, right) + 1;
|
||||
if get_position(&list[m]) > bound {
|
||||
right = m - 1;
|
||||
} else {
|
||||
left = m;
|
||||
}
|
||||
}
|
||||
left
|
||||
}
|
||||
|
||||
pub(super) fn clip_node_y(node: &Node, height: f32, offset: f32) -> Node {
|
||||
let node_bounds = node.bounds();
|
||||
Node::with_children(
|
||||
Size::new(node_bounds.width, height),
|
||||
node.children()
|
||||
.iter()
|
||||
.map(|n| n.clone().translate([0.0, -offset]))
|
||||
.collect(),
|
||||
)
|
||||
.move_to(node_bounds.position())
|
||||
.translate([0.0, offset])
|
||||
}
|
||||
|
||||
pub(super) fn clip_node_x(node: &Node, width: f32, offset: f32) -> Node {
|
||||
let node_bounds = node.bounds();
|
||||
Node::with_children(
|
||||
Size::new(width, node_bounds.height),
|
||||
node.children()
|
||||
.iter()
|
||||
.map(|n| n.clone().translate([-offset, 0.0]))
|
||||
.collect(),
|
||||
)
|
||||
.move_to(node_bounds.position())
|
||||
.translate([offset, 0.0])
|
||||
}
|
||||
|
||||
/// Parameters that are shared by all menus in the menu bar
|
||||
pub(super) struct GlobalParameters<'a, Theme: crate::style::menu_bar::Catalog> {
|
||||
pub(super) safe_bounds_margin: f32,
|
||||
pub(super) draw_path: DrawPath,
|
||||
pub(super) scroll_speed: ScrollSpeed,
|
||||
pub(super) close_on_item_click: bool,
|
||||
pub(super) close_on_background_click: bool,
|
||||
pub(super) class: Theme::Class<'a>,
|
||||
}
|
||||
|
||||
/// Tries to open a menu at the given cursor position
|
||||
pub(super) fn try_open_menu<'a, 'b, Message, Theme: Catalog, Renderer: renderer::Renderer>(
|
||||
items: &mut [Item<'a, Message, Theme, Renderer>],
|
||||
menu_state: &mut MenuState,
|
||||
item_trees: &mut [Tree],
|
||||
item_layouts: impl Iterator<Item = Layout<'b>>,
|
||||
cursor: mouse::Cursor,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
) {
|
||||
let old_active = menu_state.active;
|
||||
let slice = menu_state.slice;
|
||||
|
||||
for (i, ((item, tree), layout)) in
|
||||
itl_iter_slice_enum!(slice, items;iter_mut, item_trees;iter_mut, item_layouts)
|
||||
{
|
||||
if cursor.is_over(layout.bounds()) {
|
||||
if item.menu.is_some() {
|
||||
menu_state.open_new_menu(i, item, tree);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if menu_state.active != old_active {
|
||||
shell.invalidate_layout();
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
/// Schedules a close on click task if applicable
|
||||
///
|
||||
/// This function assumes that a mouse::Event::ButtonPressed(mouse::Button::Left) event has occurred,
|
||||
/// make sure to check the event before calling this function.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn schedule_close_on_click<
|
||||
'a,
|
||||
'b,
|
||||
Message,
|
||||
Theme: Catalog,
|
||||
Renderer: renderer::Renderer,
|
||||
>(
|
||||
global_state: &mut GlobalState,
|
||||
global_parameters: &GlobalParameters<'_, Theme>,
|
||||
slice: MenuSlice,
|
||||
items: &mut [Item<'a, Message, Theme, Renderer>],
|
||||
slice_layout: impl Iterator<Item = Layout<'b>>,
|
||||
cursor: mouse::Cursor,
|
||||
menu_close_on_item_click: Option<bool>,
|
||||
menu_close_on_background_click: Option<bool>,
|
||||
) {
|
||||
global_state.clear_task();
|
||||
|
||||
let mut coc_handled = false;
|
||||
|
||||
for (item, layout) in items[slice.start_index..=slice.end_index] // [item...]
|
||||
.iter_mut()
|
||||
.zip(slice_layout)
|
||||
{
|
||||
if cursor.is_over(layout.bounds()) {
|
||||
if let Some(coc) = item.close_on_click {
|
||||
coc_handled = true;
|
||||
if coc {
|
||||
global_state.schedule(MenuBarTask::CloseOnClick);
|
||||
}
|
||||
}
|
||||
for cocfb in [
|
||||
menu_close_on_item_click,
|
||||
Some(global_parameters.close_on_item_click),
|
||||
] {
|
||||
if let (false, Some(coc)) = (coc_handled, cocfb) {
|
||||
coc_handled = true;
|
||||
if coc {
|
||||
global_state.schedule(MenuBarTask::CloseOnClick);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for cocfb in [
|
||||
menu_close_on_background_click,
|
||||
Some(global_parameters.close_on_background_click),
|
||||
] {
|
||||
if let (false, Some(coc)) = (coc_handled, cocfb) {
|
||||
coc_handled = true;
|
||||
if coc {
|
||||
global_state.schedule(MenuBarTask::CloseOnClick);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! itl_iter_slice {
|
||||
($slice:expr, $items:expr;$iter_0:ident, $item_trees:expr;$iter_1:ident, $slice_layout:expr) => {
|
||||
$items[$slice.start_index..=$slice.end_index]
|
||||
.$iter_0()
|
||||
.zip($item_trees[$slice.start_index..=$slice.end_index].$iter_1())
|
||||
.zip($slice_layout)
|
||||
};
|
||||
}
|
||||
pub(super) use itl_iter_slice;
|
||||
|
||||
macro_rules! itl_iter_slice_enum {
|
||||
($slice:expr, $items:expr;$iter_0:ident, $item_trees:expr;$iter_1:ident, $slice_layout:expr) => {
|
||||
itl_iter_slice!($slice, $items;$iter_0, $item_trees;$iter_1, $slice_layout)
|
||||
.enumerate()
|
||||
.map(move |(i, ((item, tree), layout))| (i + $slice.start_index, ((item, tree), layout)))
|
||||
};
|
||||
}
|
||||
pub(super) use itl_iter_slice_enum;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) struct SafeTriangle {
|
||||
pub(super) p1: iced_core::Point,
|
||||
pub(super) p2: iced_core::Point,
|
||||
pub(super) p3: iced_core::Point,
|
||||
}
|
||||
|
||||
impl SafeTriangle {
|
||||
pub(super) fn new(
|
||||
p1: iced_core::Point,
|
||||
child_bounds: Rectangle,
|
||||
direction: (Direction, Direction),
|
||||
) -> Self {
|
||||
let (child_corner1, child_corner2) = match direction.0 {
|
||||
Direction::Positive => (
|
||||
iced_core::Point::new(child_bounds.x, child_bounds.y),
|
||||
iced_core::Point::new(child_bounds.x, child_bounds.y + child_bounds.height),
|
||||
),
|
||||
Direction::Negative => (
|
||||
iced_core::Point::new(child_bounds.x + child_bounds.width, child_bounds.y),
|
||||
iced_core::Point::new(
|
||||
child_bounds.x + child_bounds.width,
|
||||
child_bounds.y + child_bounds.height,
|
||||
),
|
||||
),
|
||||
};
|
||||
|
||||
Self {
|
||||
p1,
|
||||
p2: child_corner1,
|
||||
p3: child_corner2,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn contains(&self, point: iced_core::Point) -> bool {
|
||||
let sign = |p1: iced_core::Point, p2: iced_core::Point, p3: iced_core::Point| -> f32 {
|
||||
(p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y)
|
||||
};
|
||||
|
||||
let d1 = sign(point, self.p1, self.p2);
|
||||
let d2 = sign(point, self.p2, self.p3);
|
||||
let d3 = sign(point, self.p3, self.p1);
|
||||
|
||||
let has_neg = (d1 < 0.0) || (d2 < 0.0) || (d3 < 0.0);
|
||||
let has_pos = (d1 > 0.0) || (d2 > 0.0) || (d3 > 0.0);
|
||||
|
||||
!(has_neg && has_pos)
|
||||
}
|
||||
}
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
//! Distribute elements using a flex-based layout.
|
||||
// This code is heavily inspired by the [`druid`] codebase.
|
||||
//
|
||||
// [`druid`]: https://github.com/xi-editor/druid
|
||||
//
|
||||
// Copyright 2018 The xi-editor Authors, Héctor Ramón
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#![allow(clippy::all)]
|
||||
#![allow(clippy::pedantic)]
|
||||
#![allow(clippy::use_self)]
|
||||
|
||||
use iced_core::{
|
||||
Alignment, Element, Length, Padding, Pixels, Point, Size,
|
||||
layout::{Limits, Node},
|
||||
renderer, widget,
|
||||
};
|
||||
|
||||
/// The main axis of a flex layout.
|
||||
#[derive(Debug)]
|
||||
pub enum Axis {
|
||||
/// The horizontal axis
|
||||
Horizontal,
|
||||
|
||||
/// The vertical axis
|
||||
Vertical,
|
||||
}
|
||||
|
||||
impl Axis {
|
||||
fn main(&self, size: Size) -> f32 {
|
||||
match self {
|
||||
Axis::Horizontal => size.width,
|
||||
Axis::Vertical => size.height,
|
||||
}
|
||||
}
|
||||
|
||||
fn cross(&self, size: Size) -> f32 {
|
||||
match self {
|
||||
Axis::Horizontal => size.height,
|
||||
Axis::Vertical => size.width,
|
||||
}
|
||||
}
|
||||
|
||||
fn pack<T>(&self, main: T, cross: T) -> (T, T) {
|
||||
match self {
|
||||
Axis::Horizontal => (main, cross),
|
||||
Axis::Vertical => (cross, main),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the flex layout with the given axis and limits, applying spacing,
|
||||
/// padding and alignment to the items as needed.
|
||||
///
|
||||
/// It returns a new layout [`Node`].
|
||||
pub fn resolve<'a, E, T, Message, Theme, Renderer>(
|
||||
axis: Axis,
|
||||
renderer: &Renderer,
|
||||
limits: &Limits,
|
||||
width: Length,
|
||||
height: Length,
|
||||
padding: Padding,
|
||||
spacing: Pixels,
|
||||
align_items: Alignment,
|
||||
items: &mut [E],
|
||||
trees: &mut [T],
|
||||
) -> Node
|
||||
where
|
||||
E: std::borrow::BorrowMut<Element<'a, Message, Theme, Renderer>>,
|
||||
T: std::borrow::BorrowMut<widget::Tree>,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
let limits = limits.width(width).height(height).shrink(padding);
|
||||
let total_spacing = spacing * items.len().saturating_sub(1) as f32;
|
||||
let max_cross = axis.cross(limits.max());
|
||||
|
||||
let mut fill_main_sum = 0;
|
||||
let mut cross = match axis {
|
||||
Axis::Horizontal => match height {
|
||||
Length::Shrink => 0.0,
|
||||
_ => max_cross,
|
||||
},
|
||||
Axis::Vertical => match width {
|
||||
Length::Shrink => 0.0,
|
||||
_ => max_cross,
|
||||
},
|
||||
};
|
||||
|
||||
let mut available = axis.main(limits.max()) - total_spacing.0;
|
||||
|
||||
let mut nodes: Vec<Node> = Vec::with_capacity(items.len());
|
||||
nodes.resize(items.len(), Node::default());
|
||||
|
||||
for (i, (child, tree)) in items.iter_mut().zip(trees.iter_mut()).enumerate() {
|
||||
let (fill_main_factor, fill_cross_factor) = {
|
||||
let size = child.borrow().as_widget().size();
|
||||
|
||||
axis.pack(size.width.fill_factor(), size.height.fill_factor())
|
||||
};
|
||||
|
||||
if fill_main_factor == 0 {
|
||||
if fill_cross_factor == 0 {
|
||||
let (max_width, max_height) = axis.pack(available, max_cross);
|
||||
|
||||
let child_limits = Limits::new(Size::ZERO, Size::new(max_width, max_height));
|
||||
|
||||
let layout = child.borrow_mut().as_widget_mut().layout(
|
||||
tree.borrow_mut(),
|
||||
renderer,
|
||||
&child_limits,
|
||||
);
|
||||
let size = layout.size();
|
||||
|
||||
available -= axis.main(size);
|
||||
cross = cross.max(axis.cross(size));
|
||||
|
||||
nodes[i] = layout;
|
||||
}
|
||||
} else {
|
||||
fill_main_sum += fill_main_factor;
|
||||
}
|
||||
}
|
||||
|
||||
for (i, (child, tree)) in items.iter_mut().zip(trees.iter_mut()).enumerate() {
|
||||
let (fill_main_factor, fill_cross_factor) = {
|
||||
let size = child.borrow().as_widget().size();
|
||||
|
||||
axis.pack(size.width.fill_factor(), size.height.fill_factor())
|
||||
};
|
||||
|
||||
if fill_main_factor == 0 && fill_cross_factor != 0 {
|
||||
let (max_width, max_height) = axis.pack(available, cross);
|
||||
|
||||
let child_limits = Limits::new(Size::ZERO, Size::new(max_width, max_height));
|
||||
|
||||
let layout = child.borrow_mut().as_widget_mut().layout(
|
||||
tree.borrow_mut(),
|
||||
renderer,
|
||||
&child_limits,
|
||||
);
|
||||
let size = layout.size();
|
||||
|
||||
available -= axis.main(size);
|
||||
cross = cross.max(axis.cross(layout.size()));
|
||||
|
||||
nodes[i] = layout;
|
||||
}
|
||||
}
|
||||
|
||||
let remaining = match axis {
|
||||
Axis::Horizontal => match width {
|
||||
Length::Shrink => 0.0,
|
||||
_ => available.max(0.0),
|
||||
},
|
||||
Axis::Vertical => match height {
|
||||
Length::Shrink => 0.0,
|
||||
_ => available.max(0.0),
|
||||
},
|
||||
};
|
||||
|
||||
for (i, (child, tree)) in items.iter_mut().zip(trees).enumerate() {
|
||||
let (fill_main_factor, fill_cross_factor) = {
|
||||
let size = child.borrow().as_widget().size();
|
||||
|
||||
axis.pack(size.width.fill_factor(), size.height.fill_factor())
|
||||
};
|
||||
|
||||
if fill_main_factor != 0 {
|
||||
let max_main = remaining * fill_main_factor as f32 / fill_main_sum as f32;
|
||||
|
||||
let min_main = if max_main.is_infinite() {
|
||||
0.0
|
||||
} else {
|
||||
max_main
|
||||
};
|
||||
|
||||
let max_cross = if fill_cross_factor == 0 {
|
||||
max_cross
|
||||
} else {
|
||||
cross
|
||||
};
|
||||
|
||||
let (min_width, min_height) = axis.pack(min_main, 0.0);
|
||||
let (max_width, max_height) = axis.pack(max_main, max_cross);
|
||||
|
||||
let child_limits = Limits::new(
|
||||
Size::new(min_width, min_height),
|
||||
Size::new(max_width, max_height),
|
||||
);
|
||||
|
||||
let layout = child.borrow_mut().as_widget_mut().layout(
|
||||
tree.borrow_mut(),
|
||||
renderer,
|
||||
&child_limits,
|
||||
);
|
||||
cross = cross.max(axis.cross(layout.size()));
|
||||
|
||||
nodes[i] = layout;
|
||||
}
|
||||
}
|
||||
|
||||
let pad = axis.pack(padding.left, padding.top);
|
||||
let mut main = pad.0;
|
||||
|
||||
for (i, node) in nodes.iter_mut().enumerate() {
|
||||
if i > 0 {
|
||||
main += spacing.0;
|
||||
}
|
||||
|
||||
let (x, y) = axis.pack(main, pad.1);
|
||||
|
||||
node.move_to_mut(Point::new(x, y));
|
||||
|
||||
match axis {
|
||||
Axis::Horizontal => {
|
||||
node.align_mut(Alignment::Start, align_items, Size::new(0.0, cross));
|
||||
}
|
||||
Axis::Vertical => {
|
||||
node.align_mut(align_items, Alignment::Start, Size::new(cross, 0.0));
|
||||
}
|
||||
}
|
||||
|
||||
let size = node.size();
|
||||
|
||||
main += axis.main(size);
|
||||
}
|
||||
|
||||
let (intrinsic_width, intrinsic_height) = axis.pack(main - pad.0, cross);
|
||||
let size = limits.resolve(width, height, Size::new(intrinsic_width, intrinsic_height));
|
||||
|
||||
Node::with_children(size.expand(padding), nodes)
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 107 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 147 KiB |
+885
@@ -0,0 +1,885 @@
|
||||
//! [`MenuBar`]
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
#![allow(clippy::doc_markdown)]
|
||||
#![allow(clippy::wildcard_imports)]
|
||||
#![allow(clippy::enum_glob_use)]
|
||||
|
||||
use iced_core::{
|
||||
Clipboard, Element, Event, Layout, Length, Padding, Pixels, Rectangle, Shell, Size, Widget,
|
||||
alignment, event,
|
||||
layout::{Limits, Node},
|
||||
mouse, overlay, renderer,
|
||||
widget::{Operation, Tree, tree},
|
||||
window,
|
||||
};
|
||||
|
||||
use super::{common::*, flex, menu_bar_overlay::MenuBarOverlay, menu_tree::*};
|
||||
use crate::style::menu_bar::*;
|
||||
pub use crate::style::status::{Status, StyleFn};
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
use log::debug;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum MenuBarTask {
|
||||
OpenOnClick,
|
||||
CloseOnClick,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(super) struct GlobalState {
|
||||
pub(super) open: bool,
|
||||
pub(super) pressed: bool,
|
||||
task: Option<MenuBarTask>,
|
||||
}
|
||||
impl GlobalState {
|
||||
pub(super) fn schedule(&mut self, task: MenuBarTask) {
|
||||
self.task = Some(task);
|
||||
}
|
||||
|
||||
pub(super) fn task(&self) -> Option<MenuBarTask> {
|
||||
self.task
|
||||
}
|
||||
|
||||
pub(super) fn clear_task(&mut self) {
|
||||
self.task = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(super) struct MenuBarState {
|
||||
pub(super) global_state: GlobalState,
|
||||
pub(super) menu_state: MenuState,
|
||||
}
|
||||
impl MenuBarState {
|
||||
pub(super) fn open<'a, 'b, Message, Theme: Catalog, Renderer: renderer::Renderer>(
|
||||
&mut self,
|
||||
roots: &mut [Item<'a, Message, Theme, Renderer>],
|
||||
item_trees: &mut [Tree],
|
||||
item_layouts: impl Iterator<Item = Layout<'b>>,
|
||||
cursor: mouse::Cursor,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
) {
|
||||
if !self.global_state.open {
|
||||
self.global_state.open = true;
|
||||
self.menu_state.active = None;
|
||||
}
|
||||
|
||||
try_open_menu(
|
||||
roots,
|
||||
&mut self.menu_state,
|
||||
item_trees,
|
||||
item_layouts,
|
||||
cursor,
|
||||
shell,
|
||||
);
|
||||
|
||||
self.global_state.task = None;
|
||||
}
|
||||
|
||||
pub(super) fn close<Message>(
|
||||
&mut self,
|
||||
item_trees: &mut [Tree],
|
||||
shell: &mut Shell<'_, Message>,
|
||||
) {
|
||||
if self.global_state.pressed {
|
||||
return;
|
||||
}
|
||||
|
||||
for item_tree in item_trees.iter_mut() {
|
||||
if item_tree.children.len() == 2 {
|
||||
let _ = item_tree.children.pop();
|
||||
shell.invalidate_layout();
|
||||
}
|
||||
}
|
||||
self.global_state.pressed = false;
|
||||
self.global_state.task = None;
|
||||
self.global_state.open = false;
|
||||
self.menu_state.active = None;
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
/// menu bar
|
||||
#[must_use]
|
||||
pub struct MenuBar<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: Catalog,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
pub(super) roots: Vec<Item<'a, Message, Theme, Renderer>>,
|
||||
spacing: Pixels,
|
||||
padding: Padding,
|
||||
width: Length,
|
||||
height: Length,
|
||||
close_on_item_click: Option<bool>,
|
||||
close_on_background_click: Option<bool>,
|
||||
pub(super) global_parameters: GlobalParameters<'a, Theme>,
|
||||
}
|
||||
impl<'a, Message, Theme, Renderer> MenuBar<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: Catalog,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
/// Creates a [`MenuBar`] with the given root items.
|
||||
pub fn new(mut roots: Vec<Item<'a, Message, Theme, Renderer>>) -> Self {
|
||||
for i in &mut roots {
|
||||
if let Some(m) = i.menu.as_mut() {
|
||||
m.axis = Axis::Vertical;
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
roots,
|
||||
spacing: Pixels::ZERO,
|
||||
padding: Padding::ZERO,
|
||||
width: Length::Shrink,
|
||||
height: Length::Shrink,
|
||||
close_on_item_click: None,
|
||||
close_on_background_click: None,
|
||||
global_parameters: GlobalParameters {
|
||||
safe_bounds_margin: 50.0,
|
||||
draw_path: DrawPath::FakeHovering,
|
||||
scroll_speed: ScrollSpeed {
|
||||
line: 60.0,
|
||||
pixel: 1.0,
|
||||
},
|
||||
close_on_item_click: false,
|
||||
close_on_background_click: false,
|
||||
class: Theme::default(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the width of the [`MenuBar`].
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`MenuBar`].
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the spacing of the [`MenuBar`].
|
||||
pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self {
|
||||
self.spacing = spacing.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the margin of the safe bounds of the [`Menu`]s in the [`MenuBar`].
|
||||
///
|
||||
/// Defines a rectangular safe area that extends each menu's background bounds by a margin.
|
||||
/// If the cursor moves outside this area, the menu will be closed.
|
||||
pub fn safe_bounds_margin(mut self, margin: f32) -> Self {
|
||||
self.global_parameters.safe_bounds_margin = margin;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the draw path option of the [`MenuBar`]
|
||||
pub fn draw_path(mut self, draw_path: DrawPath) -> Self {
|
||||
self.global_parameters.draw_path = draw_path;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the scroll speed of the [`Menu`]s in the [`MenuBar`]
|
||||
pub fn scroll_speed(mut self, scroll_speed: ScrollSpeed) -> Self {
|
||||
self.global_parameters.scroll_speed = scroll_speed;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the close on item click option of the [`MenuBar`]
|
||||
pub fn close_on_item_click(mut self, value: bool) -> Self {
|
||||
self.close_on_item_click = Some(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the close on background click option of the [`MenuBar`]
|
||||
pub fn close_on_background_click(mut self, value: bool) -> Self {
|
||||
self.close_on_background_click = Some(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the global default close on item click option
|
||||
pub fn close_on_item_click_global(mut self, value: bool) -> Self {
|
||||
self.global_parameters.close_on_item_click = value;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the global default close on background click option
|
||||
pub fn close_on_background_click_global(mut self, value: bool) -> Self {
|
||||
self.global_parameters.close_on_background_click = value;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the padding of the [`MenuBar`].
|
||||
pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
|
||||
self.padding = padding.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the style of the [`MenuBar`].
|
||||
pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
|
||||
where
|
||||
Theme::Class<'a>: From<StyleFn<'a, Theme, Style>>,
|
||||
{
|
||||
self.global_parameters.class = (Box::new(style) as StyleFn<'a, Theme, Style>).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the class of the input of the [`MenuBar`].
|
||||
pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
|
||||
self.global_parameters.class = class.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for MenuBar<'_, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: Catalog,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size::new(self.width, self.height)
|
||||
}
|
||||
|
||||
fn tag(&self) -> tree::Tag {
|
||||
tree::Tag::of::<MenuBarState>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::Some(Box::<MenuBarState>::default())
|
||||
}
|
||||
|
||||
/// \[Tree{stateless, \[widget_state, menu_state]}...]
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
self.roots.iter().map(Item::tree).collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
/// tree: Tree{bar, \[item_tree...]}
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children_custom(&self.roots, |tree, item| item.diff(tree), Item::tree);
|
||||
}
|
||||
|
||||
/// tree: Tree{bar, \[item_tree...]}
|
||||
///
|
||||
/// out: Node{bar bounds , \[widget_layout, widget_layout, ...]}
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
// TODO: unify layout code with Menu
|
||||
|
||||
let MenuBarState {
|
||||
menu_state: bar_menu_state,
|
||||
..
|
||||
} = tree.state.downcast_mut::<MenuBarState>();
|
||||
|
||||
let items_node = flex::resolve(
|
||||
flex::Axis::Horizontal,
|
||||
renderer,
|
||||
&Limits::new(
|
||||
Size {
|
||||
width: 0.0,
|
||||
height: limits.min().height,
|
||||
},
|
||||
Size {
|
||||
width: f32::INFINITY,
|
||||
height: limits.max().height,
|
||||
},
|
||||
),
|
||||
Length::Shrink,
|
||||
// self.width,
|
||||
self.height,
|
||||
self.padding,
|
||||
self.spacing,
|
||||
alignment::Alignment::Center,
|
||||
&mut self
|
||||
.roots
|
||||
.iter_mut()
|
||||
.map(|item| &mut item.item)
|
||||
.collect::<Vec<_>>(),
|
||||
&mut tree
|
||||
.children
|
||||
.iter_mut()
|
||||
.map(|tree| &mut tree.children[0])
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
let items_node_bounds = items_node.bounds();
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!("menu::MenuBar::layout | items_node_bounds: {items_node_bounds:?}");
|
||||
|
||||
let resolved_width = match self.width {
|
||||
Length::Fill | Length::FillPortion(_) => items_node_bounds
|
||||
.width
|
||||
.min(limits.max().width)
|
||||
.max(limits.min().width),
|
||||
Length::Fixed(amount) => amount.min(limits.max().width).max(limits.min().width),
|
||||
Length::Shrink => items_node_bounds.width,
|
||||
};
|
||||
|
||||
let lower_bound_rel = self.padding.left - bar_menu_state.scroll_offset;
|
||||
let upper_bound_rel = lower_bound_rel + resolved_width - self.padding.x();
|
||||
|
||||
let slice =
|
||||
MenuSlice::from_bounds_rel(lower_bound_rel, upper_bound_rel, &items_node, |n| {
|
||||
n.bounds().x
|
||||
});
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!("menu::MenuBar::layout | slice: {slice:?}");
|
||||
|
||||
bar_menu_state.slice = slice;
|
||||
|
||||
let slice_node = if slice.start_index == slice.end_index {
|
||||
let node = &items_node.children()[slice.start_index];
|
||||
let bounds = node.bounds();
|
||||
let start_offset = slice.lower_bound_rel - bounds.x;
|
||||
let width = slice.upper_bound_rel - slice.lower_bound_rel;
|
||||
|
||||
Node::with_children(
|
||||
Size::new(width, items_node.bounds().height),
|
||||
std::iter::once(clip_node_x(node, width, start_offset)).collect(),
|
||||
)
|
||||
} else {
|
||||
let start_node = {
|
||||
let node = &items_node.children()[slice.start_index];
|
||||
let bounds = node.bounds();
|
||||
let start_offset = slice.lower_bound_rel - bounds.x;
|
||||
let width = bounds.width - start_offset;
|
||||
clip_node_x(node, width, start_offset)
|
||||
};
|
||||
|
||||
let end_node = {
|
||||
let node = &items_node.children()[slice.end_index];
|
||||
let bounds = node.bounds();
|
||||
let width = slice.upper_bound_rel - bounds.x;
|
||||
clip_node_x(node, width, 0.0)
|
||||
};
|
||||
|
||||
Node::with_children(
|
||||
items_node_bounds.size(),
|
||||
std::iter::once(start_node)
|
||||
.chain(
|
||||
items_node.children()[slice.start_index + 1..slice.end_index]
|
||||
.iter()
|
||||
.map(Clone::clone),
|
||||
)
|
||||
.chain(std::iter::once(end_node))
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
|
||||
Node::with_children(
|
||||
Size {
|
||||
width: resolved_width,
|
||||
height: items_node_bounds.height,
|
||||
},
|
||||
[
|
||||
// items_node
|
||||
slice_node.translate([bar_menu_state.scroll_offset, 0.0]),
|
||||
]
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
event: &event::Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBar::update", "");
|
||||
|
||||
let slice_layout = layout.children().next().unwrap();
|
||||
|
||||
let Tree {
|
||||
state,
|
||||
children: item_trees,
|
||||
..
|
||||
} = tree;
|
||||
let bar = state.downcast_mut::<MenuBarState>();
|
||||
let MenuBarState {
|
||||
global_state,
|
||||
menu_state: bar_menu_state,
|
||||
} = bar;
|
||||
|
||||
let slice = bar_menu_state.slice;
|
||||
itl_iter_slice!(
|
||||
slice,
|
||||
self.roots;iter_mut,
|
||||
item_trees;iter_mut,
|
||||
slice_layout.children()
|
||||
)
|
||||
.for_each(|((item, tree), layout)| {
|
||||
item.update(
|
||||
tree, event, layout, cursor, renderer, clipboard, shell, viewport,
|
||||
);
|
||||
});
|
||||
|
||||
let bar_bounds = layout.bounds();
|
||||
// println!("bar_bounds: {:?}", bar_bounds);
|
||||
// println!("cursor: {:?}", cursor);
|
||||
// println!("cursor in bar_bounds: {:?}", cursor.is_over(bar_bounds));
|
||||
|
||||
match event {
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
|
||||
if cursor.is_over(bar_bounds) =>
|
||||
{
|
||||
global_state.pressed = true;
|
||||
if global_state.open {
|
||||
schedule_close_on_click(
|
||||
global_state,
|
||||
&self.global_parameters,
|
||||
slice,
|
||||
&mut self.roots,
|
||||
slice_layout.children(),
|
||||
cursor,
|
||||
self.close_on_item_click,
|
||||
self.close_on_background_click,
|
||||
);
|
||||
} else {
|
||||
global_state.schedule(MenuBarTask::OpenOnClick);
|
||||
}
|
||||
shell.capture_event();
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
|
||||
global_state.pressed = false;
|
||||
|
||||
if let Some(task) = global_state.task {
|
||||
match task {
|
||||
MenuBarTask::OpenOnClick => {
|
||||
bar.open(
|
||||
&mut self.roots,
|
||||
item_trees,
|
||||
slice_layout.children(),
|
||||
cursor,
|
||||
shell,
|
||||
);
|
||||
}
|
||||
MenuBarTask::CloseOnClick => {
|
||||
bar.close(item_trees, shell);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::CursorMoved { .. }) if global_state.open => {
|
||||
if cursor.is_over(bar_bounds) {
|
||||
try_open_menu(
|
||||
&mut self.roots,
|
||||
bar_menu_state,
|
||||
item_trees,
|
||||
slice_layout.children(),
|
||||
cursor,
|
||||
shell,
|
||||
);
|
||||
shell.capture_event();
|
||||
} else {
|
||||
bar.close(item_trees, shell);
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::WheelScrolled { delta })
|
||||
if cursor.is_over(bar_bounds)
|
||||
&& slice_layout.bounds().width > layout.bounds().width =>
|
||||
{
|
||||
let scroll_speed = self.global_parameters.scroll_speed;
|
||||
let delta_x = match delta {
|
||||
mouse::ScrollDelta::Lines { x, .. } => x * scroll_speed.line,
|
||||
mouse::ScrollDelta::Pixels { x, .. } => x * scroll_speed.pixel,
|
||||
};
|
||||
|
||||
let min_offset = -(slice_layout.bounds().width - layout.bounds().width);
|
||||
|
||||
bar_menu_state.scroll_offset =
|
||||
(bar_menu_state.scroll_offset + delta_x).clamp(min_offset, 0.0);
|
||||
shell.invalidate_layout();
|
||||
shell.request_redraw();
|
||||
shell.capture_event();
|
||||
}
|
||||
Event::Window(window::Event::Resized { .. }) => {
|
||||
if slice_layout.bounds().width > layout.bounds().width {
|
||||
let min_offset = -(slice_layout.bounds().width - layout.bounds().width);
|
||||
|
||||
bar_menu_state.scroll_offset =
|
||||
bar_menu_state.scroll_offset.clamp(min_offset, 0.0);
|
||||
}
|
||||
shell.invalidate_layout();
|
||||
shell.request_redraw();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBar::update", "return | bar: {bar:?}");
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
let slice_layout = layout.children().next().unwrap();
|
||||
|
||||
let MenuBarState {
|
||||
menu_state: bar_menu_state,
|
||||
..
|
||||
} = tree.state.downcast_ref::<MenuBarState>();
|
||||
|
||||
let slice = bar_menu_state.slice;
|
||||
|
||||
operation.container(None, layout.bounds());
|
||||
operation.traverse(&mut |operation| {
|
||||
itl_iter_slice!(slice, self.roots;iter_mut, tree.children;iter_mut, slice_layout.children())
|
||||
.for_each(|((child, state), layout)| {
|
||||
child.operate(state, layout, renderer, operation);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
_viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
let slice_layout = layout.children().next().unwrap();
|
||||
|
||||
let MenuBarState {
|
||||
menu_state: bar_menu_state,
|
||||
..
|
||||
} = tree.state.downcast_ref::<MenuBarState>();
|
||||
|
||||
itl_iter_slice!(bar_menu_state.slice, self.roots;iter, tree.children;iter, slice_layout.children())
|
||||
.map(|((item, tree), layout)| item.mouse_interaction(tree, layout, cursor, renderer))
|
||||
.max()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let slice_layout = layout.children().next().unwrap();
|
||||
|
||||
let MenuBarState {
|
||||
global_state,
|
||||
menu_state: bar_menu_state,
|
||||
} = tree.state.downcast_ref::<MenuBarState>();
|
||||
|
||||
let slice = bar_menu_state.slice;
|
||||
|
||||
let styling = theme.style(&self.global_parameters.class, Status::Active);
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: layout.bounds(),
|
||||
border: styling.bar_border,
|
||||
shadow: styling.bar_shadow,
|
||||
..Default::default()
|
||||
},
|
||||
styling.bar_background,
|
||||
);
|
||||
|
||||
if let (DrawPath::Backdrop, true, Some(active)) = (
|
||||
&self.global_parameters.draw_path,
|
||||
global_state.open,
|
||||
bar_menu_state.active,
|
||||
) {
|
||||
let active_in_slice = active - slice.start_index;
|
||||
let active_bounds = slice_layout
|
||||
.children()
|
||||
.nth(active_in_slice)
|
||||
.expect(
|
||||
"Index (in slice space) is not within the menu bar layout. \
|
||||
This should not happen, please report this issue",
|
||||
)
|
||||
.bounds();
|
||||
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: active_bounds,
|
||||
border: styling.path_border,
|
||||
..Default::default()
|
||||
},
|
||||
styling.path,
|
||||
);
|
||||
}
|
||||
|
||||
renderer.with_layer(
|
||||
Rectangle {
|
||||
x: layout.bounds().x + self.padding.left,
|
||||
y: layout.bounds().y + self.padding.top,
|
||||
width: layout.bounds().width - self.padding.x(),
|
||||
height: layout.bounds().height - self.padding.y(),
|
||||
},
|
||||
|r| {
|
||||
itl_iter_slice!(slice, self.roots;iter, tree.children;iter, slice_layout.children())
|
||||
.for_each(|((item, tree), layout)| {
|
||||
item.draw(tree, r, theme, style, layout, cursor, viewport);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
tree: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: iced_core::Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBar::overlay", "");
|
||||
let bar = tree.state.downcast_mut::<MenuBarState>();
|
||||
|
||||
if bar.global_state.open {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBar::overlay", "return | Menu Overlay");
|
||||
Some(
|
||||
MenuBarOverlay {
|
||||
menu_bar: self,
|
||||
layout,
|
||||
translation,
|
||||
tree,
|
||||
}
|
||||
.overlay_element(),
|
||||
)
|
||||
} else {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBar::overlay", "state not open | try return root overlays");
|
||||
let slice_layout = layout.children().next()?;
|
||||
|
||||
let Tree {
|
||||
state,
|
||||
children: item_trees,
|
||||
..
|
||||
} = tree;
|
||||
let bar = state.downcast_mut::<MenuBarState>();
|
||||
let MenuBarState {
|
||||
menu_state: bar_menu_state,
|
||||
..
|
||||
} = bar;
|
||||
|
||||
let slice = bar_menu_state.slice;
|
||||
|
||||
let overlays = itl_iter_slice!(slice, self.roots;iter_mut, item_trees;iter_mut, slice_layout.children())
|
||||
.filter_map(|((item, item_tree), item_layout)| {
|
||||
item.item.as_widget_mut().overlay(
|
||||
&mut item_tree.children[0],
|
||||
item_layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if overlays.is_empty() {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBar::overlay", "return | None");
|
||||
None
|
||||
} else {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBar::overlay", "return | Root Item Overlay");
|
||||
Some(overlay::Group::with_children(overlays).overlay())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'a, Message, Theme, Renderer> From<MenuBar<'a, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a,
|
||||
Theme: 'a + Catalog,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
{
|
||||
fn from(value: MenuBar<'a, Message, Theme, Renderer>) -> Self {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use iced_widget::text::Text;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum TestMessage {
|
||||
Action1,
|
||||
Action2,
|
||||
}
|
||||
|
||||
type TestMenuBar<'a> = MenuBar<'a, TestMessage, iced_widget::Theme, iced_widget::Renderer>;
|
||||
|
||||
#[test]
|
||||
fn menu_bar_new_creates_instance() {
|
||||
let items = vec![Item::new(Text::new("File")), Item::new(Text::new("Edit"))];
|
||||
|
||||
let menu_bar = TestMenuBar::new(items);
|
||||
assert_eq!(menu_bar.roots.len(), 2);
|
||||
assert_eq!(menu_bar.spacing, Pixels::ZERO);
|
||||
assert_eq!(menu_bar.width, Length::Shrink);
|
||||
assert_eq!(menu_bar.height, Length::Shrink);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_width_sets_value() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items).width(Length::Fill);
|
||||
assert_eq!(menu_bar.width, Length::Fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_height_sets_value() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items).height(Length::Fixed(50.0));
|
||||
assert_eq!(menu_bar.height, Length::Fixed(50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_spacing_sets_value() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items).spacing(Pixels(10.0));
|
||||
assert_eq!(menu_bar.spacing, Pixels(10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_padding_sets_value() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items).padding(Padding::new(5.0));
|
||||
assert_eq!(menu_bar.padding, Padding::new(5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_safe_bounds_margin_sets_value() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items).safe_bounds_margin(100.0);
|
||||
#[allow(clippy::float_cmp)]
|
||||
{
|
||||
assert_eq!(menu_bar.global_parameters.safe_bounds_margin, 100.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_close_on_item_click_sets_value() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items).close_on_item_click(true);
|
||||
assert_eq!(menu_bar.close_on_item_click, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_close_on_background_click_sets_value() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items).close_on_background_click(true);
|
||||
assert_eq!(menu_bar.close_on_background_click, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_close_on_item_click_global_sets_value() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items).close_on_item_click_global(true);
|
||||
assert!(menu_bar.global_parameters.close_on_item_click);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_close_on_background_click_global_sets_value() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items).close_on_background_click_global(true);
|
||||
assert!(menu_bar.global_parameters.close_on_background_click);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_with_multiple_items() {
|
||||
let items = vec![
|
||||
Item::new(Text::new("File")),
|
||||
Item::new(Text::new("Edit")),
|
||||
Item::new(Text::new("View")),
|
||||
Item::new(Text::new("Help")),
|
||||
];
|
||||
|
||||
let menu_bar = TestMenuBar::new(items);
|
||||
assert_eq!(menu_bar.roots.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_chained_configuration() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
|
||||
let menu_bar = TestMenuBar::new(items)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fixed(40.0))
|
||||
.spacing(Pixels(5.0))
|
||||
.padding(Padding::new(10.0))
|
||||
.safe_bounds_margin(75.0)
|
||||
.close_on_item_click(true)
|
||||
.close_on_background_click(true);
|
||||
|
||||
assert_eq!(menu_bar.width, Length::Fill);
|
||||
assert_eq!(menu_bar.height, Length::Fixed(40.0));
|
||||
assert_eq!(menu_bar.spacing, Pixels(5.0));
|
||||
assert_eq!(menu_bar.padding, Padding::new(10.0));
|
||||
#[allow(clippy::float_cmp)]
|
||||
{
|
||||
assert_eq!(menu_bar.global_parameters.safe_bounds_margin, 75.0);
|
||||
}
|
||||
assert_eq!(menu_bar.close_on_item_click, Some(true));
|
||||
assert_eq!(menu_bar.close_on_background_click, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_tag_returns_state_tag() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items);
|
||||
|
||||
let tag = Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::tag(&menu_bar);
|
||||
assert_eq!(tag, tree::Tag::of::<MenuBarState>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_children_returns_item_trees() {
|
||||
let items = vec![Item::new(Text::new("File")), Item::new(Text::new("Edit"))];
|
||||
|
||||
let menu_bar = TestMenuBar::new(items);
|
||||
let children =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::children(&menu_bar);
|
||||
assert_eq!(children.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_size_returns_configured_size() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items)
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fixed(40.0));
|
||||
|
||||
let size =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::size(&menu_bar);
|
||||
assert_eq!(size.width, Length::Fill);
|
||||
assert_eq!(size.height, Length::Fixed(40.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_bar_converts_to_element() {
|
||||
let items = vec![Item::new(Text::new("File"))];
|
||||
let menu_bar = TestMenuBar::new(items);
|
||||
let _element: Element<TestMessage, iced_widget::Theme, iced_widget::Renderer> =
|
||||
menu_bar.into();
|
||||
}
|
||||
}
|
||||
+932
@@ -0,0 +1,932 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
#![allow(clippy::doc_markdown)]
|
||||
#![allow(clippy::wildcard_imports)]
|
||||
#![allow(clippy::enum_glob_use)]
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
#![allow(clippy::items_after_statements)]
|
||||
#![allow(clippy::similar_names)]
|
||||
|
||||
use iced_core::{
|
||||
Clipboard, Event, Layout, Point, Rectangle, Shell, Size, Vector,
|
||||
layout::{Limits, Node},
|
||||
mouse, overlay, renderer,
|
||||
time::Instant,
|
||||
widget::{Operation, Tree},
|
||||
window,
|
||||
};
|
||||
|
||||
use super::{common::*, menu_bar::*, menu_tree::*};
|
||||
use crate::style::{Status, menu_bar::*};
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
use log::{debug, trace, warn};
|
||||
|
||||
pub(super) struct MenuBarOverlay<'a, 'b, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: Catalog,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
pub(super) menu_bar: &'b mut MenuBar<'a, Message, Theme, Renderer>,
|
||||
pub(super) layout: Layout<'b>,
|
||||
pub(super) translation: Vector,
|
||||
/// Tree{ bar, [item_tree...] }
|
||||
pub(super) tree: &'b mut Tree,
|
||||
}
|
||||
impl<'b, Message, Theme, Renderer> MenuBarOverlay<'_, 'b, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: Catalog,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
pub(super) fn overlay_element(self) -> overlay::Element<'b, Message, Theme, Renderer> {
|
||||
overlay::Element::new(Box::new(self))
|
||||
}
|
||||
}
|
||||
impl<Message, Theme, Renderer> overlay::Overlay<Message, Theme, Renderer>
|
||||
for MenuBarOverlay<'_, '_, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: Catalog,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
/// out: Node{inf, [ bar_node, roots_node, menu_nodes_node{0, [ menu_node,...]} ]}
|
||||
fn layout(&mut self, renderer: &Renderer, bounds: Size) -> Node {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::layout", "");
|
||||
let translation = self.translation;
|
||||
|
||||
let bar_bounds = self.layout.bounds();
|
||||
let slice_layout = self.layout.children().next().unwrap();
|
||||
|
||||
let root_bounds = slice_layout
|
||||
.children()
|
||||
.map(|l| l.bounds())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let bar = self.tree.state.downcast_ref::<MenuBarState>();
|
||||
let MenuBarState {
|
||||
global_state,
|
||||
menu_state: bar_menu_state,
|
||||
} = bar;
|
||||
let slice = bar_menu_state.slice;
|
||||
|
||||
let bar_node = Node::with_children(bar_bounds.size(), [].into())
|
||||
.move_to(bar_bounds.position() + translation);
|
||||
|
||||
let roots_node = Node::with_children(
|
||||
Size::ZERO,
|
||||
root_bounds
|
||||
.iter()
|
||||
.map(|r| Node::new(r.size()).move_to(r.position()))
|
||||
.collect(),
|
||||
)
|
||||
.translate(translation);
|
||||
|
||||
if !global_state.open {
|
||||
return Node::with_children(bounds, [bar_node, roots_node].into());
|
||||
}
|
||||
|
||||
let Some(active) = bar_menu_state.active else {
|
||||
return Node::with_children(bounds, [bar_node, roots_node].into());
|
||||
};
|
||||
|
||||
let active_root = &mut self.menu_bar.roots[active];
|
||||
let active_tree = &mut self.tree.children[active]; // item_tree: Tree{ stateless, [ widget_tree, menu_tree ] }
|
||||
let parent_bounds = root_bounds[active - slice.start_index] + translation;
|
||||
|
||||
fn rec<Message, Theme: Catalog, Renderer: renderer::Renderer>(
|
||||
renderer: &Renderer,
|
||||
item: &mut Item<'_, Message, Theme, Renderer>,
|
||||
tree: &mut Tree,
|
||||
menu_nodes: &mut Vec<Node>,
|
||||
parent_bounds: Rectangle,
|
||||
parent_direction: (Direction, Direction),
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
if let Some(menu) = item.menu.as_mut() {
|
||||
let menu_tree = &mut tree.children[1];
|
||||
|
||||
let (menu_node, direction) = menu.layout(
|
||||
menu_tree,
|
||||
renderer,
|
||||
&Limits::NONE,
|
||||
parent_bounds,
|
||||
parent_direction,
|
||||
viewport,
|
||||
);
|
||||
// Node{inf, [ slice_node, items_bounds, offset_bounds]}
|
||||
menu_nodes.push(menu_node);
|
||||
|
||||
let menu_state = menu_tree.state.downcast_ref::<MenuState>();
|
||||
|
||||
if let Some(active) = menu_state.active {
|
||||
let next_item = &mut menu.items[active];
|
||||
let next_tree = &mut menu_tree.children[active];
|
||||
let next_parent_bounds = {
|
||||
let slice_node = &menu_nodes.last().unwrap().children()[0];
|
||||
let active_in_slice = active - menu_state.slice.start_index;
|
||||
let node = &slice_node.children()[active_in_slice];
|
||||
node.bounds() + (slice_node.bounds().position() - Point::ORIGIN)
|
||||
};
|
||||
rec(
|
||||
renderer,
|
||||
next_item,
|
||||
next_tree,
|
||||
menu_nodes,
|
||||
next_parent_bounds,
|
||||
direction,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut menu_nodes = vec![];
|
||||
|
||||
let parent_direction = {
|
||||
let hcenter = bounds.width / 2.0;
|
||||
let vcenter = bounds.height / 2.0;
|
||||
|
||||
let phcenter = parent_bounds.x + parent_bounds.width / 2.0;
|
||||
let pvcenter = parent_bounds.y + parent_bounds.height / 2.0;
|
||||
|
||||
(
|
||||
if phcenter < hcenter {
|
||||
Direction::Positive
|
||||
} else {
|
||||
Direction::Negative
|
||||
},
|
||||
if pvcenter < vcenter {
|
||||
Direction::Positive
|
||||
} else {
|
||||
Direction::Negative
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
rec(
|
||||
renderer,
|
||||
active_root,
|
||||
active_tree,
|
||||
&mut menu_nodes,
|
||||
parent_bounds,
|
||||
parent_direction,
|
||||
&Rectangle::new(Point::ORIGIN, bounds),
|
||||
);
|
||||
|
||||
Node::with_children(
|
||||
bounds,
|
||||
[
|
||||
bar_node,
|
||||
roots_node,
|
||||
Node::with_children(Size::ZERO, menu_nodes),
|
||||
]
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(unused_results)]
|
||||
fn update(
|
||||
&mut self,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::update", "");
|
||||
|
||||
let bar = self.tree.state.downcast_mut::<MenuBarState>();
|
||||
let MenuBarState {
|
||||
global_state,
|
||||
menu_state: bar_menu_state,
|
||||
} = bar;
|
||||
let slice = bar_menu_state.slice;
|
||||
|
||||
if !global_state.open {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(active) = bar_menu_state.active else {
|
||||
return;
|
||||
};
|
||||
|
||||
let viewport = layout.bounds();
|
||||
let mut lc = layout.children();
|
||||
let bar_bounds = lc.next().unwrap().bounds();
|
||||
let roots_layout = lc.next().unwrap();
|
||||
|
||||
let parent_bounds = roots_layout
|
||||
.children()
|
||||
.nth(active - slice.start_index)
|
||||
.unwrap()
|
||||
.bounds();
|
||||
let menu_layouts_layout = lc.next().unwrap(); // Node{0, [menu_node...]}
|
||||
let mut menu_layouts = menu_layouts_layout.children(); // [menu_node...]
|
||||
|
||||
let active_root = &mut self.menu_bar.roots[active];
|
||||
let active_tree = &mut self.tree.children[active];
|
||||
let mut prev_bounds_list = vec![bar_bounds];
|
||||
|
||||
match event {
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
|
||||
global_state.pressed = true;
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
|
||||
global_state.pressed = false;
|
||||
shell.request_redraw();
|
||||
}
|
||||
Event::Window(window::Event::Resized { .. }) => {
|
||||
bar.close(self.tree.children.as_mut_slice(), shell);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
#[rustfmt::skip]
|
||||
fn rec<'a, 'b, Message, Theme: Catalog, Renderer: renderer::Renderer>(
|
||||
global_state: &mut GlobalState,
|
||||
global_parameters: &GlobalParameters<'a, Theme>,
|
||||
tree: &mut Tree,
|
||||
item: &mut Item<'a, Message, Theme, Renderer>,
|
||||
event: &Event,
|
||||
layout_iter: &mut impl Iterator<Item = Layout<'b>>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
parent_bounds: Rectangle,
|
||||
viewport: &Rectangle,
|
||||
prev_bounds_list: &mut Vec<Rectangle>,
|
||||
prev_active: &mut Index,
|
||||
) -> RecEvent {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::update", "rec");
|
||||
|
||||
let Some(menu) = item.menu.as_mut() else {
|
||||
return RecEvent::Close;
|
||||
};
|
||||
let menu_tree = &mut tree.children[1];
|
||||
|
||||
let Some(menu_layout) = layout_iter.next() else {
|
||||
return RecEvent::Close;
|
||||
}; // menu_node: Node{inf, [ slice_node, items_bounds, offset_bounds]}
|
||||
|
||||
let mut mc = menu_layout.children();
|
||||
let slice_layout = mc.next().unwrap(); // slice_node
|
||||
let items_bounds = mc.next().unwrap().bounds();
|
||||
let background_bounds = pad_rectangle(items_bounds, menu.padding);
|
||||
|
||||
prev_bounds_list.push(background_bounds);
|
||||
|
||||
let menu_state = menu_tree.state.downcast_mut::<MenuState>();
|
||||
|
||||
let rec_event = if let Some(active) = menu_state.active {
|
||||
let next_tree = &mut menu_tree.children[active];
|
||||
let next_item = &mut menu.items[active];
|
||||
let active_in_slice = active - menu_state.slice.start_index;
|
||||
let next_parent_bounds = slice_layout
|
||||
.children()
|
||||
.nth(active_in_slice)
|
||||
.expect(
|
||||
"Index (in slice space) is not within the slice layout. \
|
||||
This should not happen, please report this issue"
|
||||
)
|
||||
.bounds();
|
||||
|
||||
rec(
|
||||
global_state,
|
||||
global_parameters,
|
||||
next_tree,
|
||||
next_item,
|
||||
event,
|
||||
layout_iter,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
next_parent_bounds,
|
||||
viewport,
|
||||
prev_bounds_list,
|
||||
&mut menu_state.active,
|
||||
)
|
||||
} else if cursor == mouse::Cursor::Unavailable{
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::update", "rec | cursor is unavailable");
|
||||
RecEvent::Event
|
||||
} else {
|
||||
RecEvent::Close
|
||||
};
|
||||
|
||||
prev_bounds_list.pop();
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
{
|
||||
debug!(target:"menu::MenuBarOverlay::update", "");
|
||||
debug!(target:"menu::MenuBarOverlay::update", "menu_state.active: {:?}", menu_state.active);
|
||||
debug!(target:"menu::MenuBarOverlay::update", "menu_state.slice: {:?}", menu_state.slice);
|
||||
debug!(target:"menu::MenuBarOverlay::update", "rec_event: {rec_event:?}");
|
||||
debug!(target:"menu::MenuBarOverlay::update", "event: {event:?}");
|
||||
debug!(target:"menu::MenuBarOverlay::update", "cursor: {cursor:?}");
|
||||
debug!(target:"menu::MenuBarOverlay::update", "cursor is over background bounds: {:?}", cursor.is_over(background_bounds));
|
||||
debug!(target:"menu::MenuBarOverlay::update", "shell.is_event_captured(): {:?}", shell.is_event_captured());
|
||||
}
|
||||
|
||||
menu.update(
|
||||
global_state,
|
||||
global_parameters,
|
||||
rec_event,
|
||||
menu_tree,
|
||||
event,
|
||||
menu_layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
parent_bounds,
|
||||
prev_bounds_list,
|
||||
prev_active,
|
||||
)
|
||||
}
|
||||
|
||||
let re = rec(
|
||||
global_state,
|
||||
&self.menu_bar.global_parameters,
|
||||
active_tree,
|
||||
active_root,
|
||||
event,
|
||||
&mut menu_layouts,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
parent_bounds,
|
||||
&viewport,
|
||||
&mut prev_bounds_list,
|
||||
&mut bar_menu_state.active,
|
||||
);
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::update", "re: {re:?}");
|
||||
|
||||
if matches!(
|
||||
event,
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
|
||||
) && matches!(global_state.task(), Some(MenuBarTask::CloseOnClick))
|
||||
{
|
||||
bar.close(self.tree.children.as_mut_slice(), shell);
|
||||
return;
|
||||
}
|
||||
|
||||
match re {
|
||||
RecEvent::Event => {
|
||||
let redraw_event = Event::Window(window::Event::RedrawRequested(Instant::now()));
|
||||
let mut fake_messages = vec![];
|
||||
let mut fake_shell = Shell::new(&mut fake_messages);
|
||||
|
||||
let Self {
|
||||
menu_bar,
|
||||
layout,
|
||||
tree,
|
||||
..
|
||||
} = self;
|
||||
let draw_path = menu_bar.global_parameters.draw_path;
|
||||
let cursor = match draw_path {
|
||||
DrawPath::FakeHovering => {
|
||||
let center = parent_bounds.center();
|
||||
mouse::Cursor::Available(center - self.translation)
|
||||
}
|
||||
DrawPath::Backdrop => mouse::Cursor::Unavailable,
|
||||
};
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::update", "calling update_items() on MenuBar");
|
||||
let slice_layout = layout.children().next().unwrap();
|
||||
itl_iter_slice!(
|
||||
slice,
|
||||
menu_bar.roots;iter_mut,
|
||||
tree.children;iter_mut,
|
||||
slice_layout.children()
|
||||
)
|
||||
.for_each(|((item, tree), layout)| {
|
||||
item.update(
|
||||
tree,
|
||||
&redraw_event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
&mut fake_shell,
|
||||
&viewport,
|
||||
);
|
||||
});
|
||||
}
|
||||
RecEvent::Close => {
|
||||
if !cursor.is_over(bar_bounds) {
|
||||
bar.close(self.tree.children.as_mut_slice(), shell);
|
||||
}
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::update", "RecEvent::Close | MenuBar should process the event");
|
||||
|
||||
assert!(
|
||||
!shell.is_event_captured(),
|
||||
"MenuBarOverlay::update() | RecEvent::Close | Returning"
|
||||
);
|
||||
// let the menu bar process the event
|
||||
}
|
||||
RecEvent::None => {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::update", "RecEvent::None | MenuBar should process the event");
|
||||
|
||||
assert!(
|
||||
!shell.is_event_captured(),
|
||||
"MenuBarOverlay::update() | RecEvent::None | Returning"
|
||||
);
|
||||
// let the menu bar process the event
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::update", "returning | shell.is_layout_invalid(): {:?}", shell.is_layout_invalid());
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::mouse_interaction", "");
|
||||
|
||||
let bar = self.tree.state.downcast_ref::<MenuBarState>();
|
||||
let MenuBarState {
|
||||
global_state,
|
||||
menu_state: bar_menu_state,
|
||||
} = bar;
|
||||
|
||||
if !global_state.open {
|
||||
return mouse::Interaction::default();
|
||||
}
|
||||
|
||||
let Some(active) = bar_menu_state.active else {
|
||||
return mouse::Interaction::default();
|
||||
};
|
||||
|
||||
// let viewport = layout.bounds();
|
||||
let mut lc = layout.children();
|
||||
let _bar_bounds = lc.next().unwrap().bounds();
|
||||
let _roots_layout = lc.next().unwrap();
|
||||
|
||||
// let parent_bounds = roots_layout.children().nth(active).unwrap().bounds();
|
||||
let menu_layouts_layout = lc.next().unwrap(); // Node{0, [menu_node...]}
|
||||
let mut menu_layouts = menu_layouts_layout.children(); // [menu_node...]
|
||||
|
||||
let active_root = &self.menu_bar.roots[active];
|
||||
let active_tree = &self.tree.children[active];
|
||||
|
||||
fn rec<'a, 'b, Message, Theme: Catalog, Renderer: renderer::Renderer>(
|
||||
tree: &Tree,
|
||||
item: &Item<'a, Message, Theme, Renderer>,
|
||||
layout_iter: &mut impl Iterator<Item = Layout<'b>>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
let Some(menu) = item.menu.as_ref() else {
|
||||
return mouse::Interaction::default();
|
||||
};
|
||||
let menu_tree = &tree.children[1];
|
||||
|
||||
let Some(menu_layout) = layout_iter.next() else {
|
||||
#[cfg(feature = "debug_log")]
|
||||
warn!(target:"menu::MenuBarOverlay::mouse_interaction", "menu exists, but menu_layout is None");
|
||||
return mouse::Interaction::default();
|
||||
}; // menu_node: Node{inf, [ slice_node, items_bounds, offset_bounds]}
|
||||
|
||||
let menu_state = menu_tree.state.downcast_ref::<MenuState>();
|
||||
|
||||
let i = menu.mouse_interaction(menu_tree, menu_layout, cursor, renderer);
|
||||
|
||||
menu_state.active.map_or(i, |active| {
|
||||
let next_tree = &menu_tree.children[active];
|
||||
let next_item = &menu.items[active];
|
||||
rec(next_tree, next_item, layout_iter, cursor, renderer).max(i)
|
||||
})
|
||||
}
|
||||
|
||||
rec(
|
||||
active_tree,
|
||||
active_root,
|
||||
&mut menu_layouts,
|
||||
cursor,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::operate", "");
|
||||
|
||||
let bar = self.tree.state.downcast_ref::<MenuBarState>();
|
||||
let MenuBarState {
|
||||
global_state,
|
||||
menu_state: bar_menu_state,
|
||||
} = bar;
|
||||
|
||||
if !global_state.open {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(active) = bar_menu_state.active else {
|
||||
return;
|
||||
};
|
||||
|
||||
// let viewport = layout.bounds();
|
||||
let mut lc = layout.children();
|
||||
let _bar_bounds = lc.next().unwrap().bounds();
|
||||
let _roots_layout = lc.next().unwrap();
|
||||
|
||||
// let parent_bounds = roots_layout.children().nth(active).unwrap().bounds();
|
||||
let menu_layouts_layout = lc.next().unwrap(); // Node{0, [menu_node...]}
|
||||
let mut menu_layouts = menu_layouts_layout.children(); // [menu_node...]
|
||||
|
||||
let active_root = &mut self.menu_bar.roots[active];
|
||||
let active_tree = &mut self.tree.children[active];
|
||||
|
||||
fn rec<'a, 'b, Message, Theme: Catalog, Renderer: renderer::Renderer>(
|
||||
tree: &mut Tree,
|
||||
item: &mut Item<'a, Message, Theme, Renderer>,
|
||||
layout_iter: &mut impl Iterator<Item = Layout<'b>>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
let Some(menu) = item.menu.as_mut() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let menu_tree = &mut tree.children[1];
|
||||
|
||||
let Some(menu_layout) = layout_iter.next() else {
|
||||
#[cfg(feature = "debug_log")]
|
||||
warn!(target:"menu::MenuBarOverlay::operate", "menu exists, but menu_layout is None");
|
||||
return;
|
||||
};
|
||||
|
||||
menu.operate(menu_tree, menu_layout, renderer, operation);
|
||||
|
||||
operation.container(None, menu_layout.bounds());
|
||||
operation.traverse(&mut |operation| {
|
||||
menu.items
|
||||
.iter_mut() // [Item...]
|
||||
.zip(menu_tree.children.iter_mut()) // [item_tree...] // [widget_node...]
|
||||
.for_each(|(child, state)| {
|
||||
rec(state, child, layout_iter, renderer, operation);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
rec(
|
||||
active_tree,
|
||||
active_root,
|
||||
&mut menu_layouts,
|
||||
renderer,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
|
||||
fn overlay<'c>(
|
||||
&'c mut self,
|
||||
layout: Layout<'c>,
|
||||
renderer: &Renderer,
|
||||
) -> Option<overlay::Element<'c, Message, Theme, Renderer>> {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "");
|
||||
|
||||
let Tree {
|
||||
state,
|
||||
children: item_trees,
|
||||
..
|
||||
} = self.tree;
|
||||
let bar = state.downcast_ref::<MenuBarState>();
|
||||
let MenuBarState {
|
||||
global_state,
|
||||
menu_state: bar_menu_state,
|
||||
} = bar;
|
||||
let slice = bar_menu_state.slice;
|
||||
|
||||
if !global_state.open {
|
||||
return None;
|
||||
}
|
||||
|
||||
let active = bar_menu_state.active?;
|
||||
|
||||
let mut lc = layout.children();
|
||||
let viewport = layout.bounds();
|
||||
let _bar_bounds = lc.next()?.bounds();
|
||||
let _roots_layout = lc.next()?;
|
||||
let menu_layouts_layout = lc.next()?; // Node{0, [menu_node...]}
|
||||
let mut menu_layouts = menu_layouts_layout.children(); // [menu_node...]
|
||||
|
||||
fn rec<'a, 'b, Message, Theme: Catalog, Renderer: renderer::Renderer>(
|
||||
items: &'b mut [Item<'a, Message, Theme, Renderer>],
|
||||
menu_tree: &'b mut Tree, // Tree{ menu_state, [item_tree...] }
|
||||
menu_layouts: &mut impl Iterator<Item = Layout<'b>>, // [menu_node...]
|
||||
overlays: &mut Vec<overlay::Element<'b, Message, Theme, Renderer>>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "rec");
|
||||
|
||||
let menu_state = menu_tree.state.downcast_mut::<MenuState>();
|
||||
let menu_layout = menu_layouts.next().unwrap(); // menu_node: Node{inf, [ slice_node, items_bounds, offset_bounds]}
|
||||
let mut mlc = menu_layout.children();
|
||||
let slice_layout = mlc.next().unwrap(); // slice_node: Node{inf, [item_node...]}
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "rec | slice_layout.children : {}", slice_layout.children().count());
|
||||
|
||||
let slice = menu_state.slice;
|
||||
|
||||
if let Some(active) = menu_state.active {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "rec | active");
|
||||
|
||||
let mut next = None;
|
||||
|
||||
for (i, ((item, item_tree), item_layout)) in itl_iter_slice_enum!(
|
||||
slice,
|
||||
items;iter_mut,
|
||||
menu_tree.children;iter_mut,
|
||||
slice_layout.children()
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
trace!(target:"menu::MenuBarOverlay::overlay", "rec | i: {i}");
|
||||
|
||||
let Item {
|
||||
item: item_widget,
|
||||
menu: item_menu,
|
||||
..
|
||||
} = item;
|
||||
|
||||
let item_widget_tree = if i == active {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "rec | i == active {active}");
|
||||
let [item_widget_tree, item_menu_tree] = item_tree.children.as_mut_slice()
|
||||
else {
|
||||
#[cfg(feature = "debug_log")]
|
||||
warn!(target:"menu::MenuBarOverlay::overlay", "rec | menu_state.active is Some, but there's no state tree for it");
|
||||
continue;
|
||||
};
|
||||
next = Some((item_menu.as_mut().unwrap(), item_menu_tree));
|
||||
item_widget_tree
|
||||
} else {
|
||||
&mut item_tree.children.as_mut_slice()[0]
|
||||
};
|
||||
|
||||
if let Some(overlay) = item_widget.as_widget_mut().overlay(
|
||||
item_widget_tree,
|
||||
item_layout,
|
||||
renderer,
|
||||
viewport,
|
||||
Vector::ZERO,
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "rec | active | i: {i} | Some overlay");
|
||||
overlays.push(overlay);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((next_menu, next_menu_tree)) = next {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "rec | next");
|
||||
rec(
|
||||
&mut next_menu.items,
|
||||
next_menu_tree,
|
||||
menu_layouts,
|
||||
overlays,
|
||||
renderer,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "rec | no active");
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
let mut count = slice.start_index;
|
||||
|
||||
for ((item, item_tree), item_layout) in itl_iter_slice!(
|
||||
slice,
|
||||
items;iter_mut,
|
||||
menu_tree.children;iter_mut,
|
||||
slice_layout.children()
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
trace!(target:"menu::MenuBarOverlay::overlay", "rec | i: {count}");
|
||||
|
||||
let Item {
|
||||
item: item_widget, ..
|
||||
} = item;
|
||||
|
||||
if let Some(overlay) = item_widget.as_widget_mut().overlay(
|
||||
&mut item_tree.children[0],
|
||||
item_layout,
|
||||
renderer,
|
||||
viewport,
|
||||
Vector::ZERO,
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "rec | no active | i: {count} | Some overlay");
|
||||
overlays.push(overlay);
|
||||
}
|
||||
|
||||
#[cfg(feature = "debug_log")]
|
||||
{
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut overlays = vec![];
|
||||
let mut next = None;
|
||||
|
||||
let slice_layout = self.layout.children().next()?;
|
||||
|
||||
for (i, ((item, item_tree), item_layout)) in itl_iter_slice_enum!(
|
||||
slice,
|
||||
self.menu_bar.roots;iter_mut,
|
||||
item_trees;iter_mut,
|
||||
slice_layout.children()
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
trace!(target:"menu::MenuBarOverlay::overlay", "root | i: {i}");
|
||||
|
||||
let Item {
|
||||
item: item_widget,
|
||||
menu: item_menu,
|
||||
..
|
||||
} = item;
|
||||
let [item_widget_tree, item_menu_tree] = item_tree.children.as_mut_slice() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if i == active
|
||||
&& let Some(menu) = item_menu.as_mut()
|
||||
{
|
||||
next = Some((menu, item_menu_tree));
|
||||
}
|
||||
if let Some(overlay) = item_widget.as_widget_mut().overlay(
|
||||
item_widget_tree,
|
||||
item_layout,
|
||||
renderer,
|
||||
&viewport,
|
||||
self.translation,
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "root | i: {i} | Some overlay");
|
||||
overlays.push(overlay);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((next_menu, next_menu_tree)) = next {
|
||||
rec(
|
||||
&mut next_menu.items,
|
||||
next_menu_tree,
|
||||
&mut menu_layouts,
|
||||
&mut overlays,
|
||||
renderer,
|
||||
&viewport,
|
||||
);
|
||||
}
|
||||
|
||||
if overlays.is_empty() {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "return | None");
|
||||
None
|
||||
} else {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::overlay", "return | Some");
|
||||
Some(overlay::Group::with_children(overlays).overlay())
|
||||
}
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
) {
|
||||
#[cfg(feature = "debug_log")]
|
||||
debug!(target:"menu::MenuBarOverlay::draw", "");
|
||||
|
||||
let bar = self.tree.state.downcast_ref::<MenuBarState>();
|
||||
let MenuBarState {
|
||||
global_state,
|
||||
menu_state: bar_menu_state,
|
||||
} = bar;
|
||||
|
||||
if !global_state.open {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(active) = bar_menu_state.active else {
|
||||
return;
|
||||
};
|
||||
|
||||
let viewport = layout.bounds();
|
||||
let mut lc = layout.children();
|
||||
let _bar_bounds = lc.next().unwrap().bounds();
|
||||
let _roots_layout = lc.next().unwrap();
|
||||
|
||||
// let parent_bounds = roots_layout.children().nth(active).unwrap().bounds();
|
||||
let menu_layouts_layout = lc.next().unwrap(); // Node{0, [menu_node...]}
|
||||
let mut menu_layouts = menu_layouts_layout.children(); // [menu_node...]
|
||||
|
||||
let active_root = &self.menu_bar.roots[active];
|
||||
let active_tree = &self.tree.children[active];
|
||||
|
||||
fn rec<'a, 'b, Message, Theme: Catalog, Renderer: renderer::Renderer>(
|
||||
global_parameters: &GlobalParameters<'a, Theme>,
|
||||
tree: &Tree,
|
||||
item: &Item<'a, Message, Theme, Renderer>,
|
||||
layout_iter: &mut impl Iterator<Item = Layout<'b>>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
theme_style: &Style,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let Some(menu) = item.menu.as_ref() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let menu_tree = &tree.children[1];
|
||||
|
||||
let Some(menu_layout) = layout_iter.next() else {
|
||||
#[cfg(feature = "debug_log")]
|
||||
warn!(target:"menu::MenuBarOverlay::draw", "menu exists, but menu_layout is None");
|
||||
return;
|
||||
}; // menu_node: Node{inf, [ slice_node, items_bounds, offset_bounds]}
|
||||
|
||||
let menu_state = menu_tree.state.downcast_ref::<MenuState>();
|
||||
|
||||
menu.draw(
|
||||
&global_parameters.draw_path,
|
||||
menu_tree,
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
theme_style,
|
||||
menu_layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
|
||||
if let Some(active) = menu_state.active {
|
||||
let next_tree = &menu_tree.children[active];
|
||||
let next_item = &menu.items[active];
|
||||
|
||||
renderer.with_layer(*viewport, |r| {
|
||||
rec(
|
||||
global_parameters,
|
||||
next_tree,
|
||||
next_item,
|
||||
layout_iter,
|
||||
cursor,
|
||||
r,
|
||||
theme,
|
||||
style,
|
||||
theme_style,
|
||||
viewport,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let theme_style = theme.style(&self.menu_bar.global_parameters.class, Status::Active);
|
||||
|
||||
rec(
|
||||
&self.menu_bar.global_parameters,
|
||||
active_tree,
|
||||
active_root,
|
||||
&mut menu_layouts,
|
||||
cursor,
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
&theme_style,
|
||||
&viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
+1202
File diff suppressed because it is too large.
Load diff
+1454
File diff suppressed because it is too large.
Load diff
+2426
File diff suppressed because it is too large.
Load diff
+433
@@ -0,0 +1,433 @@
|
||||
//! A modal for showing elements as an overlay on top of another.
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: ``context_menu``*
|
||||
use crate::context_menu;
|
||||
pub use crate::style::{
|
||||
context_menu::{Catalog, Style},
|
||||
status::{self, StyleFn},
|
||||
};
|
||||
|
||||
use iced_core::{
|
||||
Border, Clipboard, Color, Element, Event, Layout, Point, Shell, Size, keyboard,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
overlay, renderer, touch,
|
||||
widget::Tree,
|
||||
window,
|
||||
};
|
||||
|
||||
/// The overlay of the [`ContextMenu`](crate::widget::ContextMenu).
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct ContextMenuOverlay<
|
||||
'a,
|
||||
'b,
|
||||
Message,
|
||||
Theme = iced_widget::Theme,
|
||||
Renderer = iced_widget::Renderer,
|
||||
> where
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
Theme: Catalog,
|
||||
'b: 'a,
|
||||
{
|
||||
// The position of the element
|
||||
position: Point,
|
||||
/// The state of the [`ContextMenuOverlay`].
|
||||
tree: &'a mut Tree,
|
||||
/// The content of the [`ContextMenuOverlay`].
|
||||
content: &'a mut Element<'b, Message, Theme, Renderer>,
|
||||
/// The style of the [`ContextMenuOverlay`].
|
||||
class: &'a Theme::Class<'b>,
|
||||
/// The state shared between [`ContextMenu`](crate::widget::ContextMenu) and [`ContextMenuOverlay`].
|
||||
state: &'a mut context_menu::State,
|
||||
}
|
||||
|
||||
impl<'a, 'b, Message, Theme, Renderer> ContextMenuOverlay<'a, 'b, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone,
|
||||
Renderer: renderer::Renderer,
|
||||
Theme: 'a + Catalog,
|
||||
'b: 'a,
|
||||
{
|
||||
/// Creates a new [`ContextMenuOverlay`].
|
||||
pub(crate) fn new(
|
||||
position: Point,
|
||||
tree: &'a mut Tree,
|
||||
content: &'a mut Element<'b, Message, Theme, Renderer>,
|
||||
class: &'a <Theme as Catalog>::Class<'b>,
|
||||
state: &'a mut context_menu::State,
|
||||
) -> Self {
|
||||
ContextMenuOverlay {
|
||||
position,
|
||||
tree,
|
||||
content,
|
||||
class,
|
||||
state,
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn this [`ContextMenuOverlay`] into an overlay [`Element`](overlay::Element).
|
||||
#[must_use]
|
||||
pub fn overlay(self) -> overlay::Element<'a, Message, Theme, Renderer> {
|
||||
overlay::Element::new(Box::new(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'b, Message, Theme, Renderer> overlay::Overlay<Message, Theme, Renderer>
|
||||
for ContextMenuOverlay<'a, 'b, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
Theme: 'a + Catalog,
|
||||
'b: 'a,
|
||||
{
|
||||
fn layout(&mut self, renderer: &Renderer, bounds: Size) -> Node {
|
||||
let limits = Limits::new(Size::ZERO, bounds);
|
||||
let max_size = limits.max();
|
||||
|
||||
let mut content = self
|
||||
.content
|
||||
.as_widget_mut()
|
||||
.layout(self.tree, renderer, &limits);
|
||||
|
||||
// Try to stay inside borders
|
||||
let mut position = self.position;
|
||||
if position.x + content.size().width > bounds.width {
|
||||
position.x = f32::max(0.0, position.x - content.size().width);
|
||||
}
|
||||
if position.y + content.size().height > bounds.height {
|
||||
position.y = f32::max(0.0, position.y - content.size().height);
|
||||
}
|
||||
|
||||
content.move_to_mut(position);
|
||||
|
||||
Node::with_children(max_size, vec![content])
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
) {
|
||||
let bounds = layout.bounds();
|
||||
|
||||
let style_sheet = theme.style(self.class, status::Status::Active);
|
||||
|
||||
// Background
|
||||
|
||||
let content_layout = layout
|
||||
.children()
|
||||
.next()
|
||||
.expect("widget: Layout should have a content layout.");
|
||||
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: content_layout.bounds(),
|
||||
border: Border {
|
||||
radius: (0.0).into(),
|
||||
width: 0.0,
|
||||
color: Color::TRANSPARENT,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
style_sheet.background,
|
||||
);
|
||||
|
||||
// Modal
|
||||
self.content.as_widget().draw(
|
||||
self.tree,
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
content_layout,
|
||||
cursor,
|
||||
&bounds,
|
||||
);
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: iced_core::mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
) {
|
||||
let layout_children = layout
|
||||
.children()
|
||||
.next()
|
||||
.expect("widget: Layout should have a content layout.");
|
||||
|
||||
let mut forward_event_to_children = true;
|
||||
let mut capture_event = false;
|
||||
|
||||
match &event {
|
||||
Event::Keyboard(keyboard::Event::KeyPressed { key, .. })
|
||||
if *key == keyboard::Key::Named(keyboard::key::Named::Escape) =>
|
||||
{
|
||||
self.state.show = false;
|
||||
forward_event_to_children = false;
|
||||
shell.capture_event();
|
||||
shell.request_redraw();
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonPressed(
|
||||
mouse::Button::Left | mouse::Button::Right,
|
||||
))
|
||||
| Event::Touch(touch::Event::FingerPressed { .. }) => {
|
||||
if cursor.is_over(layout_children.bounds()) {
|
||||
capture_event = true;
|
||||
} else {
|
||||
self.state.show = false;
|
||||
forward_event_to_children = false;
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
|
||||
// close when released because because button send message on release
|
||||
self.state.show = false;
|
||||
|
||||
capture_event = true;
|
||||
shell.request_redraw();
|
||||
}
|
||||
|
||||
Event::Window(window::Event::Resized { .. }) => {
|
||||
self.state.show = false;
|
||||
forward_event_to_children = false;
|
||||
capture_event = true;
|
||||
shell.request_redraw();
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if forward_event_to_children {
|
||||
self.content.as_widget_mut().update(
|
||||
self.tree,
|
||||
event,
|
||||
layout_children,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
&layout.bounds(),
|
||||
);
|
||||
}
|
||||
if capture_event {
|
||||
shell.capture_event();
|
||||
}
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn iced_core::widget::Operation,
|
||||
) {
|
||||
let content_layout = layout
|
||||
.children()
|
||||
.next()
|
||||
.expect("widget: Layout should have a content layout.");
|
||||
|
||||
self.content
|
||||
.as_widget_mut()
|
||||
.operate(self.tree, content_layout, renderer, operation);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
layout: Layout<'_>,
|
||||
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
let bounds = layout.bounds();
|
||||
|
||||
self.content.as_widget().mouse_interaction(
|
||||
self.tree,
|
||||
layout
|
||||
.children()
|
||||
.next()
|
||||
.expect("widget: Layout should have a content layout."),
|
||||
cursor,
|
||||
&bounds,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use iced_core::Point;
|
||||
use iced_widget::text::Text;
|
||||
|
||||
#[derive(Clone)]
|
||||
enum TestMessage {}
|
||||
|
||||
fn create_test_tree() -> Tree {
|
||||
Tree::empty()
|
||||
}
|
||||
|
||||
fn create_test_content()
|
||||
-> Element<'static, TestMessage, iced_widget::Theme, iced_widget::Renderer> {
|
||||
Text::new("Test content").into()
|
||||
}
|
||||
|
||||
fn create_test_state() -> crate::context_menu::State {
|
||||
crate::context_menu::State::new()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_overlay_new_creates_instance() {
|
||||
// Test basic creation of overlay
|
||||
let mut tree = create_test_tree();
|
||||
let mut content = create_test_content();
|
||||
let class = &<iced_widget::Theme as Catalog>::default();
|
||||
let mut state = create_test_state();
|
||||
let position = Point::new(100.0, 100.0);
|
||||
|
||||
let overlay = ContextMenuOverlay::new(position, &mut tree, &mut content, class, &mut state);
|
||||
|
||||
assert_eq!(overlay.position, position);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_overlay_creates_with_different_positions() {
|
||||
// Test overlay creation with various positions
|
||||
let mut tree1 = create_test_tree();
|
||||
let mut tree2 = create_test_tree();
|
||||
let mut tree3 = create_test_tree();
|
||||
let mut content1 = create_test_content();
|
||||
let mut content2 = create_test_content();
|
||||
let mut content3 = create_test_content();
|
||||
let class = &<iced_widget::Theme as Catalog>::default();
|
||||
let mut state1 = create_test_state();
|
||||
let mut state2 = create_test_state();
|
||||
let mut state3 = create_test_state();
|
||||
|
||||
let overlay1 =
|
||||
ContextMenuOverlay::new(Point::ORIGIN, &mut tree1, &mut content1, class, &mut state1);
|
||||
let overlay2 = ContextMenuOverlay::new(
|
||||
Point::new(500.0, 300.0),
|
||||
&mut tree2,
|
||||
&mut content2,
|
||||
class,
|
||||
&mut state2,
|
||||
);
|
||||
let overlay3 = ContextMenuOverlay::new(
|
||||
Point::new(1000.0, 800.0),
|
||||
&mut tree3,
|
||||
&mut content3,
|
||||
class,
|
||||
&mut state3,
|
||||
);
|
||||
|
||||
assert_eq!(overlay1.position, Point::ORIGIN);
|
||||
assert_eq!(overlay2.position, Point::new(500.0, 300.0));
|
||||
assert_eq!(overlay3.position, Point::new(1000.0, 800.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_overlay_converts_to_overlay_element() {
|
||||
// Test conversion to overlay::Element
|
||||
let mut tree = create_test_tree();
|
||||
let mut content = create_test_content();
|
||||
let class = &<iced_widget::Theme as Catalog>::default();
|
||||
let mut state = create_test_state();
|
||||
let position = Point::new(100.0, 100.0);
|
||||
|
||||
let overlay = ContextMenuOverlay::new(position, &mut tree, &mut content, class, &mut state);
|
||||
let _overlay_element = overlay.overlay();
|
||||
|
||||
// If we get here without panic, the conversion worked
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_overlay_state_can_be_shown() {
|
||||
// Test that state can be set to shown
|
||||
let mut state = create_test_state();
|
||||
assert!(!state.show);
|
||||
|
||||
state.show = true;
|
||||
assert!(state.show);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_overlay_state_can_be_hidden() {
|
||||
// Test that state can be set to hidden
|
||||
let mut state = create_test_state();
|
||||
state.show = true;
|
||||
assert!(state.show);
|
||||
|
||||
state.show = false;
|
||||
assert!(!state.show);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_overlay_state_tracks_cursor_position() {
|
||||
// Test that state can track cursor position for overlay placement
|
||||
let mut state = create_test_state();
|
||||
assert_eq!(state.cursor_position, Point::ORIGIN);
|
||||
|
||||
state.cursor_position = Point::new(123.4, 567.8);
|
||||
assert_eq!(state.cursor_position.x, 123.4);
|
||||
assert_eq!(state.cursor_position.y, 567.8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_overlay_state_show_and_position_update_together() {
|
||||
// Test that state can track both show status and cursor position
|
||||
// This simulates what happens during a right-click event
|
||||
let mut state = create_test_state();
|
||||
assert!(!state.show);
|
||||
assert_eq!(state.cursor_position, Point::ORIGIN);
|
||||
|
||||
// Simulate showing the overlay at a specific position
|
||||
state.show = true;
|
||||
state.cursor_position = Point::new(200.0, 300.0);
|
||||
|
||||
assert!(state.show);
|
||||
assert_eq!(state.cursor_position, Point::new(200.0, 300.0));
|
||||
|
||||
// Simulate hiding the overlay (position stays the same)
|
||||
state.show = false;
|
||||
assert!(!state.show);
|
||||
assert_eq!(state.cursor_position, Point::new(200.0, 300.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_overlay_position_can_be_negative() {
|
||||
// Test that overlay can be positioned with negative coordinates
|
||||
// (Though layout() will adjust it, the initial position can be negative)
|
||||
let mut tree = create_test_tree();
|
||||
let mut content = create_test_content();
|
||||
let class = &<iced_widget::Theme as Catalog>::default();
|
||||
let mut state = create_test_state();
|
||||
let position = Point::new(-50.0, -100.0);
|
||||
|
||||
let overlay = ContextMenuOverlay::new(position, &mut tree, &mut content, class, &mut state);
|
||||
|
||||
assert_eq!(overlay.position.x, -50.0);
|
||||
assert_eq!(overlay.position.y, -100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_menu_overlay_position_accuracy() {
|
||||
// Test that position is stored with floating-point precision
|
||||
let mut tree = create_test_tree();
|
||||
let mut content = create_test_content();
|
||||
let class = &<iced_widget::Theme as Catalog>::default();
|
||||
let mut state = create_test_state();
|
||||
let position = Point::new(123.456, 789.012);
|
||||
|
||||
let overlay = ContextMenuOverlay::new(position, &mut tree, &mut content, class, &mut state);
|
||||
|
||||
assert_eq!(overlay.position.x, 123.456);
|
||||
assert_eq!(overlay.position.y, 789.012);
|
||||
}
|
||||
}
|
||||
+1577
File diff suppressed because it is too large.
Load diff
+21
@@ -0,0 +1,21 @@
|
||||
//! Display interactive elements on top of other widget.
|
||||
|
||||
#[cfg(feature = "color_picker")]
|
||||
pub mod color_picker;
|
||||
#[cfg(feature = "color_picker")]
|
||||
pub use color_picker::ColorPickerOverlay;
|
||||
|
||||
#[cfg(feature = "date_picker")]
|
||||
pub mod date_picker;
|
||||
#[cfg(feature = "date_picker")]
|
||||
pub use date_picker::DatePickerOverlay;
|
||||
|
||||
#[cfg(feature = "time_picker")]
|
||||
pub mod time_picker;
|
||||
#[cfg(feature = "time_picker")]
|
||||
pub use time_picker::{State, TimePickerOverlay};
|
||||
|
||||
#[cfg(feature = "context_menu")]
|
||||
pub mod context_menu;
|
||||
#[cfg(feature = "context_menu")]
|
||||
pub use context_menu::ContextMenuOverlay;
|
||||
+2372
File diff suppressed because it is too large.
Load diff
Vendored
+122
@@ -0,0 +1,122 @@
|
||||
//! A dummy widget that draws a quad
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: `quad`*
|
||||
|
||||
use crate::widget::InnerBounds;
|
||||
use iced_core::{
|
||||
Background, Border, Color, Element, Layout, Length, Rectangle, Shadow, Size, Widget,
|
||||
layout::{Limits, Node},
|
||||
mouse::Cursor,
|
||||
renderer,
|
||||
widget::Tree,
|
||||
};
|
||||
|
||||
/// A dummy widget that draws a quad
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct Quad {
|
||||
/// Width of the quad
|
||||
pub width: Length,
|
||||
/// Height of the quad
|
||||
pub height: Length,
|
||||
|
||||
/// Methods for creating inner bounds
|
||||
pub inner_bounds: InnerBounds,
|
||||
|
||||
/// Color of the quad
|
||||
pub quad_color: Background,
|
||||
/// Border of the quad
|
||||
pub quad_border: Border,
|
||||
/// Shadow of the quad
|
||||
pub quad_shadow: Shadow,
|
||||
|
||||
/// Background color of the quad
|
||||
pub bg_color: Option<Background>,
|
||||
/// Border of the background
|
||||
pub bg_border: Border,
|
||||
/// Shadow of the background
|
||||
pub bg_shadow: Shadow,
|
||||
}
|
||||
impl Default for Quad {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
width: Length::Fill,
|
||||
height: Length::Fill,
|
||||
inner_bounds: InnerBounds::Ratio(0.5, 0.5),
|
||||
|
||||
quad_color: Color::from([0.5; 3]).into(),
|
||||
quad_border: Border {
|
||||
color: Color::TRANSPARENT,
|
||||
width: 0.0,
|
||||
radius: 0.0.into(),
|
||||
},
|
||||
quad_shadow: Shadow::default(),
|
||||
|
||||
bg_color: None,
|
||||
bg_border: Border {
|
||||
color: Color::TRANSPARENT,
|
||||
width: 0.0,
|
||||
radius: 0.0.into(),
|
||||
},
|
||||
bg_shadow: Shadow::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Quad
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size::new(self.width, self.height)
|
||||
}
|
||||
|
||||
fn layout(&mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &Limits) -> Node {
|
||||
let limits = limits.width(self.width).height(self.height);
|
||||
Node::new(limits.max())
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
_state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
_theme: &Theme,
|
||||
_style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
_cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let bounds = layout.bounds();
|
||||
if bounds.intersects(viewport) {
|
||||
if let Some(b) = self.bg_color {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds,
|
||||
border: self.bg_border,
|
||||
shadow: self.bg_shadow,
|
||||
..Default::default()
|
||||
},
|
||||
b,
|
||||
);
|
||||
}
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: self.inner_bounds.get_bounds(bounds),
|
||||
border: self.quad_border,
|
||||
shadow: self.quad_shadow,
|
||||
..Default::default()
|
||||
},
|
||||
self.quad_color,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> From<Quad> for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
Theme: 'a,
|
||||
{
|
||||
fn from(value: Quad) -> Self {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
+511
@@ -0,0 +1,511 @@
|
||||
//! Display a dropdown list of selectable values.
|
||||
pub mod list;
|
||||
use crate::style::{
|
||||
Status, StyleFn,
|
||||
selection_list::{Catalog, Style},
|
||||
};
|
||||
|
||||
use iced_core::{
|
||||
Border, Clipboard, Element, Event, Font, Layout, Length, Padding, Pixels, Rectangle, Shell,
|
||||
Size, Widget,
|
||||
alignment::Vertical,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
renderer,
|
||||
text::{Paragraph, Text, paragraph},
|
||||
widget::{Tree, tree},
|
||||
};
|
||||
use iced_widget::{
|
||||
Container, Scrollable, container, scrollable,
|
||||
text::{self, LineHeight, Wrapping},
|
||||
};
|
||||
use std::{fmt::Display, hash::Hash, marker::PhantomData};
|
||||
|
||||
pub use list::List;
|
||||
|
||||
/// A widget for selecting a single value from a dynamic scrollable list of options.
|
||||
#[allow(missing_debug_implementations)]
|
||||
#[allow(clippy::type_repetition_in_bounds)]
|
||||
pub struct SelectionList<
|
||||
'a,
|
||||
T,
|
||||
Message,
|
||||
Theme = iced_widget::Theme,
|
||||
Renderer = iced_widget::Renderer,
|
||||
> where
|
||||
T: Clone + ToString + Eq + Hash,
|
||||
[T]: ToOwned<Owned = Vec<T>>,
|
||||
Renderer: renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: Catalog + container::Catalog,
|
||||
{
|
||||
/// Container for Rendering List.
|
||||
container: Container<'a, Message, Theme, Renderer>,
|
||||
/// List of Elements to Render.
|
||||
options: &'a [T],
|
||||
/// Label Font
|
||||
font: Renderer::Font,
|
||||
/// The Containers Width
|
||||
width: Length,
|
||||
/// The Containers height
|
||||
height: Length,
|
||||
/// The padding Width
|
||||
padding: Padding,
|
||||
/// The Text Size
|
||||
text_size: f32,
|
||||
/// Style for Looks
|
||||
class: <Theme as Catalog>::Class<'a>,
|
||||
}
|
||||
|
||||
#[allow(clippy::type_repetition_in_bounds)]
|
||||
impl<'a, T, Message, Theme, Renderer> SelectionList<'a, T, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: 'a + Catalog + container::Catalog + scrollable::Catalog + iced_widget::text::Catalog,
|
||||
T: Clone + Display + Eq + Hash,
|
||||
[T]: ToOwned<Owned = Vec<T>>,
|
||||
{
|
||||
/// Creates a new [`SelectionList`] with the given list of `options`,
|
||||
/// the current selected value, and the `message` to produce when an option is
|
||||
/// selected. This will default the `style`, `text_size` and `padding`. use `new_with`
|
||||
/// to set those.
|
||||
pub fn new(options: &'a [T], on_selected: impl Fn(usize, T) -> Message + 'static) -> Self {
|
||||
let container = Container::new(Scrollable::new(List {
|
||||
options,
|
||||
font: Font::default(),
|
||||
text_size: 12.0,
|
||||
padding: 5.0.into(),
|
||||
class: <Theme as Catalog>::default(),
|
||||
on_selected: Box::new(on_selected),
|
||||
selected: None,
|
||||
phantomdata: PhantomData,
|
||||
}))
|
||||
.padding(1);
|
||||
|
||||
Self {
|
||||
options,
|
||||
font: Font::default(),
|
||||
class: <Theme as Catalog>::default(),
|
||||
container,
|
||||
width: Length::Fill,
|
||||
height: Length::Fill,
|
||||
padding: 5.0.into(),
|
||||
text_size: 12.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new [`SelectionList`] with the given list of `options`,
|
||||
/// the current selected value, the message to produce when an option is
|
||||
/// selected, the `style`, `text_size`, `padding` and `font`.
|
||||
pub fn new_with(
|
||||
options: &'a [T],
|
||||
on_selected: impl Fn(usize, T) -> Message + 'static,
|
||||
text_size: f32,
|
||||
padding: impl Into<Padding>,
|
||||
style: impl Fn(&Theme, Status) -> Style + 'a + Clone,
|
||||
selected: Option<usize>,
|
||||
font: Font,
|
||||
) -> Self
|
||||
where
|
||||
<Theme as Catalog>::Class<'a>: From<StyleFn<'a, Theme, Style>>,
|
||||
{
|
||||
let class: <Theme as Catalog>::Class<'a> =
|
||||
(Box::new(style.clone()) as StyleFn<'a, Theme, Style>).into();
|
||||
let class2: <Theme as Catalog>::Class<'a> =
|
||||
(Box::new(style) as StyleFn<'a, Theme, Style>).into();
|
||||
|
||||
let padding = padding.into();
|
||||
|
||||
let container = Container::new(Scrollable::new(List {
|
||||
options,
|
||||
font,
|
||||
text_size,
|
||||
padding,
|
||||
class: class2,
|
||||
selected,
|
||||
on_selected: Box::new(on_selected),
|
||||
phantomdata: PhantomData,
|
||||
}))
|
||||
.padding(1);
|
||||
|
||||
Self {
|
||||
options,
|
||||
font,
|
||||
class,
|
||||
container,
|
||||
width: Length::Fill,
|
||||
height: Length::Fill,
|
||||
padding,
|
||||
text_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the width of the [`SelectionList`].
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`SelectionList`].
|
||||
#[must_use]
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the style of the [`SelectionList`].
|
||||
#[must_use]
|
||||
pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
|
||||
where
|
||||
<Theme as Catalog>::Class<'a>: From<StyleFn<'a, Theme, Style>>,
|
||||
{
|
||||
self.class = (Box::new(style) as StyleFn<'a, Theme, Style>).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the class of the input of the [`SelectionList`].
|
||||
#[must_use]
|
||||
pub fn class(mut self, class: impl Into<<Theme as Catalog>::Class<'a>>) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for SelectionList<'a, T, Message, Theme, Renderer>
|
||||
where
|
||||
T: 'a + Clone + ToString + Eq + Hash + Display,
|
||||
Message: 'static,
|
||||
Renderer: renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font> + 'a,
|
||||
Theme: Catalog + container::Catalog,
|
||||
{
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
vec![Tree::new(&self.container as &dyn Widget<_, _, _>)]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(&[&self.container as &dyn Widget<_, _, _>]);
|
||||
let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>();
|
||||
|
||||
state.values = self
|
||||
.options
|
||||
.iter()
|
||||
.map(|_| paragraph::Plain::<Renderer::Paragraph>::default())
|
||||
.collect();
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size::new(self.width, Length::Shrink)
|
||||
}
|
||||
|
||||
fn tag(&self) -> tree::Tag {
|
||||
tree::Tag::of::<State<Renderer::Paragraph>>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::new(State::<Renderer::Paragraph>::new(self.options))
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
use std::f32;
|
||||
|
||||
let state = tree.state.downcast_mut::<State<Renderer::Paragraph>>();
|
||||
|
||||
let limits = limits.width(self.width).height(self.height);
|
||||
|
||||
let max_width = match self.width {
|
||||
Length::Shrink => self
|
||||
.options
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, val)| {
|
||||
let s: &str = &val.to_string();
|
||||
let text = Text {
|
||||
content: s,
|
||||
size: Pixels(self.text_size),
|
||||
line_height: LineHeight::default(),
|
||||
bounds: Size::INFINITE,
|
||||
font: self.font,
|
||||
align_x: text::Alignment::Left,
|
||||
align_y: Vertical::Top,
|
||||
shaping: text::Shaping::Advanced,
|
||||
wrapping: Wrapping::default(),
|
||||
};
|
||||
|
||||
let _ = state.values[id].update(text);
|
||||
(state.values[id].min_bounds().width + self.padding.x()).round() as u32
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(100),
|
||||
_ => limits.max().width as u32,
|
||||
};
|
||||
|
||||
let limits = limits.max_width(max_width as f32 + self.padding.x());
|
||||
|
||||
let content = self
|
||||
.container
|
||||
.layout(&mut tree.children[0], renderer, &limits);
|
||||
let size = limits.resolve(self.width, self.height, content.size());
|
||||
Node::with_children(size, vec![content])
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.container.update(
|
||||
&mut state.children[0],
|
||||
event,
|
||||
layout
|
||||
.children()
|
||||
.next()
|
||||
.expect("Scrollable Child Missing in Selection List"),
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.container
|
||||
.mouse_interaction(&state.children[0], layout, cursor, viewport, renderer)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let bounds = layout.bounds();
|
||||
let style_sheet = <Theme as Catalog>::style(theme, &self.class, Status::Active);
|
||||
|
||||
if let Some(clipped_viewport) = bounds.intersection(viewport) {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds,
|
||||
border: Border {
|
||||
radius: (0.0).into(),
|
||||
width: style_sheet.border_width,
|
||||
color: style_sheet.border_color,
|
||||
},
|
||||
..renderer::Quad::default()
|
||||
},
|
||||
style_sheet.background,
|
||||
);
|
||||
|
||||
self.container.draw(
|
||||
&state.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout
|
||||
.children()
|
||||
.next()
|
||||
.expect("Scrollable Child Missing in Selection List"),
|
||||
cursor,
|
||||
&clipped_viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn iced_core::widget::Operation<()>,
|
||||
) {
|
||||
Widget::<Message, Theme, Renderer>::operate(
|
||||
&mut self.container,
|
||||
&mut state.children[0],
|
||||
layout
|
||||
.children()
|
||||
.next()
|
||||
.expect("Scrollable Child Missing in Selection List"),
|
||||
renderer,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, Message, Theme, Renderer> From<SelectionList<'a, T, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
T: Clone + ToString + Eq + Hash + Display,
|
||||
Message: 'static,
|
||||
Renderer: 'a + renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: 'a + Catalog + container::Catalog,
|
||||
{
|
||||
fn from(selection_list: SelectionList<'a, T, Message, Theme, Renderer>) -> Self {
|
||||
Element::new(selection_list)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Paragraph cache to enhance speed of layouting.
|
||||
#[derive(Default, Clone)]
|
||||
pub struct State<P: Paragraph> {
|
||||
values: Vec<paragraph::Plain<P>>,
|
||||
}
|
||||
|
||||
impl<P: Paragraph> State<P> {
|
||||
/// Creates a new [`State`], representing an unfocused [`TextInput`](iced_widget::TextInput).
|
||||
pub fn new<T>(options: &[T]) -> Self
|
||||
where
|
||||
T: Clone + Display + Eq + Hash,
|
||||
[T]: ToOwned<Owned = Vec<T>>,
|
||||
{
|
||||
Self {
|
||||
values: options
|
||||
.iter()
|
||||
.map(|_| paragraph::Plain::<P>::default())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum TestMessage {
|
||||
Selected(usize, String),
|
||||
}
|
||||
|
||||
type TestSelectionList<'a> = SelectionList<'a, String, TestMessage, iced_widget::Theme>;
|
||||
|
||||
#[test]
|
||||
fn selection_list_new_creates_instance() {
|
||||
let options = vec!["Option 1".to_owned(), "Option 2".to_owned()];
|
||||
|
||||
let selection_list = TestSelectionList::new(&options, TestMessage::Selected);
|
||||
|
||||
assert_eq!(selection_list.options.len(), 2);
|
||||
assert_eq!(selection_list.width, Length::Fill);
|
||||
assert_eq!(selection_list.height, Length::Fill);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_list_new_with_creates_instance() {
|
||||
let options = vec!["Option 1".to_owned(), "Option 2".to_owned()];
|
||||
|
||||
let selection_list = TestSelectionList::new_with(
|
||||
&options,
|
||||
TestMessage::Selected,
|
||||
14.0,
|
||||
10.0,
|
||||
crate::style::selection_list::primary,
|
||||
Some(0),
|
||||
Font::default(),
|
||||
);
|
||||
|
||||
assert_eq!(selection_list.options.len(), 2);
|
||||
assert_eq!(selection_list.text_size, 14.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_list_width_sets_value() {
|
||||
let options = vec!["Option 1".to_owned()];
|
||||
|
||||
let selection_list = TestSelectionList::new(&options, TestMessage::Selected).width(200);
|
||||
|
||||
assert_eq!(selection_list.width, Length::Fixed(200.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_list_height_sets_value() {
|
||||
let options = vec!["Option 1".to_owned()];
|
||||
|
||||
let selection_list = TestSelectionList::new(&options, TestMessage::Selected).height(300);
|
||||
|
||||
assert_eq!(selection_list.height, Length::Fixed(300.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_list_tag_returns_state_tag() {
|
||||
let options = vec!["Option 1".to_owned()];
|
||||
|
||||
let selection_list = TestSelectionList::new(&options, TestMessage::Selected);
|
||||
|
||||
let tag =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::tag(&selection_list);
|
||||
assert_eq!(
|
||||
tag,
|
||||
tree::Tag::of::<State<<iced_widget::Renderer as iced_core::text::Renderer>::Paragraph>>(
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_list_has_one_child() {
|
||||
let options = vec!["Option 1".to_owned()];
|
||||
|
||||
let selection_list = TestSelectionList::new(&options, TestMessage::Selected);
|
||||
|
||||
let children = Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::children(
|
||||
&selection_list,
|
||||
);
|
||||
assert_eq!(children.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_list_size_defaults() {
|
||||
let options = vec!["Option 1".to_owned()];
|
||||
|
||||
let selection_list = TestSelectionList::new(&options, TestMessage::Selected);
|
||||
|
||||
let size =
|
||||
Widget::<TestMessage, iced_widget::Theme, iced_widget::Renderer>::size(&selection_list);
|
||||
assert_eq!(size.width, Length::Fill);
|
||||
assert_eq!(size.height, Length::Shrink);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_list_multiple_options() {
|
||||
let options = vec![
|
||||
"Option 1".to_owned(),
|
||||
"Option 2".to_owned(),
|
||||
"Option 3".to_owned(),
|
||||
];
|
||||
|
||||
let selection_list = TestSelectionList::new(&options, TestMessage::Selected);
|
||||
|
||||
assert_eq!(selection_list.options.len(), 3);
|
||||
assert_eq!(selection_list.options[0], "Option 1");
|
||||
assert_eq!(selection_list.options[1], "Option 2");
|
||||
assert_eq!(selection_list.options[2], "Option 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_new_creates_empty_values() {
|
||||
type TestState = State<<iced_widget::Renderer as iced_core::text::Renderer>::Paragraph>;
|
||||
|
||||
let options = vec!["A".to_owned(), "B".to_owned()];
|
||||
let state = TestState::new(&options);
|
||||
|
||||
assert_eq!(state.values.len(), 2);
|
||||
}
|
||||
}
|
||||
+328
@@ -0,0 +1,328 @@
|
||||
//! Build and show dropdown `ListMenus`.
|
||||
|
||||
use crate::selection_list::Catalog;
|
||||
|
||||
use iced_core::{
|
||||
Border, Clipboard, Color, Element, Event, Layout, Length, Padding, Pixels, Point, Rectangle,
|
||||
Shell, Size, Widget,
|
||||
alignment::Vertical,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
renderer, touch,
|
||||
widget::text::{LineHeight, Wrapping},
|
||||
widget::{
|
||||
Tree,
|
||||
tree::{State, Tag},
|
||||
},
|
||||
};
|
||||
use std::{
|
||||
collections::hash_map::DefaultHasher,
|
||||
fmt::Display,
|
||||
hash::{Hash, Hasher},
|
||||
marker::PhantomData,
|
||||
};
|
||||
|
||||
/// The Private [`List`] Handles the Actual list rendering.
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct List<'a, T: 'a, Message, Theme, Renderer>
|
||||
where
|
||||
T: Clone + Display + Eq + Hash,
|
||||
[T]: ToOwned<Owned = Vec<T>>,
|
||||
Renderer: renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: Catalog,
|
||||
{
|
||||
/// Options pointer to hold all rendered strings
|
||||
pub options: &'a [T],
|
||||
/// Hovered Item Pointer
|
||||
/// Label Font
|
||||
pub font: Renderer::Font,
|
||||
/// Style for Font colors and Box hover colors.
|
||||
pub class: <Theme as Catalog>::Class<'a>,
|
||||
/// Function Pointer On Select to call on Mouse button press.
|
||||
pub on_selected: Box<dyn Fn(usize, T) -> Message>,
|
||||
/// The padding Width
|
||||
pub padding: Padding,
|
||||
/// The Text Size
|
||||
pub text_size: f32,
|
||||
/// Set the Selected ID manually.
|
||||
pub selected: Option<usize>,
|
||||
/// Shadow Type holder for Renderer.
|
||||
pub phantomdata: PhantomData<Renderer>,
|
||||
}
|
||||
|
||||
/// The Private [`ListState`] Handles the State of the inner list.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ListState {
|
||||
/// Statehood of ``hovered_option``
|
||||
pub hovered_option: Option<usize>,
|
||||
/// The index in the list of options of the last chosen Item Clicked for Processing
|
||||
pub last_selected_index: Option<(usize, u64)>,
|
||||
// String Build Cache
|
||||
//pub options: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for List<'_, T, Message, Theme, Renderer>
|
||||
where
|
||||
T: Clone + Display + Eq + Hash,
|
||||
Renderer: renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: Catalog + iced_widget::text::Catalog,
|
||||
{
|
||||
fn tag(&self) -> Tag {
|
||||
Tag::of::<ListState>()
|
||||
}
|
||||
|
||||
fn state(&self) -> State {
|
||||
State::new(ListState::default())
|
||||
}
|
||||
|
||||
fn diff(&self, state: &mut Tree) {
|
||||
let list_state = state.state.downcast_mut::<ListState>();
|
||||
|
||||
if let Some(id) = self.selected {
|
||||
if let Some(option) = self.options.get(id) {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
option.hash(&mut hasher);
|
||||
|
||||
list_state.last_selected_index = Some((id, hasher.finish()));
|
||||
} else {
|
||||
list_state.last_selected_index = None;
|
||||
}
|
||||
} else if let Some((id, hash)) = list_state.last_selected_index {
|
||||
if let Some(option) = self.options.get(id) {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
option.hash(&mut hasher);
|
||||
|
||||
if hash != hasher.finish() {
|
||||
list_state.last_selected_index = None;
|
||||
}
|
||||
} else {
|
||||
list_state.last_selected_index = None;
|
||||
}
|
||||
}
|
||||
|
||||
//list_state.options = self.options.iter().map(ToString::to_string).collect();
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size::new(Length::Fill, Length::Shrink)
|
||||
}
|
||||
|
||||
fn layout(&mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &Limits) -> Node {
|
||||
use std::f32;
|
||||
let limits = limits.height(Length::Fill).width(Length::Fill);
|
||||
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
let intrinsic = Size::new(
|
||||
limits.max().width,
|
||||
(self.text_size + self.padding.y()) * self.options.len() as f32,
|
||||
);
|
||||
|
||||
Node::new(intrinsic)
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
_renderer: &Renderer,
|
||||
_clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<Message>,
|
||||
_viewport: &Rectangle,
|
||||
) {
|
||||
let bounds = layout.bounds();
|
||||
let list_state = state.state.downcast_mut::<ListState>();
|
||||
let cursor = cursor.position().unwrap_or_default();
|
||||
|
||||
if bounds.contains(cursor) {
|
||||
match event {
|
||||
Event::Mouse(mouse::Event::CursorMoved { .. }) => {
|
||||
list_state.hovered_option = Some(
|
||||
((cursor.y - bounds.y) / (self.text_size + self.padding.y())) as usize,
|
||||
);
|
||||
|
||||
shell.request_redraw();
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
|
||||
| Event::Touch(touch::Event::FingerPressed { .. }) => {
|
||||
list_state.hovered_option = Some(
|
||||
((cursor.y - bounds.y) / (self.text_size + self.padding.y())) as usize,
|
||||
);
|
||||
|
||||
if let Some(index) = list_state.hovered_option
|
||||
&& let Some(option) = self.options.get(index)
|
||||
{
|
||||
let mut hasher = DefaultHasher::new();
|
||||
option.hash(&mut hasher);
|
||||
list_state.last_selected_index = Some((index, hasher.finish()));
|
||||
}
|
||||
|
||||
list_state.last_selected_index.iter().for_each(|last| {
|
||||
if let Some(option) = self.options.get(last.0) {
|
||||
shell.publish((self.on_selected)(last.0, option.clone()));
|
||||
shell.capture_event();
|
||||
}
|
||||
});
|
||||
|
||||
shell.request_redraw();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
} else if list_state.hovered_option.is_some() {
|
||||
list_state.hovered_option = None;
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
_state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
_viewport: &Rectangle,
|
||||
_renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
let bounds = layout.bounds();
|
||||
|
||||
if bounds.contains(cursor.position().unwrap_or_default()) {
|
||||
mouse::Interaction::Pointer
|
||||
} else {
|
||||
mouse::Interaction::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
_style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
_cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
use std::f32;
|
||||
|
||||
let bounds = layout.bounds();
|
||||
let option_height = self.text_size + self.padding.y();
|
||||
let offset = viewport.y - bounds.y;
|
||||
let start = (offset / option_height) as usize;
|
||||
let end = ((offset + viewport.height) / option_height).ceil() as usize;
|
||||
let list_state = state.state.downcast_ref::<ListState>();
|
||||
|
||||
for i in start..end.min(self.options.len()) {
|
||||
let is_selected = list_state.last_selected_index.is_some_and(|u| u.0 == i);
|
||||
let is_hovered = list_state.hovered_option == Some(i);
|
||||
|
||||
let bounds = Rectangle {
|
||||
x: bounds.x,
|
||||
y: bounds.y + option_height * i as f32,
|
||||
width: bounds.width,
|
||||
height: self.text_size + self.padding.y(),
|
||||
};
|
||||
|
||||
if (is_selected || is_hovered) && (bounds.width > 0.) && (bounds.height > 0.) {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds,
|
||||
border: Border {
|
||||
radius: (0.0).into(),
|
||||
width: 0.0,
|
||||
color: Color::TRANSPARENT,
|
||||
},
|
||||
..renderer::Quad::default()
|
||||
},
|
||||
if is_selected {
|
||||
<Theme as Catalog>::style(
|
||||
theme,
|
||||
&self.class,
|
||||
crate::style::Status::Selected,
|
||||
)
|
||||
.background
|
||||
} else {
|
||||
<Theme as Catalog>::style(theme, &self.class, crate::style::Status::Hovered)
|
||||
.background
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let text_color = if is_selected {
|
||||
<Theme as Catalog>::style(theme, &self.class, crate::style::Status::Selected)
|
||||
.text_color
|
||||
} else if is_hovered {
|
||||
<Theme as Catalog>::style(theme, &self.class, crate::style::Status::Hovered)
|
||||
.text_color
|
||||
} else {
|
||||
<Theme as Catalog>::style(theme, &self.class, crate::style::Status::Active)
|
||||
.text_color
|
||||
};
|
||||
|
||||
renderer.fill_text(
|
||||
iced_core::text::Text {
|
||||
content: self.options[i].to_string(),
|
||||
bounds: Size::new(f32::INFINITY, bounds.height),
|
||||
size: Pixels(self.text_size),
|
||||
font: self.font,
|
||||
align_x: iced_widget::text::Alignment::Left,
|
||||
align_y: Vertical::Center,
|
||||
line_height: LineHeight::default(),
|
||||
shaping: iced_widget::text::Shaping::Advanced,
|
||||
wrapping: Wrapping::default(),
|
||||
},
|
||||
Point::new(bounds.x, bounds.center_y()),
|
||||
text_color,
|
||||
bounds,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
_state: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn iced_core::widget::Operation<()>,
|
||||
) {
|
||||
use iced_core::layout::Node;
|
||||
use iced_core::{Size, Vector};
|
||||
|
||||
// Expose all option text for testing by creating virtual Text widgets
|
||||
// Create a layout for each text option
|
||||
let bounds = layout.bounds();
|
||||
let option_height = self.text_size + self.padding.y();
|
||||
|
||||
for (i, option) in self.options.iter().enumerate() {
|
||||
let text_widget = iced_widget::Text::new(option.to_string())
|
||||
.size(self.text_size)
|
||||
.font(self.font);
|
||||
|
||||
// Create a node with just the size (no absolute position)
|
||||
let text_node = Node::new(Size::new(bounds.width, option_height));
|
||||
|
||||
// Create a layout with the correct offset for this option
|
||||
let text_layout =
|
||||
Layout::with_offset(Vector::new(0.0, option_height * i as f32), &text_node);
|
||||
|
||||
let mut element: Element<(), Theme, Renderer> = Element::new(text_widget);
|
||||
let mut text_tree = Tree::new(element.as_widget());
|
||||
element
|
||||
.as_widget_mut()
|
||||
.operate(&mut text_tree, text_layout, renderer, operation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, Message, Theme, Renderer> From<List<'a, T, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
T: Clone + Display + Eq + Hash,
|
||||
Message: 'a,
|
||||
Renderer: 'a + renderer::Renderer + iced_core::text::Renderer<Font = iced_core::Font>,
|
||||
Theme: 'a + Catalog + iced_widget::text::Catalog,
|
||||
{
|
||||
fn from(list: List<'a, T, Message, Theme, Renderer>) -> Self {
|
||||
Element::new(list)
|
||||
}
|
||||
}
|
||||
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
//! Contains the sidebar related widget and data enums.
|
||||
|
||||
#[allow(clippy::module_inception)]
|
||||
pub mod sidebar;
|
||||
pub use sidebar::*;
|
||||
pub mod column;
|
||||
pub use column::*;
|
||||
|
||||
// Not used by `Sidebar` itself, but included for completeness.
|
||||
// The horizontal version of the vertical `Column` for the `Row`.
|
||||
pub mod row;
|
||||
pub use row::*;
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
//! Distribute content rows vertically while setting the row width to widest row.
|
||||
//!
|
||||
//! For alignment [`Alignment::Start`] the last element of the row is flushed to the end.
|
||||
//! For alignment [`Alignment::End`] the first element of the row is flushed to the start.
|
||||
//!
|
||||
//! Future: Idea to implement leaders before/after the flushed element for `Start`/`End`
|
||||
//! alignments.
|
||||
|
||||
use iced_core::{
|
||||
Alignment, Clipboard, Element, Layout, Length, Padding, Pixels, Point, Rectangle, Shell, Size,
|
||||
Vector, Widget, alignment,
|
||||
event::Event,
|
||||
layout::{self, Node},
|
||||
mouse, overlay, renderer,
|
||||
widget::{Operation, tree::Tree},
|
||||
};
|
||||
use iced_widget::Row;
|
||||
|
||||
/// A container that distributes its contents vertically.
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct FlushColumn<'a, Message, Theme = iced_widget::Theme, Renderer = iced_widget::Renderer> {
|
||||
spacing: Pixels,
|
||||
padding: Padding,
|
||||
width: Length,
|
||||
height: Length,
|
||||
max_width: f32,
|
||||
align: Alignment,
|
||||
clip: bool,
|
||||
children: Vec<Element<'a, Message, Theme, Renderer>>,
|
||||
flush: bool,
|
||||
}
|
||||
|
||||
impl<'a, Message: 'a, Theme: 'a, Renderer> FlushColumn<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: iced_core::Renderer + 'a,
|
||||
{
|
||||
/// Creates an empty [`FlushColumn`].
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::from_vec(Vec::new())
|
||||
}
|
||||
|
||||
/// Creates a [`FlushColumn`] with the given capacity.
|
||||
#[must_use]
|
||||
pub fn with_capacity(capacity: usize) -> Self {
|
||||
Self::from_vec(Vec::with_capacity(capacity))
|
||||
}
|
||||
|
||||
/// Creates a [`FlushColumn`] with the given elements.
|
||||
#[must_use]
|
||||
pub fn with_children(
|
||||
children: impl IntoIterator<Item = Row<'a, Message, Theme, Renderer>>,
|
||||
) -> Self {
|
||||
let iterator = children.into_iter();
|
||||
Self::with_capacity(iterator.size_hint().0).extend(iterator)
|
||||
}
|
||||
|
||||
/// Creates a [`FlushColumn`] from an already allocated [`Vec`].
|
||||
///
|
||||
/// Keep in mind that the [`FlushColumn`] will not inspect the [`Vec`], which means
|
||||
/// it won't automatically adapt to the sizing strategy of its contents.
|
||||
///
|
||||
/// If any of the children have a [`Length::Fill`] strategy, you will need to
|
||||
/// call [`FlushColumn::width`] or [`FlushColumn::height`] accordingly.
|
||||
#[must_use]
|
||||
pub fn from_vec(children: Vec<Row<'a, Message, Theme, Renderer>>) -> Self {
|
||||
let children = children
|
||||
.into_iter()
|
||||
.map(|x| Element::into(x.into()))
|
||||
.collect();
|
||||
Self {
|
||||
spacing: Pixels::ZERO,
|
||||
padding: Padding::ZERO,
|
||||
width: Length::Shrink,
|
||||
height: Length::Shrink,
|
||||
max_width: f32::INFINITY,
|
||||
align: Alignment::Start,
|
||||
clip: false,
|
||||
children,
|
||||
flush: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the vertical spacing _between_ elements.
|
||||
///
|
||||
/// Custom margins per element do not exist in iced. You should use this
|
||||
/// method instead! While less flexible, it helps you keep spacing between
|
||||
/// elements consistent.
|
||||
#[must_use]
|
||||
pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self {
|
||||
self.spacing = amount.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the [`Padding`] of the [`FlushColumn`].
|
||||
#[must_use]
|
||||
pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
|
||||
self.padding = padding.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the width of the [`FlushColumn`].
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`FlushColumn`].
|
||||
#[must_use]
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the maximum width of the [`FlushColumn`].
|
||||
#[must_use]
|
||||
pub fn max_width(mut self, max_width: impl Into<Pixels>) -> Self {
|
||||
self.max_width = max_width.into().0;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the horizontal alignment of the contents of the [`FlushColumn`] .
|
||||
#[must_use]
|
||||
pub fn align_x(mut self, align: impl Into<alignment::Vertical>) -> Self {
|
||||
self.align = Alignment::from(align.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the contents of the [`FlushColumn`] should be clipped on
|
||||
/// overflow.
|
||||
#[must_use]
|
||||
pub fn clip(mut self, clip: bool) -> Self {
|
||||
self.clip = clip;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the end row element is flushed to the end when the alignment is set to Start,
|
||||
/// or the start row element is flushed to the start when the alignment is set to End.
|
||||
/// No effect for alignment set to Center.
|
||||
#[must_use]
|
||||
pub fn flush(mut self, flush: bool) -> Self {
|
||||
self.flush = flush;
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds an element to the [`FlushColumn`].
|
||||
#[must_use]
|
||||
pub fn push(mut self, child: impl Into<Row<'a, Message, Theme, Renderer>>) -> Self {
|
||||
let child = child.into();
|
||||
let child_size = child.size_hint();
|
||||
self.width = self.width.enclose(child_size.width);
|
||||
self.height = self.height.enclose(child_size.height);
|
||||
self.children.push(child.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds an element to the [`FlushColumn`], if `Some`.
|
||||
#[must_use]
|
||||
pub fn push_maybe(self, child: Option<impl Into<Row<'a, Message, Theme, Renderer>>>) -> Self {
|
||||
if let Some(child) = child {
|
||||
self.push(child)
|
||||
} else {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Extends the [`FlushColumn`] with the given children.
|
||||
#[must_use]
|
||||
pub fn extend(
|
||||
self,
|
||||
children: impl IntoIterator<Item = Row<'a, Message, Theme, Renderer>>,
|
||||
) -> Self {
|
||||
children.into_iter().fold(self, Self::push)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::mismatching_type_param_order)]
|
||||
impl<'a, Message: 'a, Renderer> Default for FlushColumn<'a, Message, Renderer>
|
||||
where
|
||||
Renderer: iced_core::Renderer + 'a,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message: 'a, Theme: 'a, Renderer: iced_core::Renderer + 'a>
|
||||
FromIterator<Row<'a, Message, Theme, Renderer>> for FlushColumn<'a, Message, Theme, Renderer>
|
||||
{
|
||||
fn from_iter<T: IntoIterator<Item = Row<'a, Message, Theme, Renderer>>>(iter: T) -> Self {
|
||||
Self::with_children(iter)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message: 'a, Theme: 'a, Renderer> Widget<Message, Theme, Renderer>
|
||||
for FlushColumn<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: iced_core::Renderer,
|
||||
{
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
self.children.iter().map(Tree::new).collect()
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(&self.children);
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
renderer: &Renderer,
|
||||
limits: &layout::Limits,
|
||||
) -> layout::Node {
|
||||
let limits = limits.max_width(self.max_width);
|
||||
let node = layout::flex::resolve(
|
||||
layout::flex::Axis::Vertical,
|
||||
renderer,
|
||||
&limits,
|
||||
self.width,
|
||||
self.height,
|
||||
self.padding,
|
||||
self.spacing.0,
|
||||
self.align,
|
||||
&mut self.children,
|
||||
&mut tree.children,
|
||||
);
|
||||
let mut container_x = f32::MAX;
|
||||
let mut container_width = 0.0f32;
|
||||
for row in node.children() {
|
||||
if row.size().width > container_width {
|
||||
container_width = row.size().width;
|
||||
}
|
||||
if row.bounds().x < container_x {
|
||||
container_x = row.bounds().x;
|
||||
}
|
||||
}
|
||||
let mut children = Vec::<Node>::new();
|
||||
for row in node.children() {
|
||||
let mut row_children = Vec::<Node>::new();
|
||||
let bounds = row.bounds();
|
||||
let width_diff = container_width - bounds.width;
|
||||
if !row.children().is_empty() {
|
||||
for element in row.children() {
|
||||
let bounds = element.bounds();
|
||||
let x = bounds.x
|
||||
+ match self.align {
|
||||
Alignment::Start => 0.0,
|
||||
Alignment::Center => width_diff / 2.0,
|
||||
Alignment::End => width_diff,
|
||||
};
|
||||
let mut element_node =
|
||||
Node::with_children(element.size(), element.children().to_owned());
|
||||
element_node.move_to_mut(Point::new(x, bounds.y));
|
||||
row_children.push(element_node);
|
||||
}
|
||||
if row_children.len() > 1 {
|
||||
match self.align {
|
||||
Alignment::Start => {
|
||||
let element = row_children.last().expect("Always exists.");
|
||||
let bounds = element.bounds();
|
||||
let mut position = bounds.position();
|
||||
let mut element_node =
|
||||
Node::with_children(bounds.size(), element.children().to_owned());
|
||||
position.x += width_diff;
|
||||
element_node.move_to_mut(position);
|
||||
let node = row_children.last_mut().expect("Always exists.");
|
||||
*node = element_node;
|
||||
}
|
||||
Alignment::Center => {}
|
||||
Alignment::End => {
|
||||
let element = row_children.first().expect("Always exists.");
|
||||
let bounds = element.bounds();
|
||||
let mut position = bounds.position();
|
||||
let mut element_node =
|
||||
Node::with_children(bounds.size(), element.children().to_owned());
|
||||
position.x -= width_diff;
|
||||
element_node.move_to_mut(position);
|
||||
let node = row_children.first_mut().expect("Always exists.");
|
||||
*node = element_node;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut row_node =
|
||||
Node::with_children(Size::new(container_width, row.size().height), row_children);
|
||||
row_node.move_to_mut(Point::new(container_x, bounds.y));
|
||||
children.push(row_node);
|
||||
}
|
||||
Node::with_children(node.size(), children)
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
operation.container(None, layout.bounds());
|
||||
operation.traverse(&mut |operation| {
|
||||
self.children
|
||||
.iter_mut()
|
||||
.zip(&mut tree.children)
|
||||
.zip(layout.children())
|
||||
.for_each(|((child, state), layout)| {
|
||||
child
|
||||
.as_widget_mut()
|
||||
.operate(state, layout, renderer, operation);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
) {
|
||||
for ((child, state), layout) in self
|
||||
.children
|
||||
.iter_mut()
|
||||
.zip(&mut tree.children)
|
||||
.zip(layout.children())
|
||||
{
|
||||
child.as_widget_mut().update(
|
||||
state, event, layout, cursor, renderer, clipboard, shell, viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.children
|
||||
.iter()
|
||||
.zip(&tree.children)
|
||||
.zip(layout.children())
|
||||
.map(|((child, state), layout)| {
|
||||
child
|
||||
.as_widget()
|
||||
.mouse_interaction(state, layout, cursor, viewport, renderer)
|
||||
})
|
||||
.max()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
if let Some(clipped_viewport) = layout.bounds().intersection(viewport) {
|
||||
for ((child, state), layout) in self
|
||||
.children
|
||||
.iter()
|
||||
.zip(&tree.children)
|
||||
.zip(layout.children())
|
||||
{
|
||||
child.as_widget().draw(
|
||||
state,
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
if self.clip {
|
||||
&clipped_viewport
|
||||
} else {
|
||||
viewport
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
tree: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
overlay::from_children(
|
||||
&mut self.children,
|
||||
tree,
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> From<FlushColumn<'a, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a,
|
||||
Theme: 'a,
|
||||
Renderer: iced_core::Renderer + 'a,
|
||||
{
|
||||
fn from(column: FlushColumn<'a, Message, Theme, Renderer>) -> Self {
|
||||
Self::new(column)
|
||||
}
|
||||
}
|
||||
+433
@@ -0,0 +1,433 @@
|
||||
//! Distribute content columns horizontally while setting the column height to highest column.
|
||||
//!
|
||||
//! For alignment [`Alignment::Start`] the last element of the column is flushed to the end.
|
||||
//! For alignment [`Alignment::End`] the first element of the column is flushed to the start.
|
||||
//!
|
||||
//! Future: Idea to implement leaders before/after the flushed element for `Start`/`End`
|
||||
//! alignments.
|
||||
|
||||
use iced_core::{
|
||||
Alignment, Clipboard, Element, Layout, Length, Padding, Pixels, Point, Rectangle, Shell, Size,
|
||||
Vector, Widget, alignment,
|
||||
event::Event,
|
||||
layout::{self, Node},
|
||||
mouse, overlay, renderer,
|
||||
widget::{Operation, tree::Tree},
|
||||
};
|
||||
use iced_widget::Column;
|
||||
|
||||
/// A container that distributes its contents horizontally.
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct FlushRow<'a, Message, Theme = iced_core::Theme, Renderer = iced_widget::Renderer> {
|
||||
spacing: Pixels,
|
||||
padding: Padding,
|
||||
width: Length,
|
||||
height: Length,
|
||||
max_height: f32,
|
||||
align: Alignment,
|
||||
clip: bool,
|
||||
children: Vec<Element<'a, Message, Theme, Renderer>>,
|
||||
flush: bool,
|
||||
}
|
||||
|
||||
impl<'a, Message: 'a, Theme: 'a, Renderer> FlushRow<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: iced_core::Renderer + 'a,
|
||||
{
|
||||
/// Creates an empty [`FlushRow`].
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::from_vec(Vec::new())
|
||||
}
|
||||
|
||||
/// Creates a [`FlushRow`] with the given capacity.
|
||||
#[must_use]
|
||||
pub fn with_capacity(capacity: usize) -> Self {
|
||||
Self::from_vec(Vec::with_capacity(capacity))
|
||||
}
|
||||
|
||||
/// Creates a [`FlushRow`] with the given elements.
|
||||
#[must_use]
|
||||
pub fn with_children(
|
||||
children: impl IntoIterator<Item = Column<'a, Message, Theme, Renderer>>,
|
||||
) -> Self {
|
||||
let iterator = children.into_iter();
|
||||
Self::with_capacity(iterator.size_hint().0).extend(iterator)
|
||||
}
|
||||
|
||||
/// Creates a [`FlushRow`] from an already allocated [`Vec`].
|
||||
///
|
||||
/// Keep in mind that the [`FlushRow`] will not inspect the [`Vec`], which means
|
||||
/// it won't automatically adapt to the sizing strategy of its contents.
|
||||
///
|
||||
/// If any of the children have a [`Length::Fill`] strategy, you will need to
|
||||
/// call [`FlushRow::width`] or [`FlushRow::height`] accordingly.
|
||||
#[must_use]
|
||||
pub fn from_vec(children: Vec<Column<'a, Message, Theme, Renderer>>) -> Self {
|
||||
let children = children
|
||||
.into_iter()
|
||||
.map(|x| Element::into(x.into()))
|
||||
.collect();
|
||||
Self {
|
||||
spacing: Pixels::ZERO,
|
||||
padding: Padding::ZERO,
|
||||
width: Length::Shrink,
|
||||
height: Length::Shrink,
|
||||
max_height: f32::INFINITY,
|
||||
align: Alignment::Start,
|
||||
clip: false,
|
||||
children,
|
||||
flush: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the vertical spacing _between_ elements.
|
||||
///
|
||||
/// Custom margins per element do not exist in iced. You should use this
|
||||
/// method instead! While less flexible, it helps you keep spacing between
|
||||
/// elements consistent.
|
||||
#[must_use]
|
||||
pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self {
|
||||
self.spacing = amount.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the [`Padding`] of the [`FlushRow`].
|
||||
#[must_use]
|
||||
pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
|
||||
self.padding = padding.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the width of the [`FlushRow`].
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`FlushRow`].
|
||||
#[must_use]
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the maximum width of the [`FlushRow`].
|
||||
#[must_use]
|
||||
pub fn max_height(mut self, max_height: impl Into<Pixels>) -> Self {
|
||||
self.max_height = max_height.into().0;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the horizontal alignment of the contents of the [`FlushRow`] .
|
||||
#[must_use]
|
||||
pub fn align_y(mut self, align: impl Into<alignment::Vertical>) -> Self {
|
||||
self.align = Alignment::from(align.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the contents of the [`FlushRow`] should be clipped on
|
||||
/// overflow.
|
||||
#[must_use]
|
||||
pub fn clip(mut self, clip: bool) -> Self {
|
||||
self.clip = clip;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the end column element is flushed to the end when the alignment is set to
|
||||
/// Start, or the start column element is flushed to the start when the alignment is set
|
||||
/// to End. No effect for alignment set to Center.
|
||||
#[must_use]
|
||||
pub fn flush(mut self, flush: bool) -> Self {
|
||||
self.flush = flush;
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds an element to the [`FlushRow`].
|
||||
#[must_use]
|
||||
pub fn push(mut self, child: impl Into<Column<'a, Message, Theme, Renderer>>) -> Self {
|
||||
let child = child.into();
|
||||
let child_size = child.size_hint();
|
||||
self.width = self.width.enclose(child_size.width);
|
||||
self.height = self.height.enclose(child_size.height);
|
||||
self.children.push(child.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds an element to the [`FlushRow`], if `Some`.
|
||||
#[must_use]
|
||||
pub fn push_maybe(
|
||||
self,
|
||||
child: Option<impl Into<Column<'a, Message, Theme, Renderer>>>,
|
||||
) -> Self {
|
||||
if let Some(child) = child {
|
||||
self.push(child)
|
||||
} else {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Extends the [`FlushRow`] with the given children.
|
||||
#[must_use]
|
||||
pub fn extend(
|
||||
self,
|
||||
children: impl IntoIterator<Item = Column<'a, Message, Theme, Renderer>>,
|
||||
) -> Self {
|
||||
children.into_iter().fold(self, Self::push)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::mismatching_type_param_order)]
|
||||
impl<'a, Message: 'a, Renderer> Default for FlushRow<'a, Message, Renderer>
|
||||
where
|
||||
Renderer: iced_core::Renderer + 'a,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message: 'a, Theme: 'a, Renderer: iced_core::Renderer + 'a>
|
||||
FromIterator<Column<'a, Message, Theme, Renderer>> for FlushRow<'a, Message, Theme, Renderer>
|
||||
{
|
||||
fn from_iter<T: IntoIterator<Item = Column<'a, Message, Theme, Renderer>>>(iter: T) -> Self {
|
||||
Self::with_children(iter)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for FlushRow<'_, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: iced_core::Renderer,
|
||||
{
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
self.children.iter().map(Tree::new).collect()
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(&self.children);
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
renderer: &Renderer,
|
||||
limits: &layout::Limits,
|
||||
) -> layout::Node {
|
||||
let limits = limits.max_height(self.max_height);
|
||||
let node = layout::flex::resolve(
|
||||
layout::flex::Axis::Horizontal,
|
||||
renderer,
|
||||
&limits,
|
||||
self.width,
|
||||
self.height,
|
||||
self.padding,
|
||||
self.spacing.0,
|
||||
self.align,
|
||||
&mut self.children,
|
||||
&mut tree.children,
|
||||
);
|
||||
let mut container_y = f32::MAX;
|
||||
let mut container_height = 0.0f32;
|
||||
for column in node.children() {
|
||||
if column.size().height > container_height {
|
||||
container_height = column.size().height;
|
||||
}
|
||||
if column.bounds().y < container_y {
|
||||
container_y = column.bounds().y;
|
||||
}
|
||||
}
|
||||
let mut children = Vec::<Node>::new();
|
||||
for column in node.children() {
|
||||
let mut column_children = Vec::<Node>::new();
|
||||
let bounds = column.bounds();
|
||||
let height_diff = container_height - bounds.height;
|
||||
if !column.children().is_empty() {
|
||||
for element in column.children() {
|
||||
let bounds = element.bounds();
|
||||
let y = bounds.y
|
||||
+ match self.align {
|
||||
Alignment::Start => 0.0,
|
||||
Alignment::Center => height_diff / 2.0,
|
||||
Alignment::End => height_diff,
|
||||
};
|
||||
let mut element_node =
|
||||
Node::with_children(element.size(), element.children().to_owned());
|
||||
element_node.move_to_mut(Point::new(bounds.x, y));
|
||||
column_children.push(element_node);
|
||||
}
|
||||
if column_children.len() > 1 {
|
||||
match self.align {
|
||||
Alignment::Start => {
|
||||
let element = column_children.last().expect("Always exists.");
|
||||
let bounds = element.bounds();
|
||||
let mut position = bounds.position();
|
||||
let mut element_node =
|
||||
Node::with_children(bounds.size(), element.children().to_owned());
|
||||
position.y += height_diff;
|
||||
element_node.move_to_mut(position);
|
||||
let node = column_children.last_mut().expect("Always exists.");
|
||||
*node = element_node;
|
||||
}
|
||||
Alignment::Center => {}
|
||||
Alignment::End => {
|
||||
let element = column_children.first().expect("Always exists.");
|
||||
let bounds = element.bounds();
|
||||
let mut position = bounds.position();
|
||||
let mut element_node =
|
||||
Node::with_children(bounds.size(), element.children().to_owned());
|
||||
position.y -= height_diff;
|
||||
element_node.move_to_mut(position);
|
||||
let node = column_children.first_mut().expect("Always exists.");
|
||||
*node = element_node;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut column_node = Node::with_children(
|
||||
Size::new(column.size().width, container_height),
|
||||
column_children,
|
||||
);
|
||||
column_node.move_to_mut(Point::new(bounds.x, container_y));
|
||||
children.push(column_node);
|
||||
}
|
||||
Node::with_children(node.size(), children)
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
operation.container(None, layout.bounds());
|
||||
operation.traverse(&mut |operation| {
|
||||
self.children
|
||||
.iter_mut()
|
||||
.zip(&mut tree.children)
|
||||
.zip(layout.children())
|
||||
.for_each(|((child, state), layout)| {
|
||||
child
|
||||
.as_widget_mut()
|
||||
.operate(state, layout, renderer, operation);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
) {
|
||||
for ((child, state), layout) in self
|
||||
.children
|
||||
.iter_mut()
|
||||
.zip(&mut tree.children)
|
||||
.zip(layout.children())
|
||||
{
|
||||
child.as_widget_mut().update(
|
||||
state, event, layout, cursor, renderer, clipboard, shell, viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.children
|
||||
.iter()
|
||||
.zip(&tree.children)
|
||||
.zip(layout.children())
|
||||
.map(|((child, state), layout)| {
|
||||
child
|
||||
.as_widget()
|
||||
.mouse_interaction(state, layout, cursor, viewport, renderer)
|
||||
})
|
||||
.max()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
if let Some(clipped_viewport) = layout.bounds().intersection(viewport) {
|
||||
for ((child, state), layout) in self
|
||||
.children
|
||||
.iter()
|
||||
.zip(&tree.children)
|
||||
.zip(layout.children())
|
||||
{
|
||||
child.as_widget().draw(
|
||||
state,
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
if self.clip {
|
||||
&clipped_viewport
|
||||
} else {
|
||||
viewport
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
tree: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
overlay::from_children(
|
||||
&mut self.children,
|
||||
tree,
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> From<FlushRow<'a, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a,
|
||||
Theme: 'a,
|
||||
Renderer: iced_core::Renderer + 'a,
|
||||
{
|
||||
fn from(row: FlushRow<'a, Message, Theme, Renderer>) -> Self {
|
||||
Self::new(row)
|
||||
}
|
||||
}
|
||||
+1955
File diff suppressed because it is too large.
Load diff
+461
@@ -0,0 +1,461 @@
|
||||
//! A dummy widget that draws a quad
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: `quad`*
|
||||
|
||||
use iced_core::{
|
||||
Border, Clipboard, Color, Element, Event, Layout, Length, Point, Rectangle, Shadow, Shell,
|
||||
Size, Widget,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
renderer, touch,
|
||||
widget::{
|
||||
Operation,
|
||||
tree::{self, Tree},
|
||||
},
|
||||
};
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
/// Constant Default height of `SlideBar`.
|
||||
pub const DEFAULT_HEIGHT: f32 = 30.0;
|
||||
|
||||
/// A widget that draws a `SlideBar`
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct SlideBar<'a, T, Message>
|
||||
where
|
||||
Message: Clone,
|
||||
{
|
||||
/// Width of the bar
|
||||
pub width: Length,
|
||||
/// Height of the bar
|
||||
pub height: Option<Length>,
|
||||
/// Color of the bar
|
||||
pub color: Color,
|
||||
/// Background color of the bar
|
||||
pub background: Option<Color>,
|
||||
/// Border radius of the bar
|
||||
pub border_radius: f32,
|
||||
/// Border width of the bar
|
||||
pub border_width: f32,
|
||||
/// Border color of the bar
|
||||
pub border_color: Color,
|
||||
/// value Range
|
||||
pub range: RangeInclusive<T>,
|
||||
/// smallest value within moveable limitations.
|
||||
step: T,
|
||||
/// Value of the bar
|
||||
value: T,
|
||||
/// Change event of the bar when a value is modified
|
||||
on_change: Box<dyn Fn(T) -> Message + 'a>,
|
||||
/// Release event when the mouse is released.
|
||||
on_release: Option<Message>,
|
||||
}
|
||||
|
||||
impl<'a, T, Message> SlideBar<'a, T, Message>
|
||||
where
|
||||
T: Copy + From<u8> + std::cmp::PartialOrd,
|
||||
Message: Clone,
|
||||
{
|
||||
/// Creates a new [`SlideBar`].
|
||||
///
|
||||
/// It expects:
|
||||
/// * an inclusive range of possible values
|
||||
/// * the current value of the [`SlideBar`]
|
||||
/// * a function that will be called when the [`SlideBar`] is dragged.
|
||||
/// * the new value of the [`SlideBar`] and must produce a `Message`.
|
||||
///
|
||||
pub fn new<F>(range: RangeInclusive<T>, value: T, on_change: F) -> Self
|
||||
where
|
||||
F: 'a + Fn(T) -> Message,
|
||||
{
|
||||
let value = if value >= *range.start() {
|
||||
value
|
||||
} else {
|
||||
*range.start()
|
||||
};
|
||||
|
||||
let value = if value <= *range.end() {
|
||||
value
|
||||
} else {
|
||||
*range.end()
|
||||
};
|
||||
|
||||
Self {
|
||||
width: Length::Fill,
|
||||
height: None,
|
||||
color: Color::from([0.5; 3]),
|
||||
background: None,
|
||||
border_radius: 5.0,
|
||||
border_width: 1.0,
|
||||
border_color: Color::BLACK,
|
||||
step: T::from(1),
|
||||
value,
|
||||
range,
|
||||
on_change: Box::new(on_change),
|
||||
on_release: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the release message of the [`SlideBar`].
|
||||
/// This is called when the mouse is released from the slider.
|
||||
///
|
||||
/// Typically, the user's interaction with the slider is finished when this message is produced.
|
||||
/// This is useful if you need to spawn a long-running task from the slider's result, where
|
||||
/// the default `on_change` message could create too many events.
|
||||
#[must_use]
|
||||
pub fn on_release(mut self, on_release: Message) -> Self {
|
||||
self.on_release = Some(on_release);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the width of the [`SlideBar`].
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`SlideBar`].
|
||||
#[must_use]
|
||||
pub fn height(mut self, height: Option<Length>) -> Self {
|
||||
self.height = height;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the step size of the [`SlideBar`].
|
||||
#[must_use]
|
||||
pub fn step(mut self, step: impl Into<T>) -> Self {
|
||||
self.step = step.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Message, Theme, Renderer> Widget<Message, Theme, Renderer> for SlideBar<'_, T, Message>
|
||||
where
|
||||
T: Copy + Into<f64> + num_traits::FromPrimitive,
|
||||
Message: Clone,
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
fn tag(&self) -> tree::Tag {
|
||||
tree::Tag::of::<State>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::new(State::new())
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size {
|
||||
width: self.width,
|
||||
height: self.height.unwrap_or(Length::Fixed(DEFAULT_HEIGHT)),
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(&mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &Limits) -> Node {
|
||||
let limits = limits
|
||||
.width(self.width)
|
||||
.height(self.height.unwrap_or(Length::Fixed(DEFAULT_HEIGHT)));
|
||||
|
||||
let size = limits.resolve(
|
||||
self.width,
|
||||
self.height.unwrap_or(Length::Fixed(DEFAULT_HEIGHT)),
|
||||
Size::ZERO,
|
||||
);
|
||||
|
||||
Node::new(size)
|
||||
}
|
||||
|
||||
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,
|
||||
) {
|
||||
update(
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
shell,
|
||||
tree.state.downcast_mut::<State>(),
|
||||
&mut self.value,
|
||||
&self.range,
|
||||
self.step,
|
||||
self.on_change.as_ref(),
|
||||
&self.on_release,
|
||||
);
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
_tree: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
_renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
// Register the widget's bounds for testing
|
||||
operation.container(None, layout.bounds());
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
_tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
_theme: &Theme,
|
||||
_style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
_cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
draw(renderer, layout, viewport, self);
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes an [`Event`] and updates the [`State`] of a [`SlideBar`]
|
||||
/// accordingly.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn update<Message, T>(
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
state: &mut State,
|
||||
value: &mut T,
|
||||
range: &RangeInclusive<T>,
|
||||
step: T,
|
||||
on_change: &dyn Fn(T) -> Message,
|
||||
on_release: &Option<Message>,
|
||||
) where
|
||||
T: Copy + Into<f64> + num_traits::FromPrimitive,
|
||||
Message: Clone,
|
||||
{
|
||||
let is_dragging = state.is_dragging;
|
||||
|
||||
let mut change = |cursor_position: Point| {
|
||||
let bounds = layout.bounds();
|
||||
let new_value = if cursor_position.x <= bounds.x {
|
||||
*range.start()
|
||||
} else if cursor_position.x >= bounds.x + bounds.width {
|
||||
*range.end()
|
||||
} else {
|
||||
let step = step.into();
|
||||
let start = (*range.start()).into();
|
||||
let end = (*range.end()).into();
|
||||
|
||||
let percent = f64::from(cursor_position.x - bounds.x) / f64::from(bounds.width);
|
||||
|
||||
let steps = (percent * (end - start) / step).round();
|
||||
let value = steps * step + start;
|
||||
|
||||
if let Some(value) = T::from_f64(value) {
|
||||
value
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if ((*value).into() - new_value.into()).abs() > f64::EPSILON {
|
||||
shell.publish((on_change)(new_value));
|
||||
|
||||
*value = new_value;
|
||||
}
|
||||
};
|
||||
|
||||
match event {
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
|
||||
| Event::Touch(touch::Event::FingerPressed { .. }) => {
|
||||
if let Some(cursor_position) = cursor.position_over(layout.bounds()) {
|
||||
change(cursor_position);
|
||||
state.is_dragging = true;
|
||||
|
||||
shell.capture_event();
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
|
||||
| Event::Touch(touch::Event::FingerLifted { .. } | touch::Event::FingerLost { .. })
|
||||
if is_dragging =>
|
||||
{
|
||||
if let Some(on_release) = on_release.clone() {
|
||||
shell.publish(on_release);
|
||||
}
|
||||
state.is_dragging = false;
|
||||
|
||||
shell.capture_event();
|
||||
}
|
||||
Event::Mouse(mouse::Event::CursorMoved { .. })
|
||||
| Event::Touch(touch::Event::FingerMoved { .. })
|
||||
if is_dragging =>
|
||||
{
|
||||
let _ = cursor.position().map(change);
|
||||
|
||||
shell.capture_event();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws a [`SlideBar`].
|
||||
pub fn draw<T, R, Message>(
|
||||
renderer: &mut R,
|
||||
layout: Layout<'_>,
|
||||
viewport: &Rectangle,
|
||||
slider: &SlideBar<T, Message>,
|
||||
) where
|
||||
T: Into<f64> + Copy,
|
||||
Message: Clone,
|
||||
R: renderer::Renderer,
|
||||
{
|
||||
let bounds = layout.bounds();
|
||||
let value = slider.value.into() as f32;
|
||||
let (range_start, range_end) = {
|
||||
let (start, end) = slider.range.clone().into_inner();
|
||||
|
||||
(start.into() as f32, end.into() as f32)
|
||||
};
|
||||
|
||||
let active_progress_bounds = if range_start >= range_end {
|
||||
Rectangle {
|
||||
width: 0.0,
|
||||
..bounds
|
||||
}
|
||||
} else {
|
||||
Rectangle {
|
||||
width: bounds.width * (value - range_start) / (range_end - range_start),
|
||||
..bounds
|
||||
}
|
||||
};
|
||||
|
||||
let background = slider.background.unwrap_or_else(|| Color::from([1.0; 3]));
|
||||
|
||||
if bounds.intersects(viewport) {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds,
|
||||
border: Border {
|
||||
radius: slider.border_radius.into(),
|
||||
width: slider.border_width,
|
||||
color: slider.border_color,
|
||||
},
|
||||
shadow: Shadow::default(),
|
||||
..Default::default()
|
||||
},
|
||||
background,
|
||||
);
|
||||
}
|
||||
|
||||
if active_progress_bounds.intersects(viewport) {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: active_progress_bounds,
|
||||
border: Border {
|
||||
radius: slider.border_radius.into(),
|
||||
width: 0.0,
|
||||
color: Color::TRANSPARENT,
|
||||
},
|
||||
shadow: Shadow::default(),
|
||||
..Default::default()
|
||||
},
|
||||
slider.color,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, Message, Theme, Renderer> From<SlideBar<'a, T, Message>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
T: 'a + Copy + Into<f64> + num_traits::FromPrimitive,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
Message: 'a + Clone,
|
||||
Theme: 'a,
|
||||
{
|
||||
fn from(value: SlideBar<'a, T, Message>) -> Self {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// The local state of a [`SlideBar`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct State {
|
||||
is_dragging: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Creates a new [`State`].
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Message {
|
||||
Changed(#[allow(dead_code)] u32),
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slide_bar_new() {
|
||||
let slider = SlideBar::new(0..=100, 50, Message::Changed);
|
||||
assert_eq!(slider.value, 50);
|
||||
assert_eq!(*slider.range.start(), 0);
|
||||
assert_eq!(*slider.range.end(), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slide_bar_value_clamped_to_range() {
|
||||
// Value below range
|
||||
let slider = SlideBar::new(10..=100, 5, Message::Changed);
|
||||
assert_eq!(slider.value, 10);
|
||||
|
||||
// Value above range
|
||||
let slider = SlideBar::new(0..=50, 100, Message::Changed);
|
||||
assert_eq!(slider.value, 50);
|
||||
|
||||
// Value within range
|
||||
let slider = SlideBar::new(0..=100, 50, Message::Changed);
|
||||
assert_eq!(slider.value, 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slide_bar_with_step() {
|
||||
let slider = SlideBar::new(0u32..=100, 50, Message::Changed).step(10u32);
|
||||
assert_eq!(slider.step, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slide_bar_with_on_release() {
|
||||
let slider = SlideBar::new(0..=100, 50, Message::Changed).on_release(Message::Changed(0));
|
||||
assert!(slider.on_release.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slide_bar_with_width() {
|
||||
let slider = SlideBar::new(0..=100, 50, Message::Changed).width(Length::Fixed(300.0));
|
||||
assert_eq!(slider.width, Length::Fixed(300.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slide_bar_with_height() {
|
||||
let slider = SlideBar::new(0..=100, 50, Message::Changed).height(Some(Length::Fixed(50.0)));
|
||||
assert_eq!(slider.height, Some(Length::Fixed(50.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_state_new() {
|
||||
let state = State::new();
|
||||
assert!(!state.is_dragging);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_state_default() {
|
||||
let state = State::default();
|
||||
assert!(!state.is_dragging);
|
||||
}
|
||||
}
|
||||
Vendored
+212
@@ -0,0 +1,212 @@
|
||||
//! A spinner to suggest something is loading.
|
||||
use iced_core::{
|
||||
Border, Clipboard, Color, Element, Event, Layout, Length, Rectangle, Shell, Size, Vector,
|
||||
Widget,
|
||||
layout::{Limits, Node},
|
||||
mouse::Cursor,
|
||||
renderer,
|
||||
time::{Duration, Instant},
|
||||
widget::{
|
||||
Tree,
|
||||
tree::{State, Tag},
|
||||
},
|
||||
window,
|
||||
};
|
||||
|
||||
/// A spinner widget, a circle spinning around the center of the widget.
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct Spinner {
|
||||
/// The width of the [`Spinner`].
|
||||
width: Length,
|
||||
/// The height of the [`Spinner`].
|
||||
height: Length,
|
||||
/// The rate of the [`Spinner`].
|
||||
rate: Duration,
|
||||
/// The radius of the spinning circle.
|
||||
circle_radius: f32,
|
||||
}
|
||||
|
||||
impl Default for Spinner {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
width: Length::Fixed(20.0),
|
||||
height: Length::Fixed(20.0),
|
||||
rate: Duration::from_secs_f32(1.0),
|
||||
circle_radius: 2.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Spinner {
|
||||
/// Creates a new [`Spinner`] widget.
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Sets the width of the [`Spinner`].
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`Spinner`].
|
||||
#[must_use]
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the circle radius of the spinning circle.
|
||||
#[must_use]
|
||||
pub fn circle_radius(mut self, radius: f32) -> Self {
|
||||
self.circle_radius = radius;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
struct SpinnerState {
|
||||
last_update: Instant,
|
||||
t: f32,
|
||||
}
|
||||
|
||||
fn is_visible(bounds: &Rectangle) -> bool {
|
||||
bounds.width > 0.0 && bounds.height > 0.0
|
||||
}
|
||||
|
||||
fn fill_circle(
|
||||
renderer: &mut impl renderer::Renderer,
|
||||
position: Vector,
|
||||
radius: f32,
|
||||
color: Color,
|
||||
) {
|
||||
if radius > 0. {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: Rectangle {
|
||||
x: position.x,
|
||||
y: position.y,
|
||||
width: radius * 2.0,
|
||||
height: radius * 2.0,
|
||||
},
|
||||
border: Border {
|
||||
radius: radius.into(),
|
||||
width: 0.0,
|
||||
color: Color::TRANSPARENT,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
color,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer> for Spinner
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
{
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size::new(self.width, self.height)
|
||||
}
|
||||
|
||||
fn layout(&mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &Limits) -> Node {
|
||||
Node::new(limits.width(self.width).height(self.height).resolve(
|
||||
self.width,
|
||||
self.height,
|
||||
Size::new(f32::INFINITY, f32::INFINITY),
|
||||
))
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
_theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
_cursor: Cursor,
|
||||
_viewport: &Rectangle,
|
||||
) {
|
||||
let bounds = layout.bounds();
|
||||
|
||||
if !is_visible(&bounds) {
|
||||
return;
|
||||
}
|
||||
|
||||
let size = if bounds.width < bounds.height {
|
||||
bounds.width
|
||||
} else {
|
||||
bounds.height
|
||||
} / 2.0;
|
||||
let state = state.state.downcast_ref::<SpinnerState>();
|
||||
let center = bounds.center();
|
||||
let distance_from_center = size - self.circle_radius;
|
||||
let (y, x) = (state.t * std::f32::consts::PI * 2.0).sin_cos();
|
||||
let position = Vector::new(
|
||||
center.x + x * distance_from_center - self.circle_radius,
|
||||
center.y + y * distance_from_center - self.circle_radius,
|
||||
);
|
||||
|
||||
fill_circle(renderer, position, self.circle_radius, style.text_color);
|
||||
}
|
||||
|
||||
fn tag(&self) -> Tag {
|
||||
Tag::of::<SpinnerState>()
|
||||
}
|
||||
|
||||
fn state(&self) -> State {
|
||||
State::new(SpinnerState {
|
||||
last_update: Instant::now(),
|
||||
t: 0.0,
|
||||
})
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
_cursor: Cursor,
|
||||
_renderer: &Renderer,
|
||||
_clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
_viewport: &Rectangle,
|
||||
) {
|
||||
const FRAMES_PER_SECOND: u64 = 60;
|
||||
|
||||
let bounds = layout.bounds();
|
||||
|
||||
if let Event::Window(window::Event::RedrawRequested(now)) = event
|
||||
&& is_visible(&bounds)
|
||||
{
|
||||
let state = state.state.downcast_mut::<SpinnerState>();
|
||||
let duration = (*now - state.last_update).as_secs_f32();
|
||||
let increment = if self.rate == Duration::ZERO {
|
||||
0.0
|
||||
} else {
|
||||
duration * 1.0 / self.rate.as_secs_f32()
|
||||
};
|
||||
|
||||
state.t += increment;
|
||||
|
||||
if state.t > 1.0 {
|
||||
state.t -= 1.0;
|
||||
}
|
||||
|
||||
shell.request_redraw_at(window::RedrawRequest::At(
|
||||
*now + Duration::from_millis(1000 / FRAMES_PER_SECOND),
|
||||
));
|
||||
state.last_update = *now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> From<Spinner> for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer + 'a,
|
||||
{
|
||||
fn from(spinner: Spinner) -> Self {
|
||||
Self::new(spinner)
|
||||
}
|
||||
}
|
||||
Vendored
+1205
File diff suppressed because it is too large.
Load diff
+49
@@ -0,0 +1,49 @@
|
||||
//! A [`TabLabel`] showing an icon and/or a text on a tab.
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: `tab_bar`*
|
||||
|
||||
/// A [`TabLabel`] showing an icon and/or a text on a tab
|
||||
/// on a [`TabBar`](super::TabBar).
|
||||
#[allow(missing_debug_implementations)]
|
||||
#[derive(Clone, Hash)]
|
||||
pub enum TabLabel {
|
||||
/// A [`TabLabel`] showing only an icon on the tab.
|
||||
Icon(char),
|
||||
|
||||
/// A [`TabLabel`] showing only a text on the tab.
|
||||
Text(String),
|
||||
|
||||
/// A [`TabLabel`] showing an icon and a text on the tab.
|
||||
IconText(char, String),
|
||||
// TODO: Support any element as a label.
|
||||
}
|
||||
|
||||
impl From<char> for TabLabel {
|
||||
fn from(value: char) -> Self {
|
||||
Self::Icon(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for TabLabel {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::Text(value.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for TabLabel {
|
||||
fn from(value: String) -> Self {
|
||||
Self::Text(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<(char, &str)> for TabLabel {
|
||||
fn from(value: (char, &str)) -> Self {
|
||||
Self::IconText(value.0, value.1.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<(char, String)> for TabLabel {
|
||||
fn from(value: (char, String)) -> Self {
|
||||
Self::IconText(value.0, value.1)
|
||||
}
|
||||
}
|
||||
Vendored
+635
@@ -0,0 +1,635 @@
|
||||
//! Displays a [`Tabs`] widget to select the content to be displayed.
|
||||
//!
|
||||
//! This is a wrapper around the [`TabBar`] widget.
|
||||
//! Unlike the [`TabBar`] widget it will also handle
|
||||
//! the content of the tabs.
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: tabs*
|
||||
|
||||
pub mod tab_bar_position;
|
||||
pub use crate::tab_bar::Position;
|
||||
use crate::{
|
||||
TabLabel,
|
||||
style::{
|
||||
Status, StyleFn,
|
||||
tab_bar::{Catalog, Style},
|
||||
},
|
||||
widget::tab_bar::TabBar,
|
||||
};
|
||||
|
||||
use iced_core::{
|
||||
Clipboard, Element, Event, Font, Layout, Length, Padding, Pixels, Point, Rectangle, Shell,
|
||||
Size, Vector, Widget,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
overlay, renderer,
|
||||
widget::{
|
||||
Operation, Tree,
|
||||
tree::{State, Tag},
|
||||
},
|
||||
};
|
||||
use iced_widget::{Row, text};
|
||||
|
||||
pub use tab_bar_position::TabBarPosition;
|
||||
|
||||
/// A [`Tabs`] widget for showing a [`TabBar`]
|
||||
/// along with the tab's content.
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// # use iced_aw::{TabLabel, tabs::Tabs};
|
||||
/// # use iced_widget::Text;
|
||||
/// #
|
||||
/// #[derive(Debug, Clone)]
|
||||
/// enum Message {
|
||||
/// TabSelected(TabId),
|
||||
/// }
|
||||
///
|
||||
/// #[derive(Debug, Clone)]
|
||||
/// enum TabId {
|
||||
/// One,
|
||||
/// Two,
|
||||
/// Three,
|
||||
/// }
|
||||
///
|
||||
/// let tabs = Tabs::new(Message::TabSelected)
|
||||
/// .push(TabId::One, TabLabel::Text(String::from("One")), Text::new(String::from("One")))
|
||||
/// .push(TabId::Two, TabLabel::Text(String::from("Two")), Text::new(String::from("Two")))
|
||||
/// .push(TabId::Three, TabLabel::Text(String::from("Three")), Text::new(String::from("Three")))
|
||||
/// .set_active_tab(&TabId::Two);Theme
|
||||
/// ```
|
||||
///
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct Tabs<'a, Message, TabId, Theme = iced_widget::Theme, Renderer = iced_widget::Renderer>
|
||||
where
|
||||
Renderer: 'a + renderer::Renderer + iced_core::text::Renderer,
|
||||
Theme: Catalog,
|
||||
TabId: Eq + Clone,
|
||||
{
|
||||
/// The [`TabBar`](crate::widget::TabBar) of the [`Tabs`].
|
||||
tab_bar: TabBar<'a, Message, TabId, Theme, Renderer>,
|
||||
/// The vector containing the content of the tabs.
|
||||
children: Vec<Element<'a, Message, Theme, Renderer>>,
|
||||
/// The vector containing the indices of the tabs.
|
||||
indices: Vec<TabId>,
|
||||
/// The position of the [`TabBar`](crate::widget::TabBar).
|
||||
tab_bar_position: TabBarPosition,
|
||||
/// The position of the [`TabBar`](crate::widget::TabBar) Icon.
|
||||
tab_icon_position: Position,
|
||||
/// the width of the [`Tabs`].
|
||||
width: Length,
|
||||
/// The height of the [`Tabs`].
|
||||
height: Length,
|
||||
}
|
||||
|
||||
impl<'a, Message, TabId, Theme, Renderer> Tabs<'a, Message, TabId, Theme, Renderer>
|
||||
where
|
||||
Renderer: 'a + renderer::Renderer + iced_core::text::Renderer<Font = Font>,
|
||||
Theme: Catalog + text::Catalog,
|
||||
TabId: Eq + Clone,
|
||||
{
|
||||
/// Creates a new [`Tabs`] widget with the index of the selected tab and a
|
||||
/// specified message which will be send when a tab is selected by the user.
|
||||
///
|
||||
/// It expects:
|
||||
/// * the index of the currently active tab.
|
||||
/// * the function that will be called if a tab is selected by the user.
|
||||
/// It takes the index of the selected tab.
|
||||
pub fn new<F>(on_select: F) -> Self
|
||||
where
|
||||
F: 'static + Fn(TabId) -> Message,
|
||||
{
|
||||
Self::new_with_tabs(Vec::new(), on_select)
|
||||
}
|
||||
|
||||
/// Similar to `new` but with a given Vector of the
|
||||
/// [`TabLabel`] along with the tab's content.
|
||||
///
|
||||
/// It expects:
|
||||
/// * the index of the currently active tab.
|
||||
/// * a vector containing the [`TabLabel`]s along with the content
|
||||
/// [`Element`]s of the [`Tabs`].
|
||||
/// * the function that will be called if a tab is selected by the user.
|
||||
/// It takes the index of the selected tab.
|
||||
pub fn new_with_tabs<F>(
|
||||
tabs: impl IntoIterator<Item = (TabId, TabLabel, Element<'a, Message, Theme, Renderer>)>,
|
||||
on_select: F,
|
||||
) -> Self
|
||||
where
|
||||
F: 'static + Fn(TabId) -> Message,
|
||||
{
|
||||
let tabs = tabs.into_iter();
|
||||
let n_tabs = tabs.size_hint().0;
|
||||
|
||||
let mut tab_labels = Vec::with_capacity(n_tabs);
|
||||
let mut elements = Vec::with_capacity(n_tabs);
|
||||
let mut indices = Vec::with_capacity(n_tabs);
|
||||
|
||||
for (id, tab_label, element) in tabs {
|
||||
tab_labels.push((id.clone(), tab_label));
|
||||
indices.push(id);
|
||||
elements.push(element);
|
||||
}
|
||||
|
||||
Tabs {
|
||||
tab_bar: TabBar::with_tab_labels(tab_labels, on_select),
|
||||
children: elements,
|
||||
indices,
|
||||
tab_bar_position: TabBarPosition::Top,
|
||||
tab_icon_position: Position::Left,
|
||||
width: Length::Fill,
|
||||
height: Length::Fill,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the size of the close icon of the
|
||||
/// [`TabLabel`] of the
|
||||
/// [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn close_size(mut self, close_size: f32) -> Self {
|
||||
self.tab_bar = self.tab_bar.close_size(close_size);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the Tabs Icon render Position
|
||||
/// [`TabLabel`] of the
|
||||
/// [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn tab_icon_position(mut self, position: Position) -> Self {
|
||||
self.tab_icon_position = position;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`Tabs`].
|
||||
#[must_use]
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the font of the icons of the
|
||||
/// [`TabLabel`]s of the
|
||||
/// [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn icon_font(mut self, font: Font) -> Self {
|
||||
self.tab_bar = self.tab_bar.icon_font(font);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the icon size of the [`TabLabel`] of the
|
||||
/// [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn icon_size(mut self, icon_size: f32) -> Self {
|
||||
self.tab_bar = self.tab_bar.icon_size(icon_size);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the message that will be produced when the close icon of a tab
|
||||
/// on the [`TabBar`] is pressed.
|
||||
///
|
||||
/// Setting this enables the drawing of a close icon on the tabs.
|
||||
#[must_use]
|
||||
pub fn on_close<F>(mut self, on_close: F) -> Self
|
||||
where
|
||||
F: 'static + Fn(TabId) -> Message,
|
||||
{
|
||||
self.tab_bar = self.tab_bar.on_close(on_close);
|
||||
self
|
||||
}
|
||||
|
||||
/// Pushes a [`TabLabel`] along with the tabs
|
||||
/// content to the [`Tabs`].
|
||||
#[must_use]
|
||||
pub fn push<E>(mut self, id: TabId, tab_label: TabLabel, element: E) -> Self
|
||||
where
|
||||
E: Into<Element<'a, Message, Theme, Renderer>>,
|
||||
{
|
||||
self.tab_bar = self
|
||||
.tab_bar
|
||||
.push(id.clone(), tab_label)
|
||||
.set_position(self.tab_icon_position);
|
||||
self.children.push(element.into());
|
||||
self.indices.push(id);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the active tab of the [`Tabs`] using the ``TabId``.
|
||||
#[must_use]
|
||||
pub fn set_active_tab(mut self, id: &TabId) -> Self {
|
||||
self.tab_bar = self.tab_bar.set_active_tab(id);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the height of the [`TabBar`] of the [`Tabs`].
|
||||
#[must_use]
|
||||
pub fn tab_bar_height(mut self, height: Length) -> Self {
|
||||
self.tab_bar = self.tab_bar.height(height);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the maximum height of the [`TabBar`] of the [`Tabs`].
|
||||
#[must_use]
|
||||
pub fn tab_bar_max_height(mut self, max_height: f32) -> Self {
|
||||
self.tab_bar = self.tab_bar.max_height(max_height);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the width of the [`TabBar`] of the [`Tabs`].
|
||||
#[must_use]
|
||||
pub fn tab_bar_width(mut self, width: Length) -> Self {
|
||||
self.tab_bar = self.tab_bar.width(width);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the [`TabBarPosition`] of the [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn tab_bar_position(mut self, position: TabBarPosition) -> Self {
|
||||
self.tab_bar_position = position;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the style of the [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn tab_bar_style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
|
||||
where
|
||||
<Theme as Catalog>::Class<'a>: From<StyleFn<'a, Theme, Style>>,
|
||||
{
|
||||
self.tab_bar = self.tab_bar.style(style);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the padding of the tabs of the [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn tab_label_padding(mut self, padding: impl Into<Padding>) -> Self {
|
||||
self.tab_bar = self.tab_bar.padding(padding);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the spacing between the tabs of the
|
||||
/// [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn tab_label_spacing(mut self, spacing: impl Into<Pixels>) -> Self {
|
||||
self.tab_bar = self.tab_bar.spacing(spacing);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the font of the text of the
|
||||
/// [`TabLabel`]s of the
|
||||
/// [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn text_font(mut self, text_font: Font) -> Self {
|
||||
self.tab_bar = self.tab_bar.text_font(text_font);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the text size of the [`TabLabel`] of the
|
||||
/// [`TabBar`].
|
||||
#[must_use]
|
||||
pub fn text_size(mut self, text_size: f32) -> Self {
|
||||
self.tab_bar = self.tab_bar.text_size(text_size);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the width of the [`Tabs`].
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, TabId, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for Tabs<'_, Message, TabId, Theme, Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer + iced_core::text::Renderer<Font = Font>,
|
||||
Theme: Catalog + text::Catalog,
|
||||
TabId: Eq + Clone,
|
||||
{
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
let tabs = Tree {
|
||||
tag: Tag::stateless(),
|
||||
state: State::None,
|
||||
children: self.children.iter().map(Tree::new).collect(),
|
||||
};
|
||||
|
||||
let bar = Tree {
|
||||
tag: self.tab_bar.tag(),
|
||||
state: self.tab_bar.state(),
|
||||
children: self.tab_bar.children(),
|
||||
};
|
||||
|
||||
vec![bar, tabs]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
// we expect 2 elements to at least exist here if not lets try to reload them.
|
||||
if tree.children.len() != 2 {
|
||||
tree.children = self.children();
|
||||
}
|
||||
|
||||
if let Some(tabs) = tree.children.get_mut(1) {
|
||||
tabs.diff_children(&self.children);
|
||||
}
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size::new(self.width, self.height)
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
let tab_bar_limits = limits.width(self.width).height(Length::Fill);
|
||||
let mut tab_bar_node =
|
||||
self.tab_bar
|
||||
.layout(&mut tree.children[0], renderer, &tab_bar_limits);
|
||||
|
||||
let tab_content_limits = limits
|
||||
.width(self.width)
|
||||
.height(self.height)
|
||||
.shrink([0.0, tab_bar_node.size().height]);
|
||||
|
||||
let mut tab_content_node = if let (Some(element), Some(child)) = (
|
||||
self.children.get_mut(self.tab_bar.get_active_tab_idx()),
|
||||
tree.children.get_mut(1),
|
||||
) {
|
||||
element.as_widget_mut().layout(
|
||||
&mut child.children[self.tab_bar.get_active_tab_idx()],
|
||||
renderer,
|
||||
&tab_content_limits,
|
||||
)
|
||||
} else {
|
||||
Row::<Message, Theme, Renderer>::new()
|
||||
.width(Length::Fill)
|
||||
.height(Length::Fill)
|
||||
.layout(tree, renderer, &tab_content_limits)
|
||||
};
|
||||
|
||||
let tab_bar_bounds = tab_bar_node.bounds();
|
||||
tab_bar_node = tab_bar_node.move_to(Point::new(
|
||||
tab_bar_bounds.x,
|
||||
tab_bar_bounds.y
|
||||
+ match self.tab_bar_position {
|
||||
TabBarPosition::Top => 0.0,
|
||||
TabBarPosition::Bottom => tab_content_node.bounds().height,
|
||||
},
|
||||
));
|
||||
|
||||
let tab_content_bounds = tab_content_node.bounds();
|
||||
tab_content_node = tab_content_node.move_to(Point::new(
|
||||
tab_content_bounds.x,
|
||||
tab_content_bounds.y
|
||||
+ match self.tab_bar_position {
|
||||
TabBarPosition::Top => tab_bar_node.bounds().height,
|
||||
TabBarPosition::Bottom => 0.0,
|
||||
},
|
||||
));
|
||||
|
||||
Node::with_children(
|
||||
Size::new(
|
||||
tab_content_node.size().width,
|
||||
tab_bar_node.size().height + tab_content_node.size().height,
|
||||
),
|
||||
match self.tab_bar_position {
|
||||
TabBarPosition::Top => vec![tab_bar_node, tab_content_node],
|
||||
TabBarPosition::Bottom => vec![tab_content_node, tab_bar_node],
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let mut children = layout.children();
|
||||
let (tab_bar_layout, tab_content_layout) = match self.tab_bar_position {
|
||||
TabBarPosition::Top => {
|
||||
let tab_bar_layout = children
|
||||
.next()
|
||||
.expect("widget: Layout should have a TabBar layout at top position");
|
||||
let tab_content_layout = children
|
||||
.next()
|
||||
.expect("widget: Layout should have a tab content layout at top position");
|
||||
(tab_bar_layout, tab_content_layout)
|
||||
}
|
||||
TabBarPosition::Bottom => {
|
||||
let tab_content_layout = children
|
||||
.next()
|
||||
.expect("widget: Layout should have a tab content layout at bottom position");
|
||||
let tab_bar_layout = children
|
||||
.next()
|
||||
.expect("widget: Layout should have a TabBar layout at bottom position");
|
||||
(tab_bar_layout, tab_content_layout)
|
||||
}
|
||||
};
|
||||
|
||||
self.tab_bar.update(
|
||||
&mut Tree::empty(),
|
||||
event,
|
||||
tab_bar_layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
let idx = self.tab_bar.get_active_tab_idx();
|
||||
if let Some(element) = self.children.get_mut(idx) {
|
||||
element.as_widget_mut().update(
|
||||
&mut state.children[1].children[idx],
|
||||
event,
|
||||
tab_content_layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
// Tab bar
|
||||
let mut children = layout.children();
|
||||
let tab_bar_layout = match self.tab_bar_position {
|
||||
TabBarPosition::Top => children
|
||||
.next()
|
||||
.expect("widget: There should be a TabBar at the top position"),
|
||||
TabBarPosition::Bottom => children
|
||||
.last()
|
||||
.expect("widget: There should be a TabBar at the bottom position"),
|
||||
};
|
||||
|
||||
let mut mouse_interaction = mouse::Interaction::default();
|
||||
let new_mouse_interaction = self.tab_bar.mouse_interaction(
|
||||
&Tree::empty(),
|
||||
tab_bar_layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
);
|
||||
|
||||
if new_mouse_interaction > mouse_interaction {
|
||||
mouse_interaction = new_mouse_interaction;
|
||||
}
|
||||
|
||||
// Tab content
|
||||
let mut children = layout.children();
|
||||
let tab_content_layout = match self.tab_bar_position {
|
||||
TabBarPosition::Top => children
|
||||
.last()
|
||||
.expect("Graphics: There should be a TabBar at the top position"),
|
||||
TabBarPosition::Bottom => children
|
||||
.next()
|
||||
.expect("Graphics: There should be a TabBar at the bottom position"),
|
||||
};
|
||||
let idx = self.tab_bar.get_active_tab_idx();
|
||||
if let Some(element) = self.children.get(idx) {
|
||||
let new_mouse_interaction = element.as_widget().mouse_interaction(
|
||||
&state.children[1].children[idx],
|
||||
tab_content_layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
);
|
||||
|
||||
if new_mouse_interaction > mouse_interaction {
|
||||
mouse_interaction = new_mouse_interaction;
|
||||
}
|
||||
}
|
||||
|
||||
mouse_interaction
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let mut children = layout.children();
|
||||
let tab_bar_layout = match self.tab_bar_position {
|
||||
TabBarPosition::Top => children
|
||||
.next()
|
||||
.expect("widget: There should be a TabBar at the top position"),
|
||||
TabBarPosition::Bottom => children
|
||||
.last()
|
||||
.expect("widget: There should be a TabBar at the bottom position"),
|
||||
};
|
||||
|
||||
self.tab_bar.draw(
|
||||
&Tree::empty(),
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
tab_bar_layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
|
||||
let mut children = layout.children();
|
||||
|
||||
let tab_content_layout = match self.tab_bar_position {
|
||||
TabBarPosition::Top => children
|
||||
.last()
|
||||
.expect("Graphics: There should be a TabBar at the top position"),
|
||||
TabBarPosition::Bottom => children
|
||||
.next()
|
||||
.expect("Graphics: There should be a TabBar at the bottom position"),
|
||||
};
|
||||
|
||||
let idx = self.tab_bar.get_active_tab_idx();
|
||||
if let Some(element) = self.children.get(idx) {
|
||||
element.as_widget().draw(
|
||||
&state.children[1].children[idx],
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
tab_content_layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
state: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
let layout = match self.tab_bar_position {
|
||||
TabBarPosition::Top => layout.children().nth(1),
|
||||
TabBarPosition::Bottom => layout.children().next(),
|
||||
};
|
||||
|
||||
layout.and_then(|layout| {
|
||||
let idx = self.tab_bar.get_active_tab_idx();
|
||||
self.children
|
||||
.get_mut(idx)
|
||||
.map(Element::as_widget_mut)
|
||||
.and_then(|w| {
|
||||
w.overlay(
|
||||
&mut state.children[1].children[idx],
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
let active_tab = self.tab_bar.get_active_tab_idx();
|
||||
operation.container(None, layout.bounds());
|
||||
operation.traverse(&mut |operation| {
|
||||
self.children[active_tab].as_widget_mut().operate(
|
||||
&mut tree.children[1].children[active_tab],
|
||||
layout
|
||||
.children()
|
||||
.nth(1)
|
||||
.expect("TabBar is 0th child, contents are 1st node"),
|
||||
renderer,
|
||||
operation,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, TabId, Theme, Renderer> From<Tabs<'a, Message, TabId, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: 'a + renderer::Renderer + iced_core::text::Renderer<Font = Font>,
|
||||
Theme: 'a + Catalog + text::Catalog,
|
||||
Message: 'a,
|
||||
TabId: 'a + Eq + Clone,
|
||||
{
|
||||
fn from(tabs: Tabs<'a, Message, TabId, Theme, Renderer>) -> Self {
|
||||
Element::new(tabs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! A [`TabBarPosition`] for defining the position of a [`TabBar`](crate::widget::tab_bar::TabBar).
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: tabs*
|
||||
|
||||
/// A [`TabBarPosition`] for defining the position of a [`TabBar`](crate::widget::tab_bar::TabBar).
|
||||
#[derive(Clone, Hash)]
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub enum TabBarPosition {
|
||||
/// A [`TabBarPosition`] for placing the [`TabBar`](crate::widget::tab_bar::TabBar)
|
||||
/// on top of its content.
|
||||
Top,
|
||||
|
||||
/// A [`TabBarPosition`] for placing the [`TabBar`](crate::widget::tab_bar::TabBar)
|
||||
/// on bottom of its content.
|
||||
Bottom,
|
||||
}
|
||||
+758
@@ -0,0 +1,758 @@
|
||||
//! Use a time picker as an input element for picking times.
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: `time_picker`*
|
||||
|
||||
use super::overlay::time_picker::{self, TimePickerOverlay, TimePickerOverlayButtons};
|
||||
|
||||
use chrono::Local;
|
||||
use iced_core::{
|
||||
Clipboard, Element, Event, Layout, Length, Point, Rectangle, Shell, Size, Vector, Widget,
|
||||
layout::{Limits, Node},
|
||||
mouse::{self, Cursor},
|
||||
overlay, renderer,
|
||||
widget::{
|
||||
self,
|
||||
tree::{self, Tag, Tree},
|
||||
},
|
||||
};
|
||||
use iced_widget::{Renderer, button, container, text};
|
||||
|
||||
pub use crate::{
|
||||
core::time::{Period, Time},
|
||||
style::{
|
||||
Status, StyleFn,
|
||||
time_picker::{Catalog, Style},
|
||||
},
|
||||
};
|
||||
|
||||
//TODO: Remove ignore when Null is updated. Temp fix for Test runs
|
||||
/// An input element for picking times.
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// # use iced_aw::{TimePicker, time_picker};
|
||||
/// # use iced_widget::{button, Button, Text};
|
||||
/// #
|
||||
/// #[derive(Clone, Debug)]
|
||||
/// enum Message {
|
||||
/// Open,
|
||||
/// Cancel,
|
||||
/// Submit(time_picker::Time),
|
||||
/// }
|
||||
///
|
||||
/// let time_picker = TimePicker::new(
|
||||
/// true,
|
||||
/// time_picker::Time::now_hms(true),
|
||||
/// Button::new(Text::new("Pick time"))
|
||||
/// .on_press(Message::Open),
|
||||
/// Message::Cancel,
|
||||
/// Message::Submit,
|
||||
/// );
|
||||
/// ```
|
||||
#[allow(missing_debug_implementations)]
|
||||
pub struct TimePicker<'a, Message, Theme>
|
||||
where
|
||||
Message: Clone,
|
||||
Theme: Catalog + button::Catalog,
|
||||
{
|
||||
/// Show the picker.
|
||||
show_picker: bool,
|
||||
/// The time to show.
|
||||
time: Time,
|
||||
/// The underlying element.
|
||||
underlay: Element<'a, Message, Theme, Renderer>,
|
||||
/// The message that is send if the cancel button of the [`TimePickerOverlay`] is pressed.
|
||||
on_cancel: Message,
|
||||
/// The function that produces a message when the submit button of the [`TimePickerOverlay`] is pressed.
|
||||
on_submit: Box<dyn Fn(Time) -> Message>,
|
||||
/// The style of the [`TimePickerOverlay`].
|
||||
class: <Theme as Catalog>::Class<'a>,
|
||||
/// The buttons of the overlay.
|
||||
overlay_state: Element<'a, Message, Theme, Renderer>,
|
||||
/// Toggle the use of the 24h clock of the [`TimePickerOverlay`].
|
||||
use_24h: bool,
|
||||
/// Toggle the use of the seconds of the [`TimePickerOverlay`].
|
||||
show_seconds: bool,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme> TimePicker<'a, Message, Theme>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Theme: 'a + Catalog + button::Catalog + text::Catalog,
|
||||
{
|
||||
/// Creates a new [`TimePicker`] wrapping around the given underlay.
|
||||
///
|
||||
/// It expects:
|
||||
/// * if the overlay of the time picker is visible.
|
||||
/// * the initial time to show.
|
||||
/// * the underlay [`Element`] on which this [`TimePicker`]
|
||||
/// will be wrapped around.
|
||||
/// * a message that will be send when the cancel button of the [`TimePicker`] is pressed.
|
||||
/// * a function that will be called when the submit button of the [`TimePicker`]
|
||||
/// is pressed, which takes the picked [`Time`] value.
|
||||
pub fn new<U, F>(
|
||||
show_picker: bool,
|
||||
time: impl Into<Time>,
|
||||
underlay: U,
|
||||
on_cancel: Message,
|
||||
on_submit: F,
|
||||
) -> Self
|
||||
where
|
||||
U: Into<Element<'a, Message, Theme, Renderer>>,
|
||||
F: 'static + Fn(Time) -> Message,
|
||||
{
|
||||
Self {
|
||||
show_picker,
|
||||
time: time.into(),
|
||||
underlay: underlay.into(),
|
||||
on_cancel,
|
||||
on_submit: Box::new(on_submit),
|
||||
class: <Theme as Catalog>::default(),
|
||||
overlay_state: TimePickerOverlayButtons::default().into(),
|
||||
use_24h: false,
|
||||
show_seconds: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Enables the picker to also pick seconds.
|
||||
#[must_use]
|
||||
pub fn show_seconds(mut self) -> Self {
|
||||
self.show_seconds = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the style of the [`TimePicker`].
|
||||
#[must_use]
|
||||
pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
|
||||
where
|
||||
<Theme as Catalog>::Class<'a>: From<StyleFn<'a, Theme, Style>>,
|
||||
{
|
||||
self.class = (Box::new(style) as StyleFn<'a, Theme, Style>).into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Use 24 hour format instead of AM/PM.
|
||||
#[must_use]
|
||||
pub fn use_24h(mut self) -> Self {
|
||||
self.use_24h = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the class of the input of the [`TimePicker`].
|
||||
#[must_use]
|
||||
pub fn class(mut self, class: impl Into<<Theme as Catalog>::Class<'a>>) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The state of the [`TimePicker`] / [`TimePickerOverlay`].
|
||||
#[derive(Debug)]
|
||||
pub struct State {
|
||||
/// The state of the overlay.
|
||||
pub(crate) overlay_state: time_picker::State,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Creates a new [`State`] with the current time.
|
||||
#[must_use]
|
||||
pub fn now() -> Self {
|
||||
Self {
|
||||
overlay_state: time_picker::State::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new [`State`] with the given time.
|
||||
#[must_use]
|
||||
pub fn new(time: Time, use_24h: bool, show_seconds: bool) -> Self {
|
||||
Self {
|
||||
overlay_state: time_picker::State::new(time, use_24h, show_seconds),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the time of the state to the current time.
|
||||
pub fn reset(&mut self) {
|
||||
self.overlay_state.clock_cache.clear();
|
||||
self.overlay_state.time = Local::now().naive_local().time();
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme> Widget<Message, Theme, Renderer> for TimePicker<'_, Message, Theme>
|
||||
where
|
||||
Message: 'static + Clone,
|
||||
Theme: Catalog + button::Catalog + text::Catalog + container::Catalog,
|
||||
{
|
||||
fn tag(&self) -> Tag {
|
||||
Tag::of::<State>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::new(State::new(self.time, self.use_24h, self.show_seconds))
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
vec![Tree::new(&self.underlay), Tree::new(&self.overlay_state)]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(&[&self.underlay, &self.overlay_state]);
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
self.underlay.as_widget().size()
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
self.underlay
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree.children[0], renderer, limits)
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.underlay.as_widget_mut().update(
|
||||
&mut state.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.underlay.as_widget().mouse_interaction(
|
||||
&state.children[0],
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn widget::Operation<()>,
|
||||
) {
|
||||
self.underlay
|
||||
.as_widget_mut()
|
||||
.operate(&mut state.children[0], layout, renderer, operation);
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.underlay.as_widget().draw(
|
||||
&tree.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
tree: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
let picker_state: &mut State = tree.state.downcast_mut();
|
||||
|
||||
if !self.show_picker {
|
||||
return self.underlay.as_widget_mut().overlay(
|
||||
&mut tree.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
);
|
||||
}
|
||||
|
||||
let bounds = layout.bounds();
|
||||
let position = Point::new(bounds.center_x(), bounds.center_y());
|
||||
|
||||
Some(
|
||||
TimePickerOverlay::new(
|
||||
picker_state,
|
||||
self.on_cancel.clone(),
|
||||
&self.on_submit,
|
||||
position,
|
||||
&self.class,
|
||||
&mut tree.children[1],
|
||||
*viewport,
|
||||
)
|
||||
.overlay(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme> From<TimePicker<'a, Message, Theme>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'static + Clone,
|
||||
Theme: 'a + Catalog + button::Catalog + text::Catalog + container::Catalog,
|
||||
{
|
||||
fn from(time_picker: TimePicker<'a, Message, Theme>) -> Self {
|
||||
Element::new(time_picker)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::{NaiveTime, Timelike};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum TestMessage {
|
||||
Cancel,
|
||||
#[allow(dead_code)]
|
||||
Submit(Time),
|
||||
}
|
||||
|
||||
type TestTimePicker<'a> = TimePicker<'a, TestMessage, iced_widget::Theme>;
|
||||
|
||||
#[test]
|
||||
fn state_new_creates_state_with_time() {
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
let state = State::new(time, true, false);
|
||||
|
||||
assert_eq!(state.overlay_state.time.hour(), 14);
|
||||
assert_eq!(state.overlay_state.time.minute(), 30);
|
||||
assert!(state.overlay_state.use_24h);
|
||||
assert!(!state.overlay_state.show_seconds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_new_with_seconds() {
|
||||
let time = Time::Hms {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
second: 45,
|
||||
period: Period::H24,
|
||||
};
|
||||
let state = State::new(time, true, true);
|
||||
|
||||
assert_eq!(state.overlay_state.time.hour(), 14);
|
||||
assert_eq!(state.overlay_state.time.minute(), 30);
|
||||
assert_eq!(state.overlay_state.time.second(), 45);
|
||||
assert!(state.overlay_state.show_seconds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_new_with_12h_format() {
|
||||
let time = Time::Hm {
|
||||
hour: 2,
|
||||
minute: 30,
|
||||
period: Period::Pm,
|
||||
};
|
||||
let state = State::new(time, false, false);
|
||||
|
||||
assert_eq!(state.overlay_state.time.hour(), 14); // 2 PM = 14:00 in 24h
|
||||
assert_eq!(state.overlay_state.time.minute(), 30);
|
||||
assert!(!state.overlay_state.use_24h);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_now_creates_state() {
|
||||
let state = State::now();
|
||||
// Just verify it was created successfully and has valid time
|
||||
assert!(state.overlay_state.time.hour() < 24);
|
||||
assert!(state.overlay_state.time.minute() < 60);
|
||||
assert!(state.overlay_state.time.second() < 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn state_reset_updates_to_current_time() {
|
||||
let old_time = Time::Hm {
|
||||
hour: 1,
|
||||
minute: 1,
|
||||
period: Period::H24,
|
||||
};
|
||||
let mut state = State::new(old_time, true, false);
|
||||
|
||||
state.reset();
|
||||
|
||||
// After reset, the time should be current
|
||||
// We can't easily verify the exact time since it's based on Local::now()
|
||||
// but we can verify the state is still valid
|
||||
assert!(state.overlay_state.time.hour() < 24);
|
||||
assert!(state.overlay_state.time.minute() < 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_picker_new_creates_instance() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a time");
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
let time_picker = TestTimePicker::new(
|
||||
false,
|
||||
time,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
assert!(!time_picker.show_picker);
|
||||
match time_picker.time {
|
||||
Time::Hm { hour, minute, .. } => {
|
||||
assert_eq!(hour, 14);
|
||||
assert_eq!(minute, 30);
|
||||
}
|
||||
#[allow(clippy::panic)]
|
||||
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
|
||||
}
|
||||
assert!(!time_picker.use_24h); // Default is 12h
|
||||
assert!(!time_picker.show_seconds); // Default is no seconds
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_picker_show_picker_true() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a time");
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
let time_picker = TestTimePicker::new(
|
||||
true,
|
||||
time,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
assert!(time_picker.show_picker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_picker_use_24h_sets_value() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a time");
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
let time_picker = TestTimePicker::new(
|
||||
false,
|
||||
time,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
)
|
||||
.use_24h();
|
||||
|
||||
assert!(time_picker.use_24h);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_picker_show_seconds_sets_value() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a time");
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
let time_picker = TestTimePicker::new(
|
||||
false,
|
||||
time,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
)
|
||||
.show_seconds();
|
||||
|
||||
assert!(time_picker.show_seconds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_picker_chained_configuration() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a time");
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
let time_picker = TestTimePicker::new(
|
||||
true,
|
||||
time,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
)
|
||||
.use_24h()
|
||||
.show_seconds();
|
||||
|
||||
assert!(time_picker.show_picker);
|
||||
assert!(time_picker.use_24h);
|
||||
assert!(time_picker.show_seconds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_picker_tag_returns_state_tag() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a time");
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
let time_picker = TestTimePicker::new(
|
||||
false,
|
||||
time,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
let tag = Widget::<TestMessage, iced_widget::Theme, Renderer>::tag(&time_picker);
|
||||
assert_eq!(tag, widget::tree::Tag::of::<State>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_picker_has_two_children() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a time");
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
let time_picker = TestTimePicker::new(
|
||||
false,
|
||||
time,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
let children = Widget::<TestMessage, iced_widget::Theme, Renderer>::children(&time_picker);
|
||||
assert_eq!(children.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_picker_size_matches_underlay() {
|
||||
let underlay = iced_widget::text::Text::new("Pick a time");
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
let time_picker = TestTimePicker::new(
|
||||
false,
|
||||
time,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
let size = Widget::<TestMessage, iced_widget::Theme, Renderer>::size(&time_picker);
|
||||
assert_eq!(size.width, Length::Shrink);
|
||||
assert_eq!(size.height, Length::Shrink);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_hm_creates_correct_time() {
|
||||
let time = Time::Hm {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
match time {
|
||||
Time::Hm { hour, minute, .. } => {
|
||||
assert_eq!(hour, 14);
|
||||
assert_eq!(minute, 30);
|
||||
}
|
||||
#[allow(clippy::panic)]
|
||||
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_hms_creates_correct_time() {
|
||||
let time = Time::Hms {
|
||||
hour: 14,
|
||||
minute: 30,
|
||||
second: 45,
|
||||
period: Period::H24,
|
||||
};
|
||||
|
||||
match time {
|
||||
Time::Hms {
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(hour, 14);
|
||||
assert_eq!(minute, 30);
|
||||
assert_eq!(second, 45);
|
||||
}
|
||||
#[allow(clippy::panic)]
|
||||
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_12h_am_conversion() {
|
||||
let time = Time::Hm {
|
||||
hour: 9,
|
||||
minute: 30,
|
||||
period: Period::Am,
|
||||
};
|
||||
|
||||
let naive_time: NaiveTime = time.into();
|
||||
assert_eq!(naive_time.hour(), 9); // 9 AM = 9:00
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_12h_pm_conversion() {
|
||||
let time = Time::Hm {
|
||||
hour: 2,
|
||||
minute: 30,
|
||||
period: Period::Pm,
|
||||
};
|
||||
|
||||
let naive_time: NaiveTime = time.into();
|
||||
assert_eq!(naive_time.hour(), 14); // 2 PM = 14:00
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_12h_noon_conversion() {
|
||||
let time = Time::Hm {
|
||||
hour: 12,
|
||||
minute: 0,
|
||||
period: Period::Pm,
|
||||
};
|
||||
|
||||
let naive_time: NaiveTime = time.into();
|
||||
assert_eq!(naive_time.hour(), 12); // 12 PM = noon = 12:00
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_12h_midnight_conversion() {
|
||||
let time = Time::Hm {
|
||||
hour: 12,
|
||||
minute: 0,
|
||||
period: Period::Am,
|
||||
};
|
||||
|
||||
let naive_time: NaiveTime = time.into();
|
||||
assert_eq!(naive_time.hour(), 0); // 12 AM = midnight = 00:00
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_now_hm_creates_current_time() {
|
||||
let time = Time::now_hm(true);
|
||||
match time {
|
||||
Time::Hm { hour, minute, .. } => {
|
||||
assert!(hour < 24);
|
||||
assert!(minute < 60);
|
||||
}
|
||||
#[allow(clippy::panic)]
|
||||
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_now_hms_creates_current_time() {
|
||||
let time = Time::now_hms(true);
|
||||
match time {
|
||||
Time::Hms {
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
..
|
||||
} => {
|
||||
assert!(hour < 24);
|
||||
assert!(minute < 60);
|
||||
assert!(second < 60);
|
||||
}
|
||||
#[allow(clippy::panic)]
|
||||
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_times_with_24h_format() {
|
||||
let test_times = [
|
||||
(0, 0, Period::H24), // Midnight
|
||||
(6, 30, Period::H24), // Morning
|
||||
(12, 0, Period::H24), // Noon
|
||||
(18, 45, Period::H24), // Evening
|
||||
(23, 59, Period::H24), // End of day
|
||||
];
|
||||
|
||||
for (expected_hour, expected_minute, period) in test_times {
|
||||
let time = Time::Hm {
|
||||
hour: expected_hour,
|
||||
minute: expected_minute,
|
||||
period,
|
||||
};
|
||||
let underlay = iced_widget::text::Text::new("Pick a time");
|
||||
|
||||
let time_picker = TestTimePicker::new(
|
||||
false,
|
||||
time,
|
||||
underlay,
|
||||
TestMessage::Cancel,
|
||||
TestMessage::Submit,
|
||||
);
|
||||
|
||||
match time_picker.time {
|
||||
Time::Hm { hour, minute, .. } => {
|
||||
assert_eq!(hour, expected_hour);
|
||||
assert_eq!(minute, expected_minute);
|
||||
}
|
||||
#[allow(clippy::panic)]
|
||||
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+670
@@ -0,0 +1,670 @@
|
||||
//! Display fields that can only be filled with a specific type.
|
||||
//!
|
||||
//! *This API requires the following crate features to be activated: `typed_input`*
|
||||
|
||||
use iced_core::layout::{Layout, Limits, Node};
|
||||
use iced_core::mouse::{self, Cursor};
|
||||
use iced_core::widget::{
|
||||
Operation, Tree, Widget,
|
||||
tree::{State, Tag},
|
||||
};
|
||||
use iced_core::{Clipboard, Shell, widget};
|
||||
use iced_core::{Element, Length, Padding, Pixels, Rectangle};
|
||||
use iced_core::{Event, Size};
|
||||
use iced_widget::text_input::{self, TextInput};
|
||||
|
||||
use std::{fmt::Display, str::FromStr};
|
||||
|
||||
/// The default padding
|
||||
const DEFAULT_PADDING: Padding = Padding::new(5.0);
|
||||
|
||||
/// A field that can only be filled with a specific type.
|
||||
///
|
||||
/// # Example
|
||||
/// ```ignore
|
||||
/// # use iced_aw::TypedInput;
|
||||
/// #
|
||||
/// #[derive(Debug, Clone)]
|
||||
/// enum Message {
|
||||
/// TypedInputChanged(u32),
|
||||
/// }
|
||||
///
|
||||
/// let value = 12;
|
||||
///
|
||||
/// let input = TypedInput::new(
|
||||
/// value,
|
||||
/// Message::TypedInputChanged,
|
||||
/// );
|
||||
/// ```
|
||||
pub struct TypedInput<'a, T, Message, Theme = iced_widget::Theme, Renderer = iced_widget::Renderer>
|
||||
where
|
||||
Renderer: iced_core::text::Renderer,
|
||||
Theme: text_input::Catalog,
|
||||
{
|
||||
/// The current value of the [`TypedInput`].
|
||||
value: T,
|
||||
/// The underlying element of the [`TypedInput`].
|
||||
text_input: text_input::TextInput<'a, InternalMessage, Theme, Renderer>,
|
||||
text: String,
|
||||
/// The ``on_change`` event of the [`TypedInput`].
|
||||
on_change: Option<Box<dyn 'a + Fn(T) -> Message>>,
|
||||
/// The ``on_submit`` event of the [`TypedInput`].
|
||||
#[allow(clippy::type_complexity)]
|
||||
on_submit: Option<Box<dyn 'a + Fn(Result<T, String>) -> Message>>,
|
||||
/// The ``on_paste`` event of the [`TypedInput`]
|
||||
on_paste: Option<Box<dyn 'a + Fn(T) -> Message>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[allow(clippy::enum_variant_names)]
|
||||
enum InternalMessage {
|
||||
OnChange(String),
|
||||
OnSubmit,
|
||||
OnPaste(String),
|
||||
}
|
||||
|
||||
impl<'a, T, Message, Theme, Renderer> TypedInput<'a, T, Message, Theme, Renderer>
|
||||
where
|
||||
T: Display + FromStr,
|
||||
Message: Clone,
|
||||
Renderer: iced_core::text::Renderer,
|
||||
Theme: text_input::Catalog,
|
||||
{
|
||||
/// Creates a new [`TypedInput`].
|
||||
///
|
||||
/// It expects:
|
||||
/// - the current value
|
||||
/// - a function that produces a message when the [`TypedInput`] changes
|
||||
#[must_use]
|
||||
pub fn new(placeholder: &str, value: &T) -> Self
|
||||
where
|
||||
T: 'a + Clone,
|
||||
{
|
||||
let padding = DEFAULT_PADDING;
|
||||
|
||||
Self {
|
||||
value: value.clone(),
|
||||
text_input: text_input::TextInput::new(placeholder, format!("{value}").as_str())
|
||||
.padding(padding)
|
||||
.width(Length::Fixed(127.0))
|
||||
.class(<Theme as text_input::Catalog>::default()),
|
||||
text: value.to_string(),
|
||||
on_change: None,
|
||||
on_submit: None,
|
||||
on_paste: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the [Id](widget::Id) of the internal [`TextInput`]
|
||||
#[must_use]
|
||||
pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
|
||||
self.text_input = self.text_input.id(id);
|
||||
self
|
||||
}
|
||||
|
||||
/// Convert the [`TypedInput`] into a secure password input
|
||||
#[must_use]
|
||||
pub fn secure(mut self, is_secure: bool) -> Self {
|
||||
self.text_input = self.text_input.secure(is_secure);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the message that should be produced when some valid text is typed into [`TypedInput`]
|
||||
///
|
||||
/// If neither this method nor [`on_submit`](Self::on_submit) is called, the [`TypedInput`] will be disabled
|
||||
#[must_use]
|
||||
pub fn on_input<F>(mut self, callback: F) -> Self
|
||||
where
|
||||
F: 'a + Fn(T) -> Message,
|
||||
{
|
||||
self.text_input = self.text_input.on_input(InternalMessage::OnChange);
|
||||
self.on_change = Some(Box::new(callback));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the message that should be produced when some text is typed into the [`TypedInput`], if `Some`.
|
||||
///
|
||||
/// If this is `None`, and there is no [`on_submit`](Self::on_submit) callback, the [`TypedInput`] will be disabled.
|
||||
#[must_use]
|
||||
pub fn on_input_maybe<F>(mut self, callback: Option<F>) -> Self
|
||||
where
|
||||
F: 'a + Fn(T) -> Message,
|
||||
{
|
||||
if let Some(callback) = callback {
|
||||
self.text_input = self.text_input.on_input(InternalMessage::OnChange);
|
||||
self.on_change = Some(Box::new(callback));
|
||||
} else {
|
||||
if self.on_submit.is_none() {
|
||||
// Used to give a proper type to None, maybe someone can find a better way
|
||||
#[allow(unused_assignments)]
|
||||
let mut f = Some(InternalMessage::OnChange);
|
||||
f = None;
|
||||
self.text_input = self.text_input.on_input_maybe(f);
|
||||
}
|
||||
self.on_change = None;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the message that should be produced when the [`TypedtInput`] is
|
||||
/// focused and the enter key is pressed.
|
||||
///
|
||||
/// If neither this method nor [`on_input`](Self::on_input) is called, the [`TypedInput`] will be disabled
|
||||
#[must_use]
|
||||
pub fn on_submit<F>(mut self, callback: F) -> Self
|
||||
where
|
||||
F: 'a + Fn(Result<T, String>) -> Message,
|
||||
{
|
||||
self.text_input = self
|
||||
.text_input
|
||||
.on_input(InternalMessage::OnChange)
|
||||
.on_submit(InternalMessage::OnSubmit);
|
||||
self.on_submit = Some(Box::new(callback));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the message that should be produced when the [`TypedtInput`] is
|
||||
/// focused and the enter key is pressed, if `Some`.
|
||||
///
|
||||
/// If this is `None`, and there is no [`on_change`](Self::on_input) callback, the [`TypedInput`] will be disabled.
|
||||
#[must_use]
|
||||
pub fn on_submit_maybe<F>(mut self, callback: Option<F>) -> Self
|
||||
where
|
||||
F: 'a + Fn(Result<T, String>) -> Message,
|
||||
{
|
||||
if let Some(callback) = callback {
|
||||
self.text_input = self
|
||||
.text_input
|
||||
.on_input(InternalMessage::OnChange)
|
||||
.on_submit(InternalMessage::OnSubmit);
|
||||
self.on_submit = Some(Box::new(callback));
|
||||
} else {
|
||||
if self.on_change.is_none() {
|
||||
// Used to give a proper type to None, maybe someone can find a better way
|
||||
#[allow(unused_assignments)]
|
||||
let mut f = Some(InternalMessage::OnChange);
|
||||
f = None;
|
||||
self.text_input = self.text_input.on_input_maybe(f);
|
||||
}
|
||||
// Used to give a proper type to None, maybe someone can find a better way
|
||||
#[allow(unused_assignments)]
|
||||
let mut f = Some(InternalMessage::OnSubmit);
|
||||
f = None;
|
||||
self.text_input = self.text_input.on_submit_maybe(f);
|
||||
self.on_change = None;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the message that should be produced when some text is pasted into the [`TypedInput`], resulting in a valid value
|
||||
#[must_use]
|
||||
pub fn on_paste<F>(mut self, callback: F) -> Self
|
||||
where
|
||||
F: 'a + Fn(T) -> Message,
|
||||
{
|
||||
self.text_input = self.text_input.on_paste(InternalMessage::OnPaste);
|
||||
self.on_paste = Some(Box::new(callback));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the message that should be produced when some text is pasted into the [`TypedInput`], resulting in a valid value, if `Some`
|
||||
#[must_use]
|
||||
pub fn on_paste_maybe<F>(mut self, callback: Option<F>) -> Self
|
||||
where
|
||||
F: 'a + Fn(T) -> Message,
|
||||
{
|
||||
if let Some(callback) = callback {
|
||||
self.text_input = self.text_input.on_paste(InternalMessage::OnPaste);
|
||||
self.on_paste = Some(Box::new(callback));
|
||||
} else {
|
||||
// Used to give a proper type to None, maybe someone can find a better way
|
||||
#[allow(unused_assignments)]
|
||||
let mut f = Some(InternalMessage::OnPaste);
|
||||
f = None;
|
||||
self.text_input = self.text_input.on_paste_maybe(f);
|
||||
self.on_paste = None;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the [Font](iced_core::text::Renderer::Font) of the [`TypedInput`].
|
||||
#[must_use]
|
||||
pub fn font(mut self, font: Renderer::Font) -> Self {
|
||||
self.text_input = self.text_input.font(font);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the [Icon](iced_widget::text_input::Icon) of the [`TypedInput`]
|
||||
#[must_use]
|
||||
pub fn icon(mut self, icon: iced_widget::text_input::Icon<Renderer::Font>) -> Self {
|
||||
self.text_input = self.text_input.icon(icon);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the width of the [`TypedInput`].
|
||||
#[must_use]
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.text_input = self.text_input.width(width);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the padding of the [`TypedInput`].
|
||||
#[must_use]
|
||||
pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
|
||||
self.text_input = self.text_input.padding(padding);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the text size of the [`TypedInput`].
|
||||
#[must_use]
|
||||
pub fn size(mut self, size: impl Into<Pixels>) -> Self {
|
||||
self.text_input = self.text_input.size(size);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the [`text::LineHeight`](iced_widget::text::LineHeight) of the [`TypedInput`].
|
||||
#[must_use]
|
||||
pub fn line_height(mut self, line_height: impl Into<iced_widget::text::LineHeight>) -> Self {
|
||||
self.text_input = self.text_input.line_height(line_height);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the horizontal alignment of the [`TypedInput`].
|
||||
#[must_use]
|
||||
pub fn align_x(mut self, alignment: impl Into<iced_core::alignment::Horizontal>) -> Self {
|
||||
self.text_input = self.text_input.align_x(alignment);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the style of the input of the [`TypedInput`].
|
||||
#[must_use]
|
||||
pub fn style(
|
||||
mut self,
|
||||
style: impl Fn(&Theme, text_input::Status) -> text_input::Style + 'a,
|
||||
) -> Self
|
||||
where
|
||||
<Theme as text_input::Catalog>::Class<'a>: From<text_input::StyleFn<'a, Theme>>,
|
||||
{
|
||||
self.text_input = self.text_input.style(style);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the class of the input of the [`TypedInput`].
|
||||
#[must_use]
|
||||
pub fn class(mut self, class: impl Into<<Theme as text_input::Catalog>::Class<'a>>) -> Self {
|
||||
self.text_input = self.text_input.class(class);
|
||||
self
|
||||
}
|
||||
|
||||
/// Gets the current text of the [`TypedInput`].
|
||||
pub fn text(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for TypedInput<'a, T, Message, Theme, Renderer>
|
||||
where
|
||||
T: Display + FromStr + Clone + PartialEq,
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + iced_core::text::Renderer,
|
||||
Theme: text_input::Catalog,
|
||||
{
|
||||
fn tag(&self) -> Tag {
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::tag(&self.text_input)
|
||||
}
|
||||
fn state(&self) -> State {
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::state(&self.text_input)
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::children(&self.text_input)
|
||||
}
|
||||
|
||||
fn diff(&self, state: &mut Tree) {
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::diff(&self.text_input, state);
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::size(&self.text_input)
|
||||
}
|
||||
|
||||
fn layout(&mut self, state: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::layout(
|
||||
&mut self.text_input,
|
||||
state,
|
||||
renderer,
|
||||
limits,
|
||||
)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
state: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &iced_core::renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::draw(
|
||||
&self.text_input,
|
||||
state,
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
state: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::mouse_interaction(
|
||||
&self.text_input,
|
||||
state,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation<()>,
|
||||
) {
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::operate(
|
||||
&mut self.text_input,
|
||||
state,
|
||||
layout,
|
||||
renderer,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
|
||||
fn update(
|
||||
&mut self,
|
||||
state: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let mut messages = Vec::new();
|
||||
let mut sub_shell = Shell::new(&mut messages);
|
||||
self.text_input.update(
|
||||
state,
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
&mut sub_shell,
|
||||
viewport,
|
||||
);
|
||||
|
||||
shell.request_redraw_at(sub_shell.redraw_request());
|
||||
|
||||
if sub_shell.is_layout_invalid() {
|
||||
shell.invalidate_layout();
|
||||
}
|
||||
if sub_shell.are_widgets_invalid() {
|
||||
shell.invalidate_widgets();
|
||||
}
|
||||
|
||||
for message in messages {
|
||||
match message {
|
||||
InternalMessage::OnChange(value) => {
|
||||
self.text = value;
|
||||
|
||||
if let Ok(value) = T::from_str(&self.text)
|
||||
&& self.value != value
|
||||
{
|
||||
self.value = value.clone();
|
||||
if let Some(on_change) = &self.on_change {
|
||||
shell.publish(on_change(value));
|
||||
}
|
||||
}
|
||||
|
||||
shell.invalidate_layout();
|
||||
}
|
||||
InternalMessage::OnSubmit => {
|
||||
if let Some(on_submit) = &self.on_submit {
|
||||
let value = match T::from_str(&self.text) {
|
||||
Ok(v) => Ok(v),
|
||||
Err(_) => Err(self.text.clone()),
|
||||
};
|
||||
shell.publish(on_submit(value));
|
||||
}
|
||||
|
||||
shell.invalidate_layout();
|
||||
}
|
||||
InternalMessage::OnPaste(value) => {
|
||||
self.text = value;
|
||||
|
||||
if let Ok(value) = T::from_str(&self.text)
|
||||
&& self.value != value
|
||||
{
|
||||
self.value = value.clone();
|
||||
if let Some(on_paste) = &self.on_paste {
|
||||
shell.publish(on_paste(value));
|
||||
}
|
||||
}
|
||||
|
||||
shell.invalidate_layout();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, Message, Theme, Renderer> From<TypedInput<'a, T, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
T: 'a + Display + FromStr + Clone + PartialEq,
|
||||
Message: 'a + Clone,
|
||||
Renderer: 'a + iced_core::text::Renderer,
|
||||
Theme: 'a + text_input::Catalog,
|
||||
{
|
||||
fn from(typed_input: TypedInput<'a, T, Message, Theme, Renderer>) -> Self {
|
||||
Element::new(typed_input)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use iced_widget::Renderer;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum TestMessage {
|
||||
Changed(u32),
|
||||
Submit(Result<u32, String>),
|
||||
Paste(u32),
|
||||
}
|
||||
|
||||
type TestTypedInput<'a> = TypedInput<'a, u32, TestMessage, iced_widget::Theme, Renderer>;
|
||||
|
||||
#[test]
|
||||
fn typed_input_new_creates_instance() {
|
||||
let value = 42u32;
|
||||
let input = TestTypedInput::new("Enter a number", &value);
|
||||
|
||||
assert_eq!(input.value, 42);
|
||||
assert_eq!(input.text, "42");
|
||||
assert!(input.on_change.is_none());
|
||||
assert!(input.on_submit.is_none());
|
||||
assert!(input.on_paste.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_text_getter() {
|
||||
let value = 123u32;
|
||||
let input = TestTypedInput::new("Enter a number", &value);
|
||||
|
||||
assert_eq!(input.text(), "123");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_with_on_input() {
|
||||
let value = 42u32;
|
||||
let input = TestTypedInput::new("Enter a number", &value).on_input(TestMessage::Changed);
|
||||
|
||||
assert!(input.on_change.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_with_on_submit() {
|
||||
let value = 42u32;
|
||||
let input = TestTypedInput::new("Enter a number", &value).on_submit(TestMessage::Submit);
|
||||
|
||||
assert!(input.on_submit.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_with_on_paste() {
|
||||
let value = 42u32;
|
||||
let input = TestTypedInput::new("Enter a number", &value).on_paste(TestMessage::Paste);
|
||||
|
||||
assert!(input.on_paste.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_on_input_maybe_some() {
|
||||
let value = 42u32;
|
||||
let input = TestTypedInput::new("Enter a number", &value)
|
||||
.on_input_maybe(Some(TestMessage::Changed));
|
||||
|
||||
assert!(input.on_change.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_on_input_maybe_none() {
|
||||
let value = 42u32;
|
||||
let input: TestTypedInput = TestTypedInput::new("Enter a number", &value)
|
||||
.on_input_maybe(None::<fn(u32) -> TestMessage>);
|
||||
|
||||
assert!(input.on_change.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_on_submit_maybe_some() {
|
||||
let value = 42u32;
|
||||
let input = TestTypedInput::new("Enter a number", &value)
|
||||
.on_submit_maybe(Some(TestMessage::Submit));
|
||||
|
||||
assert!(input.on_submit.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_on_submit_maybe_none() {
|
||||
let value = 42u32;
|
||||
let input: TestTypedInput = TestTypedInput::new("Enter a number", &value)
|
||||
.on_submit_maybe(None::<fn(Result<u32, String>) -> TestMessage>);
|
||||
|
||||
assert!(input.on_submit.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_on_paste_maybe_some() {
|
||||
let value = 42u32;
|
||||
let input =
|
||||
TestTypedInput::new("Enter a number", &value).on_paste_maybe(Some(TestMessage::Paste));
|
||||
|
||||
assert!(input.on_paste.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_on_paste_maybe_none() {
|
||||
let value = 42u32;
|
||||
let input: TestTypedInput = TestTypedInput::new("Enter a number", &value)
|
||||
.on_paste_maybe(None::<fn(u32) -> TestMessage>);
|
||||
|
||||
assert!(input.on_paste.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_secure_mode() {
|
||||
let value = 1234u32;
|
||||
let _input = TestTypedInput::new("Enter PIN", &value).secure(true);
|
||||
// If it compiles and doesn't panic, the test passes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_with_different_types() {
|
||||
// Test with i32
|
||||
{
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum I32Message {
|
||||
Changed(i32),
|
||||
}
|
||||
let value = -42i32;
|
||||
let _input: TypedInput<'_, i32, I32Message, iced_widget::Theme, Renderer> =
|
||||
TypedInput::new("Enter number", &value).on_input(I32Message::Changed);
|
||||
}
|
||||
|
||||
// Test with f64
|
||||
{
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum F64Message {
|
||||
Changed(f64),
|
||||
}
|
||||
let value = 2.5;
|
||||
let _input: TypedInput<'_, f64, F64Message, iced_widget::Theme, Renderer> =
|
||||
TypedInput::new("Enter number", &value).on_input(F64Message::Changed);
|
||||
}
|
||||
|
||||
// Test with String
|
||||
{
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum StringMessage {
|
||||
Changed(String),
|
||||
}
|
||||
let value = "hello".to_owned();
|
||||
let _input: TypedInput<'_, String, StringMessage, iced_widget::Theme, Renderer> =
|
||||
TypedInput::new("Enter text", &value).on_input(StringMessage::Changed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_tag_returns_text_input_tag() {
|
||||
let value = 42u32;
|
||||
let input = TestTypedInput::new("Enter a number", &value);
|
||||
|
||||
let tag = Widget::<TestMessage, iced_widget::Theme, Renderer>::tag(&input);
|
||||
// The tag should be the same as the underlying TextInput's tag
|
||||
let text_input_tag = <TextInput<_, _, _> as Widget<_, _, _>>::tag(&input.text_input);
|
||||
assert_eq!(tag, text_input_tag);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_input_children_delegates_to_text_input() {
|
||||
let value = 42u32;
|
||||
let input = TestTypedInput::new("Enter a number", &value);
|
||||
|
||||
let children = Widget::<TestMessage, iced_widget::Theme, Renderer>::children(&input);
|
||||
let text_input_children =
|
||||
<TextInput<_, _, _> as Widget<_, _, _>>::children(&input.text_input);
|
||||
assert_eq!(children.len(), text_input_children.len());
|
||||
}
|
||||
}
|
||||
Vendored
+1006
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user