Use `Self` everywhere (#3787)

This turns on the clippy lint
[`clippy::use_self`](https://rust-lang.github.io/rust-clippy/v0.0.212/index.html#use_self)
and fixes it everywhere.
This commit is contained in:
Emil Ernerfeldt 2024-01-08 17:41:21 +01:00 committed by GitHub
parent 12ad9e7b36
commit 401de05630
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
72 changed files with 590 additions and 580 deletions

View File

@ -2,23 +2,21 @@
# cargo install cargo-cranky && cargo cranky # cargo install cargo-cranky && cargo cranky
# See also clippy.toml # See also clippy.toml
deny = [ deny = ["unsafe_code"]
"unsafe_code",
# Disabled waiting on https://github.com/rust-lang/rust-clippy/issues/9602
#"clippy::self_named_module_files",
]
warn = [ warn = [
"clippy::all", "clippy::all",
"clippy::as_ptr_cast_mut", "clippy::as_ptr_cast_mut",
"clippy::await_holding_lock", "clippy::await_holding_lock",
"clippy::bool_to_int_with_if", "clippy::bool_to_int_with_if",
"clippy::branches_sharing_code",
"clippy::char_lit_as_u8", "clippy::char_lit_as_u8",
"clippy::checked_conversions", "clippy::checked_conversions",
"clippy::clear_with_drain", "clippy::clear_with_drain",
"clippy::cloned_instead_of_copied", "clippy::cloned_instead_of_copied",
"clippy::dbg_macro", "clippy::dbg_macro",
"clippy::debug_assert_with_mut_call", "clippy::debug_assert_with_mut_call",
"clippy::default_union_representation",
"clippy::derive_partial_eq_without_eq", "clippy::derive_partial_eq_without_eq",
"clippy::disallowed_macros", # See clippy.toml "clippy::disallowed_macros", # See clippy.toml
"clippy::disallowed_methods", # See clippy.toml "clippy::disallowed_methods", # See clippy.toml
@ -28,6 +26,7 @@ warn = [
"clippy::doc_link_with_quotes", "clippy::doc_link_with_quotes",
"clippy::doc_markdown", "clippy::doc_markdown",
"clippy::empty_enum", "clippy::empty_enum",
"clippy::empty_line_after_outer_attr",
"clippy::enum_glob_use", "clippy::enum_glob_use",
"clippy::equatable_if_let", "clippy::equatable_if_let",
"clippy::exit", "clippy::exit",
@ -90,14 +89,17 @@ warn = [
"clippy::nonstandard_macro_braces", "clippy::nonstandard_macro_braces",
"clippy::option_option", "clippy::option_option",
"clippy::path_buf_push_overwrite", "clippy::path_buf_push_overwrite",
"clippy::print_stdout",
"clippy::ptr_as_ptr", "clippy::ptr_as_ptr",
"clippy::ptr_cast_constness", "clippy::ptr_cast_constness",
"clippy::pub_without_shorthand",
"clippy::rc_mutex", "clippy::rc_mutex",
"clippy::redundant_type_annotations", "clippy::redundant_type_annotations",
"clippy::ref_option_ref", "clippy::ref_option_ref",
"clippy::rest_pat_in_fully_bound_structs", "clippy::rest_pat_in_fully_bound_structs",
"clippy::same_functions_in_if_condition", "clippy::same_functions_in_if_condition",
"clippy::semicolon_if_nothing_returned", "clippy::semicolon_if_nothing_returned",
"clippy::significant_drop_tightening",
"clippy::single_match_else", "clippy::single_match_else",
"clippy::str_to_string", "clippy::str_to_string",
"clippy::string_add_assign", "clippy::string_add_assign",
@ -109,21 +111,27 @@ warn = [
"clippy::todo", "clippy::todo",
"clippy::trailing_empty_array", "clippy::trailing_empty_array",
"clippy::trait_duplication_in_bounds", "clippy::trait_duplication_in_bounds",
"clippy::transmute_ptr_to_ptr",
"clippy::tuple_array_conversions", "clippy::tuple_array_conversions",
"clippy::unchecked_duration_subtraction", "clippy::unchecked_duration_subtraction",
"clippy::undocumented_unsafe_blocks",
"clippy::unimplemented", "clippy::unimplemented",
"clippy::uninlined_format_args", "clippy::uninlined_format_args",
"clippy::unnecessary_box_returns", "clippy::unnecessary_box_returns",
"clippy::unnecessary_safety_comment",
"clippy::unnecessary_safety_doc", "clippy::unnecessary_safety_doc",
"clippy::unnecessary_self_imports",
"clippy::unnecessary_struct_initialization", "clippy::unnecessary_struct_initialization",
"clippy::unnecessary_wraps", "clippy::unnecessary_wraps",
"clippy::unnested_or_patterns", "clippy::unnested_or_patterns",
"clippy::unused_peekable", "clippy::unused_peekable",
"clippy::unused_rounding", "clippy::unused_rounding",
"clippy::unused_self", "clippy::unused_self",
"clippy::use_self",
"clippy::useless_transmute", "clippy::useless_transmute",
"clippy::verbose_file_reads", "clippy::verbose_file_reads",
"clippy::wildcard_dependencies", "clippy::wildcard_dependencies",
"clippy::wildcard_imports",
"clippy::zero_sized_map_values", "clippy::zero_sized_map_values",
"elided_lifetimes_in_paths", "elided_lifetimes_in_paths",
"future_incompatible", "future_incompatible",
@ -137,6 +145,14 @@ warn = [
"unused_extern_crates", "unused_extern_crates",
"unused_import_braces", "unused_import_braces",
"unused_lifetimes", "unused_lifetimes",
# Enable when we update MSRV:
# "clippy::implied_bounds_in_impls",
# "clippy::needless_pass_by_ref_mut",
# "clippy::readonly_write_lock",
# "clippy::should_panic_without_expect",
# "clippy::string_lit_chars_any",
] ]
allow = [ allow = [
@ -148,9 +164,13 @@ allow = [
"clippy::let_underscore_untyped", "clippy::let_underscore_untyped",
"clippy::missing_assert_message", "clippy::missing_assert_message",
"clippy::missing_errors_doc", "clippy::missing_errors_doc",
"clippy::print_stderr", # TODO(emilk): use `log` crate instead
"clippy::self_named_module_files", # False positives
"clippy::too_many_lines",
"clippy::undocumented_unsafe_blocks", "clippy::undocumented_unsafe_blocks",
"clippy::unwrap_used", "clippy::unwrap_used",
"clippy::wildcard_imports", # we do this a lot "clippy::useless_let_if_seq", # False positives
"clippy::wildcard_imports", # We do this a lot
"trivial_casts", "trivial_casts",
"unused_qualifications", "unused_qualifications",
] ]

View File

@ -10,7 +10,7 @@ impl From<Alpha<EncodedSrgb<u8>>> for Color32 {
alpha: a, alpha: a,
} = srgba; } = srgba;
Color32::from_rgba_unmultiplied(r, g, b, a) Self::from_rgba_unmultiplied(r, g, b, a)
} }
} }
@ -23,7 +23,7 @@ impl From<PremultipliedAlpha<EncodedSrgb<u8>>> for Color32 {
alpha: a, alpha: a,
} = srgba; } = srgba;
Color32::from_rgba_premultiplied(r, g, b, a) Self::from_rgba_premultiplied(r, g, b, a)
} }
} }
@ -31,7 +31,7 @@ impl From<Color32> for PremultipliedAlpha<EncodedSrgb<u8>> {
fn from(col: Color32) -> Self { fn from(col: Color32) -> Self {
let (r, g, b, a) = col.to_tuple(); let (r, g, b, a) = col.to_tuple();
PremultipliedAlpha { Self {
color: EncodedSrgb { r, g, b }, color: EncodedSrgb { r, g, b },
alpha: a, alpha: a,
} }
@ -51,7 +51,7 @@ impl From<PremultipliedAlpha<EncodedSrgb<f32>>> for Color32 {
let b = linear_u8_from_linear_f32(b); let b = linear_u8_from_linear_f32(b);
let a = linear_u8_from_linear_f32(a); let a = linear_u8_from_linear_f32(a);
Color32::from_rgba_premultiplied(r, g, b, a) Self::from_rgba_premultiplied(r, g, b, a)
} }
} }
@ -65,7 +65,7 @@ impl From<Color32> for PremultipliedAlpha<EncodedSrgb<f32>> {
let b = linear_f32_from_linear_u8(b); let b = linear_f32_from_linear_u8(b);
let a = linear_f32_from_linear_u8(a); let a = linear_f32_from_linear_u8(a);
PremultipliedAlpha { Self {
color: EncodedSrgb { r, g, b }, color: EncodedSrgb { r, g, b },
alpha: a, alpha: a,
} }
@ -85,7 +85,7 @@ impl From<PremultipliedAlpha<LinearSrgb<f32>>> for Rgba {
alpha: a, alpha: a,
} = srgba; } = srgba;
Rgba([r, g, b, a]) Self([r, g, b, a])
} }
} }
@ -93,7 +93,7 @@ impl From<Rgba> for PremultipliedAlpha<LinearSrgb<f32>> {
fn from(col: Rgba) -> Self { fn from(col: Rgba) -> Self {
let (r, g, b, a) = col.to_tuple(); let (r, g, b, a) = col.to_tuple();
PremultipliedAlpha { Self {
color: LinearSrgb { r, g, b }, color: LinearSrgb { r, g, b },
alpha: a, alpha: a,
} }
@ -113,7 +113,7 @@ impl From<Alpha<Hsv<f32>>> for Hsva {
alpha: a, alpha: a,
} = srgba; } = srgba;
Hsva::new(h, s, v, a) Self::new(h, s, v, a)
} }
} }
@ -121,7 +121,7 @@ impl From<Hsva> for Alpha<Hsv<f32>> {
fn from(col: Hsva) -> Self { fn from(col: Hsva) -> Self {
let Hsva { h, s, v, a } = col; let Hsva { h, s, v, a } = col;
Alpha { Self {
color: Hsv { h, s, v }, color: Hsv { h, s, v },
alpha: a, alpha: a,
} }
@ -153,7 +153,7 @@ impl From<HsvaGamma> for Alpha<Hsv<f32>> {
fn from(col: HsvaGamma) -> Self { fn from(col: HsvaGamma) -> Self {
let Hsva { h, s, v, a } = col.into(); let Hsva { h, s, v, a } = col.into();
Alpha { Self {
color: Hsv { h, s, v }, color: Hsv { h, s, v },
alpha: a, alpha: a,
} }

View File

@ -34,33 +34,33 @@ impl std::ops::IndexMut<usize> for Color32 {
impl Color32 { impl Color32 {
// Mostly follows CSS names: // Mostly follows CSS names:
pub const TRANSPARENT: Color32 = Color32::from_rgba_premultiplied(0, 0, 0, 0); pub const TRANSPARENT: Self = Self::from_rgba_premultiplied(0, 0, 0, 0);
pub const BLACK: Color32 = Color32::from_rgb(0, 0, 0); pub const BLACK: Self = Self::from_rgb(0, 0, 0);
pub const DARK_GRAY: Color32 = Color32::from_rgb(96, 96, 96); pub const DARK_GRAY: Self = Self::from_rgb(96, 96, 96);
pub const GRAY: Color32 = Color32::from_rgb(160, 160, 160); pub const GRAY: Self = Self::from_rgb(160, 160, 160);
pub const LIGHT_GRAY: Color32 = Color32::from_rgb(220, 220, 220); pub const LIGHT_GRAY: Self = Self::from_rgb(220, 220, 220);
pub const WHITE: Color32 = Color32::from_rgb(255, 255, 255); pub const WHITE: Self = Self::from_rgb(255, 255, 255);
pub const BROWN: Color32 = Color32::from_rgb(165, 42, 42); pub const BROWN: Self = Self::from_rgb(165, 42, 42);
pub const DARK_RED: Color32 = Color32::from_rgb(0x8B, 0, 0); pub const DARK_RED: Self = Self::from_rgb(0x8B, 0, 0);
pub const RED: Color32 = Color32::from_rgb(255, 0, 0); pub const RED: Self = Self::from_rgb(255, 0, 0);
pub const LIGHT_RED: Color32 = Color32::from_rgb(255, 128, 128); pub const LIGHT_RED: Self = Self::from_rgb(255, 128, 128);
pub const YELLOW: Color32 = Color32::from_rgb(255, 255, 0); pub const YELLOW: Self = Self::from_rgb(255, 255, 0);
pub const LIGHT_YELLOW: Color32 = Color32::from_rgb(255, 255, 0xE0); pub const LIGHT_YELLOW: Self = Self::from_rgb(255, 255, 0xE0);
pub const KHAKI: Color32 = Color32::from_rgb(240, 230, 140); pub const KHAKI: Self = Self::from_rgb(240, 230, 140);
pub const DARK_GREEN: Color32 = Color32::from_rgb(0, 0x64, 0); pub const DARK_GREEN: Self = Self::from_rgb(0, 0x64, 0);
pub const GREEN: Color32 = Color32::from_rgb(0, 255, 0); pub const GREEN: Self = Self::from_rgb(0, 255, 0);
pub const LIGHT_GREEN: Color32 = Color32::from_rgb(0x90, 0xEE, 0x90); pub const LIGHT_GREEN: Self = Self::from_rgb(0x90, 0xEE, 0x90);
pub const DARK_BLUE: Color32 = Color32::from_rgb(0, 0, 0x8B); pub const DARK_BLUE: Self = Self::from_rgb(0, 0, 0x8B);
pub const BLUE: Color32 = Color32::from_rgb(0, 0, 255); pub const BLUE: Self = Self::from_rgb(0, 0, 255);
pub const LIGHT_BLUE: Color32 = Color32::from_rgb(0xAD, 0xD8, 0xE6); pub const LIGHT_BLUE: Self = Self::from_rgb(0xAD, 0xD8, 0xE6);
pub const GOLD: Color32 = Color32::from_rgb(255, 215, 0); pub const GOLD: Self = Self::from_rgb(255, 215, 0);
pub const DEBUG_COLOR: Color32 = Color32::from_rgba_premultiplied(0, 200, 0, 128); pub const DEBUG_COLOR: Self = Self::from_rgba_premultiplied(0, 200, 0, 128);
/// An ugly color that is planned to be replaced before making it to the screen. /// An ugly color that is planned to be replaced before making it to the screen.
/// ///
@ -69,10 +69,10 @@ impl Color32 {
/// ///
/// This is used as a special color key, /// This is used as a special color key,
/// i.e. often taken to mean "no color". /// i.e. often taken to mean "no color".
pub const PLACEHOLDER: Color32 = Color32::from_rgba_premultiplied(64, 254, 0, 128); pub const PLACEHOLDER: Self = Self::from_rgba_premultiplied(64, 254, 0, 128);
#[deprecated = "Renamed to PLACEHOLDER"] #[deprecated = "Renamed to PLACEHOLDER"]
pub const TEMPORARY_COLOR: Color32 = Self::PLACEHOLDER; pub const TEMPORARY_COLOR: Self = Self::PLACEHOLDER;
#[inline] #[inline]
pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self { pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
@ -198,7 +198,7 @@ impl Color32 {
/// ///
/// This is perceptually even, and faster that [`Self::linear_multiply`]. /// This is perceptually even, and faster that [`Self::linear_multiply`].
#[inline] #[inline]
pub fn gamma_multiply(self, factor: f32) -> Color32 { pub fn gamma_multiply(self, factor: f32) -> Self {
crate::ecolor_assert!(0.0 <= factor && factor <= 1.0); crate::ecolor_assert!(0.0 <= factor && factor <= 1.0);
let Self([r, g, b, a]) = self; let Self([r, g, b, a]) = self;
Self([ Self([
@ -214,7 +214,7 @@ impl Color32 {
/// This is using linear space, which is not perceptually even. /// This is using linear space, which is not perceptually even.
/// You may want to use [`Self::gamma_multiply`] instead. /// You may want to use [`Self::gamma_multiply`] instead.
#[inline] #[inline]
pub fn linear_multiply(self, factor: f32) -> Color32 { pub fn linear_multiply(self, factor: f32) -> Self {
crate::ecolor_assert!(0.0 <= factor && factor <= 1.0); crate::ecolor_assert!(0.0 <= factor && factor <= 1.0);
// As an unfortunate side-effect of using premultiplied alpha // As an unfortunate side-effect of using premultiplied alpha
// we need a somewhat expensive conversion to linear space and back. // we need a somewhat expensive conversion to linear space and back.

View File

@ -47,20 +47,20 @@ impl FromStr for HexColor {
impl Display for HexColor { impl Display for HexColor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
HexColor::Hex3(color) => { Self::Hex3(color) => {
let [r, g, b, _] = color.to_srgba_unmultiplied().map(|u| u >> 4); let [r, g, b, _] = color.to_srgba_unmultiplied().map(|u| u >> 4);
f.write_fmt(format_args!("#{r:x}{g:x}{b:x}")) f.write_fmt(format_args!("#{r:x}{g:x}{b:x}"))
} }
HexColor::Hex4(color) => { Self::Hex4(color) => {
let [r, g, b, a] = color.to_srgba_unmultiplied().map(|u| u >> 4); let [r, g, b, a] = color.to_srgba_unmultiplied().map(|u| u >> 4);
f.write_fmt(format_args!("#{r:x}{g:x}{b:x}{a:x}")) f.write_fmt(format_args!("#{r:x}{g:x}{b:x}{a:x}"))
} }
HexColor::Hex6(color) => { Self::Hex6(color) => {
let [r, g, b, _] = color.to_srgba_unmultiplied(); let [r, g, b, _] = color.to_srgba_unmultiplied();
let u = u32::from_be_bytes([0, r, g, b]); let u = u32::from_be_bytes([0, r, g, b]);
f.write_fmt(format_args!("#{u:06x}")) f.write_fmt(format_args!("#{u:06x}"))
} }
HexColor::Hex8(color) => { Self::Hex8(color) => {
let [r, g, b, a] = color.to_srgba_unmultiplied(); let [r, g, b, a] = color.to_srgba_unmultiplied();
let u = u32::from_be_bytes([r, g, b, a]); let u = u32::from_be_bytes([r, g, b, a]);
f.write_fmt(format_args!("#{u:08x}")) f.write_fmt(format_args!("#{u:08x}"))
@ -74,10 +74,7 @@ impl HexColor {
#[inline] #[inline]
pub fn color(&self) -> Color32 { pub fn color(&self) -> Color32 {
match self { match self {
HexColor::Hex3(color) Self::Hex3(color) | Self::Hex4(color) | Self::Hex6(color) | Self::Hex8(color) => *color,
| HexColor::Hex4(color)
| HexColor::Hex6(color)
| HexColor::Hex8(color) => *color,
} }
} }
@ -94,26 +91,26 @@ impl HexColor {
.map_err(ParseHexColorError::InvalidInt)? .map_err(ParseHexColorError::InvalidInt)?
.to_be_bytes(); .to_be_bytes();
let [r, g, b] = [r, gb >> 4, gb & 0x0f].map(|u| u << 4 | u); let [r, g, b] = [r, gb >> 4, gb & 0x0f].map(|u| u << 4 | u);
Ok(HexColor::Hex3(Color32::from_rgb(r, g, b))) Ok(Self::Hex3(Color32::from_rgb(r, g, b)))
} }
4 => { 4 => {
let [r_g, b_a] = u16::from_str_radix(s, 16) let [r_g, b_a] = u16::from_str_radix(s, 16)
.map_err(ParseHexColorError::InvalidInt)? .map_err(ParseHexColorError::InvalidInt)?
.to_be_bytes(); .to_be_bytes();
let [r, g, b, a] = [r_g >> 4, r_g & 0x0f, b_a >> 4, b_a & 0x0f].map(|u| u << 4 | u); let [r, g, b, a] = [r_g >> 4, r_g & 0x0f, b_a >> 4, b_a & 0x0f].map(|u| u << 4 | u);
Ok(HexColor::Hex4(Color32::from_rgba_unmultiplied(r, g, b, a))) Ok(Self::Hex4(Color32::from_rgba_unmultiplied(r, g, b, a)))
} }
6 => { 6 => {
let [_, r, g, b] = u32::from_str_radix(s, 16) let [_, r, g, b] = u32::from_str_radix(s, 16)
.map_err(ParseHexColorError::InvalidInt)? .map_err(ParseHexColorError::InvalidInt)?
.to_be_bytes(); .to_be_bytes();
Ok(HexColor::Hex6(Color32::from_rgb(r, g, b))) Ok(Self::Hex6(Color32::from_rgb(r, g, b)))
} }
8 => { 8 => {
let [r, g, b, a] = u32::from_str_radix(s, 16) let [r, g, b, a] = u32::from_str_radix(s, 16)
.map_err(ParseHexColorError::InvalidInt)? .map_err(ParseHexColorError::InvalidInt)?
.to_be_bytes(); .to_be_bytes();
Ok(HexColor::Hex8(Color32::from_rgba_unmultiplied(r, g, b, a))) Ok(Self::Hex8(Color32::from_rgba_unmultiplied(r, g, b, a)))
} }
_ => Err(ParseHexColorError::InvalidLength)?, _ => Err(ParseHexColorError::InvalidLength)?,
} }

View File

@ -54,13 +54,13 @@ impl Hsva {
#![allow(clippy::many_single_char_names)] #![allow(clippy::many_single_char_names)]
if a == 0.0 { if a == 0.0 {
if r == 0.0 && b == 0.0 && a == 0.0 { if r == 0.0 && b == 0.0 && a == 0.0 {
Hsva::default() Self::default()
} else { } else {
Hsva::from_additive_rgb([r, g, b]) Self::from_additive_rgb([r, g, b])
} }
} else { } else {
let (h, s, v) = hsv_from_rgb([r / a, g / a, b / a]); let (h, s, v) = hsv_from_rgb([r / a, g / a, b / a]);
Hsva { h, s, v, a } Self { h, s, v, a }
} }
} }
@ -69,13 +69,13 @@ impl Hsva {
pub fn from_rgba_unmultiplied(r: f32, g: f32, b: f32, a: f32) -> Self { pub fn from_rgba_unmultiplied(r: f32, g: f32, b: f32, a: f32) -> Self {
#![allow(clippy::many_single_char_names)] #![allow(clippy::many_single_char_names)]
let (h, s, v) = hsv_from_rgb([r, g, b]); let (h, s, v) = hsv_from_rgb([r, g, b]);
Hsva { h, s, v, a } Self { h, s, v, a }
} }
#[inline] #[inline]
pub fn from_additive_rgb(rgb: [f32; 3]) -> Self { pub fn from_additive_rgb(rgb: [f32; 3]) -> Self {
let (h, s, v) = hsv_from_rgb(rgb); let (h, s, v) = hsv_from_rgb(rgb);
Hsva { Self {
h, h,
s, s,
v, v,
@ -95,7 +95,7 @@ impl Hsva {
#[inline] #[inline]
pub fn from_rgb(rgb: [f32; 3]) -> Self { pub fn from_rgb(rgb: [f32; 3]) -> Self {
let (h, s, v) = hsv_from_rgb(rgb); let (h, s, v) = hsv_from_rgb(rgb);
Hsva { h, s, v, a: 1.0 } Self { h, s, v, a: 1.0 }
} }
#[inline] #[inline]
@ -145,7 +145,7 @@ impl Hsva {
/// Represents additive colors using a negative alpha. /// Represents additive colors using a negative alpha.
#[inline] #[inline]
pub fn to_rgba_unmultiplied(&self) -> [f32; 4] { pub fn to_rgba_unmultiplied(&self) -> [f32; 4] {
let Hsva { h, s, v, a } = *self; let Self { h, s, v, a } = *self;
let [r, g, b] = rgb_from_hsv((h, s, v)); let [r, g, b] = rgb_from_hsv((h, s, v));
[r, g, b, a] [r, g, b, a]
} }
@ -176,29 +176,29 @@ impl Hsva {
impl From<Hsva> for Rgba { impl From<Hsva> for Rgba {
#[inline] #[inline]
fn from(hsva: Hsva) -> Rgba { fn from(hsva: Hsva) -> Self {
Rgba(hsva.to_rgba_premultiplied()) Self(hsva.to_rgba_premultiplied())
} }
} }
impl From<Rgba> for Hsva { impl From<Rgba> for Hsva {
#[inline] #[inline]
fn from(rgba: Rgba) -> Hsva { fn from(rgba: Rgba) -> Self {
Self::from_rgba_premultiplied(rgba.0[0], rgba.0[1], rgba.0[2], rgba.0[3]) Self::from_rgba_premultiplied(rgba.0[0], rgba.0[1], rgba.0[2], rgba.0[3])
} }
} }
impl From<Hsva> for Color32 { impl From<Hsva> for Color32 {
#[inline] #[inline]
fn from(hsva: Hsva) -> Color32 { fn from(hsva: Hsva) -> Self {
Color32::from(Rgba::from(hsva)) Self::from(Rgba::from(hsva))
} }
} }
impl From<Color32> for Hsva { impl From<Color32> for Hsva {
#[inline] #[inline]
fn from(srgba: Color32) -> Hsva { fn from(srgba: Color32) -> Self {
Hsva::from(Rgba::from(srgba)) Self::from(Rgba::from(srgba))
} }
} }

View File

@ -18,21 +18,21 @@ pub struct HsvaGamma {
} }
impl From<HsvaGamma> for Rgba { impl From<HsvaGamma> for Rgba {
fn from(hsvag: HsvaGamma) -> Rgba { fn from(hsvag: HsvaGamma) -> Self {
Hsva::from(hsvag).into() Hsva::from(hsvag).into()
} }
} }
impl From<HsvaGamma> for Color32 { impl From<HsvaGamma> for Color32 {
fn from(hsvag: HsvaGamma) -> Color32 { fn from(hsvag: HsvaGamma) -> Self {
Rgba::from(hsvag).into() Rgba::from(hsvag).into()
} }
} }
impl From<HsvaGamma> for Hsva { impl From<HsvaGamma> for Hsva {
fn from(hsvag: HsvaGamma) -> Hsva { fn from(hsvag: HsvaGamma) -> Self {
let HsvaGamma { h, s, v, a } = hsvag; let HsvaGamma { h, s, v, a } = hsvag;
Hsva { Self {
h, h,
s, s,
v: linear_from_gamma(v), v: linear_from_gamma(v),
@ -42,21 +42,21 @@ impl From<HsvaGamma> for Hsva {
} }
impl From<Rgba> for HsvaGamma { impl From<Rgba> for HsvaGamma {
fn from(rgba: Rgba) -> HsvaGamma { fn from(rgba: Rgba) -> Self {
Hsva::from(rgba).into() Hsva::from(rgba).into()
} }
} }
impl From<Color32> for HsvaGamma { impl From<Color32> for HsvaGamma {
fn from(srgba: Color32) -> HsvaGamma { fn from(srgba: Color32) -> Self {
Hsva::from(srgba).into() Hsva::from(srgba).into()
} }
} }
impl From<Hsva> for HsvaGamma { impl From<Hsva> for HsvaGamma {
fn from(hsva: Hsva) -> HsvaGamma { fn from(hsva: Hsva) -> Self {
let Hsva { h, s, v, a } = hsva; let Hsva { h, s, v, a } = hsva;
HsvaGamma { Self {
h, h,
s, s,
v: gamma_from_linear(v), v: gamma_from_linear(v),

View File

@ -35,8 +35,8 @@ pub use hex_color_runtime::*;
// Color conversion: // Color conversion:
impl From<Color32> for Rgba { impl From<Color32> for Rgba {
fn from(srgba: Color32) -> Rgba { fn from(srgba: Color32) -> Self {
Rgba([ Self([
linear_f32_from_gamma_u8(srgba.0[0]), linear_f32_from_gamma_u8(srgba.0[0]),
linear_f32_from_gamma_u8(srgba.0[1]), linear_f32_from_gamma_u8(srgba.0[1]),
linear_f32_from_gamma_u8(srgba.0[2]), linear_f32_from_gamma_u8(srgba.0[2]),
@ -46,8 +46,8 @@ impl From<Color32> for Rgba {
} }
impl From<Rgba> for Color32 { impl From<Rgba> for Color32 {
fn from(rgba: Rgba) -> Color32 { fn from(rgba: Rgba) -> Self {
Color32([ Self([
gamma_u8_from_linear_f32(rgba.0[0]), gamma_u8_from_linear_f32(rgba.0[0]),
gamma_u8_from_linear_f32(rgba.0[1]), gamma_u8_from_linear_f32(rgba.0[1]),
gamma_u8_from_linear_f32(rgba.0[2]), gamma_u8_from_linear_f32(rgba.0[2]),

View File

@ -50,12 +50,12 @@ impl std::hash::Hash for Rgba {
} }
impl Rgba { impl Rgba {
pub const TRANSPARENT: Rgba = Rgba::from_rgba_premultiplied(0.0, 0.0, 0.0, 0.0); pub const TRANSPARENT: Self = Self::from_rgba_premultiplied(0.0, 0.0, 0.0, 0.0);
pub const BLACK: Rgba = Rgba::from_rgb(0.0, 0.0, 0.0); pub const BLACK: Self = Self::from_rgb(0.0, 0.0, 0.0);
pub const WHITE: Rgba = Rgba::from_rgb(1.0, 1.0, 1.0); pub const WHITE: Self = Self::from_rgb(1.0, 1.0, 1.0);
pub const RED: Rgba = Rgba::from_rgb(1.0, 0.0, 0.0); pub const RED: Self = Self::from_rgb(1.0, 0.0, 0.0);
pub const GREEN: Rgba = Rgba::from_rgb(0.0, 1.0, 0.0); pub const GREEN: Self = Self::from_rgb(0.0, 1.0, 0.0);
pub const BLUE: Rgba = Rgba::from_rgb(0.0, 0.0, 1.0); pub const BLUE: Self = Self::from_rgb(0.0, 0.0, 1.0);
#[inline] #[inline]
pub const fn from_rgba_premultiplied(r: f32, g: f32, b: f32, a: f32) -> Self { pub const fn from_rgba_premultiplied(r: f32, g: f32, b: f32, a: f32) -> Self {
@ -220,11 +220,11 @@ impl Rgba {
} }
impl std::ops::Add for Rgba { impl std::ops::Add for Rgba {
type Output = Rgba; type Output = Self;
#[inline] #[inline]
fn add(self, rhs: Rgba) -> Rgba { fn add(self, rhs: Self) -> Self {
Rgba([ Self([
self[0] + rhs[0], self[0] + rhs[0],
self[1] + rhs[1], self[1] + rhs[1],
self[2] + rhs[2], self[2] + rhs[2],
@ -233,12 +233,12 @@ impl std::ops::Add for Rgba {
} }
} }
impl std::ops::Mul<Rgba> for Rgba { impl std::ops::Mul for Rgba {
type Output = Rgba; type Output = Self;
#[inline] #[inline]
fn mul(self, other: Rgba) -> Rgba { fn mul(self, other: Self) -> Self {
Rgba([ Self([
self[0] * other[0], self[0] * other[0],
self[1] * other[1], self[1] * other[1],
self[2] * other[2], self[2] * other[2],
@ -248,11 +248,11 @@ impl std::ops::Mul<Rgba> for Rgba {
} }
impl std::ops::Mul<f32> for Rgba { impl std::ops::Mul<f32> for Rgba {
type Output = Rgba; type Output = Self;
#[inline] #[inline]
fn mul(self, factor: f32) -> Rgba { fn mul(self, factor: f32) -> Self {
Rgba([ Self([
self[0] * factor, self[0] * factor,
self[1] * factor, self[1] * factor,
self[2] * factor, self[2] * factor,

View File

@ -962,7 +962,7 @@ impl GlutinWindowContext {
// help us start from scratch again if we fail context creation and go back to preferEgl or try with different config etc.. // help us start from scratch again if we fail context creation and go back to preferEgl or try with different config etc..
// https://github.com/emilk/egui/pull/2541#issuecomment-1370767582 // https://github.com/emilk/egui/pull/2541#issuecomment-1370767582
let mut slf = GlutinWindowContext { let mut slf = Self {
egui_ctx: egui_ctx.clone(), egui_ctx: egui_ctx.clone(),
swap_interval, swap_interval,
gl_config, gl_config,

View File

@ -492,7 +492,7 @@ impl WgpuWinitRunning {
#[cfg(feature = "puffin")] #[cfg(feature = "puffin")]
puffin::GlobalProfiler::lock().new_frame(); puffin::GlobalProfiler::lock().new_frame();
let WgpuWinitRunning { let Self {
app, app,
integration, integration,
shared, shared,

View File

@ -7,7 +7,7 @@ impl WebLogger {
/// Install a new `WebLogger`, piping all [`log`] events to the web console. /// Install a new `WebLogger`, piping all [`log`] events to the web console.
pub fn init(filter: log::LevelFilter) -> Result<(), log::SetLoggerError> { pub fn init(filter: log::LevelFilter) -> Result<(), log::SetLoggerError> {
log::set_max_level(filter); log::set_max_level(filter);
log::set_boxed_logger(Box::new(WebLogger::new(filter))) log::set_boxed_logger(Box::new(Self::new(filter)))
} }
/// Create a new [`WebLogger`] with the given filter, /// Create a new [`WebLogger`] with the given filter,

View File

@ -205,14 +205,14 @@ enum EventToUnsubscribe {
impl EventToUnsubscribe { impl EventToUnsubscribe {
pub fn unsubscribe(self) -> Result<(), JsValue> { pub fn unsubscribe(self) -> Result<(), JsValue> {
match self { match self {
EventToUnsubscribe::TargetEvent(handle) => { Self::TargetEvent(handle) => {
handle.target.remove_event_listener_with_callback( handle.target.remove_event_listener_with_callback(
handle.event_name.as_str(), handle.event_name.as_str(),
handle.closure.as_ref().unchecked_ref(), handle.closure.as_ref().unchecked_ref(),
)?; )?;
Ok(()) Ok(())
} }
EventToUnsubscribe::IntervalHandle(handle) => { Self::IntervalHandle(handle) => {
let window = web_sys::window().unwrap(); let window = web_sys::window().unwrap();
window.clear_interval_with_handle(handle.handle); window.clear_interval_with_handle(handle.handle);
Ok(()) Ok(())

View File

@ -141,7 +141,7 @@ impl RenderState {
let renderer = Renderer::new(&device, target_format, depth_format, msaa_samples); let renderer = Renderer::new(&device, target_format, depth_format, msaa_samples);
Ok(RenderState { Ok(Self {
adapter: Arc::new(adapter), adapter: Arc::new(adapter),
device: Arc::new(device), device: Arc::new(device),
queue: Arc::new(queue), queue: Arc::new(queue),

View File

@ -263,7 +263,7 @@ impl Area {
} }
pub(crate) fn begin(self, ctx: &Context) -> Prepared { pub(crate) fn begin(self, ctx: &Context) -> Prepared {
let Area { let Self {
id, id,
movable, movable,
order, order,
@ -458,7 +458,7 @@ impl Prepared {
#[allow(clippy::needless_pass_by_value)] // intentional to swallow up `content_ui`. #[allow(clippy::needless_pass_by_value)] // intentional to swallow up `content_ui`.
pub(crate) fn end(self, ctx: &Context, content_ui: Ui) -> Response { pub(crate) fn end(self, ctx: &Context, content_ui: Ui) -> Response {
let Prepared { let Self {
layer_id, layer_id,
mut state, mut state,
move_response, move_response,

View File

@ -45,7 +45,7 @@ impl CollapsingState {
} }
pub fn load_with_default_open(ctx: &Context, id: Id, default_open: bool) -> Self { pub fn load_with_default_open(ctx: &Context, id: Id, default_open: bool) -> Self {
Self::load(ctx, id).unwrap_or(CollapsingState { Self::load(ctx, id).unwrap_or(Self {
id, id,
state: InnerState { state: InnerState {
open: default_open, open: default_open,

View File

@ -256,7 +256,7 @@ impl Prepared {
pub fn end(self, ui: &mut Ui) -> Response { pub fn end(self, ui: &mut Ui) -> Response {
let paint_rect = self.paint_rect(); let paint_rect = self.paint_rect();
let Prepared { let Self {
frame, frame,
where_to_put_background, where_to_put_background,
.. ..

View File

@ -51,22 +51,22 @@ pub enum Side {
impl Side { impl Side {
fn opposite(self) -> Self { fn opposite(self) -> Self {
match self { match self {
Side::Left => Self::Right, Self::Left => Self::Right,
Side::Right => Self::Left, Self::Right => Self::Left,
} }
} }
fn set_rect_width(self, rect: &mut Rect, width: f32) { fn set_rect_width(self, rect: &mut Rect, width: f32) {
match self { match self {
Side::Left => rect.max.x = rect.min.x + width, Self::Left => rect.max.x = rect.min.x + width,
Side::Right => rect.min.x = rect.max.x - width, Self::Right => rect.min.x = rect.max.x - width,
} }
} }
fn side_x(self, rect: Rect) -> f32 { fn side_x(self, rect: Rect) -> f32 {
match self { match self {
Side::Left => rect.left(), Self::Left => rect.left(),
Side::Right => rect.right(), Self::Right => rect.right(),
} }
} }
} }
@ -506,22 +506,22 @@ pub enum TopBottomSide {
impl TopBottomSide { impl TopBottomSide {
fn opposite(self) -> Self { fn opposite(self) -> Self {
match self { match self {
TopBottomSide::Top => Self::Bottom, Self::Top => Self::Bottom,
TopBottomSide::Bottom => Self::Top, Self::Bottom => Self::Top,
} }
} }
fn set_rect_height(self, rect: &mut Rect, height: f32) { fn set_rect_height(self, rect: &mut Rect, height: f32) {
match self { match self {
TopBottomSide::Top => rect.max.y = rect.min.y + height, Self::Top => rect.max.y = rect.min.y + height,
TopBottomSide::Bottom => rect.min.y = rect.max.y - height, Self::Bottom => rect.min.y = rect.max.y - height,
} }
} }
fn side_y(self, rect: Rect) -> f32 { fn side_y(self, rect: Rect) -> f32 {
match self { match self {
TopBottomSide::Top => rect.top(), Self::Top => rect.top(),
TopBottomSide::Bottom => rect.bottom(), Self::Bottom => rect.bottom(),
} }
} }
} }

View File

@ -692,7 +692,7 @@ impl ScrollArea {
impl Prepared { impl Prepared {
/// Returns content size and state /// Returns content size and state
fn end(self, ui: &mut Ui) -> (Vec2, State) { fn end(self, ui: &mut Ui) -> (Vec2, State) {
let Prepared { let Self {
id, id,
mut state, mut state,
inner_rect, inner_rect,

View File

@ -509,7 +509,7 @@ impl std::fmt::Debug for Context {
} }
impl std::cmp::PartialEq for Context { impl std::cmp::PartialEq for Context {
fn eq(&self, other: &Context) -> bool { fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0) Arc::ptr_eq(&self.0, &other.0)
} }
} }
@ -558,7 +558,7 @@ impl Context {
/// // handle full_output /// // handle full_output
/// ``` /// ```
#[must_use] #[must_use]
pub fn run(&self, new_input: RawInput, run_ui: impl FnOnce(&Context)) -> FullOutput { pub fn run(&self, new_input: RawInput, run_ui: impl FnOnce(&Self)) -> FullOutput {
crate::profile_function!(); crate::profile_function!();
self.begin_frame(new_input); self.begin_frame(new_input);
@ -2675,7 +2675,7 @@ impl Context {
/// * Handle the output from [`Context::run`], including rendering /// * Handle the output from [`Context::run`], including rendering
#[allow(clippy::unused_self)] #[allow(clippy::unused_self)]
pub fn set_immediate_viewport_renderer( pub fn set_immediate_viewport_renderer(
callback: impl for<'a> Fn(&Context, ImmediateViewport<'a>) + 'static, callback: impl for<'a> Fn(&Self, ImmediateViewport<'a>) + 'static,
) { ) {
let callback = Box::new(callback); let callback = Box::new(callback);
IMMEDIATE_VIEWPORT_RENDERER.with(|render_sync| { IMMEDIATE_VIEWPORT_RENDERER.with(|render_sync| {
@ -2752,7 +2752,7 @@ impl Context {
&self, &self,
new_viewport_id: ViewportId, new_viewport_id: ViewportId,
viewport_builder: ViewportBuilder, viewport_builder: ViewportBuilder,
viewport_ui_cb: impl Fn(&Context, ViewportClass) + Send + Sync + 'static, viewport_ui_cb: impl Fn(&Self, ViewportClass) + Send + Sync + 'static,
) { ) {
crate::profile_function!(); crate::profile_function!();
@ -2804,7 +2804,7 @@ impl Context {
&self, &self,
new_viewport_id: ViewportId, new_viewport_id: ViewportId,
builder: ViewportBuilder, builder: ViewportBuilder,
viewport_ui_cb: impl FnOnce(&Context, ViewportClass) -> T, viewport_ui_cb: impl FnOnce(&Self, ViewportClass) -> T,
) -> T { ) -> T {
crate::profile_function!(); crate::profile_function!();

View File

@ -104,8 +104,8 @@ impl RawInput {
/// ///
/// * [`Self::hovered_files`] is cloned. /// * [`Self::hovered_files`] is cloned.
/// * [`Self::dropped_files`] is moved. /// * [`Self::dropped_files`] is moved.
pub fn take(&mut self) -> RawInput { pub fn take(&mut self) -> Self {
RawInput { Self {
viewport_id: self.viewport_id, viewport_id: self.viewport_id,
viewports: self.viewports.clone(), viewports: self.viewports.clone(),
screen_rect: self.screen_rect.take(), screen_rect: self.screen_rect.take(),
@ -692,7 +692,7 @@ impl Modifiers {
/// assert!((Modifiers::MAC_CMD | Modifiers::COMMAND).matches_logically(Modifiers::COMMAND)); /// assert!((Modifiers::MAC_CMD | Modifiers::COMMAND).matches_logically(Modifiers::COMMAND));
/// assert!(!Modifiers::COMMAND.matches_logically(Modifiers::MAC_CMD)); /// assert!(!Modifiers::COMMAND.matches_logically(Modifiers::MAC_CMD));
/// ``` /// ```
pub fn matches_logically(&self, pattern: Modifiers) -> bool { pub fn matches_logically(&self, pattern: Self) -> bool {
if pattern.alt && !self.alt { if pattern.alt && !self.alt {
return false; return false;
} }
@ -734,7 +734,7 @@ impl Modifiers {
/// assert!((Modifiers::MAC_CMD | Modifiers::COMMAND).matches(Modifiers::COMMAND)); /// assert!((Modifiers::MAC_CMD | Modifiers::COMMAND).matches(Modifiers::COMMAND));
/// assert!(!Modifiers::COMMAND.matches(Modifiers::MAC_CMD)); /// assert!(!Modifiers::COMMAND.matches(Modifiers::MAC_CMD));
/// ``` /// ```
pub fn matches_exact(&self, pattern: Modifiers) -> bool { pub fn matches_exact(&self, pattern: Self) -> bool {
// alt and shift must always match the pattern: // alt and shift must always match the pattern:
if pattern.alt != self.alt || pattern.shift != self.shift { if pattern.alt != self.alt || pattern.shift != self.shift {
return false; return false;
@ -744,7 +744,7 @@ impl Modifiers {
} }
#[deprecated = "Renamed `matches_exact`, but maybe you want to use `matches_logically` instead"] #[deprecated = "Renamed `matches_exact`, but maybe you want to use `matches_logically` instead"]
pub fn matches(&self, pattern: Modifiers) -> bool { pub fn matches(&self, pattern: Self) -> bool {
self.matches_exact(pattern) self.matches_exact(pattern)
} }
@ -755,7 +755,7 @@ impl Modifiers {
/// ///
/// This takes care to properly handle the difference between /// This takes care to properly handle the difference between
/// [`Self::ctrl`], [`Self::command`] and [`Self::mac_cmd`]. /// [`Self::ctrl`], [`Self::command`] and [`Self::mac_cmd`].
pub fn cmd_ctrl_matches(&self, pattern: Modifiers) -> bool { pub fn cmd_ctrl_matches(&self, pattern: Self) -> bool {
if pattern.mac_cmd { if pattern.mac_cmd {
// Mac-specific match: // Mac-specific match:
if !self.mac_cmd { if !self.mac_cmd {
@ -800,12 +800,12 @@ impl Modifiers {
/// assert!((Modifiers::CTRL | Modifiers::SHIFT).contains(Modifiers::CTRL)); /// assert!((Modifiers::CTRL | Modifiers::SHIFT).contains(Modifiers::CTRL));
/// assert!(!Modifiers::CTRL.contains(Modifiers::CTRL | Modifiers::SHIFT)); /// assert!(!Modifiers::CTRL.contains(Modifiers::CTRL | Modifiers::SHIFT));
/// ``` /// ```
pub fn contains(&self, query: Modifiers) -> bool { pub fn contains(&self, query: Self) -> bool {
if query == Modifiers::default() { if query == Self::default() {
return true; return true;
} }
let Modifiers { let Self {
alt, alt,
ctrl, ctrl,
shift, shift,
@ -814,27 +814,27 @@ impl Modifiers {
} = *self; } = *self;
if alt && query.alt { if alt && query.alt {
return self.contains(Modifiers { return self.contains(Self {
alt: false, alt: false,
..query ..query
}); });
} }
if shift && query.shift { if shift && query.shift {
return self.contains(Modifiers { return self.contains(Self {
shift: false, shift: false,
..query ..query
}); });
} }
if (ctrl || command) && (query.ctrl || query.command) { if (ctrl || command) && (query.ctrl || query.command) {
return self.contains(Modifiers { return self.contains(Self {
command: false, command: false,
ctrl: false, ctrl: false,
..query ..query
}); });
} }
if (mac_cmd || command) && (query.mac_cmd || query.command) { if (mac_cmd || command) && (query.mac_cmd || query.command) {
return self.contains(Modifiers { return self.contains(Self {
mac_cmd: false, mac_cmd: false,
command: false, command: false,
..query ..query
@ -1287,13 +1287,13 @@ impl Key {
// Before we do we must first make sure they are supported in `Fonts` though, // Before we do we must first make sure they are supported in `Fonts` though,
// so perhaps this functions needs to take a `supports_character: impl Fn(char) -> bool` or something. // so perhaps this functions needs to take a `supports_character: impl Fn(char) -> bool` or something.
match self { match self {
Key::ArrowDown => "", Self::ArrowDown => "",
Key::ArrowLeft => "", Self::ArrowLeft => "",
Key::ArrowRight => "", Self::ArrowRight => "",
Key::ArrowUp => "", Self::ArrowUp => "",
Key::Minus => crate::MINUS_CHAR_STR, Self::Minus => crate::MINUS_CHAR_STR,
Key::Plus => "+", Self::Plus => "+",
Key::Equals => "=", Self::Equals => "=",
_ => self.name(), _ => self.name(),
} }
} }
@ -1301,98 +1301,98 @@ impl Key {
/// Human-readable English name. /// Human-readable English name.
pub fn name(self) -> &'static str { pub fn name(self) -> &'static str {
match self { match self {
Key::ArrowDown => "Down", Self::ArrowDown => "Down",
Key::ArrowLeft => "Left", Self::ArrowLeft => "Left",
Key::ArrowRight => "Right", Self::ArrowRight => "Right",
Key::ArrowUp => "Up", Self::ArrowUp => "Up",
Key::Escape => "Escape", Self::Escape => "Escape",
Key::Tab => "Tab", Self::Tab => "Tab",
Key::Backspace => "Backspace", Self::Backspace => "Backspace",
Key::Enter => "Enter", Self::Enter => "Enter",
Key::Space => "Space", Self::Space => "Space",
Key::Insert => "Insert", Self::Insert => "Insert",
Key::Delete => "Delete", Self::Delete => "Delete",
Key::Home => "Home", Self::Home => "Home",
Key::End => "End", Self::End => "End",
Key::PageUp => "PageUp", Self::PageUp => "PageUp",
Key::PageDown => "PageDown", Self::PageDown => "PageDown",
Key::Copy => "Copy", Self::Copy => "Copy",
Key::Cut => "Cut", Self::Cut => "Cut",
Key::Paste => "Paste", Self::Paste => "Paste",
Key::Colon => "Colon", Self::Colon => "Colon",
Key::Comma => "Comma", Self::Comma => "Comma",
Key::Minus => "Minus", Self::Minus => "Minus",
Key::Period => "Period", Self::Period => "Period",
Key::Plus => "Plus", Self::Plus => "Plus",
Key::Equals => "Equals", Self::Equals => "Equals",
Key::Semicolon => "Semicolon", Self::Semicolon => "Semicolon",
Key::Backslash => "Backslash", Self::Backslash => "Backslash",
Key::OpenBracket => "OpenBracket", Self::OpenBracket => "OpenBracket",
Key::CloseBracket => "CloseBracket", Self::CloseBracket => "CloseBracket",
Key::Backtick => "Backtick", Self::Backtick => "Backtick",
Key::Num0 => "0", Self::Num0 => "0",
Key::Num1 => "1", Self::Num1 => "1",
Key::Num2 => "2", Self::Num2 => "2",
Key::Num3 => "3", Self::Num3 => "3",
Key::Num4 => "4", Self::Num4 => "4",
Key::Num5 => "5", Self::Num5 => "5",
Key::Num6 => "6", Self::Num6 => "6",
Key::Num7 => "7", Self::Num7 => "7",
Key::Num8 => "8", Self::Num8 => "8",
Key::Num9 => "9", Self::Num9 => "9",
Key::A => "A", Self::A => "A",
Key::B => "B", Self::B => "B",
Key::C => "C", Self::C => "C",
Key::D => "D", Self::D => "D",
Key::E => "E", Self::E => "E",
Key::F => "F", Self::F => "F",
Key::G => "G", Self::G => "G",
Key::H => "H", Self::H => "H",
Key::I => "I", Self::I => "I",
Key::J => "J", Self::J => "J",
Key::K => "K", Self::K => "K",
Key::L => "L", Self::L => "L",
Key::M => "M", Self::M => "M",
Key::N => "N", Self::N => "N",
Key::O => "O", Self::O => "O",
Key::P => "P", Self::P => "P",
Key::Q => "Q", Self::Q => "Q",
Key::R => "R", Self::R => "R",
Key::S => "S", Self::S => "S",
Key::T => "T", Self::T => "T",
Key::U => "U", Self::U => "U",
Key::V => "V", Self::V => "V",
Key::W => "W", Self::W => "W",
Key::X => "X", Self::X => "X",
Key::Y => "Y", Self::Y => "Y",
Key::Z => "Z", Self::Z => "Z",
Key::F1 => "F1", Self::F1 => "F1",
Key::F2 => "F2", Self::F2 => "F2",
Key::F3 => "F3", Self::F3 => "F3",
Key::F4 => "F4", Self::F4 => "F4",
Key::F5 => "F5", Self::F5 => "F5",
Key::F6 => "F6", Self::F6 => "F6",
Key::F7 => "F7", Self::F7 => "F7",
Key::F8 => "F8", Self::F8 => "F8",
Key::F9 => "F9", Self::F9 => "F9",
Key::F10 => "F10", Self::F10 => "F10",
Key::F11 => "F11", Self::F11 => "F11",
Key::F12 => "F12", Self::F12 => "F12",
Key::F13 => "F13", Self::F13 => "F13",
Key::F14 => "F14", Self::F14 => "F14",
Key::F15 => "F15", Self::F15 => "F15",
Key::F16 => "F16", Self::F16 => "F16",
Key::F17 => "F17", Self::F17 => "F17",
Key::F18 => "F18", Self::F18 => "F18",
Key::F19 => "F19", Self::F19 => "F19",
Key::F20 => "F20", Self::F20 => "F20",
} }
} }
} }

View File

@ -363,42 +363,42 @@ pub enum CursorIcon {
} }
impl CursorIcon { impl CursorIcon {
pub const ALL: [CursorIcon; 35] = [ pub const ALL: [Self; 35] = [
CursorIcon::Default, Self::Default,
CursorIcon::None, Self::None,
CursorIcon::ContextMenu, Self::ContextMenu,
CursorIcon::Help, Self::Help,
CursorIcon::PointingHand, Self::PointingHand,
CursorIcon::Progress, Self::Progress,
CursorIcon::Wait, Self::Wait,
CursorIcon::Cell, Self::Cell,
CursorIcon::Crosshair, Self::Crosshair,
CursorIcon::Text, Self::Text,
CursorIcon::VerticalText, Self::VerticalText,
CursorIcon::Alias, Self::Alias,
CursorIcon::Copy, Self::Copy,
CursorIcon::Move, Self::Move,
CursorIcon::NoDrop, Self::NoDrop,
CursorIcon::NotAllowed, Self::NotAllowed,
CursorIcon::Grab, Self::Grab,
CursorIcon::Grabbing, Self::Grabbing,
CursorIcon::AllScroll, Self::AllScroll,
CursorIcon::ResizeHorizontal, Self::ResizeHorizontal,
CursorIcon::ResizeNeSw, Self::ResizeNeSw,
CursorIcon::ResizeNwSe, Self::ResizeNwSe,
CursorIcon::ResizeVertical, Self::ResizeVertical,
CursorIcon::ResizeEast, Self::ResizeEast,
CursorIcon::ResizeSouthEast, Self::ResizeSouthEast,
CursorIcon::ResizeSouth, Self::ResizeSouth,
CursorIcon::ResizeSouthWest, Self::ResizeSouthWest,
CursorIcon::ResizeWest, Self::ResizeWest,
CursorIcon::ResizeNorthWest, Self::ResizeNorthWest,
CursorIcon::ResizeNorth, Self::ResizeNorth,
CursorIcon::ResizeNorthEast, Self::ResizeNorthEast,
CursorIcon::ResizeColumn, Self::ResizeColumn,
CursorIcon::ResizeRow, Self::ResizeRow,
CursorIcon::ZoomIn, Self::ZoomIn,
CursorIcon::ZoomOut, Self::ZoomOut,
]; ];
} }
@ -436,12 +436,12 @@ pub enum OutputEvent {
impl OutputEvent { impl OutputEvent {
pub fn widget_info(&self) -> &WidgetInfo { pub fn widget_info(&self) -> &WidgetInfo {
match self { match self {
OutputEvent::Clicked(info) Self::Clicked(info)
| OutputEvent::DoubleClicked(info) | Self::DoubleClicked(info)
| OutputEvent::TripleClicked(info) | Self::TripleClicked(info)
| OutputEvent::FocusGained(info) | Self::FocusGained(info)
| OutputEvent::TextSelectionChanged(info) | Self::TextSelectionChanged(info)
| OutputEvent::ValueChanged(info) => info, | Self::ValueChanged(info) => info,
} }
} }
} }

View File

@ -42,17 +42,17 @@ impl Id {
} }
/// Generate a new [`Id`] by hashing some source (e.g. a string or integer). /// Generate a new [`Id`] by hashing some source (e.g. a string or integer).
pub fn new(source: impl std::hash::Hash) -> Id { pub fn new(source: impl std::hash::Hash) -> Self {
Id(epaint::ahash::RandomState::with_seeds(1, 2, 3, 4).hash_one(source)) Self(epaint::ahash::RandomState::with_seeds(1, 2, 3, 4).hash_one(source))
} }
/// Generate a new [`Id`] by hashing the parent [`Id`] and the given argument. /// Generate a new [`Id`] by hashing the parent [`Id`] and the given argument.
pub fn with(self, child: impl std::hash::Hash) -> Id { pub fn with(self, child: impl std::hash::Hash) -> Self {
use std::hash::{BuildHasher, Hasher}; use std::hash::{BuildHasher, Hasher};
let mut hasher = epaint::ahash::RandomState::with_seeds(1, 2, 3, 4).build_hasher(); let mut hasher = epaint::ahash::RandomState::with_seeds(1, 2, 3, 4).build_hasher();
hasher.write_u64(self.0); hasher.write_u64(self.0);
child.hash(&mut hasher); child.hash(&mut hasher);
Id(hasher.finish()) Self(hasher.finish())
} }
/// Short and readable summary /// Short and readable summary

View File

@ -149,7 +149,7 @@ impl InputState {
mut new: RawInput, mut new: RawInput,
requested_repaint_last_frame: bool, requested_repaint_last_frame: bool,
pixels_per_point: f32, pixels_per_point: f32,
) -> InputState { ) -> Self {
crate::profile_function!(); crate::profile_function!();
let time = new.time.unwrap_or(self.time + new.predicted_dt as f64); let time = new.time.unwrap_or(self.time + new.predicted_dt as f64);
@ -212,7 +212,7 @@ impl InputState {
keys_down = Default::default(); keys_down = Default::default();
} }
InputState { Self {
pointer, pointer,
touch_states: self.touch_states, touch_states: self.touch_states,
scroll_delta, scroll_delta,
@ -538,15 +538,15 @@ pub(crate) enum PointerEvent {
impl PointerEvent { impl PointerEvent {
pub fn is_press(&self) -> bool { pub fn is_press(&self) -> bool {
matches!(self, PointerEvent::Pressed { .. }) matches!(self, Self::Pressed { .. })
} }
pub fn is_release(&self) -> bool { pub fn is_release(&self) -> bool {
matches!(self, PointerEvent::Released { .. }) matches!(self, Self::Released { .. })
} }
pub fn is_click(&self) -> bool { pub fn is_click(&self) -> bool {
matches!(self, PointerEvent::Released { click: Some(_), .. }) matches!(self, Self::Released { click: Some(_), .. })
} }
} }
@ -634,7 +634,7 @@ impl Default for PointerState {
impl PointerState { impl PointerState {
#[must_use] #[must_use]
pub(crate) fn begin_frame(mut self, time: f64, new: &RawInput) -> PointerState { pub(crate) fn begin_frame(mut self, time: f64, new: &RawInput) -> Self {
self.time = time; self.time = time;
self.pointer_events.clear(); self.pointer_events.clear();

View File

@ -31,7 +31,7 @@ pub enum Order {
impl Order { impl Order {
const COUNT: usize = 6; const COUNT: usize = 6;
const ALL: [Order; Self::COUNT] = [ const ALL: [Self; Self::COUNT] = [
Self::Background, Self::Background,
Self::PanelResizeLine, Self::PanelResizeLine,
Self::Middle, Self::Middle,

View File

@ -88,16 +88,16 @@ impl Direction {
#[inline(always)] #[inline(always)]
pub fn is_horizontal(self) -> bool { pub fn is_horizontal(self) -> bool {
match self { match self {
Direction::LeftToRight | Direction::RightToLeft => true, Self::LeftToRight | Self::RightToLeft => true,
Direction::TopDown | Direction::BottomUp => false, Self::TopDown | Self::BottomUp => false,
} }
} }
#[inline(always)] #[inline(always)]
pub fn is_vertical(self) -> bool { pub fn is_vertical(self) -> bool {
match self { match self {
Direction::LeftToRight | Direction::RightToLeft => false, Self::LeftToRight | Self::RightToLeft => false,
Direction::TopDown | Direction::BottomUp => true, Self::TopDown | Self::BottomUp => true,
} }
} }
} }

View File

@ -177,28 +177,28 @@ impl Debug for Bytes {
impl From<&'static [u8]> for Bytes { impl From<&'static [u8]> for Bytes {
#[inline] #[inline]
fn from(value: &'static [u8]) -> Self { fn from(value: &'static [u8]) -> Self {
Bytes::Static(value) Self::Static(value)
} }
} }
impl<const N: usize> From<&'static [u8; N]> for Bytes { impl<const N: usize> From<&'static [u8; N]> for Bytes {
#[inline] #[inline]
fn from(value: &'static [u8; N]) -> Self { fn from(value: &'static [u8; N]) -> Self {
Bytes::Static(value) Self::Static(value)
} }
} }
impl From<Arc<[u8]>> for Bytes { impl From<Arc<[u8]>> for Bytes {
#[inline] #[inline]
fn from(value: Arc<[u8]>) -> Self { fn from(value: Arc<[u8]>) -> Self {
Bytes::Shared(value) Self::Shared(value)
} }
} }
impl From<Vec<u8>> for Bytes { impl From<Vec<u8>> for Bytes {
#[inline] #[inline]
fn from(value: Vec<u8>) -> Self { fn from(value: Vec<u8>) -> Self {
Bytes::Shared(value.into()) Self::Shared(value.into())
} }
} }
@ -206,8 +206,8 @@ impl AsRef<[u8]> for Bytes {
#[inline] #[inline]
fn as_ref(&self) -> &[u8] { fn as_ref(&self) -> &[u8] {
match self { match self {
Bytes::Static(bytes) => bytes, Self::Static(bytes) => bytes,
Bytes::Shared(bytes) => bytes, Self::Shared(bytes) => bytes,
} }
} }
} }
@ -439,16 +439,16 @@ impl TexturePoll {
#[inline] #[inline]
pub fn size(&self) -> Option<Vec2> { pub fn size(&self) -> Option<Vec2> {
match self { match self {
TexturePoll::Pending { size } => *size, Self::Pending { size } => *size,
TexturePoll::Ready { texture } => Some(texture.size), Self::Ready { texture } => Some(texture.size),
} }
} }
#[inline] #[inline]
pub fn texture_id(&self) -> Option<TextureId> { pub fn texture_id(&self) -> Option<TextureId> {
match self { match self {
TexturePoll::Pending { .. } => None, Self::Pending { .. } => None,
TexturePoll::Ready { texture } => Some(texture.id), Self::Ready { texture } => Some(texture.id),
} }
} }
} }

View File

@ -144,12 +144,9 @@ enum FocusDirection {
impl FocusDirection { impl FocusDirection {
fn is_cardinal(&self) -> bool { fn is_cardinal(&self) -> bool {
match self { match self {
FocusDirection::Up Self::Up | Self::Right | Self::Down | Self::Left => true,
| FocusDirection::Right
| FocusDirection::Down
| FocusDirection::Left => true,
FocusDirection::Previous | FocusDirection::Next | FocusDirection::None => false, Self::Previous | Self::Next | Self::None => false,
} }
} }
} }

View File

@ -359,11 +359,7 @@ impl MenuRoot {
} }
/// Interaction with a context menu (secondary clicks). /// Interaction with a context menu (secondary clicks).
fn context_interaction( fn context_interaction(response: &Response, root: &mut Option<Self>, id: Id) -> MenuResponse {
response: &Response,
root: &mut Option<MenuRoot>,
id: Id,
) -> MenuResponse {
let response = response.interact(Sense::click()); let response = response.interact(Sense::click());
response.ctx.input(|input| { response.ctx.input(|input| {
let pointer = &input.pointer; let pointer = &input.pointer;
@ -389,7 +385,7 @@ impl MenuRoot {
fn handle_menu_response(root: &mut MenuRootManager, menu_response: MenuResponse) { fn handle_menu_response(root: &mut MenuRootManager, menu_response: MenuResponse) {
match menu_response { match menu_response {
MenuResponse::Create(pos, id) => { MenuResponse::Create(pos, id) => {
root.inner = Some(MenuRoot::new(pos, id)); root.inner = Some(Self::new(pos, id));
} }
MenuResponse::Close => root.inner = None, MenuResponse::Close => root.inner = None,
MenuResponse::Stay => {} MenuResponse::Stay => {}
@ -458,7 +454,7 @@ impl SubMenuButton {
} }
pub(crate) fn show(self, ui: &mut Ui, menu_state: &MenuState, sub_id: Id) -> Response { pub(crate) fn show(self, ui: &mut Ui, menu_state: &MenuState, sub_id: Id) -> Response {
let SubMenuButton { text, icon, .. } = self; let Self { text, icon, .. } = self;
let text_style = TextStyle::Button; let text_style = TextStyle::Button;
let sense = Sense::click(); let sense = Sense::click();
@ -655,11 +651,11 @@ impl MenuState {
self.sub_menu.as_ref().map(|(id, _)| *id) self.sub_menu.as_ref().map(|(id, _)| *id)
} }
fn current_submenu(&self) -> Option<&Arc<RwLock<MenuState>>> { fn current_submenu(&self) -> Option<&Arc<RwLock<Self>>> {
self.sub_menu.as_ref().map(|(_, sub)| sub) self.sub_menu.as_ref().map(|(_, sub)| sub)
} }
fn submenu(&mut self, id: Id) -> Option<&Arc<RwLock<MenuState>>> { fn submenu(&mut self, id: Id) -> Option<&Arc<RwLock<Self>>> {
self.sub_menu self.sub_menu
.as_ref() .as_ref()
.and_then(|(k, sub)| if id == *k { Some(sub) } else { None }) .and_then(|(k, sub)| if id == *k { Some(sub) } else { None })
@ -668,7 +664,7 @@ impl MenuState {
/// Open submenu at position, if not already open. /// Open submenu at position, if not already open.
fn open_submenu(&mut self, id: Id, pos: Pos2) { fn open_submenu(&mut self, id: Id, pos: Pos2) {
if !self.is_open(id) { if !self.is_open(id) {
self.sub_menu = Some((id, Arc::new(RwLock::new(MenuState::new(pos))))); self.sub_menu = Some((id, Arc::new(RwLock::new(Self::new(pos)))));
} }
} }
} }

View File

@ -1933,14 +1933,14 @@ impl HandleShape {
pub fn ui(&mut self, ui: &mut Ui) { pub fn ui(&mut self, ui: &mut Ui) {
ui.label("Widget handle shape"); ui.label("Widget handle shape");
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.radio_value(self, HandleShape::Circle, "Circle"); ui.radio_value(self, Self::Circle, "Circle");
if ui if ui
.radio(matches!(self, HandleShape::Rect { .. }), "Rectangle") .radio(matches!(self, Self::Rect { .. }), "Rectangle")
.clicked() .clicked()
{ {
*self = HandleShape::Rect { aspect_ratio: 0.5 }; *self = Self::Rect { aspect_ratio: 0.5 };
} }
if let HandleShape::Rect { aspect_ratio } = self { if let Self::Rect { aspect_ratio } = self {
ui.add(Slider::new(aspect_ratio, 0.1..=3.0).text("Aspect ratio")); ui.add(Slider::new(aspect_ratio, 0.1..=3.0).text("Aspect ratio"));
} }
}); });
@ -1983,8 +1983,8 @@ impl NumericColorSpace {
impl std::fmt::Display for NumericColorSpace { impl std::fmt::Display for NumericColorSpace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
NumericColorSpace::GammaByte => write!(f, "U8"), Self::GammaByte => write!(f, "U8"),
NumericColorSpace::Linear => write!(f, "F"), Self::Linear => write!(f, "F"),
} }
} }
} }

View File

@ -1,4 +1,5 @@
#![warn(missing_docs)] // Let's keep `Ui` well-documented. #![warn(missing_docs)] // Let's keep `Ui` well-documented.
#![allow(clippy::use_self)]
use std::hash::Hash; use std::hash::Hash;
use std::sync::Arc; use std::sync::Arc;

View File

@ -187,7 +187,7 @@ impl From<IconData> for epaint::ColorImage {
width, width,
height, height,
} = icon; } = icon;
epaint::ColorImage::from_rgba_premultiplied([width as usize, height as usize], &rgba) Self::from_rgba_premultiplied([width as usize, height as usize], &rgba)
} }
} }
@ -199,7 +199,7 @@ impl From<&IconData> for epaint::ColorImage {
width, width,
height, height,
} = icon; } = icon;
epaint::ColorImage::from_rgba_premultiplied([*width as usize, *height as usize], rgba) Self::from_rgba_premultiplied([*width as usize, *height as usize], rgba)
} }
} }
@ -569,8 +569,8 @@ impl ViewportBuilder {
/// Update this `ViewportBuilder` with a delta, /// Update this `ViewportBuilder` with a delta,
/// returning a list of commands and a bool intdicating if the window needs to be recreated. /// returning a list of commands and a bool intdicating if the window needs to be recreated.
#[must_use] #[must_use]
pub fn patch(&mut self, new_vp_builder: ViewportBuilder) -> (Vec<ViewportCommand>, bool) { pub fn patch(&mut self, new_vp_builder: Self) -> (Vec<ViewportCommand>, bool) {
let ViewportBuilder { let Self {
title: new_title, title: new_title,
app_id: new_app_id, app_id: new_app_id,
position: new_position, position: new_position,

View File

@ -42,28 +42,28 @@ pub struct RichText {
impl From<&str> for RichText { impl From<&str> for RichText {
#[inline] #[inline]
fn from(text: &str) -> Self { fn from(text: &str) -> Self {
RichText::new(text) Self::new(text)
} }
} }
impl From<&String> for RichText { impl From<&String> for RichText {
#[inline] #[inline]
fn from(text: &String) -> Self { fn from(text: &String) -> Self {
RichText::new(text) Self::new(text)
} }
} }
impl From<&mut String> for RichText { impl From<&mut String> for RichText {
#[inline] #[inline]
fn from(text: &mut String) -> Self { fn from(text: &mut String) -> Self {
RichText::new(text.clone()) Self::new(text.clone())
} }
} }
impl From<String> for RichText { impl From<String> for RichText {
#[inline] #[inline]
fn from(text: String) -> Self { fn from(text: String) -> Self {
RichText::new(text) Self::new(text)
} }
} }

View File

@ -512,7 +512,7 @@ impl RadioButton {
impl Widget for RadioButton { impl Widget for RadioButton {
fn ui(self, ui: &mut Ui) -> Response { fn ui(self, ui: &mut Ui) -> Response {
let RadioButton { checked, text } = self; let Self { checked, text } = self;
let spacing = &ui.spacing(); let spacing = &ui.spacing();
let icon_width = spacing.icon_width; let icon_width = spacing.icon_width;

View File

@ -31,7 +31,7 @@ impl Link {
impl Widget for Link { impl Widget for Link {
fn ui(self, ui: &mut Ui) -> Response { fn ui(self, ui: &mut Ui) -> Response {
let Link { text } = self; let Self { text } = self;
let label = Label::new(text).sense(Sense::click()); let label = Label::new(text).sense(Sense::click());
let (pos, galley, response) = label.layout_in_ui(ui); let (pos, galley, response) = label.layout_in_ui(ui);

View File

@ -395,9 +395,9 @@ pub enum ImageFit {
impl ImageFit { impl ImageFit {
pub fn resolve(self, available_size: Vec2, image_size: Vec2) -> Vec2 { pub fn resolve(self, available_size: Vec2, image_size: Vec2) -> Vec2 {
match self { match self {
ImageFit::Original { scale } => image_size * scale, Self::Original { scale } => image_size * scale,
ImageFit::Fraction(fract) => available_size * fract, Self::Fraction(fract) => available_size * fract,
ImageFit::Exact(size) => size, Self::Exact(size) => size,
} }
} }
} }

View File

@ -95,7 +95,7 @@ impl ProgressBar {
impl Widget for ProgressBar { impl Widget for ProgressBar {
fn ui(self, ui: &mut Ui) -> Response { fn ui(self, ui: &mut Ui) -> Response {
let ProgressBar { let Self {
progress, progress,
desired_width, desired_width,
desired_height, desired_height,

View File

@ -87,7 +87,7 @@ impl Separator {
impl Widget for Separator { impl Widget for Separator {
fn ui(self, ui: &mut Ui) -> Response { fn ui(self, ui: &mut Ui) -> Response {
let Separator { let Self {
spacing, spacing,
grow, grow,
is_horizontal_line, is_horizontal_line,

View File

@ -27,9 +27,9 @@ enum ChosenFit {
impl ChosenFit { impl ChosenFit {
fn as_str(&self) -> &'static str { fn as_str(&self) -> &'static str {
match self { match self {
ChosenFit::ExactSize => "exact size", Self::ExactSize => "exact size",
ChosenFit::Fraction => "fraction", Self::Fraction => "fraction",
ChosenFit::OriginalSize => "original size", Self::OriginalSize => "original size",
} }
} }
} }

View File

@ -35,7 +35,7 @@ enum RunMode {
/// so there are no events to miss. /// so there are no events to miss.
impl Default for RunMode { impl Default for RunMode {
fn default() -> Self { fn default() -> Self {
RunMode::Reactive Self::Reactive
} }
} }
@ -242,7 +242,7 @@ struct EguiWindows {
impl Default for EguiWindows { impl Default for EguiWindows {
fn default() -> Self { fn default() -> Self {
EguiWindows::none() Self::none()
} }
} }

View File

@ -94,14 +94,14 @@ impl Anchor {
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
fn all() -> Vec<Self> { fn all() -> Vec<Self> {
vec![ vec![
Anchor::Demo, Self::Demo,
Anchor::EasyMarkEditor, Self::EasyMarkEditor,
#[cfg(feature = "http")] #[cfg(feature = "http")]
Anchor::Http, Self::Http,
Anchor::Clock, Self::Clock,
#[cfg(any(feature = "glow", feature = "wgpu"))] #[cfg(any(feature = "glow", feature = "wgpu"))]
Anchor::Custom3d, Self::Custom3d,
Anchor::Colors, Self::Colors,
] ]
} }
} }

View File

@ -19,8 +19,8 @@ pub struct MiscDemoWindow {
} }
impl Default for MiscDemoWindow { impl Default for MiscDemoWindow {
fn default() -> MiscDemoWindow { fn default() -> Self {
MiscDemoWindow { Self {
num_columns: 2, num_columns: 2,
widgets: Default::default(), widgets: Default::default(),
@ -299,7 +299,7 @@ struct ColorWidgets {
impl Default for ColorWidgets { impl Default for ColorWidgets {
fn default() -> Self { fn default() -> Self {
// Approximately the same color. // Approximately the same color.
ColorWidgets { Self {
srgba_unmul: [0, 255, 183, 127], srgba_unmul: [0, 255, 183, 127],
srgba_premul: [0, 187, 140, 127], srgba_premul: [0, 187, 140, 127],
rgba_unmul: [0.0, 1.0, 0.5, 0.5], rgba_unmul: [0.0, 1.0, 0.5, 0.5],
@ -452,8 +452,8 @@ struct Tree(Vec<Tree>);
impl Tree { impl Tree {
pub fn demo() -> Self { pub fn demo() -> Self {
Self(vec![ Self(vec![
Tree(vec![Tree::default(); 4]), Self(vec![Self::default(); 4]),
Tree(vec![Tree(vec![Tree::default(); 2]); 3]), Self(vec![Self(vec![Self::default(); 2]); 3]),
]) ])
} }
@ -494,7 +494,7 @@ impl Tree {
.collect(); .collect();
if ui.button("+").clicked() { if ui.button("+").clicked() {
self.0.push(Tree::default()); self.0.push(Self::default());
} }
Action::Keep Action::Keep

View File

@ -408,7 +408,7 @@ impl LegendDemo {
} }
fn ui(&mut self, ui: &mut Ui) -> Response { fn ui(&mut self, ui: &mut Ui) -> Response {
let LegendDemo { config } = self; let Self { config } = self;
egui::Grid::new("settings").show(ui, |ui| { egui::Grid::new("settings").show(ui, |ui| {
ui.label("Text style:"); ui.label("Text style:");
@ -442,11 +442,11 @@ impl LegendDemo {
.data_aspect(1.0); .data_aspect(1.0);
legend_plot legend_plot
.show(ui, |plot_ui| { .show(ui, |plot_ui| {
plot_ui.line(LegendDemo::line_with_slope(0.5).name("lines")); plot_ui.line(Self::line_with_slope(0.5).name("lines"));
plot_ui.line(LegendDemo::line_with_slope(1.0).name("lines")); plot_ui.line(Self::line_with_slope(1.0).name("lines"));
plot_ui.line(LegendDemo::line_with_slope(2.0).name("lines")); plot_ui.line(Self::line_with_slope(2.0).name("lines"));
plot_ui.line(LegendDemo::sin().name("sin(x)")); plot_ui.line(Self::sin().name("sin(x)"));
plot_ui.line(LegendDemo::cos().name("cos(x)")); plot_ui.line(Self::cos().name("cos(x)"));
}) })
.response .response
} }
@ -467,7 +467,7 @@ impl CustomAxesDemo {
} }
let values = PlotPoints::from_explicit_callback( let values = PlotPoints::from_explicit_callback(
move |x| 1.0 / (1.0 + (-2.5 * (x / CustomAxesDemo::MINS_PER_DAY - 2.0)).exp()), move |x| 1.0 / (1.0 + (-2.5 * (x / Self::MINS_PER_DAY - 2.0)).exp()),
days(0.0)..days(5.0), days(0.0)..days(5.0),
100, 100,
); );
@ -581,10 +581,10 @@ impl CustomAxesDemo {
.data_aspect(2.0 * MINS_PER_DAY as f32) .data_aspect(2.0 * MINS_PER_DAY as f32)
.custom_x_axes(x_axes) .custom_x_axes(x_axes)
.custom_y_axes(y_axes) .custom_y_axes(y_axes)
.x_grid_spacer(CustomAxesDemo::x_grid) .x_grid_spacer(Self::x_grid)
.label_formatter(label_fmt) .label_formatter(label_fmt)
.show(ui, |plot_ui| { .show(ui, |plot_ui| {
plot_ui.line(CustomAxesDemo::logistic_fn()); plot_ui.line(Self::logistic_fn());
}) })
.response .response
} }
@ -637,11 +637,11 @@ impl LinkedAxesDemo {
} }
fn configure_plot(plot_ui: &mut egui_plot::PlotUi) { fn configure_plot(plot_ui: &mut egui_plot::PlotUi) {
plot_ui.line(LinkedAxesDemo::line_with_slope(0.5)); plot_ui.line(Self::line_with_slope(0.5));
plot_ui.line(LinkedAxesDemo::line_with_slope(1.0)); plot_ui.line(Self::line_with_slope(1.0));
plot_ui.line(LinkedAxesDemo::line_with_slope(2.0)); plot_ui.line(Self::line_with_slope(2.0));
plot_ui.line(LinkedAxesDemo::sin()); plot_ui.line(Self::sin());
plot_ui.line(LinkedAxesDemo::cos()); plot_ui.line(Self::cos());
} }
fn ui(&mut self, ui: &mut Ui) -> Response { fn ui(&mut self, ui: &mut Ui) -> Response {
@ -664,7 +664,7 @@ impl LinkedAxesDemo {
.height(250.0) .height(250.0)
.link_axis(link_group_id, self.link_x, self.link_y) .link_axis(link_group_id, self.link_x, self.link_y)
.link_cursor(link_group_id, self.link_cursor_x, self.link_cursor_y) .link_cursor(link_group_id, self.link_cursor_x, self.link_cursor_y)
.show(ui, LinkedAxesDemo::configure_plot); .show(ui, Self::configure_plot);
Plot::new("right-top") Plot::new("right-top")
.data_aspect(2.0) .data_aspect(2.0)
.width(150.0) .width(150.0)
@ -674,7 +674,7 @@ impl LinkedAxesDemo {
.y_axis_position(egui_plot::HPlacement::Right) .y_axis_position(egui_plot::HPlacement::Right)
.link_axis(link_group_id, self.link_x, self.link_y) .link_axis(link_group_id, self.link_x, self.link_y)
.link_cursor(link_group_id, self.link_cursor_x, self.link_cursor_y) .link_cursor(link_group_id, self.link_cursor_x, self.link_cursor_y)
.show(ui, LinkedAxesDemo::configure_plot); .show(ui, Self::configure_plot);
}); });
Plot::new("left-bottom") Plot::new("left-bottom")
.data_aspect(0.5) .data_aspect(0.5)
@ -683,7 +683,7 @@ impl LinkedAxesDemo {
.x_axis_label("x") .x_axis_label("x")
.link_axis(link_group_id, self.link_x, self.link_y) .link_axis(link_group_id, self.link_x, self.link_y)
.link_cursor(link_group_id, self.link_cursor_x, self.link_cursor_y) .link_cursor(link_group_id, self.link_cursor_x, self.link_cursor_y)
.show(ui, LinkedAxesDemo::configure_plot) .show(ui, Self::configure_plot)
.response .response
} }
} }

View File

@ -33,7 +33,7 @@ impl File {
let mime = response.content_type().map(|v| v.to_owned()); let mime = response.content_type().map(|v| v.to_owned());
let bytes = response.bytes.into(); let bytes = response.bytes.into();
Ok(File { bytes, mime }) Ok(Self { bytes, mime })
} }
} }

View File

@ -162,12 +162,12 @@ impl CodeTheme {
if ctx.style().visuals.dark_mode { if ctx.style().visuals.dark_mode {
ctx.data_mut(|d| { ctx.data_mut(|d| {
d.get_persisted(egui::Id::new("dark")) d.get_persisted(egui::Id::new("dark"))
.unwrap_or_else(CodeTheme::dark) .unwrap_or_else(Self::dark)
}) })
} else { } else {
ctx.data_mut(|d| { ctx.data_mut(|d| {
d.get_persisted(egui::Id::new("light")) d.get_persisted(egui::Id::new("light"))
.unwrap_or_else(CodeTheme::light) .unwrap_or_else(Self::light)
}) })
} }
} }
@ -279,9 +279,9 @@ impl CodeTheme {
}); });
let reset_value = if self.dark_mode { let reset_value = if self.dark_mode {
CodeTheme::dark() Self::dark()
} else { } else {
CodeTheme::light() Self::light()
}; };
if ui if ui

View File

@ -111,7 +111,7 @@ impl GlutinWindowContext {
) )
.unwrap(); .unwrap();
GlutinWindowContext { Self {
window, window,
gl_context, gl_context,
gl_display, gl_display,

View File

@ -28,8 +28,8 @@ trait TextureFilterExt {
impl TextureFilterExt for egui::TextureFilter { impl TextureFilterExt for egui::TextureFilter {
fn glow_code(&self) -> u32 { fn glow_code(&self) -> u32 {
match self { match self {
egui::TextureFilter::Linear => glow::LINEAR, Self::Linear => glow::LINEAR,
egui::TextureFilter::Nearest => glow::NEAREST, Self::Nearest => glow::NEAREST,
} }
} }
} }
@ -102,7 +102,7 @@ pub struct CallbackFn {
impl CallbackFn { impl CallbackFn {
pub fn new<F: Fn(PaintCallbackInfo, &Painter) + Sync + Send + 'static>(callback: F) -> Self { pub fn new<F: Fn(PaintCallbackInfo, &Painter) + Sync + Send + 'static>(callback: F) -> Self {
let f = Box::new(callback); let f = Box::new(callback);
CallbackFn { f } Self { f }
} }
} }
@ -123,7 +123,7 @@ impl Painter {
gl: Arc<glow::Context>, gl: Arc<glow::Context>,
shader_prefix: &str, shader_prefix: &str,
shader_version: Option<ShaderVersion>, shader_version: Option<ShaderVersion>,
) -> Result<Painter, PainterError> { ) -> Result<Self, PainterError> {
crate::profile_function!(); crate::profile_function!();
crate::check_for_gl_error_even_in_release!(&gl, "before Painter::new"); crate::check_for_gl_error_even_in_release!(&gl, "before Painter::new");
@ -230,7 +230,7 @@ impl Painter {
crate::check_for_gl_error_even_in_release!(&gl, "after Painter::new"); crate::check_for_gl_error_even_in_release!(&gl, "after Painter::new");
Ok(Painter { Ok(Self {
gl, gl,
max_texture_side, max_texture_side,
program, program,

View File

@ -57,8 +57,8 @@ impl From<HPlacement> for Placement {
#[inline] #[inline]
fn from(placement: HPlacement) -> Self { fn from(placement: HPlacement) -> Self {
match placement { match placement {
HPlacement::Left => Placement::LeftBottom, HPlacement::Left => Self::LeftBottom,
HPlacement::Right => Placement::RightTop, HPlacement::Right => Self::RightTop,
} }
} }
} }
@ -67,8 +67,8 @@ impl From<VPlacement> for Placement {
#[inline] #[inline]
fn from(placement: VPlacement) -> Self { fn from(placement: VPlacement) -> Self {
match placement { match placement {
VPlacement::Top => Placement::RightTop, VPlacement::Top => Self::RightTop,
VPlacement::Bottom => Placement::LeftBottom, VPlacement::Bottom => Self::LeftBottom,
} }
} }
} }

View File

@ -40,8 +40,8 @@ impl Bar {
/// - `value`: Height of the bar (if vertical). /// - `value`: Height of the bar (if vertical).
/// ///
/// By default the bar is vertical and its base is at zero. /// By default the bar is vertical and its base is at zero.
pub fn new(argument: f64, height: f64) -> Bar { pub fn new(argument: f64, height: f64) -> Self {
Bar { Self {
argument, argument,
value: height, value: height,
orientation: Orientation::default(), orientation: Orientation::default(),

View File

@ -184,7 +184,7 @@ impl HLine {
impl PlotItem for HLine { impl PlotItem for HLine {
fn shapes(&self, ui: &mut Ui, transform: &PlotTransform, shapes: &mut Vec<Shape>) { fn shapes(&self, ui: &mut Ui, transform: &PlotTransform, shapes: &mut Vec<Shape>) {
let HLine { let Self {
y, y,
stroke, stroke,
highlight, highlight,
@ -306,7 +306,7 @@ impl VLine {
impl PlotItem for VLine { impl PlotItem for VLine {
fn shapes(&self, ui: &mut Ui, transform: &PlotTransform, shapes: &mut Vec<Shape>) { fn shapes(&self, ui: &mut Ui, transform: &PlotTransform, shapes: &mut Vec<Shape>) {
let VLine { let Self {
x, x,
stroke, stroke,
highlight, highlight,
@ -1350,8 +1350,8 @@ pub struct BarChart {
impl BarChart { impl BarChart {
/// Create a bar chart. It defaults to vertically oriented elements. /// Create a bar chart. It defaults to vertically oriented elements.
pub fn new(bars: Vec<Bar>) -> BarChart { pub fn new(bars: Vec<Bar>) -> Self {
BarChart { Self {
bars, bars,
default_color: Color32::TRANSPARENT, default_color: Color32::TRANSPARENT,
name: String::new(), name: String::new(),
@ -1427,7 +1427,7 @@ impl BarChart {
/// Add a custom way to format an element. /// Add a custom way to format an element.
/// Can be used to display a set number of decimals or custom labels. /// Can be used to display a set number of decimals or custom labels.
#[inline] #[inline]
pub fn element_formatter(mut self, formatter: Box<dyn Fn(&Bar, &BarChart) -> String>) -> Self { pub fn element_formatter(mut self, formatter: Box<dyn Fn(&Bar, &Self) -> String>) -> Self {
self.element_formatter = Some(formatter); self.element_formatter = Some(formatter);
self self
} }
@ -1436,7 +1436,7 @@ impl BarChart {
/// Positive values are stacked on top of other positive values. /// Positive values are stacked on top of other positive values.
/// Negative values are stacked below other negative values. /// Negative values are stacked below other negative values.
#[inline] #[inline]
pub fn stack_on(mut self, others: &[&BarChart]) -> Self { pub fn stack_on(mut self, others: &[&Self]) -> Self {
for (index, bar) in self.bars.iter_mut().enumerate() { for (index, bar) in self.bars.iter_mut().enumerate() {
let new_base_offset = if bar.value.is_sign_positive() { let new_base_offset = if bar.value.is_sign_positive() {
others others
@ -1599,10 +1599,8 @@ impl BoxPlot {
/// Add a custom way to format an element. /// Add a custom way to format an element.
/// Can be used to display a set number of decimals or custom labels. /// Can be used to display a set number of decimals or custom labels.
pub fn element_formatter( #[inline]
mut self, pub fn element_formatter(mut self, formatter: Box<dyn Fn(&BoxElem, &Self) -> String>) -> Self {
formatter: Box<dyn Fn(&BoxElem, &BoxPlot) -> String>,
) -> Self {
self.element_formatter = Some(formatter); self.element_formatter = Some(formatter);
self self
} }
@ -1786,11 +1784,11 @@ pub(super) fn rulers_at_value(
cursors.push(Cursor::Horizontal { y: value.y }); cursors.push(Cursor::Horizontal { y: value.y });
} }
let mut prefix = String::new(); let prefix = if name.is_empty() {
String::new()
if !name.is_empty() { } else {
prefix = format!("{name}\n"); format!("{name}\n")
} };
let text = { let text = {
let scale = plot.transform.dvalue_dpos(); let scale = plot.transform.dvalue_dpos();

View File

@ -90,13 +90,13 @@ impl LineStyle {
} }
_ => { _ => {
match self { match self {
LineStyle::Solid => { Self::Solid => {
if highlight { if highlight {
stroke.width *= 2.0; stroke.width *= 2.0;
} }
shapes.push(Shape::line(line, stroke)); shapes.push(Shape::line(line, stroke));
} }
LineStyle::Dotted { spacing } => { Self::Dotted { spacing } => {
// Take the stroke width for the radius even though it's not "correct", otherwise // Take the stroke width for the radius even though it's not "correct", otherwise
// the dots would become too small. // the dots would become too small.
let mut radius = stroke.width; let mut radius = stroke.width;
@ -105,7 +105,7 @@ impl LineStyle {
} }
shapes.extend(Shape::dotted_line(&line, stroke.color, *spacing, radius)); shapes.extend(Shape::dotted_line(&line, stroke.color, *spacing, radius));
} }
LineStyle::Dashed { length } => { Self::Dashed { length } => {
if highlight { if highlight {
stroke.width *= 2.0; stroke.width *= 2.0;
} }
@ -126,9 +126,9 @@ impl LineStyle {
impl ToString for LineStyle { impl ToString for LineStyle {
fn to_string(&self) -> String { fn to_string(&self) -> String {
match self { match self {
LineStyle::Solid => "Solid".into(), Self::Solid => "Solid".into(),
LineStyle::Dotted { spacing } => format!("Dotted{spacing}Px"), Self::Dotted { spacing } => format!("Dotted{spacing}Px"),
LineStyle::Dashed { length } => format!("Dashed{length}Px"), Self::Dashed { length } => format!("Dashed{length}Px"),
} }
} }
} }
@ -190,8 +190,8 @@ impl PlotPoints {
pub fn points(&self) -> &[PlotPoint] { pub fn points(&self) -> &[PlotPoint] {
match self { match self {
PlotPoints::Owned(points) => points.as_slice(), Self::Owned(points) => points.as_slice(),
PlotPoints::Generator(_) => &[], Self::Generator(_) => &[],
} }
} }
@ -268,8 +268,8 @@ impl PlotPoints {
/// Returns true if there are no data points available and there is no function to generate any. /// Returns true if there are no data points available and there is no function to generate any.
pub(crate) fn is_empty(&self) -> bool { pub(crate) fn is_empty(&self) -> bool {
match self { match self {
PlotPoints::Owned(points) => points.is_empty(), Self::Owned(points) => points.is_empty(),
PlotPoints::Generator(_) => false, Self::Generator(_) => false,
} }
} }
@ -305,14 +305,14 @@ impl PlotPoints {
pub(super) fn bounds(&self) -> PlotBounds { pub(super) fn bounds(&self) -> PlotBounds {
match self { match self {
PlotPoints::Owned(points) => { Self::Owned(points) => {
let mut bounds = PlotBounds::NOTHING; let mut bounds = PlotBounds::NOTHING;
for point in points { for point in points {
bounds.extend_with(point); bounds.extend_with(point);
} }
bounds bounds
} }
PlotPoints::Generator(generator) => generator.estimate_bounds(), Self::Generator(generator) => generator.estimate_bounds(),
} }
} }
} }
@ -336,7 +336,7 @@ pub enum MarkerShape {
impl MarkerShape { impl MarkerShape {
/// Get a vector containing all marker shapes. /// Get a vector containing all marker shapes.
pub fn all() -> impl ExactSizeIterator<Item = MarkerShape> { pub fn all() -> impl ExactSizeIterator<Item = Self> {
[ [
Self::Circle, Self::Circle,
Self::Diamond, Self::Diamond,

View File

@ -14,12 +14,12 @@ pub enum Corner {
} }
impl Corner { impl Corner {
pub fn all() -> impl Iterator<Item = Corner> { pub fn all() -> impl Iterator<Item = Self> {
[ [
Corner::LeftTop, Self::LeftTop,
Corner::RightTop, Self::RightTop,
Corner::LeftBottom, Self::LeftBottom,
Corner::RightBottom, Self::RightBottom,
] ]
.iter() .iter()
.copied() .copied()

View File

@ -108,27 +108,27 @@ impl PlotBounds {
self.max[1] += pad; self.max[1] += pad;
} }
pub(crate) fn merge_x(&mut self, other: &PlotBounds) { pub(crate) fn merge_x(&mut self, other: &Self) {
self.min[0] = self.min[0].min(other.min[0]); self.min[0] = self.min[0].min(other.min[0]);
self.max[0] = self.max[0].max(other.max[0]); self.max[0] = self.max[0].max(other.max[0]);
} }
pub(crate) fn merge_y(&mut self, other: &PlotBounds) { pub(crate) fn merge_y(&mut self, other: &Self) {
self.min[1] = self.min[1].min(other.min[1]); self.min[1] = self.min[1].min(other.min[1]);
self.max[1] = self.max[1].max(other.max[1]); self.max[1] = self.max[1].max(other.max[1]);
} }
pub(crate) fn set_x(&mut self, other: &PlotBounds) { pub(crate) fn set_x(&mut self, other: &Self) {
self.min[0] = other.min[0]; self.min[0] = other.min[0];
self.max[0] = other.max[0]; self.max[0] = other.max[0];
} }
pub(crate) fn set_y(&mut self, other: &PlotBounds) { pub(crate) fn set_y(&mut self, other: &Self) {
self.min[1] = other.min[1]; self.min[1] = other.min[1];
self.max[1] = other.max[1]; self.max[1] = other.max[1];
} }
pub(crate) fn merge(&mut self, other: &PlotBounds) { pub(crate) fn merge(&mut self, other: &Self) {
self.min[0] = self.min[0].min(other.min[0]); self.min[0] = self.min[0].min(other.min[0]);
self.min[1] = self.min[1].min(other.min[1]); self.min[1] = self.min[1].min(other.min[1]);
self.max[0] = self.max[0].max(other.max[0]); self.max[0] = self.max[0].max(other.max[0]);

View File

@ -141,15 +141,15 @@ impl Align {
pub struct Align2(pub [Align; 2]); pub struct Align2(pub [Align; 2]);
impl Align2 { impl Align2 {
pub const LEFT_BOTTOM: Align2 = Align2([Align::Min, Align::Max]); pub const LEFT_BOTTOM: Self = Self([Align::Min, Align::Max]);
pub const LEFT_CENTER: Align2 = Align2([Align::Min, Align::Center]); pub const LEFT_CENTER: Self = Self([Align::Min, Align::Center]);
pub const LEFT_TOP: Align2 = Align2([Align::Min, Align::Min]); pub const LEFT_TOP: Self = Self([Align::Min, Align::Min]);
pub const CENTER_BOTTOM: Align2 = Align2([Align::Center, Align::Max]); pub const CENTER_BOTTOM: Self = Self([Align::Center, Align::Max]);
pub const CENTER_CENTER: Align2 = Align2([Align::Center, Align::Center]); pub const CENTER_CENTER: Self = Self([Align::Center, Align::Center]);
pub const CENTER_TOP: Align2 = Align2([Align::Center, Align::Min]); pub const CENTER_TOP: Self = Self([Align::Center, Align::Min]);
pub const RIGHT_BOTTOM: Align2 = Align2([Align::Max, Align::Max]); pub const RIGHT_BOTTOM: Self = Self([Align::Max, Align::Max]);
pub const RIGHT_CENTER: Align2 = Align2([Align::Max, Align::Center]); pub const RIGHT_CENTER: Self = Self([Align::Max, Align::Center]);
pub const RIGHT_TOP: Align2 = Align2([Align::Max, Align::Min]); pub const RIGHT_TOP: Self = Self([Align::Max, Align::Min]);
} }
impl Align2 { impl Align2 {

View File

@ -190,8 +190,8 @@ impl Pos2 {
} }
/// Linearly interpolate towards another point, so that `0.0 => self, 1.0 => other`. /// Linearly interpolate towards another point, so that `0.0 => self, 1.0 => other`.
pub fn lerp(&self, other: Pos2, t: f32) -> Pos2 { pub fn lerp(&self, other: Self, t: f32) -> Self {
Pos2 { Self {
x: lerp(self.x..=other.x, t), x: lerp(self.x..=other.x, t),
y: lerp(self.y..=other.y, t), y: lerp(self.y..=other.y, t),
} }
@ -227,7 +227,7 @@ impl Eq for Pos2 {}
impl AddAssign<Vec2> for Pos2 { impl AddAssign<Vec2> for Pos2 {
#[inline(always)] #[inline(always)]
fn add_assign(&mut self, rhs: Vec2) { fn add_assign(&mut self, rhs: Vec2) {
*self = Pos2 { *self = Self {
x: self.x + rhs.x, x: self.x + rhs.x,
y: self.y + rhs.y, y: self.y + rhs.y,
}; };
@ -237,7 +237,7 @@ impl AddAssign<Vec2> for Pos2 {
impl SubAssign<Vec2> for Pos2 { impl SubAssign<Vec2> for Pos2 {
#[inline(always)] #[inline(always)]
fn sub_assign(&mut self, rhs: Vec2) { fn sub_assign(&mut self, rhs: Vec2) {
*self = Pos2 { *self = Self {
x: self.x - rhs.x, x: self.x - rhs.x,
y: self.y - rhs.y, y: self.y - rhs.y,
}; };
@ -245,11 +245,11 @@ impl SubAssign<Vec2> for Pos2 {
} }
impl Add<Vec2> for Pos2 { impl Add<Vec2> for Pos2 {
type Output = Pos2; type Output = Self;
#[inline(always)] #[inline(always)]
fn add(self, rhs: Vec2) -> Pos2 { fn add(self, rhs: Vec2) -> Self {
Pos2 { Self {
x: self.x + rhs.x, x: self.x + rhs.x,
y: self.y + rhs.y, y: self.y + rhs.y,
} }
@ -260,7 +260,7 @@ impl Sub for Pos2 {
type Output = Vec2; type Output = Vec2;
#[inline(always)] #[inline(always)]
fn sub(self, rhs: Pos2) -> Vec2 { fn sub(self, rhs: Self) -> Vec2 {
Vec2 { Vec2 {
x: self.x - rhs.x, x: self.x - rhs.x,
y: self.y - rhs.y, y: self.y - rhs.y,
@ -269,11 +269,11 @@ impl Sub for Pos2 {
} }
impl Sub<Vec2> for Pos2 { impl Sub<Vec2> for Pos2 {
type Output = Pos2; type Output = Self;
#[inline(always)] #[inline(always)]
fn sub(self, rhs: Vec2) -> Pos2 { fn sub(self, rhs: Vec2) -> Self {
Pos2 { Self {
x: self.x - rhs.x, x: self.x - rhs.x,
y: self.y - rhs.y, y: self.y - rhs.y,
} }
@ -281,11 +281,11 @@ impl Sub<Vec2> for Pos2 {
} }
impl Mul<f32> for Pos2 { impl Mul<f32> for Pos2 {
type Output = Pos2; type Output = Self;
#[inline(always)] #[inline(always)]
fn mul(self, factor: f32) -> Pos2 { fn mul(self, factor: f32) -> Self {
Pos2 { Self {
x: self.x * factor, x: self.x * factor,
y: self.y * factor, y: self.y * factor,
} }
@ -305,11 +305,11 @@ impl Mul<Pos2> for f32 {
} }
impl Div<f32> for Pos2 { impl Div<f32> for Pos2 {
type Output = Pos2; type Output = Self;
#[inline(always)] #[inline(always)]
fn div(self, factor: f32) -> Pos2 { fn div(self, factor: f32) -> Self {
Pos2 { Self {
x: self.x / factor, x: self.x / factor,
y: self.y / factor, y: self.y / factor,
} }

View File

@ -71,7 +71,7 @@ impl Rangef {
/// Flip `min` and `max` if needed, so that `min <= max` after. /// Flip `min` and `max` if needed, so that `min <= max` after.
#[inline] #[inline]
pub fn as_positive(self) -> Self { pub fn as_positive(self) -> Self {
Rangef { Self {
min: self.min.min(self.max), min: self.min.min(self.max),
max: self.min.max(self.max), max: self.min.max(self.max),
} }

View File

@ -70,13 +70,13 @@ impl Rect {
#[inline(always)] #[inline(always)]
pub const fn from_min_max(min: Pos2, max: Pos2) -> Self { pub const fn from_min_max(min: Pos2, max: Pos2) -> Self {
Rect { min, max } Self { min, max }
} }
/// left-top corner plus a size (stretching right-down). /// left-top corner plus a size (stretching right-down).
#[inline(always)] #[inline(always)]
pub fn from_min_size(min: Pos2, size: Vec2) -> Self { pub fn from_min_size(min: Pos2, size: Vec2) -> Self {
Rect { Self {
min, min,
max: min + size, max: min + size,
} }
@ -84,7 +84,7 @@ impl Rect {
#[inline(always)] #[inline(always)]
pub fn from_center_size(center: Pos2, size: Vec2) -> Self { pub fn from_center_size(center: Pos2, size: Vec2) -> Self {
Rect { Self {
min: center - size * 0.5, min: center - size * 0.5,
max: center + size * 0.5, max: center + size * 0.5,
} }
@ -94,7 +94,7 @@ impl Rect {
pub fn from_x_y_ranges(x_range: impl Into<Rangef>, y_range: impl Into<Rangef>) -> Self { pub fn from_x_y_ranges(x_range: impl Into<Rangef>, y_range: impl Into<Rangef>) -> Self {
let x_range = x_range.into(); let x_range = x_range.into();
let y_range = y_range.into(); let y_range = y_range.into();
Rect { Self {
min: pos2(x_range.min, y_range.min), min: pos2(x_range.min, y_range.min),
max: pos2(x_range.max, y_range.max), max: pos2(x_range.max, y_range.max),
} }
@ -103,7 +103,7 @@ impl Rect {
/// Returns the bounding rectangle of the two points. /// Returns the bounding rectangle of the two points.
#[inline] #[inline]
pub fn from_two_pos(a: Pos2, b: Pos2) -> Self { pub fn from_two_pos(a: Pos2, b: Pos2) -> Self {
Rect { Self {
min: pos2(a.x.min(b.x), a.y.min(b.y)), min: pos2(a.x.min(b.x), a.y.min(b.y)),
max: pos2(a.x.max(b.x), a.y.max(b.y)), max: pos2(a.x.max(b.x), a.y.max(b.y)),
} }
@ -111,7 +111,7 @@ impl Rect {
/// Bounding-box around the points. /// Bounding-box around the points.
pub fn from_points(points: &[Pos2]) -> Self { pub fn from_points(points: &[Pos2]) -> Self {
let mut rect = Rect::NOTHING; let mut rect = Self::NOTHING;
for &p in points { for &p in points {
rect.extend_with(p); rect.extend_with(p);
} }
@ -187,7 +187,7 @@ impl Rect {
/// Expand by this much in each direction, keeping the center /// Expand by this much in each direction, keeping the center
#[must_use] #[must_use]
pub fn expand2(self, amnt: Vec2) -> Self { pub fn expand2(self, amnt: Vec2) -> Self {
Rect::from_min_max(self.min - amnt, self.max + amnt) Self::from_min_max(self.min - amnt, self.max + amnt)
} }
/// Shrink by this much in each direction, keeping the center /// Shrink by this much in each direction, keeping the center
@ -199,13 +199,13 @@ impl Rect {
/// Shrink by this much in each direction, keeping the center /// Shrink by this much in each direction, keeping the center
#[must_use] #[must_use]
pub fn shrink2(self, amnt: Vec2) -> Self { pub fn shrink2(self, amnt: Vec2) -> Self {
Rect::from_min_max(self.min + amnt, self.max - amnt) Self::from_min_max(self.min + amnt, self.max - amnt)
} }
#[must_use] #[must_use]
#[inline] #[inline]
pub fn translate(self, amnt: Vec2) -> Self { pub fn translate(self, amnt: Vec2) -> Self {
Rect::from_min_size(self.min + amnt, self.size()) Self::from_min_size(self.min + amnt, self.size())
} }
/// Rotate the bounds (will expand the [`Rect`]) /// Rotate the bounds (will expand the [`Rect`])
@ -225,7 +225,7 @@ impl Rect {
#[must_use] #[must_use]
#[inline] #[inline]
pub fn intersects(self, other: Rect) -> bool { pub fn intersects(self, other: Self) -> bool {
self.min.x <= other.max.x self.min.x <= other.max.x
&& other.min.x <= self.max.x && other.min.x <= self.max.x
&& self.min.y <= other.max.y && self.min.y <= other.max.y
@ -254,7 +254,7 @@ impl Rect {
} }
#[must_use] #[must_use]
pub fn contains_rect(&self, other: Rect) -> bool { pub fn contains_rect(&self, other: Self) -> bool {
self.contains(other.min) && self.contains(other.max) self.contains(other.min) && self.contains(other.max)
} }
@ -289,8 +289,8 @@ impl Rect {
/// that contains both input rectangles. /// that contains both input rectangles.
#[inline(always)] #[inline(always)]
#[must_use] #[must_use]
pub fn union(self, other: Rect) -> Rect { pub fn union(self, other: Self) -> Self {
Rect { Self {
min: self.min.min(other.min), min: self.min.min(other.min),
max: self.max.max(other.max), max: self.max.max(other.max),
} }
@ -299,7 +299,7 @@ impl Rect {
/// The intersection of two [`Rect`], i.e. the area covered by both. /// The intersection of two [`Rect`], i.e. the area covered by both.
#[inline] #[inline]
#[must_use] #[must_use]
pub fn intersect(self, other: Rect) -> Self { pub fn intersect(self, other: Self) -> Self {
Self { Self {
min: self.min.max(other.min), min: self.min.max(other.min),
max: self.max.min(other.max), max: self.max.min(other.max),
@ -419,7 +419,7 @@ impl Rect {
/// Linearly self towards other rect. /// Linearly self towards other rect.
#[inline] #[inline]
pub fn lerp_towards(&self, other: &Rect, t: f32) -> Self { pub fn lerp_towards(&self, other: &Self, t: f32) -> Self {
Self { Self {
min: self.min.lerp(other.min, t), min: self.min.lerp(other.min, t),
max: self.max.lerp(other.max, t), max: self.max.lerp(other.max, t),
@ -581,26 +581,26 @@ impl Rect {
} }
/// Split rectangle in left and right halves. `t` is expected to be in the (0,1) range. /// Split rectangle in left and right halves. `t` is expected to be in the (0,1) range.
pub fn split_left_right_at_fraction(&self, t: f32) -> (Rect, Rect) { pub fn split_left_right_at_fraction(&self, t: f32) -> (Self, Self) {
self.split_left_right_at_x(lerp(self.min.x..=self.max.x, t)) self.split_left_right_at_x(lerp(self.min.x..=self.max.x, t))
} }
/// Split rectangle in left and right halves at the given `x` coordinate. /// Split rectangle in left and right halves at the given `x` coordinate.
pub fn split_left_right_at_x(&self, split_x: f32) -> (Rect, Rect) { pub fn split_left_right_at_x(&self, split_x: f32) -> (Self, Self) {
let left = Rect::from_min_max(self.min, Pos2::new(split_x, self.max.y)); let left = Self::from_min_max(self.min, Pos2::new(split_x, self.max.y));
let right = Rect::from_min_max(Pos2::new(split_x, self.min.y), self.max); let right = Self::from_min_max(Pos2::new(split_x, self.min.y), self.max);
(left, right) (left, right)
} }
/// Split rectangle in top and bottom halves. `t` is expected to be in the (0,1) range. /// Split rectangle in top and bottom halves. `t` is expected to be in the (0,1) range.
pub fn split_top_bottom_at_fraction(&self, t: f32) -> (Rect, Rect) { pub fn split_top_bottom_at_fraction(&self, t: f32) -> (Self, Self) {
self.split_top_bottom_at_y(lerp(self.min.y..=self.max.y, t)) self.split_top_bottom_at_y(lerp(self.min.y..=self.max.y, t))
} }
/// Split rectangle in top and bottom halves at the given `y` coordinate. /// Split rectangle in top and bottom halves at the given `y` coordinate.
pub fn split_top_bottom_at_y(&self, split_y: f32) -> (Rect, Rect) { pub fn split_top_bottom_at_y(&self, split_y: f32) -> (Self, Self) {
let top = Rect::from_min_max(self.min, Pos2::new(self.max.x, split_y)); let top = Self::from_min_max(self.min, Pos2::new(self.max.x, split_y));
let bottom = Rect::from_min_max(Pos2::new(self.min.x, split_y), self.max); let bottom = Self::from_min_max(Pos2::new(self.min.x, split_y), self.max);
(top, bottom) (top, bottom)
} }
} }
@ -620,11 +620,11 @@ impl From<[Pos2; 2]> for Rect {
} }
impl Mul<f32> for Rect { impl Mul<f32> for Rect {
type Output = Rect; type Output = Self;
#[inline] #[inline]
fn mul(self, factor: f32) -> Rect { fn mul(self, factor: f32) -> Self {
Rect { Self {
min: self.min * factor, min: self.min * factor,
max: self.max * factor, max: self.max * factor,
} }
@ -644,11 +644,11 @@ impl Mul<Rect> for f32 {
} }
impl Div<f32> for Rect { impl Div<f32> for Rect {
type Output = Rect; type Output = Self;
#[inline] #[inline]
fn div(self, factor: f32) -> Rect { fn div(self, factor: f32) -> Self {
Rect { Self {
min: self.min / factor, min: self.min / factor,
max: self.max / factor, max: self.max / factor,
} }

View File

@ -34,7 +34,7 @@ impl RectTransform {
self.to.size() / self.from.size() self.to.size() / self.from.size()
} }
pub fn inverse(&self) -> RectTransform { pub fn inverse(&self) -> Self {
Self::from_to(self.to, self.from) Self::from_to(self.to, self.from)
} }

View File

@ -62,7 +62,7 @@ impl Rot2 {
} }
#[must_use] #[must_use]
pub fn inverse(self) -> Rot2 { pub fn inverse(self) -> Self {
Self { Self {
s: -self.s, s: -self.s,
c: self.c, c: self.c,
@ -92,15 +92,15 @@ impl std::fmt::Debug for Rot2 {
} }
} }
impl std::ops::Mul<Rot2> for Rot2 { impl std::ops::Mul<Self> for Rot2 {
type Output = Rot2; type Output = Self;
fn mul(self, r: Rot2) -> Rot2 { fn mul(self, r: Self) -> Self {
/* /*
|lc -ls| * |rc -rs| |lc -ls| * |rc -rs|
|ls lc| |rs rc| |ls lc| |rs rc|
*/ */
Rot2 { Self {
c: self.c * r.c - self.s * r.s, c: self.c * r.c - self.s * r.s,
s: self.s * r.c + self.c * r.s, s: self.s * r.c + self.c * r.s,
} }
@ -133,10 +133,10 @@ impl std::ops::Mul<Rot2> for f32 {
/// Scales the rotor. /// Scales the rotor.
impl std::ops::Mul<f32> for Rot2 { impl std::ops::Mul<f32> for Rot2 {
type Output = Rot2; type Output = Self;
fn mul(self, r: f32) -> Rot2 { fn mul(self, r: f32) -> Self {
Rot2 { Self {
c: self.c * r, c: self.c * r,
s: self.s * r, s: self.s * r,
} }
@ -145,10 +145,10 @@ impl std::ops::Mul<f32> for Rot2 {
/// Scales the rotor. /// Scales the rotor.
impl std::ops::Div<f32> for Rot2 { impl std::ops::Div<f32> for Rot2 {
type Output = Rot2; type Output = Self;
fn div(self, r: f32) -> Rot2 { fn div(self, r: f32) -> Self {
Rot2 { Self {
c: self.c / r, c: self.c / r,
s: self.s / r, s: self.s / r,
} }

View File

@ -108,13 +108,13 @@ impl From<Vec2> for mint::Vector2<f32> {
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
impl Vec2 { impl Vec2 {
pub const X: Vec2 = Vec2 { x: 1.0, y: 0.0 }; pub const X: Self = Self { x: 1.0, y: 0.0 };
pub const Y: Vec2 = Vec2 { x: 0.0, y: 1.0 }; pub const Y: Self = Self { x: 0.0, y: 1.0 };
pub const RIGHT: Vec2 = Vec2 { x: 1.0, y: 0.0 }; pub const RIGHT: Self = Self { x: 1.0, y: 0.0 };
pub const LEFT: Vec2 = Vec2 { x: -1.0, y: 0.0 }; pub const LEFT: Self = Self { x: -1.0, y: 0.0 };
pub const UP: Vec2 = Vec2 { x: 0.0, y: -1.0 }; pub const UP: Self = Self { x: 0.0, y: -1.0 };
pub const DOWN: Vec2 = Vec2 { x: 0.0, y: 1.0 }; pub const DOWN: Self = Self { x: 0.0, y: 1.0 };
pub const ZERO: Self = Self { x: 0.0, y: 0.0 }; pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
pub const INFINITY: Self = Self::splat(f32::INFINITY); pub const INFINITY: Self = Self::splat(f32::INFINITY);
@ -278,8 +278,8 @@ impl Vec2 {
/// Swizzle the axes. /// Swizzle the axes.
#[inline] #[inline]
#[must_use] #[must_use]
pub fn yx(self) -> Vec2 { pub fn yx(self) -> Self {
Vec2 { Self {
x: self.y, x: self.y,
y: self.x, y: self.x,
} }
@ -322,18 +322,18 @@ impl std::ops::IndexMut<usize> for Vec2 {
impl Eq for Vec2 {} impl Eq for Vec2 {}
impl Neg for Vec2 { impl Neg for Vec2 {
type Output = Vec2; type Output = Self;
#[inline(always)] #[inline(always)]
fn neg(self) -> Vec2 { fn neg(self) -> Self {
vec2(-self.x, -self.y) vec2(-self.x, -self.y)
} }
} }
impl AddAssign for Vec2 { impl AddAssign for Vec2 {
#[inline(always)] #[inline(always)]
fn add_assign(&mut self, rhs: Vec2) { fn add_assign(&mut self, rhs: Self) {
*self = Vec2 { *self = Self {
x: self.x + rhs.x, x: self.x + rhs.x,
y: self.y + rhs.y, y: self.y + rhs.y,
}; };
@ -342,8 +342,8 @@ impl AddAssign for Vec2 {
impl SubAssign for Vec2 { impl SubAssign for Vec2 {
#[inline(always)] #[inline(always)]
fn sub_assign(&mut self, rhs: Vec2) { fn sub_assign(&mut self, rhs: Self) {
*self = Vec2 { *self = Self {
x: self.x - rhs.x, x: self.x - rhs.x,
y: self.y - rhs.y, y: self.y - rhs.y,
}; };
@ -351,11 +351,11 @@ impl SubAssign for Vec2 {
} }
impl Add for Vec2 { impl Add for Vec2 {
type Output = Vec2; type Output = Self;
#[inline(always)] #[inline(always)]
fn add(self, rhs: Vec2) -> Vec2 { fn add(self, rhs: Self) -> Self {
Vec2 { Self {
x: self.x + rhs.x, x: self.x + rhs.x,
y: self.y + rhs.y, y: self.y + rhs.y,
} }
@ -363,11 +363,11 @@ impl Add for Vec2 {
} }
impl Sub for Vec2 { impl Sub for Vec2 {
type Output = Vec2; type Output = Self;
#[inline(always)] #[inline(always)]
fn sub(self, rhs: Vec2) -> Vec2 { fn sub(self, rhs: Self) -> Self {
Vec2 { Self {
x: self.x - rhs.x, x: self.x - rhs.x,
y: self.y - rhs.y, y: self.y - rhs.y,
} }
@ -375,12 +375,12 @@ impl Sub for Vec2 {
} }
/// Element-wise multiplication /// Element-wise multiplication
impl Mul<Vec2> for Vec2 { impl Mul<Self> for Vec2 {
type Output = Vec2; type Output = Self;
#[inline(always)] #[inline(always)]
fn mul(self, vec: Vec2) -> Vec2 { fn mul(self, vec: Self) -> Self {
Vec2 { Self {
x: self.x * vec.x, x: self.x * vec.x,
y: self.y * vec.y, y: self.y * vec.y,
} }
@ -388,12 +388,12 @@ impl Mul<Vec2> for Vec2 {
} }
/// Element-wise division /// Element-wise division
impl Div<Vec2> for Vec2 { impl Div<Self> for Vec2 {
type Output = Vec2; type Output = Self;
#[inline(always)] #[inline(always)]
fn div(self, rhs: Vec2) -> Vec2 { fn div(self, rhs: Self) -> Self {
Vec2 { Self {
x: self.x / rhs.x, x: self.x / rhs.x,
y: self.y / rhs.y, y: self.y / rhs.y,
} }
@ -417,11 +417,11 @@ impl DivAssign<f32> for Vec2 {
} }
impl Mul<f32> for Vec2 { impl Mul<f32> for Vec2 {
type Output = Vec2; type Output = Self;
#[inline(always)] #[inline(always)]
fn mul(self, factor: f32) -> Vec2 { fn mul(self, factor: f32) -> Self {
Vec2 { Self {
x: self.x * factor, x: self.x * factor,
y: self.y * factor, y: self.y * factor,
} }
@ -441,11 +441,11 @@ impl Mul<Vec2> for f32 {
} }
impl Div<f32> for Vec2 { impl Div<f32> for Vec2 {
type Output = Vec2; type Output = Self;
#[inline(always)] #[inline(always)]
fn div(self, factor: f32) -> Vec2 { fn div(self, factor: f32) -> Self {
Vec2 { Self {
x: self.x / factor, x: self.x / factor,
y: self.y / factor, y: self.y / factor,
} }

View File

@ -24,14 +24,14 @@ impl Vec2b {
impl From<bool> for Vec2b { impl From<bool> for Vec2b {
#[inline] #[inline]
fn from(val: bool) -> Self { fn from(val: bool) -> Self {
Vec2b { x: val, y: val } Self { x: val, y: val }
} }
} }
impl From<[bool; 2]> for Vec2b { impl From<[bool; 2]> for Vec2b {
#[inline] #[inline]
fn from([x, y]: [bool; 2]) -> Self { fn from([x, y]: [bool; 2]) -> Self {
Vec2b { x, y } Self { x, y }
} }
} }

View File

@ -48,7 +48,7 @@ impl CubicBezierShape {
for (i, origin_point) in self.points.iter().enumerate() { for (i, origin_point) in self.points.iter().enumerate() {
points[i] = transform * *origin_point; points[i] = transform * *origin_point;
} }
CubicBezierShape { Self {
points, points,
closed: self.closed, closed: self.closed,
fill: self.fill, fill: self.fill,
@ -163,7 +163,8 @@ impl CubicBezierShape {
let q_end = q.sample(t_range.end); let q_end = q.sample(t_range.end);
let ctrl1 = from + q_start.to_vec2() * delta_t; let ctrl1 = from + q_start.to_vec2() * delta_t;
let ctrl2 = to - q_end.to_vec2() * delta_t; let ctrl2 = to - q_end.to_vec2() * delta_t;
CubicBezierShape {
Self {
points: [from, ctrl1, ctrl2, to], points: [from, ctrl1, ctrl2, to],
closed: self.closed, closed: self.closed,
fill: self.fill, fill: self.fill,
@ -398,7 +399,7 @@ impl QuadraticBezierShape {
fill: Color32, fill: Color32,
stroke: impl Into<Stroke>, stroke: impl Into<Stroke>,
) -> Self { ) -> Self {
QuadraticBezierShape { Self {
points, points,
closed, closed,
fill, fill,
@ -412,7 +413,7 @@ impl QuadraticBezierShape {
for (i, origin_point) in self.points.iter().enumerate() { for (i, origin_point) in self.points.iter().enumerate() {
points[i] = transform * *origin_point; points[i] = transform * *origin_point;
} }
QuadraticBezierShape { Self {
points, points,
closed: self.closed, closed: self.closed,
fill: self.fill, fill: self.fill,
@ -644,7 +645,7 @@ impl FlatteningParameters {
let integral_step = integral_diff / count; let integral_step = integral_diff / count;
FlatteningParameters { Self {
count, count,
integral_from, integral_from,
integral_step, integral_step,

View File

@ -301,7 +301,7 @@ impl FontImage {
} }
/// Clone a sub-region as a new image. /// Clone a sub-region as a new image.
pub fn region(&self, [x, y]: [usize; 2], [w, h]: [usize; 2]) -> FontImage { pub fn region(&self, [x, y]: [usize; 2], [w, h]: [usize; 2]) -> Self {
assert!(x + w <= self.width()); assert!(x + w <= self.width());
assert!(y + h <= self.height()); assert!(y + h <= self.height());
@ -311,7 +311,7 @@ impl FontImage {
pixels.extend(&self.pixels[offset..(offset + w)]); pixels.extend(&self.pixels[offset..(offset + w)]);
} }
assert_eq!(pixels.len(), w * h); assert_eq!(pixels.len(), w * h);
FontImage { Self {
size: [w, h], size: [w, h],
pixels, pixels,
} }

View File

@ -105,7 +105,7 @@ impl Mesh {
} }
/// Append all the indices and vertices of `other` to `self`. /// Append all the indices and vertices of `other` to `self`.
pub fn append(&mut self, other: Mesh) { pub fn append(&mut self, other: Self) {
crate::epaint_assert!(other.is_valid()); crate::epaint_assert!(other.is_valid());
if self.is_empty() { if self.is_empty() {
@ -117,7 +117,7 @@ impl Mesh {
/// Append all the indices and vertices of `other` to `self` without /// Append all the indices and vertices of `other` to `self` without
/// taking ownership. /// taking ownership.
pub fn append_ref(&mut self, other: &Mesh) { pub fn append_ref(&mut self, other: &Self) {
crate::epaint_assert!(other.is_valid()); crate::epaint_assert!(other.is_valid());
if self.is_empty() { if self.is_empty() {

View File

@ -66,9 +66,9 @@ fn shape_impl_send_sync() {
assert_send_sync::<Shape>(); assert_send_sync::<Shape>();
} }
impl From<Vec<Shape>> for Shape { impl From<Vec<Self>> for Shape {
#[inline(always)] #[inline(always)]
fn from(shapes: Vec<Shape>) -> Self { fn from(shapes: Vec<Self>) -> Self {
Self::Vec(shapes) Self::Vec(shapes)
} }
} }
@ -95,7 +95,7 @@ impl Shape {
/// A horizontal line. /// A horizontal line.
pub fn hline(x: impl Into<Rangef>, y: f32, stroke: impl Into<Stroke>) -> Self { pub fn hline(x: impl Into<Rangef>, y: f32, stroke: impl Into<Stroke>) -> Self {
let x = x.into(); let x = x.into();
Shape::LineSegment { Self::LineSegment {
points: [pos2(x.min, y), pos2(x.max, y)], points: [pos2(x.min, y), pos2(x.max, y)],
stroke: stroke.into(), stroke: stroke.into(),
} }
@ -104,7 +104,7 @@ impl Shape {
/// A vertical line. /// A vertical line.
pub fn vline(x: f32, y: impl Into<Rangef>, stroke: impl Into<Stroke>) -> Self { pub fn vline(x: f32, y: impl Into<Rangef>, stroke: impl Into<Stroke>) -> Self {
let y = y.into(); let y = y.into();
Shape::LineSegment { Self::LineSegment {
points: [pos2(x, y.min), pos2(x, y.max)], points: [pos2(x, y.min), pos2(x, y.max)],
stroke: stroke.into(), stroke: stroke.into(),
} }
@ -182,7 +182,7 @@ impl Shape {
stroke: impl Into<Stroke>, stroke: impl Into<Stroke>,
dash_length: f32, dash_length: f32,
gap_length: f32, gap_length: f32,
shapes: &mut Vec<Shape>, shapes: &mut Vec<Self>,
) { ) {
dashes_from_line( dashes_from_line(
points, points,
@ -202,7 +202,7 @@ impl Shape {
dash_lengths: &[f32], dash_lengths: &[f32],
gap_lengths: &[f32], gap_lengths: &[f32],
dash_offset: f32, dash_offset: f32,
shapes: &mut Vec<Shape>, shapes: &mut Vec<Self>,
) { ) {
dashes_from_line( dashes_from_line(
points, points,
@ -309,7 +309,7 @@ impl Shape {
pub fn image(texture_id: TextureId, rect: Rect, uv: Rect, tint: Color32) -> Self { pub fn image(texture_id: TextureId, rect: Rect, uv: Rect, tint: Color32) -> Self {
let mut mesh = Mesh::with_texture(texture_id); let mut mesh = Mesh::with_texture(texture_id);
mesh.add_rect_with_uv(rect, uv, tint); mesh.add_rect_with_uv(rect, uv, tint);
Shape::mesh(mesh) Self::mesh(mesh)
} }
/// The visual bounding rectangle (includes stroke widths) /// The visual bounding rectangle (includes stroke widths)
@ -346,9 +346,9 @@ impl Shape {
impl Shape { impl Shape {
#[inline(always)] #[inline(always)]
pub fn texture_id(&self) -> super::TextureId { pub fn texture_id(&self) -> super::TextureId {
if let Shape::Mesh(mesh) = self { if let Self::Mesh(mesh) = self {
mesh.texture_id mesh.texture_id
} else if let Shape::Rect(rect_shape) = self { } else if let Self::Rect(rect_shape) = self {
rect_shape.fill_texture_id rect_shape.fill_texture_id
} else { } else {
super::TextureId::default() super::TextureId::default()
@ -358,45 +358,45 @@ impl Shape {
/// Move the shape by this many points, in-place. /// Move the shape by this many points, in-place.
pub fn translate(&mut self, delta: Vec2) { pub fn translate(&mut self, delta: Vec2) {
match self { match self {
Shape::Noop => {} Self::Noop => {}
Shape::Vec(shapes) => { Self::Vec(shapes) => {
for shape in shapes { for shape in shapes {
shape.translate(delta); shape.translate(delta);
} }
} }
Shape::Circle(circle_shape) => { Self::Circle(circle_shape) => {
circle_shape.center += delta; circle_shape.center += delta;
} }
Shape::LineSegment { points, .. } => { Self::LineSegment { points, .. } => {
for p in points { for p in points {
*p += delta; *p += delta;
} }
} }
Shape::Path(path_shape) => { Self::Path(path_shape) => {
for p in &mut path_shape.points { for p in &mut path_shape.points {
*p += delta; *p += delta;
} }
} }
Shape::Rect(rect_shape) => { Self::Rect(rect_shape) => {
rect_shape.rect = rect_shape.rect.translate(delta); rect_shape.rect = rect_shape.rect.translate(delta);
} }
Shape::Text(text_shape) => { Self::Text(text_shape) => {
text_shape.pos += delta; text_shape.pos += delta;
} }
Shape::Mesh(mesh) => { Self::Mesh(mesh) => {
mesh.translate(delta); mesh.translate(delta);
} }
Shape::QuadraticBezier(bezier_shape) => { Self::QuadraticBezier(bezier_shape) => {
bezier_shape.points[0] += delta; bezier_shape.points[0] += delta;
bezier_shape.points[1] += delta; bezier_shape.points[1] += delta;
bezier_shape.points[2] += delta; bezier_shape.points[2] += delta;
} }
Shape::CubicBezier(cubic_curve) => { Self::CubicBezier(cubic_curve) => {
for p in &mut cubic_curve.points { for p in &mut cubic_curve.points {
*p += delta; *p += delta;
} }
} }
Shape::Callback(shape) => { Self::Callback(shape) => {
shape.rect = shape.rect.translate(delta); shape.rect = shape.rect.translate(delta);
} }
} }
@ -484,7 +484,7 @@ impl PathShape {
/// Use [`Shape::line_segment`] instead if your line only connects two points. /// Use [`Shape::line_segment`] instead if your line only connects two points.
#[inline] #[inline]
pub fn line(points: Vec<Pos2>, stroke: impl Into<Stroke>) -> Self { pub fn line(points: Vec<Pos2>, stroke: impl Into<Stroke>) -> Self {
PathShape { Self {
points, points,
closed: false, closed: false,
fill: Default::default(), fill: Default::default(),
@ -495,7 +495,7 @@ impl PathShape {
/// A line that closes back to the start point again. /// A line that closes back to the start point again.
#[inline] #[inline]
pub fn closed_line(points: Vec<Pos2>, stroke: impl Into<Stroke>) -> Self { pub fn closed_line(points: Vec<Pos2>, stroke: impl Into<Stroke>) -> Self {
PathShape { Self {
points, points,
closed: true, closed: true,
fill: Default::default(), fill: Default::default(),
@ -512,7 +512,7 @@ impl PathShape {
fill: impl Into<Color32>, fill: impl Into<Color32>,
stroke: impl Into<Stroke>, stroke: impl Into<Stroke>,
) -> Self { ) -> Self {
PathShape { Self {
points, points,
closed: true, closed: true,
fill: fill.into(), fill: fill.into(),

View File

@ -32,9 +32,9 @@ impl<T> From<&[T]> for AllocInfo {
} }
impl std::ops::Add for AllocInfo { impl std::ops::Add for AllocInfo {
type Output = AllocInfo; type Output = Self;
fn add(self, rhs: AllocInfo) -> AllocInfo { fn add(self, rhs: Self) -> Self {
use ElementSize::{Heterogenous, Homogeneous, Unknown}; use ElementSize::{Heterogenous, Homogeneous, Unknown};
let element_size = match (self.element_size, rhs.element_size) { let element_size = match (self.element_size, rhs.element_size) {
(Heterogenous, _) | (_, Heterogenous) => Heterogenous, (Heterogenous, _) | (_, Heterogenous) => Heterogenous,
@ -43,7 +43,7 @@ impl std::ops::Add for AllocInfo {
_ => Heterogenous, _ => Heterogenous,
}; };
AllocInfo { Self {
element_size, element_size,
num_allocs: self.num_allocs + rhs.num_allocs, num_allocs: self.num_allocs + rhs.num_allocs,
num_elements: self.num_elements + rhs.num_elements, num_elements: self.num_elements + rhs.num_elements,
@ -53,7 +53,7 @@ impl std::ops::Add for AllocInfo {
} }
impl std::ops::AddAssign for AllocInfo { impl std::ops::AddAssign for AllocInfo {
fn add_assign(&mut self, rhs: AllocInfo) { fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs; *self = *self + rhs;
} }
} }

View File

@ -14,7 +14,7 @@ pub struct Stroke {
impl Stroke { impl Stroke {
/// Same as [`Stroke::default`]. /// Same as [`Stroke::default`].
pub const NONE: Stroke = Stroke { pub const NONE: Self = Self {
width: 0.0, width: 0.0,
color: Color32::TRANSPARENT, color: Color32::TRANSPARENT,
}; };
@ -39,8 +39,8 @@ where
Color: Into<Color32>, Color: Into<Color32>,
{ {
#[inline(always)] #[inline(always)]
fn from((width, color): (f32, Color)) -> Stroke { fn from((width, color): (f32, Color)) -> Self {
Stroke::new(width, color) Self::new(width, color)
} }
} }

View File

@ -26,16 +26,16 @@ impl CCursor {
/// Two `CCursor`s are considered equal if they refer to the same character boundary, /// Two `CCursor`s are considered equal if they refer to the same character boundary,
/// even if one prefers the start of the next row. /// even if one prefers the start of the next row.
impl PartialEq for CCursor { impl PartialEq for CCursor {
fn eq(&self, other: &CCursor) -> bool { fn eq(&self, other: &Self) -> bool {
self.index == other.index self.index == other.index
} }
} }
impl std::ops::Add<usize> for CCursor { impl std::ops::Add<usize> for CCursor {
type Output = CCursor; type Output = Self;
fn add(self, rhs: usize) -> Self::Output { fn add(self, rhs: usize) -> Self::Output {
CCursor { Self {
index: self.index.saturating_add(rhs), index: self.index.saturating_add(rhs),
prefer_next_row: self.prefer_next_row, prefer_next_row: self.prefer_next_row,
} }
@ -43,10 +43,10 @@ impl std::ops::Add<usize> for CCursor {
} }
impl std::ops::Sub<usize> for CCursor { impl std::ops::Sub<usize> for CCursor {
type Output = CCursor; type Output = Self;
fn sub(self, rhs: usize) -> Self::Output { fn sub(self, rhs: usize) -> Self::Output {
CCursor { Self {
index: self.index.saturating_sub(rhs), index: self.index.saturating_sub(rhs),
prefer_next_row: self.prefer_next_row, prefer_next_row: self.prefer_next_row,
} }
@ -104,7 +104,7 @@ pub struct PCursor {
/// Two `PCursor`s are considered equal if they refer to the same character boundary, /// Two `PCursor`s are considered equal if they refer to the same character boundary,
/// even if one prefers the start of the next row. /// even if one prefers the start of the next row.
impl PartialEq for PCursor { impl PartialEq for PCursor {
fn eq(&self, other: &PCursor) -> bool { fn eq(&self, other: &Self) -> bool {
self.paragraph == other.paragraph && self.offset == other.offset self.paragraph == other.paragraph && self.offset == other.offset
} }
} }

View File

@ -88,7 +88,7 @@ impl FontImpl {
ab_glyph_font: ab_glyph::FontArc, ab_glyph_font: ab_glyph::FontArc,
scale_in_pixels: f32, scale_in_pixels: f32,
tweak: FontTweak, tweak: FontTweak,
) -> FontImpl { ) -> Self {
assert!(scale_in_pixels > 0.0); assert!(scale_in_pixels > 0.0);
assert!(pixels_per_point > 0.0); assert!(pixels_per_point > 0.0);

View File

@ -214,7 +214,7 @@ impl TexturesDelta {
self.set.is_empty() && self.free.is_empty() self.set.is_empty() && self.free.is_empty()
} }
pub fn append(&mut self, mut newer: TexturesDelta) { pub fn append(&mut self, mut newer: Self) {
self.set.extend(newer.set); self.set.extend(newer.set);
self.free.append(&mut newer.free); self.free.append(&mut newer.free);
} }

View File

@ -58,7 +58,7 @@ impl<T: Float> Hash for OrderedFloat<T> {
impl<T> From<T> for OrderedFloat<T> { impl<T> From<T> for OrderedFloat<T> {
#[inline] #[inline]
fn from(val: T) -> Self { fn from(val: T) -> Self {
OrderedFloat(val) Self(val)
} }
} }
@ -84,14 +84,14 @@ pub trait FloatOrd {
impl FloatOrd for f32 { impl FloatOrd for f32 {
#[inline] #[inline]
fn ord(self) -> OrderedFloat<f32> { fn ord(self) -> OrderedFloat<Self> {
OrderedFloat(self) OrderedFloat(self)
} }
} }
impl FloatOrd for f64 { impl FloatOrd for f64 {
#[inline] #[inline]
fn ord(self) -> OrderedFloat<f64> { fn ord(self) -> OrderedFloat<Self> {
OrderedFloat(self) OrderedFloat(self)
} }
} }
@ -119,7 +119,7 @@ mod private {
impl FloatImpl for f32 { impl FloatImpl for f32 {
#[inline] #[inline]
fn is_nan(&self) -> bool { fn is_nan(&self) -> bool {
f32::is_nan(*self) Self::is_nan(*self)
} }
#[inline] #[inline]
@ -131,7 +131,7 @@ mod private {
impl FloatImpl for f64 { impl FloatImpl for f64 {
#[inline] #[inline]
fn is_nan(&self) -> bool { fn is_nan(&self) -> bool {
f64::is_nan(*self) Self::is_nan(*self)
} }
#[inline] #[inline]

View File

@ -34,7 +34,7 @@ pub struct ViewportState {
impl ViewportState { impl ViewportState {
pub fn new_deferred( pub fn new_deferred(
title: &'static str, title: &'static str,
children: Vec<Arc<RwLock<ViewportState>>>, children: Vec<Arc<RwLock<Self>>>,
) -> Arc<RwLock<Self>> { ) -> Arc<RwLock<Self>> {
Arc::new(RwLock::new(Self { Arc::new(RwLock::new(Self {
id: ViewportId::from_hash_of(title), id: ViewportId::from_hash_of(title),
@ -47,7 +47,7 @@ impl ViewportState {
pub fn new_immediate( pub fn new_immediate(
title: &'static str, title: &'static str,
children: Vec<Arc<RwLock<ViewportState>>>, children: Vec<Arc<RwLock<Self>>>,
) -> Arc<RwLock<Self>> { ) -> Arc<RwLock<Self>> {
Arc::new(RwLock::new(Self { Arc::new(RwLock::new(Self {
id: ViewportId::from_hash_of(title), id: ViewportId::from_hash_of(title),
@ -58,7 +58,7 @@ impl ViewportState {
})) }))
} }
pub fn show(vp_state: Arc<RwLock<ViewportState>>, ctx: &egui::Context) { pub fn show(vp_state: Arc<RwLock<Self>>, ctx: &egui::Context) {
if !vp_state.read().visible { if !vp_state.read().visible {
return; return;
} }

View File

@ -59,7 +59,7 @@ def lint_lines(filepath, lines_in):
) )
lines_out.append("\n") lines_out.append("\n")
if re.search(r"\(mut self.*-> Self", line): if re.search(r"\(mut self.*-> Self", line) and "pub(crate)" not in line:
if prev_line.strip() != "#[inline]": if prev_line.strip() != "#[inline]":
errors.append( errors.append(
f"{filepath}:{line_nr}: builder methods should be marked #[inline]" f"{filepath}:{line_nr}: builder methods should be marked #[inline]"