Added theme management, custom theme colors
Moorly CI / windows-build (push) Successful in 3m4s
Moorly CI / linux-build (push) Successful in 3m36s

This commit is contained in:
Squid committed 2026-11-06 21:58:06 +01:00
1 parent da752bcfd7
commit 188e4f64d4
77 files changed
+40000 -99

No files matched your search

Generated
+167 -8
View File
@@ -1266,6 +1266,12 @@ dependencies = [
"zlib-rs", "zlib-rs",
] ]
[[package]]
name = "float_next_after"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
[[package]] [[package]]
name = "foldhash" name = "foldhash"
version = "0.1.5" version = "0.1.5"
@@ -1791,6 +1797,17 @@ dependencies = [
"thiserror 2.0.21", "thiserror 2.0.21",
] ]
[[package]]
name = "iced_aw"
version = "0.14.1"
dependencies = [
"cfg-if",
"iced_core",
"iced_fonts",
"iced_widget",
"web-time",
]
[[package]] [[package]]
name = "iced_core" name = "iced_core"
version = "0.14.0" version = "0.14.0"
@@ -1820,6 +1837,29 @@ dependencies = [
"log", "log",
] ]
[[package]]
name = "iced_fonts"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "214cff7c8499e328774216690e58e315a1a5f8f6fdd1035aed6298e62ffc4c1d"
dependencies = [
"iced_core",
"iced_fonts_macros",
"iced_widget",
]
[[package]]
name = "iced_fonts_macros"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef5125e110cb19cd1910a28298661c98c5d9ab02eef43594968352940e8752e"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"ttf-parser",
]
[[package]] [[package]]
name = "iced_futures" name = "iced_futures"
version = "0.14.0" version = "0.14.0"
@@ -1830,6 +1870,7 @@ dependencies = [
"iced_core", "iced_core",
"log", "log",
"rustc-hash 2.1.3", "rustc-hash 2.1.3",
"tokio",
"wasm-bindgen-futures", "wasm-bindgen-futures",
"wasmtimer", "wasmtimer",
] ]
@@ -1847,6 +1888,7 @@ dependencies = [
"iced_core", "iced_core",
"iced_futures", "iced_futures",
"log", "log",
"lyon_path",
"raw-window-handle", "raw-window-handle",
"rustc-hash 2.1.3", "rustc-hash 2.1.3",
"thiserror 2.0.21", "thiserror 2.0.21",
@@ -1921,6 +1963,7 @@ dependencies = [
"iced_debug", "iced_debug",
"iced_graphics", "iced_graphics",
"log", "log",
"lyon",
"rustc-hash 2.1.3", "rustc-hash 2.1.3",
"thiserror 2.0.21", "thiserror 2.0.21",
"wgpu", "wgpu",
@@ -2193,6 +2236,58 @@ version = "0.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39"
[[package]]
name = "lyon"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd0578bdecb7d6d88987b8b2b1e3a4e2f81df9d0ece1078623324a567904e7b7"
dependencies = [
"lyon_algorithms",
"lyon_tessellation",
]
[[package]]
name = "lyon_algorithms"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a6b9d4e8b48acd531fbf1241ad9b270df6e60b6b92bdea1469f4f40899d805"
dependencies = [
"lyon_path",
"num-traits",
]
[[package]]
name = "lyon_geom"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d82dd26aa4dc0b5b70b9115de59824842bcb43cf4a28e1b1e6d0ad148c93f93e"
dependencies = [
"arrayvec",
"euclid",
"num-traits",
]
[[package]]
name = "lyon_path"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e"
dependencies = [
"lyon_geom",
"num-traits",
]
[[package]]
name = "lyon_tessellation"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd4872650e70dc907dd4f7ebc449d7d657a0d2658e423b2e724970870bbbf75b"
dependencies = [
"float_next_after",
"lyon_path",
"num-traits",
]
[[package]] [[package]]
name = "malloc_buf" name = "malloc_buf"
version = "0.0.6" version = "0.0.6"
@@ -2299,9 +2394,13 @@ name = "moorly"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"iced", "iced",
"iced_aw",
"russh", "russh",
"russh-sftp", "russh-sftp",
"serde",
"tokio", "tokio",
"toml",
"uuid",
] ]
[[package]] [[package]]
@@ -3178,7 +3277,7 @@ version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [ dependencies = [
"toml_edit", "toml_edit 0.25.17+spec-1.1.0",
] ]
[[package]] [[package]]
@@ -3652,6 +3751,15 @@ dependencies = [
"syn 3.0.9", "syn 3.0.9",
] ]
[[package]]
name = "serde_spanned"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "serdect" name = "serdect"
version = "0.4.3" version = "0.4.3"
@@ -4206,6 +4314,27 @@ dependencies = [
"tokio", "tokio",
] ]
[[package]]
name = "toml"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
"serde_spanned",
"toml_datetime 0.6.11",
"toml_edit 0.22.27",
]
[[package]]
name = "toml_datetime"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "toml_datetime" name = "toml_datetime"
version = "1.1.2+spec-1.1.0" version = "1.1.2+spec-1.1.0"
@@ -4215,6 +4344,20 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "toml_edit"
version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap",
"serde",
"serde_spanned",
"toml_datetime 0.6.11",
"toml_write",
"winnow 0.7.15",
]
[[package]] [[package]]
name = "toml_edit" name = "toml_edit"
version = "0.25.17+spec-1.1.0" version = "0.25.17+spec-1.1.0"
@@ -4222,9 +4365,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"toml_datetime", "toml_datetime 1.1.2+spec-1.1.0",
"toml_parser", "toml_parser",
"winnow", "winnow 1.0.4",
] ]
[[package]] [[package]]
@@ -4233,9 +4376,15 @@ version = "1.1.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
dependencies = [ dependencies = [
"winnow", "winnow 1.0.4",
] ]
[[package]]
name = "toml_write"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
[[package]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.44" version = "0.1.44"
@@ -4352,6 +4501,7 @@ version = "1.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514"
dependencies = [ dependencies = [
"getrandom 0.4.3",
"js-sys", "js-sys",
"serde_core", "serde_core",
"wasm-bindgen", "wasm-bindgen",
@@ -5104,6 +5254,15 @@ dependencies = [
"xkbcommon-dl", "xkbcommon-dl",
] ]
[[package]]
name = "winnow"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "winnow" name = "winnow"
version = "1.0.4" version = "1.0.4"
@@ -5229,7 +5388,7 @@ dependencies = [
"uds_windows", "uds_windows",
"uuid", "uuid",
"windows-sys 0.61.2", "windows-sys 0.61.2",
"winnow", "winnow 1.0.4",
"zbus_macros", "zbus_macros",
"zbus_names", "zbus_names",
"zvariant", "zvariant",
@@ -5257,7 +5416,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"
dependencies = [ dependencies = [
"serde", "serde",
"winnow", "winnow 1.0.4",
"zvariant", "zvariant",
] ]
@@ -5317,7 +5476,7 @@ dependencies = [
"endi", "endi",
"enumflags2", "enumflags2",
"serde", "serde",
"winnow", "winnow 1.0.4",
"zcheapstr", "zcheapstr",
"zvariant_derive", "zvariant_derive",
"zvariant_utils", "zvariant_utils",
@@ -5346,5 +5505,5 @@ dependencies = [
"quote", "quote",
"serde", "serde",
"syn 3.0.9", "syn 3.0.9",
"winnow", "winnow 1.0.4",
] ]
+5 -1
View File
@@ -4,7 +4,11 @@ version = "0.1.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
iced = "0.14.0" iced = { version = "0.14.0", features = ["tokio"] }
iced_aw = { path = "vendor/iced_aw", default-features = false, features = ["color_picker"] }
russh = "0.65.0" russh = "0.65.0"
russh-sftp = "3.0.1" russh-sftp = "3.0.1"
serde = { version = "1.0.229", features = ["derive"] }
tokio = { version = "1.54.1", features = ["full"] } tokio = { version = "1.54.1", features = ["full"] }
toml = "0.8"
uuid = { version = "1.29.0", features = ["v4"] }
+787 -56
View File
File diff suppressed because it is too large. Load diff
+47 -34
View File
@@ -18,6 +18,8 @@ pub const DANGER: Color = Color::from_rgb8(0xff, 0x3b, 0x30);
pub const ACTIVE_TAB: Color = Color::from_rgb8(0x60, 0x82, 0xB6); pub const ACTIVE_TAB: Color = Color::from_rgb8(0x60, 0x82, 0xB6);
/// Highlight for the selected settings section. /// Highlight for the selected settings section.
pub const SETTINGS_ACTIVE: Color = Color::from_rgb8(0x5D, 0x3F, 0xD3); pub const SETTINGS_ACTIVE: Color = Color::from_rgb8(0x5D, 0x3F, 0xD3);
/// Border for the collapsible advanced-settings area.
pub const ADVANCED_BORDER: Color = Color::from_rgb8(0xD0, 0xD0, 0xD0);
/// Tab bar surfaces: the active tab merges with the content area below. /// Tab bar surfaces: the active tab merges with the content area below.
pub const TAB_ACTIVE_BG: Color = Color::from_rgb8(0x19, 0x19, 0x19); pub const TAB_ACTIVE_BG: Color = Color::from_rgb8(0x19, 0x19, 0x19);
pub const TAB_INACTIVE_BG: Color = Color::from_rgb8(0x13, 0x13, 0x13); pub const TAB_INACTIVE_BG: Color = Color::from_rgb8(0x13, 0x13, 0x13);
@@ -51,7 +53,7 @@ impl Preference {
} }
} }
fn as_str(self) -> &'static str { pub fn as_str(self) -> &'static str {
match self { match self {
Self::System => "system", Self::System => "system",
Self::Light => "light", Self::Light => "light",
@@ -59,7 +61,7 @@ impl Preference {
} }
} }
fn parse(value: &str) -> Option<Self> { pub fn parse(value: &str) -> Option<Self> {
Self::ALL.into_iter().find(|pref| pref.as_str() == value) Self::ALL.into_iter().find(|pref| pref.as_str() == value)
} }
} }
@@ -105,20 +107,20 @@ pub(crate) fn config_path() -> Option<PathBuf> {
} }
/// Style for the top menubar. /// Style for the top menubar.
pub fn menubar(_theme: &Theme) -> container::Style { pub fn menubar(_theme: &Theme, background: Color) -> container::Style {
container::Style { container::Style {
background: Some(TAB_INACTIVE_BG.into()), background: Some(background.into()),
..container::Style::default() ..container::Style::default()
} }
} }
/// Style for buttons that sit directly on the dark menubar. /// Style for buttons that sit directly on the dark menubar.
pub fn menubar_button(theme: &Theme, status: button::Status) -> button::Style { pub fn menubar_button(theme: &Theme, status: button::Status, text_color: Color) -> button::Style {
let mut style = button::text(theme, status); let mut style = button::text(theme, status);
style.text_color = if matches!(status, button::Status::Disabled) { style.text_color = if matches!(status, button::Status::Disabled) {
TAB_TEXT.scale_alpha(0.4) text_color.scale_alpha(0.4)
} else { } else {
TAB_TEXT text_color
}; };
style style
} }
@@ -132,12 +134,17 @@ pub fn menu(theme: &Theme) -> container::Style {
/// Style for a tab in the menubar; active tabs sit on the content surface. /// Style for a tab in the menubar; active tabs sit on the content surface.
/// The active outline is drawn separately so it has no bottom edge. /// The active outline is drawn separately so it has no bottom edge.
pub fn tab(_theme: &Theme, active: bool) -> container::Style { pub fn tab(
_theme: &Theme,
active: bool,
active_bg: Color,
inactive_bg: Color,
) -> container::Style {
container::Style { container::Style {
background: Some(if active { background: Some(if active {
TAB_ACTIVE_BG.into() active_bg.into()
} else { } else {
TAB_INACTIVE_BG.into() inactive_bg.into()
}), }),
border: Border { border: Border {
color: Color::TRANSPARENT, color: Color::TRANSPARENT,
@@ -154,36 +161,32 @@ pub fn tab(_theme: &Theme, active: bool) -> container::Style {
} }
/// Style for the active tab's thin top/left/right outline. /// Style for the active tab's thin top/left/right outline.
pub fn tab_outline(_theme: &Theme) -> container::Style { pub fn tab_outline(_theme: &Theme, color: Color) -> container::Style {
container::Style { container::Style {
background: Some(ACTIVE_TAB.into()), background: Some(color.into()),
..container::Style::default()
}
}
/// Rounded frame around the advanced-settings area.
pub fn advanced_frame(_theme: &Theme) -> container::Style {
container::Style {
border: Border {
color: ADVANCED_BORDER,
width: 1.0,
radius: 6.0.into(),
},
..container::Style::default() ..container::Style::default()
} }
} }
/// Style for the selected settings section in the settings menu. /// Style for the selected settings section in the settings menu.
pub fn settings_active(_theme: &Theme, _status: button::Status) -> button::Style { pub fn settings_active(_theme: &Theme, _status: button::Status, accent: Color) -> button::Style {
button::Style { button::Style {
background: Some(SETTINGS_ACTIVE.into()), background: Some(accent.into()),
text_color: Color::WHITE, text_color: Color::WHITE,
border: Border { border: Border {
color: SETTINGS_ACTIVE, color: accent,
width: 1.0,
radius: 4.0.into(),
},
..button::Style::default()
}
}
/// Style for the currently selected option in a group of choice buttons.
pub fn selected_option(theme: &Theme, _status: button::Status) -> button::Style {
let palette = theme.extended_palette();
button::Style {
background: Some(palette.primary.base.color.into()),
text_color: palette.primary.base.text,
border: Border {
color: palette.primary.base.color,
width: 1.0, width: 1.0,
radius: 4.0.into(), radius: 4.0.into(),
}, },
@@ -325,14 +328,24 @@ mod tests {
#[test] #[test]
fn active_tabs_are_visually_distinct() { fn active_tabs_are_visually_distinct() {
let theme = Theme::Light; let theme = Theme::Light;
let active = super::tab(&theme, true); let active = super::tab(
let inactive = super::tab(&theme, false); &theme,
true,
super::TAB_ACTIVE_BG,
super::TAB_INACTIVE_BG,
);
let inactive = super::tab(
&theme,
false,
super::TAB_ACTIVE_BG,
super::TAB_INACTIVE_BG,
);
assert_ne!(active.background, inactive.background); assert_ne!(active.background, inactive.background);
assert_eq!(active.border.width, 0.0); assert_eq!(active.border.width, 0.0);
assert_eq!(inactive.border.width, 0.0); assert_eq!(inactive.border.width, 0.0);
assert_eq!( assert_eq!(
super::tab_outline(&theme).background, super::tab_outline(&theme, super::ACTIVE_TAB).background,
Some(super::ACTIVE_TAB.into()) Some(super::ACTIVE_TAB.into())
); );
} }
Generated Vendored
+4529
View File
File diff suppressed because it is too large. Load diff
+149
View File
@@ -0,0 +1,149 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.88"
name = "iced_aw"
version = "0.14.1"
authors = [
"Kaiden42 <gitlab@tinysn.com>",
"Andrew Wheeler <genusistimelord@gmail.com>",
]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Additional widgets for the Iced GUI library"
homepage = "https://iced.rs"
readme = "README.md"
keywords = [
"gui",
"graphics",
"interface",
"widgets",
"iced",
]
categories = ["gui"]
license = "MIT"
repository = "https://github.com/iced-rs/iced_aw"
[features]
badge = []
card = []
color_picker = ["iced_widget/canvas"]
context_menu = []
custom_layout = []
date_picker = ["chrono"]
debug_log = ["log"]
default = ["full"]
drop_down = []
full = [
"badge",
"card",
"number_input",
"date_picker",
"color_picker",
"tab_bar",
"tabs",
"time_picker",
"slide_bar",
"wrap",
"selection_list",
"quad",
"context_menu",
"spinner",
"drop_down",
"menu",
"sidebar",
"labeled_frame",
"custom_layout",
]
labeled_frame = []
menu = []
number_input = [
"num-format",
"num-traits",
"typed_input",
]
quad = []
selection_list = []
sidebar = []
slide_bar = []
spinner = []
tab_bar = []
tabs = ["tab_bar"]
time_picker = [
"chrono",
"iced_widget/canvas",
]
typed_input = []
wrap = []
[lib]
name = "iced_aw"
crate-type = [
"cdylib",
"rlib",
]
path = "src/lib.rs"
[dependencies.cfg-if]
version = "1.0"
[dependencies.chrono]
version = "0.4.44"
features = ["wasmbind"]
optional = true
[dependencies.iced_core]
version = "0.14.0"
[dependencies.iced_fonts]
version = "0.3.0"
features = ["advanced_text"]
[dependencies.iced_widget]
version = "0.14.2"
[dependencies.log]
version = "0.4"
optional = true
[dependencies.num-format]
version = "0.4.4"
optional = true
[dependencies.num-traits]
version = "0.2.19"
optional = true
[dependencies.web-time]
version = "1.1.0"
[dev-dependencies.env_logger]
version = "0.11.10"
[dev-dependencies.getrandom]
version = "0.4.2"
features = ["wasm_js"]
[dev-dependencies.iced]
version = "0.14.0"
features = ["advanced"]
[dev-dependencies.iced_test]
version = "0.14"
[dev-dependencies.rand]
version = "0.10.1"
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Kaiden42
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+173
View File
@@ -0,0 +1,173 @@
# Iced - Additional Widgets
[![Documentation](https://docs.rs/iced_aw/badge.svg)](https://docs.rs/iced_aw)
[![Crates.io](https://img.shields.io/crates/v/iced_aw.svg)](https://crates.io/crates/iced_aw)
[![License](https://img.shields.io/crates/l/iced_aw.svg)](https://github.com/iced-rs/iced/blob/master/LICENSE)
[![Discord Server](https://img.shields.io/discord/628993209984614400?label=&labelColor=6A7EC2&logo=discord&logoColor=ffffff&color=7389D8)](https://discord.gg/3xZJ65GAhd)
This crate contains additional widgets for the GUI library [Iced](https://github.com/hecrj/iced).
Every widget is hidden by a feature gate. This allows you to cherry pick the widgets you actually need.
## Usage
Include `iced_aw` as a dependency in your `Cargo.toml`:
```toml
[dependencies]
iced = "0.14.0"
iced_aw = { version = "0.14.0", features = ["full"] }
```
## Versioning
| `iced` version | `iced_aw` version |
| -------------- | ----------------- |
| 0.13 | 0.12 |
| 0.14 | 0.13, 0.14 |
## Widgets
### Badge
<div align="center">
![Badge showcase](./images/showcase/badge.png)
</div>
Please take a look into our examples on how to use badges.
Enable this widget with the feature `badge`.
### Card
<div align="center">
![Card showcase](./images/showcase/card.png)
</div>
Please take a look into our examples on how to use cards.
Enable this widget with the feature `card`.
### Color Picker
<div align="center">
![Color Picker showcase](./images/showcase/color_picker.png)
</div>
Please take a look into our examples on how to use color pickers.
Enable this widget with the feature `color_picker`.
### Date Picker
<div align="center">
![Date Picker showcase](./images/showcase/date_picker.png)
</div>
Please take a look into our examples on how to use date pickers.
Enable this widget with the feature `date_picker`.
### NumberInput
Just like TextInput, but only for numbers.
<div align="center">
![NumberInput showcase](./images/showcase/number_input.png)
</div>
Please take a look into our examples on how to use number inputs.
Enable this widget with the feature `number_input`.
*This widget does currently not support web*
### SelectionList
A selection space to show any options passed in.
<div align="center">
![SelectionList showcase](./images/showcase/selection_list.gif)
</div>
Enable this widget with the feature `selection_list`.
### TabBar and Tabs
<div align="center">
![Tabs showcase](./images/showcase/tabs_example.gif)
</div>
Please take a look into our examples on how to use TabBars and Tabs.
Enable TabBars with the feature `tab_bar` and Tabs with `tabs`.
### Time Picker
<div align="center">
![Modal showcase](./images/showcase/time_picker.png)
</div>
Please take a look into our examples on how to use time pickers.
Enable this widget with the feature `time_picker`.
### Menu
<div align="center">
![Menu showcase](./images/showcase/menu.gif)
</div>
Please take a look into our examples on how to use menus.
Enable this widget with the feature `menu`.
You might also want to enable the feature `quad` for drawing separators.
### Slide Bar
Please take a look into our examples on how to use slidebars.
Enable this widget with the feature `slide_bar`.
### Context Menu
See the example [here](./examples/context_menu.rs)
### Drop Down Menu
See the example [here](./examples/drop_down.rs)
### Sidebar
<div align="center">
![Modal showcase](./images/showcase/sidebar.png)
</div>
Please take a look into our examples on how to use Sidebar.
Enable Sidebar with the feature `sidebar`.
Also included in this feature, are two widgets `sidebar::column::FlushColumn` and `sidebar::row::FlushRow` that flushes the end/start element to the opposite direction to the alignment of the container.
### Color palette
This crate adds a predefined color palette based on the [CSS color palette](https://www.w3schools.com/cssref/css_colors.asp).
### LabeledFrame
A frame with a title.
<div align="center">
![LabeledFrame showcase](./images/showcase/labeled_frame.png)
</div>
BIN
View File
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
//! `iced_aw_core`.
#[cfg(feature = "date_picker")]
pub mod date;
#[cfg(feature = "time_picker")]
pub mod clock;
#[cfg(feature = "color_picker")]
pub mod color;
pub mod overlay;
pub mod renderer;
#[cfg(feature = "time_picker")]
pub mod time;
#[cfg(feature = "drop_down")]
pub mod offset;
#[cfg(feature = "drop_down")]
pub mod alignment;
+26
View File
@@ -0,0 +1,26 @@
//! Alignment enum, similar to an anchor
/// ```text
/// +-----------+-----------+-----------+
/// | TopStart | Top | TopEnd |
/// +-----------+-----------+-----------+
/// | Start | | End |
/// +-----------+-----------+-----------+
/// |BottomStart| Bottom | BottomEnd |
/// +-----------+-----------+-----------+
/// ```
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Alignment {
TopStart,
Top,
TopEnd,
End,
BottomEnd,
Bottom,
BottomStart,
Start,
}
+367
View File
@@ -0,0 +1,367 @@
//! Helper functions for calculating the clock
use iced_core::Point;
use std::fmt::Display;
/// The size of the period on the clock based on the clock's size.
pub const PERIOD_PERCENTAGE: f32 = 0.1;
/// The radius of the hour on the clock based on the clock's size.
pub const HOUR_RADIUS_PERCENTAGE: f32 = 0.4;
/// The radius of the minute on the clock based on the clock's size.
pub const MINUTE_RADIUS_PERCENTAGE: f32 = 0.65;
/// The radius of the second on the clock based on the clock's size.
pub const SECOND_RADIUS_PERCENTAGE: f32 = 0.9;
/// The radius of the hour without the seconds on the clock based on the
/// clock's size.
pub const HOUR_RADIUS_PERCENTAGE_NO_SECONDS: f32 = 0.5;
/// The radius of the minute without the seconds on the clock based on the
/// clock's size.
pub const MINUTE_RADIUS_PERCENTAGE_NO_SECONDS: f32 = 0.9;
/// The current period of the clock.
#[derive(Clone, Debug)]
pub enum Period {
/// Ante meridiem: Before noon.
AM,
/// Post meridiem: After noon.
PM,
}
impl Display for Period {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::AM => "AM",
Self::PM => "PM",
}
)
}
}
/// The radius nearest to the cursor position.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NearestRadius {
/// Nothing is near to the cursor position.
None,
/// Period is the nearest radius to the cursor position.
Period,
/// Hour is the nearest radius to the cursor position.
Hour,
/// Minute is the nearest radius to the cursor position.
Minute,
/// Second is the nearest radius to the cursor position.
Second,
}
/// Distributes the amount of points on a circle with the given radius around the
/// center.
#[must_use]
pub fn circle_points(distance_radius: f32, center: Point, amount: u16) -> Vec<Point> {
let part = std::f32::consts::TAU / f32::from(amount);
let rotation =
|(x, y): (f32, f32), t: f32| (x * t.cos() - y * t.sin(), x * t.sin() + y * t.cos());
let points: Vec<(f32, f32)> = (0..amount).fold(Vec::new(), |mut v, i| {
v.push(rotation((0.0, -distance_radius), part * f32::from(i)));
v
});
let points: Vec<Point> = points
.iter()
.map(|p| Point::new(p.0 + center.x, p.1 + center.y))
.collect();
points
}
/// # Panics
/// Determines the nearest point with the smallest distance to the cursor
/// position. The index of the point is returned.
/// Will panic if distance vec can not compare a and b
#[must_use]
pub fn nearest_point(points: &[Point], cursor_position: Point) -> usize {
let mut distance_vec: Vec<(usize, f32)> = points
.iter()
.enumerate()
.map(|(i, p)| (i, p.distance(cursor_position)))
.collect();
distance_vec.sort_by(|a, b| a.1.partial_cmp(&b.1).expect("Should be comparable"));
distance_vec[0].0
}
/// # Panics
/// Determining the nearest radius to the position of the cursor position based
/// on the distance to the center.
/// Will panic if distance vec can not compare a and b
#[must_use]
pub fn nearest_radius(
radii: &[(f32, NearestRadius)],
cursor_position: Point,
center: Point,
) -> NearestRadius {
let distance = cursor_position.distance(center);
let mut distance_vec: Vec<(f32, &NearestRadius)> = radii
.iter()
.map(|(r, n)| ((r - distance).abs(), n))
.collect();
distance_vec.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("Should be comparable"));
distance_vec[0].1.clone()
}
#[cfg(test)]
mod tests {
use iced_core::{Point, Vector};
use super::{NearestRadius, circle_points, nearest_point, nearest_radius};
#[test]
fn circle_points_test() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 10);
let expected = vec![
Point { x: 0.0, y: -10.0 },
Point {
x: 5.877_852_4,
y: -8.09017,
},
Point {
x: 9.510_566,
y: -3.090_169_7,
},
Point {
x: 9.510_565,
y: 3.090_170_4,
},
Point {
x: 5.877_852,
y: 8.090_171,
},
Point {
x: -0.000_000_874_227_8,
y: 10.0,
},
Point {
x: -5.877_853_4,
y: 8.09017,
},
Point {
x: -9.510_565,
y: 3.090_170_9,
},
Point {
x: -9.510_565,
y: -3.090_171_3,
},
Point {
x: -5.877_849_6,
y: -8.090_173,
},
];
assert_eq!(points, expected);
}
#[test]
fn nearest_radius_test() {
let radii = vec![
(10.0, NearestRadius::Period),
(20.0, NearestRadius::Hour),
(30.0, NearestRadius::Minute),
(40.0, NearestRadius::Second),
];
let center = Point::new(0.0, 0.0);
let cursor_position = Point::new(5.0, 0.0);
let result = nearest_radius(&radii, cursor_position, center);
assert_eq!(result, NearestRadius::Period);
let cursor_position = Point::new(16.0, 0.0);
let result = nearest_radius(&radii, cursor_position, center);
assert_eq!(result, NearestRadius::Hour);
let cursor_position = Point::new(26.0, 0.0);
let result = nearest_radius(&radii, cursor_position, center);
assert_eq!(result, NearestRadius::Minute);
let cursor_position = Point::new(36.0, 0.0);
let result = nearest_radius(&radii, cursor_position, center);
assert_eq!(result, NearestRadius::Second);
}
#[test]
fn nearest_point_test() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 10);
let mut index = 5;
let cursor_position = points[index] + Vector::new(1.0, -1.0);
let mut result = nearest_point(&points, cursor_position);
assert_eq!(index, result);
index = 0;
let cursor_position = points[index] + Vector::new(-1.0, 1.0);
result = nearest_point(&points, cursor_position);
assert_eq!(index, result);
}
#[test]
fn period_display_am() {
use super::Period;
let period = Period::AM;
assert_eq!(format!("{period}"), "AM");
}
#[test]
fn period_display_pm() {
use super::Period;
let period = Period::PM;
assert_eq!(format!("{period}"), "PM");
}
#[test]
fn circle_points_with_offset_center() {
let points = circle_points(5.0, Point::new(10.0, 20.0), 4);
assert_eq!(points.len(), 4);
// Top point should be at (10, 15) - center.y - radius
assert!((points[0].x - 10.0).abs() < 0.001);
assert!((points[0].y - 15.0).abs() < 0.001);
}
#[test]
fn circle_points_single_point() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 1);
assert_eq!(points.len(), 1);
// Single point should be at top (0, -10)
assert!((points[0].x - 0.0).abs() < 0.001);
assert!((points[0].y - (-10.0)).abs() < 0.001);
}
#[test]
fn circle_points_twelve_points() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 12);
assert_eq!(points.len(), 12);
// 12 points should be evenly distributed (like clock hours)
// First point should be at top
assert!((points[0].x - 0.0).abs() < 0.001);
assert!((points[0].y - (-10.0)).abs() < 0.001);
}
#[test]
fn nearest_point_single_point() {
let points = vec![Point::new(5.0, 5.0)];
let cursor = Point::new(100.0, 100.0);
let result = nearest_point(&points, cursor);
assert_eq!(result, 0);
}
#[test]
fn nearest_point_exact_match() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 8);
// Cursor exactly on point 3
let cursor = points[3];
let result = nearest_point(&points, cursor);
assert_eq!(result, 3);
}
#[test]
fn nearest_radius_at_exact_radius() {
let radii = vec![
(10.0, NearestRadius::Period),
(20.0, NearestRadius::Hour),
(30.0, NearestRadius::Minute),
];
let center = Point::new(0.0, 0.0);
// Cursor exactly at radius 20
let cursor = Point::new(20.0, 0.0);
let result = nearest_radius(&radii, cursor, center);
assert_eq!(result, NearestRadius::Hour);
}
#[test]
fn nearest_radius_at_center() {
let radii = vec![
(10.0, NearestRadius::Period),
(20.0, NearestRadius::Hour),
(30.0, NearestRadius::Minute),
];
let center = Point::new(0.0, 0.0);
// Cursor at center
let cursor = Point::new(0.0, 0.0);
let result = nearest_radius(&radii, cursor, center);
// Should pick the smallest radius (Period at 10.0)
assert_eq!(result, NearestRadius::Period);
}
#[test]
fn nearest_radius_beyond_largest() {
let radii = vec![
(10.0, NearestRadius::Period),
(20.0, NearestRadius::Hour),
(30.0, NearestRadius::Minute),
];
let center = Point::new(0.0, 0.0);
// Cursor far beyond all radii
let cursor = Point::new(100.0, 0.0);
let result = nearest_radius(&radii, cursor, center);
// Should still pick the closest (Minute at 30.0)
assert_eq!(result, NearestRadius::Minute);
}
#[test]
fn nearest_radius_with_offset_center() {
let radii = vec![(5.0, NearestRadius::Period), (15.0, NearestRadius::Hour)];
let center = Point::new(50.0, 50.0);
let cursor = Point::new(62.0, 50.0);
// Distance from center is 12, closer to Hour (15) than Period (5)
// |5 - 12| = 7, |15 - 12| = 3, so Hour is closer
let result = nearest_radius(&radii, cursor, center);
assert_eq!(result, NearestRadius::Hour);
}
#[test]
fn nearest_radius_none_variant() {
let radii = vec![(10.0, NearestRadius::None), (20.0, NearestRadius::Hour)];
let center = Point::new(0.0, 0.0);
let cursor = Point::new(11.0, 0.0);
let result = nearest_radius(&radii, cursor, center);
// Should pick None as it's closer to radius 10
assert_eq!(result, NearestRadius::None);
}
#[test]
fn circle_points_large_amount() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 60);
assert_eq!(points.len(), 60);
// All points should be approximately 10.0 away from center
let center = Point::new(0.0, 0.0);
for point in points {
let distance = point.distance(center);
assert!((distance - 10.0).abs() < 0.001);
}
}
#[test]
fn constants_are_defined() {
use super::*;
// Just verify the constants are accessible and have expected values
assert_eq!(PERIOD_PERCENTAGE, 0.1);
assert_eq!(HOUR_RADIUS_PERCENTAGE, 0.4);
assert_eq!(MINUTE_RADIUS_PERCENTAGE, 0.65);
assert_eq!(SECOND_RADIUS_PERCENTAGE, 0.9);
assert_eq!(HOUR_RADIUS_PERCENTAGE_NO_SECONDS, 0.5);
assert_eq!(MINUTE_RADIUS_PERCENTAGE_NO_SECONDS, 0.9);
}
}
+339
View File
@@ -0,0 +1,339 @@
//! Helper functions and structs for picking dates.
use iced_core::Color;
/// A color in the HSV color space.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Hsv {
/// HSV hue.
pub(crate) hue: u16,
/// HSV Saturation.
pub(crate) saturation: f32,
/// HSV value.
pub(crate) value: f32,
}
impl Hsv {
/// Creates a [`Hsv`] from its HSV components.
#[must_use]
pub const fn from_hsv(hue: u16, saturation: f32, value: f32) -> Self {
Self {
hue,
saturation,
value,
}
}
}
/// Creates a string of hexadecimal characters.
pub trait HexString {
/// Turns self into a string of hexadecimal characters.
fn as_hex_string(&self) -> String;
}
impl HexString for Color {
fn as_hex_string(&self) -> String {
format!(
"#{:02X?}{:02X?}{:02X?}{:02X?}",
(self.r * 255.0) as u8,
(self.g * 255.0) as u8,
(self.b * 255.0) as u8,
(self.a * 255.0) as u8,
)
}
}
impl From<Color> for Hsv {
// https://de.wikipedia.org/wiki/HSV-Farbraum#Umrechnung_RGB_in_HSV/HSL
fn from(color: Color) -> Self {
let max = color.r.max(color.g.max(color.b));
let min = color.r.min(color.g.min(color.b));
let hue = if (max - min).abs() < f32::EPSILON {
0.0
} else if (max - color.r).abs() < f32::EPSILON {
60.0 * (0.0 + (color.g - color.b) / (max - min))
} else if (max - color.g).abs() < f32::EPSILON {
60.0 * (2.0 + (color.b - color.r) / (max - min))
} else {
60.0 * (4.0 + (color.r - color.g) / (max - min))
};
let hue = if hue < 0.0 { hue + 360.0 } else { hue } as u16 % 360;
let saturation = if max == 0.0 { 0.0 } else { (max - min) / max };
let value = max;
Self {
hue,
saturation,
value,
}
}
}
impl From<Hsv> for Color {
fn from(hsv: Hsv) -> Self {
// https://de.wikipedia.org/wiki/HSV-Farbraum#Umrechnung_HSV_in_RGB
let h_i = (f32::from(hsv.hue) / 60.0).floor();
let f = (f32::from(hsv.hue) / 60.0) - h_i;
let p = hsv.value * (1.0 - hsv.saturation);
let q = hsv.value * (1.0 - hsv.saturation * f);
let t = hsv.value * (1.0 - hsv.saturation * (1.0 - f));
let h_i = h_i as u8;
let (red, green, blue) = match h_i {
1 => (q, hsv.value, p),
2 => (p, hsv.value, t),
3 => (p, q, hsv.value),
4 => (t, p, hsv.value),
5 => (hsv.value, p, q),
_ => (hsv.value, t, p),
};
Self::from_rgb(red, green, blue)
}
}
#[cfg(test)]
mod tests {
use iced_core::Color;
use super::Hsv;
#[allow(clippy::cognitive_complexity)]
#[test]
fn rgb_to_hsv() {
// https://de.wikipedia.org/wiki/HSV-Farbraum#Transformation_von_HSV/HSL_und_RGB
let red_rgb = Color::from_rgb(1.0, 0.0, 0.0);
let red_hsv = Hsv::from_hsv(0, 1.0, 1.0);
assert_eq!(red_hsv, red_rgb.into());
let orange_rgb = Color::from_rgb(1.0, 0.5, 0.0);
let orange_hsv = Hsv::from_hsv(30, 1.0, 1.0);
assert_eq!(orange_hsv, orange_rgb.into());
let yellow_rgb = Color::from_rgb(1.0, 1.0, 0.0);
let yellow_hsv = Hsv::from_hsv(60, 1.0, 1.0);
assert_eq!(yellow_hsv, yellow_rgb.into());
let dark_green_rgb = Color::from_rgb(0.0, 0.5, 0.0);
let dark_green_hsv = Hsv::from_hsv(120, 1.0, 0.5);
assert_eq!(dark_green_hsv, dark_green_rgb.into());
let violett_rgb = Color::from_rgb(0.5, 0.0, 1.0);
let violett_hsv = Hsv::from_hsv(270, 1.0, 1.0);
assert_eq!(violett_hsv, violett_rgb.into());
let black_rgb = Color::from_rgb(0.0, 0.0, 0.0);
let black_hsv = Hsv::from_hsv(0, 0.0, 0.0);
assert_eq!(black_hsv, black_rgb.into());
let blue_rgb = Color::from_rgb(0.0, 0.0, 1.0);
let blue_hsv = Hsv::from_hsv(240, 1.0, 1.0);
assert_eq!(blue_hsv, blue_rgb.into());
let brown_rgb = Color::from_rgb(0.36, 0.18, 0.09);
let brown_hsv = Hsv::from_hsv(20, 0.75, 0.36);
assert_eq!(brown_hsv, brown_rgb.into());
let white_rgb = Color::from_rgb(1.0, 1.0, 1.0);
let white_hsv = Hsv::from_hsv(0, 0.0, 1.0);
assert_eq!(white_hsv, white_rgb.into());
let green_rgb = Color::from_rgb(0.0, 1.0, 0.0);
let green_hsv = Hsv::from_hsv(120, 1.0, 1.0);
assert_eq!(green_hsv, green_rgb.into());
let cyan_rgb = Color::from_rgb(0.0, 1.0, 1.0);
let cyan_hsv = Hsv::from_hsv(180, 1.0, 1.0);
assert_eq!(cyan_hsv, cyan_rgb.into());
let magenta_rgb = Color::from_rgb(1.0, 0.0, 1.0);
let magenta_hsv = Hsv::from_hsv(300, 1.0, 1.0);
assert_eq!(magenta_hsv, magenta_rgb.into());
let blue_green_rgb = Color::from_rgb(0.0, 1.0, 0.5);
let blue_green_hsv = Hsv::from_hsv(150, 1.0, 1.0);
assert_eq!(blue_green_hsv, blue_green_rgb.into());
let green_blue_rgb = Color::from_rgb(0.0, 0.5, 1.0);
let green_blue_hsv = Hsv::from_hsv(210, 1.0, 1.0);
assert_eq!(green_blue_hsv, green_blue_rgb.into());
let green_yellow_rgb = Color::from_rgb(0.5, 1.0, 0.0);
let green_yellow_hsv = Hsv::from_hsv(90, 1.0, 1.0);
assert_eq!(green_yellow_hsv, green_yellow_rgb.into());
let blue_red_rgb = Color::from_rgb(1.0, 0.0, 0.5);
let blue_red_hsv = Hsv::from_hsv(330, 1.0, 1.0);
assert_eq!(blue_red_hsv, blue_red_rgb.into());
let zinnober_rgb = Color::from_rgb(1.0, 0.25, 0.0);
let zinnober_hsv = Hsv::from_hsv(15, 1.0, 1.0);
assert_eq!(zinnober_hsv, zinnober_rgb.into());
let indigo_rgb = Color::from_rgb(0.25, 0.0, 1.0);
let indigo_hsv = Hsv::from_hsv(255, 1.0, 1.0);
assert_eq!(indigo_hsv, indigo_rgb.into());
let light_blue_green_rgb = Color::from_rgb(0.0, 1.0, 0.25);
let light_blue_green_hsv = Hsv::from_hsv(135, 1.0, 1.0);
assert_eq!(light_blue_green_hsv, light_blue_green_rgb.into());
let blue_cyan_rgb = Color::from_rgb(0.0, 0.75, 1.0);
let blue_cyan_hsv = Hsv::from_hsv(195, 1.0, 1.0);
assert_eq!(blue_cyan_hsv, blue_cyan_rgb.into());
let light_green_yellow_rgb = Color::from_rgb(0.75, 1.0, 0.0);
let light_green_yellow_hsv = Hsv::from_hsv(75, 1.0, 1.0);
assert_eq!(light_green_yellow_hsv, light_green_yellow_rgb.into());
let red_magenta_rgb = Color::from_rgb(1.0, 0.0, 0.75);
let red_magenta_hsv = Hsv::from_hsv(315, 1.0, 1.0);
assert_eq!(red_magenta_hsv, red_magenta_rgb.into());
let safran_rgb = Color::from_rgb(1.0, 0.75, 0.0);
let safran_hsv = Hsv::from_hsv(45, 1.0, 1.0);
assert_eq!(safran_hsv, safran_rgb.into());
let blue_magenta_rgb = Color::from_rgb(0.75, 0.0, 1.0);
let blue_magenta_hsv = Hsv::from_hsv(285, 1.0, 1.0);
assert_eq!(blue_magenta_hsv, blue_magenta_rgb.into());
let green_cyan_rgb = Color::from_rgb(0.0, 1.0, 0.75);
let green_cyan_hsv = Hsv::from_hsv(165, 1.0, 1.0);
assert_eq!(green_cyan_hsv, green_cyan_rgb.into());
let light_green_blue_rgb = Color::from_rgb(0.0, 0.25, 1.0);
let light_green_blue_hsv = Hsv::from_hsv(225, 1.0, 1.0);
assert_eq!(light_green_blue_hsv, light_green_blue_rgb.into());
let lime_rgb = Color::from_rgb(0.25, 1.0, 0.0);
let lime_hsv = Hsv::from_hsv(105, 1.0, 1.0);
assert_eq!(lime_hsv, lime_rgb.into());
let light_blue_red_rgb = Color::from_rgb(1.0, 0.0, 0.25);
let light_blue_red_hsv = Hsv::from_hsv(345, 1.0, 1.0);
assert_eq!(light_blue_red_hsv, light_blue_red_rgb.into());
}
#[allow(clippy::cognitive_complexity)]
#[test]
fn hsv_to_rgb() {
// https://de.wikipedia.org/wiki/HSV-Farbraum#Transformation_von_HSV/HSL_und_RGB
let red_hsv = Hsv::from_hsv(0, 1.0, 1.0);
let red_rgb = Color::from_rgb(1.0, 0.0, 0.0);
assert_eq!(red_rgb, red_hsv.into());
let orange_hsv = Hsv::from_hsv(30, 1.0, 1.0);
let orange_rgb = Color::from_rgb(1.0, 0.5, 0.0);
assert_eq!(orange_rgb, orange_hsv.into());
let yellow_hsv = Hsv::from_hsv(60, 1.0, 1.0);
let yellow_rgb = Color::from_rgb(1.0, 1.0, 0.0);
assert_eq!(yellow_rgb, yellow_hsv.into());
let dark_green_hsv = Hsv::from_hsv(120, 1.0, 0.5);
let dark_green_rgb = Color::from_rgb(0.0, 0.5, 0.0);
assert_eq!(dark_green_rgb, dark_green_hsv.into());
let violett_hsv = Hsv::from_hsv(270, 1.0, 1.0);
let violett_rgb = Color::from_rgb(0.5, 0.0, 1.0);
assert_eq!(violett_rgb, violett_hsv.into());
let black_hsv = Hsv::from_hsv(0, 0.0, 0.0);
let black_rgb = Color::from_rgb(0.0, 0.0, 0.0);
assert_eq!(black_rgb, black_hsv.into());
let blue_hsv = Hsv::from_hsv(240, 1.0, 1.0);
let blue_rgb = Color::from_rgb(0.0, 0.0, 1.0);
assert_eq!(blue_rgb, blue_hsv.into());
let brown_hsv = Hsv::from_hsv(20, 0.75, 0.36);
let brown_rgb = Color::from_rgb(0.36, 0.18, 0.09);
assert_eq!(brown_rgb, brown_hsv.into());
let white_hsv = Hsv::from_hsv(0, 0.0, 1.0);
let white_rgb = Color::from_rgb(1.0, 1.0, 1.0);
assert_eq!(white_rgb, white_hsv.into());
let green_hsv = Hsv::from_hsv(120, 1.0, 1.0);
let green_rgb = Color::from_rgb(0.0, 1.0, 0.0);
assert_eq!(green_rgb, green_hsv.into());
let cyan_hsv = Hsv::from_hsv(180, 1.0, 1.0);
let cyan_rgb = Color::from_rgb(0.0, 1.0, 1.0);
assert_eq!(cyan_rgb, cyan_hsv.into());
let magenta_hsv = Hsv::from_hsv(300, 1.0, 1.0);
let magenta_rgb = Color::from_rgb(1.0, 0.0, 1.0);
assert_eq!(magenta_rgb, magenta_hsv.into());
let blue_green_hsv = Hsv::from_hsv(150, 1.0, 1.0);
let blue_green_rgb = Color::from_rgb(0.0, 1.0, 0.5);
assert_eq!(blue_green_rgb, blue_green_hsv.into());
let green_blue_hsv = Hsv::from_hsv(210, 1.0, 1.0);
let green_blue_rgb = Color::from_rgb(0.0, 0.5, 1.0);
assert_eq!(green_blue_rgb, green_blue_hsv.into());
let green_yellow_hsv = Hsv::from_hsv(90, 1.0, 1.0);
let green_yellow_rgb = Color::from_rgb(0.5, 1.0, 0.0);
assert_eq!(green_yellow_rgb, green_yellow_hsv.into());
let blue_red_hsv = Hsv::from_hsv(330, 1.0, 1.0);
let blue_red_rgb = Color::from_rgb(1.0, 0.0, 0.5);
assert_eq!(blue_red_rgb, blue_red_hsv.into());
let zinnober_hsv = Hsv::from_hsv(15, 1.0, 1.0);
let zinnober_rgb = Color::from_rgb(1.0, 0.25, 0.0);
assert_eq!(zinnober_rgb, zinnober_hsv.into());
let indigo_hsv = Hsv::from_hsv(255, 1.0, 1.0);
let indigo_rgb = Color::from_rgb(0.25, 0.0, 1.0);
assert_eq!(indigo_rgb, indigo_hsv.into());
let light_blue_green_hsv = Hsv::from_hsv(135, 1.0, 1.0);
let light_blue_green_rgb = Color::from_rgb(0.0, 1.0, 0.25);
assert_eq!(light_blue_green_rgb, light_blue_green_hsv.into());
let blue_cyan_hsv = Hsv::from_hsv(195, 1.0, 1.0);
let blue_cyan_rgb = Color::from_rgb(0.0, 0.75, 1.0);
assert_eq!(blue_cyan_rgb, blue_cyan_hsv.into());
let light_green_yellow_hsv = Hsv::from_hsv(75, 1.0, 1.0);
let light_green_yellow_rgb = Color::from_rgb(0.75, 1.0, 0.0);
assert_eq!(light_green_yellow_rgb, light_green_yellow_hsv.into());
let red_magenta_hsv = Hsv::from_hsv(315, 1.0, 1.0);
let red_magenta_rgb = Color::from_rgb(1.0, 0.0, 0.75);
assert_eq!(red_magenta_rgb, red_magenta_hsv.into());
let safran_hsv = Hsv::from_hsv(45, 1.0, 1.0);
let safran_rgb = Color::from_rgb(1.0, 0.75, 0.0);
assert_eq!(safran_rgb, safran_hsv.into());
let blue_magenta_hsv = Hsv::from_hsv(285, 1.0, 1.0);
let blue_magenta_rgb = Color::from_rgb(0.75, 0.0, 1.0);
assert_eq!(blue_magenta_rgb, blue_magenta_hsv.into());
let green_cyan_hsv = Hsv::from_hsv(165, 1.0, 1.0);
let green_cyan_rgb = Color::from_rgb(0.0, 1.0, 0.75);
assert_eq!(green_cyan_rgb, green_cyan_hsv.into());
let light_green_blue_hsv = Hsv::from_hsv(225, 1.0, 1.0);
let light_green_blue_rgb = Color::from_rgb(0.0, 0.25, 1.0);
assert_eq!(light_green_blue_rgb, light_green_blue_hsv.into());
let lime_hsv = Hsv::from_hsv(105, 1.0, 1.0);
let lime_rgb = Color::from_rgb(0.25, 1.0, 0.0);
assert_eq!(lime_rgb, lime_hsv.into());
let light_blue_red_hsv = Hsv::from_hsv(345, 1.0, 1.0);
let light_blue_red_rgb = Color::from_rgb(1.0, 0.0, 0.25);
assert_eq!(light_blue_red_rgb, light_blue_red_hsv.into());
}
}
+682
View File
@@ -0,0 +1,682 @@
//! Helper functions for calculating dates
use chrono::{Datelike, Duration, Local, NaiveDate};
use std::fmt::Display;
use std::sync::LazyLock;
/// The date value
#[derive(Clone, Copy, Debug)]
pub struct Date {
/// The year value of the date.
pub year: i32,
/// The month value of the date (1 - 12).
pub month: u32,
/// The day value of the date (1 - 31).
pub day: u32,
}
impl Default for Date {
fn default() -> Self {
Self {
year: 2024,
month: 1,
day: 1,
}
}
}
impl Date {
/// Creates a new date from the current timestamp.
#[must_use]
pub fn today() -> Self {
let today = Local::now().naive_local().date();
today.into()
}
/// Creates a new date.
#[must_use]
pub const fn from_ymd(year: i32, month: u32, day: u32) -> Self {
Self { year, month, day }
}
}
impl Display for Date {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
}
}
impl From<Date> for NaiveDate {
fn from(date: Date) -> Self {
Self::from_ymd_opt(date.year, date.month, date.day)
.expect("Year, Month or Day doesnt Exist")
}
}
impl From<NaiveDate> for Date {
fn from(date: NaiveDate) -> Self {
Self::from_ymd(date.year(), date.month(), date.day())
}
}
/// # Panics
/// Creates a date with the previous month based on the given date.
/// panics if year, month or day doesnt exist.
#[must_use]
pub fn pred_month(date: NaiveDate) -> NaiveDate {
let (year, month) = if date.month() == 1 {
(date.year() - 1, 12)
} else {
(date.year(), date.month() - 1)
};
let day = date.day().min(num_days_of_month(year, month));
NaiveDate::from_ymd_opt(year, month, day).expect("Year, Month or Day doesnt Exist")
}
/// # Panics
/// Creates a date with the next month based on given date.
/// panics if year, month or day doesnt exist.
#[must_use]
pub fn succ_month(date: NaiveDate) -> NaiveDate {
let (year, month) = if date.month() == 12 {
(date.year() + 1, 1)
} else {
(date.year(), date.month() + 1)
};
let day = date.day().min(num_days_of_month(year, month));
NaiveDate::from_ymd_opt(year, month, day).expect("Year, Month or Day doesnt Exist")
}
/// # Panics
/// Creates a date with the previous year based on the given date.
// panics if year, month or day doesnt exist.
#[must_use]
pub fn pred_year(date: NaiveDate) -> NaiveDate {
let year = date.year() - 1;
let day = date.day().min(num_days_of_month(year, date.month()));
NaiveDate::from_ymd_opt(year, date.month(), day).expect("Year, Month or Day doesnt Exist")
}
/// # Panics
/// Creates a date with the next year based on the given date.
// panics if year, month or day doesnt exist.
#[must_use]
pub fn succ_year(date: NaiveDate) -> NaiveDate {
let year = date.year() + 1;
let day = date.day().min(num_days_of_month(year, date.month()));
NaiveDate::from_ymd_opt(year, date.month(), day).expect("Year, Month or Day doesnt Exist")
}
/// Calculates a date with the previous week based on the given date.
#[must_use]
pub fn pred_week(date: NaiveDate) -> NaiveDate {
date - Duration::days(7)
}
/// Calculates a date with the next week based on the given date.
#[must_use]
pub fn succ_week(date: NaiveDate) -> NaiveDate {
date + Duration::days(7)
}
/// Calculates a date with the previous day based on the given date.
#[must_use]
pub fn pred_day(date: NaiveDate) -> NaiveDate {
date - Duration::days(1)
}
/// Calculates a date with the next day based on the given date.
#[must_use]
pub fn succ_day(date: NaiveDate) -> NaiveDate {
date + Duration::days(1)
}
/// Specifies if the calculated day lays in the previous, same or next month of
/// the date.
#[derive(Debug, PartialEq, Eq)]
pub enum IsInMonth {
/// The day lays in the previous month.
Previous,
/// The day lays in the same month.
Same,
/// The day lays in the next month.
Next,
}
/// # Panics
/// Calculates the day number at the given position in the calendar table based
/// on the given year and month.
/// panics if year, month or day does not exist.
#[must_use]
pub fn position_to_day(x: usize, y: usize, year: i32, month: u32) -> (usize, IsInMonth) {
let (x, y) = (x as isize, y as isize);
let first_day =
NaiveDate::from_ymd_opt(year, month, 1).expect("Year, Month or Day doesnt Exist");
let day_of_week = first_day.weekday().num_days_from_monday() as isize;
let day_of_week = if day_of_week == 0 { 7 } else { day_of_week };
let day = (x + 7 * y) + 1 - day_of_week;
if day < 1 {
let last_month = first_day.pred_opt().unwrap_or_default();
(
(num_days_of_month(last_month.year(), last_month.month()) as isize + day) as usize,
IsInMonth::Previous,
)
} else if day > num_days_of_month(year, month) as isize {
(
(day - num_days_of_month(year, month) as isize) as usize,
IsInMonth::Next,
)
} else {
(day as usize, IsInMonth::Same)
}
}
/// Checks if the given year is a leap year.
const fn is_leap_year(year: i32) -> bool {
let mod4 = year % 4 == 0;
let mod100 = year % 100 == 0;
let mod400 = year % 400 == 0;
mod4 && (!mod100 || mod400)
}
/// Gets the number of days the given month in the year has.
const fn num_days_of_month(year: i32, month: u32) -> u32 {
match month {
4 | 6 | 9 | 11 => 30,
2 => {
if is_leap_year(year) {
29
} else {
28
}
}
_ => 31,
}
}
/// Gets the string representation of the date of the given month and date.
#[must_use]
pub fn date_as_string(date: NaiveDate) -> String {
date.format("%Y %B").to_string()
}
/// Gets the length of the longest month name.
pub static MAX_MONTH_STR_LEN: LazyLock<usize> = LazyLock::new(|| {
let months = [
NaiveDate::from_ymd_opt(0, 1, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 2, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 3, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 4, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 5, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 6, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 7, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 8, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 9, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 10, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 11, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 12, 1).expect("Year, Month or Day doesnt Exist"),
];
months
.iter()
.map(|m| {
let d = date_as_string(*m);
let (_, s) = d.split_once(' ').expect("Date must contain space");
s.len()
})
.max()
.expect("There should be a maximum element")
});
/// Gets the labels of the weekdays containing the first two characters of
/// the weekdays.
pub static WEEKDAY_LABELS: LazyLock<Vec<String>> = LazyLock::new(|| {
let days = [
// Monday
NaiveDate::from_ymd_opt(2020, 6, 1).expect("Year, Month or Day doesnt Exist"),
// Tuesday
NaiveDate::from_ymd_opt(2020, 6, 2).expect("Year, Month or Day doesnt Exist"),
// Wednesday
NaiveDate::from_ymd_opt(2020, 6, 3).expect("Year, Month or Day doesnt Exist"),
// Thursday
NaiveDate::from_ymd_opt(2020, 6, 4).expect("Year, Month or Day doesnt Exist"),
// Friday
NaiveDate::from_ymd_opt(2020, 6, 5).expect("Year, Month or Day doesnt Exist"),
// Saturday
NaiveDate::from_ymd_opt(2020, 6, 6).expect("Year, Month or Day doesnt Exist"),
// Sunday
NaiveDate::from_ymd_opt(2020, 6, 7).expect("Year, Month or Day doesnt Exist"),
];
days.iter()
.map(|d| d.format("%a").to_string())
.map(|s| s[0..2].to_owned())
.collect()
});
#[cfg(test)]
mod tests {
use chrono::{Datelike, NaiveDate};
use super::{
IsInMonth, is_leap_year, num_days_of_month, position_to_day, pred_month, pred_year,
succ_month, succ_year,
};
#[test]
fn pred_month_test() {
let date = NaiveDate::from_ymd_opt(2020, 5, 6).expect("Year, Month or Day doesnt Exist");
let result = pred_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 4, 6).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 1, 24).expect("Year, Month or Day doesnt Exist");
let result = pred_month(date);
let expected =
NaiveDate::from_ymd_opt(2019, 12, 24).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 3, 31).expect("Year, Month or Day doesnt Exist");
let result = pred_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 2, 29).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
}
#[test]
fn succ_month_test() {
let date = NaiveDate::from_ymd_opt(2020, 5, 6).expect("Year, Month or Day doesnt Exist");
let result = succ_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 6, 6).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2019, 12, 24).expect("Year, Month or Day doesnt Exist");
let result = succ_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 1, 24).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 1, 31).expect("Year, Month or Day doesnt Exist");
let result = succ_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 2, 29).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
}
#[test]
fn pred_year_test() {
let date = NaiveDate::from_ymd_opt(2020, 5, 6).expect("Year, Month or Day doesnt Exist");
let result = pred_year(date);
let expected =
NaiveDate::from_ymd_opt(2019, 5, 6).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 2, 29).expect("Year, Month or Day doesnt Exist");
let result = pred_year(date);
let expected =
NaiveDate::from_ymd_opt(2019, 2, 28).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2021, 2, 28).expect("Year, Month or Day doesnt Exist");
let result = pred_year(date);
let expected =
NaiveDate::from_ymd_opt(2020, 2, 28).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
}
#[test]
fn succ_year_test() {
let date = NaiveDate::from_ymd_opt(2020, 5, 6).expect("Year, Month or Day doesnt Exist");
let result = succ_year(date);
let expected =
NaiveDate::from_ymd_opt(2021, 5, 6).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 2, 29).expect("Year, Month or Day doesnt Exist");
let result = succ_year(date);
let expected =
NaiveDate::from_ymd_opt(2021, 2, 28).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2019, 2, 28).expect("Year, Month or Day doesnt Exist");
let result = succ_year(date);
let expected =
NaiveDate::from_ymd_opt(2020, 2, 28).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
}
#[allow(clippy::shadow_unrelated)]
#[test]
fn position_to_day_test() {
let (day, is_in_month) = position_to_day(0, 0, 2020, 12);
assert_eq!(day, 30);
assert_eq!(is_in_month, IsInMonth::Previous);
let (day, is_in_month) = position_to_day(1, 0, 2020, 12);
assert_eq!(day, 1);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(3, 4, 2020, 12);
assert_eq!(day, 31);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(6, 5, 2020, 12);
assert_eq!(day, 10);
assert_eq!(is_in_month, IsInMonth::Next);
let (day, is_in_month) = position_to_day(0, 0, 2020, 11);
assert_eq!(day, 26);
assert_eq!(is_in_month, IsInMonth::Previous);
let (day, is_in_month) = position_to_day(6, 0, 2020, 11);
assert_eq!(day, 1);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(0, 5, 2020, 11);
assert_eq!(day, 30);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(6, 5, 2020, 11);
assert_eq!(day, 6);
assert_eq!(is_in_month, IsInMonth::Next);
let (day, is_in_month) = position_to_day(0, 0, 2021, 2);
assert_eq!(day, 25);
assert_eq!(is_in_month, IsInMonth::Previous);
let (day, is_in_month) = position_to_day(0, 1, 2021, 2);
assert_eq!(day, 1);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(6, 4, 2021, 2);
assert_eq!(day, 28);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(0, 5, 2021, 2);
assert_eq!(day, 1);
assert_eq!(is_in_month, IsInMonth::Next);
}
#[test]
fn is_leap_year_test() {
assert!(is_leap_year(2020));
assert!(!is_leap_year(2019));
assert!(!is_leap_year(2021));
assert!(is_leap_year(2000));
assert!(!is_leap_year(1000));
}
#[test]
fn num_days_of_month_test() {
assert_eq!(num_days_of_month(2020, 1), 31);
assert_eq!(num_days_of_month(2020, 2), 29);
assert_eq!(num_days_of_month(2019, 2), 28);
assert_eq!(num_days_of_month(2020, 3), 31);
assert_eq!(num_days_of_month(2020, 4), 30);
assert_eq!(num_days_of_month(2020, 5), 31);
assert_eq!(num_days_of_month(2020, 6), 30);
assert_eq!(num_days_of_month(2020, 7), 31);
assert_eq!(num_days_of_month(2020, 8), 31);
assert_eq!(num_days_of_month(2020, 9), 30);
assert_eq!(num_days_of_month(2020, 10), 31);
assert_eq!(num_days_of_month(2020, 11), 30);
assert_eq!(num_days_of_month(2020, 12), 31);
}
#[test]
fn date_default() {
use super::Date;
let date = Date::default();
assert_eq!(date.year, 2024);
assert_eq!(date.month, 1);
assert_eq!(date.day, 1);
}
#[test]
fn date_from_ymd() {
use super::Date;
let date = Date::from_ymd(2023, 12, 25);
assert_eq!(date.year, 2023);
assert_eq!(date.month, 12);
assert_eq!(date.day, 25);
}
#[test]
fn date_display() {
use super::Date;
let date = Date::from_ymd(2023, 3, 5);
assert_eq!(format!("{date}"), "2023-03-05");
let date = Date::from_ymd(2023, 12, 31);
assert_eq!(format!("{date}"), "2023-12-31");
let date = Date::from_ymd(1999, 1, 1);
assert_eq!(format!("{date}"), "1999-01-01");
}
#[test]
fn date_to_naive_date() {
use super::Date;
let date = Date::from_ymd(2023, 6, 15);
let naive: NaiveDate = date.into();
assert_eq!(naive.year(), 2023);
assert_eq!(naive.month(), 6);
assert_eq!(naive.day(), 15);
}
#[test]
fn naive_date_to_date() {
use super::Date;
let naive =
NaiveDate::from_ymd_opt(2023, 6, 15).expect("naive_date_to_date should not be none");
let date: Date = naive.into();
assert_eq!(date.year, 2023);
assert_eq!(date.month, 6);
assert_eq!(date.day, 15);
}
#[test]
fn pred_week_test() {
use super::pred_week;
let date = NaiveDate::from_ymd_opt(2020, 5, 15).expect("pred_week_test should not be none");
let result = pred_week(date);
let expected =
NaiveDate::from_ymd_opt(2020, 5, 8).expect("pred_week_test should not be none");
assert_eq!(result, expected);
}
#[test]
fn pred_week_crosses_month() {
use super::pred_week;
let date = NaiveDate::from_ymd_opt(2020, 5, 5)
.expect("pred_week_crosses_month should not be none");
let result = pred_week(date);
let expected = NaiveDate::from_ymd_opt(2020, 4, 28)
.expect("pred_week_crosses_month should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_week_test() {
use super::succ_week;
let date = NaiveDate::from_ymd_opt(2020, 5, 15).expect("succ_week_test should not be none");
let result = succ_week(date);
let expected =
NaiveDate::from_ymd_opt(2020, 5, 22).expect("succ_week_test should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_week_crosses_month() {
use super::succ_week;
let date = NaiveDate::from_ymd_opt(2020, 5, 28)
.expect("succ_week_crosses_month should not be none");
let result = succ_week(date);
let expected = NaiveDate::from_ymd_opt(2020, 6, 4)
.expect("succ_week_crosses_month should not be none");
assert_eq!(result, expected);
}
#[test]
fn pred_day_test() {
use super::pred_day;
let date = NaiveDate::from_ymd_opt(2020, 5, 15).expect("pred_day_test should not be none");
let result = pred_day(date);
let expected =
NaiveDate::from_ymd_opt(2020, 5, 14).expect("pred_day_test should not be none");
assert_eq!(result, expected);
}
#[test]
fn pred_day_crosses_month() {
use super::pred_day;
let date =
NaiveDate::from_ymd_opt(2020, 5, 1).expect("pred_day_crosses_month should not be none");
let result = pred_day(date);
let expected = NaiveDate::from_ymd_opt(2020, 4, 30)
.expect("pred_day_crosses_month should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_day_test() {
use super::succ_day;
let date = NaiveDate::from_ymd_opt(2020, 5, 15).expect("succ_day_test should not be none");
let result = succ_day(date);
let expected =
NaiveDate::from_ymd_opt(2020, 5, 16).expect("succ_day_test should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_day_crosses_month() {
use super::succ_day;
let date = NaiveDate::from_ymd_opt(2020, 5, 31)
.expect("succ_day_crosses_month should not be none");
let result = succ_day(date);
let expected =
NaiveDate::from_ymd_opt(2020, 6, 1).expect("succ_day_crosses_month should not be none");
assert_eq!(result, expected);
}
#[test]
fn date_as_string_test() {
use super::date_as_string;
let date =
NaiveDate::from_ymd_opt(2023, 1, 15).expect("date_as_string_test should not be none");
let result = date_as_string(date);
assert!(result.starts_with("2023"));
assert!(result.contains("January") || result.contains("Jan"));
}
#[test]
fn is_leap_year_century_rules() {
// Century years divisible by 400 are leap years
assert!(is_leap_year(2000));
assert!(is_leap_year(2400));
// Century years not divisible by 400 are not leap years
assert!(!is_leap_year(1900));
assert!(!is_leap_year(2100));
assert!(!is_leap_year(2200));
assert!(!is_leap_year(2300));
}
#[test]
fn is_leap_year_edge_cases() {
// Regular leap years
assert!(is_leap_year(2024));
assert!(is_leap_year(2028));
// Regular non-leap years
assert!(!is_leap_year(2023));
assert!(!is_leap_year(2025));
assert!(!is_leap_year(2026));
assert!(!is_leap_year(2027));
}
#[test]
fn max_month_str_len_is_defined() {
use super::MAX_MONTH_STR_LEN;
// Just verify it's accessible and has a reasonable value
assert!(*MAX_MONTH_STR_LEN > 0);
assert!(*MAX_MONTH_STR_LEN <= 20); // No month name should be longer than 20 chars
}
#[test]
fn weekday_labels_has_seven_days() {
use super::WEEKDAY_LABELS;
assert_eq!(WEEKDAY_LABELS.len(), 7);
// Each label should be exactly 2 characters
for label in WEEKDAY_LABELS.iter() {
assert_eq!(label.len(), 2);
}
}
#[test]
fn pred_month_february_to_january() {
let date = NaiveDate::from_ymd_opt(2020, 2, 15)
.expect("pred_month_february_to_january should not be none");
let result = pred_month(date);
let expected = NaiveDate::from_ymd_opt(2020, 1, 15)
.expect("pred_month_february_to_january should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_month_november_to_december() {
let date = NaiveDate::from_ymd_opt(2020, 11, 15)
.expect("succ_month_november_to_december should not be none");
let result = succ_month(date);
let expected = NaiveDate::from_ymd_opt(2020, 12, 15)
.expect("succ_month_november_to_december should not be none");
assert_eq!(result, expected);
}
#[test]
fn num_days_february_leap_vs_non_leap() {
// Leap year
assert_eq!(num_days_of_month(2020, 2), 29);
assert_eq!(num_days_of_month(2024, 2), 29);
// Non-leap year
assert_eq!(num_days_of_month(2019, 2), 28);
assert_eq!(num_days_of_month(2021, 2), 28);
assert_eq!(num_days_of_month(2022, 2), 28);
assert_eq!(num_days_of_month(2023, 2), 28);
}
#[test]
fn date_copy_trait() {
use super::Date;
let date1 = Date::from_ymd(2023, 6, 15);
let date2 = date1; // Copy
// Both should be usable
assert_eq!(date1.year, 2023);
assert_eq!(date2.year, 2023);
}
#[test]
fn date_clone_trait() {
use super::Date;
let date1 = Date::from_ymd(2023, 6, 15);
let date2 = date1;
assert_eq!(date1.year, date2.year);
assert_eq!(date1.month, date2.month);
assert_eq!(date1.day, date2.day);
}
}
+134
View File
@@ -0,0 +1,134 @@
//! Offset struct
use iced_core::Point;
/// Represents an offset in a two-dimensional space.
#[derive(Copy, Clone, Debug)]
pub struct Offset {
/// Offset on the x-axis
pub x: f32,
/// Offset on the y-axis
pub y: f32,
}
impl Offset {
/// Construct a new [`Offset`]
#[must_use]
pub fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
impl From<f32> for Offset {
fn from(float: f32) -> Self {
Self { x: float, y: float }
}
}
impl From<[f32; 2]> for Offset {
fn from(array: [f32; 2]) -> Self {
Self {
x: array[0],
y: array[1],
}
}
}
impl From<Offset> for Point {
fn from(offset: Offset) -> Self {
Self::new(offset.x, offset.y)
}
}
impl From<&Offset> for Point {
fn from(offset: &Offset) -> Self {
Self::new(offset.x, offset.y)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_creates_offset() {
let offset = Offset::new(10.0, 20.0);
assert_eq!(offset.x, 10.0);
assert_eq!(offset.y, 20.0);
}
#[test]
fn new_handles_negative_values() {
let offset = Offset::new(-5.0, -15.0);
assert_eq!(offset.x, -5.0);
assert_eq!(offset.y, -15.0);
}
#[test]
fn new_handles_zero() {
let offset = Offset::new(0.0, 0.0);
assert_eq!(offset.x, 0.0);
assert_eq!(offset.y, 0.0);
}
#[test]
fn from_f32_creates_offset_with_same_values() {
let offset = Offset::from(5.0);
assert_eq!(offset.x, 5.0);
assert_eq!(offset.y, 5.0);
}
#[test]
fn from_f32_handles_negative() {
let offset = Offset::from(-3.5);
assert_eq!(offset.x, -3.5);
assert_eq!(offset.y, -3.5);
}
#[test]
fn from_array_creates_offset() {
let offset = Offset::from([12.0, 34.0]);
assert_eq!(offset.x, 12.0);
assert_eq!(offset.y, 34.0);
}
#[test]
fn from_array_handles_different_signs() {
let offset = Offset::from([-7.5, 8.5]);
assert_eq!(offset.x, -7.5);
assert_eq!(offset.y, 8.5);
}
#[test]
fn offset_to_point_conversion() {
let offset = Offset::new(15.0, 25.0);
let point: Point = offset.into();
assert_eq!(point.x, 15.0);
assert_eq!(point.y, 25.0);
}
#[test]
fn offset_ref_to_point_conversion() {
let offset = Offset::new(15.0, 25.0);
let point: Point = (&offset).into();
assert_eq!(point.x, 15.0);
assert_eq!(point.y, 25.0);
}
#[test]
fn offset_is_copy() {
let offset1 = Offset::new(1.0, 2.0);
let offset2 = offset1;
// Both should be usable since Offset implements Copy
assert_eq!(offset1.x, 1.0);
assert_eq!(offset2.x, 1.0);
}
#[test]
fn offset_is_clone() {
let offset1 = Offset::new(3.0, 4.0);
let offset2 = offset1;
assert_eq!(offset1.x, offset2.x);
assert_eq!(offset1.y, offset2.y);
}
}
+214
View File
@@ -0,0 +1,214 @@
//! Helper functions for overlays
use iced_core::{Point, Size, layout};
/// Trait containing functions for positioning of nodes.
pub trait Position {
/// Centers this node around the given position. If the node is over the
/// specified bounds it's bouncing back to be fully visible on screen.
fn center_and_bounce(&mut self, position: Point, bounds: Size);
}
impl Position for layout::Node {
fn center_and_bounce(&mut self, position: Point, bounds: Size) {
let size = self.size();
self.move_to_mut(Point::new(
(position.x - (size.width / 2.0)).max(0.0),
(position.y - (size.height / 2.0)).max(0.0),
));
let new_self_bounds = self.bounds();
self.move_to_mut(Point::new(
if new_self_bounds.x + new_self_bounds.width > bounds.width {
(new_self_bounds.x - (new_self_bounds.width - (bounds.width - new_self_bounds.x)))
.max(0.0)
} else {
new_self_bounds.x
},
if new_self_bounds.y + new_self_bounds.height > bounds.height {
(new_self_bounds.y - (new_self_bounds.height - (bounds.height - new_self_bounds.y)))
.max(0.0)
} else {
new_self_bounds.y
},
));
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::layout::Node;
#[test]
fn center_within_bounds() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node should be centered at position: x = 200 - 50 = 150, y = 150 - 25 = 125
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 150.0);
assert_eq!(node_bounds.y, 125.0);
}
#[test]
fn bounce_right_edge() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(380.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node would center at x = 380 - 50 = 330, which extends to 430
// This exceeds bounds.width (400), so should bounce back to x = 300
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 300.0);
assert_eq!(node_bounds.y, 125.0);
}
#[test]
fn bounce_bottom_edge() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(200.0, 285.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node would center at y = 285 - 25 = 260, which extends to 310
// This exceeds bounds.height (300), so should bounce back to y = 250
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 150.0);
assert_eq!(node_bounds.y, 250.0);
}
#[test]
fn bounce_right_and_bottom() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(380.0, 285.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Should bounce back on both axes
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 300.0);
assert_eq!(node_bounds.y, 250.0);
}
#[test]
fn position_at_origin() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(0.0, 0.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Centering at origin would give negative position, but it's clamped to 0
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 0.0);
assert_eq!(node_bounds.y, 0.0);
}
#[test]
fn position_near_top_left() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(10.0, 10.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Would center at negative position, clamped to 0
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 0.0);
assert_eq!(node_bounds.y, 0.0);
}
#[test]
fn exact_fit_at_corner() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(350.0, 275.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node centers at (300, 250) and fits exactly within bounds
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 300.0);
assert_eq!(node_bounds.y, 250.0);
}
#[test]
fn small_node_centered() {
let mut node = Node::new(Size::new(20.0, 10.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Small node should center perfectly
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 190.0);
assert_eq!(node_bounds.y, 145.0);
}
#[test]
fn node_larger_than_bounds() {
let mut node = Node::new(Size::new(500.0, 400.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node is larger than bounds, should position at (0, 0) as best effort
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 0.0);
assert_eq!(node_bounds.y, 0.0);
}
#[test]
fn node_width_equals_bounds_width() {
let mut node = Node::new(Size::new(400.0, 50.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node width equals bounds, should position at x = 0
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 0.0);
assert_eq!(node_bounds.y, 125.0);
}
#[test]
fn node_height_equals_bounds_height() {
let mut node = Node::new(Size::new(100.0, 300.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node height equals bounds, should position at y = 0
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 150.0);
assert_eq!(node_bounds.y, 0.0);
}
#[test]
fn position_at_exact_bounds() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(400.0, 300.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Position at bounds edge, should bounce back
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 300.0);
assert_eq!(node_bounds.y, 250.0);
}
}
+20
View File
@@ -0,0 +1,20 @@
//! Helper struct for drawing
use iced_core::{Layout, Point, Rectangle};
/// Collection of all necessary data to draw a widget.
#[derive(Debug)]
pub struct DrawEnvironment<'a, Defaults, Style, Focus> {
/// The defaults of the renderer.
pub defaults: &'a Defaults,
/// The layout of the widget.
pub layout: Layout<'a>,
/// The position of the cursor.
pub cursor_position: Point,
/// The style of the widget.
pub style_sheet: &'a Style,
/// The viewport of the renderer.
pub viewport: Option<&'a Rectangle>,
/// The focus to an input element on the widget.
pub focus: Focus,
}
+683
View File
@@ -0,0 +1,683 @@
//! Use a time picker as an input element for picking times.
//!
//! *This API requires the following crate features to be activated: `time_picker`*
use chrono::{Local, Timelike};
use std::fmt::Display;
/// The time value
#[derive(Clone, Copy, Debug)]
pub enum Time {
/// The time value containing hour, minute and period.
Hm {
/// The hour value.
hour: u32,
/// The minute value.
minute: u32,
/// The current period of the time.
period: Period,
},
/// The time value containing hour, minute, second and period.
Hms {
/// The hour value.
hour: u32,
/// The minute value.
minute: u32,
/// The second value.
second: u32,
/// The current period of the time.
period: Period,
},
}
impl Default for Time {
fn default() -> Self {
Self::Hm {
hour: 1,
minute: 0,
period: Period::Am,
}
}
}
impl Time {
/// Creates a new time (hours, minutes) from the current timestamp.
#[must_use]
pub fn now_hm(use_24h: bool) -> Self {
let now = Local::now().naive_local().time();
let (hour, period) = if use_24h {
(now.hour(), Period::H24)
} else {
let (period, hour12) = now.hour12();
(hour12, if period { Period::Pm } else { Period::Am })
};
Self::Hm {
hour,
minute: now.minute(),
period,
}
}
/// Creates a new time (hours, minutes, seconds) from the current timestamp.
#[must_use]
pub fn now_hms(use_24h: bool) -> Self {
let now = Local::now().naive_local().time();
let (hour, period) = if use_24h {
(now.hour(), Period::H24)
} else {
let (period, hour12) = now.hour12();
(hour12, if period { Period::Pm } else { Period::Am })
};
Self::Hms {
hour,
minute: now.minute(),
second: now.second(),
period,
}
}
/// The default time `00:00` with the given period.
#[must_use]
pub const fn default_hm(period: Period) -> Self {
Self::Hm {
hour: 0,
minute: 0,
period,
}
}
/// The default time `00:00:00` with the given period.
#[must_use]
pub const fn default_hms(period: Period) -> Self {
Self::Hms {
hour: 0,
minute: 0,
second: 0,
period,
}
}
}
impl Display for Time {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Hm {
hour,
minute,
period,
} => {
write!(f, "{hour:02}:{minute:02}{period}")
}
Self::Hms {
hour,
minute,
second,
period,
} => {
write!(f, "{hour:02}:{minute:02}:{second:02}{period}")
}
}
}
}
/// The current period of the clock
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Period {
/// No period - using 24 hour format.
H24,
/// Ante meridiem: Before noon.
Am,
/// Post meridiem: After noon.
Pm,
}
impl Display for Period {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::H24 => "",
Self::Am => " AM",
Self::Pm => " PM",
}
)
}
}
impl From<Time> for chrono::NaiveTime {
fn from(time: Time) -> Self {
let (h, m, s, p) = match time {
Time::Hm {
hour,
minute,
period,
} => (hour, minute, 0, period),
Time::Hms {
hour,
minute,
second,
period,
} => (hour, minute, second, period),
};
let h = if h == 12 && p != Period::H24 { 0 } else { h };
let h = match p {
Period::H24 | Period::Am => h,
Period::Pm => (h + 12) % 24,
};
Self::from_hms_opt(h, m, s).expect("Time Conversion failed. H, M, or S was too large.")
}
}
impl From<chrono::NaiveTime> for Time {
fn from(time: chrono::NaiveTime) -> Self {
Self::Hms {
hour: time.hour(),
minute: time.minute(),
second: time.second(),
period: Period::H24,
}
}
}
#[cfg(test)]
mod tests {
use chrono::NaiveTime;
use super::{Period, Time};
#[test]
fn time_to_naive() {
let time = Time::Hms {
hour: 8,
minute: 52,
second: 17,
period: Period::H24,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(8, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 23,
minute: 48,
second: 39,
period: Period::H24,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(23, 48, 39).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 8,
minute: 52,
second: 17,
period: Period::Am,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(8, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 8,
minute: 52,
second: 17,
period: Period::Pm,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(20, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 12,
minute: 52,
second: 17,
period: Period::Am,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(0, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 12,
minute: 52,
second: 17,
period: Period::Pm,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(12, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hm {
hour: 17,
minute: 52,
period: Period::H24,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(17, 52, 0).expect("Time Conversion failed")
);
}
#[test]
fn time_default() {
let time = Time::default();
match time {
Time::Hm {
hour,
minute,
period,
} => {
assert_eq!(hour, 1);
assert_eq!(minute, 0);
assert_eq!(period, Period::Am);
}
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
}
}
#[test]
fn time_default_hm_am() {
let time = Time::default_hm(Period::Am);
match time {
Time::Hm {
hour,
minute,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(period, Period::Am);
}
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
}
}
#[test]
fn time_default_hm_pm() {
let time = Time::default_hm(Period::Pm);
match time {
Time::Hm {
hour,
minute,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(period, Period::Pm);
}
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
}
}
#[test]
fn time_default_hm_h24() {
let time = Time::default_hm(Period::H24);
match time {
Time::Hm {
hour,
minute,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(period, Period::H24);
}
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
}
}
#[test]
fn time_default_hms_am() {
let time = Time::default_hms(Period::Am);
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(second, 0);
assert_eq!(period, Period::Am);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn time_default_hms_pm() {
let time = Time::default_hms(Period::Pm);
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(second, 0);
assert_eq!(period, Period::Pm);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn time_default_hms_h24() {
let time = Time::default_hms(Period::H24);
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(second, 0);
assert_eq!(period, Period::H24);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn time_hm_display_h24() {
let time = Time::Hm {
hour: 14,
minute: 30,
period: Period::H24,
};
assert_eq!(format!("{time}"), "14:30");
}
#[test]
fn time_hm_display_am() {
let time = Time::Hm {
hour: 9,
minute: 15,
period: Period::Am,
};
assert_eq!(format!("{time}"), "09:15 AM");
}
#[test]
fn time_hm_display_pm() {
let time = Time::Hm {
hour: 3,
minute: 45,
period: Period::Pm,
};
assert_eq!(format!("{time}"), "03:45 PM");
}
#[test]
fn time_hms_display_h24() {
let time = Time::Hms {
hour: 23,
minute: 59,
second: 59,
period: Period::H24,
};
assert_eq!(format!("{time}"), "23:59:59");
}
#[test]
fn time_hms_display_am() {
let time = Time::Hms {
hour: 6,
minute: 30,
second: 45,
period: Period::Am,
};
assert_eq!(format!("{time}"), "06:30:45 AM");
}
#[test]
fn time_hms_display_pm() {
let time = Time::Hms {
hour: 11,
minute: 22,
second: 33,
period: Period::Pm,
};
assert_eq!(format!("{time}"), "11:22:33 PM");
}
#[test]
fn period_display_h24() {
assert_eq!(format!("{}", Period::H24), "");
}
#[test]
fn period_display_am() {
assert_eq!(format!("{}", Period::Am), " AM");
}
#[test]
fn period_display_pm() {
assert_eq!(format!("{}", Period::Pm), " PM");
}
#[test]
fn naive_time_to_time() {
let naive =
NaiveTime::from_hms_opt(14, 30, 45).expect("naive_time_to_time should not be none");
let time: Time = naive.into();
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 14);
assert_eq!(minute, 30);
assert_eq!(second, 45);
assert_eq!(period, Period::H24);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn naive_time_midnight_to_time() {
let naive = NaiveTime::from_hms_opt(0, 0, 0)
.expect("naive_time_midnight_to_time should not be none");
let time: Time = naive.into();
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(second, 0);
assert_eq!(period, Period::H24);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn time_hm_midnight_am_to_naive() {
let time = Time::Hm {
hour: 12,
minute: 0,
period: Period::Am,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(0, 0, 0)
.expect("time_hm_midnight_am_to_naive Should not be none")
);
}
#[test]
fn time_hm_noon_pm_to_naive() {
let time = Time::Hm {
hour: 12,
minute: 0,
period: Period::Pm,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(12, 0, 0).expect("time_hm_noon_pm_to_naive Should not be none")
);
}
#[test]
fn time_hm_one_am_to_naive() {
let time = Time::Hm {
hour: 1,
minute: 30,
period: Period::Am,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(1, 30, 0).expect("time_hm_one_am_to_naive Should not be none")
);
}
#[test]
fn time_hm_eleven_pm_to_naive() {
let time = Time::Hm {
hour: 11,
minute: 45,
period: Period::Pm,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(23, 45, 0)
.expect("time_hm_eleven_pm_to_naive Should not be none")
);
}
#[test]
fn time_copy_trait() {
let time1 = Time::Hm {
hour: 10,
minute: 30,
period: Period::Am,
};
let time2 = time1; // Copy
// Both should be usable
match time1 {
Time::Hm { hour, .. } => assert_eq!(hour, 10),
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm"),
}
match time2 {
Time::Hm { hour, .. } => assert_eq!(hour, 10),
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm"),
}
}
#[test]
fn time_clone_trait() {
let time1 = Time::Hms {
hour: 15,
minute: 45,
second: 30,
period: Period::H24,
};
let time2 = time1;
match (time1, time2) {
(
Time::Hms {
hour: h1,
minute: m1,
second: s1,
period: p1,
},
Time::Hms {
hour: h2,
minute: m2,
second: s2,
period: p2,
},
) => {
assert_eq!(h1, h2);
assert_eq!(m1, m2);
assert_eq!(s1, s2);
assert_eq!(p1, p2);
}
#[allow(clippy::panic)]
_ => panic!("Expected Time::Hms for both"),
}
}
#[test]
fn period_copy_trait() {
let p1 = Period::Am;
let p2 = p1; // Copy
assert_eq!(p1, Period::Am);
assert_eq!(p2, Period::Am);
}
#[test]
fn period_clone_trait() {
let p1 = Period::Pm;
let p2 = p1;
assert_eq!(p1, p2);
}
#[test]
fn period_equality() {
assert_eq!(Period::Am, Period::Am);
assert_eq!(Period::Pm, Period::Pm);
assert_eq!(Period::H24, Period::H24);
assert_ne!(Period::Am, Period::Pm);
assert_ne!(Period::Am, Period::H24);
assert_ne!(Period::Pm, Period::H24);
}
}
+178
View File
@@ -0,0 +1,178 @@
//! Additional widget for the Iced GUI library.
//!
//! # Examples
//!
//! * `badge` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `card` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `color_picker` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `context_menu` (Author: wiiznokes <wiiznokes2@gmail.com>)
//! * `date_picker` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `drop_down` (Author: wiiznokes <wiiznokes2@gmail.com>)
//! * `menu`
//! * `number_input` (Author: leang27 <52003343+leang27@users.noreply.github.com>)
//! * `selection_list` (Author: Héctor Ramón Jiménez <hector0193@gmail.com> and Andrew Wheeler <genusistimelord@gmail.com>)
//! * `side_bar` (Author: Kaiden42 <gitlab@tinysn.com> and Rizzen Yazston)
//! * `slide_bar` (Author: Andrew Wheeler <genusistimelord@gmail.com>)
//! * `spinner` (Author: Iohann Rabeson <irabeson42@gmail.com>)
//! * `tab_bar` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `tabs` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `time_picker` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `typed_input` (Author: Ultraxime <36888699+Ultraxime@users.noreply.github.com>)
//! * `widget_id_return` (Author: Andrew Wheeler <genusistimelord@gmail.com>)
//! * `wrap` (Author: owntime <yrainbxqc@gmail.com>)
//! * `labeled_frame` (Author: JL710)
#![deny(missing_docs)]
#![deny(unused_results)]
#![forbid(unsafe_code)]
#![warn(
clippy::pedantic,
clippy::nursery,
// Restriction lints
clippy::clone_on_ref_ptr,
clippy::create_dir,
clippy::dbg_macro,
clippy::decimal_literal_representation,
clippy::exit,
clippy::float_cmp_const,
clippy::get_unwrap,
clippy::let_underscore_must_use,
clippy::map_err_ignore,
clippy::mem_forget,
clippy::missing_docs_in_private_items,
clippy::multiple_inherent_impl,
clippy::panic,
clippy::panic_in_result_fn,
clippy::print_stderr,
clippy::print_stdout,
clippy::rest_pat_in_fully_bound_structs,
clippy::str_to_string,
clippy::todo,
clippy::unimplemented,
clippy::unneeded_field_pattern,
clippy::unwrap_in_result,
clippy::unwrap_used,
clippy::use_debug,
)]
#![allow(
clippy::suboptimal_flops,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_possible_wrap,
clippy::module_name_repetitions,
clippy::borrowed_box,
clippy::missing_const_for_fn,
clippy::too_many_lines,
clippy::cast_precision_loss,
clippy::missing_docs_in_private_items,
clippy::unit_arg,
clippy::trivially_copy_pass_by_ref,
clippy::let_unit_value,
clippy::float_cmp
)]
pub mod widget;
#[deprecated(since = "0.9.4", note = "use `widget` instead")]
pub use widget as widgets;
pub mod core;
pub mod style;
pub use iced_fonts;
/// Exports for all platforms that are not WASM32.
mod platform {
#[allow(unused_imports)]
pub use crate::style;
pub use crate::widget::helpers;
#[doc(no_inline)]
#[cfg(feature = "badge")]
pub use {crate::widget::badge, badge::Badge};
#[doc(no_inline)]
#[cfg(feature = "card")]
pub use {crate::widget::card, card::Card};
#[doc(no_inline)]
#[cfg(feature = "color_picker")]
pub use {crate::widget::color_picker, color_picker::ColorPicker};
#[doc(no_inline)]
#[cfg(feature = "date_picker")]
pub use {crate::widget::date_picker, date_picker::DatePicker};
#[doc(no_inline)]
#[cfg(feature = "tab_bar")]
pub use {
crate::widget::tab_bar,
tab_bar::{TabBar, TabLabel},
};
#[doc(no_inline)]
#[cfg(feature = "tabs")]
pub use {
crate::widget::tabs,
tabs::{TabBarPosition, Tabs},
};
#[doc(no_inline)]
#[cfg(feature = "time_picker")]
pub use {crate::widget::time_picker, time_picker::TimePicker};
#[doc(no_inline)]
#[cfg(feature = "wrap")]
pub use {crate::widget::wrap, wrap::Wrap, wrap::direction};
#[doc(no_inline)]
#[cfg(feature = "number_input")]
pub use {crate::widget::number_input, number_input::NumberInput};
#[doc(no_inline)]
#[cfg(feature = "typed_input")]
pub use {crate::widget::typed_input, typed_input::TypedInput};
#[doc(no_inline)]
#[cfg(feature = "selection_list")]
pub use {crate::widget::selection_list, selection_list::SelectionList};
#[doc(no_inline)]
#[cfg(feature = "menu")]
pub use {crate::widget::menu, menu::Menu, menu::MenuBar};
#[doc(no_inline)]
#[cfg(feature = "quad")]
pub use {crate::widget::quad, quad::Quad};
#[doc(no_inline)]
#[cfg(feature = "spinner")]
pub use {crate::widget::spinner, spinner::Spinner};
#[doc(no_inline)]
#[cfg(feature = "slide_bar")]
pub use crate::widget::SlideBar;
#[doc(no_inline)]
#[cfg(feature = "context_menu")]
pub use {crate::widget::context_menu, context_menu::ContextMenu};
#[doc(no_inline)]
#[cfg(feature = "drop_down")]
pub use {crate::widget::drop_down, drop_down::DropDown};
#[doc(no_inline)]
#[cfg(feature = "sidebar")]
pub use crate::widget::sidebar;
}
#[doc(no_inline)]
pub use platform::*;
use iced_core::Font;
use iced_fonts::generate_icon_functions;
/// Embedded font file. There a handfull of glyphs so no need to worry.
pub const ICED_AW_FONT_BYTES: &[u8] = include_bytes!("../font.ttf");
/// Font type to use in text widgets.
pub const ICED_AW_FONT: Font = Font::with_name("iced_aw");
// The icon macro resolves this path from the workspace root.
generate_icon_functions!("vendor/iced_aw/font.ttf", iced_aw_font, ICED_AW_FONT);
+40
View File
@@ -0,0 +1,40 @@
//! The appearance of the widget
pub mod colors;
pub mod status;
pub mod style_state;
pub use status::{Status, StyleFn};
#[cfg(feature = "badge")]
pub mod badge;
#[cfg(feature = "card")]
pub mod card;
#[cfg(feature = "color_picker")]
pub mod color_picker;
#[cfg(feature = "date_picker")]
pub mod date_picker;
#[cfg(feature = "tab_bar")]
pub mod tab_bar;
#[cfg(feature = "time_picker")]
pub mod time_picker;
#[cfg(feature = "number_input")]
pub mod number_input;
#[cfg(feature = "selection_list")]
pub mod selection_list;
#[cfg(feature = "menu")]
pub mod menu_bar;
#[cfg(feature = "context_menu")]
pub mod context_menu;
#[cfg(feature = "sidebar")]
pub mod sidebar;
+475
View File
@@ -0,0 +1,475 @@
//! Use a badge for color highlighting important information.
//!
//! *This API requires the following crate features to be activated: badge*
use super::{Status, StyleFn, colors};
use iced_core::{Background, Color, Theme, theme::palette};
/// The style of a [`Badge`](crate::widget::badge::Badge).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`Badge`](crate::widget::badge::Badge).
pub background: Background,
/// The border radius of the [`Badge`](crate::widget::badge::Badge).
/// If no radius is specified the default one will be used.
pub border_radius: Option<f32>,
/// The border with of the [`Badge`](crate::widget::badge::Badge).
pub border_width: f32,
/// The border color of the [`Badge`](crate::widget::badge::Badge).
pub border_color: Option<Color>,
/// The default text color of the [`Badge`](crate::widget::badge::Badge).
pub text_color: Color,
}
/// The Catalog of a [`Badge`](crate::widget::badge::Badge).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl std::default::Default for Style {
fn default() -> Self {
Self {
background: Background::Color([0.87, 0.87, 0.87].into()),
border_radius: None,
border_width: 1.0,
border_color: Some([0.8, 0.8, 0.8].into()),
text_color: Color::BLACK,
}
}
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = styled(palette.primary.strong);
match status {
Status::Hovered => Style {
background: Background::Color(palette.primary.base.color),
..base
},
Status::Disabled => disabled(base),
_ => base,
}
}
/// The secondary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn secondary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = styled(palette.secondary.strong);
match status {
Status::Hovered => Style {
background: Background::Color(palette.primary.base.color),
..base
},
Status::Disabled => disabled(base),
_ => base,
}
}
/// The success theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn success(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = styled(palette.success.strong);
match status {
Status::Hovered => Style {
background: Background::Color(palette.primary.base.color),
..base
},
Status::Disabled => disabled(base),
_ => base,
}
}
/// The danger theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn danger(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = styled(palette.danger.strong);
match status {
Status::Hovered => Style {
background: Background::Color(palette.primary.base.color),
..base
},
Status::Disabled => disabled(base),
_ => base,
}
}
/// The warning theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn warning(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::WARNING, colors::BLACK);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
/// The info theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn info(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::INFO, colors::BLACK);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
/// The light theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn light(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::LIGHT, colors::BLACK);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
/// The dark theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn dark(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::DARK, colors::WHITE);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
/// The white theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn white(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::WHITE, colors::BLACK);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
fn from_color(color: Color, text_color: Color) -> Style {
Style {
background: Background::Color(color),
border_color: Some(color),
text_color,
..Style::default()
}
}
fn styled(pair: palette::Pair) -> Style {
Style {
background: Background::Color(pair.color),
border_color: Some(pair.color),
text_color: pair.text,
..Style::default()
}
}
fn disabled(style: Style) -> Style {
Style {
background: style.background.scale_alpha(0.5),
text_color: style.text_color.scale_alpha(0.5),
..style
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Color, Theme};
#[test]
fn style_default() {
let style = Style::default();
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_radius.is_none());
assert_eq!(style.border_width, 1.0);
assert!(style.border_color.is_some());
assert_eq!(style.text_color, Color::BLACK);
}
#[test]
fn from_color_creates_style() {
let color = Color::from_rgb(1.0, 0.0, 0.0);
let text = Color::WHITE;
let style = from_color(color, text);
assert_eq!(style.background, Background::Color(color));
assert_eq!(style.border_color, Some(color));
assert_eq!(style.text_color, text);
assert_eq!(style.border_width, 1.0);
assert!(style.border_radius.is_none());
}
#[test]
fn disabled_scales_alpha() {
let base = Style {
background: Background::Color(Color::from_rgb(1.0, 0.0, 0.0)),
border_radius: Some(5.0),
border_width: 2.0,
border_color: Some(Color::from_rgb(0.5, 0.5, 0.5)),
text_color: Color::WHITE,
};
let disabled_style = disabled(base);
// Background and text color should have scaled alpha
assert!(matches!(disabled_style.background, Background::Color(_)));
assert_eq!(disabled_style.border_radius, Some(5.0));
assert_eq!(disabled_style.border_width, 2.0);
assert_eq!(
disabled_style.border_color,
Some(Color::from_rgb(0.5, 0.5, 0.5))
);
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn secondary_theme_active() {
let theme = Theme::TokyoNight;
let style = secondary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn secondary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = secondary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn secondary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = secondary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn success_theme_active() {
let theme = Theme::TokyoNight;
let style = success(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn success_theme_hovered() {
let theme = Theme::TokyoNight;
let style = success(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn success_theme_disabled() {
let theme = Theme::TokyoNight;
let style = success(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn danger_theme_active() {
let theme = Theme::TokyoNight;
let style = danger(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn danger_theme_hovered() {
let theme = Theme::TokyoNight;
let style = danger(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn danger_theme_disabled() {
let theme = Theme::TokyoNight;
let style = danger(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn warning_theme_active() {
let theme = Theme::TokyoNight;
let style = warning(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::BLACK);
}
#[test]
fn warning_theme_disabled() {
let theme = Theme::TokyoNight;
let style = warning(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn info_theme_active() {
let theme = Theme::TokyoNight;
let style = info(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::BLACK);
}
#[test]
fn info_theme_disabled() {
let theme = Theme::TokyoNight;
let style = info(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn light_theme_active() {
let theme = Theme::TokyoNight;
let style = light(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::BLACK);
}
#[test]
fn light_theme_disabled() {
let theme = Theme::TokyoNight;
let style = light(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn dark_theme_active() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::WHITE);
}
#[test]
fn dark_theme_disabled() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn white_theme_active() {
let theme = Theme::TokyoNight;
let style = white(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::BLACK);
}
#[test]
fn white_theme_disabled() {
let theme = Theme::TokyoNight;
let style = white(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
}
+348
View File
@@ -0,0 +1,348 @@
//! Displays a [`Card`](crate::widget::Card).
//!
//! *This API requires the following crate features to be activated: card*
use super::{Status, StyleFn, colors};
use iced_core::{Background, Color, Theme};
/// The appearance of a [`Card`](crate::widget::card::Card).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`Card`](crate::widget::card::Card).
pub background: Background,
/// The border radius of the [`Card`](crate::widget::card::Card).
pub border_radius: f32,
/// The border width of the [`Card`](crate::widget::card::Card).
pub border_width: f32,
/// The border color of the [`Card`](crate::widget::card::Card).
pub border_color: Color,
/// The background of the head of the [`Card`](crate::widget::card::Card).
pub head_background: Background,
/// The text color of the head of the [`Card`](crate::widget::card::Card).
pub head_text_color: Color,
/// The background of the body of the [`Card`](crate::widget::card::Card).
pub body_background: Background,
/// The text color of the body of the [`Card`](crate::widget::card::Card).
pub body_text_color: Color,
/// The background of the foot of the [`Card`](crate::widget::card::Card).
pub foot_background: Background,
/// The text color of the foot of the [`Card`](crate::widget::card::Card).
pub foot_text_color: Color,
/// The color of the close icon of the [`Card`](crate::widget::card::Card).
pub close_color: Color,
}
/// The appearance of a [`Card`](crate::widget::card::Card).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Default for Style {
fn default() -> Self {
Self {
background: Color::WHITE.into(),
border_radius: 10.0,
border_width: 1.0,
border_color: [0.87, 0.87, 0.87].into(),
head_background: Background::Color([0.87, 0.87, 0.87].into()),
head_text_color: Color::BLACK,
body_background: Color::TRANSPARENT.into(),
body_text_color: Color::BLACK,
foot_background: Color::TRANSPARENT.into(),
foot_text_color: Color::BLACK,
close_color: Color::BLACK,
}
}
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn primary(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::PRIMARY, colors::WHITE)
}
/// The secondary theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn secondary(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::SECONDARY, colors::WHITE)
}
/// The success theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn success(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::SUCCESS, colors::WHITE)
}
/// The danger theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn danger(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::DANGER, colors::WHITE)
}
/// The warning theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn warning(theme: &Theme, _status: Status) -> Style {
backing_only(theme, colors::WARNING)
}
/// The info theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn info(theme: &Theme, _status: Status) -> Style {
backing_only(theme, colors::INFO)
}
/// The light theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn light(theme: &Theme, _status: Status) -> Style {
backing_only(theme, colors::LIGHT)
}
/// The dark theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn dark(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::DARK, colors::WHITE)
}
/// The white theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn white(theme: &Theme, _status: Status) -> Style {
backing_only(theme, colors::WHITE)
}
fn backing_with_text(theme: &Theme, color: Color, text_color: Color) -> Style {
let palette = theme.extended_palette();
let foreground = theme.palette();
Style {
border_color: color,
head_background: color.into(),
head_text_color: text_color,
close_color: text_color,
background: palette.background.base.color.into(),
body_text_color: foreground.text,
foot_text_color: foreground.text,
..Style::default()
}
}
fn backing_only(theme: &Theme, color: Color) -> Style {
let palette = theme.extended_palette();
let foreground = theme.palette();
Style {
border_color: color,
head_background: color.into(),
background: palette.background.base.color.into(),
body_text_color: foreground.text,
foot_text_color: foreground.text,
..Style::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Color, Theme};
#[test]
fn style_default() {
let style = Style::default();
assert_eq!(style.background, Background::Color(Color::WHITE));
assert_eq!(style.border_radius, 10.0);
assert_eq!(style.border_width, 1.0);
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, Color::BLACK);
assert_eq!(style.body_background, Background::Color(Color::TRANSPARENT));
assert_eq!(style.body_text_color, Color::BLACK);
assert_eq!(style.foot_background, Background::Color(Color::TRANSPARENT));
assert_eq!(style.foot_text_color, Color::BLACK);
assert_eq!(style.close_color, Color::BLACK);
}
#[test]
fn backing_with_text_creates_style() {
let theme = Theme::TokyoNight;
let color = Color::from_rgb(1.0, 0.0, 0.0);
let text = Color::WHITE;
let style = backing_with_text(&theme, color, text);
assert_eq!(style.border_color, color);
assert_eq!(style.head_background, Background::Color(color));
assert_eq!(style.head_text_color, text);
assert_eq!(style.close_color, text);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.body_background, Background::Color(_)));
assert!(matches!(style.foot_background, Background::Color(_)));
}
#[test]
fn backing_only_creates_style() {
let theme = Theme::TokyoNight;
let color = Color::from_rgb(0.0, 1.0, 0.0);
let style = backing_only(&theme, color);
assert_eq!(style.border_color, color);
assert_eq!(style.head_background, Background::Color(color));
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.body_background, Background::Color(_)));
assert!(matches!(style.foot_background, Background::Color(_)));
}
#[test]
fn primary_theme() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
}
#[test]
fn secondary_theme() {
let theme = Theme::TokyoNight;
let style = secondary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
}
#[test]
fn success_theme() {
let theme = Theme::TokyoNight;
let style = success(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
}
#[test]
fn danger_theme() {
let theme = Theme::TokyoNight;
let style = danger(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
}
#[test]
fn warning_theme() {
let theme = Theme::TokyoNight;
let style = warning(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.border_color, colors::WARNING);
}
#[test]
fn info_theme() {
let theme = Theme::TokyoNight;
let style = info(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.border_color, colors::INFO);
}
#[test]
fn light_theme() {
let theme = Theme::TokyoNight;
let style = light(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.border_color, colors::LIGHT);
}
#[test]
fn dark_theme() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
assert_eq!(style.border_color, colors::DARK);
}
#[test]
fn white_theme() {
let theme = Theme::TokyoNight;
let style = white(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.border_color, colors::WHITE);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
}
#[test]
fn primary_theme_with_hovered_status() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
}
#[test]
fn primary_theme_with_disabled_status() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
}
}
+192
View File
@@ -0,0 +1,192 @@
//! Use a color picker as an input element for picking colors.
//!
//! *This API requires the following crate features to be activated: `color_picker`*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
/// The appearance of a [`ColorPicker`](crate::widget::ColorPicker).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`ColorPicker`](crate::widget::ColorPicker).
pub background: Background,
/// The border radius of the [`ColorPicker`](crate::widget::ColorPicker).
pub border_radius: f32,
/// The border with of the [`ColorPicker`](crate::widget::ColorPicker).
pub border_width: f32,
/// The border color of the [`ColorPicker`](crate::widget::ColorPicker).
pub border_color: Color,
/// The border radius of the bars of the [`ColorPicker`](crate::widget::ColorPicker).
pub bar_border_radius: f32,
/// The border width of the bars of the [`ColorPicker`](crate::widget::ColorPicker).
pub bar_border_width: f32,
/// The border color of the bars of the [`ColorPicker`](crate::widget::ColorPicker).
pub bar_border_color: Color,
}
/// The Catalog of a [`ColorPicker`](crate::widget::ColorPicker).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let foreground = theme.palette();
let base = Style {
background: palette.background.base.color.into(),
border_radius: 15.0,
border_width: 1.0,
border_color: foreground.text,
bar_border_radius: 5.0,
bar_border_width: 1.0,
bar_border_color: foreground.text,
};
match status {
Status::Focused => Style {
border_color: palette.background.strong.color,
bar_border_color: palette.background.strong.color,
..base
},
_ => base,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
assert_eq!(style.bar_border_radius, 5.0);
assert_eq!(style.bar_border_width, 1.0);
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
assert_eq!(style.bar_border_radius, 5.0);
assert_eq!(style.bar_border_width, 1.0);
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn focused_changes_border_colors() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let focused_style = primary(&theme, Status::Focused);
// Border colors should be different when focused
assert_ne!(base_style.border_color, focused_style.border_color);
assert_ne!(base_style.bar_border_color, focused_style.bar_border_color);
// Other properties should remain the same
assert_eq!(base_style.background, focused_style.background);
assert_eq!(base_style.border_radius, focused_style.border_radius);
assert_eq!(base_style.border_width, focused_style.border_width);
assert_eq!(
base_style.bar_border_radius,
focused_style.bar_border_radius
);
assert_eq!(base_style.bar_border_width, focused_style.bar_border_width);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
assert_eq!(style.bar_border_radius, 5.0);
assert_eq!(style.bar_border_width, 1.0);
}
#[test]
fn catalog_style_focused() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
}
#[test]
fn style_fields_are_valid() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Verify all fields have valid values
assert!(style.border_radius > 0.0);
assert!(style.border_width > 0.0);
assert!(style.bar_border_radius > 0.0);
assert!(style.bar_border_width > 0.0);
}
}
+662
View File
@@ -0,0 +1,662 @@
//! Predefined color palette based on the CSS color palette
//!
//!
//! Thanks to:
//! * [W3 Schools](https://www.w3schools.com/cssref/css_colors.asp)
//! * [Corecoding](https://corecoding.com/utilities/rgb-or-hex-to-float.php)
use iced_core::Color;
/// Primary <span style="color:dodgerblue">Color</span>.
pub const PRIMARY: Color = DODGER_BLUE;
/// Secondary <span style="color:dimgray">Color</span>.
pub const SECONDARY: Color = DIM_GRAY;
/// Success <span style="color:limeGreen">Color</span>.
pub const SUCCESS: Color = LIME_GREEN;
/// Danger <span style="color:red">Color</span>.
pub const DANGER: Color = RED;
/// Warning <span style="color:gold">Color</span>.
pub const WARNING: Color = GOLD;
/// Info <span style="color:skyBlue">Color</span>.
pub const INFO: Color = SKY_BLUE;
/// Light <span style="color:ghostWhite">Color</span>.
pub const LIGHT: Color = GHOST_WHITE;
/// Dark <span style="color:rgb(0.204, 0.227, 0.251)">Color</span>.
pub const DARK: Color = Color::from_rgb(0.204, 0.227, 0.251);
/// Alice Blue <span style="color:aliceBlue">Color</span>.
pub const ALICE_BLUE: Color = Color::from_rgb(0.941, 0.973, 1.0);
/// Antique White <span style="color:antiqueWhite">Color</span>.
pub const ANTIQUE_WHITE: Color = Color::from_rgb(0.98, 0.922, 0.843);
/// Aqua <span style="color:aqua">Color</span>.
pub const AQUA: Color = Color::from_rgb(0.0, 1.0, 1.0);
/// Aquamarine <span style="color:aquamarine">Color</span>.
pub const AQUAMARINE: Color = Color::from_rgb(0.498, 1.0, 0.831);
/// Azure <span style="color:azure">Color</span>.
pub const AZURE: Color = Color::from_rgb(0.941, 1.0, 1.0);
/// Beige <span style="color:beige">Color</span>.
pub const BEIGE: Color = Color::from_rgb(0.961, 0.961, 0.863);
/// Bisque <span style="color:bisque">Color</span>.
pub const BISQUE: Color = Color::from_rgb(1.0, 0.894, 0.769);
/// Black <span style="color:black">Color</span>.
pub const BLACK: Color = Color::BLACK;
/// Blanched Almond <span style="color:blanchedAlmond">Color</span>.
pub const BLANCHED_ALMOND: Color = Color::from_rgb(1.0, 0.922, 0.804);
/// Blue <span style="color:blue">Color</span>.
pub const BLUE: Color = Color::from_rgb(0.0, 0.0, 1.0);
/// Blue Violet <span style="color:blueViolet">Color</span>.
pub const BLUE_VIOLET: Color = Color::from_rgb(0.541, 0.169, 0.886);
/// Brown <span style="color:brown">Color</span>.
pub const BROWN: Color = Color::from_rgb(0.647, 0.165, 0.165);
/// Burly Wood <span style="color:burlyWood">Color</span>.
pub const BURLY_WOOD: Color = Color::from_rgb(0.871, 0.722, 0.529);
/// Cadet Blue <span style="color:cadetBlue">Color</span>.
pub const CADET_BLUE: Color = Color::from_rgb(0.373, 0.62, 0.627);
/// Chartreuse <span style="color:chartreuse">Color</span>.
pub const CHARTREUSE: Color = Color::from_rgb(0.498, 1.0, 0.0);
/// Chocolate <span style="color:chocolate">Color</span>.
pub const CHOCOLATE: Color = Color::from_rgb(0.824, 0.412, 0.118);
/// Coral <span style="color:coral">Color</span>.
pub const CORAL: Color = Color::from_rgb(1.0, 0.498, 0.314);
/// Cornflower Blue <span style="color:cornflowerBlue">Color</span>.
pub const CORNFLOWER_BLUE: Color = Color::from_rgb(0.392, 0.584, 0.929);
/// Cornsilk <span style="color:cornsilk">Color</span>.
pub const CORNSILK: Color = Color::from_rgb(1.0, 0.973, 0.863);
/// Crimson <span style="color:crimson">Color</span>.
pub const CRIMSON: Color = Color::from_rgb(0.863, 0.078, 0.235);
/// Cyan <span style="color:cyan">Color</span>.
pub const CYAN: Color = Color::from_rgb(0.0, 1.0, 1.0);
/// Dark Blue <span style="color:darkBlue">Color</span>.
pub const DARK_BLUE: Color = Color::from_rgb(0.0, 0.0, 0.545);
/// Dark Cyan <span style="color:darkCyan">Color</span>.
pub const DARK_CYAN: Color = Color::from_rgb(0.0, 0.545, 0.545);
/// Dark Golden Rod <span style="color:darkGoldenRod">Color</span>.
pub const DARK_GOLDEN_ROD: Color = Color::from_rgb(0.722, 0.525, 0.043);
/// Dark Gray <span style="color:darkGray">Color</span>.
pub const DARK_GRAY: Color = Color::from_rgb(0.663, 0.663, 0.663);
/// Dark Grey <span style="color:darkGrey">Color</span>.
pub const DARK_GREY: Color = DARK_GRAY;
/// Dark Green <span style="color:darkGreen">Color</span>.
pub const DARK_GREEN: Color = Color::from_rgb(0.0, 0.392, 0.0);
/// Dark Khaki <span style="color:darkKhaki">Color</span>.
pub const DARK_KHAKI: Color = Color::from_rgb(0.741, 0.718, 0.42);
/// Dark Magenta <span style="color:darkMagenta">Color</span>.
pub const DARK_MAGENTA: Color = Color::from_rgb(0.545, 0.0, 0.545);
/// Dark Olive Green <span style="color:darkOliveGreen">Color</span>.
pub const DARK_OLIVE_GREEN: Color = Color::from_rgb(0.333, 0.42, 0.184);
/// Dark Orange <span style="color:darkOrange">Color</span>.
pub const DARK_ORANGE: Color = Color::from_rgb(1.0, 0.549, 0.0);
/// Dark Orchid <span style="color:darkOrchid">Color</span>.
pub const DARK_ORCHID: Color = Color::from_rgb(0.6, 0.196, 0.8);
/// Dark Red <span style="color:darkRed">Color</span>.
pub const DARK_RED: Color = Color::from_rgb(0.545, 0.0, 0.0);
/// Dark Salmon <span style="color:darkSalmon">Color</span>.
pub const DARK_SALMON: Color = Color::from_rgb(0.914, 0.588, 0.478);
/// Dark Sea Green <span style="color:darkSeaGreen">Color</span>.
pub const DARK_SEA_GREEN: Color = Color::from_rgb(0.561, 0.737, 0.561);
/// Dark Slate Blue <span style="color:darkSlateBlue">Color</span>.
pub const DARK_SLATE_BLUE: Color = Color::from_rgb(0.282, 0.239, 0.545);
/// Dark Slate Gray <span style="color:darkSlateGray">Color</span>.
pub const DARK_SLATE_GRAY: Color = Color::from_rgb(0.184, 0.31, 0.31);
/// Dark Slate Grey <span style="color:darkSlateGrey">Color</span>.
pub const DARK_SLATE_GREY: Color = DARK_SLATE_GRAY;
/// Dark Turquoise <span style="color:darkTurquoise">Color</span>.
pub const DARK_TURQUOISE: Color = Color::from_rgb(0.0, 0.808, 0.82);
/// Dark Violet <span style="color:darkViolet">Color</span>.
pub const DARK_VIOLET: Color = Color::from_rgb(0.58, 0.0, 0.827);
/// Deep Pink <span style="color:deepPink">Color</span>.
pub const DEEP_PINK: Color = Color::from_rgb(1.0, 0.078, 0.576);
/// Deep Sky Blue <span style="color:deepSkyBlue">Color</span>.
pub const DEEP_SKY_BLUE: Color = Color::from_rgb(0.0, 0.749, 1.0);
/// Dim Gray <span style="color:dimgray">Color</span>.
pub const DIM_GRAY: Color = Color::from_rgb(0.412, 0.412, 0.412);
/// Dim Grey <span style="color:dimgrey">Color</span>.
pub const DIM_GREY: Color = DIM_GRAY;
/// Dodger Blue <span style="color:dodgerBlue">Color</span>.
pub const DODGER_BLUE: Color = Color::from_rgb(0.118, 0.565, 1.0);
/// Fire Brick <span style="color:fireBrick">Color</span>.
pub const FIRE_BRICK: Color = Color::from_rgb(0.698, 0.133, 0.133);
/// Floral White <span style="color:floralWhite">Color</span>.
pub const FLORAL_WHITE: Color = Color::from_rgb(1.0, 0.98, 0.941);
/// Forest Green <span style="color:forestGreen">Color</span>.
pub const FOREST_GREEN: Color = Color::from_rgb(0.133, 0.545, 0.133);
/// Fuchsia <span style="color:fuchsia">Color</span>.
pub const FUCHSIA: Color = Color::from_rgb(1.0, 0.0, 1.0);
/// Gainsboro <span style="color:gainsboro">Color</span>.
pub const GAINSBORO: Color = Color::from_rgb(0.863, 0.863, 0.863);
/// Ghost White <span style="color:ghostWhite">Color</span>.
pub const GHOST_WHITE: Color = Color::from_rgb(0.973, 0.973, 1.0);
/// Gold <span style="color:gold">Color</span>.
pub const GOLD: Color = Color::from_rgb(1.0, 0.843, 0.0);
/// Golden Rod <span style="color:goldenRod">Color</span>.
pub const GOLDEN_ROD: Color = Color::from_rgb(0.855, 0.647, 0.125);
/// Gray <span style="color:gray">Color</span>.
pub const GRAY: Color = Color::from_rgb(0.502, 0.502, 0.502);
/// Grey <span style="color:grey">Color</span>.
pub const GREY: Color = GRAY;
/// Green <span style="color:green">Color</span>.
pub const GREEN: Color = Color::from_rgb(0.0, 0.502, 0.0);
/// Green Yellow <span style="color:greenYellow">Color</span>.
pub const GREEN_YELLOW: Color = Color::from_rgb(0.678, 1.0, 0.184);
/// Honey Dew <span style="color:honeyDew">Color</span>.
pub const HONEY_DEW: Color = Color::from_rgb(0.941, 1.0, 0.941);
/// Hot Pink <span style="color:hotPink">Color</span>.
pub const HOT_PINK: Color = Color::from_rgb(1.0, 0.412, 0.706);
/// Indian Red <span style="color:indianRed">Color</span>.
pub const INDIAN_RED: Color = Color::from_rgb(0.804, 0.361, 0.361);
/// Indigo <span style="color:indigo">Color</span>.
pub const INDIGO: Color = Color::from_rgb(0.294, 0.0, 0.51);
/// Ivory <span style="color:ivory">Color</span>.
pub const IVORY: Color = Color::from_rgb(1.0, 1.0, 0.941);
/// Khaki <span style="color:khaki">Color</span>.
pub const KHAKI: Color = Color::from_rgb(0.941, 0.902, 0.549);
/// Lavender <span style="color:lavender">Color</span>.
pub const LAVENDER: Color = Color::from_rgb(0.902, 0.902, 0.98);
/// Lavender Blush <span style="color:lavenderBlush">Color</span>.
pub const LAVENDER_BLUSH: Color = Color::from_rgb(1.0, 0.941, 0.961);
/// Lawn Green <span style="color:lawnGreen">Color</span>.
pub const LAWN_GREEN: Color = Color::from_rgb(0.486, 0.988, 0.0);
/// Lemon Chiffon <span style="color:lemonChiffon">Color</span>.
pub const LEMON_CHIFFON: Color = Color::from_rgb(1.0, 0.98, 0.804);
/// Light Blue <span style="color:lightBlue">Color</span>.
pub const LIGHT_BLUE: Color = Color::from_rgb(0.678, 0.847, 0.902);
/// Light Coral <span style="color:lightCoral">Color</span>.
pub const LIGHT_CORAL: Color = Color::from_rgb(0.941, 0.502, 0.502);
/// Light Cyan <span style="color:lightCyan">Color</span>.
pub const LIGHT_CYAN: Color = Color::from_rgb(0.878, 1.0, 1.0);
/// Light Golden Rod Yellow <span style="color:lightGoldenRodYellow">Color</span>.
pub const LIGHT_GOLDEN_ROD_YELLOW: Color = Color::from_rgb(0.98, 0.98, 0.824);
/// Light Gray <span style="color:lightGray">Color</span>.
pub const LIGHT_GRAY: Color = Color::from_rgb(0.827, 0.827, 0.827);
/// Light Grey <span style="color:lightGrey">Color</span>.
pub const LIGHT_GREY: Color = LIGHT_GRAY;
/// Light Green <span style="color:lightGreen">Color</span>.
pub const LIGHT_GREEN: Color = Color::from_rgb(0.565, 0.933, 0.565);
/// Light Pink <span style="color:lightPink">Color</span>.
pub const LIGHT_PINK: Color = Color::from_rgb(1.0, 0.714, 0.757);
/// Light Salmon <span style="color:lightSalmon">Color</span>.
pub const LIGHT_SALMON: Color = Color::from_rgb(1.0, 0.627, 0.478);
/// Light Sea Green <span style="color:lightSeaGreen">Color</span>.
pub const LIGHT_SEA_GREEN: Color = Color::from_rgb(0.125, 0.698, 0.667);
/// Light Sky Blue <span style="color:lightSkyBlue">Color</span>.
pub const LIGHT_SKY_BLUE: Color = Color::from_rgb(0.529, 0.808, 0.98);
/// Light Slate Gray <span style="color:lightSlateGray">Color</span>.
pub const LIGHT_SLATE_GRAY: Color = Color::from_rgb(0.467, 0.533, 0.6);
/// Light Slate Grey <span style="color:lightSlateGrey">Color</span>.
pub const LIGHT_SLATE_GREY: Color = LIGHT_SLATE_GRAY;
/// Light Steel Blue <span style="color:lightSteelBlue">Color</span>.
pub const LIGHT_STEEL_BLUE: Color = Color::from_rgb(0.69, 0.769, 0.871);
/// Light Yellow <span style="color:lightYellow">Color</span>.
pub const LIGHT_YELLOW: Color = Color::from_rgb(1.0, 1.0, 0.878);
/// Lime <span style="color:lime">Color</span>.
pub const LIME: Color = Color::from_rgb(0.0, 1.0, 0.0);
/// Lime Green <span style="color:limeGreen">Color</span>.
pub const LIME_GREEN: Color = Color::from_rgb(0.196, 0.804, 0.196);
/// Linen <span style="color:linen">Color</span>.
pub const LINEN: Color = Color::from_rgb(0.98, 0.941, 0.902);
/// Magenta <span style="color:magenta">Color</span>.
pub const MAGENTA: Color = Color::from_rgb(1.0, 0.0, 1.0);
/// Maroon <span style="color:maroon">Color</span>.
pub const MAROON: Color = Color::from_rgb(0.502, 0.0, 0.0);
/// Medium Aqua Marine <span style="color:mediumAquaMarine">Color</span>.
pub const MEDIUM_AQUA_MARINE: Color = Color::from_rgb(0.4, 0.804, 0.667);
/// Medium Blue <span style="color:mediumBlue">Color</span>.
pub const MEDIUM_BLUE: Color = Color::from_rgb(0.0, 0.0, 0.804);
/// Medium Orchid <span style="color:mediumOrchid">Color</span>.
pub const MEDIUM_ORCHID: Color = Color::from_rgb(0.729, 0.333, 0.827);
/// Medium Purple <span style="color:mediumPurple">Color</span>.
pub const MEDIUM_PURPLE: Color = Color::from_rgb(0.576, 0.439, 0.859);
/// Medium Sea Green <span style="color:mediumSeaGreen">Color</span>.
pub const MEDIUM_SEA_GREEN: Color = Color::from_rgb(0.235, 0.702, 0.443);
/// Medium Slate Blue <span style="color:mediumSlateBlue">Color</span>.
pub const MEDIUM_SLATE_BLUE: Color = Color::from_rgb(0.482, 0.408, 0.933);
/// Medium Spring Green <span style="color:mediumSpringGreen">Color</span>.
pub const MEDIUM_SPRING_GREEN: Color = Color::from_rgb(0.0, 0.98, 0.604);
/// Medium Turquoise <span style="color:mediumTurquoise">Color</span>.
pub const MEDIUM_TURQUOISE: Color = Color::from_rgb(0.282, 0.82, 0.8);
/// Medium Violet Red <span style="color:mediumVioletRed">Color</span>.
pub const MEDIUM_VIOLET_RED: Color = Color::from_rgb(0.78, 0.082, 0.522);
/// Midnight Blue <span style="color:midnightBlue">Color</span>.
pub const MIDNIGHT_BLUE: Color = Color::from_rgb(0.098, 0.098, 0.439);
/// Mint Cream <span style="color:mintCream">Color</span>.
pub const MINT_CREAM: Color = Color::from_rgb(0.961, 1.0, 0.98);
/// Misty Rose <span style="color:mistyRose">Color</span>.
pub const MISTY_ROSE: Color = Color::from_rgb(1.0, 0.894, 0.882);
/// Moccasin <span style="color:moccasin">Color</span>.
pub const MOCCASIN: Color = Color::from_rgb(1.0, 0.894, 0.71);
/// Navajo White <span style="color:navajo_white">Color</span>.
pub const NAVAJO_WHITE: Color = Color::from_rgb(1.0, 0.871, 0.678);
/// Navy <span style="color:navy">Color</span>.
pub const NAVY: Color = Color::from_rgb(0.0, 0.0, 0.502);
/// Old Lace <span style="color:oldLace">Color</span>.
pub const OLD_LACE: Color = Color::from_rgb(0.992, 0.961, 0.902);
/// Olive <span style="color:olive">Color</span>.
pub const OLIVE: Color = Color::from_rgb(0.502, 0.502, 0.0);
/// Olive Drab <span style="color:oliveDrab">Color</span>.
pub const OLIVE_DRAB: Color = Color::from_rgb(0.42, 0.557, 0.137);
/// Orange <span style="color:orange">Color</span>.
pub const ORANGE: Color = Color::from_rgb(1.0, 0.647, 0.0);
/// Orange Red <span style="color:orangeRed">Color</span>.
pub const ORANGE_RED: Color = Color::from_rgb(1.0, 0.271, 0.0);
/// Orchid <span style="color:orchid">Color</span>.
pub const ORCHID: Color = Color::from_rgb(0.855, 0.439, 0.839);
/// Pale Golden Rod <span style="color:paleGoldenRod">Color</span>.
pub const PALE_GOLDEN_ROD: Color = Color::from_rgb(0.933, 0.91, 0.667);
/// Pale Green <span style="color:paleGreen">Color</span>.
pub const PALE_GREEN: Color = Color::from_rgb(0.596, 0.984, 0.596);
/// Pale Turquoise <span style="color:paleTurquoise">Color</span>.
pub const PALE_TURQUOISE: Color = Color::from_rgb(0.686, 0.933, 0.933);
/// Pale Violet Red <span style="color:paleVioletRed">Color</span>.
pub const PALE_VIOLET_RED: Color = Color::from_rgb(0.859, 0.439, 0.576);
/// Papaya Whip <span style="color:papayaWhip">Color</span>.
pub const PAPAYA_WHIP: Color = Color::from_rgb(1.0, 0.937, 0.835);
/// Peach Puff <span style="color:peachPuff">Color</span>.
pub const PEACH_PUFF: Color = Color::from_rgb(1.0, 0.855, 0.725);
/// Peru <span style="color:peru">Color</span>.
pub const PERU: Color = Color::from_rgb(0.804, 0.522, 0.247);
/// Pink <span style="color:pink">Color</span>.
pub const PINK: Color = Color::from_rgb(1.0, 0.753, 0.796);
/// Plum <span style="color:plum">Color</span>.
pub const PLUM: Color = Color::from_rgb(0.867, 0.627, 0.867);
/// Powder Blue <span style="color:powderBlue">Color</span>.
pub const POWDER_BLUE: Color = Color::from_rgb(0.69, 0.878, 0.902);
/// Purple <span style="color:purple">Color</span>.
pub const PURPLE: Color = Color::from_rgb(0.502, 0.0, 0.502);
/// Rebecca Purple <span style="color:rebeccaPurple">Color</span>.
pub const REBECCA_PURPLE: Color = Color::from_rgb(0.4, 0.2, 0.6);
/// Red <span style="color:red">Color</span>.
pub const RED: Color = Color::from_rgb(1.0, 0.0, 0.0);
/// Rosy Brown <span style="color:rosyBrown">Color</span>.
pub const ROSY_BROWN: Color = Color::from_rgb(0.737, 0.561, 0.561);
/// Royal Blue <span style="color:royalBlue">Color</span>.
pub const ROYAL_BLUE: Color = Color::from_rgb(0.255, 0.412, 0.882);
/// Saddle Brown <span style="color:saddleBrown">Color</span>.
pub const SADDLE_BROWN: Color = Color::from_rgb(0.545, 0.271, 0.075);
/// Salmon <span style="color:salmon">Color</span>.
pub const SALMON: Color = Color::from_rgb(0.98, 0.502, 0.447);
/// Sandy Brown <span style="color:sandyBrown">Color</span>.
pub const SANDY_BROWN: Color = Color::from_rgb(0.957, 0.643, 0.376);
/// Sea Green <span style="color:seaGreen">Color</span>.
pub const SEA_GREEN: Color = Color::from_rgb(0.18, 0.545, 0.341);
/// Sea Shell <span style="color:seaShell">Color</span>.
pub const SEA_SHELL: Color = Color::from_rgb(1.0, 0.961, 0.933);
/// Sienna <span style="color:sienna">Color</span>.
pub const SIENNA: Color = Color::from_rgb(0.627, 0.322, 0.176);
/// Silver <span style="color:silver">Color</span>.
pub const SILVER: Color = Color::from_rgb(0.753, 0.753, 0.753);
/// Sky Blue <span style="color:skyBlue">Color</span>.
pub const SKY_BLUE: Color = Color::from_rgb(0.529, 0.808, 0.922);
/// Slate Blue <span style="color:slateBlue">Color</span>.
pub const SLATE_BLUE: Color = Color::from_rgb(0.416, 0.353, 0.804);
/// Slate Gray <span style="color:slateGray">Color</span>.
pub const SLATE_GRAY: Color = Color::from_rgb(0.439, 0.502, 0.565);
/// Slate Grey <span style="color:slateGrey">Color</span>.
pub const SLATE_GREY: Color = SLATE_GRAY;
/// Snow <span style="color:snow">Color</span>.
pub const SNOW: Color = Color::from_rgb(1.0, 0.98, 0.98);
/// Spring Green <span style="color:springGreen">Color</span>.
pub const SPRING_GREEN: Color = Color::from_rgb(0.0, 1.0, 0.498);
/// Steel Blue <span style="color:steelBlue">Color</span>.
pub const STEEL_BLUE: Color = Color::from_rgb(0.275, 0.51, 0.706);
/// Tan <span style="color:tan">Color</span>.
pub const TAN: Color = Color::from_rgb(0.824, 0.706, 0.549);
/// Teal <span style="color:teal">Color</span>.
pub const TEAL: Color = Color::from_rgb(0.0, 0.502, 0.502);
/// Thistle <span style="color:thistle">Color</span>.
pub const THISTLE: Color = Color::from_rgb(0.847, 0.749, 0.847);
/// Tomato <span style="color:tomato">Color</span>.
pub const TOMATO: Color = Color::from_rgb(1.0, 0.388, 0.278);
/// Turquoise <span style="color:turquoise">Color</span>.
pub const TURQUOISE: Color = Color::from_rgb(0.251, 0.878, 0.816);
/// Violet <span style="color:violet">Color</span>.
pub const VIOLET: Color = Color::from_rgb(0.933, 0.51, 0.933);
/// Wheat <span style="color:wheat">Color</span>.
pub const WHEAT: Color = Color::from_rgb(0.961, 0.871, 0.702);
/// White <span style="color:white">Color</span>.
pub const WHITE: Color = Color::WHITE;
/// White Smoke <span style="color:whiteSmoke">Color</span>.
pub const WHITE_SMOKE: Color = Color::WHITE;
/// Yellow <span style="color:yellow">Color</span>.
pub const YELLOW: Color = Color::from_rgb(1.0, 1.0, 0.0);
/// Yellow Green <span style="color:yellowGreen">Color</span>.
pub const YELLOW_GREEN: Color = Color::from_rgb(0.604, 0.804, 0.196);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn semantic_colors_are_defined() {
// Verify semantic colors point to the correct values
assert_eq!(PRIMARY, DODGER_BLUE);
assert_eq!(SECONDARY, DIM_GRAY);
assert_eq!(SUCCESS, LIME_GREEN);
assert_eq!(DANGER, RED);
assert_eq!(WARNING, GOLD);
assert_eq!(INFO, SKY_BLUE);
assert_eq!(LIGHT, GHOST_WHITE);
}
#[test]
fn dark_color_is_custom() {
// DARK is a custom color, not an alias
assert_eq!(DARK, Color::from_rgb(0.204, 0.227, 0.251));
}
#[test]
fn black_and_white_constants() {
assert_eq!(BLACK, Color::BLACK);
assert_eq!(WHITE, Color::WHITE);
assert_eq!(WHITE_SMOKE, Color::WHITE);
}
#[test]
fn gray_grey_aliases_match() {
// American/British spelling aliases should be equal
assert_eq!(GRAY, GREY);
assert_eq!(DARK_GRAY, DARK_GREY);
assert_eq!(DIM_GRAY, DIM_GREY);
assert_eq!(LIGHT_GRAY, LIGHT_GREY);
assert_eq!(SLATE_GRAY, SLATE_GREY);
assert_eq!(DARK_SLATE_GRAY, DARK_SLATE_GREY);
assert_eq!(LIGHT_SLATE_GRAY, LIGHT_SLATE_GREY);
}
#[test]
fn primary_colors_are_valid() {
// Test basic RGB colors
assert_eq!(RED, Color::from_rgb(1.0, 0.0, 0.0));
assert_eq!(GREEN, Color::from_rgb(0.0, 0.502, 0.0));
assert_eq!(BLUE, Color::from_rgb(0.0, 0.0, 1.0));
}
#[test]
fn cyan_magenta_yellow_are_valid() {
assert_eq!(CYAN, Color::from_rgb(0.0, 1.0, 1.0));
assert_eq!(MAGENTA, Color::from_rgb(1.0, 0.0, 1.0));
assert_eq!(YELLOW, Color::from_rgb(1.0, 1.0, 0.0));
}
#[test]
fn aqua_equals_cyan() {
assert_eq!(AQUA, CYAN);
}
#[test]
fn fuchsia_equals_magenta() {
assert_eq!(FUCHSIA, MAGENTA);
}
#[test]
fn color_values_are_in_valid_range() {
// Sample various colors to ensure RGB values are between 0.0 and 1.0
let sample_colors = [
ALICE_BLUE,
ANTIQUE_WHITE,
CORAL,
CRIMSON,
DARK_GOLDEN_ROD,
DEEP_PINK,
DODGER_BLUE,
FOREST_GREEN,
GOLD,
INDIAN_RED,
LAVENDER,
LIME_GREEN,
MEDIUM_PURPLE,
NAVY,
ORANGE,
PALE_GREEN,
PURPLE,
ROSY_BROWN,
SALMON,
SLATE_BLUE,
TOMATO,
TURQUOISE,
VIOLET,
];
for color in &sample_colors {
assert!(
color.r >= 0.0 && color.r <= 1.0,
"Red component out of range"
);
assert!(
color.g >= 0.0 && color.g <= 1.0,
"Green component out of range"
);
assert!(
color.b >= 0.0 && color.b <= 1.0,
"Blue component out of range"
);
}
}
#[test]
fn specific_colors_have_correct_values() {
// Test a few specific colors to ensure accuracy
assert_eq!(GOLD, Color::from_rgb(1.0, 0.843, 0.0));
assert_eq!(LIME_GREEN, Color::from_rgb(0.196, 0.804, 0.196));
assert_eq!(SKY_BLUE, Color::from_rgb(0.529, 0.808, 0.922));
assert_eq!(DODGER_BLUE, Color::from_rgb(0.118, 0.565, 1.0));
assert_eq!(GHOST_WHITE, Color::from_rgb(0.973, 0.973, 1.0));
assert_eq!(DIM_GRAY, Color::from_rgb(0.412, 0.412, 0.412));
}
#[test]
fn dark_colors_are_darker() {
// Verify dark variants have lower RGB values than their base colors
const {
assert!(DARK_BLUE.r <= BLUE.r);
assert!(DARK_BLUE.g <= BLUE.g);
assert!(DARK_BLUE.b <= BLUE.b);
assert!(DARK_GREEN.r <= GREEN.r);
assert!(DARK_GREEN.g <= GREEN.g);
assert!(DARK_GREEN.b <= GREEN.b);
assert!(DARK_RED.r <= RED.r);
assert!(DARK_RED.g <= RED.g);
assert!(DARK_RED.b <= RED.b);
}
}
#[test]
fn light_colors_are_lighter() {
// Verify some light variants are generally lighter (higher average RGB brightness)
// Note: Not all CSS "light" colors are consistently lighter than their base
let light_blue_avg = (LIGHT_BLUE.r + LIGHT_BLUE.g + LIGHT_BLUE.b) / 3.0;
let blue_avg = (BLUE.r + BLUE.g + BLUE.b) / 3.0;
assert!(light_blue_avg > blue_avg);
let light_green_avg = (LIGHT_GREEN.r + LIGHT_GREEN.g + LIGHT_GREEN.b) / 3.0;
let green_avg = (GREEN.r + GREEN.g + GREEN.b) / 3.0;
assert!(light_green_avg > green_avg);
const {
// Light Gray should be lighter than Gray in all components (grayscale)
assert!(LIGHT_GRAY.r >= GRAY.r);
assert!(LIGHT_GRAY.g >= GRAY.g);
assert!(LIGHT_GRAY.b >= GRAY.b);
}
}
#[test]
fn brown_shades_exist() {
// Test various brown colors
assert_eq!(BROWN, Color::from_rgb(0.647, 0.165, 0.165));
assert_eq!(SADDLE_BROWN, Color::from_rgb(0.545, 0.271, 0.075));
assert_eq!(SANDY_BROWN, Color::from_rgb(0.957, 0.643, 0.376));
assert_eq!(ROSY_BROWN, Color::from_rgb(0.737, 0.561, 0.561));
}
#[test]
fn purple_shades_exist() {
// Test various purple colors
assert_eq!(PURPLE, Color::from_rgb(0.502, 0.0, 0.502));
assert_eq!(REBECCA_PURPLE, Color::from_rgb(0.4, 0.2, 0.6));
assert_eq!(MEDIUM_PURPLE, Color::from_rgb(0.576, 0.439, 0.859));
}
#[test]
fn orange_shades_exist() {
// Test various orange colors
assert_eq!(ORANGE, Color::from_rgb(1.0, 0.647, 0.0));
assert_eq!(DARK_ORANGE, Color::from_rgb(1.0, 0.549, 0.0));
assert_eq!(ORANGE_RED, Color::from_rgb(1.0, 0.271, 0.0));
}
}
+176
View File
@@ -0,0 +1,176 @@
//! Use a badge for color highlighting important information.
//!
//! *This API requires the following crate features to be activated: badge*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
/// The style of a [`ContextMenu`](crate::widget::ContextMenu).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`ContextMenu`](crate::widget::ContextMenu).
///
/// This is used to color the backdrop of the modal.
pub background: Background,
}
impl Default for Style {
fn default() -> Self {
Self {
background: Background::Color([0.87, 0.87, 0.87, 0.30].into()),
}
}
}
/// The Catalog of a [`ContextMenu`](crate::widget::ContextMenu).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`ContextMenu`](crate::widget::ContextMenu).
#[must_use]
pub fn primary(theme: &Theme, _status: Status) -> Style {
let palette = theme.extended_palette();
Style {
background: Background::Color(Color {
a: 0f32,
..palette.background.base.color
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn style_default() {
let style = Style::default();
assert!(matches!(style.background, Background::Color(_)));
// Verify the default has a semi-transparent background
if let Background::Color(color) = style.background {
assert_eq!(color.a, 0.30);
}
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn primary_theme_has_transparent_background() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// The primary theme should create a transparent background
#[allow(clippy::panic)]
if let Background::Color(color) = style.background {
assert_eq!(
color.a, 0.0,
"Primary theme should have fully transparent background"
);
} else {
panic!("Expected Background::Color");
}
}
#[test]
fn status_does_not_affect_style() {
let theme = Theme::TokyoNight;
let active_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
let disabled_style = primary(&theme, Status::Disabled);
let focused_style = primary(&theme, Status::Focused);
// All statuses should produce the same style
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", hovered_style.background)
);
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", disabled_style.background)
);
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", focused_style.background)
);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = theme.style(&class, Status::Active);
let hovered_style = theme.style(&class, Status::Hovered);
let disabled_style = theme.style(&class, Status::Disabled);
assert!(matches!(active_style.background, Background::Color(_)));
assert!(matches!(hovered_style.background, Background::Color(_)));
assert!(matches!(disabled_style.background, Background::Color(_)));
}
}
+271
View File
@@ -0,0 +1,271 @@
//! 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::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
/// The appearance of a [`DatePicker`](crate::widget::DatePicker).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`DatePicker`](crate::widget::DatePicker).
pub background: Background,
/// The border radius of the [`DatePicker`](crate::widget::DatePicker).
pub border_radius: f32,
/// The border with of the [`DatePicker`](crate::widget::DatePicker).
pub border_width: f32,
/// The border color of the [`DatePicker`](crate::widget::DatePicker).
pub border_color: Color,
/// The text color of the [`DatePicker`](crate::widget::DatePicker).
pub text_color: Color,
/// The attenuated color of the days which are not in the selected month
/// of the [`DatePicker`](crate::widget::DatePicker).
pub text_attenuated_color: Color,
/// The background of the days in the calender of the
/// [`DatePicker`](crate::widget::DatePicker).
pub day_background: Background,
}
/// The Catalog of a [`DatePicker`](crate::widget::DatePicker).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let foreground = theme.palette();
let base = Style {
background: palette.background.base.color.into(),
border_radius: 15.0,
border_width: 1.0,
border_color: foreground.text,
text_color: foreground.text,
text_attenuated_color: Color {
a: foreground.text.a * 0.5,
..foreground.text
},
day_background: palette.background.base.color.into(),
};
match status {
Status::Selected => Style {
day_background: palette.primary.strong.color.into(),
text_color: palette.primary.strong.text,
..base
},
Status::Hovered => Style {
day_background: palette.primary.weak.color.into(),
text_color: palette.primary.weak.text,
..base
},
Status::Focused => Style {
border_color: Color::from_rgb(0.5, 0.5, 0.5),
..base
},
_ => base,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
assert!(matches!(style.day_background, Background::Color(_)));
}
#[test]
fn primary_theme_selected() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Selected);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.day_background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.day_background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_color, Color::from_rgb(0.5, 0.5, 0.5));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn selected_changes_day_background_and_text() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let selected_style = primary(&theme, Status::Selected);
// Day background and text color should be different when selected
assert_ne!(
format!("{:?}", base_style.day_background),
format!("{:?}", selected_style.day_background)
);
assert_ne!(base_style.text_color, selected_style.text_color);
// Other properties should remain the same
assert_eq!(base_style.background, selected_style.background);
assert_eq!(base_style.border_radius, selected_style.border_radius);
assert_eq!(base_style.border_width, selected_style.border_width);
assert_eq!(base_style.border_color, selected_style.border_color);
}
#[test]
fn hovered_changes_day_background_and_text() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
// Day background and text color should be different when hovered
assert_ne!(
format!("{:?}", base_style.day_background),
format!("{:?}", hovered_style.day_background)
);
assert_ne!(base_style.text_color, hovered_style.text_color);
// Other properties should remain the same
assert_eq!(base_style.background, hovered_style.background);
assert_eq!(base_style.border_radius, hovered_style.border_radius);
assert_eq!(base_style.border_width, hovered_style.border_width);
assert_eq!(base_style.border_color, hovered_style.border_color);
}
#[test]
fn focused_changes_border_color() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let focused_style = primary(&theme, Status::Focused);
// Border color should be different when focused
assert_ne!(base_style.border_color, focused_style.border_color);
assert_eq!(focused_style.border_color, Color::from_rgb(0.5, 0.5, 0.5));
// Other properties should remain the same
assert_eq!(base_style.background, focused_style.background);
assert_eq!(base_style.border_radius, focused_style.border_radius);
assert_eq!(base_style.border_width, focused_style.border_width);
assert_eq!(base_style.text_color, focused_style.text_color);
assert_eq!(
format!("{:?}", base_style.day_background),
format!("{:?}", focused_style.day_background)
);
}
#[test]
fn text_attenuated_color_has_reduced_alpha() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Attenuated color should have half the alpha
assert!(
style.text_attenuated_color.a <= style.text_color.a,
"Attenuated color should have reduced alpha"
);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = theme.style(&class, Status::Active);
let selected_style = theme.style(&class, Status::Selected);
let hovered_style = theme.style(&class, Status::Hovered);
let focused_style = theme.style(&class, Status::Focused);
assert!(matches!(active_style.background, Background::Color(_)));
assert!(matches!(selected_style.background, Background::Color(_)));
assert!(matches!(hovered_style.background, Background::Color(_)));
assert!(matches!(focused_style.background, Background::Color(_)));
}
#[test]
fn style_fields_are_valid() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Verify all fields have valid values
assert!(style.border_radius > 0.0);
assert!(style.border_width > 0.0);
assert!(style.text_attenuated_color.a >= 0.0);
assert!(style.text_attenuated_color.a <= 1.0);
}
}
+301
View File
@@ -0,0 +1,301 @@
//! Change the appearance of menu bars and their menus.
use super::{Status, StyleFn};
use iced_core::{Background, Border, Color, Shadow, Theme, Vector};
/// The appearance of a menu bar and its menus.
#[derive(Debug, Clone, Copy)]
pub struct Style {
/// The background of the menu bar.
pub bar_background: Background,
/// The border of the menu bar.
pub bar_border: Border,
/// The shadow of the menu bar.
pub bar_shadow: Shadow,
/// The background of the menus.
pub menu_background: Background,
/// The border of the menus.
pub menu_border: Border,
/// The shadow of the menus
pub menu_shadow: Shadow,
/// The backgraound of the path
pub path: Background,
/// The border of the path
pub path_border: Border,
}
impl std::default::Default for Style {
fn default() -> Self {
Self {
bar_background: Color::from([0.85; 3]).into(),
bar_border: Border {
radius: 8.0.into(),
..Default::default()
},
bar_shadow: Shadow::default(),
menu_background: Color::from([0.85; 3]).into(),
menu_border: Border {
radius: 8.0.into(),
..Default::default()
},
menu_shadow: Shadow {
color: Color::from([0.0, 0.0, 0.0, 0.5]),
offset: Vector::ZERO,
blur_radius: 10.0,
},
path: Color::from([0.3; 3]).into(),
path_border: Border {
radius: 6.0.into(),
..Default::default()
},
}
}
}
/// The Catalog of a [`Menu`](crate::widget::menu::Menu).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Menu`](crate::widget::menu::Menu).
#[must_use]
pub fn primary(theme: &Theme, _status: Status) -> Style {
let palette = theme.extended_palette();
Style {
bar_background: palette.background.base.color.into(),
menu_background: palette.background.base.color.into(),
path: palette.primary.weak.color.into(),
..Default::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn style_default() {
let style = Style::default();
// Verify bar properties
assert!(matches!(style.bar_background, Background::Color(_)));
assert_eq!(style.bar_border.radius.top_left, 8.0);
assert_eq!(style.bar_border.radius.top_right, 8.0);
assert_eq!(style.bar_border.radius.bottom_left, 8.0);
assert_eq!(style.bar_border.radius.bottom_right, 8.0);
// Verify menu properties
assert!(matches!(style.menu_background, Background::Color(_)));
assert_eq!(style.menu_border.radius.top_left, 8.0);
assert_eq!(style.menu_shadow.blur_radius, 10.0);
// Verify path properties
assert!(matches!(style.path, Background::Color(_)));
assert_eq!(style.path_border.radius.top_left, 6.0);
}
#[test]
fn default_shadow_has_blur() {
let style = Style::default();
// Menu shadow should have blur
assert_eq!(style.menu_shadow.blur_radius, 10.0);
assert_eq!(style.menu_shadow.offset, Vector::ZERO);
// Verify shadow color has transparency
if let Background::Color(color) = style.bar_background {
// Just verify it exists
let _ = color;
}
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn primary_uses_default_borders_and_shadows() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
let default_style = Style::default();
// Primary theme should use default borders
assert_eq!(style.bar_border.radius, default_style.bar_border.radius);
assert_eq!(style.menu_border.radius, default_style.menu_border.radius);
assert_eq!(style.path_border.radius, default_style.path_border.radius);
// Primary theme should use default shadows
assert_eq!(
style.bar_shadow.blur_radius,
default_style.bar_shadow.blur_radius
);
assert_eq!(
style.menu_shadow.blur_radius,
default_style.menu_shadow.blur_radius
);
}
#[test]
fn status_does_not_affect_style() {
let theme = Theme::TokyoNight;
let active_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
let disabled_style = primary(&theme, Status::Disabled);
// All statuses should produce the same style
assert_eq!(
format!("{:?}", active_style.bar_background),
format!("{:?}", hovered_style.bar_background)
);
assert_eq!(
format!("{:?}", active_style.bar_background),
format!("{:?}", disabled_style.bar_background)
);
assert_eq!(
format!("{:?}", active_style.menu_background),
format!("{:?}", hovered_style.menu_background)
);
assert_eq!(
format!("{:?}", active_style.path),
format!("{:?}", hovered_style.path)
);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = theme.style(&class, Status::Active);
let hovered_style = theme.style(&class, Status::Hovered);
let disabled_style = theme.style(&class, Status::Disabled);
assert!(matches!(active_style.bar_background, Background::Color(_)));
assert!(matches!(hovered_style.bar_background, Background::Color(_)));
assert!(matches!(
disabled_style.bar_background,
Background::Color(_)
));
}
#[test]
fn default_border_radii_are_consistent() {
let style = Style::default();
// Bar border should have uniform radius
assert_eq!(
style.bar_border.radius.top_left,
style.bar_border.radius.top_right
);
assert_eq!(
style.bar_border.radius.bottom_left,
style.bar_border.radius.bottom_right
);
// Menu border should have uniform radius
assert_eq!(
style.menu_border.radius.top_left,
style.menu_border.radius.top_right
);
assert_eq!(
style.menu_border.radius.bottom_left,
style.menu_border.radius.bottom_right
);
// Path border should have uniform radius
assert_eq!(
style.path_border.radius.top_left,
style.path_border.radius.top_right
);
assert_eq!(
style.path_border.radius.bottom_left,
style.path_border.radius.bottom_right
);
}
#[test]
fn all_backgrounds_are_colors() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// All backgrounds should be Color variants
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
}
+275
View File
@@ -0,0 +1,275 @@
//! Display fields that can only be filled with numeric type.
//!
//! *This API requires the following crate features to be activated: `number_input`*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
use iced_widget::{container, text, text_input};
/// The appearance of a [`NumberInput`](crate::widget::number_input::NumberInput).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`NumberInput`](crate::widget::number_input::NumberInput).
pub button_background: Option<Background>,
/// The Color of the arrows of [`NumberInput`](crate::widget::number_input::NumberInput).
pub icon_color: Color,
}
impl Default for Style {
fn default() -> Self {
Self {
button_background: None,
icon_color: Color::BLACK,
}
}
}
/// The Catalog of a [`NumberInput`](crate::widget::number_input::NumberInput).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The Extended Catalog of a [`NumberInput`](crate::widget::number_input::NumberInput).
pub trait ExtendedCatalog:
text_input::Catalog + container::Catalog + text::Catalog + self::Catalog
{
/// The default class produced by the [`Catalog`].
#[must_use]
fn default_input<'a>() -> <Self as text_input::Catalog>::Class<'a> {
<Self as text_input::Catalog>::default()
}
/// The [`Style`] of a class with the given status.
fn style(&self, class: &<Self as self::Catalog>::Class<'_>, status: Status) -> Style;
}
impl ExtendedCatalog for Theme {
fn style(&self, class: &<Self as self::Catalog>::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = Style {
button_background: Some(palette.primary.strong.color.into()),
icon_color: palette.primary.strong.text,
};
match status {
Status::Disabled => Style {
button_background: base.button_background.map(|bg| match bg {
Background::Color(color) => Background::Color(Color {
a: color.a * 0.5,
..color
}),
Background::Gradient(grad) => Background::Gradient(grad),
}),
icon_color: Color {
a: base.icon_color.a * 0.5,
..base.icon_color
},
},
_ => base,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::Theme;
#[test]
fn style_default() {
let style = Style::default();
assert!(style.button_background.is_none());
assert_eq!(style.icon_color, Color::BLACK);
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(style.button_background.is_some());
#[allow(clippy::panic)]
if let Some(Background::Color(_)) = style.button_background {
// Background is a color
} else {
panic!("Expected button_background to be Some(Background::Color)");
}
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(style.button_background.is_some());
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(style.button_background.is_some());
}
#[test]
fn primary_theme_selected() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Selected);
assert!(style.button_background.is_some());
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(style.button_background.is_some());
}
#[test]
fn disabled_reduces_alpha() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let disabled_style = primary(&theme, Status::Disabled);
// Icon color alpha should be reduced
assert!(
disabled_style.icon_color.a <= base_style.icon_color.a,
"Disabled icon color should have reduced alpha"
);
// Button background alpha should be reduced for Color backgrounds
if let (Some(Background::Color(base_color)), Some(Background::Color(disabled_color))) = (
base_style.button_background,
disabled_style.button_background,
) {
assert!(
disabled_color.a <= base_color.a,
"Disabled button background should have reduced alpha"
);
}
}
#[test]
fn disabled_has_half_alpha() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let disabled_style = primary(&theme, Status::Disabled);
// Icon color should have approximately half the alpha
let expected_icon_alpha = base_style.icon_color.a * 0.5;
assert!(
(disabled_style.icon_color.a - expected_icon_alpha).abs() < 0.01,
"Disabled icon alpha should be approximately half"
);
}
#[test]
fn non_disabled_statuses_use_base_style() {
let theme = Theme::TokyoNight;
let active_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
let focused_style = primary(&theme, Status::Focused);
// All non-disabled statuses should have the same style
assert_eq!(
format!("{:?}", active_style.button_background),
format!("{:?}", hovered_style.button_background)
);
assert_eq!(
format!("{:?}", active_style.button_background),
format!("{:?}", focused_style.button_background)
);
assert_eq!(active_style.icon_color, hovered_style.icon_color);
assert_eq!(active_style.icon_color, focused_style.icon_color);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = <Theme as Catalog>::style(&theme, &class, Status::Active);
assert!(style.button_background.is_some());
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = <Theme as Catalog>::style(&theme, &class, Status::Active);
let hovered_style = <Theme as Catalog>::style(&theme, &class, Status::Hovered);
let disabled_style = <Theme as Catalog>::style(&theme, &class, Status::Disabled);
assert!(active_style.button_background.is_some());
assert!(hovered_style.button_background.is_some());
assert!(disabled_style.button_background.is_some());
}
#[test]
fn extended_catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = <Theme as ExtendedCatalog>::style(&theme, &class, Status::Active);
assert!(style.button_background.is_some());
}
#[test]
fn extended_catalog_default_input() {
let _class = <Theme as ExtendedCatalog>::default_input();
}
#[test]
fn disabled_preserves_gradient_backgrounds() {
// Create a style with a gradient background
let gradient = iced_core::Gradient::Linear(iced_core::gradient::Linear {
angle: 0.0.into(),
stops: [None; 8],
});
let style_with_gradient = Style {
button_background: Some(Background::Gradient(gradient)),
icon_color: Color::WHITE,
};
// If we had a disabled version, it should preserve the gradient
// This tests that gradients are handled in the match statement
#[allow(clippy::panic)]
if let Some(Background::Color(_)) = style_with_gradient.button_background {
panic!("Expected gradient to be preserved");
}
}
}
+256
View File
@@ -0,0 +1,256 @@
//! Selection List
//!
//! *This API requires the following crate features to be activated: `selection_list`*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
/// The appearance of a menu.
#[derive(Debug, Clone, Copy)]
pub struct Style {
/// The List Label Text Color
pub text_color: Color,
/// The background
pub background: Background,
/// The container Border width
pub border_width: f32,
/// The container Border color
pub border_color: Color,
}
/// The Catalog of a [`Badge`](crate::widget::selection_list::SelectionList).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::selection_list::SelectionList).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = Style {
text_color: palette.background.base.text,
background: palette.background.base.color.into(),
border_width: 1.0,
border_color: palette.background.weak.color,
};
match status {
Status::Hovered => Style {
text_color: palette.primary.base.text,
background: palette.primary.base.color.into(),
..base
},
Status::Selected => Style {
text_color: palette.primary.strong.text,
background: palette.primary.strong.color.into(),
..base
},
_ => base,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_selected() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Selected);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn hovered_changes_text_and_background() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
// Text color and background should be different when hovered
assert_ne!(base_style.text_color, hovered_style.text_color);
assert_ne!(
format!("{:?}", base_style.background),
format!("{:?}", hovered_style.background)
);
// Border properties should remain the same
assert_eq!(base_style.border_width, hovered_style.border_width);
assert_eq!(base_style.border_color, hovered_style.border_color);
}
#[test]
fn selected_changes_text_and_background() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let selected_style = primary(&theme, Status::Selected);
// Text color and background should be different when selected
assert_ne!(base_style.text_color, selected_style.text_color);
assert_ne!(
format!("{:?}", base_style.background),
format!("{:?}", selected_style.background)
);
// Border properties should remain the same
assert_eq!(base_style.border_width, selected_style.border_width);
assert_eq!(base_style.border_color, selected_style.border_color);
}
#[test]
fn selected_and_hovered_have_different_styles() {
let theme = Theme::TokyoNight;
let hovered_style = primary(&theme, Status::Hovered);
let selected_style = primary(&theme, Status::Selected);
// Selected and hovered should use different colors
assert_ne!(hovered_style.text_color, selected_style.text_color);
assert_ne!(
format!("{:?}", hovered_style.background),
format!("{:?}", selected_style.background)
);
}
#[test]
fn non_interactive_statuses_use_base_style() {
let theme = Theme::TokyoNight;
let active_style = primary(&theme, Status::Active);
let disabled_style = primary(&theme, Status::Disabled);
let focused_style = primary(&theme, Status::Focused);
// Non-interactive statuses should have the same style
assert_eq!(active_style.text_color, disabled_style.text_color);
assert_eq!(active_style.text_color, focused_style.text_color);
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", disabled_style.background)
);
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", focused_style.background)
);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = theme.style(&class, Status::Active);
let hovered_style = theme.style(&class, Status::Hovered);
let selected_style = theme.style(&class, Status::Selected);
assert!(matches!(active_style.background, Background::Color(_)));
assert!(matches!(hovered_style.background, Background::Color(_)));
assert!(matches!(selected_style.background, Background::Color(_)));
}
#[test]
fn border_width_is_consistent() {
let theme = Theme::TokyoNight;
// All statuses should have the same border width
let active = primary(&theme, Status::Active);
let hovered = primary(&theme, Status::Hovered);
let selected = primary(&theme, Status::Selected);
assert_eq!(active.border_width, 1.0);
assert_eq!(hovered.border_width, 1.0);
assert_eq!(selected.border_width, 1.0);
}
#[test]
fn border_color_is_consistent() {
let theme = Theme::TokyoNight;
// All statuses should have the same border color
let active = primary(&theme, Status::Active);
let hovered = primary(&theme, Status::Hovered);
let selected = primary(&theme, Status::Selected);
assert_eq!(active.border_color, hovered.border_color);
assert_eq!(active.border_color, selected.border_color);
}
#[test]
fn style_fields_are_valid() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Verify all fields have valid values
assert!(style.border_width > 0.0);
}
}
+458
View File
@@ -0,0 +1,458 @@
//! This is the style for [`Sidebar`](crate::widget::sidebar::Sidebar) and
//! [`SidebarWithContent`](crate::widget::sidebar::SidebarWithContent).
//!
//! *This API requires the following crate features to be activated: `sidebar`*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme, border::Radius};
/// The appearance of a [`Sidebar`](crate::widget::sidebar::Sidebar).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the sidebar.
pub background: Option<Background>,
/// The border color of the sidebar.
pub border_color: Option<Color>,
/// The border width of the sidebar.
pub border_width: f32,
/// The background of the tab labels.
pub tab_label_background: Background,
/// The border color of the tab labels.
pub tab_label_border_color: Color,
/// The border with of the tab labels.
pub tab_label_border_width: f32,
/// The icon color of the tab labels.
pub icon_color: Color,
/// The color of the closing icon border
pub icon_background: Option<Background>,
/// How soft/hard the corners of the icon border are
pub icon_border_radius: Radius,
/// The text color of the tab labels.
pub text_color: Color,
}
impl Default for Style {
fn default() -> Self {
Self {
background: None,
border_color: None,
border_width: 0.0,
tab_label_background: Background::Color([0.87, 0.87, 0.87].into()),
tab_label_border_color: [0.7, 0.7, 0.7].into(),
tab_label_border_width: 1.0,
icon_color: Color::BLACK,
icon_background: Some(Background::Color(Color::TRANSPARENT)),
icon_border_radius: 4.0.into(),
text_color: Color::BLACK,
}
}
}
/// The Catalog of a [`Sidebar`](crate::widget::sidebar::Sidebar).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Sidebar`](crate::widget::sidebar::Sidebar).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let mut base = Style::default();
let palette = theme.extended_palette();
base.text_color = palette.background.base.text;
match status {
Status::Disabled => {
base.tab_label_background = Background::Color(palette.background.strong.color);
}
Status::Hovered => {
base.tab_label_background = Background::Color(palette.primary.strong.color);
}
_ => {
base.tab_label_background = Background::Color(palette.primary.base.color);
}
}
base
}
/// The dark theme of a [`Sidebar`](crate::widget::sidebar::Sidebar).
#[must_use]
pub fn dark(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Background::Color([0.1, 0.1, 0.1].into()),
tab_label_border_color: [0.3, 0.3, 0.3].into(),
icon_color: Color::WHITE,
text_color: Color::WHITE,
..Default::default()
};
if status == Status::Disabled {
base.tab_label_background = Background::Color([0.13, 0.13, 0.13].into());
}
base
}
/// The red theme of a [`Sidebar`](crate::widget::sidebar::Sidebar).
#[must_use]
pub fn red(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Background::Color([1.0, 0.0, 0.0].into()),
tab_label_border_color: Color::TRANSPARENT,
tab_label_border_width: 0.0,
icon_color: Color::WHITE,
text_color: Color::WHITE,
..Default::default()
};
if status == Status::Disabled {
base.tab_label_background = Background::Color([0.13, 0.13, 0.13].into());
base.icon_color = Color::BLACK;
base.text_color = Color::BLACK;
}
base
}
/// The blue theme of a [`Sidebar`](crate::widget::sidebar::Sidebar).
#[must_use]
pub fn blue(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Background::Color([0.0, 0.0, 1.0].into()),
tab_label_border_color: [0.0, 0.0, 1.0].into(),
icon_color: Color::WHITE,
text_color: Color::WHITE,
..Default::default()
};
if status == Status::Disabled {
base.tab_label_background = Background::Color([0.5, 0.5, 1.0].into());
base.tab_label_border_color = [0.5, 0.5, 1.0].into();
}
base
}
/// The blue theme of a [`Sidebar`](crate::widget::sidebar::Sidebar).
#[must_use]
pub fn green(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Color::WHITE.into(),
icon_color: [0.0, 0.5, 0.0].into(),
text_color: [0.0, 0.5, 0.0].into(),
..Default::default()
};
match status {
Status::Disabled => {
base.icon_color = [0.7, 0.7, 0.7].into();
base.text_color = [0.7, 0.7, 0.7].into();
base.tab_label_border_color = [0.7, 0.7, 0.7].into();
}
_ => {
base.tab_label_border_color = [0.0, 0.5, 0.0].into();
}
}
base
}
/// The purple theme of a [`Sidebar`](crate::widget::sidebar::Sidebar).
#[must_use]
pub fn purple(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Color::WHITE.into(),
tab_label_border_color: Color::TRANSPARENT,
icon_color: [0.7, 0.0, 1.0].into(),
text_color: [0.7, 0.0, 1.0].into(),
..Default::default()
};
if status == Status::Disabled {
base.icon_color = Color::BLACK;
base.text_color = Color::BLACK;
}
base
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn style_default() {
let style = Style::default();
assert!(style.background.is_none());
assert!(style.border_color.is_none());
assert_eq!(style.border_width, 0.0);
assert!(matches!(style.tab_label_background, Background::Color(_)));
assert_eq!(style.tab_label_border_width, 1.0);
assert_eq!(style.icon_color, Color::BLACK);
assert!(style.icon_background.is_some());
assert_eq!(style.text_color, Color::BLACK);
assert_eq!(style.icon_border_radius.top_left, 4.0);
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.tab_label_background, Background::Color(_)));
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.tab_label_background, Background::Color(_)));
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.tab_label_background, Background::Color(_)));
}
#[test]
fn primary_changes_background_by_status() {
let theme = Theme::TokyoNight;
let active = primary(&theme, Status::Active);
let hovered = primary(&theme, Status::Hovered);
let disabled = primary(&theme, Status::Disabled);
// Different statuses should have different backgrounds
assert_ne!(
format!("{:?}", active.tab_label_background),
format!("{:?}", hovered.tab_label_background)
);
assert_ne!(
format!("{:?}", active.tab_label_background),
format!("{:?}", disabled.tab_label_background)
);
}
#[test]
fn dark_theme_active() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Active);
assert_eq!(style.icon_color, Color::WHITE);
assert_eq!(style.text_color, Color::WHITE);
}
#[test]
fn dark_theme_disabled() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Disabled);
assert_eq!(style.icon_color, Color::WHITE);
assert_eq!(style.text_color, Color::WHITE);
}
#[test]
fn dark_theme_changes_background_when_disabled() {
let theme = Theme::TokyoNight;
let active = dark(&theme, Status::Active);
let disabled = dark(&theme, Status::Disabled);
assert_ne!(
format!("{:?}", active.tab_label_background),
format!("{:?}", disabled.tab_label_background)
);
}
#[test]
fn red_theme_active() {
let theme = Theme::TokyoNight;
let style = red(&theme, Status::Active);
assert_eq!(
style.tab_label_background,
Background::Color([1.0, 0.0, 0.0].into())
);
assert_eq!(style.icon_color, Color::WHITE);
assert_eq!(style.text_color, Color::WHITE);
assert_eq!(style.tab_label_border_width, 0.0);
}
#[test]
fn red_theme_disabled() {
let theme = Theme::TokyoNight;
let style = red(&theme, Status::Disabled);
assert_eq!(style.icon_color, Color::BLACK);
assert_eq!(style.text_color, Color::BLACK);
}
#[test]
fn blue_theme_active() {
let theme = Theme::TokyoNight;
let style = blue(&theme, Status::Active);
assert_eq!(
style.tab_label_background,
Background::Color([0.0, 0.0, 1.0].into())
);
assert_eq!(style.icon_color, Color::WHITE);
assert_eq!(style.text_color, Color::WHITE);
}
#[test]
fn blue_theme_disabled() {
let theme = Theme::TokyoNight;
let style = blue(&theme, Status::Disabled);
assert_eq!(
style.tab_label_background,
Background::Color([0.5, 0.5, 1.0].into())
);
assert_eq!(style.tab_label_border_color, [0.5, 0.5, 1.0].into());
}
#[test]
fn green_theme_active() {
let theme = Theme::TokyoNight;
let style = green(&theme, Status::Active);
assert_eq!(style.tab_label_background, Background::Color(Color::WHITE));
assert_eq!(style.icon_color, [0.0, 0.5, 0.0].into());
assert_eq!(style.text_color, [0.0, 0.5, 0.0].into());
assert_eq!(style.tab_label_border_color, [0.0, 0.5, 0.0].into());
}
#[test]
fn green_theme_disabled() {
let theme = Theme::TokyoNight;
let style = green(&theme, Status::Disabled);
assert_eq!(style.icon_color, [0.7, 0.7, 0.7].into());
assert_eq!(style.text_color, [0.7, 0.7, 0.7].into());
assert_eq!(style.tab_label_border_color, [0.7, 0.7, 0.7].into());
}
#[test]
fn purple_theme_active() {
let theme = Theme::TokyoNight;
let style = purple(&theme, Status::Active);
assert_eq!(style.tab_label_background, Background::Color(Color::WHITE));
assert_eq!(style.icon_color, [0.7, 0.0, 1.0].into());
assert_eq!(style.text_color, [0.7, 0.0, 1.0].into());
assert_eq!(style.tab_label_border_color, Color::TRANSPARENT);
}
#[test]
fn purple_theme_disabled() {
let theme = Theme::TokyoNight;
let style = purple(&theme, Status::Disabled);
assert_eq!(style.icon_color, Color::BLACK);
assert_eq!(style.text_color, Color::BLACK);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.tab_label_background, Background::Color(_)));
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active = theme.style(&class, Status::Active);
let hovered = theme.style(&class, Status::Hovered);
let disabled = theme.style(&class, Status::Disabled);
assert!(matches!(active.tab_label_background, Background::Color(_)));
assert!(matches!(hovered.tab_label_background, Background::Color(_)));
assert!(matches!(
disabled.tab_label_background,
Background::Color(_)
));
}
#[test]
fn icon_border_radius_is_set() {
let style = Style::default();
// Icon border radius should be set to 4.0 (all corners)
assert_eq!(style.icon_border_radius.top_left, 4.0);
assert_eq!(style.icon_border_radius.top_right, 4.0);
assert_eq!(style.icon_border_radius.bottom_left, 4.0);
assert_eq!(style.icon_border_radius.bottom_right, 4.0);
}
#[test]
fn different_themes_produce_different_styles() {
let theme = Theme::TokyoNight;
let status = Status::Active;
let _primary_style = primary(&theme, status);
let dark_style = dark(&theme, status);
let red_style = red(&theme, status);
let blue_style = blue(&theme, status);
let green_style = green(&theme, status);
let purple_style = purple(&theme, status);
// All themes should produce different background styles
assert_ne!(
format!("{:?}", dark_style.tab_label_background),
format!("{:?}", red_style.tab_label_background)
);
assert_ne!(
format!("{:?}", red_style.tab_label_background),
format!("{:?}", blue_style.tab_label_background)
);
assert_ne!(
format!("{:?}", blue_style.tab_label_background),
format!("{:?}", green_style.tab_label_background)
);
// Text colors also differ between some themes
assert_ne!(green_style.text_color, purple_style.text_color);
}
}
+156
View File
@@ -0,0 +1,156 @@
//! Status Enum of an mouse Event.
//!
/// The Status of a widget event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
/// can be pressed.
Active,
/// can be pressed and it is being hovered.
Hovered,
/// is being pressed.
Pressed,
/// cannot be pressed.
Disabled,
/// is focused.
Focused,
/// is Selected.
Selected,
}
/// The style function of widget.
pub type StyleFn<'a, Theme, Style> = Box<dyn Fn(&Theme, Status) -> Style + 'a>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn status_active_exists() {
let status = Status::Active;
assert_eq!(status, Status::Active);
}
#[test]
fn status_hovered_exists() {
let status = Status::Hovered;
assert_eq!(status, Status::Hovered);
}
#[test]
fn status_pressed_exists() {
let status = Status::Pressed;
assert_eq!(status, Status::Pressed);
}
#[test]
fn status_disabled_exists() {
let status = Status::Disabled;
assert_eq!(status, Status::Disabled);
}
#[test]
fn status_focused_exists() {
let status = Status::Focused;
assert_eq!(status, Status::Focused);
}
#[test]
fn status_selected_exists() {
let status = Status::Selected;
assert_eq!(status, Status::Selected);
}
#[test]
fn status_equality() {
assert_eq!(Status::Active, Status::Active);
assert_eq!(Status::Hovered, Status::Hovered);
assert_eq!(Status::Pressed, Status::Pressed);
assert_eq!(Status::Disabled, Status::Disabled);
assert_eq!(Status::Focused, Status::Focused);
assert_eq!(Status::Selected, Status::Selected);
}
#[test]
fn status_inequality() {
assert_ne!(Status::Active, Status::Hovered);
assert_ne!(Status::Active, Status::Pressed);
assert_ne!(Status::Active, Status::Disabled);
assert_ne!(Status::Active, Status::Focused);
assert_ne!(Status::Active, Status::Selected);
assert_ne!(Status::Hovered, Status::Pressed);
assert_ne!(Status::Hovered, Status::Disabled);
assert_ne!(Status::Disabled, Status::Focused);
}
#[test]
fn status_clone() {
let status = Status::Active;
let cloned = status;
assert_eq!(status, cloned);
}
#[test]
fn status_copy() {
let status = Status::Active;
let copied = status;
assert_eq!(status, copied);
}
#[test]
fn status_debug() {
let status = Status::Active;
let debug_str = format!("{status:?}");
assert_eq!(debug_str, "Active");
let status = Status::Hovered;
let debug_str = format!("{status:?}");
assert_eq!(debug_str, "Hovered");
}
#[test]
fn all_statuses_are_different() {
let statuses = [
Status::Active,
Status::Hovered,
Status::Pressed,
Status::Disabled,
Status::Focused,
Status::Selected,
];
// Each status should be unique
for (i, status1) in statuses.iter().enumerate() {
for (j, status2) in statuses.iter().enumerate() {
if i == j {
assert_eq!(status1, status2);
} else {
assert_ne!(status1, status2);
}
}
}
}
#[test]
fn style_fn_type_compiles() {
// This test verifies that the StyleFn type alias is correctly defined
// and can be used with a simple function
fn example_style_fn(_theme: &(), status: Status) -> u32 {
match status {
Status::Active => 1,
Status::Hovered => 2,
Status::Pressed => 3,
Status::Disabled => 4,
Status::Focused => 5,
Status::Selected => 6,
}
}
let style_fn: StyleFn<(), u32> = Box::new(example_style_fn);
assert_eq!(style_fn(&(), Status::Active), 1);
assert_eq!(style_fn(&(), Status::Hovered), 2);
assert_eq!(style_fn(&(), Status::Pressed), 3);
assert_eq!(style_fn(&(), Status::Disabled), 4);
assert_eq!(style_fn(&(), Status::Focused), 5);
assert_eq!(style_fn(&(), Status::Selected), 6);
}
}
+172
View File
@@ -0,0 +1,172 @@
//! Helper enum for the state of the style
/// The state of the style
#[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum StyleState {
/// Use the active style
Active,
/// Use the selected style
Selected,
/// Use the hovered style
Hovered,
/// Use the focused style
Focused,
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[test]
fn style_state_active_exists() {
let state = StyleState::Active;
assert_eq!(state, StyleState::Active);
}
#[test]
fn style_state_selected_exists() {
let state = StyleState::Selected;
assert_eq!(state, StyleState::Selected);
}
#[test]
fn style_state_hovered_exists() {
let state = StyleState::Hovered;
assert_eq!(state, StyleState::Hovered);
}
#[test]
fn style_state_focused_exists() {
let state = StyleState::Focused;
assert_eq!(state, StyleState::Focused);
}
#[test]
fn style_state_equality() {
assert_eq!(StyleState::Active, StyleState::Active);
assert_eq!(StyleState::Selected, StyleState::Selected);
assert_eq!(StyleState::Hovered, StyleState::Hovered);
assert_eq!(StyleState::Focused, StyleState::Focused);
}
#[test]
fn style_state_inequality() {
assert_ne!(StyleState::Active, StyleState::Selected);
assert_ne!(StyleState::Active, StyleState::Hovered);
assert_ne!(StyleState::Active, StyleState::Focused);
assert_ne!(StyleState::Selected, StyleState::Hovered);
assert_ne!(StyleState::Selected, StyleState::Focused);
assert_ne!(StyleState::Hovered, StyleState::Focused);
}
#[test]
fn style_state_debug() {
let state = StyleState::Active;
let debug_str = format!("{state:?}");
assert_eq!(debug_str, "Active");
let state = StyleState::Selected;
let debug_str = format!("{state:?}");
assert_eq!(debug_str, "Selected");
let state = StyleState::Hovered;
let debug_str = format!("{state:?}");
assert_eq!(debug_str, "Hovered");
let state = StyleState::Focused;
let debug_str = format!("{state:?}");
assert_eq!(debug_str, "Focused");
}
#[test]
fn style_state_ordering() {
// Verify the order based on enum definition
assert!(StyleState::Active < StyleState::Selected);
assert!(StyleState::Selected < StyleState::Hovered);
assert!(StyleState::Hovered < StyleState::Focused);
assert!(StyleState::Active <= StyleState::Active);
assert!(StyleState::Active <= StyleState::Selected);
assert!(StyleState::Focused >= StyleState::Active);
assert!(StyleState::Focused >= StyleState::Focused);
}
#[test]
fn style_state_hash() {
// Verify that StyleState can be used as a HashMap key
let mut map = HashMap::new();
let _ = map.insert(StyleState::Active, "active");
let _ = map.insert(StyleState::Selected, "selected");
let _ = map.insert(StyleState::Hovered, "hovered");
let _ = map.insert(StyleState::Focused, "focused");
assert_eq!(map.get(&StyleState::Active), Some(&"active"));
assert_eq!(map.get(&StyleState::Selected), Some(&"selected"));
assert_eq!(map.get(&StyleState::Hovered), Some(&"hovered"));
assert_eq!(map.get(&StyleState::Focused), Some(&"focused"));
}
#[test]
fn all_style_states_are_different() {
let states = [
StyleState::Active,
StyleState::Selected,
StyleState::Hovered,
StyleState::Focused,
];
// Each state should be unique
for (i, state1) in states.iter().enumerate() {
for (j, state2) in states.iter().enumerate() {
if i == j {
assert_eq!(state1, state2);
} else {
assert_ne!(state1, state2);
}
}
}
}
#[test]
fn style_state_can_be_matched() {
let state = StyleState::Active;
let value = match state {
StyleState::Active => 1,
StyleState::Selected => 2,
StyleState::Hovered => 3,
StyleState::Focused => 4,
};
assert_eq!(value, 1);
let state = StyleState::Focused;
let value = match state {
StyleState::Active => 1,
StyleState::Selected => 2,
StyleState::Hovered => 3,
StyleState::Focused => 4,
};
assert_eq!(value, 4);
}
#[test]
fn style_state_ord_comparison() {
let mut states = vec![
StyleState::Focused,
StyleState::Active,
StyleState::Hovered,
StyleState::Selected,
];
states.sort();
assert_eq!(
states,
vec![
StyleState::Active,
StyleState::Selected,
StyleState::Hovered,
StyleState::Focused,
]
);
}
}
+472
View File
@@ -0,0 +1,472 @@
//! Displays a [`TabBar`](crate::widget::tab_bar::TabBar) to select the content
//! to be displayed.
//!
//! You have to manage the logic to show the contend by yourself or you may want
//! to use the [`Tabs`](crate::widget::tabs::Tabs) widget instead.
//!
//! *This API requires the following crate features to be activated: `tab_bar`*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme, border::Radius};
/// The appearance of a [`TabBar`](crate::widget::tab_bar::TabBar).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the tab bar.
pub background: Option<Background>,
/// The border color of the tab bar.
pub border_color: Option<Color>,
/// The border width of the tab bar.
pub border_width: f32,
/// The border radius of a tab.
pub tab_border_radius: Radius,
/// The background of the tab labels.
pub tab_label_background: Background,
/// The border color of the tab labels.
pub tab_label_border_color: Color,
/// The border with of the tab labels.
pub tab_label_border_width: f32,
/// The icon color of the tab labels.
pub icon_color: Color,
/// The color of the closing icon border
pub icon_background: Option<Background>,
/// How soft/hard the corners of the icon border are
pub icon_border_radius: Radius,
/// The text color of the tab labels.
pub text_color: Color,
}
impl Default for Style {
fn default() -> Self {
Self {
background: None,
border_color: None,
border_width: 0.0,
tab_border_radius: Radius::default(),
tab_label_background: Background::Color([0.87, 0.87, 0.87].into()),
tab_label_border_color: [0.7, 0.7, 0.7].into(),
tab_label_border_width: 1.0,
icon_color: Color::BLACK,
icon_background: Some(Background::Color(Color::TRANSPARENT)),
icon_border_radius: 4.0.into(),
text_color: Color::BLACK,
}
}
}
/// The Catalog of a [`TabBar`](crate::widget::tab_bar::TabBar).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`TabBar`](crate::widget::tab_bar::TabBar).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let mut base = Style::default();
let palette = theme.extended_palette();
base.text_color = palette.background.base.text;
match status {
Status::Disabled => {
base.tab_label_background = Background::Color(palette.background.strong.color);
}
Status::Hovered => {
base.tab_label_background = Background::Color(palette.primary.strong.color);
}
_ => {
base.tab_label_background = Background::Color(palette.primary.base.color);
}
}
base
}
/// The dark theme of a [`TabBar`](crate::widget::tab_bar::TabBar).
#[must_use]
pub fn dark(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Background::Color([0.1, 0.1, 0.1].into()),
tab_label_border_color: [0.3, 0.3, 0.3].into(),
icon_color: Color::WHITE,
text_color: Color::WHITE,
..Default::default()
};
if status == Status::Disabled {
base.tab_label_background = Background::Color([0.13, 0.13, 0.13].into());
}
base
}
/// The red theme of a [`TabBar`](crate::widget::tab_bar::TabBar).
#[must_use]
pub fn red(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Background::Color([1.0, 0.0, 0.0].into()),
tab_label_border_color: Color::TRANSPARENT,
tab_label_border_width: 0.0,
icon_color: Color::WHITE,
text_color: Color::WHITE,
..Default::default()
};
if status == Status::Disabled {
base.tab_label_background = Background::Color([0.13, 0.13, 0.13].into());
base.icon_color = Color::BLACK;
base.text_color = Color::BLACK;
}
base
}
/// The blue theme of a [`TabBar`](crate::widget::tab_bar::TabBar).
#[must_use]
pub fn blue(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Background::Color([0.0, 0.0, 1.0].into()),
tab_label_border_color: [0.0, 0.0, 1.0].into(),
icon_color: Color::WHITE,
text_color: Color::WHITE,
..Default::default()
};
if status == Status::Disabled {
base.tab_label_background = Background::Color([0.5, 0.5, 1.0].into());
base.tab_label_border_color = [0.5, 0.5, 1.0].into();
}
base
}
/// The blue theme of a [`TabBar`](crate::widget::tab_bar::TabBar).
#[must_use]
pub fn green(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Color::WHITE.into(),
icon_color: [0.0, 0.5, 0.0].into(),
text_color: [0.0, 0.5, 0.0].into(),
..Default::default()
};
match status {
Status::Disabled => {
base.icon_color = [0.7, 0.7, 0.7].into();
base.text_color = [0.7, 0.7, 0.7].into();
base.tab_label_border_color = [0.7, 0.7, 0.7].into();
}
_ => {
base.tab_label_border_color = [0.0, 0.5, 0.0].into();
}
}
base
}
/// The purple theme of a [`TabBar`](crate::widget::tab_bar::TabBar).
#[must_use]
pub fn purple(_theme: &Theme, status: Status) -> Style {
let mut base = Style {
tab_label_background: Color::WHITE.into(),
tab_label_border_color: Color::TRANSPARENT,
icon_color: [0.7, 0.0, 1.0].into(),
text_color: [0.7, 0.0, 1.0].into(),
..Default::default()
};
if status == Status::Disabled {
base.icon_color = Color::BLACK;
base.text_color = Color::BLACK;
}
base
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn style_default() {
let style = Style::default();
assert!(style.background.is_none());
assert!(style.border_color.is_none());
assert_eq!(style.border_width, 0.0);
assert!(matches!(style.tab_label_background, Background::Color(_)));
assert_eq!(style.tab_label_border_width, 1.0);
assert_eq!(style.icon_color, Color::BLACK);
assert!(style.icon_background.is_some());
assert_eq!(style.text_color, Color::BLACK);
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.tab_label_background, Background::Color(_)));
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.tab_label_background, Background::Color(_)));
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.tab_label_background, Background::Color(_)));
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.tab_label_background, Background::Color(_)));
}
#[test]
fn primary_changes_background_by_status() {
let theme = Theme::TokyoNight;
let active = primary(&theme, Status::Active);
let hovered = primary(&theme, Status::Hovered);
let disabled = primary(&theme, Status::Disabled);
// Different statuses should have different backgrounds
assert_ne!(
format!("{:?}", active.tab_label_background),
format!("{:?}", hovered.tab_label_background)
);
assert_ne!(
format!("{:?}", active.tab_label_background),
format!("{:?}", disabled.tab_label_background)
);
}
#[test]
fn dark_theme_active() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Active);
assert_eq!(style.icon_color, Color::WHITE);
assert_eq!(style.text_color, Color::WHITE);
}
#[test]
fn dark_theme_disabled() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Disabled);
assert_eq!(style.icon_color, Color::WHITE);
assert_eq!(style.text_color, Color::WHITE);
}
#[test]
fn dark_theme_changes_background_when_disabled() {
let theme = Theme::TokyoNight;
let active = dark(&theme, Status::Active);
let disabled = dark(&theme, Status::Disabled);
assert_ne!(
format!("{:?}", active.tab_label_background),
format!("{:?}", disabled.tab_label_background)
);
}
#[test]
fn red_theme_active() {
let theme = Theme::TokyoNight;
let style = red(&theme, Status::Active);
assert_eq!(
style.tab_label_background,
Background::Color([1.0, 0.0, 0.0].into())
);
assert_eq!(style.icon_color, Color::WHITE);
assert_eq!(style.text_color, Color::WHITE);
assert_eq!(style.tab_label_border_width, 0.0);
}
#[test]
fn red_theme_disabled() {
let theme = Theme::TokyoNight;
let style = red(&theme, Status::Disabled);
assert_eq!(style.icon_color, Color::BLACK);
assert_eq!(style.text_color, Color::BLACK);
}
#[test]
fn blue_theme_active() {
let theme = Theme::TokyoNight;
let style = blue(&theme, Status::Active);
assert_eq!(
style.tab_label_background,
Background::Color([0.0, 0.0, 1.0].into())
);
assert_eq!(style.icon_color, Color::WHITE);
assert_eq!(style.text_color, Color::WHITE);
}
#[test]
fn blue_theme_disabled() {
let theme = Theme::TokyoNight;
let style = blue(&theme, Status::Disabled);
assert_eq!(
style.tab_label_background,
Background::Color([0.5, 0.5, 1.0].into())
);
assert_eq!(style.tab_label_border_color, [0.5, 0.5, 1.0].into());
}
#[test]
fn green_theme_active() {
let theme = Theme::TokyoNight;
let style = green(&theme, Status::Active);
assert_eq!(style.tab_label_background, Background::Color(Color::WHITE));
assert_eq!(style.icon_color, [0.0, 0.5, 0.0].into());
assert_eq!(style.text_color, [0.0, 0.5, 0.0].into());
assert_eq!(style.tab_label_border_color, [0.0, 0.5, 0.0].into());
}
#[test]
fn green_theme_disabled() {
let theme = Theme::TokyoNight;
let style = green(&theme, Status::Disabled);
assert_eq!(style.icon_color, [0.7, 0.7, 0.7].into());
assert_eq!(style.text_color, [0.7, 0.7, 0.7].into());
assert_eq!(style.tab_label_border_color, [0.7, 0.7, 0.7].into());
}
#[test]
fn purple_theme_active() {
let theme = Theme::TokyoNight;
let style = purple(&theme, Status::Active);
assert_eq!(style.tab_label_background, Background::Color(Color::WHITE));
assert_eq!(style.icon_color, [0.7, 0.0, 1.0].into());
assert_eq!(style.text_color, [0.7, 0.0, 1.0].into());
assert_eq!(style.tab_label_border_color, Color::TRANSPARENT);
}
#[test]
fn purple_theme_disabled() {
let theme = Theme::TokyoNight;
let style = purple(&theme, Status::Disabled);
assert_eq!(style.icon_color, Color::BLACK);
assert_eq!(style.text_color, Color::BLACK);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.tab_label_background, Background::Color(_)));
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active = theme.style(&class, Status::Active);
let hovered = theme.style(&class, Status::Hovered);
let disabled = theme.style(&class, Status::Disabled);
assert!(matches!(active.tab_label_background, Background::Color(_)));
assert!(matches!(hovered.tab_label_background, Background::Color(_)));
assert!(matches!(
disabled.tab_label_background,
Background::Color(_)
));
}
#[test]
fn icon_border_radius_is_set() {
let style = Style::default();
// Icon border radius should be set to 4.0 (all corners)
assert_eq!(style.icon_border_radius.top_left, 4.0);
assert_eq!(style.icon_border_radius.top_right, 4.0);
assert_eq!(style.icon_border_radius.bottom_left, 4.0);
assert_eq!(style.icon_border_radius.bottom_right, 4.0);
}
#[test]
fn different_themes_produce_different_styles() {
let theme = Theme::TokyoNight;
let status = Status::Active;
let _primary_style = primary(&theme, status);
let dark_style = dark(&theme, status);
let red_style = red(&theme, status);
let blue_style = blue(&theme, status);
let green_style = green(&theme, status);
let purple_style = purple(&theme, status);
// All themes should produce different background styles
assert_ne!(
format!("{:?}", dark_style.tab_label_background),
format!("{:?}", red_style.tab_label_background)
);
assert_ne!(
format!("{:?}", red_style.tab_label_background),
format!("{:?}", blue_style.tab_label_background)
);
assert_ne!(
format!("{:?}", blue_style.tab_label_background),
format!("{:?}", green_style.tab_label_background)
);
// Text colors also differ between some themes
assert_ne!(green_style.text_color, purple_style.text_color);
}
}
+317
View File
@@ -0,0 +1,317 @@
//! Use a time picker as an input element for picking times.
//!
//! *This API requires the following crate features to be activated: `time_picker`*
#![allow(clippy::doc_markdown)]
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
/// The style of a [`TimePicker`](crate::widget::TimePicker).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`TimePicker`](crate::widget::TimePicker).
pub background: Background,
/// The border radius of the [`TimePicker`](crate::widget::TimePicker).
pub border_radius: f32,
/// The border width of the [`TimePicker`](crate::widget::TimePicker).
pub border_width: f32,
/// The border color of the [`TimePicker`](crate::widget::TimePicker).
pub border_color: Color,
/// The text color of the [`TimePicker`](crate::widget::TimePicker).
pub text_color: Color,
/// The color of the clock numbers of the
/// [`TimePicker`](crate::widget::TimePicker).
pub clock_number_color: Color,
/// The background of the clock numbers of the
/// [`TimePicker`](crate::widget::TimePicker).
pub clock_number_background: Color,
/// The color of the dots on the clock of the
/// [`TimePicker`](crate::widget::TimePicker).
pub clock_dots_color: Color,
/// The color of the hands of the clock of the
/// [`TimePicker`](crate::widget::TimePicker).
pub clock_hand_color: Color,
/// The with of the hands of the clock of the
/// [`TimePicker](crate::widget::TimePicker).
pub clock_hand_width: f32,
}
/// The Catalog of a [`TimePicker`](crate::widget::TimePicker).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`TimePicker`](crate::widget::TimePicker).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let foreground = theme.palette();
let base = Style {
background: palette.background.base.color.into(),
border_radius: 15.0,
border_width: 1.0,
border_color: foreground.text,
text_color: foreground.text,
clock_number_color: foreground.text,
clock_number_background: palette.background.base.color,
clock_dots_color: [0.87, 0.87, 0.87].into(),
clock_hand_color: [0.87, 0.87, 0.87].into(),
clock_hand_width: 3.0,
};
match status {
Status::Focused => Style {
border_color: Color::from_rgb(0.5, 0.5, 0.5),
..base
},
Status::Hovered => Style {
clock_number_color: palette.primary.weak.text,
clock_number_background: palette.primary.weak.color,
..base
},
Status::Selected => Style {
clock_number_color: palette.primary.strong.text,
clock_number_background: palette.primary.strong.color,
..base
},
_ => base,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
assert_eq!(style.clock_hand_width, 3.0);
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_color, Color::from_rgb(0.5, 0.5, 0.5));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_selected() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Selected);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn focused_changes_border_color() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let focused_style = primary(&theme, Status::Focused);
// Border color should change when focused
assert_ne!(base_style.border_color, focused_style.border_color);
assert_eq!(focused_style.border_color, Color::from_rgb(0.5, 0.5, 0.5));
// Other properties should remain the same
assert_eq!(base_style.background, focused_style.background);
assert_eq!(base_style.border_radius, focused_style.border_radius);
assert_eq!(base_style.border_width, focused_style.border_width);
assert_eq!(base_style.text_color, focused_style.text_color);
}
#[test]
fn hovered_changes_clock_number_styling() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
// Clock number color and background should change when hovered
assert_ne!(
base_style.clock_number_color,
hovered_style.clock_number_color
);
assert_ne!(
base_style.clock_number_background,
hovered_style.clock_number_background
);
// Other properties should remain the same
assert_eq!(base_style.background, hovered_style.background);
assert_eq!(base_style.border_color, hovered_style.border_color);
assert_eq!(base_style.text_color, hovered_style.text_color);
}
#[test]
fn selected_changes_clock_number_styling() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let selected_style = primary(&theme, Status::Selected);
// Clock number color and background should change when selected
assert_ne!(
base_style.clock_number_color,
selected_style.clock_number_color
);
assert_ne!(
base_style.clock_number_background,
selected_style.clock_number_background
);
// Other properties should remain the same
assert_eq!(base_style.background, selected_style.background);
assert_eq!(base_style.border_color, selected_style.border_color);
assert_eq!(base_style.text_color, selected_style.text_color);
}
#[test]
fn selected_and_hovered_have_different_styles() {
let theme = Theme::TokyoNight;
let hovered_style = primary(&theme, Status::Hovered);
let selected_style = primary(&theme, Status::Selected);
// Hovered and selected should use different colors
assert_ne!(
hovered_style.clock_number_color,
selected_style.clock_number_color
);
assert_ne!(
hovered_style.clock_number_background,
selected_style.clock_number_background
);
}
#[test]
fn clock_components_have_valid_styling() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Verify clock components have valid colors
assert_eq!(style.clock_dots_color, [0.87, 0.87, 0.87].into());
assert_eq!(style.clock_hand_color, [0.87, 0.87, 0.87].into());
assert_eq!(style.clock_hand_width, 3.0);
}
#[test]
fn non_interactive_statuses_use_base_style() {
let theme = Theme::TokyoNight;
let active_style = primary(&theme, Status::Active);
let disabled_style = primary(&theme, Status::Disabled);
// Non-interactive statuses should have the same style
assert_eq!(active_style.background, disabled_style.background);
assert_eq!(active_style.border_color, disabled_style.border_color);
assert_eq!(active_style.text_color, disabled_style.text_color);
assert_eq!(
active_style.clock_number_color,
disabled_style.clock_number_color
);
assert_eq!(
active_style.clock_number_background,
disabled_style.clock_number_background
);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = theme.style(&class, Status::Active);
let focused_style = theme.style(&class, Status::Focused);
let hovered_style = theme.style(&class, Status::Hovered);
let selected_style = theme.style(&class, Status::Selected);
assert!(matches!(active_style.background, Background::Color(_)));
assert!(matches!(focused_style.background, Background::Color(_)));
assert!(matches!(hovered_style.background, Background::Color(_)));
assert!(matches!(selected_style.background, Background::Color(_)));
}
#[test]
fn style_fields_are_valid() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Verify all fields have valid values
assert!(style.border_radius > 0.0);
assert!(style.border_width > 0.0);
assert!(style.clock_hand_width > 0.0);
}
}
+109
View File
@@ -0,0 +1,109 @@
//! Stateless, pure widget for iced
//use iced_widget::{renderer, style};
pub mod helpers;
#[allow(unused_imports)]
pub use helpers::*;
pub mod overlay;
pub mod common;
pub use common::InnerBounds;
#[cfg(feature = "badge")]
pub mod badge;
#[cfg(feature = "badge")]
pub use badge::Badge;
#[cfg(feature = "number_input")]
pub mod number_input;
#[cfg(feature = "number_input")]
pub use number_input::NumberInput;
#[cfg(feature = "typed_input")]
pub mod typed_input;
#[cfg(feature = "typed_input")]
pub use typed_input::TypedInput;
#[cfg(feature = "card")]
pub mod card;
#[cfg(feature = "card")]
pub use card::Card;
#[cfg(feature = "color_picker")]
pub mod color_picker;
#[cfg(feature = "color_picker")]
pub use color_picker::ColorPicker;
#[cfg(feature = "date_picker")]
pub mod date_picker;
#[cfg(feature = "date_picker")]
pub use date_picker::DatePicker;
#[cfg(feature = "selection_list")]
pub mod selection_list;
#[cfg(feature = "selection_list")]
pub use selection_list::{List, SelectionList};
#[cfg(feature = "tab_bar")]
pub mod tab_bar;
#[cfg(feature = "tab_bar")]
pub use tab_bar::{TabBar, TabLabel};
#[cfg(feature = "tabs")]
pub mod tabs;
#[cfg(feature = "tabs")]
pub use tabs::{TabBarPosition, Tabs};
#[cfg(feature = "time_picker")]
pub mod time_picker;
#[cfg(feature = "time_picker")]
pub use time_picker::TimePicker;
#[cfg(feature = "wrap")]
pub mod wrap;
#[cfg(feature = "wrap")]
pub use wrap::Wrap;
#[cfg(feature = "menu")]
pub mod menu;
#[cfg(feature = "menu")]
pub use menu::Menu;
#[cfg(feature = "quad")]
pub mod quad;
#[cfg(feature = "spinner")]
pub mod spinner;
#[cfg(feature = "spinner")]
pub use spinner::Spinner;
#[cfg(feature = "context_menu")]
pub mod context_menu;
#[cfg(feature = "context_menu")]
pub use context_menu::ContextMenu;
#[cfg(feature = "slide_bar")]
pub mod slide_bar;
#[cfg(feature = "slide_bar")]
pub use slide_bar::SlideBar;
#[cfg(feature = "drop_down")]
pub mod drop_down;
#[cfg(feature = "drop_down")]
pub use drop_down::DropDown;
#[cfg(feature = "sidebar")]
pub mod sidebar;
#[cfg(feature = "sidebar")]
pub use sidebar::{Sidebar, SidebarWithContent};
#[cfg(feature = "labeled_frame")]
pub mod labeled_frame;
#[cfg(feature = "labeled_frame")]
pub use labeled_frame::LabeledFrame;
#[cfg(feature = "custom_layout")]
pub mod custom_layout;
#[cfg(feature = "custom_layout")]
pub use custom_layout::CustomLayout;
+496
View File
@@ -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);
}
}
+1406
View File
File diff suppressed because it is too large. Load diff
+421
View File
@@ -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);
}
}
+63
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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);
}
}
+390
View File
@@ -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
View File
@@ -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)
}
}
+159
View File
@@ -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
View File
@@ -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
![iced_aw_menu_doc_1](images/iced_aw_menu_doc_1.png)
### 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.
![iced_aw_menu_doc_3](images/iced_aw_menu_doc_3.png)
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).
![iced_aw_menu_doc_2](images/iced_aw_menu_doc_2.png)
# 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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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,
);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+433
View File
@@ -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);
}
}
File diff suppressed because it is too large. Load diff
+21
View File
@@ -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;
File diff suppressed because it is too large. Load diff
+122
View File
@@ -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
View File
@@ -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
View File
@@ -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)
}
}
+12
View File
@@ -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
View File
@@ -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
View File
@@ -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)
}
}
File diff suppressed because it is too large. Load diff
+461
View File
@@ -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);
}
}
+212
View File
@@ -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)
}
}
File diff suppressed because it is too large. Load diff
+49
View File
@@ -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)
}
}
+635
View File
@@ -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)
}
}
+16
View File
@@ -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
View File
@@ -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
View File
@@ -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());
}
}
+1006
View File
File diff suppressed because it is too large. Load diff