Skip to content

Commit

Permalink
feat: add UI code conveniences for colors and UI state. (#212)
Browse files Browse the repository at this point in the history
- Add conversion impl for our Color type to Egui's color type.
- Add `get_state()` and `set_state()` extension methods on the egui
context to make it eaiser to deal with UI state.
  • Loading branch information
zicklag committed Oct 2, 2023
1 parent b6d1c23 commit fe453e3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
14 changes: 14 additions & 0 deletions framework_crates/bones_framework/src/render/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ pub enum Color {
},
}

#[cfg(feature = "ui")]
impl From<Color> for egui::Color32 {
fn from(value: Color) -> Self {
match value {
Color::Rgba {
red,
green,
blue,
alpha,
} => egui::Rgba::from_rgba_unmultiplied(red, green, blue, alpha).into(),
}
}
}

impl<'de> serde::Deserialize<'de> for Color {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down
28 changes: 28 additions & 0 deletions framework_crates/bones_framework/src/render/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,15 @@ impl FontMeta {
.color(self.color.into_egui())
.font(self.id())
}

/// Clone the font and set a new color.
pub fn with_color(&self, color: Color) -> Self {
Self {
family: self.family.clone(),
size: self.size,
color,
}
}
}

fn deserialize_arc_str<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Arc<str>, D::Error> {
Expand Down Expand Up @@ -172,12 +181,31 @@ impl Default for EguiSettings {
pub trait EguiContextExt {
/// Clear the UI focus
fn clear_focus(self);

/// Get a global runtime state from the EGUI context, returning the default value if it is not
/// present.
///
/// This is just a convenience wrapper around Egui's built in temporary data store.
///
/// The value will be cloned to get it out of the store without holding a lock.
fn get_state<T: Clone + Default + Sync + Send + 'static>(self) -> T;

/// Set a global runtime state from the EGUI context.
///
/// This is just a convenience wrapper around Egui's built in temporary data store.
fn set_state<T: Clone + Default + Sync + Send + 'static>(self, value: T);
}

impl EguiContextExt for &egui::Context {
fn clear_focus(self) {
self.memory_mut(|r| r.request_focus(egui::Id::null()));
}
fn get_state<T: Clone + Default + Sync + Send + 'static>(self) -> T {
self.data_mut(|data| data.get_temp_mut_or_default::<T>(egui::Id::null()).clone())
}
fn set_state<T: Clone + Default + Sync + Send + 'static>(self, value: T) {
self.data_mut(|data| *data.get_temp_mut_or_default::<T>(egui::Id::null()) = value);
}
}

/// Extension trait with helpers for egui responses
Expand Down

0 comments on commit fe453e3

Please sign in to comment.